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