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