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