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