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