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