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