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