xref: /titanic_52/usr/src/cmd/svc/startd/graph.c (revision 269e59f9a28bf47e0f463e64fc5af4a408b73b21)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
24  */
25 
26 /*
27  * graph.c - master restarter graph engine
28  *
29  *   The graph engine keeps a dependency graph of all service instances on the
30  *   system, as recorded in the repository.  It decides when services should
31  *   be brought up or down based on service states and dependencies and sends
32  *   commands to restarters to effect any changes.  It also executes
33  *   administrator commands sent by svcadm via the repository.
34  *
35  *   The graph is stored in uu_list_t *dgraph and its vertices are
36  *   graph_vertex_t's, each of which has a name and an integer id unique to
37  *   its name (see dict.c).  A vertex's type attribute designates the type
38  *   of object it represents: GVT_INST for service instances, GVT_SVC for
39  *   service objects (since service instances may depend on another service,
40  *   rather than service instance), GVT_FILE for files (which services may
41  *   depend on), and GVT_GROUP for dependencies on multiple objects.  GVT_GROUP
42  *   vertices are necessary because dependency lists may have particular
43  *   grouping types (require any, require all, optional, or exclude) and
44  *   event-propagation characteristics.
45  *
46  *   The initial graph is built by libscf_populate_graph() invoking
47  *   dgraph_add_instance() for each instance in the repository.  The function
48  *   adds a GVT_SVC vertex for the service if one does not already exist, adds
49  *   a GVT_INST vertex named by the FMRI of the instance, and sets up the edges.
50  *   The resulting web of vertices & edges associated with an instance's vertex
51  *   includes
52  *
53  *     - an edge from the GVT_SVC vertex for the instance's service
54  *
55  *     - an edge to the GVT_INST vertex of the instance's resarter, if its
56  *       restarter is not svc.startd
57  *
58  *     - edges from other GVT_INST vertices if the instance is a restarter
59  *
60  *     - for each dependency property group in the instance's "running"
61  *       snapshot, an edge to a GVT_GROUP vertex named by the FMRI of the
62  *       instance and the name of the property group
63  *
64  *     - for each value of the "entities" property in each dependency property
65  *       group, an edge from the corresponding GVT_GROUP vertex to a
66  *       GVT_INST, GVT_SVC, or GVT_FILE vertex
67  *
68  *     - edges from GVT_GROUP vertices for each dependent instance
69  *
70  *   After the edges are set up the vertex's GV_CONFIGURED flag is set.  If
71  *   there are problems, or if a service is mentioned in a dependency but does
72  *   not exist in the repository, the GV_CONFIGURED flag will be clear.
73  *
74  *   The graph and all of its vertices are protected by the dgraph_lock mutex.
75  *   See restarter.c for more information.
76  *
77  *   The properties of an instance fall into two classes: immediate and
78  *   snapshotted.  Immediate properties should have an immediate effect when
79  *   changed.  Snapshotted properties should be read from a snapshot, so they
80  *   only change when the snapshot changes.  The immediate properties used by
81  *   the graph engine are general/enabled, general/restarter, and the properties
82  *   in the restarter_actions property group.  Since they are immediate, they
83  *   are not read out of a snapshot.  The snapshotted properties used by the
84  *   graph engine are those in the property groups with type "dependency" and
85  *   are read out of the "running" snapshot.  The "running" snapshot is created
86  *   by the the graph engine as soon as possible, and it is updated, along with
87  *   in-core copies of the data (dependency information for the graph engine) on
88  *   receipt of the refresh command from svcadm.  In addition, the graph engine
89  *   updates the "start" snapshot from the "running" snapshot whenever a service
90  *   comes online.
91  *
92  *   When a DISABLE event is requested by the administrator, svc.startd shutdown
93  *   the dependents first before shutting down the requested service.
94  *   In graph_enable_by_vertex, we create a subtree that contains the dependent
95  *   vertices by marking those vertices with the GV_TOOFFLINE flag. And we mark
96  *   the vertex to disable with the GV_TODISABLE flag. Once the tree is created,
97  *   we send the _ADMIN_DISABLE event to the leaves. The leaves will then
98  *   transition from STATE_ONLINE/STATE_DEGRADED to STATE_OFFLINE/STATE_MAINT.
99  *   In gt_enter_offline and gt_enter_maint if the vertex was in a subtree then
100  *   we clear the GV_TOOFFLINE flag and walk the dependencies to offline the new
101  *   exposed leaves. We do the same until we reach the last leaf (the one with
102  *   the GV_TODISABLE flag). If the vertex to disable is also part of a larger
103  *   subtree (eg. multiple DISABLE events on vertices in the same subtree) then
104  *   once the first vertex is disabled (GV_TODISABLE flag is removed), we
105  *   continue to propagate the offline event to the vertex's dependencies.
106  */
107 
108 #include <sys/uadmin.h>
109 #include <sys/wait.h>
110 
111 #include <assert.h>
112 #include <errno.h>
113 #include <fcntl.h>
114 #include <libscf.h>
115 #include <libscf_priv.h>
116 #include <libuutil.h>
117 #include <locale.h>
118 #include <poll.h>
119 #include <pthread.h>
120 #include <signal.h>
121 #include <stddef.h>
122 #include <stdio.h>
123 #include <stdlib.h>
124 #include <string.h>
125 #include <strings.h>
126 #include <sys/statvfs.h>
127 #include <sys/uadmin.h>
128 #include <zone.h>
129 #if defined(__i386)
130 #include <libgrubmgmt.h>
131 #endif	/* __i386 */
132 
133 #include "startd.h"
134 #include "protocol.h"
135 
136 
137 #define	MILESTONE_NONE	((graph_vertex_t *)1)
138 
139 #define	CONSOLE_LOGIN_FMRI	"svc:/system/console-login:default"
140 #define	FS_MINIMAL_FMRI		"svc:/system/filesystem/minimal:default"
141 
142 #define	VERTEX_REMOVED	0	/* vertex has been freed  */
143 #define	VERTEX_INUSE	1	/* vertex is still in use */
144 
145 /*
146  * Services in these states are not considered 'down' by the
147  * milestone/shutdown code.
148  */
149 #define	up_state(state)	((state) == RESTARTER_STATE_ONLINE || \
150 	(state) == RESTARTER_STATE_DEGRADED || \
151 	(state) == RESTARTER_STATE_OFFLINE)
152 
153 #define	is_depgrp_bypassed(v) ((v->gv_type == GVT_GROUP) && \
154 	((v->gv_depgroup == DEPGRP_EXCLUDE_ALL) || \
155 	(v->gv_depgroup == DEPGRP_OPTIONAL_ALL) || \
156 	(v->gv_restart < RERR_RESTART)))
157 
158 static uu_list_pool_t *graph_edge_pool, *graph_vertex_pool;
159 static uu_list_t *dgraph;
160 static pthread_mutex_t dgraph_lock;
161 
162 /*
163  * milestone indicates the current subgraph.  When NULL, it is the entire
164  * graph.  When MILESTONE_NONE, it is the empty graph.  Otherwise, it is all
165  * services on which the target vertex depends.
166  */
167 static graph_vertex_t *milestone = NULL;
168 static boolean_t initial_milestone_set = B_FALSE;
169 static pthread_cond_t initial_milestone_cv = PTHREAD_COND_INITIALIZER;
170 
171 /* protected by dgraph_lock */
172 static boolean_t sulogin_thread_running = B_FALSE;
173 static boolean_t sulogin_running = B_FALSE;
174 static boolean_t console_login_ready = B_FALSE;
175 
176 /* Number of services to come down to complete milestone transition. */
177 static uint_t non_subgraph_svcs;
178 
179 /*
180  * These variables indicate what should be done when we reach the milestone
181  * target milestone, i.e., when non_subgraph_svcs == 0.  They are acted upon in
182  * dgraph_set_instance_state().
183  */
184 static int halting = -1;
185 static boolean_t go_single_user_mode = B_FALSE;
186 static boolean_t go_to_level1 = B_FALSE;
187 
188 /*
189  * Tracks when we started halting.
190  */
191 static time_t halting_time = 0;
192 
193 /*
194  * This tracks the legacy runlevel to ensure we signal init and manage
195  * utmpx entries correctly.
196  */
197 static char current_runlevel = '\0';
198 
199 /* Number of single user threads currently running */
200 static pthread_mutex_t single_user_thread_lock;
201 static int single_user_thread_count = 0;
202 
203 /* Statistics for dependency cycle-checking */
204 static u_longlong_t dep_inserts = 0;
205 static u_longlong_t dep_cycle_ns = 0;
206 static u_longlong_t dep_insert_ns = 0;
207 
208 
209 static const char * const emsg_invalid_restarter =
210 	"Transitioning %s to maintenance, restarter FMRI %s is invalid "
211 	"(see 'svcs -xv' for details).\n";
212 static const char * const console_login_fmri = CONSOLE_LOGIN_FMRI;
213 static const char * const single_user_fmri = SCF_MILESTONE_SINGLE_USER;
214 static const char * const multi_user_fmri = SCF_MILESTONE_MULTI_USER;
215 static const char * const multi_user_svr_fmri = SCF_MILESTONE_MULTI_USER_SERVER;
216 
217 
218 /*
219  * These services define the system being "up".  If none of them can come
220  * online, then we will run sulogin on the console.  Note that the install ones
221  * are for the miniroot and when installing CDs after the first.  can_come_up()
222  * does the decision making, and an sulogin_thread() runs sulogin, which can be
223  * started by dgraph_set_instance_state() or single_user_thread().
224  *
225  * NOTE: can_come_up() relies on SCF_MILESTONE_SINGLE_USER being the first
226  * entry, which is only used when booting_to_single_user (boot -s) is set.
227  * This is because when doing a "boot -s", sulogin is started from specials.c
228  * after milestone/single-user comes online, for backwards compatibility.
229  * In this case, SCF_MILESTONE_SINGLE_USER needs to be part of up_svcs
230  * to ensure sulogin will be spawned if milestone/single-user cannot be reached.
231  */
232 static const char * const up_svcs[] = {
233 	SCF_MILESTONE_SINGLE_USER,
234 	CONSOLE_LOGIN_FMRI,
235 	"svc:/system/install-setup:default",
236 	"svc:/system/install:default",
237 	NULL
238 };
239 
240 /* This array must have an element for each non-NULL element of up_svcs[]. */
241 static graph_vertex_t *up_svcs_p[] = { NULL, NULL, NULL, NULL };
242 
243 /* These are for seed repository magic.  See can_come_up(). */
244 static const char * const manifest_import = SCF_INSTANCE_MI;
245 static graph_vertex_t *manifest_import_p = NULL;
246 
247 
248 static char target_milestone_as_runlevel(void);
249 static void graph_runlevel_changed(char rl, int online);
250 static int dgraph_set_milestone(const char *, scf_handle_t *, boolean_t);
251 static boolean_t should_be_in_subgraph(graph_vertex_t *v);
252 static int mark_subtree(graph_edge_t *, void *);
253 static boolean_t insubtree_dependents_down(graph_vertex_t *);
254 
255 /*
256  * graph_vertex_compare()
257  *	This function can compare either int *id or * graph_vertex_t *gv
258  *	values, as the vertex id is always the first element of a
259  *	graph_vertex structure.
260  */
261 /* ARGSUSED */
262 static int
263 graph_vertex_compare(const void *lc_arg, const void *rc_arg, void *private)
264 {
265 	int lc_id = ((const graph_vertex_t *)lc_arg)->gv_id;
266 	int rc_id = *(int *)rc_arg;
267 
268 	if (lc_id > rc_id)
269 		return (1);
270 	if (lc_id < rc_id)
271 		return (-1);
272 	return (0);
273 }
274 
275 void
276 graph_init()
277 {
278 	graph_edge_pool = startd_list_pool_create("graph_edges",
279 	    sizeof (graph_edge_t), offsetof(graph_edge_t, ge_link), NULL,
280 	    UU_LIST_POOL_DEBUG);
281 	assert(graph_edge_pool != NULL);
282 
283 	graph_vertex_pool = startd_list_pool_create("graph_vertices",
284 	    sizeof (graph_vertex_t), offsetof(graph_vertex_t, gv_link),
285 	    graph_vertex_compare, UU_LIST_POOL_DEBUG);
286 	assert(graph_vertex_pool != NULL);
287 
288 	(void) pthread_mutex_init(&dgraph_lock, &mutex_attrs);
289 	(void) pthread_mutex_init(&single_user_thread_lock, &mutex_attrs);
290 	dgraph = startd_list_create(graph_vertex_pool, NULL, UU_LIST_SORTED);
291 	assert(dgraph != NULL);
292 
293 	if (!st->st_initial)
294 		current_runlevel = utmpx_get_runlevel();
295 
296 	log_framework(LOG_DEBUG, "Initialized graph\n");
297 }
298 
299 static graph_vertex_t *
300 vertex_get_by_name(const char *name)
301 {
302 	int id;
303 
304 	assert(MUTEX_HELD(&dgraph_lock));
305 
306 	id = dict_lookup_byname(name);
307 	if (id == -1)
308 		return (NULL);
309 
310 	return (uu_list_find(dgraph, &id, NULL, NULL));
311 }
312 
313 static graph_vertex_t *
314 vertex_get_by_id(int id)
315 {
316 	assert(MUTEX_HELD(&dgraph_lock));
317 
318 	if (id == -1)
319 		return (NULL);
320 
321 	return (uu_list_find(dgraph, &id, NULL, NULL));
322 }
323 
324 /*
325  * Creates a new vertex with the given name, adds it to the graph, and returns
326  * a pointer to it.  The graph lock must be held by this thread on entry.
327  */
328 static graph_vertex_t *
329 graph_add_vertex(const char *name)
330 {
331 	int id;
332 	graph_vertex_t *v;
333 	void *p;
334 	uu_list_index_t idx;
335 
336 	assert(MUTEX_HELD(&dgraph_lock));
337 
338 	id = dict_insert(name);
339 
340 	v = startd_zalloc(sizeof (*v));
341 
342 	v->gv_id = id;
343 
344 	v->gv_name = startd_alloc(strlen(name) + 1);
345 	(void) strcpy(v->gv_name, name);
346 
347 	v->gv_dependencies = startd_list_create(graph_edge_pool, v, 0);
348 	v->gv_dependents = startd_list_create(graph_edge_pool, v, 0);
349 
350 	p = uu_list_find(dgraph, &id, NULL, &idx);
351 	assert(p == NULL);
352 
353 	uu_list_node_init(v, &v->gv_link, graph_vertex_pool);
354 	uu_list_insert(dgraph, v, idx);
355 
356 	return (v);
357 }
358 
359 /*
360  * Removes v from the graph and frees it.  The graph should be locked by this
361  * thread, and v should have no edges associated with it.
362  */
363 static void
364 graph_remove_vertex(graph_vertex_t *v)
365 {
366 	assert(MUTEX_HELD(&dgraph_lock));
367 
368 	assert(uu_list_numnodes(v->gv_dependencies) == 0);
369 	assert(uu_list_numnodes(v->gv_dependents) == 0);
370 	assert(v->gv_refs == 0);
371 
372 	startd_free(v->gv_name, strlen(v->gv_name) + 1);
373 	uu_list_destroy(v->gv_dependencies);
374 	uu_list_destroy(v->gv_dependents);
375 	uu_list_remove(dgraph, v);
376 
377 	startd_free(v, sizeof (graph_vertex_t));
378 }
379 
380 static void
381 graph_add_edge(graph_vertex_t *fv, graph_vertex_t *tv)
382 {
383 	graph_edge_t *e, *re;
384 	int r;
385 
386 	assert(MUTEX_HELD(&dgraph_lock));
387 
388 	e = startd_alloc(sizeof (graph_edge_t));
389 	re = startd_alloc(sizeof (graph_edge_t));
390 
391 	e->ge_parent = fv;
392 	e->ge_vertex = tv;
393 
394 	re->ge_parent = tv;
395 	re->ge_vertex = fv;
396 
397 	uu_list_node_init(e, &e->ge_link, graph_edge_pool);
398 	r = uu_list_insert_before(fv->gv_dependencies, NULL, e);
399 	assert(r == 0);
400 
401 	uu_list_node_init(re, &re->ge_link, graph_edge_pool);
402 	r = uu_list_insert_before(tv->gv_dependents, NULL, re);
403 	assert(r == 0);
404 }
405 
406 static void
407 graph_remove_edge(graph_vertex_t *v, graph_vertex_t *dv)
408 {
409 	graph_edge_t *e;
410 
411 	for (e = uu_list_first(v->gv_dependencies);
412 	    e != NULL;
413 	    e = uu_list_next(v->gv_dependencies, e)) {
414 		if (e->ge_vertex == dv) {
415 			uu_list_remove(v->gv_dependencies, e);
416 			startd_free(e, sizeof (graph_edge_t));
417 			break;
418 		}
419 	}
420 
421 	for (e = uu_list_first(dv->gv_dependents);
422 	    e != NULL;
423 	    e = uu_list_next(dv->gv_dependents, e)) {
424 		if (e->ge_vertex == v) {
425 			uu_list_remove(dv->gv_dependents, e);
426 			startd_free(e, sizeof (graph_edge_t));
427 			break;
428 		}
429 	}
430 }
431 
432 static void
433 remove_inst_vertex(graph_vertex_t *v)
434 {
435 	graph_edge_t *e;
436 	graph_vertex_t *sv;
437 	int i;
438 
439 	assert(MUTEX_HELD(&dgraph_lock));
440 	assert(uu_list_numnodes(v->gv_dependents) == 1);
441 	assert(uu_list_numnodes(v->gv_dependencies) == 0);
442 	assert(v->gv_refs == 0);
443 	assert((v->gv_flags & GV_CONFIGURED) == 0);
444 
445 	e = uu_list_first(v->gv_dependents);
446 	sv = e->ge_vertex;
447 	graph_remove_edge(sv, v);
448 
449 	for (i = 0; up_svcs[i] != NULL; ++i) {
450 		if (up_svcs_p[i] == v)
451 			up_svcs_p[i] = NULL;
452 	}
453 
454 	if (manifest_import_p == v)
455 		manifest_import_p = NULL;
456 
457 	graph_remove_vertex(v);
458 
459 	if (uu_list_numnodes(sv->gv_dependencies) == 0 &&
460 	    uu_list_numnodes(sv->gv_dependents) == 0 &&
461 	    sv->gv_refs == 0)
462 		graph_remove_vertex(sv);
463 }
464 
465 static void
466 graph_walk_dependents(graph_vertex_t *v, void (*func)(graph_vertex_t *, void *),
467     void *arg)
468 {
469 	graph_edge_t *e;
470 
471 	for (e = uu_list_first(v->gv_dependents);
472 	    e != NULL;
473 	    e = uu_list_next(v->gv_dependents, e))
474 		func(e->ge_vertex, arg);
475 }
476 
477 static void
478 graph_walk_dependencies(graph_vertex_t *v, void (*func)(graph_vertex_t *,
479 	void *), void *arg)
480 {
481 	graph_edge_t *e;
482 
483 	assert(MUTEX_HELD(&dgraph_lock));
484 
485 	for (e = uu_list_first(v->gv_dependencies);
486 	    e != NULL;
487 	    e = uu_list_next(v->gv_dependencies, e)) {
488 
489 		func(e->ge_vertex, arg);
490 	}
491 }
492 
493 /*
494  * Generic graph walking function.
495  *
496  * Given a vertex, this function will walk either dependencies
497  * (WALK_DEPENDENCIES) or dependents (WALK_DEPENDENTS) of a vertex recursively
498  * for the entire graph.  It will avoid cycles and never visit the same vertex
499  * twice.
500  *
501  * We avoid traversing exclusion dependencies, because they are allowed to
502  * create cycles in the graph.  When propagating satisfiability, there is no
503  * need to walk exclusion dependencies because exclude_all_satisfied() doesn't
504  * test for satisfiability.
505  *
506  * The walker takes two callbacks.  The first is called before examining the
507  * dependents of each vertex.  The second is called on each vertex after
508  * examining its dependents.  This allows is_path_to() to construct a path only
509  * after the target vertex has been found.
510  */
511 typedef enum {
512 	WALK_DEPENDENTS,
513 	WALK_DEPENDENCIES
514 } graph_walk_dir_t;
515 
516 typedef int (*graph_walk_cb_t)(graph_vertex_t *, void *);
517 
518 typedef struct graph_walk_info {
519 	graph_walk_dir_t 	gi_dir;
520 	uchar_t			*gi_visited;	/* vertex bitmap */
521 	int			(*gi_pre)(graph_vertex_t *, void *);
522 	void			(*gi_post)(graph_vertex_t *, void *);
523 	void			*gi_arg;	/* callback arg */
524 	int			gi_ret;		/* return value */
525 } graph_walk_info_t;
526 
527 static int
528 graph_walk_recurse(graph_edge_t *e, graph_walk_info_t *gip)
529 {
530 	uu_list_t *list;
531 	int r;
532 	graph_vertex_t *v = e->ge_vertex;
533 	int i;
534 	uint_t b;
535 
536 	i = v->gv_id / 8;
537 	b = 1 << (v->gv_id % 8);
538 
539 	/*
540 	 * Check to see if we've visited this vertex already.
541 	 */
542 	if (gip->gi_visited[i] & b)
543 		return (UU_WALK_NEXT);
544 
545 	gip->gi_visited[i] |= b;
546 
547 	/*
548 	 * Don't follow exclusions.
549 	 */
550 	if (v->gv_type == GVT_GROUP && v->gv_depgroup == DEPGRP_EXCLUDE_ALL)
551 		return (UU_WALK_NEXT);
552 
553 	/*
554 	 * Call pre-visit callback.  If this doesn't terminate the walk,
555 	 * continue search.
556 	 */
557 	if ((gip->gi_ret = gip->gi_pre(v, gip->gi_arg)) == UU_WALK_NEXT) {
558 		/*
559 		 * Recurse using appropriate list.
560 		 */
561 		if (gip->gi_dir == WALK_DEPENDENTS)
562 			list = v->gv_dependents;
563 		else
564 			list = v->gv_dependencies;
565 
566 		r = uu_list_walk(list, (uu_walk_fn_t *)graph_walk_recurse,
567 		    gip, 0);
568 		assert(r == 0);
569 	}
570 
571 	/*
572 	 * Callbacks must return either UU_WALK_NEXT or UU_WALK_DONE.
573 	 */
574 	assert(gip->gi_ret == UU_WALK_NEXT || gip->gi_ret == UU_WALK_DONE);
575 
576 	/*
577 	 * If given a post-callback, call the function for every vertex.
578 	 */
579 	if (gip->gi_post != NULL)
580 		(void) gip->gi_post(v, gip->gi_arg);
581 
582 	/*
583 	 * Preserve the callback's return value.  If the callback returns
584 	 * UU_WALK_DONE, then we propagate that to the caller in order to
585 	 * terminate the walk.
586 	 */
587 	return (gip->gi_ret);
588 }
589 
590 static void
591 graph_walk(graph_vertex_t *v, graph_walk_dir_t dir,
592     int (*pre)(graph_vertex_t *, void *),
593     void (*post)(graph_vertex_t *, void *), void *arg)
594 {
595 	graph_walk_info_t gi;
596 	graph_edge_t fake;
597 	size_t sz = dictionary->dict_new_id / 8 + 1;
598 
599 	gi.gi_visited = startd_zalloc(sz);
600 	gi.gi_pre = pre;
601 	gi.gi_post = post;
602 	gi.gi_arg = arg;
603 	gi.gi_dir = dir;
604 	gi.gi_ret = 0;
605 
606 	/*
607 	 * Fake up an edge for the first iteration
608 	 */
609 	fake.ge_vertex = v;
610 	(void) graph_walk_recurse(&fake, &gi);
611 
612 	startd_free(gi.gi_visited, sz);
613 }
614 
615 typedef struct child_search {
616 	int	id;		/* id of vertex to look for */
617 	uint_t	depth;		/* recursion depth */
618 	/*
619 	 * While the vertex is not found, path is NULL.  After the search, if
620 	 * the vertex was found then path should point to a -1-terminated
621 	 * array of vertex id's which constitute the path to the vertex.
622 	 */
623 	int	*path;
624 } child_search_t;
625 
626 static int
627 child_pre(graph_vertex_t *v, void *arg)
628 {
629 	child_search_t *cs = arg;
630 
631 	cs->depth++;
632 
633 	if (v->gv_id == cs->id) {
634 		cs->path = startd_alloc((cs->depth + 1) * sizeof (int));
635 		cs->path[cs->depth] = -1;
636 		return (UU_WALK_DONE);
637 	}
638 
639 	return (UU_WALK_NEXT);
640 }
641 
642 static void
643 child_post(graph_vertex_t *v, void *arg)
644 {
645 	child_search_t *cs = arg;
646 
647 	cs->depth--;
648 
649 	if (cs->path != NULL)
650 		cs->path[cs->depth] = v->gv_id;
651 }
652 
653 /*
654  * Look for a path from from to to.  If one exists, returns a pointer to
655  * a NULL-terminated array of pointers to the vertices along the path.  If
656  * there is no path, returns NULL.
657  */
658 static int *
659 is_path_to(graph_vertex_t *from, graph_vertex_t *to)
660 {
661 	child_search_t cs;
662 
663 	cs.id = to->gv_id;
664 	cs.depth = 0;
665 	cs.path = NULL;
666 
667 	graph_walk(from, WALK_DEPENDENCIES, child_pre, child_post, &cs);
668 
669 	return (cs.path);
670 }
671 
672 /*
673  * Given an array of int's as returned by is_path_to, allocates a string of
674  * their names joined by newlines.  Returns the size of the allocated buffer
675  * in *sz and frees path.
676  */
677 static void
678 path_to_str(int *path, char **cpp, size_t *sz)
679 {
680 	int i;
681 	graph_vertex_t *v;
682 	size_t allocd, new_allocd;
683 	char *new, *name;
684 
685 	assert(MUTEX_HELD(&dgraph_lock));
686 	assert(path[0] != -1);
687 
688 	allocd = 1;
689 	*cpp = startd_alloc(1);
690 	(*cpp)[0] = '\0';
691 
692 	for (i = 0; path[i] != -1; ++i) {
693 		name = NULL;
694 
695 		v = vertex_get_by_id(path[i]);
696 
697 		if (v == NULL)
698 			name = "<deleted>";
699 		else if (v->gv_type == GVT_INST || v->gv_type == GVT_SVC)
700 			name = v->gv_name;
701 
702 		if (name != NULL) {
703 			new_allocd = allocd + strlen(name) + 1;
704 			new = startd_alloc(new_allocd);
705 			(void) strcpy(new, *cpp);
706 			(void) strcat(new, name);
707 			(void) strcat(new, "\n");
708 
709 			startd_free(*cpp, allocd);
710 
711 			*cpp = new;
712 			allocd = new_allocd;
713 		}
714 	}
715 
716 	startd_free(path, sizeof (int) * (i + 1));
717 
718 	*sz = allocd;
719 }
720 
721 
722 /*
723  * This function along with run_sulogin() implements an exclusion relationship
724  * between system/console-login and sulogin.  run_sulogin() will fail if
725  * system/console-login is online, and the graph engine should call
726  * graph_clogin_start() to bring system/console-login online, which defers the
727  * start if sulogin is running.
728  */
729 static void
730 graph_clogin_start(graph_vertex_t *v)
731 {
732 	assert(MUTEX_HELD(&dgraph_lock));
733 
734 	if (sulogin_running)
735 		console_login_ready = B_TRUE;
736 	else
737 		vertex_send_event(v, RESTARTER_EVENT_TYPE_START);
738 }
739 
740 static void
741 graph_su_start(graph_vertex_t *v)
742 {
743 	/*
744 	 * /etc/inittab used to have the initial /sbin/rcS as a 'sysinit'
745 	 * entry with a runlevel of 'S', before jumping to the final
746 	 * target runlevel (as set in initdefault).  We mimic that legacy
747 	 * behavior here.
748 	 */
749 	utmpx_set_runlevel('S', '0', B_FALSE);
750 	vertex_send_event(v, RESTARTER_EVENT_TYPE_START);
751 }
752 
753 static void
754 graph_post_su_online(void)
755 {
756 	graph_runlevel_changed('S', 1);
757 }
758 
759 static void
760 graph_post_su_disable(void)
761 {
762 	graph_runlevel_changed('S', 0);
763 }
764 
765 static void
766 graph_post_mu_online(void)
767 {
768 	graph_runlevel_changed('2', 1);
769 }
770 
771 static void
772 graph_post_mu_disable(void)
773 {
774 	graph_runlevel_changed('2', 0);
775 }
776 
777 static void
778 graph_post_mus_online(void)
779 {
780 	graph_runlevel_changed('3', 1);
781 }
782 
783 static void
784 graph_post_mus_disable(void)
785 {
786 	graph_runlevel_changed('3', 0);
787 }
788 
789 static struct special_vertex_info {
790 	const char	*name;
791 	void		(*start_f)(graph_vertex_t *);
792 	void		(*post_online_f)(void);
793 	void		(*post_disable_f)(void);
794 } special_vertices[] = {
795 	{ CONSOLE_LOGIN_FMRI, graph_clogin_start, NULL, NULL },
796 	{ SCF_MILESTONE_SINGLE_USER, graph_su_start,
797 	    graph_post_su_online, graph_post_su_disable },
798 	{ SCF_MILESTONE_MULTI_USER, NULL,
799 	    graph_post_mu_online, graph_post_mu_disable },
800 	{ SCF_MILESTONE_MULTI_USER_SERVER, NULL,
801 	    graph_post_mus_online, graph_post_mus_disable },
802 	{ NULL },
803 };
804 
805 
806 void
807 vertex_send_event(graph_vertex_t *v, restarter_event_type_t e)
808 {
809 	switch (e) {
810 	case RESTARTER_EVENT_TYPE_ADD_INSTANCE:
811 		assert(v->gv_state == RESTARTER_STATE_UNINIT);
812 
813 		MUTEX_LOCK(&st->st_load_lock);
814 		st->st_load_instances++;
815 		MUTEX_UNLOCK(&st->st_load_lock);
816 		break;
817 
818 	case RESTARTER_EVENT_TYPE_ENABLE:
819 		log_framework(LOG_DEBUG, "Enabling %s.\n", v->gv_name);
820 		assert(v->gv_state == RESTARTER_STATE_UNINIT ||
821 		    v->gv_state == RESTARTER_STATE_DISABLED ||
822 		    v->gv_state == RESTARTER_STATE_MAINT);
823 		break;
824 
825 	case RESTARTER_EVENT_TYPE_DISABLE:
826 	case RESTARTER_EVENT_TYPE_ADMIN_DISABLE:
827 		log_framework(LOG_DEBUG, "Disabling %s.\n", v->gv_name);
828 		assert(v->gv_state != RESTARTER_STATE_DISABLED);
829 		break;
830 
831 	case RESTARTER_EVENT_TYPE_STOP_RESET:
832 	case RESTARTER_EVENT_TYPE_STOP:
833 		log_framework(LOG_DEBUG, "Stopping %s.\n", v->gv_name);
834 		assert(v->gv_state == RESTARTER_STATE_DEGRADED ||
835 		    v->gv_state == RESTARTER_STATE_ONLINE);
836 		break;
837 
838 	case RESTARTER_EVENT_TYPE_START:
839 		log_framework(LOG_DEBUG, "Starting %s.\n", v->gv_name);
840 		assert(v->gv_state == RESTARTER_STATE_OFFLINE);
841 		break;
842 
843 	case RESTARTER_EVENT_TYPE_REMOVE_INSTANCE:
844 	case RESTARTER_EVENT_TYPE_ADMIN_DEGRADED:
845 	case RESTARTER_EVENT_TYPE_ADMIN_REFRESH:
846 	case RESTARTER_EVENT_TYPE_ADMIN_RESTART:
847 	case RESTARTER_EVENT_TYPE_ADMIN_MAINT_OFF:
848 	case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
849 	case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON_IMMEDIATE:
850 	case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
851 	case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
852 		break;
853 
854 	default:
855 #ifndef NDEBUG
856 		uu_warn("%s:%d: Bad event %d.\n", __FILE__, __LINE__, e);
857 #endif
858 		abort();
859 	}
860 
861 	restarter_protocol_send_event(v->gv_name, v->gv_restarter_channel, e);
862 }
863 
864 static void
865 graph_unset_restarter(graph_vertex_t *v)
866 {
867 	assert(MUTEX_HELD(&dgraph_lock));
868 	assert(v->gv_flags & GV_CONFIGURED);
869 
870 	vertex_send_event(v, RESTARTER_EVENT_TYPE_REMOVE_INSTANCE);
871 
872 	if (v->gv_restarter_id != -1) {
873 		graph_vertex_t *rv;
874 
875 		rv = vertex_get_by_id(v->gv_restarter_id);
876 		graph_remove_edge(v, rv);
877 	}
878 
879 	v->gv_restarter_id = -1;
880 	v->gv_restarter_channel = NULL;
881 }
882 
883 /*
884  * Return VERTEX_REMOVED when the vertex passed in argument is deleted from the
885  * dgraph otherwise return VERTEX_INUSE.
886  */
887 static int
888 free_if_unrefed(graph_vertex_t *v)
889 {
890 	assert(MUTEX_HELD(&dgraph_lock));
891 
892 	if (v->gv_refs > 0)
893 		return (VERTEX_INUSE);
894 
895 	if (v->gv_type == GVT_SVC &&
896 	    uu_list_numnodes(v->gv_dependents) == 0 &&
897 	    uu_list_numnodes(v->gv_dependencies) == 0) {
898 		graph_remove_vertex(v);
899 		return (VERTEX_REMOVED);
900 	} else if (v->gv_type == GVT_INST &&
901 	    (v->gv_flags & GV_CONFIGURED) == 0 &&
902 	    uu_list_numnodes(v->gv_dependents) == 1 &&
903 	    uu_list_numnodes(v->gv_dependencies) == 0) {
904 		remove_inst_vertex(v);
905 		return (VERTEX_REMOVED);
906 	}
907 
908 	return (VERTEX_INUSE);
909 }
910 
911 static void
912 delete_depgroup(graph_vertex_t *v)
913 {
914 	graph_edge_t *e;
915 	graph_vertex_t *dv;
916 
917 	assert(MUTEX_HELD(&dgraph_lock));
918 	assert(v->gv_type == GVT_GROUP);
919 	assert(uu_list_numnodes(v->gv_dependents) == 0);
920 
921 	while ((e = uu_list_first(v->gv_dependencies)) != NULL) {
922 		dv = e->ge_vertex;
923 
924 		graph_remove_edge(v, dv);
925 
926 		switch (dv->gv_type) {
927 		case GVT_INST:		/* instance dependency */
928 		case GVT_SVC:		/* service dependency */
929 			(void) free_if_unrefed(dv);
930 			break;
931 
932 		case GVT_FILE:		/* file dependency */
933 			assert(uu_list_numnodes(dv->gv_dependencies) == 0);
934 			if (uu_list_numnodes(dv->gv_dependents) == 0)
935 				graph_remove_vertex(dv);
936 			break;
937 
938 		default:
939 #ifndef NDEBUG
940 			uu_warn("%s:%d: Unexpected node type %d", __FILE__,
941 			    __LINE__, dv->gv_type);
942 #endif
943 			abort();
944 		}
945 	}
946 
947 	graph_remove_vertex(v);
948 }
949 
950 static int
951 delete_instance_deps_cb(graph_edge_t *e, void **ptrs)
952 {
953 	graph_vertex_t *v = ptrs[0];
954 	boolean_t delete_restarter_dep = (boolean_t)ptrs[1];
955 	graph_vertex_t *dv;
956 
957 	dv = e->ge_vertex;
958 
959 	/*
960 	 * We have four possibilities here:
961 	 *   - GVT_INST: restarter
962 	 *   - GVT_GROUP - GVT_INST: instance dependency
963 	 *   - GVT_GROUP - GVT_SVC - GV_INST: service dependency
964 	 *   - GVT_GROUP - GVT_FILE: file dependency
965 	 */
966 	switch (dv->gv_type) {
967 	case GVT_INST:	/* restarter */
968 		assert(dv->gv_id == v->gv_restarter_id);
969 		if (delete_restarter_dep)
970 			graph_remove_edge(v, dv);
971 		break;
972 
973 	case GVT_GROUP:	/* pg dependency */
974 		graph_remove_edge(v, dv);
975 		delete_depgroup(dv);
976 		break;
977 
978 	case GVT_FILE:
979 		/* These are currently not direct dependencies */
980 
981 	default:
982 #ifndef NDEBUG
983 		uu_warn("%s:%d: Bad vertex type %d.\n", __FILE__, __LINE__,
984 		    dv->gv_type);
985 #endif
986 		abort();
987 	}
988 
989 	return (UU_WALK_NEXT);
990 }
991 
992 static void
993 delete_instance_dependencies(graph_vertex_t *v, boolean_t delete_restarter_dep)
994 {
995 	void *ptrs[2];
996 	int r;
997 
998 	assert(MUTEX_HELD(&dgraph_lock));
999 	assert(v->gv_type == GVT_INST);
1000 
1001 	ptrs[0] = v;
1002 	ptrs[1] = (void *)delete_restarter_dep;
1003 
1004 	r = uu_list_walk(v->gv_dependencies,
1005 	    (uu_walk_fn_t *)delete_instance_deps_cb, &ptrs, UU_WALK_ROBUST);
1006 	assert(r == 0);
1007 }
1008 
1009 /*
1010  * int graph_insert_vertex_unconfigured()
1011  *   Insert a vertex without sending any restarter events. If the vertex
1012  *   already exists or creation is successful, return a pointer to it in *vp.
1013  *
1014  *   If type is not GVT_GROUP, dt can remain unset.
1015  *
1016  *   Returns 0, EEXIST, or EINVAL if the arguments are invalid (i.e., fmri
1017  *   doesn't agree with type, or type doesn't agree with dt).
1018  */
1019 static int
1020 graph_insert_vertex_unconfigured(const char *fmri, gv_type_t type,
1021     depgroup_type_t dt, restarter_error_t rt, graph_vertex_t **vp)
1022 {
1023 	int r;
1024 	int i;
1025 
1026 	assert(MUTEX_HELD(&dgraph_lock));
1027 
1028 	switch (type) {
1029 	case GVT_SVC:
1030 	case GVT_INST:
1031 		if (strncmp(fmri, "svc:", sizeof ("svc:") - 1) != 0)
1032 			return (EINVAL);
1033 		break;
1034 
1035 	case GVT_FILE:
1036 		if (strncmp(fmri, "file:", sizeof ("file:") - 1) != 0)
1037 			return (EINVAL);
1038 		break;
1039 
1040 	case GVT_GROUP:
1041 		if (dt <= 0 || rt < 0)
1042 			return (EINVAL);
1043 		break;
1044 
1045 	default:
1046 #ifndef NDEBUG
1047 		uu_warn("%s:%d: Unknown type %d.\n", __FILE__, __LINE__, type);
1048 #endif
1049 		abort();
1050 	}
1051 
1052 	*vp = vertex_get_by_name(fmri);
1053 	if (*vp != NULL)
1054 		return (EEXIST);
1055 
1056 	*vp = graph_add_vertex(fmri);
1057 
1058 	(*vp)->gv_type = type;
1059 	(*vp)->gv_depgroup = dt;
1060 	(*vp)->gv_restart = rt;
1061 
1062 	(*vp)->gv_flags = 0;
1063 	(*vp)->gv_state = RESTARTER_STATE_NONE;
1064 
1065 	for (i = 0; special_vertices[i].name != NULL; ++i) {
1066 		if (strcmp(fmri, special_vertices[i].name) == 0) {
1067 			(*vp)->gv_start_f = special_vertices[i].start_f;
1068 			(*vp)->gv_post_online_f =
1069 			    special_vertices[i].post_online_f;
1070 			(*vp)->gv_post_disable_f =
1071 			    special_vertices[i].post_disable_f;
1072 			break;
1073 		}
1074 	}
1075 
1076 	(*vp)->gv_restarter_id = -1;
1077 	(*vp)->gv_restarter_channel = 0;
1078 
1079 	if (type == GVT_INST) {
1080 		char *sfmri;
1081 		graph_vertex_t *sv;
1082 
1083 		sfmri = inst_fmri_to_svc_fmri(fmri);
1084 		sv = vertex_get_by_name(sfmri);
1085 		if (sv == NULL) {
1086 			r = graph_insert_vertex_unconfigured(sfmri, GVT_SVC, 0,
1087 			    0, &sv);
1088 			assert(r == 0);
1089 		}
1090 		startd_free(sfmri, max_scf_fmri_size);
1091 
1092 		graph_add_edge(sv, *vp);
1093 	}
1094 
1095 	/*
1096 	 * If this vertex is in the subgraph, mark it as so, for both
1097 	 * GVT_INST and GVT_SERVICE verteces.
1098 	 * A GVT_SERVICE vertex can only be in the subgraph if another instance
1099 	 * depends on it, in which case it's already been added to the graph
1100 	 * and marked as in the subgraph (by refresh_vertex()).  If a
1101 	 * GVT_SERVICE vertex was freshly added (by the code above), it means
1102 	 * that it has no dependents, and cannot be in the subgraph.
1103 	 * Regardless of this, we still check that gv_flags includes
1104 	 * GV_INSUBGRAPH in the event that future behavior causes the above
1105 	 * code to add a GVT_SERVICE vertex which should be in the subgraph.
1106 	 */
1107 
1108 	(*vp)->gv_flags |= (should_be_in_subgraph(*vp)? GV_INSUBGRAPH : 0);
1109 
1110 	return (0);
1111 }
1112 
1113 /*
1114  * Returns 0 on success or ELOOP if the dependency would create a cycle.
1115  */
1116 static int
1117 graph_insert_dependency(graph_vertex_t *fv, graph_vertex_t *tv, int **pathp)
1118 {
1119 	hrtime_t now;
1120 
1121 	assert(MUTEX_HELD(&dgraph_lock));
1122 
1123 	/* cycle detection */
1124 	now = gethrtime();
1125 
1126 	/* Don't follow exclusions. */
1127 	if (!(fv->gv_type == GVT_GROUP &&
1128 	    fv->gv_depgroup == DEPGRP_EXCLUDE_ALL)) {
1129 		*pathp = is_path_to(tv, fv);
1130 		if (*pathp)
1131 			return (ELOOP);
1132 	}
1133 
1134 	dep_cycle_ns += gethrtime() - now;
1135 	++dep_inserts;
1136 	now = gethrtime();
1137 
1138 	graph_add_edge(fv, tv);
1139 
1140 	dep_insert_ns += gethrtime() - now;
1141 
1142 	/* Check if the dependency adds the "to" vertex to the subgraph */
1143 	tv->gv_flags |= (should_be_in_subgraph(tv) ? GV_INSUBGRAPH : 0);
1144 
1145 	return (0);
1146 }
1147 
1148 static int
1149 inst_running(graph_vertex_t *v)
1150 {
1151 	assert(v->gv_type == GVT_INST);
1152 
1153 	if (v->gv_state == RESTARTER_STATE_ONLINE ||
1154 	    v->gv_state == RESTARTER_STATE_DEGRADED)
1155 		return (1);
1156 
1157 	return (0);
1158 }
1159 
1160 /*
1161  * The dependency evaluation functions return
1162  *   1 - dependency satisfied
1163  *   0 - dependency unsatisfied
1164  *   -1 - dependency unsatisfiable (without administrator intervention)
1165  *
1166  * The functions also take a boolean satbility argument.  When true, the
1167  * functions may recurse in order to determine satisfiability.
1168  */
1169 static int require_any_satisfied(graph_vertex_t *, boolean_t);
1170 static int dependency_satisfied(graph_vertex_t *, boolean_t);
1171 
1172 /*
1173  * A require_all dependency is unsatisfied if any elements are unsatisfied.  It
1174  * is unsatisfiable if any elements are unsatisfiable.
1175  */
1176 static int
1177 require_all_satisfied(graph_vertex_t *groupv, boolean_t satbility)
1178 {
1179 	graph_edge_t *edge;
1180 	int i;
1181 	boolean_t any_unsatisfied;
1182 
1183 	if (uu_list_numnodes(groupv->gv_dependencies) == 0)
1184 		return (1);
1185 
1186 	any_unsatisfied = B_FALSE;
1187 
1188 	for (edge = uu_list_first(groupv->gv_dependencies);
1189 	    edge != NULL;
1190 	    edge = uu_list_next(groupv->gv_dependencies, edge)) {
1191 		i = dependency_satisfied(edge->ge_vertex, satbility);
1192 		if (i == 1)
1193 			continue;
1194 
1195 		log_framework2(LOG_DEBUG, DEBUG_DEPENDENCIES,
1196 		    "require_all(%s): %s is unsatisfi%s.\n", groupv->gv_name,
1197 		    edge->ge_vertex->gv_name, i == 0 ? "ed" : "able");
1198 
1199 		if (!satbility)
1200 			return (0);
1201 
1202 		if (i == -1)
1203 			return (-1);
1204 
1205 		any_unsatisfied = B_TRUE;
1206 	}
1207 
1208 	return (any_unsatisfied ? 0 : 1);
1209 }
1210 
1211 /*
1212  * A require_any dependency is satisfied if any element is satisfied.  It is
1213  * satisfiable if any element is satisfiable.
1214  */
1215 static int
1216 require_any_satisfied(graph_vertex_t *groupv, boolean_t satbility)
1217 {
1218 	graph_edge_t *edge;
1219 	int s;
1220 	boolean_t satisfiable;
1221 
1222 	if (uu_list_numnodes(groupv->gv_dependencies) == 0)
1223 		return (1);
1224 
1225 	satisfiable = B_FALSE;
1226 
1227 	for (edge = uu_list_first(groupv->gv_dependencies);
1228 	    edge != NULL;
1229 	    edge = uu_list_next(groupv->gv_dependencies, edge)) {
1230 		s = dependency_satisfied(edge->ge_vertex, satbility);
1231 
1232 		if (s == 1)
1233 			return (1);
1234 
1235 		log_framework2(LOG_DEBUG, DEBUG_DEPENDENCIES,
1236 		    "require_any(%s): %s is unsatisfi%s.\n",
1237 		    groupv->gv_name, edge->ge_vertex->gv_name,
1238 		    s == 0 ? "ed" : "able");
1239 
1240 		if (satbility && s == 0)
1241 			satisfiable = B_TRUE;
1242 	}
1243 
1244 	return (!satbility || satisfiable ? 0 : -1);
1245 }
1246 
1247 /*
1248  * An optional_all dependency only considers elements which are configured,
1249  * enabled, and not in maintenance.  If any are unsatisfied, then the dependency
1250  * is unsatisfied.
1251  *
1252  * Offline dependencies which are waiting for a dependency to come online are
1253  * unsatisfied.  Offline dependences which cannot possibly come online
1254  * (unsatisfiable) are always considered satisfied.
1255  */
1256 static int
1257 optional_all_satisfied(graph_vertex_t *groupv, boolean_t satbility)
1258 {
1259 	graph_edge_t *edge;
1260 	graph_vertex_t *v;
1261 	boolean_t any_qualified;
1262 	boolean_t any_unsatisfied;
1263 	int i;
1264 
1265 	any_qualified = B_FALSE;
1266 	any_unsatisfied = B_FALSE;
1267 
1268 	for (edge = uu_list_first(groupv->gv_dependencies);
1269 	    edge != NULL;
1270 	    edge = uu_list_next(groupv->gv_dependencies, edge)) {
1271 		v = edge->ge_vertex;
1272 
1273 		switch (v->gv_type) {
1274 		case GVT_INST:
1275 			/* Skip missing or disabled instances */
1276 			if ((v->gv_flags & (GV_CONFIGURED | GV_ENABLED)) !=
1277 			    (GV_CONFIGURED | GV_ENABLED))
1278 				continue;
1279 
1280 			if (v->gv_state == RESTARTER_STATE_MAINT)
1281 				continue;
1282 
1283 			if (v->gv_flags & GV_TOOFFLINE)
1284 				continue;
1285 
1286 			any_qualified = B_TRUE;
1287 			if (v->gv_state == RESTARTER_STATE_OFFLINE) {
1288 				/*
1289 				 * For offline dependencies, treat unsatisfiable
1290 				 * as satisfied.
1291 				 */
1292 				i = dependency_satisfied(v, B_TRUE);
1293 				if (i == -1)
1294 					i = 1;
1295 			} else if (v->gv_state == RESTARTER_STATE_DISABLED) {
1296 				/*
1297 				 * The service is enabled, but hasn't
1298 				 * transitioned out of disabled yet.  Treat it
1299 				 * as unsatisfied (not unsatisfiable).
1300 				 */
1301 				i = 0;
1302 			} else {
1303 				i = dependency_satisfied(v, satbility);
1304 			}
1305 			break;
1306 
1307 		case GVT_FILE:
1308 			any_qualified = B_TRUE;
1309 			i = dependency_satisfied(v, satbility);
1310 
1311 			break;
1312 
1313 		case GVT_SVC: {
1314 			boolean_t svc_any_qualified;
1315 			boolean_t svc_satisfied;
1316 			boolean_t svc_satisfiable;
1317 			graph_vertex_t *v2;
1318 			graph_edge_t *e2;
1319 
1320 			svc_any_qualified = B_FALSE;
1321 			svc_satisfied = B_FALSE;
1322 			svc_satisfiable = B_FALSE;
1323 
1324 			for (e2 = uu_list_first(v->gv_dependencies);
1325 			    e2 != NULL;
1326 			    e2 = uu_list_next(v->gv_dependencies, e2)) {
1327 				v2 = e2->ge_vertex;
1328 				assert(v2->gv_type == GVT_INST);
1329 
1330 				if ((v2->gv_flags &
1331 				    (GV_CONFIGURED | GV_ENABLED)) !=
1332 				    (GV_CONFIGURED | GV_ENABLED))
1333 					continue;
1334 
1335 				if (v2->gv_state == RESTARTER_STATE_MAINT)
1336 					continue;
1337 
1338 				if (v2->gv_flags & GV_TOOFFLINE)
1339 					continue;
1340 
1341 				svc_any_qualified = B_TRUE;
1342 
1343 				if (v2->gv_state == RESTARTER_STATE_OFFLINE) {
1344 					/*
1345 					 * For offline dependencies, treat
1346 					 * unsatisfiable as satisfied.
1347 					 */
1348 					i = dependency_satisfied(v2, B_TRUE);
1349 					if (i == -1)
1350 						i = 1;
1351 				} else if (v2->gv_state ==
1352 				    RESTARTER_STATE_DISABLED) {
1353 					i = 0;
1354 				} else {
1355 					i = dependency_satisfied(v2, satbility);
1356 				}
1357 
1358 				if (i == 1) {
1359 					svc_satisfied = B_TRUE;
1360 					break;
1361 				}
1362 				if (i == 0)
1363 					svc_satisfiable = B_TRUE;
1364 			}
1365 
1366 			if (!svc_any_qualified)
1367 				continue;
1368 			any_qualified = B_TRUE;
1369 			if (svc_satisfied) {
1370 				i = 1;
1371 			} else if (svc_satisfiable) {
1372 				i = 0;
1373 			} else {
1374 				i = -1;
1375 			}
1376 			break;
1377 		}
1378 
1379 		case GVT_GROUP:
1380 		default:
1381 #ifndef NDEBUG
1382 			uu_warn("%s:%d: Unexpected vertex type %d.\n", __FILE__,
1383 			    __LINE__, v->gv_type);
1384 #endif
1385 			abort();
1386 		}
1387 
1388 		if (i == 1)
1389 			continue;
1390 
1391 		log_framework2(LOG_DEBUG, DEBUG_DEPENDENCIES,
1392 		    "optional_all(%s): %s is unsatisfi%s.\n", groupv->gv_name,
1393 		    v->gv_name, i == 0 ? "ed" : "able");
1394 
1395 		if (!satbility)
1396 			return (0);
1397 		if (i == -1)
1398 			return (-1);
1399 		any_unsatisfied = B_TRUE;
1400 	}
1401 
1402 	if (!any_qualified)
1403 		return (1);
1404 
1405 	return (any_unsatisfied ? 0 : 1);
1406 }
1407 
1408 /*
1409  * An exclude_all dependency is unsatisfied if any non-service element is
1410  * satisfied or any service instance which is configured, enabled, and not in
1411  * maintenance is satisfied.  Usually when unsatisfied, it is also
1412  * unsatisfiable.
1413  */
1414 #define	LOG_EXCLUDE(u, v)						\
1415 	log_framework2(LOG_DEBUG, DEBUG_DEPENDENCIES,			\
1416 	    "exclude_all(%s): %s is satisfied.\n",			\
1417 	    (u)->gv_name, (v)->gv_name)
1418 
1419 /* ARGSUSED */
1420 static int
1421 exclude_all_satisfied(graph_vertex_t *groupv, boolean_t satbility)
1422 {
1423 	graph_edge_t *edge, *e2;
1424 	graph_vertex_t *v, *v2;
1425 
1426 	for (edge = uu_list_first(groupv->gv_dependencies);
1427 	    edge != NULL;
1428 	    edge = uu_list_next(groupv->gv_dependencies, edge)) {
1429 		v = edge->ge_vertex;
1430 
1431 		switch (v->gv_type) {
1432 		case GVT_INST:
1433 			if ((v->gv_flags & GV_CONFIGURED) == 0)
1434 				continue;
1435 
1436 			switch (v->gv_state) {
1437 			case RESTARTER_STATE_ONLINE:
1438 			case RESTARTER_STATE_DEGRADED:
1439 				LOG_EXCLUDE(groupv, v);
1440 				return (v->gv_flags & GV_ENABLED ? -1 : 0);
1441 
1442 			case RESTARTER_STATE_OFFLINE:
1443 			case RESTARTER_STATE_UNINIT:
1444 				LOG_EXCLUDE(groupv, v);
1445 				return (0);
1446 
1447 			case RESTARTER_STATE_DISABLED:
1448 			case RESTARTER_STATE_MAINT:
1449 				continue;
1450 
1451 			default:
1452 #ifndef NDEBUG
1453 				uu_warn("%s:%d: Unexpected vertex state %d.\n",
1454 				    __FILE__, __LINE__, v->gv_state);
1455 #endif
1456 				abort();
1457 			}
1458 			/* NOTREACHED */
1459 
1460 		case GVT_SVC:
1461 			break;
1462 
1463 		case GVT_FILE:
1464 			if (!file_ready(v))
1465 				continue;
1466 			LOG_EXCLUDE(groupv, v);
1467 			return (-1);
1468 
1469 		case GVT_GROUP:
1470 		default:
1471 #ifndef NDEBUG
1472 			uu_warn("%s:%d: Unexpected vertex type %d.\n", __FILE__,
1473 			    __LINE__, v->gv_type);
1474 #endif
1475 			abort();
1476 		}
1477 
1478 		/* v represents a service */
1479 		if (uu_list_numnodes(v->gv_dependencies) == 0)
1480 			continue;
1481 
1482 		for (e2 = uu_list_first(v->gv_dependencies);
1483 		    e2 != NULL;
1484 		    e2 = uu_list_next(v->gv_dependencies, e2)) {
1485 			v2 = e2->ge_vertex;
1486 			assert(v2->gv_type == GVT_INST);
1487 
1488 			if ((v2->gv_flags & GV_CONFIGURED) == 0)
1489 				continue;
1490 
1491 			switch (v2->gv_state) {
1492 			case RESTARTER_STATE_ONLINE:
1493 			case RESTARTER_STATE_DEGRADED:
1494 				LOG_EXCLUDE(groupv, v2);
1495 				return (v2->gv_flags & GV_ENABLED ? -1 : 0);
1496 
1497 			case RESTARTER_STATE_OFFLINE:
1498 			case RESTARTER_STATE_UNINIT:
1499 				LOG_EXCLUDE(groupv, v2);
1500 				return (0);
1501 
1502 			case RESTARTER_STATE_DISABLED:
1503 			case RESTARTER_STATE_MAINT:
1504 				continue;
1505 
1506 			default:
1507 #ifndef NDEBUG
1508 				uu_warn("%s:%d: Unexpected vertex type %d.\n",
1509 				    __FILE__, __LINE__, v2->gv_type);
1510 #endif
1511 				abort();
1512 			}
1513 		}
1514 	}
1515 
1516 	return (1);
1517 }
1518 
1519 /*
1520  * int instance_satisfied()
1521  *   Determine if all the dependencies are satisfied for the supplied instance
1522  *   vertex. Return 1 if they are, 0 if they aren't, and -1 if they won't be
1523  *   without administrator intervention.
1524  */
1525 static int
1526 instance_satisfied(graph_vertex_t *v, boolean_t satbility)
1527 {
1528 	assert(v->gv_type == GVT_INST);
1529 	assert(!inst_running(v));
1530 
1531 	return (require_all_satisfied(v, satbility));
1532 }
1533 
1534 /*
1535  * Decide whether v can satisfy a dependency.  v can either be a child of
1536  * a group vertex, or of an instance vertex.
1537  */
1538 static int
1539 dependency_satisfied(graph_vertex_t *v, boolean_t satbility)
1540 {
1541 	switch (v->gv_type) {
1542 	case GVT_INST:
1543 		if ((v->gv_flags & GV_CONFIGURED) == 0) {
1544 			if (v->gv_flags & GV_DEATHROW) {
1545 				/*
1546 				 * A dependency on an instance with GV_DEATHROW
1547 				 * flag is always considered as satisfied.
1548 				 */
1549 				return (1);
1550 			}
1551 			return (-1);
1552 		}
1553 
1554 		/*
1555 		 * Any vertex with the GV_TOOFFLINE flag set is guaranteed
1556 		 * to have its dependencies unsatisfiable.
1557 		 */
1558 		if (v->gv_flags & GV_TOOFFLINE)
1559 			return (-1);
1560 
1561 		switch (v->gv_state) {
1562 		case RESTARTER_STATE_ONLINE:
1563 		case RESTARTER_STATE_DEGRADED:
1564 			return (1);
1565 
1566 		case RESTARTER_STATE_OFFLINE:
1567 			if (!satbility)
1568 				return (0);
1569 			return (instance_satisfied(v, satbility) != -1 ?
1570 			    0 : -1);
1571 
1572 		case RESTARTER_STATE_DISABLED:
1573 		case RESTARTER_STATE_MAINT:
1574 			return (-1);
1575 
1576 		case RESTARTER_STATE_UNINIT:
1577 			return (0);
1578 
1579 		default:
1580 #ifndef NDEBUG
1581 			uu_warn("%s:%d: Unexpected vertex state %d.\n",
1582 			    __FILE__, __LINE__, v->gv_state);
1583 #endif
1584 			abort();
1585 			/* NOTREACHED */
1586 		}
1587 
1588 	case GVT_SVC:
1589 		if (uu_list_numnodes(v->gv_dependencies) == 0)
1590 			return (-1);
1591 		return (require_any_satisfied(v, satbility));
1592 
1593 	case GVT_FILE:
1594 		/* i.e., we assume files will not be automatically generated */
1595 		return (file_ready(v) ? 1 : -1);
1596 
1597 	case GVT_GROUP:
1598 		break;
1599 
1600 	default:
1601 #ifndef NDEBUG
1602 		uu_warn("%s:%d: Unexpected node type %d.\n", __FILE__, __LINE__,
1603 		    v->gv_type);
1604 #endif
1605 		abort();
1606 		/* NOTREACHED */
1607 	}
1608 
1609 	switch (v->gv_depgroup) {
1610 	case DEPGRP_REQUIRE_ANY:
1611 		return (require_any_satisfied(v, satbility));
1612 
1613 	case DEPGRP_REQUIRE_ALL:
1614 		return (require_all_satisfied(v, satbility));
1615 
1616 	case DEPGRP_OPTIONAL_ALL:
1617 		return (optional_all_satisfied(v, satbility));
1618 
1619 	case DEPGRP_EXCLUDE_ALL:
1620 		return (exclude_all_satisfied(v, satbility));
1621 
1622 	default:
1623 #ifndef NDEBUG
1624 		uu_warn("%s:%d: Unknown dependency grouping %d.\n", __FILE__,
1625 		    __LINE__, v->gv_depgroup);
1626 #endif
1627 		abort();
1628 	}
1629 }
1630 
1631 void
1632 graph_start_if_satisfied(graph_vertex_t *v)
1633 {
1634 	if (v->gv_state == RESTARTER_STATE_OFFLINE &&
1635 	    instance_satisfied(v, B_FALSE) == 1) {
1636 		if (v->gv_start_f == NULL)
1637 			vertex_send_event(v, RESTARTER_EVENT_TYPE_START);
1638 		else
1639 			v->gv_start_f(v);
1640 	}
1641 }
1642 
1643 /*
1644  * propagate_satbility()
1645  *
1646  * This function is used when the given vertex changes state in such a way that
1647  * one of its dependents may become unsatisfiable.  This happens when an
1648  * instance transitions between offline -> online, or from !running ->
1649  * maintenance, as well as when an instance is removed from the graph.
1650  *
1651  * We have to walk all the dependents, since optional_all dependencies several
1652  * levels up could become (un)satisfied, instead of unsatisfiable.  For example,
1653  *
1654  *	+-----+  optional_all  +-----+  require_all  +-----+
1655  *	|  A  |--------------->|  B  |-------------->|  C  |
1656  *	+-----+                +-----+               +-----+
1657  *
1658  *	                                        offline -> maintenance
1659  *
1660  * If C goes into maintenance, it's not enough simply to check B.  Because A has
1661  * an optional dependency, what was previously an unsatisfiable situation is now
1662  * satisfied (B will never come online, even though its state hasn't changed).
1663  *
1664  * Note that it's not necessary to continue examining dependents after reaching
1665  * an optional_all dependency.  It's not possible for an optional_all dependency
1666  * to change satisfiability without also coming online, in which case we get a
1667  * start event and propagation continues naturally.  However, it does no harm to
1668  * continue propagating satisfiability (as it is a relatively rare event), and
1669  * keeps the walker code simple and generic.
1670  */
1671 /*ARGSUSED*/
1672 static int
1673 satbility_cb(graph_vertex_t *v, void *arg)
1674 {
1675 	if (v->gv_type == GVT_INST)
1676 		graph_start_if_satisfied(v);
1677 
1678 	return (UU_WALK_NEXT);
1679 }
1680 
1681 static void
1682 propagate_satbility(graph_vertex_t *v)
1683 {
1684 	graph_walk(v, WALK_DEPENDENTS, satbility_cb, NULL, NULL);
1685 }
1686 
1687 static void propagate_stop(graph_vertex_t *, void *);
1688 
1689 /* ARGSUSED */
1690 static void
1691 propagate_start(graph_vertex_t *v, void *arg)
1692 {
1693 	switch (v->gv_type) {
1694 	case GVT_INST:
1695 		graph_start_if_satisfied(v);
1696 		break;
1697 
1698 	case GVT_GROUP:
1699 		if (v->gv_depgroup == DEPGRP_EXCLUDE_ALL) {
1700 			graph_walk_dependents(v, propagate_stop,
1701 			    (void *)RERR_RESTART);
1702 			break;
1703 		}
1704 		/* FALLTHROUGH */
1705 
1706 	case GVT_SVC:
1707 		graph_walk_dependents(v, propagate_start, NULL);
1708 		break;
1709 
1710 	case GVT_FILE:
1711 #ifndef NDEBUG
1712 		uu_warn("%s:%d: propagate_start() encountered GVT_FILE.\n",
1713 		    __FILE__, __LINE__);
1714 #endif
1715 		abort();
1716 		/* NOTREACHED */
1717 
1718 	default:
1719 #ifndef NDEBUG
1720 		uu_warn("%s:%d: Unknown vertex type %d.\n", __FILE__, __LINE__,
1721 		    v->gv_type);
1722 #endif
1723 		abort();
1724 	}
1725 }
1726 
1727 static void
1728 propagate_stop(graph_vertex_t *v, void *arg)
1729 {
1730 	graph_edge_t *e;
1731 	graph_vertex_t *svc;
1732 	restarter_error_t err = (restarter_error_t)arg;
1733 
1734 	switch (v->gv_type) {
1735 	case GVT_INST:
1736 		/* Restarter */
1737 		if (err > RERR_NONE && inst_running(v)) {
1738 			if (err == RERR_RESTART || err == RERR_REFRESH) {
1739 				vertex_send_event(v,
1740 				    RESTARTER_EVENT_TYPE_STOP_RESET);
1741 			} else {
1742 				vertex_send_event(v, RESTARTER_EVENT_TYPE_STOP);
1743 			}
1744 		}
1745 		break;
1746 
1747 	case GVT_SVC:
1748 		graph_walk_dependents(v, propagate_stop, arg);
1749 		break;
1750 
1751 	case GVT_FILE:
1752 #ifndef NDEBUG
1753 		uu_warn("%s:%d: propagate_stop() encountered GVT_FILE.\n",
1754 		    __FILE__, __LINE__);
1755 #endif
1756 		abort();
1757 		/* NOTREACHED */
1758 
1759 	case GVT_GROUP:
1760 		if (v->gv_depgroup == DEPGRP_EXCLUDE_ALL) {
1761 			graph_walk_dependents(v, propagate_start, NULL);
1762 			break;
1763 		}
1764 
1765 		if (err == RERR_NONE || err > v->gv_restart)
1766 			break;
1767 
1768 		assert(uu_list_numnodes(v->gv_dependents) == 1);
1769 		e = uu_list_first(v->gv_dependents);
1770 		svc = e->ge_vertex;
1771 
1772 		if (inst_running(svc)) {
1773 			if (err == RERR_RESTART || err == RERR_REFRESH) {
1774 				vertex_send_event(svc,
1775 				    RESTARTER_EVENT_TYPE_STOP_RESET);
1776 			} else {
1777 				vertex_send_event(svc,
1778 				    RESTARTER_EVENT_TYPE_STOP);
1779 			}
1780 		}
1781 		break;
1782 
1783 	default:
1784 #ifndef NDEBUG
1785 		uu_warn("%s:%d: Unknown vertex type %d.\n", __FILE__, __LINE__,
1786 		    v->gv_type);
1787 #endif
1788 		abort();
1789 	}
1790 }
1791 
1792 void
1793 offline_vertex(graph_vertex_t *v)
1794 {
1795 	scf_handle_t *h = libscf_handle_create_bound_loop();
1796 	scf_instance_t *scf_inst = safe_scf_instance_create(h);
1797 	scf_propertygroup_t *pg = safe_scf_pg_create(h);
1798 	restarter_instance_state_t state, next_state;
1799 	int r;
1800 
1801 	assert(v->gv_type == GVT_INST);
1802 
1803 	if (scf_inst == NULL)
1804 		bad_error("safe_scf_instance_create", scf_error());
1805 	if (pg == NULL)
1806 		bad_error("safe_scf_pg_create", scf_error());
1807 
1808 	/* if the vertex is already going offline, return */
1809 rep_retry:
1810 	if (scf_handle_decode_fmri(h, v->gv_name, NULL, NULL, scf_inst, NULL,
1811 	    NULL, SCF_DECODE_FMRI_EXACT) != 0) {
1812 		switch (scf_error()) {
1813 		case SCF_ERROR_CONNECTION_BROKEN:
1814 			libscf_handle_rebind(h);
1815 			goto rep_retry;
1816 
1817 		case SCF_ERROR_NOT_FOUND:
1818 			scf_pg_destroy(pg);
1819 			scf_instance_destroy(scf_inst);
1820 			(void) scf_handle_unbind(h);
1821 			scf_handle_destroy(h);
1822 			return;
1823 		}
1824 		uu_die("Can't decode FMRI %s: %s\n", v->gv_name,
1825 		    scf_strerror(scf_error()));
1826 	}
1827 
1828 	r = scf_instance_get_pg(scf_inst, SCF_PG_RESTARTER, pg);
1829 	if (r != 0) {
1830 		switch (scf_error()) {
1831 		case SCF_ERROR_CONNECTION_BROKEN:
1832 			libscf_handle_rebind(h);
1833 			goto rep_retry;
1834 
1835 		case SCF_ERROR_NOT_SET:
1836 		case SCF_ERROR_NOT_FOUND:
1837 			scf_pg_destroy(pg);
1838 			scf_instance_destroy(scf_inst);
1839 			(void) scf_handle_unbind(h);
1840 			scf_handle_destroy(h);
1841 			return;
1842 
1843 		default:
1844 			bad_error("scf_instance_get_pg", scf_error());
1845 		}
1846 	} else {
1847 		r = libscf_read_states(pg, &state, &next_state);
1848 		if (r == 0 && (next_state == RESTARTER_STATE_OFFLINE ||
1849 		    next_state == RESTARTER_STATE_DISABLED)) {
1850 			log_framework(LOG_DEBUG,
1851 			    "%s: instance is already going down.\n",
1852 			    v->gv_name);
1853 			scf_pg_destroy(pg);
1854 			scf_instance_destroy(scf_inst);
1855 			(void) scf_handle_unbind(h);
1856 			scf_handle_destroy(h);
1857 			return;
1858 		}
1859 	}
1860 
1861 	scf_pg_destroy(pg);
1862 	scf_instance_destroy(scf_inst);
1863 	(void) scf_handle_unbind(h);
1864 	scf_handle_destroy(h);
1865 
1866 	vertex_send_event(v, RESTARTER_EVENT_TYPE_STOP_RESET);
1867 }
1868 
1869 /*
1870  * void graph_enable_by_vertex()
1871  *   If admin is non-zero, this is an administrative request for change
1872  *   of the enabled property.  Thus, send the ADMIN_DISABLE rather than
1873  *   a plain DISABLE restarter event.
1874  */
1875 void
1876 graph_enable_by_vertex(graph_vertex_t *vertex, int enable, int admin)
1877 {
1878 	graph_vertex_t *v;
1879 	int r;
1880 
1881 	assert(MUTEX_HELD(&dgraph_lock));
1882 	assert((vertex->gv_flags & GV_CONFIGURED));
1883 
1884 	vertex->gv_flags = (vertex->gv_flags & ~GV_ENABLED) |
1885 	    (enable ? GV_ENABLED : 0);
1886 
1887 	if (enable) {
1888 		if (vertex->gv_state != RESTARTER_STATE_OFFLINE &&
1889 		    vertex->gv_state != RESTARTER_STATE_DEGRADED &&
1890 		    vertex->gv_state != RESTARTER_STATE_ONLINE) {
1891 			/*
1892 			 * In case the vertex was notified to go down,
1893 			 * but now can return online, clear the _TOOFFLINE
1894 			 * and _TODISABLE flags.
1895 			 */
1896 			vertex->gv_flags &= ~GV_TOOFFLINE;
1897 			vertex->gv_flags &= ~GV_TODISABLE;
1898 
1899 			vertex_send_event(vertex, RESTARTER_EVENT_TYPE_ENABLE);
1900 		}
1901 
1902 		/*
1903 		 * Wait for state update from restarter before sending _START or
1904 		 * _STOP.
1905 		 */
1906 
1907 		return;
1908 	}
1909 
1910 	if (vertex->gv_state == RESTARTER_STATE_DISABLED)
1911 		return;
1912 
1913 	if (!admin) {
1914 		vertex_send_event(vertex, RESTARTER_EVENT_TYPE_DISABLE);
1915 
1916 		/*
1917 		 * Wait for state update from restarter before sending _START or
1918 		 * _STOP.
1919 		 */
1920 
1921 		return;
1922 	}
1923 
1924 	/*
1925 	 * If it is a DISABLE event requested by the administrator then we are
1926 	 * offlining the dependents first.
1927 	 */
1928 
1929 	/*
1930 	 * Set GV_TOOFFLINE for the services we are offlining. We cannot
1931 	 * clear the GV_TOOFFLINE bits from all the services because
1932 	 * other DISABLE events might be handled at the same time.
1933 	 */
1934 	vertex->gv_flags |= GV_TOOFFLINE;
1935 
1936 	/* remember which vertex to disable... */
1937 	vertex->gv_flags |= GV_TODISABLE;
1938 
1939 	log_framework(LOG_DEBUG, "Marking in-subtree vertices before "
1940 	    "disabling %s.\n", vertex->gv_name);
1941 
1942 	/* set GV_TOOFFLINE for its dependents */
1943 	r = uu_list_walk(vertex->gv_dependents, (uu_walk_fn_t *)mark_subtree,
1944 	    NULL, 0);
1945 	assert(r == 0);
1946 
1947 	/* disable the instance now if there is nothing else to offline */
1948 	if (insubtree_dependents_down(vertex) == B_TRUE) {
1949 		vertex_send_event(vertex, RESTARTER_EVENT_TYPE_ADMIN_DISABLE);
1950 		return;
1951 	}
1952 
1953 	/*
1954 	 * This loop is similar to the one used for the graph reversal shutdown
1955 	 * and could be improved in term of performance for the subtree reversal
1956 	 * disable case.
1957 	 */
1958 	for (v = uu_list_first(dgraph); v != NULL;
1959 	    v = uu_list_next(dgraph, v)) {
1960 		/* skip the vertex we are disabling for now */
1961 		if (v == vertex)
1962 			continue;
1963 
1964 		if (v->gv_type != GVT_INST ||
1965 		    (v->gv_flags & GV_CONFIGURED) == 0 ||
1966 		    (v->gv_flags & GV_ENABLED) == 0 ||
1967 		    (v->gv_flags & GV_TOOFFLINE) == 0)
1968 			continue;
1969 
1970 		if ((v->gv_state != RESTARTER_STATE_ONLINE) &&
1971 		    (v->gv_state != RESTARTER_STATE_DEGRADED)) {
1972 			/* continue if there is nothing to offline */
1973 			continue;
1974 		}
1975 
1976 		/*
1977 		 * Instances which are up need to come down before we're
1978 		 * done, but we can only offline the leaves here. An
1979 		 * instance is a leaf when all its dependents are down.
1980 		 */
1981 		if (insubtree_dependents_down(v) == B_TRUE) {
1982 			log_framework(LOG_DEBUG, "Offlining in-subtree "
1983 			    "instance %s for %s.\n",
1984 			    v->gv_name, vertex->gv_name);
1985 			offline_vertex(v);
1986 		}
1987 	}
1988 }
1989 
1990 static int configure_vertex(graph_vertex_t *, scf_instance_t *);
1991 
1992 /*
1993  * Set the restarter for v to fmri_arg.  That is, make sure a vertex for
1994  * fmri_arg exists, make v depend on it, and send _ADD_INSTANCE for v.  If
1995  * v is already configured and fmri_arg indicates the current restarter, do
1996  * nothing.  If v is configured and fmri_arg is a new restarter, delete v's
1997  * dependency on the restarter, send _REMOVE_INSTANCE for v, and set the new
1998  * restarter.  Returns 0 on success, EINVAL if the FMRI is invalid,
1999  * ECONNABORTED if the repository connection is broken, and ELOOP
2000  * if the dependency would create a cycle.  In the last case, *pathp will
2001  * point to a -1-terminated array of ids which compose the path from v to
2002  * restarter_fmri.
2003  */
2004 int
2005 graph_change_restarter(graph_vertex_t *v, const char *fmri_arg, scf_handle_t *h,
2006     int **pathp)
2007 {
2008 	char *restarter_fmri = NULL;
2009 	graph_vertex_t *rv;
2010 	int err;
2011 	int id;
2012 
2013 	assert(MUTEX_HELD(&dgraph_lock));
2014 
2015 	if (fmri_arg[0] != '\0') {
2016 		err = fmri_canonify(fmri_arg, &restarter_fmri, B_TRUE);
2017 		if (err != 0) {
2018 			assert(err == EINVAL);
2019 			return (err);
2020 		}
2021 	}
2022 
2023 	if (restarter_fmri == NULL ||
2024 	    strcmp(restarter_fmri, SCF_SERVICE_STARTD) == 0) {
2025 		if (v->gv_flags & GV_CONFIGURED) {
2026 			if (v->gv_restarter_id == -1) {
2027 				if (restarter_fmri != NULL)
2028 					startd_free(restarter_fmri,
2029 					    max_scf_fmri_size);
2030 				return (0);
2031 			}
2032 
2033 			graph_unset_restarter(v);
2034 		}
2035 
2036 		/* Master restarter, nothing to do. */
2037 		v->gv_restarter_id = -1;
2038 		v->gv_restarter_channel = NULL;
2039 		vertex_send_event(v, RESTARTER_EVENT_TYPE_ADD_INSTANCE);
2040 		return (0);
2041 	}
2042 
2043 	if (v->gv_flags & GV_CONFIGURED) {
2044 		id = dict_lookup_byname(restarter_fmri);
2045 		if (id != -1 && v->gv_restarter_id == id) {
2046 			startd_free(restarter_fmri, max_scf_fmri_size);
2047 			return (0);
2048 		}
2049 
2050 		graph_unset_restarter(v);
2051 	}
2052 
2053 	err = graph_insert_vertex_unconfigured(restarter_fmri, GVT_INST, 0,
2054 	    RERR_NONE, &rv);
2055 	startd_free(restarter_fmri, max_scf_fmri_size);
2056 	assert(err == 0 || err == EEXIST);
2057 
2058 	if (rv->gv_delegate_initialized == 0) {
2059 		if ((rv->gv_delegate_channel = restarter_protocol_init_delegate(
2060 		    rv->gv_name)) == NULL)
2061 			return (EINVAL);
2062 		rv->gv_delegate_initialized = 1;
2063 	}
2064 	v->gv_restarter_id = rv->gv_id;
2065 	v->gv_restarter_channel = rv->gv_delegate_channel;
2066 
2067 	err = graph_insert_dependency(v, rv, pathp);
2068 	if (err != 0) {
2069 		assert(err == ELOOP);
2070 		return (ELOOP);
2071 	}
2072 
2073 	vertex_send_event(v, RESTARTER_EVENT_TYPE_ADD_INSTANCE);
2074 
2075 	if (!(rv->gv_flags & GV_CONFIGURED)) {
2076 		scf_instance_t *inst;
2077 
2078 		err = libscf_fmri_get_instance(h, rv->gv_name, &inst);
2079 		switch (err) {
2080 		case 0:
2081 			err = configure_vertex(rv, inst);
2082 			scf_instance_destroy(inst);
2083 			switch (err) {
2084 			case 0:
2085 			case ECANCELED:
2086 				break;
2087 
2088 			case ECONNABORTED:
2089 				return (ECONNABORTED);
2090 
2091 			default:
2092 				bad_error("configure_vertex", err);
2093 			}
2094 			break;
2095 
2096 		case ECONNABORTED:
2097 			return (ECONNABORTED);
2098 
2099 		case ENOENT:
2100 			break;
2101 
2102 		case ENOTSUP:
2103 			/*
2104 			 * The fmri doesn't specify an instance - translate
2105 			 * to EINVAL.
2106 			 */
2107 			return (EINVAL);
2108 
2109 		case EINVAL:
2110 		default:
2111 			bad_error("libscf_fmri_get_instance", err);
2112 		}
2113 	}
2114 
2115 	return (0);
2116 }
2117 
2118 
2119 /*
2120  * Add all of the instances of the service named by fmri to the graph.
2121  * Returns
2122  *   0 - success
2123  *   ENOENT - service indicated by fmri does not exist
2124  *
2125  * In both cases *reboundp will be B_TRUE if the handle was rebound, or B_FALSE
2126  * otherwise.
2127  */
2128 static int
2129 add_service(const char *fmri, scf_handle_t *h, boolean_t *reboundp)
2130 {
2131 	scf_service_t *svc;
2132 	scf_instance_t *inst;
2133 	scf_iter_t *iter;
2134 	char *inst_fmri;
2135 	int ret, r;
2136 
2137 	*reboundp = B_FALSE;
2138 
2139 	svc = safe_scf_service_create(h);
2140 	inst = safe_scf_instance_create(h);
2141 	iter = safe_scf_iter_create(h);
2142 	inst_fmri = startd_alloc(max_scf_fmri_size);
2143 
2144 rebound:
2145 	if (scf_handle_decode_fmri(h, fmri, NULL, svc, NULL, NULL, NULL,
2146 	    SCF_DECODE_FMRI_EXACT) != 0) {
2147 		switch (scf_error()) {
2148 		case SCF_ERROR_CONNECTION_BROKEN:
2149 		default:
2150 			libscf_handle_rebind(h);
2151 			*reboundp = B_TRUE;
2152 			goto rebound;
2153 
2154 		case SCF_ERROR_NOT_FOUND:
2155 			ret = ENOENT;
2156 			goto out;
2157 
2158 		case SCF_ERROR_INVALID_ARGUMENT:
2159 		case SCF_ERROR_CONSTRAINT_VIOLATED:
2160 		case SCF_ERROR_NOT_BOUND:
2161 		case SCF_ERROR_HANDLE_MISMATCH:
2162 			bad_error("scf_handle_decode_fmri", scf_error());
2163 		}
2164 	}
2165 
2166 	if (scf_iter_service_instances(iter, svc) != 0) {
2167 		switch (scf_error()) {
2168 		case SCF_ERROR_CONNECTION_BROKEN:
2169 		default:
2170 			libscf_handle_rebind(h);
2171 			*reboundp = B_TRUE;
2172 			goto rebound;
2173 
2174 		case SCF_ERROR_DELETED:
2175 			ret = ENOENT;
2176 			goto out;
2177 
2178 		case SCF_ERROR_HANDLE_MISMATCH:
2179 		case SCF_ERROR_NOT_BOUND:
2180 		case SCF_ERROR_NOT_SET:
2181 			bad_error("scf_iter_service_instances", scf_error());
2182 		}
2183 	}
2184 
2185 	for (;;) {
2186 		r = scf_iter_next_instance(iter, inst);
2187 		if (r == 0)
2188 			break;
2189 		if (r != 1) {
2190 			switch (scf_error()) {
2191 			case SCF_ERROR_CONNECTION_BROKEN:
2192 			default:
2193 				libscf_handle_rebind(h);
2194 				*reboundp = B_TRUE;
2195 				goto rebound;
2196 
2197 			case SCF_ERROR_DELETED:
2198 				ret = ENOENT;
2199 				goto out;
2200 
2201 			case SCF_ERROR_HANDLE_MISMATCH:
2202 			case SCF_ERROR_NOT_BOUND:
2203 			case SCF_ERROR_NOT_SET:
2204 			case SCF_ERROR_INVALID_ARGUMENT:
2205 				bad_error("scf_iter_next_instance",
2206 				    scf_error());
2207 			}
2208 		}
2209 
2210 		if (scf_instance_to_fmri(inst, inst_fmri, max_scf_fmri_size) <
2211 		    0) {
2212 			switch (scf_error()) {
2213 			case SCF_ERROR_CONNECTION_BROKEN:
2214 				libscf_handle_rebind(h);
2215 				*reboundp = B_TRUE;
2216 				goto rebound;
2217 
2218 			case SCF_ERROR_DELETED:
2219 				continue;
2220 
2221 			case SCF_ERROR_NOT_BOUND:
2222 			case SCF_ERROR_NOT_SET:
2223 				bad_error("scf_instance_to_fmri", scf_error());
2224 			}
2225 		}
2226 
2227 		r = dgraph_add_instance(inst_fmri, inst, B_FALSE);
2228 		switch (r) {
2229 		case 0:
2230 		case ECANCELED:
2231 			break;
2232 
2233 		case EEXIST:
2234 			continue;
2235 
2236 		case ECONNABORTED:
2237 			libscf_handle_rebind(h);
2238 			*reboundp = B_TRUE;
2239 			goto rebound;
2240 
2241 		case EINVAL:
2242 		default:
2243 			bad_error("dgraph_add_instance", r);
2244 		}
2245 	}
2246 
2247 	ret = 0;
2248 
2249 out:
2250 	startd_free(inst_fmri, max_scf_fmri_size);
2251 	scf_iter_destroy(iter);
2252 	scf_instance_destroy(inst);
2253 	scf_service_destroy(svc);
2254 	return (ret);
2255 }
2256 
2257 struct depfmri_info {
2258 	graph_vertex_t	*v;		/* GVT_GROUP vertex */
2259 	gv_type_t	type;		/* type of dependency */
2260 	const char	*inst_fmri;	/* FMRI of parental GVT_INST vert. */
2261 	const char	*pg_name;	/* Name of dependency pg */
2262 	scf_handle_t	*h;
2263 	int		err;		/* return error code */
2264 	int		**pathp;	/* return circular dependency path */
2265 };
2266 
2267 /*
2268  * Find or create a vertex for fmri and make info->v depend on it.
2269  * Returns
2270  *   0 - success
2271  *   nonzero - failure
2272  *
2273  * On failure, sets info->err to
2274  *   EINVAL - fmri is invalid
2275  *	      fmri does not match info->type
2276  *   ELOOP - Adding the dependency creates a circular dependency.  *info->pathp
2277  *	     will point to an array of the ids of the members of the cycle.
2278  *   ECONNABORTED - repository connection was broken
2279  *   ECONNRESET - succeeded, but repository connection was reset
2280  */
2281 static int
2282 process_dependency_fmri(const char *fmri, struct depfmri_info *info)
2283 {
2284 	int err;
2285 	graph_vertex_t *depgroup_v, *v;
2286 	char *fmri_copy, *cfmri;
2287 	size_t fmri_copy_sz;
2288 	const char *scope, *service, *instance, *pg;
2289 	scf_instance_t *inst;
2290 	boolean_t rebound;
2291 
2292 	assert(MUTEX_HELD(&dgraph_lock));
2293 
2294 	/* Get or create vertex for FMRI */
2295 	depgroup_v = info->v;
2296 
2297 	if (strncmp(fmri, "file:", sizeof ("file:") - 1) == 0) {
2298 		if (info->type != GVT_FILE) {
2299 			log_framework(LOG_NOTICE,
2300 			    "FMRI \"%s\" is not allowed for the \"%s\" "
2301 			    "dependency's type of instance %s.\n", fmri,
2302 			    info->pg_name, info->inst_fmri);
2303 			return (info->err = EINVAL);
2304 		}
2305 
2306 		err = graph_insert_vertex_unconfigured(fmri, info->type, 0,
2307 		    RERR_NONE, &v);
2308 		switch (err) {
2309 		case 0:
2310 			break;
2311 
2312 		case EEXIST:
2313 			assert(v->gv_type == GVT_FILE);
2314 			break;
2315 
2316 		case EINVAL:		/* prevented above */
2317 		default:
2318 			bad_error("graph_insert_vertex_unconfigured", err);
2319 		}
2320 	} else {
2321 		if (info->type != GVT_INST) {
2322 			log_framework(LOG_NOTICE,
2323 			    "FMRI \"%s\" is not allowed for the \"%s\" "
2324 			    "dependency's type of instance %s.\n", fmri,
2325 			    info->pg_name, info->inst_fmri);
2326 			return (info->err = EINVAL);
2327 		}
2328 
2329 		/*
2330 		 * We must canonify fmri & add a vertex for it.
2331 		 */
2332 		fmri_copy_sz = strlen(fmri) + 1;
2333 		fmri_copy = startd_alloc(fmri_copy_sz);
2334 		(void) strcpy(fmri_copy, fmri);
2335 
2336 		/* Determine if the FMRI is a property group or instance */
2337 		if (scf_parse_svc_fmri(fmri_copy, &scope, &service,
2338 		    &instance, &pg, NULL) != 0) {
2339 			startd_free(fmri_copy, fmri_copy_sz);
2340 			log_framework(LOG_NOTICE,
2341 			    "Dependency \"%s\" of %s has invalid FMRI "
2342 			    "\"%s\".\n", info->pg_name, info->inst_fmri,
2343 			    fmri);
2344 			return (info->err = EINVAL);
2345 		}
2346 
2347 		if (service == NULL || pg != NULL) {
2348 			startd_free(fmri_copy, fmri_copy_sz);
2349 			log_framework(LOG_NOTICE,
2350 			    "Dependency \"%s\" of %s does not designate a "
2351 			    "service or instance.\n", info->pg_name,
2352 			    info->inst_fmri);
2353 			return (info->err = EINVAL);
2354 		}
2355 
2356 		if (scope == NULL || strcmp(scope, SCF_SCOPE_LOCAL) == 0) {
2357 			cfmri = uu_msprintf("svc:/%s%s%s",
2358 			    service, instance ? ":" : "", instance ? instance :
2359 			    "");
2360 		} else {
2361 			cfmri = uu_msprintf("svc://%s/%s%s%s",
2362 			    scope, service, instance ? ":" : "", instance ?
2363 			    instance : "");
2364 		}
2365 
2366 		startd_free(fmri_copy, fmri_copy_sz);
2367 
2368 		err = graph_insert_vertex_unconfigured(cfmri, instance ?
2369 		    GVT_INST : GVT_SVC, instance ? 0 : DEPGRP_REQUIRE_ANY,
2370 		    RERR_NONE, &v);
2371 		uu_free(cfmri);
2372 		switch (err) {
2373 		case 0:
2374 			break;
2375 
2376 		case EEXIST:
2377 			/* Verify v. */
2378 			if (instance != NULL)
2379 				assert(v->gv_type == GVT_INST);
2380 			else
2381 				assert(v->gv_type == GVT_SVC);
2382 			break;
2383 
2384 		default:
2385 			bad_error("graph_insert_vertex_unconfigured", err);
2386 		}
2387 	}
2388 
2389 	/* Add dependency from depgroup_v to new vertex */
2390 	info->err = graph_insert_dependency(depgroup_v, v, info->pathp);
2391 	switch (info->err) {
2392 	case 0:
2393 		break;
2394 
2395 	case ELOOP:
2396 		return (ELOOP);
2397 
2398 	default:
2399 		bad_error("graph_insert_dependency", info->err);
2400 	}
2401 
2402 	/* This must be after we insert the dependency, to avoid looping. */
2403 	switch (v->gv_type) {
2404 	case GVT_INST:
2405 		if ((v->gv_flags & GV_CONFIGURED) != 0)
2406 			break;
2407 
2408 		inst = safe_scf_instance_create(info->h);
2409 
2410 		rebound = B_FALSE;
2411 
2412 rebound:
2413 		err = libscf_lookup_instance(v->gv_name, inst);
2414 		switch (err) {
2415 		case 0:
2416 			err = configure_vertex(v, inst);
2417 			switch (err) {
2418 			case 0:
2419 			case ECANCELED:
2420 				break;
2421 
2422 			case ECONNABORTED:
2423 				libscf_handle_rebind(info->h);
2424 				rebound = B_TRUE;
2425 				goto rebound;
2426 
2427 			default:
2428 				bad_error("configure_vertex", err);
2429 			}
2430 			break;
2431 
2432 		case ENOENT:
2433 			break;
2434 
2435 		case ECONNABORTED:
2436 			libscf_handle_rebind(info->h);
2437 			rebound = B_TRUE;
2438 			goto rebound;
2439 
2440 		case EINVAL:
2441 		case ENOTSUP:
2442 		default:
2443 			bad_error("libscf_fmri_get_instance", err);
2444 		}
2445 
2446 		scf_instance_destroy(inst);
2447 
2448 		if (rebound)
2449 			return (info->err = ECONNRESET);
2450 		break;
2451 
2452 	case GVT_SVC:
2453 		(void) add_service(v->gv_name, info->h, &rebound);
2454 		if (rebound)
2455 			return (info->err = ECONNRESET);
2456 	}
2457 
2458 	return (0);
2459 }
2460 
2461 struct deppg_info {
2462 	graph_vertex_t	*v;		/* GVT_INST vertex */
2463 	int		err;		/* return error */
2464 	int		**pathp;	/* return circular dependency path */
2465 };
2466 
2467 /*
2468  * Make info->v depend on a new GVT_GROUP node for this property group,
2469  * and then call process_dependency_fmri() for the values of the entity
2470  * property.  Return 0 on success, or if something goes wrong return nonzero
2471  * and set info->err to ECONNABORTED, EINVAL, or the error code returned by
2472  * process_dependency_fmri().
2473  */
2474 static int
2475 process_dependency_pg(scf_propertygroup_t *pg, struct deppg_info *info)
2476 {
2477 	scf_handle_t *h;
2478 	depgroup_type_t deptype;
2479 	restarter_error_t rerr;
2480 	struct depfmri_info linfo;
2481 	char *fmri, *pg_name;
2482 	size_t fmri_sz;
2483 	graph_vertex_t *depgrp;
2484 	scf_property_t *prop;
2485 	int err;
2486 	int empty;
2487 	scf_error_t scferr;
2488 	ssize_t len;
2489 
2490 	assert(MUTEX_HELD(&dgraph_lock));
2491 
2492 	h = scf_pg_handle(pg);
2493 
2494 	pg_name = startd_alloc(max_scf_name_size);
2495 
2496 	len = scf_pg_get_name(pg, pg_name, max_scf_name_size);
2497 	if (len < 0) {
2498 		startd_free(pg_name, max_scf_name_size);
2499 		switch (scf_error()) {
2500 		case SCF_ERROR_CONNECTION_BROKEN:
2501 		default:
2502 			return (info->err = ECONNABORTED);
2503 
2504 		case SCF_ERROR_DELETED:
2505 			return (info->err = 0);
2506 
2507 		case SCF_ERROR_NOT_SET:
2508 			bad_error("scf_pg_get_name", scf_error());
2509 		}
2510 	}
2511 
2512 	/*
2513 	 * Skip over empty dependency groups.  Since dependency property
2514 	 * groups are updated atomically, they are either empty or
2515 	 * fully populated.
2516 	 */
2517 	empty = depgroup_empty(h, pg);
2518 	if (empty < 0) {
2519 		log_error(LOG_INFO,
2520 		    "Error reading dependency group \"%s\" of %s: %s\n",
2521 		    pg_name, info->v->gv_name, scf_strerror(scf_error()));
2522 		startd_free(pg_name, max_scf_name_size);
2523 		return (info->err = EINVAL);
2524 
2525 	} else if (empty == 1) {
2526 		log_framework(LOG_DEBUG,
2527 		    "Ignoring empty dependency group \"%s\" of %s\n",
2528 		    pg_name, info->v->gv_name);
2529 		startd_free(pg_name, max_scf_name_size);
2530 		return (info->err = 0);
2531 	}
2532 
2533 	fmri_sz = strlen(info->v->gv_name) + 1 + len + 1;
2534 	fmri = startd_alloc(fmri_sz);
2535 
2536 	(void) snprintf(fmri, max_scf_name_size, "%s>%s", info->v->gv_name,
2537 	    pg_name);
2538 
2539 	/* Validate the pg before modifying the graph */
2540 	deptype = depgroup_read_grouping(h, pg);
2541 	if (deptype == DEPGRP_UNSUPPORTED) {
2542 		log_error(LOG_INFO,
2543 		    "Dependency \"%s\" of %s has an unknown grouping value.\n",
2544 		    pg_name, info->v->gv_name);
2545 		startd_free(fmri, fmri_sz);
2546 		startd_free(pg_name, max_scf_name_size);
2547 		return (info->err = EINVAL);
2548 	}
2549 
2550 	rerr = depgroup_read_restart(h, pg);
2551 	if (rerr == RERR_UNSUPPORTED) {
2552 		log_error(LOG_INFO,
2553 		    "Dependency \"%s\" of %s has an unknown restart_on value."
2554 		    "\n", pg_name, info->v->gv_name);
2555 		startd_free(fmri, fmri_sz);
2556 		startd_free(pg_name, max_scf_name_size);
2557 		return (info->err = EINVAL);
2558 	}
2559 
2560 	prop = safe_scf_property_create(h);
2561 
2562 	if (scf_pg_get_property(pg, SCF_PROPERTY_ENTITIES, prop) != 0) {
2563 		scferr = scf_error();
2564 		scf_property_destroy(prop);
2565 		if (scferr == SCF_ERROR_DELETED) {
2566 			startd_free(fmri, fmri_sz);
2567 			startd_free(pg_name, max_scf_name_size);
2568 			return (info->err = 0);
2569 		} else if (scferr != SCF_ERROR_NOT_FOUND) {
2570 			startd_free(fmri, fmri_sz);
2571 			startd_free(pg_name, max_scf_name_size);
2572 			return (info->err = ECONNABORTED);
2573 		}
2574 
2575 		log_error(LOG_INFO,
2576 		    "Dependency \"%s\" of %s is missing a \"%s\" property.\n",
2577 		    pg_name, info->v->gv_name, SCF_PROPERTY_ENTITIES);
2578 
2579 		startd_free(fmri, fmri_sz);
2580 		startd_free(pg_name, max_scf_name_size);
2581 
2582 		return (info->err = EINVAL);
2583 	}
2584 
2585 	/* Create depgroup vertex for pg */
2586 	err = graph_insert_vertex_unconfigured(fmri, GVT_GROUP, deptype,
2587 	    rerr, &depgrp);
2588 	assert(err == 0);
2589 	startd_free(fmri, fmri_sz);
2590 
2591 	/* Add dependency from inst vertex to new vertex */
2592 	err = graph_insert_dependency(info->v, depgrp, info->pathp);
2593 	/* ELOOP can't happen because this should be a new vertex */
2594 	assert(err == 0);
2595 
2596 	linfo.v = depgrp;
2597 	linfo.type = depgroup_read_scheme(h, pg);
2598 	linfo.inst_fmri = info->v->gv_name;
2599 	linfo.pg_name = pg_name;
2600 	linfo.h = h;
2601 	linfo.err = 0;
2602 	linfo.pathp = info->pathp;
2603 	err = walk_property_astrings(prop, (callback_t)process_dependency_fmri,
2604 	    &linfo);
2605 
2606 	scf_property_destroy(prop);
2607 	startd_free(pg_name, max_scf_name_size);
2608 
2609 	switch (err) {
2610 	case 0:
2611 	case EINTR:
2612 		return (info->err = linfo.err);
2613 
2614 	case ECONNABORTED:
2615 	case EINVAL:
2616 		return (info->err = err);
2617 
2618 	case ECANCELED:
2619 		return (info->err = 0);
2620 
2621 	case ECONNRESET:
2622 		return (info->err = ECONNABORTED);
2623 
2624 	default:
2625 		bad_error("walk_property_astrings", err);
2626 		/* NOTREACHED */
2627 	}
2628 }
2629 
2630 /*
2631  * Build the dependency info for v from the repository.  Returns 0 on success,
2632  * ECONNABORTED on repository disconnection, EINVAL if the repository
2633  * configuration is invalid, and ELOOP if a dependency would cause a cycle.
2634  * In the last case, *pathp will point to a -1-terminated array of ids which
2635  * constitute the rest of the dependency cycle.
2636  */
2637 static int
2638 set_dependencies(graph_vertex_t *v, scf_instance_t *inst, int **pathp)
2639 {
2640 	struct deppg_info info;
2641 	int err;
2642 	uint_t old_configured;
2643 
2644 	assert(MUTEX_HELD(&dgraph_lock));
2645 
2646 	/*
2647 	 * Mark the vertex as configured during dependency insertion to avoid
2648 	 * dependency cycles (which can appear in the graph if one of the
2649 	 * vertices is an exclusion-group).
2650 	 */
2651 	old_configured = v->gv_flags & GV_CONFIGURED;
2652 	v->gv_flags |= GV_CONFIGURED;
2653 
2654 	info.err = 0;
2655 	info.v = v;
2656 	info.pathp = pathp;
2657 
2658 	err = walk_dependency_pgs(inst, (callback_t)process_dependency_pg,
2659 	    &info);
2660 
2661 	if (!old_configured)
2662 		v->gv_flags &= ~GV_CONFIGURED;
2663 
2664 	switch (err) {
2665 	case 0:
2666 	case EINTR:
2667 		return (info.err);
2668 
2669 	case ECONNABORTED:
2670 		return (ECONNABORTED);
2671 
2672 	case ECANCELED:
2673 		/* Should get delete event, so return 0. */
2674 		return (0);
2675 
2676 	default:
2677 		bad_error("walk_dependency_pgs", err);
2678 		/* NOTREACHED */
2679 	}
2680 }
2681 
2682 
2683 static void
2684 handle_cycle(const char *fmri, int *path)
2685 {
2686 	const char *cp;
2687 	size_t sz;
2688 
2689 	assert(MUTEX_HELD(&dgraph_lock));
2690 
2691 	path_to_str(path, (char **)&cp, &sz);
2692 
2693 	log_error(LOG_ERR, "Transitioning %s to maintenance "
2694 	    "because it completes a dependency cycle (see svcs -xv for "
2695 	    "details):\n%s", fmri ? fmri : "?", cp);
2696 
2697 	startd_free((void *)cp, sz);
2698 }
2699 
2700 /*
2701  * Increment the vertex's reference count to prevent the vertex removal
2702  * from the dgraph.
2703  */
2704 static void
2705 vertex_ref(graph_vertex_t *v)
2706 {
2707 	assert(MUTEX_HELD(&dgraph_lock));
2708 
2709 	v->gv_refs++;
2710 }
2711 
2712 /*
2713  * Decrement the vertex's reference count and remove the vertex from
2714  * the dgraph when possible.
2715  *
2716  * Return VERTEX_REMOVED when the vertex has been removed otherwise
2717  * return VERTEX_INUSE.
2718  */
2719 static int
2720 vertex_unref(graph_vertex_t *v)
2721 {
2722 	assert(MUTEX_HELD(&dgraph_lock));
2723 	assert(v->gv_refs > 0);
2724 
2725 	v->gv_refs--;
2726 
2727 	return (free_if_unrefed(v));
2728 }
2729 
2730 /*
2731  * When run on the dependencies of a vertex, populates list with
2732  * graph_edge_t's which point to the service vertices or the instance
2733  * vertices (no GVT_GROUP nodes) on which the vertex depends.
2734  *
2735  * Increment the vertex's reference count once the vertex is inserted
2736  * in the list. The vertex won't be able to be deleted from the dgraph
2737  * while it is referenced.
2738  */
2739 static int
2740 append_svcs_or_insts(graph_edge_t *e, uu_list_t *list)
2741 {
2742 	graph_vertex_t *v = e->ge_vertex;
2743 	graph_edge_t *new;
2744 	int r;
2745 
2746 	switch (v->gv_type) {
2747 	case GVT_INST:
2748 	case GVT_SVC:
2749 		break;
2750 
2751 	case GVT_GROUP:
2752 		r = uu_list_walk(v->gv_dependencies,
2753 		    (uu_walk_fn_t *)append_svcs_or_insts, list, 0);
2754 		assert(r == 0);
2755 		return (UU_WALK_NEXT);
2756 
2757 	case GVT_FILE:
2758 		return (UU_WALK_NEXT);
2759 
2760 	default:
2761 #ifndef NDEBUG
2762 		uu_warn("%s:%d: Unexpected vertex type %d.\n", __FILE__,
2763 		    __LINE__, v->gv_type);
2764 #endif
2765 		abort();
2766 	}
2767 
2768 	new = startd_alloc(sizeof (*new));
2769 	new->ge_vertex = v;
2770 	uu_list_node_init(new, &new->ge_link, graph_edge_pool);
2771 	r = uu_list_insert_before(list, NULL, new);
2772 	assert(r == 0);
2773 
2774 	/*
2775 	 * Because we are inserting the vertex in a list, we don't want
2776 	 * the vertex to be freed while the list is in use. In order to
2777 	 * achieve that, increment the vertex's reference count.
2778 	 */
2779 	vertex_ref(v);
2780 
2781 	return (UU_WALK_NEXT);
2782 }
2783 
2784 static boolean_t
2785 should_be_in_subgraph(graph_vertex_t *v)
2786 {
2787 	graph_edge_t *e;
2788 
2789 	if (v == milestone)
2790 		return (B_TRUE);
2791 
2792 	/*
2793 	 * v is in the subgraph if any of its dependents are in the subgraph.
2794 	 * Except for EXCLUDE_ALL dependents.  And OPTIONAL dependents only
2795 	 * count if we're enabled.
2796 	 */
2797 	for (e = uu_list_first(v->gv_dependents);
2798 	    e != NULL;
2799 	    e = uu_list_next(v->gv_dependents, e)) {
2800 		graph_vertex_t *dv = e->ge_vertex;
2801 
2802 		if (!(dv->gv_flags & GV_INSUBGRAPH))
2803 			continue;
2804 
2805 		/*
2806 		 * Don't include instances that are optional and disabled.
2807 		 */
2808 		if (v->gv_type == GVT_INST && dv->gv_type == GVT_SVC) {
2809 
2810 			int in = 0;
2811 			graph_edge_t *ee;
2812 
2813 			for (ee = uu_list_first(dv->gv_dependents);
2814 			    ee != NULL;
2815 			    ee = uu_list_next(dv->gv_dependents, ee)) {
2816 
2817 				graph_vertex_t *ddv = e->ge_vertex;
2818 
2819 				if (ddv->gv_type == GVT_GROUP &&
2820 				    ddv->gv_depgroup == DEPGRP_EXCLUDE_ALL)
2821 					continue;
2822 
2823 				if (ddv->gv_type == GVT_GROUP &&
2824 				    ddv->gv_depgroup == DEPGRP_OPTIONAL_ALL &&
2825 				    !(v->gv_flags & GV_ENBLD_NOOVR))
2826 					continue;
2827 
2828 				in = 1;
2829 			}
2830 			if (!in)
2831 				continue;
2832 		}
2833 		if (v->gv_type == GVT_INST &&
2834 		    dv->gv_type == GVT_GROUP &&
2835 		    dv->gv_depgroup == DEPGRP_OPTIONAL_ALL &&
2836 		    !(v->gv_flags & GV_ENBLD_NOOVR))
2837 			continue;
2838 
2839 		/* Don't include excluded services and instances */
2840 		if (dv->gv_type == GVT_GROUP &&
2841 		    dv->gv_depgroup == DEPGRP_EXCLUDE_ALL)
2842 			continue;
2843 
2844 		return (B_TRUE);
2845 	}
2846 
2847 	return (B_FALSE);
2848 }
2849 
2850 /*
2851  * Ensures that GV_INSUBGRAPH is set properly for v and its descendents.  If
2852  * any bits change, manipulate the repository appropriately.  Returns 0 or
2853  * ECONNABORTED.
2854  */
2855 static int
2856 eval_subgraph(graph_vertex_t *v, scf_handle_t *h)
2857 {
2858 	boolean_t old = (v->gv_flags & GV_INSUBGRAPH) != 0;
2859 	boolean_t new;
2860 	graph_edge_t *e;
2861 	scf_instance_t *inst;
2862 	int ret = 0, r;
2863 
2864 	assert(milestone != NULL && milestone != MILESTONE_NONE);
2865 
2866 	new = should_be_in_subgraph(v);
2867 
2868 	if (new == old)
2869 		return (0);
2870 
2871 	log_framework(LOG_DEBUG, new ? "Adding %s to the subgraph.\n" :
2872 	    "Removing %s from the subgraph.\n", v->gv_name);
2873 
2874 	v->gv_flags = (v->gv_flags & ~GV_INSUBGRAPH) |
2875 	    (new ? GV_INSUBGRAPH : 0);
2876 
2877 	if (v->gv_type == GVT_INST && (v->gv_flags & GV_CONFIGURED)) {
2878 		int err;
2879 
2880 get_inst:
2881 		err = libscf_fmri_get_instance(h, v->gv_name, &inst);
2882 		if (err != 0) {
2883 			switch (err) {
2884 			case ECONNABORTED:
2885 				libscf_handle_rebind(h);
2886 				ret = ECONNABORTED;
2887 				goto get_inst;
2888 
2889 			case ENOENT:
2890 				break;
2891 
2892 			case EINVAL:
2893 			case ENOTSUP:
2894 			default:
2895 				bad_error("libscf_fmri_get_instance", err);
2896 			}
2897 		} else {
2898 			const char *f;
2899 
2900 			if (new) {
2901 				err = libscf_delete_enable_ovr(inst);
2902 				f = "libscf_delete_enable_ovr";
2903 			} else {
2904 				err = libscf_set_enable_ovr(inst, 0);
2905 				f = "libscf_set_enable_ovr";
2906 			}
2907 			scf_instance_destroy(inst);
2908 			switch (err) {
2909 			case 0:
2910 			case ECANCELED:
2911 				break;
2912 
2913 			case ECONNABORTED:
2914 				libscf_handle_rebind(h);
2915 				/*
2916 				 * We must continue so the graph is updated,
2917 				 * but we must return ECONNABORTED so any
2918 				 * libscf state held by any callers is reset.
2919 				 */
2920 				ret = ECONNABORTED;
2921 				goto get_inst;
2922 
2923 			case EROFS:
2924 			case EPERM:
2925 				log_error(LOG_WARNING,
2926 				    "Could not set %s/%s for %s: %s.\n",
2927 				    SCF_PG_GENERAL_OVR, SCF_PROPERTY_ENABLED,
2928 				    v->gv_name, strerror(err));
2929 				break;
2930 
2931 			default:
2932 				bad_error(f, err);
2933 			}
2934 		}
2935 	}
2936 
2937 	for (e = uu_list_first(v->gv_dependencies);
2938 	    e != NULL;
2939 	    e = uu_list_next(v->gv_dependencies, e)) {
2940 		r = eval_subgraph(e->ge_vertex, h);
2941 		if (r != 0) {
2942 			assert(r == ECONNABORTED);
2943 			ret = ECONNABORTED;
2944 		}
2945 	}
2946 
2947 	return (ret);
2948 }
2949 
2950 /*
2951  * Delete the (property group) dependencies of v & create new ones based on
2952  * inst.  If doing so would create a cycle, log a message and put the instance
2953  * into maintenance.  Update GV_INSUBGRAPH flags as necessary.  Returns 0 or
2954  * ECONNABORTED.
2955  */
2956 int
2957 refresh_vertex(graph_vertex_t *v, scf_instance_t *inst)
2958 {
2959 	int err;
2960 	int *path;
2961 	char *fmri;
2962 	int r;
2963 	scf_handle_t *h = scf_instance_handle(inst);
2964 	uu_list_t *old_deps;
2965 	int ret = 0;
2966 	graph_edge_t *e;
2967 	graph_vertex_t *vv;
2968 
2969 	assert(MUTEX_HELD(&dgraph_lock));
2970 	assert(v->gv_type == GVT_INST);
2971 
2972 	log_framework(LOG_DEBUG, "Graph engine: Refreshing %s.\n", v->gv_name);
2973 
2974 	if (milestone > MILESTONE_NONE) {
2975 		/*
2976 		 * In case some of v's dependencies are being deleted we must
2977 		 * make a list of them now for GV_INSUBGRAPH-flag evaluation
2978 		 * after the new dependencies are in place.
2979 		 */
2980 		old_deps = startd_list_create(graph_edge_pool, NULL, 0);
2981 
2982 		err = uu_list_walk(v->gv_dependencies,
2983 		    (uu_walk_fn_t *)append_svcs_or_insts, old_deps, 0);
2984 		assert(err == 0);
2985 	}
2986 
2987 	delete_instance_dependencies(v, B_FALSE);
2988 
2989 	err = set_dependencies(v, inst, &path);
2990 	switch (err) {
2991 	case 0:
2992 		break;
2993 
2994 	case ECONNABORTED:
2995 		ret = err;
2996 		goto out;
2997 
2998 	case EINVAL:
2999 	case ELOOP:
3000 		r = libscf_instance_get_fmri(inst, &fmri);
3001 		switch (r) {
3002 		case 0:
3003 			break;
3004 
3005 		case ECONNABORTED:
3006 			ret = ECONNABORTED;
3007 			goto out;
3008 
3009 		case ECANCELED:
3010 			ret = 0;
3011 			goto out;
3012 
3013 		default:
3014 			bad_error("libscf_instance_get_fmri", r);
3015 		}
3016 
3017 		if (err == EINVAL) {
3018 			log_error(LOG_ERR, "Transitioning %s "
3019 			    "to maintenance due to misconfiguration.\n",
3020 			    fmri ? fmri : "?");
3021 			vertex_send_event(v,
3022 			    RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY);
3023 		} else {
3024 			handle_cycle(fmri, path);
3025 			vertex_send_event(v,
3026 			    RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE);
3027 		}
3028 		startd_free(fmri, max_scf_fmri_size);
3029 		ret = 0;
3030 		goto out;
3031 
3032 	default:
3033 		bad_error("set_dependencies", err);
3034 	}
3035 
3036 	if (milestone > MILESTONE_NONE) {
3037 		boolean_t aborted = B_FALSE;
3038 
3039 		for (e = uu_list_first(old_deps);
3040 		    e != NULL;
3041 		    e = uu_list_next(old_deps, e)) {
3042 			vv = e->ge_vertex;
3043 
3044 			if (vertex_unref(vv) == VERTEX_INUSE &&
3045 			    eval_subgraph(vv, h) == ECONNABORTED)
3046 				aborted = B_TRUE;
3047 		}
3048 
3049 		for (e = uu_list_first(v->gv_dependencies);
3050 		    e != NULL;
3051 		    e = uu_list_next(v->gv_dependencies, e)) {
3052 			if (eval_subgraph(e->ge_vertex, h) ==
3053 			    ECONNABORTED)
3054 				aborted = B_TRUE;
3055 		}
3056 
3057 		if (aborted) {
3058 			ret = ECONNABORTED;
3059 			goto out;
3060 		}
3061 	}
3062 
3063 	graph_start_if_satisfied(v);
3064 
3065 	ret = 0;
3066 
3067 out:
3068 	if (milestone > MILESTONE_NONE) {
3069 		void *cookie = NULL;
3070 
3071 		while ((e = uu_list_teardown(old_deps, &cookie)) != NULL)
3072 			startd_free(e, sizeof (*e));
3073 
3074 		uu_list_destroy(old_deps);
3075 	}
3076 
3077 	return (ret);
3078 }
3079 
3080 /*
3081  * Set up v according to inst.  That is, make sure it depends on its
3082  * restarter and set up its dependencies.  Send the ADD_INSTANCE command to
3083  * the restarter, and send ENABLE or DISABLE as appropriate.
3084  *
3085  * Returns 0 on success, ECONNABORTED on repository disconnection, or
3086  * ECANCELED if inst is deleted.
3087  */
3088 static int
3089 configure_vertex(graph_vertex_t *v, scf_instance_t *inst)
3090 {
3091 	scf_handle_t *h;
3092 	scf_propertygroup_t *pg;
3093 	scf_snapshot_t *snap;
3094 	char *restarter_fmri = startd_alloc(max_scf_value_size);
3095 	int enabled, enabled_ovr;
3096 	int err;
3097 	int *path;
3098 	int deathrow;
3099 
3100 	restarter_fmri[0] = '\0';
3101 
3102 	assert(MUTEX_HELD(&dgraph_lock));
3103 	assert(v->gv_type == GVT_INST);
3104 	assert((v->gv_flags & GV_CONFIGURED) == 0);
3105 
3106 	/* GV_INSUBGRAPH should already be set properly. */
3107 	assert(should_be_in_subgraph(v) ==
3108 	    ((v->gv_flags & GV_INSUBGRAPH) != 0));
3109 
3110 	/*
3111 	 * If the instance fmri is in the deathrow list then set the
3112 	 * GV_DEATHROW flag on the vertex and create and set to true the
3113 	 * SCF_PROPERTY_DEATHROW boolean property in the non-persistent
3114 	 * repository for this instance fmri.
3115 	 */
3116 	if ((v->gv_flags & GV_DEATHROW) ||
3117 	    (is_fmri_in_deathrow(v->gv_name) == B_TRUE)) {
3118 		if ((v->gv_flags & GV_DEATHROW) == 0) {
3119 			/*
3120 			 * Set flag GV_DEATHROW, create and set to true
3121 			 * the SCF_PROPERTY_DEATHROW property in the
3122 			 * non-persistent repository for this instance fmri.
3123 			 */
3124 			v->gv_flags |= GV_DEATHROW;
3125 
3126 			switch (err = libscf_set_deathrow(inst, 1)) {
3127 			case 0:
3128 				break;
3129 
3130 			case ECONNABORTED:
3131 			case ECANCELED:
3132 				startd_free(restarter_fmri, max_scf_value_size);
3133 				return (err);
3134 
3135 			case EROFS:
3136 				log_error(LOG_WARNING, "Could not set %s/%s "
3137 				    "for deathrow %s: %s.\n",
3138 				    SCF_PG_DEATHROW, SCF_PROPERTY_DEATHROW,
3139 				    v->gv_name, strerror(err));
3140 				break;
3141 
3142 			case EPERM:
3143 				uu_die("Permission denied.\n");
3144 				/* NOTREACHED */
3145 
3146 			default:
3147 				bad_error("libscf_set_deathrow", err);
3148 			}
3149 			log_framework(LOG_DEBUG, "Deathrow, graph set %s.\n",
3150 			    v->gv_name);
3151 		}
3152 		startd_free(restarter_fmri, max_scf_value_size);
3153 		return (0);
3154 	}
3155 
3156 	h = scf_instance_handle(inst);
3157 
3158 	/*
3159 	 * Using a temporary deathrow boolean property, set through
3160 	 * libscf_set_deathrow(), only for fmris on deathrow, is necessary
3161 	 * because deathrow_fini() may already have been called, and in case
3162 	 * of a refresh, GV_DEATHROW may need to be set again.
3163 	 * libscf_get_deathrow() sets deathrow to 1 only if this instance
3164 	 * has a temporary boolean property named 'deathrow' valued true
3165 	 * in a property group 'deathrow', -1 or 0 in all other cases.
3166 	 */
3167 	err = libscf_get_deathrow(h, inst, &deathrow);
3168 	switch (err) {
3169 	case 0:
3170 		break;
3171 
3172 	case ECONNABORTED:
3173 	case ECANCELED:
3174 		startd_free(restarter_fmri, max_scf_value_size);
3175 		return (err);
3176 
3177 	default:
3178 		bad_error("libscf_get_deathrow", err);
3179 	}
3180 
3181 	if (deathrow == 1) {
3182 		v->gv_flags |= GV_DEATHROW;
3183 		startd_free(restarter_fmri, max_scf_value_size);
3184 		return (0);
3185 	}
3186 
3187 	log_framework(LOG_DEBUG, "Graph adding %s.\n", v->gv_name);
3188 
3189 	/*
3190 	 * If the instance does not have a restarter property group,
3191 	 * initialize its state to uninitialized/none, in case the restarter
3192 	 * is not enabled.
3193 	 */
3194 	pg = safe_scf_pg_create(h);
3195 
3196 	if (scf_instance_get_pg(inst, SCF_PG_RESTARTER, pg) != 0) {
3197 		instance_data_t idata;
3198 		uint_t count = 0, msecs = ALLOC_DELAY;
3199 
3200 		switch (scf_error()) {
3201 		case SCF_ERROR_NOT_FOUND:
3202 			break;
3203 
3204 		case SCF_ERROR_CONNECTION_BROKEN:
3205 		default:
3206 			scf_pg_destroy(pg);
3207 			startd_free(restarter_fmri, max_scf_value_size);
3208 			return (ECONNABORTED);
3209 
3210 		case SCF_ERROR_DELETED:
3211 			scf_pg_destroy(pg);
3212 			startd_free(restarter_fmri, max_scf_value_size);
3213 			return (ECANCELED);
3214 
3215 		case SCF_ERROR_NOT_SET:
3216 			bad_error("scf_instance_get_pg", scf_error());
3217 		}
3218 
3219 		switch (err = libscf_instance_get_fmri(inst,
3220 		    (char **)&idata.i_fmri)) {
3221 		case 0:
3222 			break;
3223 
3224 		case ECONNABORTED:
3225 		case ECANCELED:
3226 			scf_pg_destroy(pg);
3227 			startd_free(restarter_fmri, max_scf_value_size);
3228 			return (err);
3229 
3230 		default:
3231 			bad_error("libscf_instance_get_fmri", err);
3232 		}
3233 
3234 		idata.i_state = RESTARTER_STATE_NONE;
3235 		idata.i_next_state = RESTARTER_STATE_NONE;
3236 
3237 init_state:
3238 		switch (err = _restarter_commit_states(h, &idata,
3239 		    RESTARTER_STATE_UNINIT, RESTARTER_STATE_NONE, NULL)) {
3240 		case 0:
3241 			break;
3242 
3243 		case ENOMEM:
3244 			++count;
3245 			if (count < ALLOC_RETRY) {
3246 				(void) poll(NULL, 0, msecs);
3247 				msecs *= ALLOC_DELAY_MULT;
3248 				goto init_state;
3249 			}
3250 
3251 			uu_die("Insufficient memory.\n");
3252 			/* NOTREACHED */
3253 
3254 		case ECONNABORTED:
3255 			startd_free((void *)idata.i_fmri, max_scf_fmri_size);
3256 			scf_pg_destroy(pg);
3257 			startd_free(restarter_fmri, max_scf_value_size);
3258 			return (ECONNABORTED);
3259 
3260 		case ENOENT:
3261 			startd_free((void *)idata.i_fmri, max_scf_fmri_size);
3262 			scf_pg_destroy(pg);
3263 			startd_free(restarter_fmri, max_scf_value_size);
3264 			return (ECANCELED);
3265 
3266 		case EPERM:
3267 		case EACCES:
3268 		case EROFS:
3269 			log_error(LOG_NOTICE, "Could not initialize state for "
3270 			    "%s: %s.\n", idata.i_fmri, strerror(err));
3271 			break;
3272 
3273 		case EINVAL:
3274 		default:
3275 			bad_error("_restarter_commit_states", err);
3276 		}
3277 
3278 		startd_free((void *)idata.i_fmri, max_scf_fmri_size);
3279 	}
3280 
3281 	scf_pg_destroy(pg);
3282 
3283 	if (milestone != NULL) {
3284 		/*
3285 		 * Make sure the enable-override is set properly before we
3286 		 * read whether we should be enabled.
3287 		 */
3288 		if (milestone == MILESTONE_NONE ||
3289 		    !(v->gv_flags & GV_INSUBGRAPH)) {
3290 			/*
3291 			 * This might seem unjustified after the milestone
3292 			 * transition has completed (non_subgraph_svcs == 0),
3293 			 * but it's important because when we boot to
3294 			 * a milestone, we set the milestone before populating
3295 			 * the graph, and all of the new non-subgraph services
3296 			 * need to be disabled here.
3297 			 */
3298 			switch (err = libscf_set_enable_ovr(inst, 0)) {
3299 			case 0:
3300 				break;
3301 
3302 			case ECONNABORTED:
3303 			case ECANCELED:
3304 				startd_free(restarter_fmri, max_scf_value_size);
3305 				return (err);
3306 
3307 			case EROFS:
3308 				log_error(LOG_WARNING,
3309 				    "Could not set %s/%s for %s: %s.\n",
3310 				    SCF_PG_GENERAL_OVR, SCF_PROPERTY_ENABLED,
3311 				    v->gv_name, strerror(err));
3312 				break;
3313 
3314 			case EPERM:
3315 				uu_die("Permission denied.\n");
3316 				/* NOTREACHED */
3317 
3318 			default:
3319 				bad_error("libscf_set_enable_ovr", err);
3320 			}
3321 		} else {
3322 			assert(v->gv_flags & GV_INSUBGRAPH);
3323 			switch (err = libscf_delete_enable_ovr(inst)) {
3324 			case 0:
3325 				break;
3326 
3327 			case ECONNABORTED:
3328 			case ECANCELED:
3329 				startd_free(restarter_fmri, max_scf_value_size);
3330 				return (err);
3331 
3332 			case EPERM:
3333 				uu_die("Permission denied.\n");
3334 				/* NOTREACHED */
3335 
3336 			default:
3337 				bad_error("libscf_delete_enable_ovr", err);
3338 			}
3339 		}
3340 	}
3341 
3342 	err = libscf_get_basic_instance_data(h, inst, v->gv_name, &enabled,
3343 	    &enabled_ovr, &restarter_fmri);
3344 	switch (err) {
3345 	case 0:
3346 		break;
3347 
3348 	case ECONNABORTED:
3349 	case ECANCELED:
3350 		startd_free(restarter_fmri, max_scf_value_size);
3351 		return (err);
3352 
3353 	case ENOENT:
3354 		log_framework(LOG_DEBUG,
3355 		    "Ignoring %s because it has no general property group.\n",
3356 		    v->gv_name);
3357 		startd_free(restarter_fmri, max_scf_value_size);
3358 		return (0);
3359 
3360 	default:
3361 		bad_error("libscf_get_basic_instance_data", err);
3362 	}
3363 
3364 	if (enabled == -1) {
3365 		startd_free(restarter_fmri, max_scf_value_size);
3366 		return (0);
3367 	}
3368 
3369 	v->gv_flags = (v->gv_flags & ~GV_ENBLD_NOOVR) |
3370 	    (enabled ? GV_ENBLD_NOOVR : 0);
3371 
3372 	if (enabled_ovr != -1)
3373 		enabled = enabled_ovr;
3374 
3375 	v->gv_state = RESTARTER_STATE_UNINIT;
3376 
3377 	snap = libscf_get_or_make_running_snapshot(inst, v->gv_name, B_TRUE);
3378 	scf_snapshot_destroy(snap);
3379 
3380 	/* Set up the restarter. (Sends _ADD_INSTANCE on success.) */
3381 	err = graph_change_restarter(v, restarter_fmri, h, &path);
3382 	if (err != 0) {
3383 		instance_data_t idata;
3384 		uint_t count = 0, msecs = ALLOC_DELAY;
3385 		const char *reason;
3386 
3387 		if (err == ECONNABORTED) {
3388 			startd_free(restarter_fmri, max_scf_value_size);
3389 			return (err);
3390 		}
3391 
3392 		assert(err == EINVAL || err == ELOOP);
3393 
3394 		if (err == EINVAL) {
3395 			log_framework(LOG_ERR, emsg_invalid_restarter,
3396 			    v->gv_name, restarter_fmri);
3397 			reason = "invalid_restarter";
3398 		} else {
3399 			handle_cycle(v->gv_name, path);
3400 			reason = "dependency_cycle";
3401 		}
3402 
3403 		startd_free(restarter_fmri, max_scf_value_size);
3404 
3405 		/*
3406 		 * We didn't register the instance with the restarter, so we
3407 		 * must set maintenance mode ourselves.
3408 		 */
3409 		err = libscf_instance_get_fmri(inst, (char **)&idata.i_fmri);
3410 		if (err != 0) {
3411 			assert(err == ECONNABORTED || err == ECANCELED);
3412 			return (err);
3413 		}
3414 
3415 		idata.i_state = RESTARTER_STATE_NONE;
3416 		idata.i_next_state = RESTARTER_STATE_NONE;
3417 
3418 set_maint:
3419 		switch (err = _restarter_commit_states(h, &idata,
3420 		    RESTARTER_STATE_MAINT, RESTARTER_STATE_NONE, reason)) {
3421 		case 0:
3422 			break;
3423 
3424 		case ENOMEM:
3425 			++count;
3426 			if (count < ALLOC_RETRY) {
3427 				(void) poll(NULL, 0, msecs);
3428 				msecs *= ALLOC_DELAY_MULT;
3429 				goto set_maint;
3430 			}
3431 
3432 			uu_die("Insufficient memory.\n");
3433 			/* NOTREACHED */
3434 
3435 		case ECONNABORTED:
3436 			startd_free((void *)idata.i_fmri, max_scf_fmri_size);
3437 			return (ECONNABORTED);
3438 
3439 		case ENOENT:
3440 			startd_free((void *)idata.i_fmri, max_scf_fmri_size);
3441 			return (ECANCELED);
3442 
3443 		case EPERM:
3444 		case EACCES:
3445 		case EROFS:
3446 			log_error(LOG_NOTICE, "Could not initialize state for "
3447 			    "%s: %s.\n", idata.i_fmri, strerror(err));
3448 			break;
3449 
3450 		case EINVAL:
3451 		default:
3452 			bad_error("_restarter_commit_states", err);
3453 		}
3454 
3455 		startd_free((void *)idata.i_fmri, max_scf_fmri_size);
3456 
3457 		v->gv_state = RESTARTER_STATE_MAINT;
3458 
3459 		goto out;
3460 	}
3461 	startd_free(restarter_fmri, max_scf_value_size);
3462 
3463 	/* Add all the other dependencies. */
3464 	err = refresh_vertex(v, inst);
3465 	if (err != 0) {
3466 		assert(err == ECONNABORTED);
3467 		return (err);
3468 	}
3469 
3470 out:
3471 	v->gv_flags |= GV_CONFIGURED;
3472 
3473 	graph_enable_by_vertex(v, enabled, 0);
3474 
3475 	return (0);
3476 }
3477 
3478 
3479 static void
3480 kill_user_procs(void)
3481 {
3482 	(void) fputs("svc.startd: Killing user processes.\n", stdout);
3483 
3484 	/*
3485 	 * Despite its name, killall's role is to get select user processes--
3486 	 * basically those representing terminal-based logins-- to die.  Victims
3487 	 * are located by killall in the utmp database.  Since these are most
3488 	 * often shell based logins, and many shells mask SIGTERM (but are
3489 	 * responsive to SIGHUP) we first HUP and then shortly thereafter
3490 	 * kill -9.
3491 	 */
3492 	(void) fork_with_timeout("/usr/sbin/killall HUP", 1, 5);
3493 	(void) fork_with_timeout("/usr/sbin/killall KILL", 1, 5);
3494 
3495 	/*
3496 	 * Note the selection of user id's 0, 1 and 15, subsequently
3497 	 * inverted by -v.  15 is reserved for dladmd.  Yes, this is a
3498 	 * kludge-- a better policy is needed.
3499 	 *
3500 	 * Note that fork_with_timeout will only wait out the 1 second
3501 	 * "grace time" if pkill actually returns 0.  So if there are
3502 	 * no matches, this will run to completion much more quickly.
3503 	 */
3504 	(void) fork_with_timeout("/usr/bin/pkill -TERM -v -u 0,1,15", 1, 5);
3505 	(void) fork_with_timeout("/usr/bin/pkill -KILL -v -u 0,1,15", 1, 5);
3506 }
3507 
3508 static void
3509 do_uadmin(void)
3510 {
3511 	const char * const resetting = "/etc/svc/volatile/resetting";
3512 	int fd;
3513 	struct statvfs vfs;
3514 	time_t now;
3515 	struct tm nowtm;
3516 	char down_buf[256], time_buf[256];
3517 	uintptr_t mdep;
3518 #if defined(__i386)
3519 	grub_boot_args_t fbarg;
3520 #endif	/* __i386 */
3521 
3522 	mdep = NULL;
3523 	fd = creat(resetting, 0777);
3524 	if (fd >= 0)
3525 		startd_close(fd);
3526 	else
3527 		uu_warn("Could not create \"%s\"", resetting);
3528 
3529 	/* Kill dhcpagent if we're not using nfs for root */
3530 	if ((statvfs("/", &vfs) == 0) &&
3531 	    (strncmp(vfs.f_basetype, "nfs", sizeof ("nfs") - 1) != 0))
3532 		fork_with_timeout("/usr/bin/pkill -x -u 0 dhcpagent", 0, 5);
3533 
3534 	/*
3535 	 * Call sync(2) now, before we kill off user processes.  This takes
3536 	 * advantage of the several seconds of pause we have before the
3537 	 * killalls are done.  Time we can make good use of to get pages
3538 	 * moving out to disk.
3539 	 *
3540 	 * Inside non-global zones, we don't bother, and it's better not to
3541 	 * anyway, since sync(2) can have system-wide impact.
3542 	 */
3543 	if (getzoneid() == 0)
3544 		sync();
3545 
3546 	kill_user_procs();
3547 
3548 	/*
3549 	 * Note that this must come after the killing of user procs, since
3550 	 * killall relies on utmpx, and this command affects the contents of
3551 	 * said file.
3552 	 */
3553 	if (access("/usr/lib/acct/closewtmp", X_OK) == 0)
3554 		fork_with_timeout("/usr/lib/acct/closewtmp", 0, 5);
3555 
3556 	/*
3557 	 * For patches which may be installed as the system is shutting
3558 	 * down, we need to ensure, one more time, that the boot archive
3559 	 * really is up to date.
3560 	 */
3561 	if (getzoneid() == 0 && access("/usr/sbin/bootadm", X_OK) == 0)
3562 		fork_with_timeout("/usr/sbin/bootadm -ea update_all", 0, 3600);
3563 
3564 	/*
3565 	 * Right now, fast reboot is supported only on i386.
3566 	 * scf_is_fastboot_default() should take care of it.
3567 	 * If somehow we got there on unsupported platform -
3568 	 * print warning and fall back to regular reboot.
3569 	 */
3570 	if (halting == AD_FASTREBOOT) {
3571 #if defined(__i386)
3572 		int rc;
3573 
3574 		if ((rc = grub_get_boot_args(&fbarg, NULL,
3575 		    GRUB_ENTRY_DEFAULT)) == 0) {
3576 			mdep = (uintptr_t)&fbarg.gba_bootargs;
3577 		} else {
3578 			/*
3579 			 * Failed to read GRUB menu, fall back to normal reboot
3580 			 */
3581 			halting = AD_BOOT;
3582 			uu_warn("Failed to process GRUB menu entry "
3583 			    "for fast reboot.\n\t%s\n"
3584 			    "Falling back to regular reboot.\n",
3585 			    grub_strerror(rc));
3586 		}
3587 #else	/* __i386 */
3588 		halting = AD_BOOT;
3589 		uu_warn("Fast reboot configured, but not supported by "
3590 		    "this ISA\n");
3591 #endif	/* __i386 */
3592 	}
3593 
3594 	fork_with_timeout("/sbin/umountall -l", 0, 5);
3595 	fork_with_timeout("/sbin/umount /tmp /var/adm /var/run /var "
3596 	    ">/dev/null 2>&1", 0, 5);
3597 
3598 	/*
3599 	 * Try to get to consistency for whatever UFS filesystems are left.
3600 	 * This is pretty expensive, so we save it for the end in the hopes of
3601 	 * minimizing what it must do.  The other option would be to start in
3602 	 * parallel with the killall's, but lockfs tends to throw out much more
3603 	 * than is needed, and so subsequent commands (like umountall) take a
3604 	 * long time to get going again.
3605 	 *
3606 	 * Inside of zones, we don't bother, since we're not about to terminate
3607 	 * the whole OS instance.
3608 	 *
3609 	 * On systems using only ZFS, this call to lockfs -fa is a no-op.
3610 	 */
3611 	if (getzoneid() == 0) {
3612 		if (access("/usr/sbin/lockfs", X_OK) == 0)
3613 			fork_with_timeout("/usr/sbin/lockfs -fa", 0, 30);
3614 
3615 		sync();	/* once more, with feeling */
3616 	}
3617 
3618 	fork_with_timeout("/sbin/umount /usr >/dev/null 2>&1", 0, 5);
3619 
3620 	/*
3621 	 * Construct and emit the last words from userland:
3622 	 * "<timestamp> The system is down.  Shutdown took <N> seconds."
3623 	 *
3624 	 * Normally we'd use syslog, but with /var and other things
3625 	 * potentially gone, try to minimize the external dependencies.
3626 	 */
3627 	now = time(NULL);
3628 	(void) localtime_r(&now, &nowtm);
3629 
3630 	if (strftime(down_buf, sizeof (down_buf),
3631 	    "%b %e %T The system is down.", &nowtm) == 0) {
3632 		(void) strlcpy(down_buf, "The system is down.",
3633 		    sizeof (down_buf));
3634 	}
3635 
3636 	if (halting_time != 0 && halting_time <= now) {
3637 		(void) snprintf(time_buf, sizeof (time_buf),
3638 		    "  Shutdown took %lu seconds.", now - halting_time);
3639 	} else {
3640 		time_buf[0] = '\0';
3641 	}
3642 	(void) printf("%s%s\n", down_buf, time_buf);
3643 
3644 	(void) uadmin(A_SHUTDOWN, halting, mdep);
3645 	uu_warn("uadmin() failed");
3646 
3647 #if defined(__i386)
3648 	/* uadmin fail, cleanup grub_boot_args */
3649 	if (halting == AD_FASTREBOOT)
3650 		grub_cleanup_boot_args(&fbarg);
3651 #endif	/* __i386 */
3652 
3653 	if (remove(resetting) != 0 && errno != ENOENT)
3654 		uu_warn("Could not remove \"%s\"", resetting);
3655 }
3656 
3657 /*
3658  * If any of the up_svcs[] are online or satisfiable, return true.  If they are
3659  * all missing, disabled, in maintenance, or unsatisfiable, return false.
3660  */
3661 boolean_t
3662 can_come_up(void)
3663 {
3664 	int i;
3665 
3666 	assert(MUTEX_HELD(&dgraph_lock));
3667 
3668 	/*
3669 	 * If we are booting to single user (boot -s),
3670 	 * SCF_MILESTONE_SINGLE_USER is needed to come up because startd
3671 	 * spawns sulogin after single-user is online (see specials.c).
3672 	 */
3673 	i = (booting_to_single_user ? 0 : 1);
3674 
3675 	for (; up_svcs[i] != NULL; ++i) {
3676 		if (up_svcs_p[i] == NULL) {
3677 			up_svcs_p[i] = vertex_get_by_name(up_svcs[i]);
3678 
3679 			if (up_svcs_p[i] == NULL)
3680 				continue;
3681 		}
3682 
3683 		/*
3684 		 * Ignore unconfigured services (the ones that have been
3685 		 * mentioned in a dependency from other services, but do
3686 		 * not exist in the repository).  Services which exist
3687 		 * in the repository but don't have general/enabled
3688 		 * property will be also ignored.
3689 		 */
3690 		if (!(up_svcs_p[i]->gv_flags & GV_CONFIGURED))
3691 			continue;
3692 
3693 		switch (up_svcs_p[i]->gv_state) {
3694 		case RESTARTER_STATE_ONLINE:
3695 		case RESTARTER_STATE_DEGRADED:
3696 			/*
3697 			 * Deactivate verbose boot once a login service has been
3698 			 * reached.
3699 			 */
3700 			st->st_log_login_reached = 1;
3701 			/*FALLTHROUGH*/
3702 		case RESTARTER_STATE_UNINIT:
3703 			return (B_TRUE);
3704 
3705 		case RESTARTER_STATE_OFFLINE:
3706 			if (instance_satisfied(up_svcs_p[i], B_TRUE) != -1)
3707 				return (B_TRUE);
3708 			log_framework(LOG_DEBUG,
3709 			    "can_come_up(): %s is unsatisfiable.\n",
3710 			    up_svcs_p[i]->gv_name);
3711 			continue;
3712 
3713 		case RESTARTER_STATE_DISABLED:
3714 		case RESTARTER_STATE_MAINT:
3715 			log_framework(LOG_DEBUG,
3716 			    "can_come_up(): %s is in state %s.\n",
3717 			    up_svcs_p[i]->gv_name,
3718 			    instance_state_str[up_svcs_p[i]->gv_state]);
3719 			continue;
3720 
3721 		default:
3722 #ifndef NDEBUG
3723 			uu_warn("%s:%d: Unexpected vertex state %d.\n",
3724 			    __FILE__, __LINE__, up_svcs_p[i]->gv_state);
3725 #endif
3726 			abort();
3727 		}
3728 	}
3729 
3730 	/*
3731 	 * In the seed repository, console-login is unsatisfiable because
3732 	 * services are missing.  To behave correctly in that case we don't want
3733 	 * to return false until manifest-import is online.
3734 	 */
3735 
3736 	if (manifest_import_p == NULL) {
3737 		manifest_import_p = vertex_get_by_name(manifest_import);
3738 
3739 		if (manifest_import_p == NULL)
3740 			return (B_FALSE);
3741 	}
3742 
3743 	switch (manifest_import_p->gv_state) {
3744 	case RESTARTER_STATE_ONLINE:
3745 	case RESTARTER_STATE_DEGRADED:
3746 	case RESTARTER_STATE_DISABLED:
3747 	case RESTARTER_STATE_MAINT:
3748 		break;
3749 
3750 	case RESTARTER_STATE_OFFLINE:
3751 		if (instance_satisfied(manifest_import_p, B_TRUE) == -1)
3752 			break;
3753 		/* FALLTHROUGH */
3754 
3755 	case RESTARTER_STATE_UNINIT:
3756 		return (B_TRUE);
3757 	}
3758 
3759 	return (B_FALSE);
3760 }
3761 
3762 /*
3763  * Runs sulogin.  Returns
3764  *   0 - success
3765  *   EALREADY - sulogin is already running
3766  *   EBUSY - console-login is running
3767  */
3768 static int
3769 run_sulogin(const char *msg)
3770 {
3771 	graph_vertex_t *v;
3772 
3773 	assert(MUTEX_HELD(&dgraph_lock));
3774 
3775 	if (sulogin_running)
3776 		return (EALREADY);
3777 
3778 	v = vertex_get_by_name(console_login_fmri);
3779 	if (v != NULL && inst_running(v))
3780 		return (EBUSY);
3781 
3782 	sulogin_running = B_TRUE;
3783 
3784 	MUTEX_UNLOCK(&dgraph_lock);
3785 
3786 	fork_sulogin(B_FALSE, msg);
3787 
3788 	MUTEX_LOCK(&dgraph_lock);
3789 
3790 	sulogin_running = B_FALSE;
3791 
3792 	if (console_login_ready) {
3793 		v = vertex_get_by_name(console_login_fmri);
3794 
3795 		if (v != NULL && v->gv_state == RESTARTER_STATE_OFFLINE) {
3796 			if (v->gv_start_f == NULL)
3797 				vertex_send_event(v,
3798 				    RESTARTER_EVENT_TYPE_START);
3799 			else
3800 				v->gv_start_f(v);
3801 		}
3802 
3803 		console_login_ready = B_FALSE;
3804 	}
3805 
3806 	return (0);
3807 }
3808 
3809 /*
3810  * The sulogin thread runs sulogin while can_come_up() is false.  run_sulogin()
3811  * keeps sulogin from stepping on console-login's toes.
3812  */
3813 /* ARGSUSED */
3814 static void *
3815 sulogin_thread(void *unused)
3816 {
3817 	MUTEX_LOCK(&dgraph_lock);
3818 
3819 	assert(sulogin_thread_running);
3820 
3821 	do {
3822 		(void) run_sulogin("Console login service(s) cannot run\n");
3823 	} while (!can_come_up());
3824 
3825 	sulogin_thread_running = B_FALSE;
3826 	MUTEX_UNLOCK(&dgraph_lock);
3827 
3828 	return (NULL);
3829 }
3830 
3831 /* ARGSUSED */
3832 void *
3833 single_user_thread(void *unused)
3834 {
3835 	uint_t left;
3836 	scf_handle_t *h;
3837 	scf_instance_t *inst;
3838 	scf_property_t *prop;
3839 	scf_value_t *val;
3840 	const char *msg;
3841 	char *buf;
3842 	int r;
3843 
3844 	MUTEX_LOCK(&single_user_thread_lock);
3845 	single_user_thread_count++;
3846 
3847 	if (!booting_to_single_user)
3848 		kill_user_procs();
3849 
3850 	if (go_single_user_mode || booting_to_single_user) {
3851 		msg = "SINGLE USER MODE\n";
3852 	} else {
3853 		assert(go_to_level1);
3854 
3855 		fork_rc_script('1', "start", B_TRUE);
3856 
3857 		uu_warn("The system is ready for administration.\n");
3858 
3859 		msg = "";
3860 	}
3861 
3862 	MUTEX_UNLOCK(&single_user_thread_lock);
3863 
3864 	for (;;) {
3865 		MUTEX_LOCK(&dgraph_lock);
3866 		r = run_sulogin(msg);
3867 		MUTEX_UNLOCK(&dgraph_lock);
3868 		if (r == 0)
3869 			break;
3870 
3871 		assert(r == EALREADY || r == EBUSY);
3872 
3873 		left = 3;
3874 		while (left > 0)
3875 			left = sleep(left);
3876 	}
3877 
3878 	MUTEX_LOCK(&single_user_thread_lock);
3879 
3880 	/*
3881 	 * If another single user thread has started, let it finish changing
3882 	 * the run level.
3883 	 */
3884 	if (single_user_thread_count > 1) {
3885 		single_user_thread_count--;
3886 		MUTEX_UNLOCK(&single_user_thread_lock);
3887 		return (NULL);
3888 	}
3889 
3890 	h = libscf_handle_create_bound_loop();
3891 	inst = scf_instance_create(h);
3892 	prop = safe_scf_property_create(h);
3893 	val = safe_scf_value_create(h);
3894 	buf = startd_alloc(max_scf_fmri_size);
3895 
3896 lookup:
3897 	if (scf_handle_decode_fmri(h, SCF_SERVICE_STARTD, NULL, NULL, inst,
3898 	    NULL, NULL, SCF_DECODE_FMRI_EXACT) != 0) {
3899 		switch (scf_error()) {
3900 		case SCF_ERROR_NOT_FOUND:
3901 			r = libscf_create_self(h);
3902 			if (r == 0)
3903 				goto lookup;
3904 			assert(r == ECONNABORTED);
3905 			/* FALLTHROUGH */
3906 
3907 		case SCF_ERROR_CONNECTION_BROKEN:
3908 			libscf_handle_rebind(h);
3909 			goto lookup;
3910 
3911 		case SCF_ERROR_INVALID_ARGUMENT:
3912 		case SCF_ERROR_CONSTRAINT_VIOLATED:
3913 		case SCF_ERROR_NOT_BOUND:
3914 		case SCF_ERROR_HANDLE_MISMATCH:
3915 		default:
3916 			bad_error("scf_handle_decode_fmri", scf_error());
3917 		}
3918 	}
3919 
3920 	MUTEX_LOCK(&dgraph_lock);
3921 
3922 	r = scf_instance_delete_prop(inst, SCF_PG_OPTIONS_OVR,
3923 	    SCF_PROPERTY_MILESTONE);
3924 	switch (r) {
3925 	case 0:
3926 	case ECANCELED:
3927 		break;
3928 
3929 	case ECONNABORTED:
3930 		MUTEX_UNLOCK(&dgraph_lock);
3931 		libscf_handle_rebind(h);
3932 		goto lookup;
3933 
3934 	case EPERM:
3935 	case EACCES:
3936 	case EROFS:
3937 		log_error(LOG_WARNING, "Could not clear temporary milestone: "
3938 		    "%s.\n", strerror(r));
3939 		break;
3940 
3941 	default:
3942 		bad_error("scf_instance_delete_prop", r);
3943 	}
3944 
3945 	MUTEX_UNLOCK(&dgraph_lock);
3946 
3947 	r = libscf_get_milestone(inst, prop, val, buf, max_scf_fmri_size);
3948 	switch (r) {
3949 	case ECANCELED:
3950 	case ENOENT:
3951 	case EINVAL:
3952 		(void) strcpy(buf, "all");
3953 		/* FALLTHROUGH */
3954 
3955 	case 0:
3956 		uu_warn("Returning to milestone %s.\n", buf);
3957 		break;
3958 
3959 	case ECONNABORTED:
3960 		libscf_handle_rebind(h);
3961 		goto lookup;
3962 
3963 	default:
3964 		bad_error("libscf_get_milestone", r);
3965 	}
3966 
3967 	r = dgraph_set_milestone(buf, h, B_FALSE);
3968 	switch (r) {
3969 	case 0:
3970 	case ECONNRESET:
3971 	case EALREADY:
3972 	case EINVAL:
3973 	case ENOENT:
3974 		break;
3975 
3976 	default:
3977 		bad_error("dgraph_set_milestone", r);
3978 	}
3979 
3980 	/*
3981 	 * See graph_runlevel_changed().
3982 	 */
3983 	MUTEX_LOCK(&dgraph_lock);
3984 	utmpx_set_runlevel(target_milestone_as_runlevel(), 'S', B_TRUE);
3985 	MUTEX_UNLOCK(&dgraph_lock);
3986 
3987 	startd_free(buf, max_scf_fmri_size);
3988 	scf_value_destroy(val);
3989 	scf_property_destroy(prop);
3990 	scf_instance_destroy(inst);
3991 	scf_handle_destroy(h);
3992 
3993 	/*
3994 	 * We'll give ourselves 3 seconds to respond to all of the enablings
3995 	 * that setting the milestone should have created before checking
3996 	 * whether to run sulogin.
3997 	 */
3998 	left = 3;
3999 	while (left > 0)
4000 		left = sleep(left);
4001 
4002 	MUTEX_LOCK(&dgraph_lock);
4003 	/*
4004 	 * Clearing these variables will allow the sulogin thread to run.  We
4005 	 * check here in case there aren't any more state updates anytime soon.
4006 	 */
4007 	go_to_level1 = go_single_user_mode = booting_to_single_user = B_FALSE;
4008 	if (!sulogin_thread_running && !can_come_up()) {
4009 		(void) startd_thread_create(sulogin_thread, NULL);
4010 		sulogin_thread_running = B_TRUE;
4011 	}
4012 	MUTEX_UNLOCK(&dgraph_lock);
4013 	single_user_thread_count--;
4014 	MUTEX_UNLOCK(&single_user_thread_lock);
4015 	return (NULL);
4016 }
4017 
4018 
4019 /*
4020  * Dependency graph operations API.  These are handle-independent thread-safe
4021  * graph manipulation functions which are the entry points for the event
4022  * threads below.
4023  */
4024 
4025 /*
4026  * If a configured vertex exists for inst_fmri, return EEXIST.  If no vertex
4027  * exists for inst_fmri, add one.  Then fetch the restarter from inst, make
4028  * this vertex dependent on it, and send _ADD_INSTANCE to the restarter.
4029  * Fetch whether the instance should be enabled from inst and send _ENABLE or
4030  * _DISABLE as appropriate.  Finally rummage through inst's dependency
4031  * property groups and add vertices and edges as appropriate.  If anything
4032  * goes wrong after sending _ADD_INSTANCE, send _ADMIN_MAINT_ON to put the
4033  * instance in maintenance.  Don't send _START or _STOP until we get a state
4034  * update in case we're being restarted and the service is already running.
4035  *
4036  * To support booting to a milestone, we must also make sure all dependencies
4037  * encountered are configured, if they exist in the repository.
4038  *
4039  * Returns 0 on success, ECONNABORTED on repository disconnection, EINVAL if
4040  * inst_fmri is an invalid (or not canonical) FMRI, ECANCELED if inst is
4041  * deleted, or EEXIST if a configured vertex for inst_fmri already exists.
4042  */
4043 int
4044 dgraph_add_instance(const char *inst_fmri, scf_instance_t *inst,
4045     boolean_t lock_graph)
4046 {
4047 	graph_vertex_t *v;
4048 	int err;
4049 
4050 	if (strcmp(inst_fmri, SCF_SERVICE_STARTD) == 0)
4051 		return (0);
4052 
4053 	/* Check for a vertex for inst_fmri. */
4054 	if (lock_graph) {
4055 		MUTEX_LOCK(&dgraph_lock);
4056 	} else {
4057 		assert(MUTEX_HELD(&dgraph_lock));
4058 	}
4059 
4060 	v = vertex_get_by_name(inst_fmri);
4061 
4062 	if (v != NULL) {
4063 		assert(v->gv_type == GVT_INST);
4064 
4065 		if (v->gv_flags & GV_CONFIGURED) {
4066 			if (lock_graph)
4067 				MUTEX_UNLOCK(&dgraph_lock);
4068 			return (EEXIST);
4069 		}
4070 	} else {
4071 		/* Add the vertex. */
4072 		err = graph_insert_vertex_unconfigured(inst_fmri, GVT_INST, 0,
4073 		    RERR_NONE, &v);
4074 		if (err != 0) {
4075 			assert(err == EINVAL);
4076 			if (lock_graph)
4077 				MUTEX_UNLOCK(&dgraph_lock);
4078 			return (EINVAL);
4079 		}
4080 	}
4081 
4082 	err = configure_vertex(v, inst);
4083 
4084 	if (lock_graph)
4085 		MUTEX_UNLOCK(&dgraph_lock);
4086 
4087 	return (err);
4088 }
4089 
4090 /*
4091  * Locate the vertex for this property group's instance.  If it doesn't exist
4092  * or is unconfigured, call dgraph_add_instance() & return.  Otherwise fetch
4093  * the restarter for the instance, and if it has changed, send
4094  * _REMOVE_INSTANCE to the old restarter, remove the dependency, make sure the
4095  * new restarter has a vertex, add a new dependency, and send _ADD_INSTANCE to
4096  * the new restarter.  Then fetch whether the instance should be enabled, and
4097  * if it is different from what we had, or if we changed the restarter, send
4098  * the appropriate _ENABLE or _DISABLE command.
4099  *
4100  * Returns 0 on success, ENOTSUP if the pg's parent is not an instance,
4101  * ECONNABORTED on repository disconnection, ECANCELED if the instance is
4102  * deleted, or -1 if the instance's general property group is deleted or if
4103  * its enabled property is misconfigured.
4104  */
4105 static int
4106 dgraph_update_general(scf_propertygroup_t *pg)
4107 {
4108 	scf_handle_t *h;
4109 	scf_instance_t *inst;
4110 	char *fmri;
4111 	char *restarter_fmri;
4112 	graph_vertex_t *v;
4113 	int err;
4114 	int enabled, enabled_ovr;
4115 	int oldflags;
4116 
4117 	/* Find the vertex for this service */
4118 	h = scf_pg_handle(pg);
4119 
4120 	inst = safe_scf_instance_create(h);
4121 
4122 	if (scf_pg_get_parent_instance(pg, inst) != 0) {
4123 		switch (scf_error()) {
4124 		case SCF_ERROR_CONSTRAINT_VIOLATED:
4125 			return (ENOTSUP);
4126 
4127 		case SCF_ERROR_CONNECTION_BROKEN:
4128 		default:
4129 			return (ECONNABORTED);
4130 
4131 		case SCF_ERROR_DELETED:
4132 			return (0);
4133 
4134 		case SCF_ERROR_NOT_SET:
4135 			bad_error("scf_pg_get_parent_instance", scf_error());
4136 		}
4137 	}
4138 
4139 	err = libscf_instance_get_fmri(inst, &fmri);
4140 	switch (err) {
4141 	case 0:
4142 		break;
4143 
4144 	case ECONNABORTED:
4145 		scf_instance_destroy(inst);
4146 		return (ECONNABORTED);
4147 
4148 	case ECANCELED:
4149 		scf_instance_destroy(inst);
4150 		return (0);
4151 
4152 	default:
4153 		bad_error("libscf_instance_get_fmri", err);
4154 	}
4155 
4156 	log_framework(LOG_DEBUG,
4157 	    "Graph engine: Reloading general properties for %s.\n", fmri);
4158 
4159 	MUTEX_LOCK(&dgraph_lock);
4160 
4161 	v = vertex_get_by_name(fmri);
4162 	if (v == NULL || !(v->gv_flags & GV_CONFIGURED)) {
4163 		/* Will get the up-to-date properties. */
4164 		MUTEX_UNLOCK(&dgraph_lock);
4165 		err = dgraph_add_instance(fmri, inst, B_TRUE);
4166 		startd_free(fmri, max_scf_fmri_size);
4167 		scf_instance_destroy(inst);
4168 		return (err == ECANCELED ? 0 : err);
4169 	}
4170 
4171 	/* Read enabled & restarter from repository. */
4172 	restarter_fmri = startd_alloc(max_scf_value_size);
4173 	err = libscf_get_basic_instance_data(h, inst, v->gv_name, &enabled,
4174 	    &enabled_ovr, &restarter_fmri);
4175 	if (err != 0 || enabled == -1) {
4176 		MUTEX_UNLOCK(&dgraph_lock);
4177 		scf_instance_destroy(inst);
4178 		startd_free(fmri, max_scf_fmri_size);
4179 
4180 		switch (err) {
4181 		case ENOENT:
4182 		case 0:
4183 			startd_free(restarter_fmri, max_scf_value_size);
4184 			return (-1);
4185 
4186 		case ECONNABORTED:
4187 		case ECANCELED:
4188 			startd_free(restarter_fmri, max_scf_value_size);
4189 			return (err);
4190 
4191 		default:
4192 			bad_error("libscf_get_basic_instance_data", err);
4193 		}
4194 	}
4195 
4196 	oldflags = v->gv_flags;
4197 	v->gv_flags = (v->gv_flags & ~GV_ENBLD_NOOVR) |
4198 	    (enabled ? GV_ENBLD_NOOVR : 0);
4199 
4200 	if (enabled_ovr != -1)
4201 		enabled = enabled_ovr;
4202 
4203 	/*
4204 	 * If GV_ENBLD_NOOVR has changed, then we need to re-evaluate the
4205 	 * subgraph.
4206 	 */
4207 	if (milestone > MILESTONE_NONE && v->gv_flags != oldflags)
4208 		(void) eval_subgraph(v, h);
4209 
4210 	scf_instance_destroy(inst);
4211 
4212 	/* Ignore restarter change for now. */
4213 
4214 	startd_free(restarter_fmri, max_scf_value_size);
4215 	startd_free(fmri, max_scf_fmri_size);
4216 
4217 	/*
4218 	 * Always send _ENABLE or _DISABLE.  We could avoid this if the
4219 	 * restarter didn't change and the enabled value didn't change, but
4220 	 * that's not easy to check and improbable anyway, so we'll just do
4221 	 * this.
4222 	 */
4223 	graph_enable_by_vertex(v, enabled, 1);
4224 
4225 	MUTEX_UNLOCK(&dgraph_lock);
4226 
4227 	return (0);
4228 }
4229 
4230 /*
4231  * Delete all of the property group dependencies of v, update inst's running
4232  * snapshot, and add the dependencies in the new snapshot.  If any of the new
4233  * dependencies would create a cycle, send _ADMIN_MAINT_ON.  Otherwise
4234  * reevaluate v's dependencies, send _START or _STOP as appropriate, and do
4235  * the same for v's dependents.
4236  *
4237  * Returns
4238  *   0 - success
4239  *   ECONNABORTED - repository connection broken
4240  *   ECANCELED - inst was deleted
4241  *   EINVAL - inst is invalid (e.g., missing general/enabled)
4242  *   -1 - libscf_snapshots_refresh() failed
4243  */
4244 static int
4245 dgraph_refresh_instance(graph_vertex_t *v, scf_instance_t *inst)
4246 {
4247 	int r;
4248 	int enabled;
4249 
4250 	assert(MUTEX_HELD(&dgraph_lock));
4251 	assert(v->gv_type == GVT_INST);
4252 
4253 	/* Only refresh services with valid general/enabled properties. */
4254 	r = libscf_get_basic_instance_data(scf_instance_handle(inst), inst,
4255 	    v->gv_name, &enabled, NULL, NULL);
4256 	switch (r) {
4257 	case 0:
4258 		break;
4259 
4260 	case ECONNABORTED:
4261 	case ECANCELED:
4262 		return (r);
4263 
4264 	case ENOENT:
4265 		log_framework(LOG_DEBUG,
4266 		    "Ignoring %s because it has no general property group.\n",
4267 		    v->gv_name);
4268 		return (EINVAL);
4269 
4270 	default:
4271 		bad_error("libscf_get_basic_instance_data", r);
4272 	}
4273 
4274 	if (enabled == -1)
4275 		return (EINVAL);
4276 
4277 	r = libscf_snapshots_refresh(inst, v->gv_name);
4278 	if (r != 0) {
4279 		if (r != -1)
4280 			bad_error("libscf_snapshots_refresh", r);
4281 
4282 		/* error logged */
4283 		return (r);
4284 	}
4285 
4286 	r = refresh_vertex(v, inst);
4287 	if (r != 0 && r != ECONNABORTED)
4288 		bad_error("refresh_vertex", r);
4289 	return (r);
4290 }
4291 
4292 /*
4293  * Returns true only if none of this service's dependents are 'up' -- online
4294  * or degraded (offline is considered down in this situation). This function
4295  * is somehow similar to is_nonsubgraph_leaf() but works on subtrees.
4296  */
4297 static boolean_t
4298 insubtree_dependents_down(graph_vertex_t *v)
4299 {
4300 	graph_vertex_t *vv;
4301 	graph_edge_t *e;
4302 
4303 	assert(MUTEX_HELD(&dgraph_lock));
4304 
4305 	for (e = uu_list_first(v->gv_dependents); e != NULL;
4306 	    e = uu_list_next(v->gv_dependents, e)) {
4307 		vv = e->ge_vertex;
4308 		if (vv->gv_type == GVT_INST) {
4309 			if ((vv->gv_flags & GV_CONFIGURED) == 0)
4310 				continue;
4311 
4312 			if ((vv->gv_flags & GV_TOOFFLINE) == 0)
4313 				continue;
4314 
4315 			if ((vv->gv_state == RESTARTER_STATE_ONLINE) ||
4316 			    (vv->gv_state == RESTARTER_STATE_DEGRADED))
4317 				return (B_FALSE);
4318 		} else {
4319 			/*
4320 			 * Skip all excluded and optional_all dependencies
4321 			 * and decide whether to offline the service based
4322 			 * on restart_on attribute.
4323 			 */
4324 			if (is_depgrp_bypassed(vv))
4325 				continue;
4326 
4327 			/*
4328 			 * For dependency groups or service vertices, keep
4329 			 * traversing to see if instances are running.
4330 			 */
4331 			if (insubtree_dependents_down(vv) == B_FALSE)
4332 				return (B_FALSE);
4333 		}
4334 	}
4335 
4336 	return (B_TRUE);
4337 }
4338 
4339 /*
4340  * Returns true only if none of this service's dependents are 'up' -- online,
4341  * degraded, or offline.
4342  */
4343 static int
4344 is_nonsubgraph_leaf(graph_vertex_t *v)
4345 {
4346 	graph_vertex_t *vv;
4347 	graph_edge_t *e;
4348 
4349 	assert(MUTEX_HELD(&dgraph_lock));
4350 
4351 	for (e = uu_list_first(v->gv_dependents);
4352 	    e != NULL;
4353 	    e = uu_list_next(v->gv_dependents, e)) {
4354 
4355 		vv = e->ge_vertex;
4356 		if (vv->gv_type == GVT_INST) {
4357 			if ((vv->gv_flags & GV_CONFIGURED) == 0)
4358 				continue;
4359 
4360 			if (vv->gv_flags & GV_INSUBGRAPH)
4361 				continue;
4362 
4363 			if (up_state(vv->gv_state))
4364 				return (0);
4365 		} else {
4366 			/*
4367 			 * For dependency group or service vertices, keep
4368 			 * traversing to see if instances are running.
4369 			 *
4370 			 * We should skip exclude_all dependencies otherwise
4371 			 * the vertex will never be considered as a leaf
4372 			 * if the dependent is offline. The main reason for
4373 			 * this is that disable_nonsubgraph_leaves() skips
4374 			 * exclusion dependencies.
4375 			 */
4376 			if (vv->gv_type == GVT_GROUP &&
4377 			    vv->gv_depgroup == DEPGRP_EXCLUDE_ALL)
4378 				continue;
4379 
4380 			if (!is_nonsubgraph_leaf(vv))
4381 				return (0);
4382 		}
4383 	}
4384 
4385 	return (1);
4386 }
4387 
4388 /*
4389  * Disable v temporarily.  Attempt to do this by setting its enabled override
4390  * property in the repository.  If that fails, send a _DISABLE command.
4391  * Returns 0 on success and ECONNABORTED if the repository connection is
4392  * broken.
4393  */
4394 static int
4395 disable_service_temporarily(graph_vertex_t *v, scf_handle_t *h)
4396 {
4397 	const char * const emsg = "Could not temporarily disable %s because "
4398 	    "%s.  Will stop service anyways.  Repository status for the "
4399 	    "service may be inaccurate.\n";
4400 	const char * const emsg_cbroken =
4401 	    "the repository connection was broken";
4402 
4403 	scf_instance_t *inst;
4404 	int r;
4405 
4406 	inst = scf_instance_create(h);
4407 	if (inst == NULL) {
4408 		char buf[100];
4409 
4410 		(void) snprintf(buf, sizeof (buf),
4411 		    "scf_instance_create() failed (%s)",
4412 		    scf_strerror(scf_error()));
4413 		log_error(LOG_WARNING, emsg, v->gv_name, buf);
4414 
4415 		graph_enable_by_vertex(v, 0, 0);
4416 		return (0);
4417 	}
4418 
4419 	r = scf_handle_decode_fmri(h, v->gv_name, NULL, NULL, inst,
4420 	    NULL, NULL, SCF_DECODE_FMRI_EXACT);
4421 	if (r != 0) {
4422 		switch (scf_error()) {
4423 		case SCF_ERROR_CONNECTION_BROKEN:
4424 			log_error(LOG_WARNING, emsg, v->gv_name, emsg_cbroken);
4425 			graph_enable_by_vertex(v, 0, 0);
4426 			return (ECONNABORTED);
4427 
4428 		case SCF_ERROR_NOT_FOUND:
4429 			return (0);
4430 
4431 		case SCF_ERROR_HANDLE_MISMATCH:
4432 		case SCF_ERROR_INVALID_ARGUMENT:
4433 		case SCF_ERROR_CONSTRAINT_VIOLATED:
4434 		case SCF_ERROR_NOT_BOUND:
4435 		default:
4436 			bad_error("scf_handle_decode_fmri",
4437 			    scf_error());
4438 		}
4439 	}
4440 
4441 	r = libscf_set_enable_ovr(inst, 0);
4442 	switch (r) {
4443 	case 0:
4444 		scf_instance_destroy(inst);
4445 		return (0);
4446 
4447 	case ECANCELED:
4448 		scf_instance_destroy(inst);
4449 		return (0);
4450 
4451 	case ECONNABORTED:
4452 		log_error(LOG_WARNING, emsg, v->gv_name, emsg_cbroken);
4453 		graph_enable_by_vertex(v, 0, 0);
4454 		return (ECONNABORTED);
4455 
4456 	case EPERM:
4457 		log_error(LOG_WARNING, emsg, v->gv_name,
4458 		    "the repository denied permission");
4459 		graph_enable_by_vertex(v, 0, 0);
4460 		return (0);
4461 
4462 	case EROFS:
4463 		log_error(LOG_WARNING, emsg, v->gv_name,
4464 		    "the repository is read-only");
4465 		graph_enable_by_vertex(v, 0, 0);
4466 		return (0);
4467 
4468 	default:
4469 		bad_error("libscf_set_enable_ovr", r);
4470 		/* NOTREACHED */
4471 	}
4472 }
4473 
4474 /*
4475  * Of the transitive instance dependencies of v, offline those which are
4476  * in the subtree and which are leaves (i.e., have no dependents which are
4477  * "up").
4478  */
4479 void
4480 offline_subtree_leaves(graph_vertex_t *v, void *arg)
4481 {
4482 	assert(MUTEX_HELD(&dgraph_lock));
4483 
4484 	/* If v isn't an instance, recurse on its dependencies. */
4485 	if (v->gv_type != GVT_INST) {
4486 		graph_walk_dependencies(v, offline_subtree_leaves, arg);
4487 		return;
4488 	}
4489 
4490 	/*
4491 	 * If v is not in the subtree, so should all of its dependencies,
4492 	 * so do nothing.
4493 	 */
4494 	if ((v->gv_flags & GV_TOOFFLINE) == 0)
4495 		return;
4496 
4497 	/* If v isn't a leaf because it's already down, recurse. */
4498 	if (!up_state(v->gv_state)) {
4499 		graph_walk_dependencies(v, offline_subtree_leaves, arg);
4500 		return;
4501 	}
4502 
4503 	/* if v is a leaf, offline it or disable it if it's the last one */
4504 	if (insubtree_dependents_down(v) == B_TRUE) {
4505 		if (v->gv_flags & GV_TODISABLE)
4506 			vertex_send_event(v,
4507 			    RESTARTER_EVENT_TYPE_ADMIN_DISABLE);
4508 		else
4509 			offline_vertex(v);
4510 	}
4511 }
4512 
4513 void
4514 graph_offline_subtree_leaves(graph_vertex_t *v, void *h)
4515 {
4516 	graph_walk_dependencies(v, offline_subtree_leaves, (void *)h);
4517 }
4518 
4519 
4520 /*
4521  * Of the transitive instance dependencies of v, disable those which are not
4522  * in the subgraph and which are leaves (i.e., have no dependents which are
4523  * "up").
4524  */
4525 static void
4526 disable_nonsubgraph_leaves(graph_vertex_t *v, void *arg)
4527 {
4528 	assert(MUTEX_HELD(&dgraph_lock));
4529 
4530 	/*
4531 	 * We must skip exclusion dependencies because they are allowed to
4532 	 * complete dependency cycles.  This is correct because A's exclusion
4533 	 * dependency on B doesn't bear on the order in which they should be
4534 	 * stopped.  Indeed, the exclusion dependency should guarantee that
4535 	 * they are never online at the same time.
4536 	 */
4537 	if (v->gv_type == GVT_GROUP && v->gv_depgroup == DEPGRP_EXCLUDE_ALL)
4538 		return;
4539 
4540 	/* If v isn't an instance, recurse on its dependencies. */
4541 	if (v->gv_type != GVT_INST)
4542 		goto recurse;
4543 
4544 	if ((v->gv_flags & GV_CONFIGURED) == 0)
4545 		/*
4546 		 * Unconfigured instances should have no dependencies, but in
4547 		 * case they ever get them,
4548 		 */
4549 		goto recurse;
4550 
4551 	/*
4552 	 * If v is in the subgraph, so should all of its dependencies, so do
4553 	 * nothing.
4554 	 */
4555 	if (v->gv_flags & GV_INSUBGRAPH)
4556 		return;
4557 
4558 	/* If v isn't a leaf because it's already down, recurse. */
4559 	if (!up_state(v->gv_state))
4560 		goto recurse;
4561 
4562 	/* If v is disabled but not down yet, be patient. */
4563 	if ((v->gv_flags & GV_ENABLED) == 0)
4564 		return;
4565 
4566 	/* If v is a leaf, disable it. */
4567 	if (is_nonsubgraph_leaf(v))
4568 		(void) disable_service_temporarily(v, (scf_handle_t *)arg);
4569 
4570 	return;
4571 
4572 recurse:
4573 	graph_walk_dependencies(v, disable_nonsubgraph_leaves, arg);
4574 }
4575 
4576 /*
4577  * Find the vertex for inst_name.  If it doesn't exist, return ENOENT.
4578  * Otherwise set its state to state.  If the instance has entered a state
4579  * which requires automatic action, take it (Uninitialized: do
4580  * dgraph_refresh_instance() without the snapshot update.  Disabled: if the
4581  * instance should be enabled, send _ENABLE.  Offline: if the instance should
4582  * be disabled, send _DISABLE, and if its dependencies are satisfied, send
4583  * _START.  Online, Degraded: if the instance wasn't running, update its start
4584  * snapshot.  Maintenance: no action.)
4585  *
4586  * Also fails with ECONNABORTED, or EINVAL if state is invalid.
4587  */
4588 static int
4589 dgraph_set_instance_state(scf_handle_t *h, const char *inst_name,
4590     restarter_instance_state_t state, restarter_error_t serr)
4591 {
4592 	graph_vertex_t *v;
4593 	int err = 0;
4594 	restarter_instance_state_t old_state;
4595 
4596 	MUTEX_LOCK(&dgraph_lock);
4597 
4598 	v = vertex_get_by_name(inst_name);
4599 	if (v == NULL) {
4600 		MUTEX_UNLOCK(&dgraph_lock);
4601 		return (ENOENT);
4602 	}
4603 
4604 	assert(v->gv_type == GVT_INST);
4605 
4606 	switch (state) {
4607 	case RESTARTER_STATE_UNINIT:
4608 	case RESTARTER_STATE_DISABLED:
4609 	case RESTARTER_STATE_OFFLINE:
4610 	case RESTARTER_STATE_ONLINE:
4611 	case RESTARTER_STATE_DEGRADED:
4612 	case RESTARTER_STATE_MAINT:
4613 		break;
4614 
4615 	default:
4616 		MUTEX_UNLOCK(&dgraph_lock);
4617 		return (EINVAL);
4618 	}
4619 
4620 	log_framework(LOG_DEBUG, "Graph noting %s %s -> %s.\n", v->gv_name,
4621 	    instance_state_str[v->gv_state], instance_state_str[state]);
4622 
4623 	old_state = v->gv_state;
4624 	v->gv_state = state;
4625 
4626 	err = gt_transition(h, v, serr, old_state);
4627 
4628 	MUTEX_UNLOCK(&dgraph_lock);
4629 	return (err);
4630 }
4631 
4632 /*
4633  * Handle state changes during milestone shutdown.  See
4634  * dgraph_set_milestone().  If the repository connection is broken,
4635  * ECONNABORTED will be returned, though a _DISABLE command will be sent for
4636  * the vertex anyway.
4637  */
4638 int
4639 vertex_subgraph_dependencies_shutdown(scf_handle_t *h, graph_vertex_t *v,
4640     restarter_instance_state_t old_state)
4641 {
4642 	int was_up, now_up;
4643 	int ret = 0;
4644 
4645 	assert(v->gv_type == GVT_INST);
4646 
4647 	/* Don't care if we're not going to a milestone. */
4648 	if (milestone == NULL)
4649 		return (0);
4650 
4651 	/* Don't care if we already finished coming down. */
4652 	if (non_subgraph_svcs == 0)
4653 		return (0);
4654 
4655 	/* Don't care if the service is in the subgraph. */
4656 	if (v->gv_flags & GV_INSUBGRAPH)
4657 		return (0);
4658 
4659 	/*
4660 	 * Update non_subgraph_svcs.  It is the number of non-subgraph
4661 	 * services which are in online, degraded, or offline.
4662 	 */
4663 
4664 	was_up = up_state(old_state);
4665 	now_up = up_state(v->gv_state);
4666 
4667 	if (!was_up && now_up) {
4668 		++non_subgraph_svcs;
4669 	} else if (was_up && !now_up) {
4670 		--non_subgraph_svcs;
4671 
4672 		if (non_subgraph_svcs == 0) {
4673 			if (halting != -1) {
4674 				do_uadmin();
4675 			} else if (go_single_user_mode || go_to_level1) {
4676 				(void) startd_thread_create(single_user_thread,
4677 				    NULL);
4678 			}
4679 			return (0);
4680 		}
4681 	}
4682 
4683 	/* If this service is a leaf, it should be disabled. */
4684 	if ((v->gv_flags & GV_ENABLED) && is_nonsubgraph_leaf(v)) {
4685 		int r;
4686 
4687 		r = disable_service_temporarily(v, h);
4688 		switch (r) {
4689 		case 0:
4690 			break;
4691 
4692 		case ECONNABORTED:
4693 			ret = ECONNABORTED;
4694 			break;
4695 
4696 		default:
4697 			bad_error("disable_service_temporarily", r);
4698 		}
4699 	}
4700 
4701 	/*
4702 	 * If the service just came down, propagate the disable to the newly
4703 	 * exposed leaves.
4704 	 */
4705 	if (was_up && !now_up)
4706 		graph_walk_dependencies(v, disable_nonsubgraph_leaves,
4707 		    (void *)h);
4708 
4709 	return (ret);
4710 }
4711 
4712 /*
4713  * Decide whether to start up an sulogin thread after a service is
4714  * finished changing state.  Only need to do the full can_come_up()
4715  * evaluation if an instance is changing state, we're not halfway through
4716  * loading the thread, and we aren't shutting down or going to the single
4717  * user milestone.
4718  */
4719 void
4720 graph_transition_sulogin(restarter_instance_state_t state,
4721     restarter_instance_state_t old_state)
4722 {
4723 	assert(MUTEX_HELD(&dgraph_lock));
4724 
4725 	if (state != old_state && st->st_load_complete &&
4726 	    !go_single_user_mode && !go_to_level1 &&
4727 	    halting == -1) {
4728 		if (!sulogin_thread_running && !can_come_up()) {
4729 			(void) startd_thread_create(sulogin_thread, NULL);
4730 			sulogin_thread_running = B_TRUE;
4731 		}
4732 	}
4733 }
4734 
4735 /*
4736  * Propagate a start, stop event, or a satisfiability event.
4737  *
4738  * PROPAGATE_START and PROPAGATE_STOP simply propagate the transition event
4739  * to direct dependents.  PROPAGATE_SAT propagates a start then walks the
4740  * full dependent graph to check for newly satisfied nodes.  This is
4741  * necessary for cases when non-direct dependents may be effected but direct
4742  * dependents may not (e.g. for optional_all evaluations, see the
4743  * propagate_satbility() comments).
4744  *
4745  * PROPAGATE_SAT should be used whenever a non-running service moves into
4746  * a state which can satisfy optional dependencies, like disabled or
4747  * maintenance.
4748  */
4749 void
4750 graph_transition_propagate(graph_vertex_t *v, propagate_event_t type,
4751     restarter_error_t rerr)
4752 {
4753 	if (type == PROPAGATE_STOP) {
4754 		graph_walk_dependents(v, propagate_stop, (void *)rerr);
4755 	} else if (type == PROPAGATE_START || type == PROPAGATE_SAT) {
4756 		graph_walk_dependents(v, propagate_start, NULL);
4757 
4758 		if (type == PROPAGATE_SAT)
4759 			propagate_satbility(v);
4760 	} else {
4761 #ifndef NDEBUG
4762 		uu_warn("%s:%d: Unexpected type value %d.\n",  __FILE__,
4763 		    __LINE__, type);
4764 #endif
4765 		abort();
4766 	}
4767 }
4768 
4769 /*
4770  * If a vertex for fmri exists and it is enabled, send _DISABLE to the
4771  * restarter.  If it is running, send _STOP.  Send _REMOVE_INSTANCE.  Delete
4772  * all property group dependencies, and the dependency on the restarter,
4773  * disposing of vertices as appropriate.  If other vertices depend on this
4774  * one, mark it unconfigured and return.  Otherwise remove the vertex.  Always
4775  * returns 0.
4776  */
4777 static int
4778 dgraph_remove_instance(const char *fmri, scf_handle_t *h)
4779 {
4780 	graph_vertex_t *v;
4781 	graph_edge_t *e;
4782 	uu_list_t *old_deps;
4783 	int err;
4784 
4785 	log_framework(LOG_DEBUG, "Graph engine: Removing %s.\n", fmri);
4786 
4787 	MUTEX_LOCK(&dgraph_lock);
4788 
4789 	v = vertex_get_by_name(fmri);
4790 	if (v == NULL) {
4791 		MUTEX_UNLOCK(&dgraph_lock);
4792 		return (0);
4793 	}
4794 
4795 	/* Send restarter delete event. */
4796 	if (v->gv_flags & GV_CONFIGURED)
4797 		graph_unset_restarter(v);
4798 
4799 	if (milestone > MILESTONE_NONE) {
4800 		/*
4801 		 * Make a list of v's current dependencies so we can
4802 		 * reevaluate their GV_INSUBGRAPH flags after the dependencies
4803 		 * are removed.
4804 		 */
4805 		old_deps = startd_list_create(graph_edge_pool, NULL, 0);
4806 
4807 		err = uu_list_walk(v->gv_dependencies,
4808 		    (uu_walk_fn_t *)append_svcs_or_insts, old_deps, 0);
4809 		assert(err == 0);
4810 	}
4811 
4812 	delete_instance_dependencies(v, B_TRUE);
4813 
4814 	/*
4815 	 * Deleting an instance can both satisfy and unsatisfy dependencies,
4816 	 * depending on their type.  First propagate the stop as a RERR_RESTART
4817 	 * event -- deletion isn't a fault, just a normal stop.  This gives
4818 	 * dependent services the chance to do a clean shutdown.  Then, mark
4819 	 * the service as unconfigured and propagate the start event for the
4820 	 * optional_all dependencies that might have become satisfied.
4821 	 */
4822 	graph_walk_dependents(v, propagate_stop, (void *)RERR_RESTART);
4823 
4824 	v->gv_flags &= ~GV_CONFIGURED;
4825 	v->gv_flags &= ~GV_DEATHROW;
4826 
4827 	graph_walk_dependents(v, propagate_start, NULL);
4828 	propagate_satbility(v);
4829 
4830 	/*
4831 	 * If there are no (non-service) dependents, the vertex can be
4832 	 * completely removed.
4833 	 */
4834 	if (v != milestone && v->gv_refs == 0 &&
4835 	    uu_list_numnodes(v->gv_dependents) == 1)
4836 		remove_inst_vertex(v);
4837 
4838 	if (milestone > MILESTONE_NONE) {
4839 		void *cookie = NULL;
4840 
4841 		while ((e = uu_list_teardown(old_deps, &cookie)) != NULL) {
4842 			v = e->ge_vertex;
4843 
4844 			if (vertex_unref(v) == VERTEX_INUSE)
4845 				while (eval_subgraph(v, h) == ECONNABORTED)
4846 					libscf_handle_rebind(h);
4847 
4848 			startd_free(e, sizeof (*e));
4849 		}
4850 
4851 		uu_list_destroy(old_deps);
4852 	}
4853 
4854 	MUTEX_UNLOCK(&dgraph_lock);
4855 
4856 	return (0);
4857 }
4858 
4859 /*
4860  * Return the eventual (maybe current) milestone in the form of a
4861  * legacy runlevel.
4862  */
4863 static char
4864 target_milestone_as_runlevel()
4865 {
4866 	assert(MUTEX_HELD(&dgraph_lock));
4867 
4868 	if (milestone == NULL)
4869 		return ('3');
4870 	else if (milestone == MILESTONE_NONE)
4871 		return ('0');
4872 
4873 	if (strcmp(milestone->gv_name, multi_user_fmri) == 0)
4874 		return ('2');
4875 	else if (strcmp(milestone->gv_name, single_user_fmri) == 0)
4876 		return ('S');
4877 	else if (strcmp(milestone->gv_name, multi_user_svr_fmri) == 0)
4878 		return ('3');
4879 
4880 #ifndef NDEBUG
4881 	(void) fprintf(stderr, "%s:%d: Unknown milestone name \"%s\".\n",
4882 	    __FILE__, __LINE__, milestone->gv_name);
4883 #endif
4884 	abort();
4885 	/* NOTREACHED */
4886 }
4887 
4888 static struct {
4889 	char	rl;
4890 	int	sig;
4891 } init_sigs[] = {
4892 	{ 'S', SIGBUS },
4893 	{ '0', SIGINT },
4894 	{ '1', SIGQUIT },
4895 	{ '2', SIGILL },
4896 	{ '3', SIGTRAP },
4897 	{ '4', SIGIOT },
4898 	{ '5', SIGEMT },
4899 	{ '6', SIGFPE },
4900 	{ 0, 0 }
4901 };
4902 
4903 static void
4904 signal_init(char rl)
4905 {
4906 	pid_t init_pid;
4907 	int i;
4908 
4909 	assert(MUTEX_HELD(&dgraph_lock));
4910 
4911 	if (zone_getattr(getzoneid(), ZONE_ATTR_INITPID, &init_pid,
4912 	    sizeof (init_pid)) != sizeof (init_pid)) {
4913 		log_error(LOG_NOTICE, "Could not get pid to signal init.\n");
4914 		return;
4915 	}
4916 
4917 	for (i = 0; init_sigs[i].rl != 0; ++i)
4918 		if (init_sigs[i].rl == rl)
4919 			break;
4920 
4921 	if (init_sigs[i].rl != 0) {
4922 		if (kill(init_pid, init_sigs[i].sig) != 0) {
4923 			switch (errno) {
4924 			case EPERM:
4925 			case ESRCH:
4926 				log_error(LOG_NOTICE, "Could not signal init: "
4927 				    "%s.\n", strerror(errno));
4928 				break;
4929 
4930 			case EINVAL:
4931 			default:
4932 				bad_error("kill", errno);
4933 			}
4934 		}
4935 	}
4936 }
4937 
4938 /*
4939  * This is called when one of the major milestones changes state, or when
4940  * init is signalled and tells us it was told to change runlevel.  We wait
4941  * to reach the milestone because this allows /etc/inittab entries to retain
4942  * some boot ordering: historically, entries could place themselves before/after
4943  * the running of /sbin/rcX scripts but we can no longer make the
4944  * distinction because the /sbin/rcX scripts no longer exist as punctuation
4945  * marks in /etc/inittab.
4946  *
4947  * Also, we only trigger an update when we reach the eventual target
4948  * milestone: without this, an /etc/inittab entry marked only for
4949  * runlevel 2 would be executed for runlevel 3, which is not how
4950  * /etc/inittab entries work.
4951  *
4952  * If we're single user coming online, then we set utmpx to the target
4953  * runlevel so that legacy scripts can work as expected.
4954  */
4955 static void
4956 graph_runlevel_changed(char rl, int online)
4957 {
4958 	char trl;
4959 
4960 	assert(MUTEX_HELD(&dgraph_lock));
4961 
4962 	trl = target_milestone_as_runlevel();
4963 
4964 	if (online) {
4965 		if (rl == trl) {
4966 			current_runlevel = trl;
4967 			signal_init(trl);
4968 		} else if (rl == 'S') {
4969 			/*
4970 			 * At boot, set the entry early for the benefit of the
4971 			 * legacy init scripts.
4972 			 */
4973 			utmpx_set_runlevel(trl, 'S', B_FALSE);
4974 		}
4975 	} else {
4976 		if (rl == '3' && trl == '2') {
4977 			current_runlevel = trl;
4978 			signal_init(trl);
4979 		} else if (rl == '2' && trl == 'S') {
4980 			current_runlevel = trl;
4981 			signal_init(trl);
4982 		}
4983 	}
4984 }
4985 
4986 /*
4987  * Move to a backwards-compatible runlevel by executing the appropriate
4988  * /etc/rc?.d/K* scripts and/or setting the milestone.
4989  *
4990  * Returns
4991  *   0 - success
4992  *   ECONNRESET - success, but handle was reset
4993  *   ECONNABORTED - repository connection broken
4994  *   ECANCELED - pg was deleted
4995  */
4996 static int
4997 dgraph_set_runlevel(scf_propertygroup_t *pg, scf_property_t *prop)
4998 {
4999 	char rl;
5000 	scf_handle_t *h;
5001 	int r;
5002 	const char *ms = NULL;	/* what to commit as options/milestone */
5003 	boolean_t rebound = B_FALSE;
5004 	int mark_rl = 0;
5005 
5006 	const char * const stop = "stop";
5007 
5008 	r = libscf_extract_runlevel(prop, &rl);
5009 	switch (r) {
5010 	case 0:
5011 		break;
5012 
5013 	case ECONNABORTED:
5014 	case ECANCELED:
5015 		return (r);
5016 
5017 	case EINVAL:
5018 	case ENOENT:
5019 		log_error(LOG_WARNING, "runlevel property is misconfigured; "
5020 		    "ignoring.\n");
5021 		/* delete the bad property */
5022 		goto nolock_out;
5023 
5024 	default:
5025 		bad_error("libscf_extract_runlevel", r);
5026 	}
5027 
5028 	switch (rl) {
5029 	case 's':
5030 		rl = 'S';
5031 		/* FALLTHROUGH */
5032 
5033 	case 'S':
5034 	case '2':
5035 	case '3':
5036 		/*
5037 		 * These cases cause a milestone change, so
5038 		 * graph_runlevel_changed() will eventually deal with
5039 		 * signalling init.
5040 		 */
5041 		break;
5042 
5043 	case '0':
5044 	case '1':
5045 	case '4':
5046 	case '5':
5047 	case '6':
5048 		mark_rl = 1;
5049 		break;
5050 
5051 	default:
5052 		log_framework(LOG_NOTICE, "Unknown runlevel '%c'.\n", rl);
5053 		ms = NULL;
5054 		goto nolock_out;
5055 	}
5056 
5057 	h = scf_pg_handle(pg);
5058 
5059 	MUTEX_LOCK(&dgraph_lock);
5060 
5061 	/*
5062 	 * Since this triggers no milestone changes, force it by hand.
5063 	 */
5064 	if (current_runlevel == '4' && rl == '3')
5065 		mark_rl = 1;
5066 
5067 	/*
5068 	 * 1. If we are here after an "init X":
5069 	 *
5070 	 * init X
5071 	 *	init/lscf_set_runlevel()
5072 	 *		process_pg_event()
5073 	 *		dgraph_set_runlevel()
5074 	 *
5075 	 * then we haven't passed through graph_runlevel_changed() yet,
5076 	 * therefore 'current_runlevel' has not changed for sure but 'rl' has.
5077 	 * In consequence, if 'rl' is lower than 'current_runlevel', we change
5078 	 * the system runlevel and execute the appropriate /etc/rc?.d/K* scripts
5079 	 * past this test.
5080 	 *
5081 	 * 2. On the other hand, if we are here after a "svcadm milestone":
5082 	 *
5083 	 * svcadm milestone X
5084 	 *	dgraph_set_milestone()
5085 	 *		handle_graph_update_event()
5086 	 *		dgraph_set_instance_state()
5087 	 *		graph_post_X_[online|offline]()
5088 	 *		graph_runlevel_changed()
5089 	 *		signal_init()
5090 	 *			init/lscf_set_runlevel()
5091 	 *				process_pg_event()
5092 	 *				dgraph_set_runlevel()
5093 	 *
5094 	 * then we already passed through graph_runlevel_changed() (by the way
5095 	 * of dgraph_set_milestone()) and 'current_runlevel' may have changed
5096 	 * and already be equal to 'rl' so we are going to return immediately
5097 	 * from dgraph_set_runlevel() without changing the system runlevel and
5098 	 * without executing the /etc/rc?.d/K* scripts.
5099 	 */
5100 	if (rl == current_runlevel) {
5101 		ms = NULL;
5102 		goto out;
5103 	}
5104 
5105 	log_framework(LOG_DEBUG, "Changing to runlevel '%c'.\n", rl);
5106 
5107 	/*
5108 	 * Make sure stop rc scripts see the new settings via who -r.
5109 	 */
5110 	utmpx_set_runlevel(rl, current_runlevel, B_TRUE);
5111 
5112 	/*
5113 	 * Some run levels don't have a direct correspondence to any
5114 	 * milestones, so we have to signal init directly.
5115 	 */
5116 	if (mark_rl) {
5117 		current_runlevel = rl;
5118 		signal_init(rl);
5119 	}
5120 
5121 	switch (rl) {
5122 	case 'S':
5123 		uu_warn("The system is coming down for administration.  "
5124 		    "Please wait.\n");
5125 		fork_rc_script(rl, stop, B_FALSE);
5126 		ms = single_user_fmri;
5127 		go_single_user_mode = B_TRUE;
5128 		break;
5129 
5130 	case '0':
5131 		halting_time = time(NULL);
5132 		fork_rc_script(rl, stop, B_TRUE);
5133 		halting = AD_HALT;
5134 		goto uadmin;
5135 
5136 	case '5':
5137 		halting_time = time(NULL);
5138 		fork_rc_script(rl, stop, B_TRUE);
5139 		halting = AD_POWEROFF;
5140 		goto uadmin;
5141 
5142 	case '6':
5143 		halting_time = time(NULL);
5144 		fork_rc_script(rl, stop, B_TRUE);
5145 		if (scf_is_fastboot_default() && getzoneid() == GLOBAL_ZONEID)
5146 			halting = AD_FASTREBOOT;
5147 		else
5148 			halting = AD_BOOT;
5149 
5150 uadmin:
5151 		uu_warn("The system is coming down.  Please wait.\n");
5152 		ms = "none";
5153 
5154 		/*
5155 		 * We can't wait until all services are offline since this
5156 		 * thread is responsible for taking them offline.  Instead we
5157 		 * set halting to the second argument for uadmin() and call
5158 		 * do_uadmin() from dgraph_set_instance_state() when
5159 		 * appropriate.
5160 		 */
5161 		break;
5162 
5163 	case '1':
5164 		if (current_runlevel != 'S') {
5165 			uu_warn("Changing to state 1.\n");
5166 			fork_rc_script(rl, stop, B_FALSE);
5167 		} else {
5168 			uu_warn("The system is coming up for administration.  "
5169 			    "Please wait.\n");
5170 		}
5171 		ms = single_user_fmri;
5172 		go_to_level1 = B_TRUE;
5173 		break;
5174 
5175 	case '2':
5176 		if (current_runlevel == '3' || current_runlevel == '4')
5177 			fork_rc_script(rl, stop, B_FALSE);
5178 		ms = multi_user_fmri;
5179 		break;
5180 
5181 	case '3':
5182 	case '4':
5183 		ms = "all";
5184 		break;
5185 
5186 	default:
5187 #ifndef NDEBUG
5188 		(void) fprintf(stderr, "%s:%d: Uncaught case %d ('%c').\n",
5189 		    __FILE__, __LINE__, rl, rl);
5190 #endif
5191 		abort();
5192 	}
5193 
5194 out:
5195 	MUTEX_UNLOCK(&dgraph_lock);
5196 
5197 nolock_out:
5198 	switch (r = libscf_clear_runlevel(pg, ms)) {
5199 	case 0:
5200 		break;
5201 
5202 	case ECONNABORTED:
5203 		libscf_handle_rebind(h);
5204 		rebound = B_TRUE;
5205 		goto nolock_out;
5206 
5207 	case ECANCELED:
5208 		break;
5209 
5210 	case EPERM:
5211 	case EACCES:
5212 	case EROFS:
5213 		log_error(LOG_NOTICE, "Could not delete \"%s/%s\" property: "
5214 		    "%s.\n", SCF_PG_OPTIONS, "runlevel", strerror(r));
5215 		break;
5216 
5217 	default:
5218 		bad_error("libscf_clear_runlevel", r);
5219 	}
5220 
5221 	return (rebound ? ECONNRESET : 0);
5222 }
5223 
5224 /*
5225  * mark_subtree walks the dependents and add the GV_TOOFFLINE flag
5226  * to the instances that are supposed to go offline during an
5227  * administrative disable operation.
5228  */
5229 static int
5230 mark_subtree(graph_edge_t *e, void *arg)
5231 {
5232 	graph_vertex_t *v;
5233 	int r;
5234 
5235 	v = e->ge_vertex;
5236 
5237 	/* If it's already in the subgraph, skip. */
5238 	if (v->gv_flags & GV_TOOFFLINE)
5239 		return (UU_WALK_NEXT);
5240 
5241 	switch (v->gv_type) {
5242 	case GVT_INST:
5243 		/* If the instance is already disabled, skip it. */
5244 		if (!(v->gv_flags & GV_ENABLED))
5245 			return (UU_WALK_NEXT);
5246 
5247 		v->gv_flags |= GV_TOOFFLINE;
5248 		log_framework(LOG_DEBUG, "%s added to subtree\n", v->gv_name);
5249 		break;
5250 	case GVT_GROUP:
5251 		/*
5252 		 * Skip all excluded and optional_all dependencies and decide
5253 		 * whether to offline the service based on restart_on attribute.
5254 		 */
5255 		if (is_depgrp_bypassed(v))
5256 			return (UU_WALK_NEXT);
5257 		break;
5258 	}
5259 
5260 	r = uu_list_walk(v->gv_dependents, (uu_walk_fn_t *)mark_subtree, arg,
5261 	    0);
5262 	assert(r == 0);
5263 	return (UU_WALK_NEXT);
5264 }
5265 
5266 static int
5267 mark_subgraph(graph_edge_t *e, void *arg)
5268 {
5269 	graph_vertex_t *v;
5270 	int r;
5271 	int optional = (int)arg;
5272 
5273 	v = e->ge_vertex;
5274 
5275 	/* If it's already in the subgraph, skip. */
5276 	if (v->gv_flags & GV_INSUBGRAPH)
5277 		return (UU_WALK_NEXT);
5278 
5279 	/*
5280 	 * Keep track if walk has entered an optional dependency group
5281 	 */
5282 	if (v->gv_type == GVT_GROUP && v->gv_depgroup == DEPGRP_OPTIONAL_ALL) {
5283 		optional = 1;
5284 	}
5285 	/*
5286 	 * Quit if we are in an optional dependency group and the instance
5287 	 * is disabled
5288 	 */
5289 	if (optional && (v->gv_type == GVT_INST) &&
5290 	    (!(v->gv_flags & GV_ENBLD_NOOVR)))
5291 		return (UU_WALK_NEXT);
5292 
5293 	v->gv_flags |= GV_INSUBGRAPH;
5294 
5295 	/* Skip all excluded dependencies. */
5296 	if (v->gv_type == GVT_GROUP && v->gv_depgroup == DEPGRP_EXCLUDE_ALL)
5297 		return (UU_WALK_NEXT);
5298 
5299 	r = uu_list_walk(v->gv_dependencies, (uu_walk_fn_t *)mark_subgraph,
5300 	    (void *)optional, 0);
5301 	assert(r == 0);
5302 	return (UU_WALK_NEXT);
5303 }
5304 
5305 /*
5306  * Bring down all services which are not dependencies of fmri.  The
5307  * dependencies of fmri (direct & indirect) will constitute the "subgraph",
5308  * and will have the GV_INSUBGRAPH flag set.  The rest must be brought down,
5309  * which means the state is "disabled", "maintenance", or "uninitialized".  We
5310  * could consider "offline" to be down, and refrain from sending start
5311  * commands for such services, but that's not strictly necessary, so we'll
5312  * decline to intrude on the state machine.  It would probably confuse users
5313  * anyway.
5314  *
5315  * The services should be brought down in reverse-dependency order, so we
5316  * can't do it all at once here.  We initiate by override-disabling the leaves
5317  * of the dependency tree -- those services which are up but have no
5318  * dependents which are up.  When they come down,
5319  * vertex_subgraph_dependencies_shutdown() will override-disable the newly
5320  * exposed leaves.  Perseverance will ensure completion.
5321  *
5322  * Sometimes we need to take action when the transition is complete, like
5323  * start sulogin or halt the system.  To tell when we're done, we initialize
5324  * non_subgraph_svcs here to be the number of services which need to come
5325  * down.  As each does, we decrement the counter.  When it hits zero, we take
5326  * the appropriate action.  See vertex_subgraph_dependencies_shutdown().
5327  *
5328  * In case we're coming up, we also remove any enable-overrides for the
5329  * services which are dependencies of fmri.
5330  *
5331  * If norepository is true, the function will not change the repository.
5332  *
5333  * The decision to change the system run level in accordance with the milestone
5334  * is taken in dgraph_set_runlevel().
5335  *
5336  * Returns
5337  *   0 - success
5338  *   ECONNRESET - success, but handle was rebound
5339  *   EINVAL - fmri is invalid (error is logged)
5340  *   EALREADY - the milestone is already set to fmri
5341  *   ENOENT - a configured vertex does not exist for fmri (an error is logged)
5342  */
5343 static int
5344 dgraph_set_milestone(const char *fmri, scf_handle_t *h, boolean_t norepository)
5345 {
5346 	const char *cfmri, *fs;
5347 	graph_vertex_t *nm, *v;
5348 	int ret = 0, r;
5349 	scf_instance_t *inst;
5350 	boolean_t isall, isnone, rebound = B_FALSE;
5351 
5352 	/* Validate fmri */
5353 	isall = (strcmp(fmri, "all") == 0);
5354 	isnone = (strcmp(fmri, "none") == 0);
5355 
5356 	if (!isall && !isnone) {
5357 		if (fmri_canonify(fmri, (char **)&cfmri, B_FALSE) == EINVAL)
5358 			goto reject;
5359 
5360 		if (strcmp(cfmri, single_user_fmri) != 0 &&
5361 		    strcmp(cfmri, multi_user_fmri) != 0 &&
5362 		    strcmp(cfmri, multi_user_svr_fmri) != 0) {
5363 			startd_free((void *)cfmri, max_scf_fmri_size);
5364 reject:
5365 			log_framework(LOG_WARNING,
5366 			    "Rejecting request for invalid milestone \"%s\".\n",
5367 			    fmri);
5368 			return (EINVAL);
5369 		}
5370 	}
5371 
5372 	inst = safe_scf_instance_create(h);
5373 
5374 	MUTEX_LOCK(&dgraph_lock);
5375 
5376 	if (milestone == NULL) {
5377 		if (isall) {
5378 			log_framework(LOG_DEBUG,
5379 			    "Milestone already set to all.\n");
5380 			ret = EALREADY;
5381 			goto out;
5382 		}
5383 	} else if (milestone == MILESTONE_NONE) {
5384 		if (isnone) {
5385 			log_framework(LOG_DEBUG,
5386 			    "Milestone already set to none.\n");
5387 			ret = EALREADY;
5388 			goto out;
5389 		}
5390 	} else {
5391 		if (!isall && !isnone &&
5392 		    strcmp(cfmri, milestone->gv_name) == 0) {
5393 			log_framework(LOG_DEBUG,
5394 			    "Milestone already set to %s.\n", cfmri);
5395 			ret = EALREADY;
5396 			goto out;
5397 		}
5398 	}
5399 
5400 	if (!isall && !isnone) {
5401 		nm = vertex_get_by_name(cfmri);
5402 		if (nm == NULL || !(nm->gv_flags & GV_CONFIGURED)) {
5403 			log_framework(LOG_WARNING, "Cannot set milestone to %s "
5404 			    "because no such service exists.\n", cfmri);
5405 			ret = ENOENT;
5406 			goto out;
5407 		}
5408 	}
5409 
5410 	log_framework(LOG_DEBUG, "Changing milestone to %s.\n", fmri);
5411 
5412 	/*
5413 	 * Set milestone, removing the old one if this was the last reference.
5414 	 */
5415 	if (milestone > MILESTONE_NONE)
5416 		(void) vertex_unref(milestone);
5417 
5418 	if (isall)
5419 		milestone = NULL;
5420 	else if (isnone)
5421 		milestone = MILESTONE_NONE;
5422 	else {
5423 		milestone = nm;
5424 		/* milestone should count as a reference */
5425 		vertex_ref(milestone);
5426 	}
5427 
5428 	/* Clear all GV_INSUBGRAPH bits. */
5429 	for (v = uu_list_first(dgraph); v != NULL; v = uu_list_next(dgraph, v))
5430 		v->gv_flags &= ~GV_INSUBGRAPH;
5431 
5432 	if (!isall && !isnone) {
5433 		/* Set GV_INSUBGRAPH for milestone & descendents. */
5434 		milestone->gv_flags |= GV_INSUBGRAPH;
5435 
5436 		r = uu_list_walk(milestone->gv_dependencies,
5437 		    (uu_walk_fn_t *)mark_subgraph, NULL, 0);
5438 		assert(r == 0);
5439 	}
5440 
5441 	/* Un-override services in the subgraph & override-disable the rest. */
5442 	if (norepository)
5443 		goto out;
5444 
5445 	non_subgraph_svcs = 0;
5446 	for (v = uu_list_first(dgraph);
5447 	    v != NULL;
5448 	    v = uu_list_next(dgraph, v)) {
5449 		if (v->gv_type != GVT_INST ||
5450 		    (v->gv_flags & GV_CONFIGURED) == 0)
5451 			continue;
5452 
5453 again:
5454 		r = scf_handle_decode_fmri(h, v->gv_name, NULL, NULL, inst,
5455 		    NULL, NULL, SCF_DECODE_FMRI_EXACT);
5456 		if (r != 0) {
5457 			switch (scf_error()) {
5458 			case SCF_ERROR_CONNECTION_BROKEN:
5459 			default:
5460 				libscf_handle_rebind(h);
5461 				rebound = B_TRUE;
5462 				goto again;
5463 
5464 			case SCF_ERROR_NOT_FOUND:
5465 				continue;
5466 
5467 			case SCF_ERROR_HANDLE_MISMATCH:
5468 			case SCF_ERROR_INVALID_ARGUMENT:
5469 			case SCF_ERROR_CONSTRAINT_VIOLATED:
5470 			case SCF_ERROR_NOT_BOUND:
5471 				bad_error("scf_handle_decode_fmri",
5472 				    scf_error());
5473 			}
5474 		}
5475 
5476 		if (isall || (v->gv_flags & GV_INSUBGRAPH)) {
5477 			r = libscf_delete_enable_ovr(inst);
5478 			fs = "libscf_delete_enable_ovr";
5479 		} else {
5480 			assert(isnone || (v->gv_flags & GV_INSUBGRAPH) == 0);
5481 
5482 			/*
5483 			 * Services which are up need to come down before
5484 			 * we're done, but we can only disable the leaves
5485 			 * here.
5486 			 */
5487 
5488 			if (up_state(v->gv_state))
5489 				++non_subgraph_svcs;
5490 
5491 			/* If it's already disabled, don't bother. */
5492 			if ((v->gv_flags & GV_ENABLED) == 0)
5493 				continue;
5494 
5495 			if (!is_nonsubgraph_leaf(v))
5496 				continue;
5497 
5498 			r = libscf_set_enable_ovr(inst, 0);
5499 			fs = "libscf_set_enable_ovr";
5500 		}
5501 		switch (r) {
5502 		case 0:
5503 		case ECANCELED:
5504 			break;
5505 
5506 		case ECONNABORTED:
5507 			libscf_handle_rebind(h);
5508 			rebound = B_TRUE;
5509 			goto again;
5510 
5511 		case EPERM:
5512 		case EROFS:
5513 			log_error(LOG_WARNING,
5514 			    "Could not set %s/%s for %s: %s.\n",
5515 			    SCF_PG_GENERAL_OVR, SCF_PROPERTY_ENABLED,
5516 			    v->gv_name, strerror(r));
5517 			break;
5518 
5519 		default:
5520 			bad_error(fs, r);
5521 		}
5522 	}
5523 
5524 	if (halting != -1) {
5525 		if (non_subgraph_svcs > 1)
5526 			uu_warn("%d system services are now being stopped.\n",
5527 			    non_subgraph_svcs);
5528 		else if (non_subgraph_svcs == 1)
5529 			uu_warn("One system service is now being stopped.\n");
5530 		else if (non_subgraph_svcs == 0)
5531 			do_uadmin();
5532 	}
5533 
5534 	ret = rebound ? ECONNRESET : 0;
5535 
5536 out:
5537 	MUTEX_UNLOCK(&dgraph_lock);
5538 	if (!isall && !isnone)
5539 		startd_free((void *)cfmri, max_scf_fmri_size);
5540 	scf_instance_destroy(inst);
5541 	return (ret);
5542 }
5543 
5544 
5545 /*
5546  * Returns 0, ECONNABORTED, or EINVAL.
5547  */
5548 static int
5549 handle_graph_update_event(scf_handle_t *h, graph_protocol_event_t *e)
5550 {
5551 	int r;
5552 
5553 	switch (e->gpe_type) {
5554 	case GRAPH_UPDATE_RELOAD_GRAPH:
5555 		log_error(LOG_WARNING,
5556 		    "graph_event: reload graph unimplemented\n");
5557 		break;
5558 
5559 	case GRAPH_UPDATE_STATE_CHANGE: {
5560 		protocol_states_t *states = e->gpe_data;
5561 
5562 		switch (r = dgraph_set_instance_state(h, e->gpe_inst,
5563 		    states->ps_state, states->ps_err)) {
5564 		case 0:
5565 		case ENOENT:
5566 			break;
5567 
5568 		case ECONNABORTED:
5569 			return (ECONNABORTED);
5570 
5571 		case EINVAL:
5572 		default:
5573 #ifndef NDEBUG
5574 			(void) fprintf(stderr, "dgraph_set_instance_state() "
5575 			    "failed with unexpected error %d at %s:%d.\n", r,
5576 			    __FILE__, __LINE__);
5577 #endif
5578 			abort();
5579 		}
5580 
5581 		startd_free(states, sizeof (protocol_states_t));
5582 		break;
5583 	}
5584 
5585 	default:
5586 		log_error(LOG_WARNING,
5587 		    "graph_event_loop received an unknown event: %d\n",
5588 		    e->gpe_type);
5589 		break;
5590 	}
5591 
5592 	return (0);
5593 }
5594 
5595 /*
5596  * graph_event_thread()
5597  *    Wait for state changes from the restarters.
5598  */
5599 /*ARGSUSED*/
5600 void *
5601 graph_event_thread(void *unused)
5602 {
5603 	scf_handle_t *h;
5604 	int err;
5605 
5606 	h = libscf_handle_create_bound_loop();
5607 
5608 	/*CONSTCOND*/
5609 	while (1) {
5610 		graph_protocol_event_t *e;
5611 
5612 		MUTEX_LOCK(&gu->gu_lock);
5613 
5614 		while (gu->gu_wakeup == 0)
5615 			(void) pthread_cond_wait(&gu->gu_cv, &gu->gu_lock);
5616 
5617 		gu->gu_wakeup = 0;
5618 
5619 		while ((e = graph_event_dequeue()) != NULL) {
5620 			MUTEX_LOCK(&e->gpe_lock);
5621 			MUTEX_UNLOCK(&gu->gu_lock);
5622 
5623 			while ((err = handle_graph_update_event(h, e)) ==
5624 			    ECONNABORTED)
5625 				libscf_handle_rebind(h);
5626 
5627 			if (err == 0)
5628 				graph_event_release(e);
5629 			else
5630 				graph_event_requeue(e);
5631 
5632 			MUTEX_LOCK(&gu->gu_lock);
5633 		}
5634 
5635 		MUTEX_UNLOCK(&gu->gu_lock);
5636 	}
5637 
5638 	/*
5639 	 * Unreachable for now -- there's currently no graceful cleanup
5640 	 * called on exit().
5641 	 */
5642 	MUTEX_UNLOCK(&gu->gu_lock);
5643 	scf_handle_destroy(h);
5644 	return (NULL);
5645 }
5646 
5647 static void
5648 set_initial_milestone(scf_handle_t *h)
5649 {
5650 	scf_instance_t *inst;
5651 	char *fmri, *cfmri;
5652 	size_t sz;
5653 	int r;
5654 
5655 	inst = safe_scf_instance_create(h);
5656 	fmri = startd_alloc(max_scf_fmri_size);
5657 
5658 	/*
5659 	 * If -m milestone= was specified, we want to set options_ovr/milestone
5660 	 * to it.  Otherwise we want to read what the milestone should be set
5661 	 * to.  Either way we need our inst.
5662 	 */
5663 get_self:
5664 	if (scf_handle_decode_fmri(h, SCF_SERVICE_STARTD, NULL, NULL, inst,
5665 	    NULL, NULL, SCF_DECODE_FMRI_EXACT) != 0) {
5666 		switch (scf_error()) {
5667 		case SCF_ERROR_CONNECTION_BROKEN:
5668 			libscf_handle_rebind(h);
5669 			goto get_self;
5670 
5671 		case SCF_ERROR_NOT_FOUND:
5672 			if (st->st_subgraph != NULL &&
5673 			    st->st_subgraph[0] != '\0') {
5674 				sz = strlcpy(fmri, st->st_subgraph,
5675 				    max_scf_fmri_size);
5676 				assert(sz < max_scf_fmri_size);
5677 			} else {
5678 				fmri[0] = '\0';
5679 			}
5680 			break;
5681 
5682 		case SCF_ERROR_INVALID_ARGUMENT:
5683 		case SCF_ERROR_CONSTRAINT_VIOLATED:
5684 		case SCF_ERROR_HANDLE_MISMATCH:
5685 		default:
5686 			bad_error("scf_handle_decode_fmri", scf_error());
5687 		}
5688 	} else {
5689 		if (st->st_subgraph != NULL && st->st_subgraph[0] != '\0') {
5690 			scf_propertygroup_t *pg;
5691 
5692 			pg = safe_scf_pg_create(h);
5693 
5694 			sz = strlcpy(fmri, st->st_subgraph, max_scf_fmri_size);
5695 			assert(sz < max_scf_fmri_size);
5696 
5697 			r = libscf_inst_get_or_add_pg(inst, SCF_PG_OPTIONS_OVR,
5698 			    SCF_PG_OPTIONS_OVR_TYPE, SCF_PG_OPTIONS_OVR_FLAGS,
5699 			    pg);
5700 			switch (r) {
5701 			case 0:
5702 				break;
5703 
5704 			case ECONNABORTED:
5705 				libscf_handle_rebind(h);
5706 				goto get_self;
5707 
5708 			case EPERM:
5709 			case EACCES:
5710 			case EROFS:
5711 				log_error(LOG_WARNING, "Could not set %s/%s: "
5712 				    "%s.\n", SCF_PG_OPTIONS_OVR,
5713 				    SCF_PROPERTY_MILESTONE, strerror(r));
5714 				/* FALLTHROUGH */
5715 
5716 			case ECANCELED:
5717 				sz = strlcpy(fmri, st->st_subgraph,
5718 				    max_scf_fmri_size);
5719 				assert(sz < max_scf_fmri_size);
5720 				break;
5721 
5722 			default:
5723 				bad_error("libscf_inst_get_or_add_pg", r);
5724 			}
5725 
5726 			r = libscf_clear_runlevel(pg, fmri);
5727 			switch (r) {
5728 			case 0:
5729 				break;
5730 
5731 			case ECONNABORTED:
5732 				libscf_handle_rebind(h);
5733 				goto get_self;
5734 
5735 			case EPERM:
5736 			case EACCES:
5737 			case EROFS:
5738 				log_error(LOG_WARNING, "Could not set %s/%s: "
5739 				    "%s.\n", SCF_PG_OPTIONS_OVR,
5740 				    SCF_PROPERTY_MILESTONE, strerror(r));
5741 				/* FALLTHROUGH */
5742 
5743 			case ECANCELED:
5744 				sz = strlcpy(fmri, st->st_subgraph,
5745 				    max_scf_fmri_size);
5746 				assert(sz < max_scf_fmri_size);
5747 				break;
5748 
5749 			default:
5750 				bad_error("libscf_clear_runlevel", r);
5751 			}
5752 
5753 			scf_pg_destroy(pg);
5754 		} else {
5755 			scf_property_t *prop;
5756 			scf_value_t *val;
5757 
5758 			prop = safe_scf_property_create(h);
5759 			val = safe_scf_value_create(h);
5760 
5761 			r = libscf_get_milestone(inst, prop, val, fmri,
5762 			    max_scf_fmri_size);
5763 			switch (r) {
5764 			case 0:
5765 				break;
5766 
5767 			case ECONNABORTED:
5768 				libscf_handle_rebind(h);
5769 				goto get_self;
5770 
5771 			case EINVAL:
5772 				log_error(LOG_WARNING, "Milestone property is "
5773 				    "misconfigured.  Defaulting to \"all\".\n");
5774 				/* FALLTHROUGH */
5775 
5776 			case ECANCELED:
5777 			case ENOENT:
5778 				fmri[0] = '\0';
5779 				break;
5780 
5781 			default:
5782 				bad_error("libscf_get_milestone", r);
5783 			}
5784 
5785 			scf_value_destroy(val);
5786 			scf_property_destroy(prop);
5787 		}
5788 	}
5789 
5790 	if (fmri[0] == '\0' || strcmp(fmri, "all") == 0)
5791 		goto out;
5792 
5793 	if (strcmp(fmri, "none") != 0) {
5794 retry:
5795 		if (scf_handle_decode_fmri(h, fmri, NULL, NULL, inst, NULL,
5796 		    NULL, SCF_DECODE_FMRI_EXACT) != 0) {
5797 			switch (scf_error()) {
5798 			case SCF_ERROR_INVALID_ARGUMENT:
5799 				log_error(LOG_WARNING,
5800 				    "Requested milestone \"%s\" is invalid.  "
5801 				    "Reverting to \"all\".\n", fmri);
5802 				goto out;
5803 
5804 			case SCF_ERROR_CONSTRAINT_VIOLATED:
5805 				log_error(LOG_WARNING, "Requested milestone "
5806 				    "\"%s\" does not specify an instance.  "
5807 				    "Reverting to \"all\".\n", fmri);
5808 				goto out;
5809 
5810 			case SCF_ERROR_CONNECTION_BROKEN:
5811 				libscf_handle_rebind(h);
5812 				goto retry;
5813 
5814 			case SCF_ERROR_NOT_FOUND:
5815 				log_error(LOG_WARNING, "Requested milestone "
5816 				    "\"%s\" not in repository.  Reverting to "
5817 				    "\"all\".\n", fmri);
5818 				goto out;
5819 
5820 			case SCF_ERROR_HANDLE_MISMATCH:
5821 			default:
5822 				bad_error("scf_handle_decode_fmri",
5823 				    scf_error());
5824 			}
5825 		}
5826 
5827 		r = fmri_canonify(fmri, &cfmri, B_FALSE);
5828 		assert(r == 0);
5829 
5830 		r = dgraph_add_instance(cfmri, inst, B_TRUE);
5831 		startd_free(cfmri, max_scf_fmri_size);
5832 		switch (r) {
5833 		case 0:
5834 			break;
5835 
5836 		case ECONNABORTED:
5837 			goto retry;
5838 
5839 		case EINVAL:
5840 			log_error(LOG_WARNING,
5841 			    "Requested milestone \"%s\" is invalid.  "
5842 			    "Reverting to \"all\".\n", fmri);
5843 			goto out;
5844 
5845 		case ECANCELED:
5846 			log_error(LOG_WARNING,
5847 			    "Requested milestone \"%s\" not "
5848 			    "in repository.  Reverting to \"all\".\n",
5849 			    fmri);
5850 			goto out;
5851 
5852 		case EEXIST:
5853 		default:
5854 			bad_error("dgraph_add_instance", r);
5855 		}
5856 	}
5857 
5858 	log_console(LOG_INFO, "Booting to milestone \"%s\".\n", fmri);
5859 
5860 	r = dgraph_set_milestone(fmri, h, B_FALSE);
5861 	switch (r) {
5862 	case 0:
5863 	case ECONNRESET:
5864 	case EALREADY:
5865 		break;
5866 
5867 	case EINVAL:
5868 	case ENOENT:
5869 	default:
5870 		bad_error("dgraph_set_milestone", r);
5871 	}
5872 
5873 out:
5874 	startd_free(fmri, max_scf_fmri_size);
5875 	scf_instance_destroy(inst);
5876 }
5877 
5878 void
5879 set_restart_milestone(scf_handle_t *h)
5880 {
5881 	scf_instance_t *inst;
5882 	scf_property_t *prop;
5883 	scf_value_t *val;
5884 	char *fmri;
5885 	int r;
5886 
5887 	inst = safe_scf_instance_create(h);
5888 
5889 get_self:
5890 	if (scf_handle_decode_fmri(h, SCF_SERVICE_STARTD, NULL, NULL,
5891 	    inst, NULL, NULL, SCF_DECODE_FMRI_EXACT) != 0) {
5892 		switch (scf_error()) {
5893 		case SCF_ERROR_CONNECTION_BROKEN:
5894 			libscf_handle_rebind(h);
5895 			goto get_self;
5896 
5897 		case SCF_ERROR_NOT_FOUND:
5898 			break;
5899 
5900 		case SCF_ERROR_INVALID_ARGUMENT:
5901 		case SCF_ERROR_CONSTRAINT_VIOLATED:
5902 		case SCF_ERROR_HANDLE_MISMATCH:
5903 		default:
5904 			bad_error("scf_handle_decode_fmri", scf_error());
5905 		}
5906 
5907 		scf_instance_destroy(inst);
5908 		return;
5909 	}
5910 
5911 	prop = safe_scf_property_create(h);
5912 	val = safe_scf_value_create(h);
5913 	fmri = startd_alloc(max_scf_fmri_size);
5914 
5915 	r = libscf_get_milestone(inst, prop, val, fmri, max_scf_fmri_size);
5916 	switch (r) {
5917 	case 0:
5918 		break;
5919 
5920 	case ECONNABORTED:
5921 		libscf_handle_rebind(h);
5922 		goto get_self;
5923 
5924 	case ECANCELED:
5925 	case ENOENT:
5926 	case EINVAL:
5927 		goto out;
5928 
5929 	default:
5930 		bad_error("libscf_get_milestone", r);
5931 	}
5932 
5933 	r = dgraph_set_milestone(fmri, h, B_TRUE);
5934 	switch (r) {
5935 	case 0:
5936 	case ECONNRESET:
5937 	case EALREADY:
5938 	case EINVAL:
5939 	case ENOENT:
5940 		break;
5941 
5942 	default:
5943 		bad_error("dgraph_set_milestone", r);
5944 	}
5945 
5946 out:
5947 	startd_free(fmri, max_scf_fmri_size);
5948 	scf_value_destroy(val);
5949 	scf_property_destroy(prop);
5950 	scf_instance_destroy(inst);
5951 }
5952 
5953 /*
5954  * void *graph_thread(void *)
5955  *
5956  * Graph management thread.
5957  */
5958 /*ARGSUSED*/
5959 void *
5960 graph_thread(void *arg)
5961 {
5962 	scf_handle_t *h;
5963 	int err;
5964 
5965 	h = libscf_handle_create_bound_loop();
5966 
5967 	if (st->st_initial)
5968 		set_initial_milestone(h);
5969 
5970 	MUTEX_LOCK(&dgraph_lock);
5971 	initial_milestone_set = B_TRUE;
5972 	err = pthread_cond_broadcast(&initial_milestone_cv);
5973 	assert(err == 0);
5974 	MUTEX_UNLOCK(&dgraph_lock);
5975 
5976 	libscf_populate_graph(h);
5977 
5978 	if (!st->st_initial)
5979 		set_restart_milestone(h);
5980 
5981 	MUTEX_LOCK(&st->st_load_lock);
5982 	st->st_load_complete = 1;
5983 	(void) pthread_cond_broadcast(&st->st_load_cv);
5984 	MUTEX_UNLOCK(&st->st_load_lock);
5985 
5986 	MUTEX_LOCK(&dgraph_lock);
5987 	/*
5988 	 * Now that we've set st_load_complete we need to check can_come_up()
5989 	 * since if we booted to a milestone, then there won't be any more
5990 	 * state updates.
5991 	 */
5992 	if (!go_single_user_mode && !go_to_level1 &&
5993 	    halting == -1) {
5994 		if (!sulogin_thread_running && !can_come_up()) {
5995 			(void) startd_thread_create(sulogin_thread, NULL);
5996 			sulogin_thread_running = B_TRUE;
5997 		}
5998 	}
5999 	MUTEX_UNLOCK(&dgraph_lock);
6000 
6001 	(void) pthread_mutex_lock(&gu->gu_freeze_lock);
6002 
6003 	/*CONSTCOND*/
6004 	while (1) {
6005 		(void) pthread_cond_wait(&gu->gu_freeze_cv,
6006 		    &gu->gu_freeze_lock);
6007 	}
6008 
6009 	/*
6010 	 * Unreachable for now -- there's currently no graceful cleanup
6011 	 * called on exit().
6012 	 */
6013 	(void) pthread_mutex_unlock(&gu->gu_freeze_lock);
6014 	scf_handle_destroy(h);
6015 
6016 	return (NULL);
6017 }
6018 
6019 
6020 /*
6021  * int next_action()
6022  *   Given an array of timestamps 'a' with 'num' elements, find the
6023  *   lowest non-zero timestamp and return its index. If there are no
6024  *   non-zero elements, return -1.
6025  */
6026 static int
6027 next_action(hrtime_t *a, int num)
6028 {
6029 	hrtime_t t = 0;
6030 	int i = 0, smallest = -1;
6031 
6032 	for (i = 0; i < num; i++) {
6033 		if (t == 0) {
6034 			t = a[i];
6035 			smallest = i;
6036 		} else if (a[i] != 0 && a[i] < t) {
6037 			t = a[i];
6038 			smallest = i;
6039 		}
6040 	}
6041 
6042 	if (t == 0)
6043 		return (-1);
6044 	else
6045 		return (smallest);
6046 }
6047 
6048 /*
6049  * void process_actions()
6050  *   Process actions requested by the administrator. Possibilities include:
6051  *   refresh, restart, maintenance mode off, maintenance mode on,
6052  *   maintenance mode immediate, and degraded.
6053  *
6054  *   The set of pending actions is represented in the repository as a
6055  *   per-instance property group, with each action being a single property
6056  *   in that group.  This property group is converted to an array, with each
6057  *   action type having an array slot.  The actions in the array at the
6058  *   time process_actions() is called are acted on in the order of the
6059  *   timestamp (which is the value stored in the slot).  A value of zero
6060  *   indicates that there is no pending action of the type associated with
6061  *   a particular slot.
6062  *
6063  *   Sending an action event multiple times before the restarter has a
6064  *   chance to process that action will force it to be run at the last
6065  *   timestamp where it appears in the ordering.
6066  *
6067  *   Turning maintenance mode on trumps all other actions.
6068  *
6069  *   Returns 0 or ECONNABORTED.
6070  */
6071 static int
6072 process_actions(scf_handle_t *h, scf_propertygroup_t *pg, scf_instance_t *inst)
6073 {
6074 	scf_property_t *prop = NULL;
6075 	scf_value_t *val = NULL;
6076 	scf_type_t type;
6077 	graph_vertex_t *vertex;
6078 	admin_action_t a;
6079 	int i, ret = 0, r;
6080 	hrtime_t action_ts[NACTIONS];
6081 	char *inst_name;
6082 
6083 	r = libscf_instance_get_fmri(inst, &inst_name);
6084 	switch (r) {
6085 	case 0:
6086 		break;
6087 
6088 	case ECONNABORTED:
6089 		return (ECONNABORTED);
6090 
6091 	case ECANCELED:
6092 		return (0);
6093 
6094 	default:
6095 		bad_error("libscf_instance_get_fmri", r);
6096 	}
6097 
6098 	MUTEX_LOCK(&dgraph_lock);
6099 
6100 	vertex = vertex_get_by_name(inst_name);
6101 	if (vertex == NULL) {
6102 		MUTEX_UNLOCK(&dgraph_lock);
6103 		log_framework(LOG_DEBUG, "%s: Can't find graph vertex. "
6104 		    "The instance must have been removed.\n", inst_name);
6105 		startd_free(inst_name, max_scf_fmri_size);
6106 		return (0);
6107 	}
6108 
6109 	prop = safe_scf_property_create(h);
6110 	val = safe_scf_value_create(h);
6111 
6112 	for (i = 0; i < NACTIONS; i++) {
6113 		if (scf_pg_get_property(pg, admin_actions[i], prop) != 0) {
6114 			switch (scf_error()) {
6115 			case SCF_ERROR_CONNECTION_BROKEN:
6116 			default:
6117 				ret = ECONNABORTED;
6118 				goto out;
6119 
6120 			case SCF_ERROR_DELETED:
6121 				goto out;
6122 
6123 			case SCF_ERROR_NOT_FOUND:
6124 				action_ts[i] = 0;
6125 				continue;
6126 
6127 			case SCF_ERROR_HANDLE_MISMATCH:
6128 			case SCF_ERROR_INVALID_ARGUMENT:
6129 			case SCF_ERROR_NOT_SET:
6130 				bad_error("scf_pg_get_property", scf_error());
6131 			}
6132 		}
6133 
6134 		if (scf_property_type(prop, &type) != 0) {
6135 			switch (scf_error()) {
6136 			case SCF_ERROR_CONNECTION_BROKEN:
6137 			default:
6138 				ret = ECONNABORTED;
6139 				goto out;
6140 
6141 			case SCF_ERROR_DELETED:
6142 				action_ts[i] = 0;
6143 				continue;
6144 
6145 			case SCF_ERROR_NOT_SET:
6146 				bad_error("scf_property_type", scf_error());
6147 			}
6148 		}
6149 
6150 		if (type != SCF_TYPE_INTEGER) {
6151 			action_ts[i] = 0;
6152 			continue;
6153 		}
6154 
6155 		if (scf_property_get_value(prop, val) != 0) {
6156 			switch (scf_error()) {
6157 			case SCF_ERROR_CONNECTION_BROKEN:
6158 			default:
6159 				ret = ECONNABORTED;
6160 				goto out;
6161 
6162 			case SCF_ERROR_DELETED:
6163 				goto out;
6164 
6165 			case SCF_ERROR_NOT_FOUND:
6166 			case SCF_ERROR_CONSTRAINT_VIOLATED:
6167 				action_ts[i] = 0;
6168 				continue;
6169 
6170 			case SCF_ERROR_NOT_SET:
6171 			case SCF_ERROR_PERMISSION_DENIED:
6172 				bad_error("scf_property_get_value",
6173 				    scf_error());
6174 			}
6175 		}
6176 
6177 		r = scf_value_get_integer(val, &action_ts[i]);
6178 		assert(r == 0);
6179 	}
6180 
6181 	a = ADMIN_EVENT_MAINT_ON_IMMEDIATE;
6182 	if (action_ts[ADMIN_EVENT_MAINT_ON_IMMEDIATE] ||
6183 	    action_ts[ADMIN_EVENT_MAINT_ON]) {
6184 		a = action_ts[ADMIN_EVENT_MAINT_ON_IMMEDIATE] ?
6185 		    ADMIN_EVENT_MAINT_ON_IMMEDIATE : ADMIN_EVENT_MAINT_ON;
6186 
6187 		vertex_send_event(vertex, admin_events[a]);
6188 		r = libscf_unset_action(h, pg, a, action_ts[a]);
6189 		switch (r) {
6190 		case 0:
6191 		case EACCES:
6192 			break;
6193 
6194 		case ECONNABORTED:
6195 			ret = ECONNABORTED;
6196 			goto out;
6197 
6198 		case EPERM:
6199 			uu_die("Insufficient privilege.\n");
6200 			/* NOTREACHED */
6201 
6202 		default:
6203 			bad_error("libscf_unset_action", r);
6204 		}
6205 	}
6206 
6207 	while ((a = next_action(action_ts, NACTIONS)) != -1) {
6208 		log_framework(LOG_DEBUG,
6209 		    "Graph: processing %s action for %s.\n", admin_actions[a],
6210 		    inst_name);
6211 
6212 		if (a == ADMIN_EVENT_REFRESH) {
6213 			r = dgraph_refresh_instance(vertex, inst);
6214 			switch (r) {
6215 			case 0:
6216 			case ECANCELED:
6217 			case EINVAL:
6218 			case -1:
6219 				break;
6220 
6221 			case ECONNABORTED:
6222 				/* pg & inst are reset now, so just return. */
6223 				ret = ECONNABORTED;
6224 				goto out;
6225 
6226 			default:
6227 				bad_error("dgraph_refresh_instance", r);
6228 			}
6229 		}
6230 
6231 		vertex_send_event(vertex, admin_events[a]);
6232 
6233 		r = libscf_unset_action(h, pg, a, action_ts[a]);
6234 		switch (r) {
6235 		case 0:
6236 		case EACCES:
6237 			break;
6238 
6239 		case ECONNABORTED:
6240 			ret = ECONNABORTED;
6241 			goto out;
6242 
6243 		case EPERM:
6244 			uu_die("Insufficient privilege.\n");
6245 			/* NOTREACHED */
6246 
6247 		default:
6248 			bad_error("libscf_unset_action", r);
6249 		}
6250 
6251 		action_ts[a] = 0;
6252 	}
6253 
6254 out:
6255 	MUTEX_UNLOCK(&dgraph_lock);
6256 
6257 	scf_property_destroy(prop);
6258 	scf_value_destroy(val);
6259 	startd_free(inst_name, max_scf_fmri_size);
6260 	return (ret);
6261 }
6262 
6263 /*
6264  * inst and pg_name are scratch space, and are unset on entry.
6265  * Returns
6266  *   0 - success
6267  *   ECONNRESET - success, but repository handle rebound
6268  *   ECONNABORTED - repository connection broken
6269  */
6270 static int
6271 process_pg_event(scf_handle_t *h, scf_propertygroup_t *pg, scf_instance_t *inst,
6272     char *pg_name)
6273 {
6274 	int r;
6275 	scf_property_t *prop;
6276 	scf_value_t *val;
6277 	char *fmri;
6278 	boolean_t rebound = B_FALSE, rebind_inst = B_FALSE;
6279 
6280 	if (scf_pg_get_name(pg, pg_name, max_scf_value_size) < 0) {
6281 		switch (scf_error()) {
6282 		case SCF_ERROR_CONNECTION_BROKEN:
6283 		default:
6284 			return (ECONNABORTED);
6285 
6286 		case SCF_ERROR_DELETED:
6287 			return (0);
6288 
6289 		case SCF_ERROR_NOT_SET:
6290 			bad_error("scf_pg_get_name", scf_error());
6291 		}
6292 	}
6293 
6294 	if (strcmp(pg_name, SCF_PG_GENERAL) == 0 ||
6295 	    strcmp(pg_name, SCF_PG_GENERAL_OVR) == 0) {
6296 		r = dgraph_update_general(pg);
6297 		switch (r) {
6298 		case 0:
6299 		case ENOTSUP:
6300 		case ECANCELED:
6301 			return (0);
6302 
6303 		case ECONNABORTED:
6304 			return (ECONNABORTED);
6305 
6306 		case -1:
6307 			/* Error should have been logged. */
6308 			return (0);
6309 
6310 		default:
6311 			bad_error("dgraph_update_general", r);
6312 		}
6313 	} else if (strcmp(pg_name, SCF_PG_RESTARTER_ACTIONS) == 0) {
6314 		if (scf_pg_get_parent_instance(pg, inst) != 0) {
6315 			switch (scf_error()) {
6316 			case SCF_ERROR_CONNECTION_BROKEN:
6317 				return (ECONNABORTED);
6318 
6319 			case SCF_ERROR_DELETED:
6320 			case SCF_ERROR_CONSTRAINT_VIOLATED:
6321 				/* Ignore commands on services. */
6322 				return (0);
6323 
6324 			case SCF_ERROR_NOT_BOUND:
6325 			case SCF_ERROR_HANDLE_MISMATCH:
6326 			case SCF_ERROR_NOT_SET:
6327 			default:
6328 				bad_error("scf_pg_get_parent_instance",
6329 				    scf_error());
6330 			}
6331 		}
6332 
6333 		return (process_actions(h, pg, inst));
6334 	}
6335 
6336 	if (strcmp(pg_name, SCF_PG_OPTIONS) != 0 &&
6337 	    strcmp(pg_name, SCF_PG_OPTIONS_OVR) != 0)
6338 		return (0);
6339 
6340 	/*
6341 	 * We only care about the options[_ovr] property groups of our own
6342 	 * instance, so get the fmri and compare.  Plus, once we know it's
6343 	 * correct, if the repository connection is broken we know exactly what
6344 	 * property group we were operating on, and can look it up again.
6345 	 */
6346 	if (scf_pg_get_parent_instance(pg, inst) != 0) {
6347 		switch (scf_error()) {
6348 		case SCF_ERROR_CONNECTION_BROKEN:
6349 			return (ECONNABORTED);
6350 
6351 		case SCF_ERROR_DELETED:
6352 		case SCF_ERROR_CONSTRAINT_VIOLATED:
6353 			return (0);
6354 
6355 		case SCF_ERROR_HANDLE_MISMATCH:
6356 		case SCF_ERROR_NOT_BOUND:
6357 		case SCF_ERROR_NOT_SET:
6358 		default:
6359 			bad_error("scf_pg_get_parent_instance",
6360 			    scf_error());
6361 		}
6362 	}
6363 
6364 	switch (r = libscf_instance_get_fmri(inst, &fmri)) {
6365 	case 0:
6366 		break;
6367 
6368 	case ECONNABORTED:
6369 		return (ECONNABORTED);
6370 
6371 	case ECANCELED:
6372 		return (0);
6373 
6374 	default:
6375 		bad_error("libscf_instance_get_fmri", r);
6376 	}
6377 
6378 	if (strcmp(fmri, SCF_SERVICE_STARTD) != 0) {
6379 		startd_free(fmri, max_scf_fmri_size);
6380 		return (0);
6381 	}
6382 
6383 	prop = safe_scf_property_create(h);
6384 	val = safe_scf_value_create(h);
6385 
6386 	if (strcmp(pg_name, SCF_PG_OPTIONS_OVR) == 0) {
6387 		/* See if we need to set the runlevel. */
6388 		/* CONSTCOND */
6389 		if (0) {
6390 rebind_pg:
6391 			libscf_handle_rebind(h);
6392 			rebound = B_TRUE;
6393 
6394 			r = libscf_lookup_instance(SCF_SERVICE_STARTD, inst);
6395 			switch (r) {
6396 			case 0:
6397 				break;
6398 
6399 			case ECONNABORTED:
6400 				goto rebind_pg;
6401 
6402 			case ENOENT:
6403 				goto out;
6404 
6405 			case EINVAL:
6406 			case ENOTSUP:
6407 				bad_error("libscf_lookup_instance", r);
6408 			}
6409 
6410 			if (scf_instance_get_pg(inst, pg_name, pg) != 0) {
6411 				switch (scf_error()) {
6412 				case SCF_ERROR_DELETED:
6413 				case SCF_ERROR_NOT_FOUND:
6414 					goto out;
6415 
6416 				case SCF_ERROR_CONNECTION_BROKEN:
6417 					goto rebind_pg;
6418 
6419 				case SCF_ERROR_HANDLE_MISMATCH:
6420 				case SCF_ERROR_NOT_BOUND:
6421 				case SCF_ERROR_NOT_SET:
6422 				case SCF_ERROR_INVALID_ARGUMENT:
6423 				default:
6424 					bad_error("scf_instance_get_pg",
6425 					    scf_error());
6426 				}
6427 			}
6428 		}
6429 
6430 		if (scf_pg_get_property(pg, "runlevel", prop) == 0) {
6431 			r = dgraph_set_runlevel(pg, prop);
6432 			switch (r) {
6433 			case ECONNRESET:
6434 				rebound = B_TRUE;
6435 				rebind_inst = B_TRUE;
6436 				/* FALLTHROUGH */
6437 
6438 			case 0:
6439 				break;
6440 
6441 			case ECONNABORTED:
6442 				goto rebind_pg;
6443 
6444 			case ECANCELED:
6445 				goto out;
6446 
6447 			default:
6448 				bad_error("dgraph_set_runlevel", r);
6449 			}
6450 		} else {
6451 			switch (scf_error()) {
6452 			case SCF_ERROR_CONNECTION_BROKEN:
6453 			default:
6454 				goto rebind_pg;
6455 
6456 			case SCF_ERROR_DELETED:
6457 				goto out;
6458 
6459 			case SCF_ERROR_NOT_FOUND:
6460 				break;
6461 
6462 			case SCF_ERROR_INVALID_ARGUMENT:
6463 			case SCF_ERROR_HANDLE_MISMATCH:
6464 			case SCF_ERROR_NOT_BOUND:
6465 			case SCF_ERROR_NOT_SET:
6466 				bad_error("scf_pg_get_property", scf_error());
6467 			}
6468 		}
6469 	}
6470 
6471 	if (rebind_inst) {
6472 lookup_inst:
6473 		r = libscf_lookup_instance(SCF_SERVICE_STARTD, inst);
6474 		switch (r) {
6475 		case 0:
6476 			break;
6477 
6478 		case ECONNABORTED:
6479 			libscf_handle_rebind(h);
6480 			rebound = B_TRUE;
6481 			goto lookup_inst;
6482 
6483 		case ENOENT:
6484 			goto out;
6485 
6486 		case EINVAL:
6487 		case ENOTSUP:
6488 			bad_error("libscf_lookup_instance", r);
6489 		}
6490 	}
6491 
6492 	r = libscf_get_milestone(inst, prop, val, fmri, max_scf_fmri_size);
6493 	switch (r) {
6494 	case 0:
6495 		break;
6496 
6497 	case ECONNABORTED:
6498 		libscf_handle_rebind(h);
6499 		rebound = B_TRUE;
6500 		goto lookup_inst;
6501 
6502 	case EINVAL:
6503 		log_error(LOG_NOTICE,
6504 		    "%s/%s property of %s is misconfigured.\n", pg_name,
6505 		    SCF_PROPERTY_MILESTONE, SCF_SERVICE_STARTD);
6506 		/* FALLTHROUGH */
6507 
6508 	case ECANCELED:
6509 	case ENOENT:
6510 		(void) strcpy(fmri, "all");
6511 		break;
6512 
6513 	default:
6514 		bad_error("libscf_get_milestone", r);
6515 	}
6516 
6517 	r = dgraph_set_milestone(fmri, h, B_FALSE);
6518 	switch (r) {
6519 	case 0:
6520 	case ECONNRESET:
6521 	case EALREADY:
6522 		break;
6523 
6524 	case EINVAL:
6525 		log_error(LOG_WARNING, "Milestone %s is invalid.\n", fmri);
6526 		break;
6527 
6528 	case ENOENT:
6529 		log_error(LOG_WARNING, "Milestone %s does not exist.\n", fmri);
6530 		break;
6531 
6532 	default:
6533 		bad_error("dgraph_set_milestone", r);
6534 	}
6535 
6536 out:
6537 	startd_free(fmri, max_scf_fmri_size);
6538 	scf_value_destroy(val);
6539 	scf_property_destroy(prop);
6540 
6541 	return (rebound ? ECONNRESET : 0);
6542 }
6543 
6544 /*
6545  * process_delete() deletes an instance from the dgraph if 'fmri' is an
6546  * instance fmri or if 'fmri' matches the 'general' property group of an
6547  * instance (or the 'general/enabled' property).
6548  *
6549  * 'fmri' may be overwritten and cannot be trusted on return by the caller.
6550  */
6551 static void
6552 process_delete(char *fmri, scf_handle_t *h)
6553 {
6554 	char *lfmri, *end_inst_fmri;
6555 	const char *inst_name = NULL;
6556 	const char *pg_name = NULL;
6557 	const char *prop_name = NULL;
6558 
6559 	lfmri = safe_strdup(fmri);
6560 
6561 	/* Determine if the FMRI is a property group or instance */
6562 	if (scf_parse_svc_fmri(lfmri, NULL, NULL, &inst_name, &pg_name,
6563 	    &prop_name) != SCF_SUCCESS) {
6564 		log_error(LOG_WARNING,
6565 		    "Received invalid FMRI \"%s\" from repository server.\n",
6566 		    fmri);
6567 	} else if (inst_name != NULL && pg_name == NULL) {
6568 		(void) dgraph_remove_instance(fmri, h);
6569 	} else if (inst_name != NULL && pg_name != NULL) {
6570 		/*
6571 		 * If we're deleting the 'general' property group or
6572 		 * 'general/enabled' property then the whole instance
6573 		 * must be removed from the dgraph.
6574 		 */
6575 		if (strcmp(pg_name, SCF_PG_GENERAL) != 0) {
6576 			free(lfmri);
6577 			return;
6578 		}
6579 
6580 		if (prop_name != NULL &&
6581 		    strcmp(prop_name, SCF_PROPERTY_ENABLED) != 0) {
6582 			free(lfmri);
6583 			return;
6584 		}
6585 
6586 		/*
6587 		 * Because the instance has already been deleted from the
6588 		 * repository, we cannot use any scf_ functions to retrieve
6589 		 * the instance FMRI however we can easily reconstruct it
6590 		 * manually.
6591 		 */
6592 		end_inst_fmri = strstr(fmri, SCF_FMRI_PROPERTYGRP_PREFIX);
6593 		if (end_inst_fmri == NULL)
6594 			bad_error("process_delete", 0);
6595 
6596 		end_inst_fmri[0] = '\0';
6597 
6598 		(void) dgraph_remove_instance(fmri, h);
6599 	}
6600 
6601 	free(lfmri);
6602 }
6603 
6604 /*ARGSUSED*/
6605 void *
6606 repository_event_thread(void *unused)
6607 {
6608 	scf_handle_t *h;
6609 	scf_propertygroup_t *pg;
6610 	scf_instance_t *inst;
6611 	char *fmri = startd_alloc(max_scf_fmri_size);
6612 	char *pg_name = startd_alloc(max_scf_value_size);
6613 	int r;
6614 
6615 	h = libscf_handle_create_bound_loop();
6616 
6617 	pg = safe_scf_pg_create(h);
6618 	inst = safe_scf_instance_create(h);
6619 
6620 retry:
6621 	if (_scf_notify_add_pgtype(h, SCF_GROUP_FRAMEWORK) != SCF_SUCCESS) {
6622 		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN) {
6623 			libscf_handle_rebind(h);
6624 		} else {
6625 			log_error(LOG_WARNING,
6626 			    "Couldn't set up repository notification "
6627 			    "for property group type %s: %s\n",
6628 			    SCF_GROUP_FRAMEWORK, scf_strerror(scf_error()));
6629 
6630 			(void) sleep(1);
6631 		}
6632 
6633 		goto retry;
6634 	}
6635 
6636 	/*CONSTCOND*/
6637 	while (1) {
6638 		ssize_t res;
6639 
6640 		/* Note: fmri is only set on delete events. */
6641 		res = _scf_notify_wait(pg, fmri, max_scf_fmri_size);
6642 		if (res < 0) {
6643 			libscf_handle_rebind(h);
6644 			goto retry;
6645 		} else if (res == 0) {
6646 			/*
6647 			 * property group modified.  inst and pg_name are
6648 			 * pre-allocated scratch space.
6649 			 */
6650 			if (scf_pg_update(pg) < 0) {
6651 				switch (scf_error()) {
6652 				case SCF_ERROR_DELETED:
6653 					continue;
6654 
6655 				case SCF_ERROR_CONNECTION_BROKEN:
6656 					log_error(LOG_WARNING,
6657 					    "Lost repository event due to "
6658 					    "disconnection.\n");
6659 					libscf_handle_rebind(h);
6660 					goto retry;
6661 
6662 				case SCF_ERROR_NOT_BOUND:
6663 				case SCF_ERROR_NOT_SET:
6664 				default:
6665 					bad_error("scf_pg_update", scf_error());
6666 				}
6667 			}
6668 
6669 			r = process_pg_event(h, pg, inst, pg_name);
6670 			switch (r) {
6671 			case 0:
6672 				break;
6673 
6674 			case ECONNABORTED:
6675 				log_error(LOG_WARNING, "Lost repository event "
6676 				    "due to disconnection.\n");
6677 				libscf_handle_rebind(h);
6678 				/* FALLTHROUGH */
6679 
6680 			case ECONNRESET:
6681 				goto retry;
6682 
6683 			default:
6684 				bad_error("process_pg_event", r);
6685 			}
6686 		} else {
6687 			/*
6688 			 * Service, instance, or pg deleted.
6689 			 * Don't trust fmri on return.
6690 			 */
6691 			process_delete(fmri, h);
6692 		}
6693 	}
6694 
6695 	/*NOTREACHED*/
6696 	return (NULL);
6697 }
6698 
6699 void
6700 graph_engine_start()
6701 {
6702 	int err;
6703 
6704 	(void) startd_thread_create(graph_thread, NULL);
6705 
6706 	MUTEX_LOCK(&dgraph_lock);
6707 	while (!initial_milestone_set) {
6708 		err = pthread_cond_wait(&initial_milestone_cv, &dgraph_lock);
6709 		assert(err == 0);
6710 	}
6711 	MUTEX_UNLOCK(&dgraph_lock);
6712 
6713 	(void) startd_thread_create(repository_event_thread, NULL);
6714 	(void) startd_thread_create(graph_event_thread, NULL);
6715 }
6716