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