xref: /titanic_52/usr/src/cmd/svc/startd/graph.c (revision 700c902c445eb3882848aaddc19d13638818cfd6)
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 all the 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);
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 event, or a satisfiability event.
4072  *
4073  * PROPAGATE_START and PROPAGATE_STOP simply propagate the transition event
4074  * to direct dependents.  PROPAGATE_SAT propagates a start then walks the
4075  * full dependent graph to check for newly satisfied nodes.  This is
4076  * necessary for cases when non-direct dependents may be effected but direct
4077  * dependents may not (e.g. for optional_all evaluations, see the
4078  * propagate_satbility() comments).
4079  *
4080  * PROPAGATE_SAT should be used whenever a non-running service moves into
4081  * a state which can satisfy optional dependencies, like disabled or
4082  * maintenance.
4083  */
4084 void
4085 graph_transition_propagate(graph_vertex_t *v, propagate_event_t type,
4086     restarter_error_t rerr)
4087 {
4088 	if (type == PROPAGATE_STOP) {
4089 		graph_walk_dependents(v, propagate_stop, (void *)rerr);
4090 	} else if (type == PROPAGATE_START || type == PROPAGATE_SAT) {
4091 		graph_walk_dependents(v, propagate_start, NULL);
4092 
4093 		if (type == PROPAGATE_SAT)
4094 			propagate_satbility(v);
4095 	} else {
4096 #ifndef NDEBUG
4097 		uu_warn("%s:%d: Unexpected type value %d.\n",  __FILE__,
4098 		    __LINE__, type);
4099 #endif
4100 		abort();
4101 	}
4102 }
4103 
4104 /*
4105  * If a vertex for fmri exists and it is enabled, send _DISABLE to the
4106  * restarter.  If it is running, send _STOP.  Send _REMOVE_INSTANCE.  Delete
4107  * all property group dependencies, and the dependency on the restarter,
4108  * disposing of vertices as appropriate.  If other vertices depend on this
4109  * one, mark it unconfigured and return.  Otherwise remove the vertex.  Always
4110  * returns 0.
4111  */
4112 static int
4113 dgraph_remove_instance(const char *fmri, scf_handle_t *h)
4114 {
4115 	graph_vertex_t *v;
4116 	graph_edge_t *e;
4117 	uu_list_t *old_deps;
4118 	int err;
4119 
4120 	log_framework(LOG_DEBUG, "Graph engine: Removing %s.\n", fmri);
4121 
4122 	MUTEX_LOCK(&dgraph_lock);
4123 
4124 	v = vertex_get_by_name(fmri);
4125 	if (v == NULL) {
4126 		MUTEX_UNLOCK(&dgraph_lock);
4127 		return (0);
4128 	}
4129 
4130 	/* Send restarter delete event. */
4131 	if (v->gv_flags & GV_CONFIGURED)
4132 		graph_unset_restarter(v);
4133 
4134 	if (milestone > MILESTONE_NONE) {
4135 		/*
4136 		 * Make a list of v's current dependencies so we can
4137 		 * reevaluate their GV_INSUBGRAPH flags after the dependencies
4138 		 * are removed.
4139 		 */
4140 		old_deps = startd_list_create(graph_edge_pool, NULL, 0);
4141 
4142 		err = uu_list_walk(v->gv_dependencies,
4143 		    (uu_walk_fn_t *)append_svcs_or_insts, old_deps, 0);
4144 		assert(err == 0);
4145 	}
4146 
4147 	delete_instance_dependencies(v, B_TRUE);
4148 
4149 	/*
4150 	 * Deleting an instance can both satisfy and unsatisfy dependencies,
4151 	 * depending on their type.  First propagate the stop as a RERR_RESTART
4152 	 * event -- deletion isn't a fault, just a normal stop.  This gives
4153 	 * dependent services the chance to do a clean shutdown.  Then, mark
4154 	 * the service as unconfigured and propagate the start event for the
4155 	 * optional_all dependencies that might have become satisfied.
4156 	 */
4157 	graph_walk_dependents(v, propagate_stop, (void *)RERR_RESTART);
4158 
4159 	v->gv_flags &= ~GV_CONFIGURED;
4160 
4161 	graph_walk_dependents(v, propagate_start, NULL);
4162 	propagate_satbility(v);
4163 
4164 	/*
4165 	 * If there are no (non-service) dependents, the vertex can be
4166 	 * completely removed.
4167 	 */
4168 	if (v != milestone && v->gv_refs == 0 &&
4169 	    uu_list_numnodes(v->gv_dependents) == 1)
4170 		remove_inst_vertex(v);
4171 
4172 	if (milestone > MILESTONE_NONE) {
4173 		void *cookie = NULL;
4174 
4175 		while ((e = uu_list_teardown(old_deps, &cookie)) != NULL) {
4176 			v = e->ge_vertex;
4177 
4178 			if (vertex_unref(v) == VERTEX_INUSE)
4179 				while (eval_subgraph(v, h) == ECONNABORTED)
4180 					libscf_handle_rebind(h);
4181 
4182 			startd_free(e, sizeof (*e));
4183 		}
4184 
4185 		uu_list_destroy(old_deps);
4186 	}
4187 
4188 	MUTEX_UNLOCK(&dgraph_lock);
4189 
4190 	return (0);
4191 }
4192 
4193 /*
4194  * Return the eventual (maybe current) milestone in the form of a
4195  * legacy runlevel.
4196  */
4197 static char
4198 target_milestone_as_runlevel()
4199 {
4200 	assert(PTHREAD_MUTEX_HELD(&dgraph_lock));
4201 
4202 	if (milestone == NULL)
4203 		return ('3');
4204 	else if (milestone == MILESTONE_NONE)
4205 		return ('0');
4206 
4207 	if (strcmp(milestone->gv_name, multi_user_fmri) == 0)
4208 		return ('2');
4209 	else if (strcmp(milestone->gv_name, single_user_fmri) == 0)
4210 		return ('S');
4211 	else if (strcmp(milestone->gv_name, multi_user_svr_fmri) == 0)
4212 		return ('3');
4213 
4214 #ifndef NDEBUG
4215 	(void) fprintf(stderr, "%s:%d: Unknown milestone name \"%s\".\n",
4216 	    __FILE__, __LINE__, milestone->gv_name);
4217 #endif
4218 	abort();
4219 	/* NOTREACHED */
4220 }
4221 
4222 static struct {
4223 	char	rl;
4224 	int	sig;
4225 } init_sigs[] = {
4226 	{ 'S', SIGBUS },
4227 	{ '0', SIGINT },
4228 	{ '1', SIGQUIT },
4229 	{ '2', SIGILL },
4230 	{ '3', SIGTRAP },
4231 	{ '4', SIGIOT },
4232 	{ '5', SIGEMT },
4233 	{ '6', SIGFPE },
4234 	{ 0, 0 }
4235 };
4236 
4237 static void
4238 signal_init(char rl)
4239 {
4240 	pid_t init_pid;
4241 	int i;
4242 
4243 	assert(PTHREAD_MUTEX_HELD(&dgraph_lock));
4244 
4245 	if (zone_getattr(getzoneid(), ZONE_ATTR_INITPID, &init_pid,
4246 	    sizeof (init_pid)) != sizeof (init_pid)) {
4247 		log_error(LOG_NOTICE, "Could not get pid to signal init.\n");
4248 		return;
4249 	}
4250 
4251 	for (i = 0; init_sigs[i].rl != 0; ++i)
4252 		if (init_sigs[i].rl == rl)
4253 			break;
4254 
4255 	if (init_sigs[i].rl != 0) {
4256 		if (kill(init_pid, init_sigs[i].sig) != 0) {
4257 			switch (errno) {
4258 			case EPERM:
4259 			case ESRCH:
4260 				log_error(LOG_NOTICE, "Could not signal init: "
4261 				    "%s.\n", strerror(errno));
4262 				break;
4263 
4264 			case EINVAL:
4265 			default:
4266 				bad_error("kill", errno);
4267 			}
4268 		}
4269 	}
4270 }
4271 
4272 /*
4273  * This is called when one of the major milestones changes state, or when
4274  * init is signalled and tells us it was told to change runlevel.  We wait
4275  * to reach the milestone because this allows /etc/inittab entries to retain
4276  * some boot ordering: historically, entries could place themselves before/after
4277  * the running of /sbin/rcX scripts but we can no longer make the
4278  * distinction because the /sbin/rcX scripts no longer exist as punctuation
4279  * marks in /etc/inittab.
4280  *
4281  * Also, we only trigger an update when we reach the eventual target
4282  * milestone: without this, an /etc/inittab entry marked only for
4283  * runlevel 2 would be executed for runlevel 3, which is not how
4284  * /etc/inittab entries work.
4285  *
4286  * If we're single user coming online, then we set utmpx to the target
4287  * runlevel so that legacy scripts can work as expected.
4288  */
4289 static void
4290 graph_runlevel_changed(char rl, int online)
4291 {
4292 	char trl;
4293 
4294 	assert(PTHREAD_MUTEX_HELD(&dgraph_lock));
4295 
4296 	trl = target_milestone_as_runlevel();
4297 
4298 	if (online) {
4299 		if (rl == trl) {
4300 			current_runlevel = trl;
4301 			signal_init(trl);
4302 		} else if (rl == 'S') {
4303 			/*
4304 			 * At boot, set the entry early for the benefit of the
4305 			 * legacy init scripts.
4306 			 */
4307 			utmpx_set_runlevel(trl, 'S', B_FALSE);
4308 		}
4309 	} else {
4310 		if (rl == '3' && trl == '2') {
4311 			current_runlevel = trl;
4312 			signal_init(trl);
4313 		} else if (rl == '2' && trl == 'S') {
4314 			current_runlevel = trl;
4315 			signal_init(trl);
4316 		}
4317 	}
4318 }
4319 
4320 /*
4321  * Move to a backwards-compatible runlevel by executing the appropriate
4322  * /etc/rc?.d/K* scripts and/or setting the milestone.
4323  *
4324  * Returns
4325  *   0 - success
4326  *   ECONNRESET - success, but handle was reset
4327  *   ECONNABORTED - repository connection broken
4328  *   ECANCELED - pg was deleted
4329  */
4330 static int
4331 dgraph_set_runlevel(scf_propertygroup_t *pg, scf_property_t *prop)
4332 {
4333 	char rl;
4334 	scf_handle_t *h;
4335 	int r;
4336 	const char *ms = NULL;	/* what to commit as options/milestone */
4337 	boolean_t rebound = B_FALSE;
4338 	int mark_rl = 0;
4339 
4340 	const char * const stop = "stop";
4341 
4342 	r = libscf_extract_runlevel(prop, &rl);
4343 	switch (r) {
4344 	case 0:
4345 		break;
4346 
4347 	case ECONNABORTED:
4348 	case ECANCELED:
4349 		return (r);
4350 
4351 	case EINVAL:
4352 	case ENOENT:
4353 		log_error(LOG_WARNING, "runlevel property is misconfigured; "
4354 		    "ignoring.\n");
4355 		/* delete the bad property */
4356 		goto nolock_out;
4357 
4358 	default:
4359 		bad_error("libscf_extract_runlevel", r);
4360 	}
4361 
4362 	switch (rl) {
4363 	case 's':
4364 		rl = 'S';
4365 		/* FALLTHROUGH */
4366 
4367 	case 'S':
4368 	case '2':
4369 	case '3':
4370 		/*
4371 		 * These cases cause a milestone change, so
4372 		 * graph_runlevel_changed() will eventually deal with
4373 		 * signalling init.
4374 		 */
4375 		break;
4376 
4377 	case '0':
4378 	case '1':
4379 	case '4':
4380 	case '5':
4381 	case '6':
4382 		mark_rl = 1;
4383 		break;
4384 
4385 	default:
4386 		log_framework(LOG_NOTICE, "Unknown runlevel '%c'.\n", rl);
4387 		ms = NULL;
4388 		goto nolock_out;
4389 	}
4390 
4391 	h = scf_pg_handle(pg);
4392 
4393 	MUTEX_LOCK(&dgraph_lock);
4394 
4395 	/*
4396 	 * Since this triggers no milestone changes, force it by hand.
4397 	 */
4398 	if (current_runlevel == '4' && rl == '3')
4399 		mark_rl = 1;
4400 
4401 	/*
4402 	 * 1. If we are here after an "init X":
4403 	 *
4404 	 * init X
4405 	 *	init/lscf_set_runlevel()
4406 	 *		process_pg_event()
4407 	 *		dgraph_set_runlevel()
4408 	 *
4409 	 * then we haven't passed through graph_runlevel_changed() yet,
4410 	 * therefore 'current_runlevel' has not changed for sure but 'rl' has.
4411 	 * In consequence, if 'rl' is lower than 'current_runlevel', we change
4412 	 * the system runlevel and execute the appropriate /etc/rc?.d/K* scripts
4413 	 * past this test.
4414 	 *
4415 	 * 2. On the other hand, if we are here after a "svcadm milestone":
4416 	 *
4417 	 * svcadm milestone X
4418 	 *	dgraph_set_milestone()
4419 	 *		handle_graph_update_event()
4420 	 *		dgraph_set_instance_state()
4421 	 *		graph_post_X_[online|offline]()
4422 	 *		graph_runlevel_changed()
4423 	 *		signal_init()
4424 	 *			init/lscf_set_runlevel()
4425 	 *				process_pg_event()
4426 	 *				dgraph_set_runlevel()
4427 	 *
4428 	 * then we already passed through graph_runlevel_changed() (by the way
4429 	 * of dgraph_set_milestone()) and 'current_runlevel' may have changed
4430 	 * and already be equal to 'rl' so we are going to return immediately
4431 	 * from dgraph_set_runlevel() without changing the system runlevel and
4432 	 * without executing the /etc/rc?.d/K* scripts.
4433 	 */
4434 	if (rl == current_runlevel) {
4435 		ms = NULL;
4436 		goto out;
4437 	}
4438 
4439 	log_framework(LOG_DEBUG, "Changing to runlevel '%c'.\n", rl);
4440 
4441 	/*
4442 	 * Make sure stop rc scripts see the new settings via who -r.
4443 	 */
4444 	utmpx_set_runlevel(rl, current_runlevel, B_TRUE);
4445 
4446 	/*
4447 	 * Some run levels don't have a direct correspondence to any
4448 	 * milestones, so we have to signal init directly.
4449 	 */
4450 	if (mark_rl) {
4451 		current_runlevel = rl;
4452 		signal_init(rl);
4453 	}
4454 
4455 	switch (rl) {
4456 	case 'S':
4457 		uu_warn("The system is coming down for administration.  "
4458 		    "Please wait.\n");
4459 		fork_rc_script(rl, stop, B_FALSE);
4460 		ms = single_user_fmri;
4461 		go_single_user_mode = B_TRUE;
4462 		break;
4463 
4464 	case '0':
4465 		fork_rc_script(rl, stop, B_TRUE);
4466 		halting = AD_HALT;
4467 		goto uadmin;
4468 
4469 	case '5':
4470 		fork_rc_script(rl, stop, B_TRUE);
4471 		halting = AD_POWEROFF;
4472 		goto uadmin;
4473 
4474 	case '6':
4475 		fork_rc_script(rl, stop, B_TRUE);
4476 		halting = AD_BOOT;
4477 		goto uadmin;
4478 
4479 uadmin:
4480 		uu_warn("The system is coming down.  Please wait.\n");
4481 		ms = "none";
4482 
4483 		/*
4484 		 * We can't wait until all services are offline since this
4485 		 * thread is responsible for taking them offline.  Instead we
4486 		 * set halting to the second argument for uadmin() and call
4487 		 * do_uadmin() from dgraph_set_instance_state() when
4488 		 * appropriate.
4489 		 */
4490 		break;
4491 
4492 	case '1':
4493 		if (current_runlevel != 'S') {
4494 			uu_warn("Changing to state 1.\n");
4495 			fork_rc_script(rl, stop, B_FALSE);
4496 		} else {
4497 			uu_warn("The system is coming up for administration.  "
4498 			    "Please wait.\n");
4499 		}
4500 		ms = single_user_fmri;
4501 		go_to_level1 = B_TRUE;
4502 		break;
4503 
4504 	case '2':
4505 		if (current_runlevel == '3' || current_runlevel == '4')
4506 			fork_rc_script(rl, stop, B_FALSE);
4507 		ms = multi_user_fmri;
4508 		break;
4509 
4510 	case '3':
4511 	case '4':
4512 		ms = "all";
4513 		break;
4514 
4515 	default:
4516 #ifndef NDEBUG
4517 		(void) fprintf(stderr, "%s:%d: Uncaught case %d ('%c').\n",
4518 		    __FILE__, __LINE__, rl, rl);
4519 #endif
4520 		abort();
4521 	}
4522 
4523 out:
4524 	MUTEX_UNLOCK(&dgraph_lock);
4525 
4526 nolock_out:
4527 	switch (r = libscf_clear_runlevel(pg, ms)) {
4528 	case 0:
4529 		break;
4530 
4531 	case ECONNABORTED:
4532 		libscf_handle_rebind(h);
4533 		rebound = B_TRUE;
4534 		goto nolock_out;
4535 
4536 	case ECANCELED:
4537 		break;
4538 
4539 	case EPERM:
4540 	case EACCES:
4541 	case EROFS:
4542 		log_error(LOG_NOTICE, "Could not delete \"%s/%s\" property: "
4543 		    "%s.\n", SCF_PG_OPTIONS, "runlevel", strerror(r));
4544 		break;
4545 
4546 	default:
4547 		bad_error("libscf_clear_runlevel", r);
4548 	}
4549 
4550 	return (rebound ? ECONNRESET : 0);
4551 }
4552 
4553 static int
4554 mark_subgraph(graph_edge_t *e, void *arg)
4555 {
4556 	graph_vertex_t *v;
4557 	int r;
4558 	int optional = (int)arg;
4559 
4560 	v = e->ge_vertex;
4561 
4562 	/* If it's already in the subgraph, skip. */
4563 	if (v->gv_flags & GV_INSUBGRAPH)
4564 		return (UU_WALK_NEXT);
4565 
4566 	/*
4567 	 * Keep track if walk has entered an optional dependency group
4568 	 */
4569 	if (v->gv_type == GVT_GROUP && v->gv_depgroup == DEPGRP_OPTIONAL_ALL) {
4570 		optional = 1;
4571 	}
4572 	/*
4573 	 * Quit if we are in an optional dependency group and the instance
4574 	 * is disabled
4575 	 */
4576 	if (optional && (v->gv_type == GVT_INST) &&
4577 	    (!(v->gv_flags & GV_ENBLD_NOOVR)))
4578 		return (UU_WALK_NEXT);
4579 
4580 	v->gv_flags |= GV_INSUBGRAPH;
4581 
4582 	/* Skip all excluded dependencies. */
4583 	if (v->gv_type == GVT_GROUP && v->gv_depgroup == DEPGRP_EXCLUDE_ALL)
4584 		return (UU_WALK_NEXT);
4585 
4586 	r = uu_list_walk(v->gv_dependencies, (uu_walk_fn_t *)mark_subgraph,
4587 	    (void *)optional, 0);
4588 	assert(r == 0);
4589 	return (UU_WALK_NEXT);
4590 }
4591 
4592 /*
4593  * "Restrict" the graph to dependencies of fmri.  We implement it by walking
4594  * all services, override-disabling those which are not descendents of the
4595  * instance, and removing any enable-override for the rest.  milestone is set
4596  * to the vertex which represents fmri so that the other graph operations may
4597  * act appropriately.
4598  *
4599  * If norepository is true, the function will not change the repository.
4600  *
4601  * The decision to change the system run level in accordance with the milestone
4602  * is taken in dgraph_set_runlevel().
4603  *
4604  * Returns
4605  *   0 - success
4606  *   ECONNRESET - success, but handle was rebound
4607  *   EINVAL - fmri is invalid (error is logged)
4608  *   EALREADY - the milestone is already set to fmri
4609  *   ENOENT - a configured vertex does not exist for fmri (an error is logged)
4610  */
4611 static int
4612 dgraph_set_milestone(const char *fmri, scf_handle_t *h, boolean_t norepository)
4613 {
4614 	const char *cfmri, *fs;
4615 	graph_vertex_t *nm, *v;
4616 	int ret = 0, r;
4617 	scf_instance_t *inst;
4618 	boolean_t isall, isnone, rebound = B_FALSE;
4619 
4620 	/* Validate fmri */
4621 	isall = (strcmp(fmri, "all") == 0);
4622 	isnone = (strcmp(fmri, "none") == 0);
4623 
4624 	if (!isall && !isnone) {
4625 		if (fmri_canonify(fmri, (char **)&cfmri, B_FALSE) == EINVAL)
4626 			goto reject;
4627 
4628 		if (strcmp(cfmri, single_user_fmri) != 0 &&
4629 		    strcmp(cfmri, multi_user_fmri) != 0 &&
4630 		    strcmp(cfmri, multi_user_svr_fmri) != 0) {
4631 			startd_free((void *)cfmri, max_scf_fmri_size);
4632 reject:
4633 			log_framework(LOG_WARNING,
4634 			    "Rejecting request for invalid milestone \"%s\".\n",
4635 			    fmri);
4636 			return (EINVAL);
4637 		}
4638 	}
4639 
4640 	inst = safe_scf_instance_create(h);
4641 
4642 	MUTEX_LOCK(&dgraph_lock);
4643 
4644 	if (milestone == NULL) {
4645 		if (isall) {
4646 			log_framework(LOG_DEBUG,
4647 			    "Milestone already set to all.\n");
4648 			ret = EALREADY;
4649 			goto out;
4650 		}
4651 	} else if (milestone == MILESTONE_NONE) {
4652 		if (isnone) {
4653 			log_framework(LOG_DEBUG,
4654 			    "Milestone already set to none.\n");
4655 			ret = EALREADY;
4656 			goto out;
4657 		}
4658 	} else {
4659 		if (!isall && !isnone &&
4660 		    strcmp(cfmri, milestone->gv_name) == 0) {
4661 			log_framework(LOG_DEBUG,
4662 			    "Milestone already set to %s.\n", cfmri);
4663 			ret = EALREADY;
4664 			goto out;
4665 		}
4666 	}
4667 
4668 	if (!isall && !isnone) {
4669 		nm = vertex_get_by_name(cfmri);
4670 		if (nm == NULL || !(nm->gv_flags & GV_CONFIGURED)) {
4671 			log_framework(LOG_WARNING, "Cannot set milestone to %s "
4672 			    "because no such service exists.\n", cfmri);
4673 			ret = ENOENT;
4674 			goto out;
4675 		}
4676 	}
4677 
4678 	log_framework(LOG_DEBUG, "Changing milestone to %s.\n", fmri);
4679 
4680 	/*
4681 	 * Set milestone, removing the old one if this was the last reference.
4682 	 */
4683 	if (milestone > MILESTONE_NONE)
4684 		(void) vertex_unref(milestone);
4685 
4686 	if (isall)
4687 		milestone = NULL;
4688 	else if (isnone)
4689 		milestone = MILESTONE_NONE;
4690 	else {
4691 		milestone = nm;
4692 		/* milestone should count as a reference */
4693 		vertex_ref(milestone);
4694 	}
4695 
4696 	/* Clear all GV_INSUBGRAPH bits. */
4697 	for (v = uu_list_first(dgraph); v != NULL; v = uu_list_next(dgraph, v))
4698 		v->gv_flags &= ~GV_INSUBGRAPH;
4699 
4700 	if (!isall && !isnone) {
4701 		/* Set GV_INSUBGRAPH for milestone & descendents. */
4702 		milestone->gv_flags |= GV_INSUBGRAPH;
4703 
4704 		r = uu_list_walk(milestone->gv_dependencies,
4705 		    (uu_walk_fn_t *)mark_subgraph, NULL, 0);
4706 		assert(r == 0);
4707 	}
4708 
4709 	/* Un-override services in the subgraph & override-disable the rest. */
4710 	if (norepository)
4711 		goto out;
4712 
4713 	non_subgraph_svcs = 0;
4714 	for (v = uu_list_first(dgraph);
4715 	    v != NULL;
4716 	    v = uu_list_next(dgraph, v)) {
4717 		if (v->gv_type != GVT_INST ||
4718 		    (v->gv_flags & GV_CONFIGURED) == 0)
4719 			continue;
4720 
4721 again:
4722 		r = scf_handle_decode_fmri(h, v->gv_name, NULL, NULL, inst,
4723 		    NULL, NULL, SCF_DECODE_FMRI_EXACT);
4724 		if (r != 0) {
4725 			switch (scf_error()) {
4726 			case SCF_ERROR_CONNECTION_BROKEN:
4727 			default:
4728 				libscf_handle_rebind(h);
4729 				rebound = B_TRUE;
4730 				goto again;
4731 
4732 			case SCF_ERROR_NOT_FOUND:
4733 				continue;
4734 
4735 			case SCF_ERROR_HANDLE_MISMATCH:
4736 			case SCF_ERROR_INVALID_ARGUMENT:
4737 			case SCF_ERROR_CONSTRAINT_VIOLATED:
4738 			case SCF_ERROR_NOT_BOUND:
4739 				bad_error("scf_handle_decode_fmri",
4740 				    scf_error());
4741 			}
4742 		}
4743 
4744 		if (isall || (v->gv_flags & GV_INSUBGRAPH)) {
4745 			r = libscf_delete_enable_ovr(inst);
4746 			fs = "libscf_delete_enable_ovr";
4747 		} else {
4748 			assert(isnone || (v->gv_flags & GV_INSUBGRAPH) == 0);
4749 
4750 			if (inst_running(v))
4751 				++non_subgraph_svcs;
4752 
4753 			if (has_running_nonsubgraph_dependents(v))
4754 				continue;
4755 
4756 			r = libscf_set_enable_ovr(inst, 0);
4757 			fs = "libscf_set_enable_ovr";
4758 		}
4759 		switch (r) {
4760 		case 0:
4761 		case ECANCELED:
4762 			break;
4763 
4764 		case ECONNABORTED:
4765 			libscf_handle_rebind(h);
4766 			rebound = B_TRUE;
4767 			goto again;
4768 
4769 		case EPERM:
4770 		case EROFS:
4771 			log_error(LOG_WARNING,
4772 			    "Could not set %s/%s for %s: %s.\n",
4773 			    SCF_PG_GENERAL_OVR, SCF_PROPERTY_ENABLED,
4774 			    v->gv_name, strerror(r));
4775 			break;
4776 
4777 		default:
4778 			bad_error(fs, r);
4779 		}
4780 	}
4781 
4782 	if (halting != -1) {
4783 		if (non_subgraph_svcs > 1)
4784 			uu_warn("%d system services are now being stopped.\n",
4785 			    non_subgraph_svcs);
4786 		else if (non_subgraph_svcs == 1)
4787 			uu_warn("One system service is now being stopped.\n");
4788 		else if (non_subgraph_svcs == 0)
4789 			do_uadmin();
4790 	}
4791 
4792 	ret = rebound ? ECONNRESET : 0;
4793 
4794 out:
4795 	MUTEX_UNLOCK(&dgraph_lock);
4796 	if (!isall && !isnone)
4797 		startd_free((void *)cfmri, max_scf_fmri_size);
4798 	scf_instance_destroy(inst);
4799 	return (ret);
4800 }
4801 
4802 
4803 /*
4804  * Returns 0, ECONNABORTED, or EINVAL.
4805  */
4806 static int
4807 handle_graph_update_event(scf_handle_t *h, graph_protocol_event_t *e)
4808 {
4809 	int r;
4810 
4811 	switch (e->gpe_type) {
4812 	case GRAPH_UPDATE_RELOAD_GRAPH:
4813 		log_error(LOG_WARNING,
4814 		    "graph_event: reload graph unimplemented\n");
4815 		break;
4816 
4817 	case GRAPH_UPDATE_STATE_CHANGE: {
4818 		protocol_states_t *states = e->gpe_data;
4819 
4820 		switch (r = dgraph_set_instance_state(h, e->gpe_inst,
4821 		    states->ps_state, states->ps_err)) {
4822 		case 0:
4823 		case ENOENT:
4824 			break;
4825 
4826 		case ECONNABORTED:
4827 			return (ECONNABORTED);
4828 
4829 		case EINVAL:
4830 		default:
4831 #ifndef NDEBUG
4832 			(void) fprintf(stderr, "dgraph_set_instance_state() "
4833 			    "failed with unexpected error %d at %s:%d.\n", r,
4834 			    __FILE__, __LINE__);
4835 #endif
4836 			abort();
4837 		}
4838 
4839 		startd_free(states, sizeof (protocol_states_t));
4840 		break;
4841 	}
4842 
4843 	default:
4844 		log_error(LOG_WARNING,
4845 		    "graph_event_loop received an unknown event: %d\n",
4846 		    e->gpe_type);
4847 		break;
4848 	}
4849 
4850 	return (0);
4851 }
4852 
4853 /*
4854  * graph_event_thread()
4855  *    Wait for state changes from the restarters.
4856  */
4857 /*ARGSUSED*/
4858 void *
4859 graph_event_thread(void *unused)
4860 {
4861 	scf_handle_t *h;
4862 	int err;
4863 
4864 	h = libscf_handle_create_bound_loop();
4865 
4866 	/*CONSTCOND*/
4867 	while (1) {
4868 		graph_protocol_event_t *e;
4869 
4870 		MUTEX_LOCK(&gu->gu_lock);
4871 
4872 		while (gu->gu_wakeup == 0)
4873 			(void) pthread_cond_wait(&gu->gu_cv, &gu->gu_lock);
4874 
4875 		gu->gu_wakeup = 0;
4876 
4877 		while ((e = graph_event_dequeue()) != NULL) {
4878 			MUTEX_LOCK(&e->gpe_lock);
4879 			MUTEX_UNLOCK(&gu->gu_lock);
4880 
4881 			while ((err = handle_graph_update_event(h, e)) ==
4882 			    ECONNABORTED)
4883 				libscf_handle_rebind(h);
4884 
4885 			if (err == 0)
4886 				graph_event_release(e);
4887 			else
4888 				graph_event_requeue(e);
4889 
4890 			MUTEX_LOCK(&gu->gu_lock);
4891 		}
4892 
4893 		MUTEX_UNLOCK(&gu->gu_lock);
4894 	}
4895 
4896 	/*
4897 	 * Unreachable for now -- there's currently no graceful cleanup
4898 	 * called on exit().
4899 	 */
4900 	MUTEX_UNLOCK(&gu->gu_lock);
4901 	scf_handle_destroy(h);
4902 	return (NULL);
4903 }
4904 
4905 static void
4906 set_initial_milestone(scf_handle_t *h)
4907 {
4908 	scf_instance_t *inst;
4909 	char *fmri, *cfmri;
4910 	size_t sz;
4911 	int r;
4912 
4913 	inst = safe_scf_instance_create(h);
4914 	fmri = startd_alloc(max_scf_fmri_size);
4915 
4916 	/*
4917 	 * If -m milestone= was specified, we want to set options_ovr/milestone
4918 	 * to it.  Otherwise we want to read what the milestone should be set
4919 	 * to.  Either way we need our inst.
4920 	 */
4921 get_self:
4922 	if (scf_handle_decode_fmri(h, SCF_SERVICE_STARTD, NULL, NULL, inst,
4923 	    NULL, NULL, SCF_DECODE_FMRI_EXACT) != 0) {
4924 		switch (scf_error()) {
4925 		case SCF_ERROR_CONNECTION_BROKEN:
4926 			libscf_handle_rebind(h);
4927 			goto get_self;
4928 
4929 		case SCF_ERROR_NOT_FOUND:
4930 			if (st->st_subgraph != NULL &&
4931 			    st->st_subgraph[0] != '\0') {
4932 				sz = strlcpy(fmri, st->st_subgraph,
4933 				    max_scf_fmri_size);
4934 				assert(sz < max_scf_fmri_size);
4935 			} else {
4936 				fmri[0] = '\0';
4937 			}
4938 			break;
4939 
4940 		case SCF_ERROR_INVALID_ARGUMENT:
4941 		case SCF_ERROR_CONSTRAINT_VIOLATED:
4942 		case SCF_ERROR_HANDLE_MISMATCH:
4943 		default:
4944 			bad_error("scf_handle_decode_fmri", scf_error());
4945 		}
4946 	} else {
4947 		if (st->st_subgraph != NULL && st->st_subgraph[0] != '\0') {
4948 			scf_propertygroup_t *pg;
4949 
4950 			pg = safe_scf_pg_create(h);
4951 
4952 			sz = strlcpy(fmri, st->st_subgraph, max_scf_fmri_size);
4953 			assert(sz < max_scf_fmri_size);
4954 
4955 			r = libscf_inst_get_or_add_pg(inst, SCF_PG_OPTIONS_OVR,
4956 			    SCF_PG_OPTIONS_OVR_TYPE, SCF_PG_OPTIONS_OVR_FLAGS,
4957 			    pg);
4958 			switch (r) {
4959 			case 0:
4960 				break;
4961 
4962 			case ECONNABORTED:
4963 				libscf_handle_rebind(h);
4964 				goto get_self;
4965 
4966 			case EPERM:
4967 			case EACCES:
4968 			case EROFS:
4969 				log_error(LOG_WARNING, "Could not set %s/%s: "
4970 				    "%s.\n", SCF_PG_OPTIONS_OVR,
4971 				    SCF_PROPERTY_MILESTONE, strerror(r));
4972 				/* FALLTHROUGH */
4973 
4974 			case ECANCELED:
4975 				sz = strlcpy(fmri, st->st_subgraph,
4976 				    max_scf_fmri_size);
4977 				assert(sz < max_scf_fmri_size);
4978 				break;
4979 
4980 			default:
4981 				bad_error("libscf_inst_get_or_add_pg", r);
4982 			}
4983 
4984 			r = libscf_clear_runlevel(pg, fmri);
4985 			switch (r) {
4986 			case 0:
4987 				break;
4988 
4989 			case ECONNABORTED:
4990 				libscf_handle_rebind(h);
4991 				goto get_self;
4992 
4993 			case EPERM:
4994 			case EACCES:
4995 			case EROFS:
4996 				log_error(LOG_WARNING, "Could not set %s/%s: "
4997 				    "%s.\n", SCF_PG_OPTIONS_OVR,
4998 				    SCF_PROPERTY_MILESTONE, strerror(r));
4999 				/* FALLTHROUGH */
5000 
5001 			case ECANCELED:
5002 				sz = strlcpy(fmri, st->st_subgraph,
5003 				    max_scf_fmri_size);
5004 				assert(sz < max_scf_fmri_size);
5005 				break;
5006 
5007 			default:
5008 				bad_error("libscf_clear_runlevel", r);
5009 			}
5010 
5011 			scf_pg_destroy(pg);
5012 		} else {
5013 			scf_property_t *prop;
5014 			scf_value_t *val;
5015 
5016 			prop = safe_scf_property_create(h);
5017 			val = safe_scf_value_create(h);
5018 
5019 			r = libscf_get_milestone(inst, prop, val, fmri,
5020 			    max_scf_fmri_size);
5021 			switch (r) {
5022 			case 0:
5023 				break;
5024 
5025 			case ECONNABORTED:
5026 				libscf_handle_rebind(h);
5027 				goto get_self;
5028 
5029 			case EINVAL:
5030 				log_error(LOG_WARNING, "Milestone property is "
5031 				    "misconfigured.  Defaulting to \"all\".\n");
5032 				/* FALLTHROUGH */
5033 
5034 			case ECANCELED:
5035 			case ENOENT:
5036 				fmri[0] = '\0';
5037 				break;
5038 
5039 			default:
5040 				bad_error("libscf_get_milestone", r);
5041 			}
5042 
5043 			scf_value_destroy(val);
5044 			scf_property_destroy(prop);
5045 		}
5046 	}
5047 
5048 	if (fmri[0] == '\0' || strcmp(fmri, "all") == 0)
5049 		goto out;
5050 
5051 	if (strcmp(fmri, "none") != 0) {
5052 retry:
5053 		if (scf_handle_decode_fmri(h, fmri, NULL, NULL, inst, NULL,
5054 		    NULL, SCF_DECODE_FMRI_EXACT) != 0) {
5055 			switch (scf_error()) {
5056 			case SCF_ERROR_INVALID_ARGUMENT:
5057 				log_error(LOG_WARNING,
5058 				    "Requested milestone \"%s\" is invalid.  "
5059 				    "Reverting to \"all\".\n", fmri);
5060 				goto out;
5061 
5062 			case SCF_ERROR_CONSTRAINT_VIOLATED:
5063 				log_error(LOG_WARNING, "Requested milestone "
5064 				    "\"%s\" does not specify an instance.  "
5065 				    "Reverting to \"all\".\n", fmri);
5066 				goto out;
5067 
5068 			case SCF_ERROR_CONNECTION_BROKEN:
5069 				libscf_handle_rebind(h);
5070 				goto retry;
5071 
5072 			case SCF_ERROR_NOT_FOUND:
5073 				log_error(LOG_WARNING, "Requested milestone "
5074 				    "\"%s\" not in repository.  Reverting to "
5075 				    "\"all\".\n", fmri);
5076 				goto out;
5077 
5078 			case SCF_ERROR_HANDLE_MISMATCH:
5079 			default:
5080 				bad_error("scf_handle_decode_fmri",
5081 				    scf_error());
5082 			}
5083 		}
5084 
5085 		r = fmri_canonify(fmri, &cfmri, B_FALSE);
5086 		assert(r == 0);
5087 
5088 		r = dgraph_add_instance(cfmri, inst, B_TRUE);
5089 		startd_free(cfmri, max_scf_fmri_size);
5090 		switch (r) {
5091 		case 0:
5092 			break;
5093 
5094 		case ECONNABORTED:
5095 			goto retry;
5096 
5097 		case EINVAL:
5098 			log_error(LOG_WARNING,
5099 			    "Requested milestone \"%s\" is invalid.  "
5100 			    "Reverting to \"all\".\n", fmri);
5101 			goto out;
5102 
5103 		case ECANCELED:
5104 			log_error(LOG_WARNING,
5105 			    "Requested milestone \"%s\" not "
5106 			    "in repository.  Reverting to \"all\".\n",
5107 			    fmri);
5108 			goto out;
5109 
5110 		case EEXIST:
5111 		default:
5112 			bad_error("dgraph_add_instance", r);
5113 		}
5114 	}
5115 
5116 	log_console(LOG_INFO, "Booting to milestone \"%s\".\n", fmri);
5117 
5118 	r = dgraph_set_milestone(fmri, h, B_FALSE);
5119 	switch (r) {
5120 	case 0:
5121 	case ECONNRESET:
5122 	case EALREADY:
5123 		break;
5124 
5125 	case EINVAL:
5126 	case ENOENT:
5127 	default:
5128 		bad_error("dgraph_set_milestone", r);
5129 	}
5130 
5131 out:
5132 	startd_free(fmri, max_scf_fmri_size);
5133 	scf_instance_destroy(inst);
5134 }
5135 
5136 void
5137 set_restart_milestone(scf_handle_t *h)
5138 {
5139 	scf_instance_t *inst;
5140 	scf_property_t *prop;
5141 	scf_value_t *val;
5142 	char *fmri;
5143 	int r;
5144 
5145 	inst = safe_scf_instance_create(h);
5146 
5147 get_self:
5148 	if (scf_handle_decode_fmri(h, SCF_SERVICE_STARTD, NULL, NULL,
5149 	    inst, NULL, NULL, SCF_DECODE_FMRI_EXACT) != 0) {
5150 		switch (scf_error()) {
5151 		case SCF_ERROR_CONNECTION_BROKEN:
5152 			libscf_handle_rebind(h);
5153 			goto get_self;
5154 
5155 		case SCF_ERROR_NOT_FOUND:
5156 			break;
5157 
5158 		case SCF_ERROR_INVALID_ARGUMENT:
5159 		case SCF_ERROR_CONSTRAINT_VIOLATED:
5160 		case SCF_ERROR_HANDLE_MISMATCH:
5161 		default:
5162 			bad_error("scf_handle_decode_fmri", scf_error());
5163 		}
5164 
5165 		scf_instance_destroy(inst);
5166 		return;
5167 	}
5168 
5169 	prop = safe_scf_property_create(h);
5170 	val = safe_scf_value_create(h);
5171 	fmri = startd_alloc(max_scf_fmri_size);
5172 
5173 	r = libscf_get_milestone(inst, prop, val, fmri, max_scf_fmri_size);
5174 	switch (r) {
5175 	case 0:
5176 		break;
5177 
5178 	case ECONNABORTED:
5179 		libscf_handle_rebind(h);
5180 		goto get_self;
5181 
5182 	case ECANCELED:
5183 	case ENOENT:
5184 	case EINVAL:
5185 		goto out;
5186 
5187 	default:
5188 		bad_error("libscf_get_milestone", r);
5189 	}
5190 
5191 	r = dgraph_set_milestone(fmri, h, B_TRUE);
5192 	switch (r) {
5193 	case 0:
5194 	case ECONNRESET:
5195 	case EALREADY:
5196 	case EINVAL:
5197 	case ENOENT:
5198 		break;
5199 
5200 	default:
5201 		bad_error("dgraph_set_milestone", r);
5202 	}
5203 
5204 out:
5205 	startd_free(fmri, max_scf_fmri_size);
5206 	scf_value_destroy(val);
5207 	scf_property_destroy(prop);
5208 	scf_instance_destroy(inst);
5209 }
5210 
5211 /*
5212  * void *graph_thread(void *)
5213  *
5214  * Graph management thread.
5215  */
5216 /*ARGSUSED*/
5217 void *
5218 graph_thread(void *arg)
5219 {
5220 	scf_handle_t *h;
5221 	int err;
5222 
5223 	h = libscf_handle_create_bound_loop();
5224 
5225 	if (st->st_initial)
5226 		set_initial_milestone(h);
5227 
5228 	MUTEX_LOCK(&dgraph_lock);
5229 	initial_milestone_set = B_TRUE;
5230 	err = pthread_cond_broadcast(&initial_milestone_cv);
5231 	assert(err == 0);
5232 	MUTEX_UNLOCK(&dgraph_lock);
5233 
5234 	libscf_populate_graph(h);
5235 
5236 	if (!st->st_initial)
5237 		set_restart_milestone(h);
5238 
5239 	MUTEX_LOCK(&st->st_load_lock);
5240 	st->st_load_complete = 1;
5241 	(void) pthread_cond_broadcast(&st->st_load_cv);
5242 	MUTEX_UNLOCK(&st->st_load_lock);
5243 
5244 	MUTEX_LOCK(&dgraph_lock);
5245 	/*
5246 	 * Now that we've set st_load_complete we need to check can_come_up()
5247 	 * since if we booted to a milestone, then there won't be any more
5248 	 * state updates.
5249 	 */
5250 	if (!go_single_user_mode && !go_to_level1 &&
5251 	    halting == -1) {
5252 		if (!can_come_up() && !sulogin_thread_running) {
5253 			(void) startd_thread_create(sulogin_thread, NULL);
5254 			sulogin_thread_running = B_TRUE;
5255 		}
5256 	}
5257 	MUTEX_UNLOCK(&dgraph_lock);
5258 
5259 	(void) pthread_mutex_lock(&gu->gu_freeze_lock);
5260 
5261 	/*CONSTCOND*/
5262 	while (1) {
5263 		(void) pthread_cond_wait(&gu->gu_freeze_cv,
5264 		    &gu->gu_freeze_lock);
5265 	}
5266 
5267 	/*
5268 	 * Unreachable for now -- there's currently no graceful cleanup
5269 	 * called on exit().
5270 	 */
5271 	(void) pthread_mutex_unlock(&gu->gu_freeze_lock);
5272 	scf_handle_destroy(h);
5273 
5274 	return (NULL);
5275 }
5276 
5277 
5278 /*
5279  * int next_action()
5280  *   Given an array of timestamps 'a' with 'num' elements, find the
5281  *   lowest non-zero timestamp and return its index. If there are no
5282  *   non-zero elements, return -1.
5283  */
5284 static int
5285 next_action(hrtime_t *a, int num)
5286 {
5287 	hrtime_t t = 0;
5288 	int i = 0, smallest = -1;
5289 
5290 	for (i = 0; i < num; i++) {
5291 		if (t == 0) {
5292 			t = a[i];
5293 			smallest = i;
5294 		} else if (a[i] != 0 && a[i] < t) {
5295 			t = a[i];
5296 			smallest = i;
5297 		}
5298 	}
5299 
5300 	if (t == 0)
5301 		return (-1);
5302 	else
5303 		return (smallest);
5304 }
5305 
5306 /*
5307  * void process_actions()
5308  *   Process actions requested by the administrator. Possibilities include:
5309  *   refresh, restart, maintenance mode off, maintenance mode on,
5310  *   maintenance mode immediate, and degraded.
5311  *
5312  *   The set of pending actions is represented in the repository as a
5313  *   per-instance property group, with each action being a single property
5314  *   in that group.  This property group is converted to an array, with each
5315  *   action type having an array slot.  The actions in the array at the
5316  *   time process_actions() is called are acted on in the order of the
5317  *   timestamp (which is the value stored in the slot).  A value of zero
5318  *   indicates that there is no pending action of the type associated with
5319  *   a particular slot.
5320  *
5321  *   Sending an action event multiple times before the restarter has a
5322  *   chance to process that action will force it to be run at the last
5323  *   timestamp where it appears in the ordering.
5324  *
5325  *   Turning maintenance mode on trumps all other actions.
5326  *
5327  *   Returns 0 or ECONNABORTED.
5328  */
5329 static int
5330 process_actions(scf_handle_t *h, scf_propertygroup_t *pg, scf_instance_t *inst)
5331 {
5332 	scf_property_t *prop = NULL;
5333 	scf_value_t *val = NULL;
5334 	scf_type_t type;
5335 	graph_vertex_t *vertex;
5336 	admin_action_t a;
5337 	int i, ret = 0, r;
5338 	hrtime_t action_ts[NACTIONS];
5339 	char *inst_name;
5340 
5341 	r = libscf_instance_get_fmri(inst, &inst_name);
5342 	switch (r) {
5343 	case 0:
5344 		break;
5345 
5346 	case ECONNABORTED:
5347 		return (ECONNABORTED);
5348 
5349 	case ECANCELED:
5350 		return (0);
5351 
5352 	default:
5353 		bad_error("libscf_instance_get_fmri", r);
5354 	}
5355 
5356 	MUTEX_LOCK(&dgraph_lock);
5357 
5358 	vertex = vertex_get_by_name(inst_name);
5359 	if (vertex == NULL) {
5360 		MUTEX_UNLOCK(&dgraph_lock);
5361 		log_framework(LOG_DEBUG, "%s: Can't find graph vertex. "
5362 		    "The instance must have been removed.\n", inst_name);
5363 		return (0);
5364 	}
5365 
5366 	prop = safe_scf_property_create(h);
5367 	val = safe_scf_value_create(h);
5368 
5369 	for (i = 0; i < NACTIONS; i++) {
5370 		if (scf_pg_get_property(pg, admin_actions[i], prop) != 0) {
5371 			switch (scf_error()) {
5372 			case SCF_ERROR_CONNECTION_BROKEN:
5373 			default:
5374 				ret = ECONNABORTED;
5375 				goto out;
5376 
5377 			case SCF_ERROR_DELETED:
5378 				goto out;
5379 
5380 			case SCF_ERROR_NOT_FOUND:
5381 				action_ts[i] = 0;
5382 				continue;
5383 
5384 			case SCF_ERROR_HANDLE_MISMATCH:
5385 			case SCF_ERROR_INVALID_ARGUMENT:
5386 			case SCF_ERROR_NOT_SET:
5387 				bad_error("scf_pg_get_property", scf_error());
5388 			}
5389 		}
5390 
5391 		if (scf_property_type(prop, &type) != 0) {
5392 			switch (scf_error()) {
5393 			case SCF_ERROR_CONNECTION_BROKEN:
5394 			default:
5395 				ret = ECONNABORTED;
5396 				goto out;
5397 
5398 			case SCF_ERROR_DELETED:
5399 				action_ts[i] = 0;
5400 				continue;
5401 
5402 			case SCF_ERROR_NOT_SET:
5403 				bad_error("scf_property_type", scf_error());
5404 			}
5405 		}
5406 
5407 		if (type != SCF_TYPE_INTEGER) {
5408 			action_ts[i] = 0;
5409 			continue;
5410 		}
5411 
5412 		if (scf_property_get_value(prop, val) != 0) {
5413 			switch (scf_error()) {
5414 			case SCF_ERROR_CONNECTION_BROKEN:
5415 			default:
5416 				ret = ECONNABORTED;
5417 				goto out;
5418 
5419 			case SCF_ERROR_DELETED:
5420 				goto out;
5421 
5422 			case SCF_ERROR_NOT_FOUND:
5423 			case SCF_ERROR_CONSTRAINT_VIOLATED:
5424 				action_ts[i] = 0;
5425 				continue;
5426 
5427 			case SCF_ERROR_NOT_SET:
5428 				bad_error("scf_property_get_value",
5429 				    scf_error());
5430 			}
5431 		}
5432 
5433 		r = scf_value_get_integer(val, &action_ts[i]);
5434 		assert(r == 0);
5435 	}
5436 
5437 	a = ADMIN_EVENT_MAINT_ON_IMMEDIATE;
5438 	if (action_ts[ADMIN_EVENT_MAINT_ON_IMMEDIATE] ||
5439 	    action_ts[ADMIN_EVENT_MAINT_ON]) {
5440 		a = action_ts[ADMIN_EVENT_MAINT_ON_IMMEDIATE] ?
5441 		    ADMIN_EVENT_MAINT_ON_IMMEDIATE : ADMIN_EVENT_MAINT_ON;
5442 
5443 		vertex_send_event(vertex, admin_events[a]);
5444 		r = libscf_unset_action(h, pg, a, action_ts[a]);
5445 		switch (r) {
5446 		case 0:
5447 		case EACCES:
5448 			break;
5449 
5450 		case ECONNABORTED:
5451 			ret = ECONNABORTED;
5452 			goto out;
5453 
5454 		case EPERM:
5455 			uu_die("Insufficient privilege.\n");
5456 			/* NOTREACHED */
5457 
5458 		default:
5459 			bad_error("libscf_unset_action", r);
5460 		}
5461 	}
5462 
5463 	while ((a = next_action(action_ts, NACTIONS)) != -1) {
5464 		log_framework(LOG_DEBUG,
5465 		    "Graph: processing %s action for %s.\n", admin_actions[a],
5466 		    inst_name);
5467 
5468 		if (a == ADMIN_EVENT_REFRESH) {
5469 			r = dgraph_refresh_instance(vertex, inst);
5470 			switch (r) {
5471 			case 0:
5472 			case ECANCELED:
5473 			case EINVAL:
5474 			case -1:
5475 				break;
5476 
5477 			case ECONNABORTED:
5478 				/* pg & inst are reset now, so just return. */
5479 				ret = ECONNABORTED;
5480 				goto out;
5481 
5482 			default:
5483 				bad_error("dgraph_refresh_instance", r);
5484 			}
5485 		}
5486 
5487 		vertex_send_event(vertex, admin_events[a]);
5488 
5489 		r = libscf_unset_action(h, pg, a, action_ts[a]);
5490 		switch (r) {
5491 		case 0:
5492 		case EACCES:
5493 			break;
5494 
5495 		case ECONNABORTED:
5496 			ret = ECONNABORTED;
5497 			goto out;
5498 
5499 		case EPERM:
5500 			uu_die("Insufficient privilege.\n");
5501 			/* NOTREACHED */
5502 
5503 		default:
5504 			bad_error("libscf_unset_action", r);
5505 		}
5506 
5507 		action_ts[a] = 0;
5508 	}
5509 
5510 out:
5511 	MUTEX_UNLOCK(&dgraph_lock);
5512 
5513 	scf_property_destroy(prop);
5514 	scf_value_destroy(val);
5515 	startd_free(inst_name, max_scf_fmri_size);
5516 	return (ret);
5517 }
5518 
5519 /*
5520  * inst and pg_name are scratch space, and are unset on entry.
5521  * Returns
5522  *   0 - success
5523  *   ECONNRESET - success, but repository handle rebound
5524  *   ECONNABORTED - repository connection broken
5525  */
5526 static int
5527 process_pg_event(scf_handle_t *h, scf_propertygroup_t *pg, scf_instance_t *inst,
5528     char *pg_name)
5529 {
5530 	int r;
5531 	scf_property_t *prop;
5532 	scf_value_t *val;
5533 	char *fmri;
5534 	boolean_t rebound = B_FALSE, rebind_inst = B_FALSE;
5535 
5536 	if (scf_pg_get_name(pg, pg_name, max_scf_value_size) < 0) {
5537 		switch (scf_error()) {
5538 		case SCF_ERROR_CONNECTION_BROKEN:
5539 		default:
5540 			return (ECONNABORTED);
5541 
5542 		case SCF_ERROR_DELETED:
5543 			return (0);
5544 
5545 		case SCF_ERROR_NOT_SET:
5546 			bad_error("scf_pg_get_name", scf_error());
5547 		}
5548 	}
5549 
5550 	if (strcmp(pg_name, SCF_PG_GENERAL) == 0 ||
5551 	    strcmp(pg_name, SCF_PG_GENERAL_OVR) == 0) {
5552 		r = dgraph_update_general(pg);
5553 		switch (r) {
5554 		case 0:
5555 		case ENOTSUP:
5556 		case ECANCELED:
5557 			return (0);
5558 
5559 		case ECONNABORTED:
5560 			return (ECONNABORTED);
5561 
5562 		case -1:
5563 			/* Error should have been logged. */
5564 			return (0);
5565 
5566 		default:
5567 			bad_error("dgraph_update_general", r);
5568 		}
5569 	} else if (strcmp(pg_name, SCF_PG_RESTARTER_ACTIONS) == 0) {
5570 		if (scf_pg_get_parent_instance(pg, inst) != 0) {
5571 			switch (scf_error()) {
5572 			case SCF_ERROR_CONNECTION_BROKEN:
5573 				return (ECONNABORTED);
5574 
5575 			case SCF_ERROR_DELETED:
5576 			case SCF_ERROR_CONSTRAINT_VIOLATED:
5577 				/* Ignore commands on services. */
5578 				return (0);
5579 
5580 			case SCF_ERROR_NOT_BOUND:
5581 			case SCF_ERROR_HANDLE_MISMATCH:
5582 			case SCF_ERROR_NOT_SET:
5583 			default:
5584 				bad_error("scf_pg_get_parent_instance",
5585 				    scf_error());
5586 			}
5587 		}
5588 
5589 		return (process_actions(h, pg, inst));
5590 	}
5591 
5592 	if (strcmp(pg_name, SCF_PG_OPTIONS) != 0 &&
5593 	    strcmp(pg_name, SCF_PG_OPTIONS_OVR) != 0)
5594 		return (0);
5595 
5596 	/*
5597 	 * We only care about the options[_ovr] property groups of our own
5598 	 * instance, so get the fmri and compare.  Plus, once we know it's
5599 	 * correct, if the repository connection is broken we know exactly what
5600 	 * property group we were operating on, and can look it up again.
5601 	 */
5602 	if (scf_pg_get_parent_instance(pg, inst) != 0) {
5603 		switch (scf_error()) {
5604 		case SCF_ERROR_CONNECTION_BROKEN:
5605 			return (ECONNABORTED);
5606 
5607 		case SCF_ERROR_DELETED:
5608 		case SCF_ERROR_CONSTRAINT_VIOLATED:
5609 			return (0);
5610 
5611 		case SCF_ERROR_HANDLE_MISMATCH:
5612 		case SCF_ERROR_NOT_BOUND:
5613 		case SCF_ERROR_NOT_SET:
5614 		default:
5615 			bad_error("scf_pg_get_parent_instance",
5616 			    scf_error());
5617 		}
5618 	}
5619 
5620 	switch (r = libscf_instance_get_fmri(inst, &fmri)) {
5621 	case 0:
5622 		break;
5623 
5624 	case ECONNABORTED:
5625 		return (ECONNABORTED);
5626 
5627 	case ECANCELED:
5628 		return (0);
5629 
5630 	default:
5631 		bad_error("libscf_instance_get_fmri", r);
5632 	}
5633 
5634 	if (strcmp(fmri, SCF_SERVICE_STARTD) != 0) {
5635 		startd_free(fmri, max_scf_fmri_size);
5636 		return (0);
5637 	}
5638 
5639 	prop = safe_scf_property_create(h);
5640 	val = safe_scf_value_create(h);
5641 
5642 	if (strcmp(pg_name, SCF_PG_OPTIONS_OVR) == 0) {
5643 		/* See if we need to set the runlevel. */
5644 		/* CONSTCOND */
5645 		if (0) {
5646 rebind_pg:
5647 			libscf_handle_rebind(h);
5648 			rebound = B_TRUE;
5649 
5650 			r = libscf_lookup_instance(SCF_SERVICE_STARTD, inst);
5651 			switch (r) {
5652 			case 0:
5653 				break;
5654 
5655 			case ECONNABORTED:
5656 				goto rebind_pg;
5657 
5658 			case ENOENT:
5659 				goto out;
5660 
5661 			case EINVAL:
5662 			case ENOTSUP:
5663 				bad_error("libscf_lookup_instance", r);
5664 			}
5665 
5666 			if (scf_instance_get_pg(inst, pg_name, pg) != 0) {
5667 				switch (scf_error()) {
5668 				case SCF_ERROR_DELETED:
5669 				case SCF_ERROR_NOT_FOUND:
5670 					goto out;
5671 
5672 				case SCF_ERROR_CONNECTION_BROKEN:
5673 					goto rebind_pg;
5674 
5675 				case SCF_ERROR_HANDLE_MISMATCH:
5676 				case SCF_ERROR_NOT_BOUND:
5677 				case SCF_ERROR_NOT_SET:
5678 				case SCF_ERROR_INVALID_ARGUMENT:
5679 				default:
5680 					bad_error("scf_instance_get_pg",
5681 					    scf_error());
5682 				}
5683 			}
5684 		}
5685 
5686 		if (scf_pg_get_property(pg, "runlevel", prop) == 0) {
5687 			r = dgraph_set_runlevel(pg, prop);
5688 			switch (r) {
5689 			case ECONNRESET:
5690 				rebound = B_TRUE;
5691 				rebind_inst = B_TRUE;
5692 				/* FALLTHROUGH */
5693 
5694 			case 0:
5695 				break;
5696 
5697 			case ECONNABORTED:
5698 				goto rebind_pg;
5699 
5700 			case ECANCELED:
5701 				goto out;
5702 
5703 			default:
5704 				bad_error("dgraph_set_runlevel", r);
5705 			}
5706 		} else {
5707 			switch (scf_error()) {
5708 			case SCF_ERROR_CONNECTION_BROKEN:
5709 			default:
5710 				goto rebind_pg;
5711 
5712 			case SCF_ERROR_DELETED:
5713 				goto out;
5714 
5715 			case SCF_ERROR_NOT_FOUND:
5716 				break;
5717 
5718 			case SCF_ERROR_INVALID_ARGUMENT:
5719 			case SCF_ERROR_HANDLE_MISMATCH:
5720 			case SCF_ERROR_NOT_BOUND:
5721 			case SCF_ERROR_NOT_SET:
5722 				bad_error("scf_pg_get_property", scf_error());
5723 			}
5724 		}
5725 	}
5726 
5727 	if (rebind_inst) {
5728 lookup_inst:
5729 		r = libscf_lookup_instance(SCF_SERVICE_STARTD, inst);
5730 		switch (r) {
5731 		case 0:
5732 			break;
5733 
5734 		case ECONNABORTED:
5735 			libscf_handle_rebind(h);
5736 			rebound = B_TRUE;
5737 			goto lookup_inst;
5738 
5739 		case ENOENT:
5740 			goto out;
5741 
5742 		case EINVAL:
5743 		case ENOTSUP:
5744 			bad_error("libscf_lookup_instance", r);
5745 		}
5746 	}
5747 
5748 	r = libscf_get_milestone(inst, prop, val, fmri, max_scf_fmri_size);
5749 	switch (r) {
5750 	case 0:
5751 		break;
5752 
5753 	case ECONNABORTED:
5754 		libscf_handle_rebind(h);
5755 		rebound = B_TRUE;
5756 		goto lookup_inst;
5757 
5758 	case EINVAL:
5759 		log_error(LOG_NOTICE,
5760 		    "%s/%s property of %s is misconfigured.\n", pg_name,
5761 		    SCF_PROPERTY_MILESTONE, SCF_SERVICE_STARTD);
5762 		/* FALLTHROUGH */
5763 
5764 	case ECANCELED:
5765 	case ENOENT:
5766 		(void) strcpy(fmri, "all");
5767 		break;
5768 
5769 	default:
5770 		bad_error("libscf_get_milestone", r);
5771 	}
5772 
5773 	r = dgraph_set_milestone(fmri, h, B_FALSE);
5774 	switch (r) {
5775 	case 0:
5776 	case ECONNRESET:
5777 	case EALREADY:
5778 		break;
5779 
5780 	case EINVAL:
5781 		log_error(LOG_WARNING, "Milestone %s is invalid.\n", fmri);
5782 		break;
5783 
5784 	case ENOENT:
5785 		log_error(LOG_WARNING, "Milestone %s does not exist.\n", fmri);
5786 		break;
5787 
5788 	default:
5789 		bad_error("dgraph_set_milestone", r);
5790 	}
5791 
5792 out:
5793 	startd_free(fmri, max_scf_fmri_size);
5794 	scf_value_destroy(val);
5795 	scf_property_destroy(prop);
5796 
5797 	return (rebound ? ECONNRESET : 0);
5798 }
5799 
5800 static void
5801 process_delete(char *fmri, scf_handle_t *h)
5802 {
5803 	char *lfmri;
5804 	const char *inst_name, *pg_name;
5805 
5806 	lfmri = safe_strdup(fmri);
5807 
5808 	/* Determine if the FMRI is a property group or instance */
5809 	if (scf_parse_svc_fmri(lfmri, NULL, NULL, &inst_name, &pg_name,
5810 	    NULL) != SCF_SUCCESS) {
5811 		log_error(LOG_WARNING,
5812 		    "Received invalid FMRI \"%s\" from repository server.\n",
5813 		    fmri);
5814 	} else if (inst_name != NULL && pg_name == NULL) {
5815 		(void) dgraph_remove_instance(fmri, h);
5816 	}
5817 
5818 	free(lfmri);
5819 }
5820 
5821 /*ARGSUSED*/
5822 void *
5823 repository_event_thread(void *unused)
5824 {
5825 	scf_handle_t *h;
5826 	scf_propertygroup_t *pg;
5827 	scf_instance_t *inst;
5828 	char *fmri = startd_alloc(max_scf_fmri_size);
5829 	char *pg_name = startd_alloc(max_scf_value_size);
5830 	int r;
5831 
5832 	h = libscf_handle_create_bound_loop();
5833 
5834 	pg = safe_scf_pg_create(h);
5835 	inst = safe_scf_instance_create(h);
5836 
5837 retry:
5838 	if (_scf_notify_add_pgtype(h, SCF_GROUP_FRAMEWORK) != SCF_SUCCESS) {
5839 		if (scf_error() == SCF_ERROR_CONNECTION_BROKEN) {
5840 			libscf_handle_rebind(h);
5841 		} else {
5842 			log_error(LOG_WARNING,
5843 			    "Couldn't set up repository notification "
5844 			    "for property group type %s: %s\n",
5845 			    SCF_GROUP_FRAMEWORK, scf_strerror(scf_error()));
5846 
5847 			(void) sleep(1);
5848 		}
5849 
5850 		goto retry;
5851 	}
5852 
5853 	/*CONSTCOND*/
5854 	while (1) {
5855 		ssize_t res;
5856 
5857 		/* Note: fmri is only set on delete events. */
5858 		res = _scf_notify_wait(pg, fmri, max_scf_fmri_size);
5859 		if (res < 0) {
5860 			libscf_handle_rebind(h);
5861 			goto retry;
5862 		} else if (res == 0) {
5863 			/*
5864 			 * property group modified.  inst and pg_name are
5865 			 * pre-allocated scratch space.
5866 			 */
5867 			if (scf_pg_update(pg) < 0) {
5868 				switch (scf_error()) {
5869 				case SCF_ERROR_DELETED:
5870 					continue;
5871 
5872 				case SCF_ERROR_CONNECTION_BROKEN:
5873 					log_error(LOG_WARNING,
5874 					    "Lost repository event due to "
5875 					    "disconnection.\n");
5876 					libscf_handle_rebind(h);
5877 					goto retry;
5878 
5879 				case SCF_ERROR_NOT_BOUND:
5880 				case SCF_ERROR_NOT_SET:
5881 				default:
5882 					bad_error("scf_pg_update", scf_error());
5883 				}
5884 			}
5885 
5886 			r = process_pg_event(h, pg, inst, pg_name);
5887 			switch (r) {
5888 			case 0:
5889 				break;
5890 
5891 			case ECONNABORTED:
5892 				log_error(LOG_WARNING, "Lost repository event "
5893 				    "due to disconnection.\n");
5894 				libscf_handle_rebind(h);
5895 				/* FALLTHROUGH */
5896 
5897 			case ECONNRESET:
5898 				goto retry;
5899 
5900 			default:
5901 				bad_error("process_pg_event", r);
5902 			}
5903 		} else {
5904 			/* service, instance, or pg deleted. */
5905 			process_delete(fmri, h);
5906 		}
5907 	}
5908 
5909 	/*NOTREACHED*/
5910 	return (NULL);
5911 }
5912 
5913 void
5914 graph_engine_start()
5915 {
5916 	int err;
5917 
5918 	(void) startd_thread_create(graph_thread, NULL);
5919 
5920 	MUTEX_LOCK(&dgraph_lock);
5921 	while (!initial_milestone_set) {
5922 		err = pthread_cond_wait(&initial_milestone_cv, &dgraph_lock);
5923 		assert(err == 0);
5924 	}
5925 	MUTEX_UNLOCK(&dgraph_lock);
5926 
5927 	(void) startd_thread_create(repository_event_thread, NULL);
5928 	(void) startd_thread_create(graph_event_thread, NULL);
5929 }
5930