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