xref: /titanic_50/usr/src/cmd/svc/startd/restarter.c (revision c0c934808d1b7d058148814255f32064a0e09555)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * restarter.c - service manipulation
29  *
30  * This component manages services whose restarter is svc.startd, the standard
31  * restarter.  It translates restarter protocol events from the graph engine
32  * into actions on processes, as a delegated restarter would do.
33  *
34  * The master restarter manages a number of always-running threads:
35  *   - restarter event thread: events from the graph engine
36  *   - timeout thread: thread to fire queued timeouts
37  *   - contract thread: thread to handle contract events
38  *   - wait thread: thread to handle wait-based services
39  *
40  * The other threads are created as-needed:
41  *   - per-instance method threads
42  *   - per-instance event processing threads
43  *
44  * The interaction of all threads must result in the following conditions
45  * being satisfied (on a per-instance basis):
46  *   - restarter events must be processed in order
47  *   - method execution must be serialized
48  *   - instance delete must be held until outstanding methods are complete
49  *   - contract events shouldn't be processed while a method is running
50  *   - timeouts should fire even when a method is running
51  *
52  * Service instances are represented by restarter_inst_t's and are kept in the
53  * instance_list list.
54  *
55  * Service States
56  *   The current state of a service instance is kept in
57  *   restarter_inst_t->ri_i.i_state.  If transition to a new state could take
58  *   some time, then before we effect the transition we set
59  *   restarter_inst_t->ri_i.i_next_state to the target state, and afterwards we
60  *   rotate i_next_state to i_state and set i_next_state to
61  *   RESTARTER_STATE_NONE.  So usually i_next_state is _NONE when ri_lock is not
62  *   held.  The exception is when we launch methods, which are done with
63  *   a separate thread.  To keep any other threads from grabbing ri_lock before
64  *   method_thread() does, we set ri_method_thread to the thread id of the
65  *   method thread, and when it is nonzero any thread with a different thread id
66  *   waits on ri_method_cv.
67  *
68  * Method execution is serialized by blocking on ri_method_cv in
69  * inst_lookup_by_id() and waiting for a 0 value of ri_method_thread.  This
70  * also prevents the instance structure from being deleted until all
71  * outstanding operations such as method_thread() have finished.
72  *
73  * Lock ordering:
74  *
75  * dgraph_lock [can be held when taking:]
76  *   utmpx_lock
77  *   dictionary->dict_lock
78  *   st->st_load_lock
79  *   wait_info_lock
80  *   ru->restarter_update_lock
81  *     restarter_queue->rpeq_lock
82  *   instance_list.ril_lock
83  *     inst->ri_lock
84  *   st->st_configd_live_lock
85  *
86  * instance_list.ril_lock
87  *   graph_queue->gpeq_lock
88  *   gu->gu_lock
89  *   st->st_configd_live_lock
90  *   dictionary->dict_lock
91  *   inst->ri_lock
92  *     graph_queue->gpeq_lock
93  *     gu->gu_lock
94  *     tu->tu_lock
95  *     tq->tq_lock
96  *     inst->ri_queue_lock
97  *       wait_info_lock
98  *       bp->cb_lock
99  *     utmpx_lock
100  *
101  * single_user_thread_lock
102  *   wait_info_lock
103  *   utmpx_lock
104  *
105  * gu_freeze_lock
106  *
107  * logbuf_mutex nests inside pretty much everything.
108  */
109 
110 #include <sys/contract/process.h>
111 #include <sys/ctfs.h>
112 #include <sys/stat.h>
113 #include <sys/time.h>
114 #include <sys/types.h>
115 #include <sys/uio.h>
116 #include <sys/wait.h>
117 #include <assert.h>
118 #include <errno.h>
119 #include <fcntl.h>
120 #include <libcontract.h>
121 #include <libcontract_priv.h>
122 #include <libintl.h>
123 #include <librestart.h>
124 #include <librestart_priv.h>
125 #include <libuutil.h>
126 #include <limits.h>
127 #include <poll.h>
128 #include <port.h>
129 #include <pthread.h>
130 #include <stdarg.h>
131 #include <stdio.h>
132 #include <strings.h>
133 #include <unistd.h>
134 
135 #include "startd.h"
136 #include "protocol.h"
137 
138 static uu_list_pool_t *restarter_instance_pool;
139 static restarter_instance_list_t instance_list;
140 
141 static uu_list_pool_t *restarter_queue_pool;
142 
143 /*
144  * Function used to reset the restart times for an instance, when
145  * an administrative task comes along and essentially makes the times
146  * in this array ineffective.
147  */
148 static void
149 reset_start_times(restarter_inst_t *inst)
150 {
151 	inst->ri_start_index = 0;
152 	bzero(inst->ri_start_time, sizeof (inst->ri_start_time));
153 }
154 
155 /*ARGSUSED*/
156 static int
157 restarter_instance_compare(const void *lc_arg, const void *rc_arg,
158     void *private)
159 {
160 	int lc_id = ((const restarter_inst_t *)lc_arg)->ri_id;
161 	int rc_id = *(int *)rc_arg;
162 
163 	if (lc_id > rc_id)
164 		return (1);
165 	if (lc_id < rc_id)
166 		return (-1);
167 	return (0);
168 }
169 
170 static restarter_inst_t *
171 inst_lookup_by_name(const char *name)
172 {
173 	int id;
174 
175 	id = dict_lookup_byname(name);
176 	if (id == -1)
177 		return (NULL);
178 
179 	return (inst_lookup_by_id(id));
180 }
181 
182 restarter_inst_t *
183 inst_lookup_by_id(int id)
184 {
185 	restarter_inst_t *inst;
186 
187 	MUTEX_LOCK(&instance_list.ril_lock);
188 	inst = uu_list_find(instance_list.ril_instance_list, &id, NULL, NULL);
189 	if (inst != NULL)
190 		MUTEX_LOCK(&inst->ri_lock);
191 	MUTEX_UNLOCK(&instance_list.ril_lock);
192 
193 	if (inst != NULL) {
194 		while (inst->ri_method_thread != 0 &&
195 		    !pthread_equal(inst->ri_method_thread, pthread_self())) {
196 			++inst->ri_method_waiters;
197 			(void) pthread_cond_wait(&inst->ri_method_cv,
198 			    &inst->ri_lock);
199 			assert(inst->ri_method_waiters > 0);
200 			--inst->ri_method_waiters;
201 		}
202 	}
203 
204 	return (inst);
205 }
206 
207 static restarter_inst_t *
208 inst_lookup_queue(const char *name)
209 {
210 	int id;
211 	restarter_inst_t *inst;
212 
213 	id = dict_lookup_byname(name);
214 	if (id == -1)
215 		return (NULL);
216 
217 	MUTEX_LOCK(&instance_list.ril_lock);
218 	inst = uu_list_find(instance_list.ril_instance_list, &id, NULL, NULL);
219 	if (inst != NULL)
220 		MUTEX_LOCK(&inst->ri_queue_lock);
221 	MUTEX_UNLOCK(&instance_list.ril_lock);
222 
223 	return (inst);
224 }
225 
226 const char *
227 service_style(int flags)
228 {
229 	switch (flags & RINST_STYLE_MASK) {
230 	case RINST_CONTRACT:	return ("contract");
231 	case RINST_TRANSIENT:	return ("transient");
232 	case RINST_WAIT:	return ("wait");
233 
234 	default:
235 #ifndef NDEBUG
236 		uu_warn("%s:%d: Bad flags 0x%x.\n", __FILE__, __LINE__, flags);
237 #endif
238 		abort();
239 		/* NOTREACHED */
240 	}
241 }
242 
243 /*
244  * Fails with ECONNABORTED or ECANCELED.
245  */
246 static int
247 check_contract(restarter_inst_t *inst, boolean_t primary,
248     scf_instance_t *scf_inst)
249 {
250 	ctid_t *ctidp;
251 	int fd, r;
252 
253 	ctidp = primary ? &inst->ri_i.i_primary_ctid :
254 	    &inst->ri_i.i_transient_ctid;
255 
256 	assert(*ctidp >= 1);
257 
258 	fd = contract_open(*ctidp, NULL, "status", O_RDONLY);
259 	if (fd >= 0) {
260 		r = close(fd);
261 		assert(r == 0);
262 		return (0);
263 	}
264 
265 	r = restarter_remove_contract(scf_inst, *ctidp, primary ?
266 	    RESTARTER_CONTRACT_PRIMARY : RESTARTER_CONTRACT_TRANSIENT);
267 	switch (r) {
268 	case 0:
269 	case ECONNABORTED:
270 	case ECANCELED:
271 		*ctidp = 0;
272 		return (r);
273 
274 	case ENOMEM:
275 		uu_die("Out of memory\n");
276 		/* NOTREACHED */
277 
278 	case EPERM:
279 		uu_die("Insufficient privilege.\n");
280 		/* NOTREACHED */
281 
282 	case EACCES:
283 		uu_die("Repository backend access denied.\n");
284 		/* NOTREACHED */
285 
286 	case EROFS:
287 		log_error(LOG_INFO, "Could not remove unusable contract id %ld "
288 		    "for %s from repository.\n", *ctidp, inst->ri_i.i_fmri);
289 		return (0);
290 
291 	case EINVAL:
292 	case EBADF:
293 	default:
294 		assert(0);
295 		abort();
296 		/* NOTREACHED */
297 	}
298 }
299 
300 static int stop_instance(scf_handle_t *, restarter_inst_t *, stop_cause_t);
301 
302 /*
303  * int restarter_insert_inst(scf_handle_t *, char *)
304  *   If the inst is already in the restarter list, return its id.  If the inst
305  *   is not in the restarter list, initialize a restarter_inst_t, initialize its
306  *   states, insert it into the list, and return 0.
307  *
308  *   Fails with
309  *     ENOENT - name is not in the repository
310  */
311 static int
312 restarter_insert_inst(scf_handle_t *h, const char *name)
313 {
314 	int id, r;
315 	restarter_inst_t *inst;
316 	uu_list_index_t idx;
317 	scf_service_t *scf_svc;
318 	scf_instance_t *scf_inst;
319 	scf_snapshot_t *snap = NULL;
320 	scf_propertygroup_t *pg;
321 	char *svc_name, *inst_name;
322 	char logfilebuf[PATH_MAX];
323 	char *c;
324 	boolean_t do_commit_states;
325 	restarter_instance_state_t state, next_state;
326 	protocol_states_t *ps;
327 	pid_t start_pid;
328 
329 	MUTEX_LOCK(&instance_list.ril_lock);
330 
331 	/*
332 	 * We don't use inst_lookup_by_name() here because we want the lookup
333 	 * & insert to be atomic.
334 	 */
335 	id = dict_lookup_byname(name);
336 	if (id != -1) {
337 		inst = uu_list_find(instance_list.ril_instance_list, &id, NULL,
338 		    &idx);
339 		if (inst != NULL) {
340 			MUTEX_UNLOCK(&instance_list.ril_lock);
341 			return (0);
342 		}
343 	}
344 
345 	/* Allocate an instance */
346 	inst = startd_zalloc(sizeof (restarter_inst_t));
347 	inst->ri_utmpx_prefix = startd_alloc(max_scf_value_size);
348 	inst->ri_utmpx_prefix[0] = '\0';
349 
350 	inst->ri_i.i_fmri = startd_alloc(strlen(name) + 1);
351 	(void) strcpy((char *)inst->ri_i.i_fmri, name);
352 
353 	inst->ri_queue = startd_list_create(restarter_queue_pool, inst, 0);
354 
355 	/*
356 	 * id shouldn't be -1 since we use the same dictionary as graph.c, but
357 	 * just in case.
358 	 */
359 	inst->ri_id = (id != -1 ? id : dict_insert(name));
360 
361 	special_online_hooks_get(name, &inst->ri_pre_online_hook,
362 	    &inst->ri_post_online_hook, &inst->ri_post_offline_hook);
363 
364 	scf_svc = safe_scf_service_create(h);
365 	scf_inst = safe_scf_instance_create(h);
366 	pg = safe_scf_pg_create(h);
367 	svc_name = startd_alloc(max_scf_name_size);
368 	inst_name = startd_alloc(max_scf_name_size);
369 
370 rep_retry:
371 	if (snap != NULL)
372 		scf_snapshot_destroy(snap);
373 	if (inst->ri_logstem != NULL)
374 		startd_free(inst->ri_logstem, PATH_MAX);
375 	if (inst->ri_common_name != NULL)
376 		startd_free(inst->ri_common_name, max_scf_value_size);
377 	if (inst->ri_C_common_name != NULL)
378 		startd_free(inst->ri_C_common_name, max_scf_value_size);
379 	snap = NULL;
380 	inst->ri_logstem = NULL;
381 	inst->ri_common_name = NULL;
382 	inst->ri_C_common_name = NULL;
383 
384 	if (scf_handle_decode_fmri(h, name, NULL, scf_svc, scf_inst, NULL,
385 	    NULL, SCF_DECODE_FMRI_EXACT) != 0) {
386 		switch (scf_error()) {
387 		case SCF_ERROR_CONNECTION_BROKEN:
388 			libscf_handle_rebind(h);
389 			goto rep_retry;
390 
391 		case SCF_ERROR_NOT_FOUND:
392 			goto deleted;
393 		}
394 
395 		uu_die("Can't decode FMRI %s: %s\n", name,
396 		    scf_strerror(scf_error()));
397 	}
398 
399 	/*
400 	 * If there's no running snapshot, then we execute using the editing
401 	 * snapshot.  Pending snapshots will be taken later.
402 	 */
403 	snap = libscf_get_running_snapshot(scf_inst);
404 
405 	if ((scf_service_get_name(scf_svc, svc_name, max_scf_name_size) < 0) ||
406 	    (scf_instance_get_name(scf_inst, inst_name, max_scf_name_size) <
407 	    0)) {
408 		switch (scf_error()) {
409 		case SCF_ERROR_NOT_SET:
410 			break;
411 
412 		case SCF_ERROR_CONNECTION_BROKEN:
413 			libscf_handle_rebind(h);
414 			goto rep_retry;
415 
416 		default:
417 			assert(0);
418 			abort();
419 		}
420 
421 		goto deleted;
422 	}
423 
424 	(void) snprintf(logfilebuf, PATH_MAX, "%s:%s", svc_name, inst_name);
425 	for (c = logfilebuf; *c != '\0'; c++)
426 		if (*c == '/')
427 			*c = '-';
428 
429 	inst->ri_logstem = startd_alloc(PATH_MAX);
430 	(void) snprintf(inst->ri_logstem, PATH_MAX, "%s%s", logfilebuf,
431 	    LOG_SUFFIX);
432 
433 	/*
434 	 * If the restarter group is missing, use uninit/none.  Otherwise,
435 	 * we're probably being restarted & don't want to mess up the states
436 	 * that are there.
437 	 */
438 	state = RESTARTER_STATE_UNINIT;
439 	next_state = RESTARTER_STATE_NONE;
440 
441 	r = scf_instance_get_pg(scf_inst, SCF_PG_RESTARTER, pg);
442 	if (r != 0) {
443 		switch (scf_error()) {
444 		case SCF_ERROR_CONNECTION_BROKEN:
445 			libscf_handle_rebind(h);
446 			goto rep_retry;
447 
448 		case SCF_ERROR_NOT_SET:
449 			goto deleted;
450 
451 		case SCF_ERROR_NOT_FOUND:
452 			/*
453 			 * This shouldn't happen since the graph engine should
454 			 * have initialized the state to uninitialized/none if
455 			 * there was no restarter pg.  In case somebody
456 			 * deleted it, though....
457 			 */
458 			do_commit_states = B_TRUE;
459 			break;
460 
461 		default:
462 			assert(0);
463 			abort();
464 		}
465 	} else {
466 		r = libscf_read_states(pg, &state, &next_state);
467 		if (r != 0) {
468 			do_commit_states = B_TRUE;
469 		} else {
470 			if (next_state != RESTARTER_STATE_NONE) {
471 				/*
472 				 * Force next_state to _NONE since we
473 				 * don't look for method processes.
474 				 */
475 				next_state = RESTARTER_STATE_NONE;
476 				do_commit_states = B_TRUE;
477 			} else {
478 				/*
479 				 * Inform the restarter of our state without
480 				 * changing the STIME in the repository.
481 				 */
482 				ps = startd_alloc(sizeof (*ps));
483 				inst->ri_i.i_state = ps->ps_state = state;
484 				inst->ri_i.i_next_state = ps->ps_state_next =
485 				    next_state;
486 
487 				graph_protocol_send_event(inst->ri_i.i_fmri,
488 				    GRAPH_UPDATE_STATE_CHANGE, ps);
489 
490 				do_commit_states = B_FALSE;
491 			}
492 		}
493 	}
494 
495 	switch (libscf_get_startd_properties(scf_inst, snap, &inst->ri_flags,
496 	    &inst->ri_utmpx_prefix)) {
497 	case 0:
498 		break;
499 
500 	case ECONNABORTED:
501 		libscf_handle_rebind(h);
502 		goto rep_retry;
503 
504 	case ECANCELED:
505 		goto deleted;
506 
507 	case ENOENT:
508 		/*
509 		 * This is odd, because the graph engine should have required
510 		 * the general property group.  So we'll just use default
511 		 * flags in anticipation of the graph engine sending us
512 		 * REMOVE_INSTANCE when it finds out that the general property
513 		 * group has been deleted.
514 		 */
515 		inst->ri_flags = RINST_CONTRACT;
516 		break;
517 
518 	default:
519 		assert(0);
520 		abort();
521 	}
522 
523 	switch (libscf_get_template_values(scf_inst, snap,
524 	    &inst->ri_common_name, &inst->ri_C_common_name)) {
525 	case 0:
526 		break;
527 
528 	case ECONNABORTED:
529 		libscf_handle_rebind(h);
530 		goto rep_retry;
531 
532 	case ECANCELED:
533 		goto deleted;
534 
535 	case ECHILD:
536 	case ENOENT:
537 		break;
538 
539 	default:
540 		assert(0);
541 		abort();
542 	}
543 
544 	switch (libscf_read_method_ids(h, scf_inst, inst->ri_i.i_fmri,
545 	    &inst->ri_i.i_primary_ctid, &inst->ri_i.i_transient_ctid,
546 	    &start_pid)) {
547 	case 0:
548 		break;
549 
550 	case ECONNABORTED:
551 		libscf_handle_rebind(h);
552 		goto rep_retry;
553 
554 	case ECANCELED:
555 		goto deleted;
556 
557 	default:
558 		assert(0);
559 		abort();
560 	}
561 
562 	if (inst->ri_i.i_primary_ctid >= 1) {
563 		contract_hash_store(inst->ri_i.i_primary_ctid, inst->ri_id);
564 
565 		switch (check_contract(inst, B_TRUE, scf_inst)) {
566 		case 0:
567 			break;
568 
569 		case ECONNABORTED:
570 			libscf_handle_rebind(h);
571 			goto rep_retry;
572 
573 		case ECANCELED:
574 			goto deleted;
575 
576 		default:
577 			assert(0);
578 			abort();
579 		}
580 	}
581 
582 	if (inst->ri_i.i_transient_ctid >= 1) {
583 		switch (check_contract(inst, B_FALSE, scf_inst)) {
584 		case 0:
585 			break;
586 
587 		case ECONNABORTED:
588 			libscf_handle_rebind(h);
589 			goto rep_retry;
590 
591 		case ECANCELED:
592 			goto deleted;
593 
594 		default:
595 			assert(0);
596 			abort();
597 		}
598 	}
599 
600 	/* No more failures we live through, so add it to the list. */
601 	(void) pthread_mutex_init(&inst->ri_lock, &mutex_attrs);
602 	(void) pthread_mutex_init(&inst->ri_queue_lock, &mutex_attrs);
603 	MUTEX_LOCK(&inst->ri_lock);
604 	MUTEX_LOCK(&inst->ri_queue_lock);
605 
606 	(void) pthread_cond_init(&inst->ri_method_cv, NULL);
607 
608 	uu_list_node_init(inst, &inst->ri_link, restarter_instance_pool);
609 	uu_list_insert(instance_list.ril_instance_list, inst, idx);
610 	MUTEX_UNLOCK(&instance_list.ril_lock);
611 
612 	if (start_pid != -1 &&
613 	    (inst->ri_flags & RINST_STYLE_MASK) == RINST_WAIT) {
614 		int ret;
615 		ret = wait_register(start_pid, inst->ri_i.i_fmri, 0, 1);
616 		if (ret == -1) {
617 			/*
618 			 * Implication:  if we can't reregister the
619 			 * instance, we will start another one.  Two
620 			 * instances may or may not result in a resource
621 			 * conflict.
622 			 */
623 			log_error(LOG_WARNING,
624 			    "%s: couldn't reregister %ld for wait\n",
625 			    inst->ri_i.i_fmri, start_pid);
626 		} else if (ret == 1) {
627 			/*
628 			 * Leading PID has exited.
629 			 */
630 			(void) stop_instance(h, inst, RSTOP_EXIT);
631 		}
632 	}
633 
634 
635 	scf_pg_destroy(pg);
636 
637 	if (do_commit_states)
638 		(void) restarter_instance_update_states(h, inst, state,
639 		    next_state, RERR_NONE, NULL);
640 
641 	log_framework(LOG_DEBUG, "%s is a %s-style service\n", name,
642 	    service_style(inst->ri_flags));
643 
644 	MUTEX_UNLOCK(&inst->ri_queue_lock);
645 	MUTEX_UNLOCK(&inst->ri_lock);
646 
647 	startd_free(svc_name, max_scf_name_size);
648 	startd_free(inst_name, max_scf_name_size);
649 	scf_snapshot_destroy(snap);
650 	scf_instance_destroy(scf_inst);
651 	scf_service_destroy(scf_svc);
652 
653 	log_framework(LOG_DEBUG, "%s: inserted instance into restarter list\n",
654 	    name);
655 
656 	return (0);
657 
658 deleted:
659 	MUTEX_UNLOCK(&instance_list.ril_lock);
660 	startd_free(inst_name, max_scf_name_size);
661 	startd_free(svc_name, max_scf_name_size);
662 	if (snap != NULL)
663 		scf_snapshot_destroy(snap);
664 	scf_pg_destroy(pg);
665 	scf_instance_destroy(scf_inst);
666 	scf_service_destroy(scf_svc);
667 	startd_free((void *)inst->ri_i.i_fmri, strlen(inst->ri_i.i_fmri) + 1);
668 	uu_list_destroy(inst->ri_queue);
669 	if (inst->ri_logstem != NULL)
670 		startd_free(inst->ri_logstem, PATH_MAX);
671 	if (inst->ri_common_name != NULL)
672 		startd_free(inst->ri_common_name, max_scf_value_size);
673 	if (inst->ri_C_common_name != NULL)
674 		startd_free(inst->ri_C_common_name, max_scf_value_size);
675 	startd_free(inst->ri_utmpx_prefix, max_scf_value_size);
676 	startd_free(inst, sizeof (restarter_inst_t));
677 	return (ENOENT);
678 }
679 
680 static void
681 restarter_delete_inst(restarter_inst_t *ri)
682 {
683 	int id;
684 	restarter_inst_t *rip;
685 	void *cookie = NULL;
686 	restarter_instance_qentry_t *e;
687 
688 	assert(MUTEX_HELD(&ri->ri_lock));
689 
690 	/*
691 	 * Must drop the instance lock so we can pick up the instance_list
692 	 * lock & remove the instance.
693 	 */
694 	id = ri->ri_id;
695 	MUTEX_UNLOCK(&ri->ri_lock);
696 
697 	MUTEX_LOCK(&instance_list.ril_lock);
698 
699 	rip = uu_list_find(instance_list.ril_instance_list, &id, NULL, NULL);
700 	if (rip == NULL) {
701 		MUTEX_UNLOCK(&instance_list.ril_lock);
702 		return;
703 	}
704 
705 	assert(ri == rip);
706 
707 	uu_list_remove(instance_list.ril_instance_list, ri);
708 
709 	log_framework(LOG_DEBUG, "%s: deleted instance from restarter list\n",
710 	    ri->ri_i.i_fmri);
711 
712 	MUTEX_UNLOCK(&instance_list.ril_lock);
713 
714 	/*
715 	 * We can lock the instance without holding the instance_list lock
716 	 * since we removed the instance from the list.
717 	 */
718 	MUTEX_LOCK(&ri->ri_lock);
719 	MUTEX_LOCK(&ri->ri_queue_lock);
720 
721 	if (ri->ri_i.i_primary_ctid >= 1)
722 		contract_hash_remove(ri->ri_i.i_primary_ctid);
723 
724 	while (ri->ri_method_thread != 0 || ri->ri_method_waiters > 0)
725 		(void) pthread_cond_wait(&ri->ri_method_cv, &ri->ri_lock);
726 
727 	while ((e = uu_list_teardown(ri->ri_queue, &cookie)) != NULL)
728 		startd_free(e, sizeof (*e));
729 	uu_list_destroy(ri->ri_queue);
730 
731 	startd_free((void *)ri->ri_i.i_fmri, strlen(ri->ri_i.i_fmri) + 1);
732 	startd_free(ri->ri_logstem, PATH_MAX);
733 	if (ri->ri_common_name != NULL)
734 		startd_free(ri->ri_common_name, max_scf_value_size);
735 	if (ri->ri_C_common_name != NULL)
736 		startd_free(ri->ri_C_common_name, max_scf_value_size);
737 	startd_free(ri->ri_utmpx_prefix, max_scf_value_size);
738 	(void) pthread_mutex_destroy(&ri->ri_lock);
739 	(void) pthread_mutex_destroy(&ri->ri_queue_lock);
740 	startd_free(ri, sizeof (restarter_inst_t));
741 }
742 
743 /*
744  * instance_is_wait_style()
745  *
746  *   Returns 1 if the given instance is a "wait-style" service instance.
747  */
748 int
749 instance_is_wait_style(restarter_inst_t *inst)
750 {
751 	assert(MUTEX_HELD(&inst->ri_lock));
752 	return ((inst->ri_flags & RINST_STYLE_MASK) == RINST_WAIT);
753 }
754 
755 /*
756  * instance_is_transient_style()
757  *
758  *   Returns 1 if the given instance is a transient service instance.
759  */
760 int
761 instance_is_transient_style(restarter_inst_t *inst)
762 {
763 	assert(MUTEX_HELD(&inst->ri_lock));
764 	return ((inst->ri_flags & RINST_STYLE_MASK) == RINST_TRANSIENT);
765 }
766 
767 /*
768  * instance_in_transition()
769  * Returns 1 if instance is in transition, 0 if not
770  */
771 int
772 instance_in_transition(restarter_inst_t *inst)
773 {
774 	assert(MUTEX_HELD(&inst->ri_lock));
775 	if (inst->ri_i.i_next_state == RESTARTER_STATE_NONE)
776 		return (0);
777 	return (1);
778 }
779 
780 /*
781  * returns 1 if instance is already started, 0 if not
782  */
783 static int
784 instance_started(restarter_inst_t *inst)
785 {
786 	int ret;
787 
788 	assert(MUTEX_HELD(&inst->ri_lock));
789 
790 	if (inst->ri_i.i_state == RESTARTER_STATE_ONLINE ||
791 	    inst->ri_i.i_state == RESTARTER_STATE_DEGRADED)
792 		ret = 1;
793 	else
794 		ret = 0;
795 
796 	return (ret);
797 }
798 
799 /*
800  * Returns
801  *   0 - success
802  *   ECONNRESET - success, but h was rebound
803  */
804 int
805 restarter_instance_update_states(scf_handle_t *h, restarter_inst_t *ri,
806     restarter_instance_state_t new_state,
807     restarter_instance_state_t new_state_next, restarter_error_t err, char *aux)
808 {
809 	protocol_states_t *states;
810 	int e;
811 	uint_t retry_count = 0, msecs = ALLOC_DELAY;
812 	boolean_t rebound = B_FALSE;
813 	int prev_state_online;
814 	int state_online;
815 
816 	assert(MUTEX_HELD(&ri->ri_lock));
817 
818 	prev_state_online = instance_started(ri);
819 
820 retry:
821 	e = _restarter_commit_states(h, &ri->ri_i, new_state, new_state_next,
822 	    aux);
823 	switch (e) {
824 	case 0:
825 		break;
826 
827 	case ENOMEM:
828 		++retry_count;
829 		if (retry_count < ALLOC_RETRY) {
830 			(void) poll(NULL, 0, msecs);
831 			msecs *= ALLOC_DELAY_MULT;
832 			goto retry;
833 		}
834 
835 		/* Like startd_alloc(). */
836 		uu_die("Insufficient memory.\n");
837 		/* NOTREACHED */
838 
839 	case ECONNABORTED:
840 		libscf_handle_rebind(h);
841 		rebound = B_TRUE;
842 		goto retry;
843 
844 	case EPERM:
845 	case EACCES:
846 	case EROFS:
847 		log_error(LOG_NOTICE, "Could not commit state change for %s "
848 		    "to repository: %s.\n", ri->ri_i.i_fmri, strerror(e));
849 		/* FALLTHROUGH */
850 
851 	case ENOENT:
852 		ri->ri_i.i_state = new_state;
853 		ri->ri_i.i_next_state = new_state_next;
854 		break;
855 
856 	case EINVAL:
857 	default:
858 		bad_error("_restarter_commit_states", e);
859 	}
860 
861 	states = startd_alloc(sizeof (protocol_states_t));
862 	states->ps_state = new_state;
863 	states->ps_state_next = new_state_next;
864 	states->ps_err = err;
865 	graph_protocol_send_event(ri->ri_i.i_fmri, GRAPH_UPDATE_STATE_CHANGE,
866 	    (void *)states);
867 
868 	state_online = instance_started(ri);
869 
870 	if (prev_state_online && !state_online)
871 		ri->ri_post_offline_hook();
872 	else if (!prev_state_online && state_online)
873 		ri->ri_post_online_hook();
874 
875 	return (rebound ? ECONNRESET : 0);
876 }
877 
878 void
879 restarter_mark_pending_snapshot(const char *fmri, uint_t flag)
880 {
881 	restarter_inst_t *inst;
882 
883 	assert(flag == RINST_RETAKE_RUNNING || flag == RINST_RETAKE_START);
884 
885 	inst = inst_lookup_by_name(fmri);
886 	if (inst == NULL)
887 		return;
888 
889 	inst->ri_flags |= flag;
890 
891 	MUTEX_UNLOCK(&inst->ri_lock);
892 }
893 
894 static void
895 restarter_take_pending_snapshots(scf_handle_t *h)
896 {
897 	restarter_inst_t *inst;
898 	int r;
899 
900 	MUTEX_LOCK(&instance_list.ril_lock);
901 
902 	for (inst = uu_list_first(instance_list.ril_instance_list);
903 	    inst != NULL;
904 	    inst = uu_list_next(instance_list.ril_instance_list, inst)) {
905 		const char *fmri;
906 		scf_instance_t *sinst = NULL;
907 
908 		MUTEX_LOCK(&inst->ri_lock);
909 
910 		/*
911 		 * This is where we'd check inst->ri_method_thread and if it
912 		 * were nonzero we'd wait in anticipation of another thread
913 		 * executing a method for inst.  Doing so with the instance_list
914 		 * locked, though, leads to deadlock.  Since taking a snapshot
915 		 * during that window won't hurt anything, we'll just continue.
916 		 */
917 
918 		fmri = inst->ri_i.i_fmri;
919 
920 		if (inst->ri_flags & RINST_RETAKE_RUNNING) {
921 			scf_snapshot_t *rsnap;
922 
923 			(void) libscf_fmri_get_instance(h, fmri, &sinst);
924 
925 			rsnap = libscf_get_or_make_running_snapshot(sinst,
926 			    fmri, B_FALSE);
927 
928 			scf_instance_destroy(sinst);
929 
930 			if (rsnap != NULL)
931 				inst->ri_flags &= ~RINST_RETAKE_RUNNING;
932 
933 			scf_snapshot_destroy(rsnap);
934 		}
935 
936 		if (inst->ri_flags & RINST_RETAKE_START) {
937 			switch (r = libscf_snapshots_poststart(h, fmri,
938 			    B_FALSE)) {
939 			case 0:
940 			case ENOENT:
941 				inst->ri_flags &= ~RINST_RETAKE_START;
942 				break;
943 
944 			case ECONNABORTED:
945 				break;
946 
947 			case EACCES:
948 			default:
949 				bad_error("libscf_snapshots_poststart", r);
950 			}
951 		}
952 
953 		MUTEX_UNLOCK(&inst->ri_lock);
954 	}
955 
956 	MUTEX_UNLOCK(&instance_list.ril_lock);
957 }
958 
959 /* ARGSUSED */
960 void *
961 restarter_post_fsminimal_thread(void *unused)
962 {
963 	scf_handle_t *h;
964 	int r;
965 
966 	h = libscf_handle_create_bound_loop();
967 
968 	for (;;) {
969 		r = libscf_create_self(h);
970 		if (r == 0)
971 			break;
972 
973 		assert(r == ECONNABORTED);
974 		libscf_handle_rebind(h);
975 	}
976 
977 	restarter_take_pending_snapshots(h);
978 
979 	(void) scf_handle_unbind(h);
980 	scf_handle_destroy(h);
981 
982 	return (NULL);
983 }
984 
985 /*
986  * int stop_instance()
987  *
988  *   Stop the instance identified by the instance given as the second argument,
989  *   for the cause stated.
990  *
991  *   Returns
992  *     0 - success
993  *     -1 - inst is in transition
994  */
995 static int
996 stop_instance(scf_handle_t *local_handle, restarter_inst_t *inst,
997     stop_cause_t cause)
998 {
999 	fork_info_t *info;
1000 	const char *cp;
1001 	int err;
1002 	restarter_error_t re;
1003 
1004 	assert(MUTEX_HELD(&inst->ri_lock));
1005 	assert(inst->ri_method_thread == 0);
1006 
1007 	switch (cause) {
1008 	case RSTOP_EXIT:
1009 		re = RERR_RESTART;
1010 		cp = "all processes in service exited";
1011 		break;
1012 	case RSTOP_CORE:
1013 		re = RERR_FAULT;
1014 		cp = "process dumped core";
1015 		break;
1016 	case RSTOP_SIGNAL:
1017 		re = RERR_FAULT;
1018 		cp = "process received fatal signal from outside the service";
1019 		break;
1020 	case RSTOP_HWERR:
1021 		re = RERR_FAULT;
1022 		cp = "process killed due to uncorrectable hardware error";
1023 		break;
1024 	case RSTOP_DEPENDENCY:
1025 		re = RERR_RESTART;
1026 		cp = "dependency activity requires stop";
1027 		break;
1028 	case RSTOP_DISABLE:
1029 		re = RERR_RESTART;
1030 		cp = "service disabled";
1031 		break;
1032 	case RSTOP_RESTART:
1033 		re = RERR_RESTART;
1034 		cp = "service restarting";
1035 		break;
1036 	default:
1037 #ifndef NDEBUG
1038 		(void) fprintf(stderr, "Unknown cause %d at %s:%d.\n",
1039 		    cause, __FILE__, __LINE__);
1040 #endif
1041 		abort();
1042 	}
1043 
1044 	/* Services in the disabled and maintenance state are ignored */
1045 	if (inst->ri_i.i_state == RESTARTER_STATE_MAINT ||
1046 	    inst->ri_i.i_state == RESTARTER_STATE_DISABLED) {
1047 		log_framework(LOG_DEBUG,
1048 		    "%s: stop_instance -> is maint/disabled\n",
1049 		    inst->ri_i.i_fmri);
1050 		return (0);
1051 	}
1052 
1053 	/* Already stopped instances are left alone */
1054 	if (instance_started(inst) == 0) {
1055 		log_framework(LOG_DEBUG, "Restarter: %s is already stopped.\n",
1056 		    inst->ri_i.i_fmri);
1057 		return (0);
1058 	}
1059 
1060 	if (instance_in_transition(inst)) {
1061 		/* requeue event by returning -1 */
1062 		log_framework(LOG_DEBUG,
1063 		    "Restarter: Not stopping %s, in transition.\n",
1064 		    inst->ri_i.i_fmri);
1065 		return (-1);
1066 	}
1067 
1068 	log_instance(inst, B_TRUE, "Stopping because %s.", cp);
1069 
1070 	log_framework(re == RERR_FAULT ? LOG_INFO : LOG_DEBUG,
1071 	    "%s: Instance stopping because %s.\n", inst->ri_i.i_fmri, cp);
1072 
1073 	if (instance_is_wait_style(inst) && cause == RSTOP_EXIT) {
1074 		/*
1075 		 * No need to stop instance, as child has exited; remove
1076 		 * contract and move the instance to the offline state.
1077 		 */
1078 		switch (err = restarter_instance_update_states(local_handle,
1079 		    inst, inst->ri_i.i_state, RESTARTER_STATE_OFFLINE, re,
1080 		    NULL)) {
1081 		case 0:
1082 		case ECONNRESET:
1083 			break;
1084 
1085 		default:
1086 			bad_error("restarter_instance_update_states", err);
1087 		}
1088 
1089 		(void) update_fault_count(inst, FAULT_COUNT_RESET);
1090 		reset_start_times(inst);
1091 
1092 		if (inst->ri_i.i_primary_ctid != 0) {
1093 			inst->ri_m_inst =
1094 			    safe_scf_instance_create(local_handle);
1095 			inst->ri_mi_deleted = B_FALSE;
1096 
1097 			libscf_reget_instance(inst);
1098 			method_remove_contract(inst, B_TRUE, B_TRUE);
1099 
1100 			scf_instance_destroy(inst->ri_m_inst);
1101 			inst->ri_m_inst = NULL;
1102 		}
1103 
1104 		switch (err = restarter_instance_update_states(local_handle,
1105 		    inst, inst->ri_i.i_next_state, RESTARTER_STATE_NONE, re,
1106 		    NULL)) {
1107 		case 0:
1108 		case ECONNRESET:
1109 			break;
1110 
1111 		default:
1112 			bad_error("restarter_instance_update_states", err);
1113 		}
1114 
1115 		return (0);
1116 	} else if (instance_is_wait_style(inst) && re == RERR_RESTART) {
1117 		/*
1118 		 * Stopping a wait service through means other than the pid
1119 		 * exiting should keep wait_thread() from restarting the
1120 		 * service, by removing it from the wait list.
1121 		 * We cannot remove it right now otherwise the process will
1122 		 * end up <defunct> so mark it to be ignored.
1123 		 */
1124 		wait_ignore_by_fmri(inst->ri_i.i_fmri);
1125 	}
1126 
1127 	switch (err = restarter_instance_update_states(local_handle, inst,
1128 	    inst->ri_i.i_state, inst->ri_i.i_enabled ? RESTARTER_STATE_OFFLINE :
1129 	    RESTARTER_STATE_DISABLED, RERR_NONE, NULL)) {
1130 	case 0:
1131 	case ECONNRESET:
1132 		break;
1133 
1134 	default:
1135 		bad_error("restarter_instance_update_states", err);
1136 	}
1137 
1138 	info = startd_zalloc(sizeof (fork_info_t));
1139 
1140 	info->sf_id = inst->ri_id;
1141 	info->sf_method_type = METHOD_STOP;
1142 	info->sf_event_type = re;
1143 	inst->ri_method_thread = startd_thread_create(method_thread, info);
1144 
1145 	return (0);
1146 }
1147 
1148 /*
1149  * Returns
1150  *   ENOENT - fmri is not in instance_list
1151  *   0 - success
1152  *   ECONNRESET - success, though handle was rebound
1153  *   -1 - instance is in transition
1154  */
1155 int
1156 stop_instance_fmri(scf_handle_t *h, const char *fmri, uint_t flags)
1157 {
1158 	restarter_inst_t *rip;
1159 	int r;
1160 
1161 	rip = inst_lookup_by_name(fmri);
1162 	if (rip == NULL)
1163 		return (ENOENT);
1164 
1165 	r = stop_instance(h, rip, flags);
1166 
1167 	MUTEX_UNLOCK(&rip->ri_lock);
1168 
1169 	return (r);
1170 }
1171 
1172 static void
1173 unmaintain_instance(scf_handle_t *h, restarter_inst_t *rip,
1174     unmaint_cause_t cause)
1175 {
1176 	ctid_t ctid;
1177 	scf_instance_t *inst;
1178 	int r;
1179 	uint_t tries = 0, msecs = ALLOC_DELAY;
1180 	const char *cp;
1181 
1182 	assert(MUTEX_HELD(&rip->ri_lock));
1183 
1184 	if (rip->ri_i.i_state != RESTARTER_STATE_MAINT) {
1185 		log_error(LOG_DEBUG, "Restarter: "
1186 		    "Ignoring maintenance off command because %s is not in the "
1187 		    "maintenance state.\n", rip->ri_i.i_fmri);
1188 		return;
1189 	}
1190 
1191 	switch (cause) {
1192 	case RUNMAINT_CLEAR:
1193 		cp = "clear requested";
1194 		break;
1195 	case RUNMAINT_DISABLE:
1196 		cp = "disable requested";
1197 		break;
1198 	default:
1199 #ifndef NDEBUG
1200 		(void) fprintf(stderr, "Uncaught case for %d at %s:%d.\n",
1201 		    cause, __FILE__, __LINE__);
1202 #endif
1203 		abort();
1204 	}
1205 
1206 	log_instance(rip, B_TRUE, "Leaving maintenance because %s.",
1207 	    cp);
1208 	log_framework(LOG_DEBUG, "%s: Instance leaving maintenance because "
1209 	    "%s.\n", rip->ri_i.i_fmri, cp);
1210 
1211 	(void) restarter_instance_update_states(h, rip, RESTARTER_STATE_UNINIT,
1212 	    RESTARTER_STATE_NONE, RERR_RESTART, "none");
1213 
1214 	/*
1215 	 * If we did ADMIN_MAINT_ON_IMMEDIATE, then there might still be
1216 	 * a primary contract.
1217 	 */
1218 	if (rip->ri_i.i_primary_ctid == 0)
1219 		return;
1220 
1221 	ctid = rip->ri_i.i_primary_ctid;
1222 	contract_abandon(ctid);
1223 	rip->ri_i.i_primary_ctid = 0;
1224 
1225 rep_retry:
1226 	switch (r = libscf_fmri_get_instance(h, rip->ri_i.i_fmri, &inst)) {
1227 	case 0:
1228 		break;
1229 
1230 	case ECONNABORTED:
1231 		libscf_handle_rebind(h);
1232 		goto rep_retry;
1233 
1234 	case ENOENT:
1235 		/* Must have been deleted. */
1236 		return;
1237 
1238 	case EINVAL:
1239 	case ENOTSUP:
1240 	default:
1241 		bad_error("libscf_handle_rebind", r);
1242 	}
1243 
1244 again:
1245 	r = restarter_remove_contract(inst, ctid, RESTARTER_CONTRACT_PRIMARY);
1246 	switch (r) {
1247 	case 0:
1248 		break;
1249 
1250 	case ENOMEM:
1251 		++tries;
1252 		if (tries < ALLOC_RETRY) {
1253 			(void) poll(NULL, 0, msecs);
1254 			msecs *= ALLOC_DELAY_MULT;
1255 			goto again;
1256 		}
1257 
1258 		uu_die("Insufficient memory.\n");
1259 		/* NOTREACHED */
1260 
1261 	case ECONNABORTED:
1262 		scf_instance_destroy(inst);
1263 		libscf_handle_rebind(h);
1264 		goto rep_retry;
1265 
1266 	case ECANCELED:
1267 		break;
1268 
1269 	case EPERM:
1270 	case EACCES:
1271 	case EROFS:
1272 		log_error(LOG_INFO,
1273 		    "Could not remove contract id %lu for %s (%s).\n", ctid,
1274 		    rip->ri_i.i_fmri, strerror(r));
1275 		break;
1276 
1277 	case EINVAL:
1278 	case EBADF:
1279 	default:
1280 		bad_error("restarter_remove_contract", r);
1281 	}
1282 
1283 	scf_instance_destroy(inst);
1284 }
1285 
1286 /*
1287  * enable_inst()
1288  *   Set inst->ri_i.i_enabled.  Expects 'e' to be _ENABLE, _DISABLE, or
1289  *   _ADMIN_DISABLE.  If the event is _ENABLE and inst is uninitialized or
1290  *   disabled, move it to offline.  If the event is _DISABLE or
1291  *   _ADMIN_DISABLE, make sure inst will move to disabled.
1292  *
1293  *   Returns
1294  *     0 - success
1295  *     ECONNRESET - h was rebound
1296  */
1297 static int
1298 enable_inst(scf_handle_t *h, restarter_inst_t *inst, restarter_event_type_t e)
1299 {
1300 	restarter_instance_state_t state;
1301 	int r;
1302 
1303 	assert(MUTEX_HELD(&inst->ri_lock));
1304 	assert(e == RESTARTER_EVENT_TYPE_ADMIN_DISABLE ||
1305 	    e == RESTARTER_EVENT_TYPE_DISABLE ||
1306 	    e == RESTARTER_EVENT_TYPE_ENABLE);
1307 	assert(instance_in_transition(inst) == 0);
1308 
1309 	state = inst->ri_i.i_state;
1310 
1311 	if (e == RESTARTER_EVENT_TYPE_ENABLE) {
1312 		inst->ri_i.i_enabled = 1;
1313 
1314 		if (state == RESTARTER_STATE_UNINIT ||
1315 		    state == RESTARTER_STATE_DISABLED) {
1316 			/*
1317 			 * B_FALSE: Don't log an error if the log_instance()
1318 			 * fails because it will fail on the miniroot before
1319 			 * install-discovery runs.
1320 			 */
1321 			log_instance(inst, B_FALSE, "Enabled.");
1322 			log_framework(LOG_DEBUG, "%s: Instance enabled.\n",
1323 			    inst->ri_i.i_fmri);
1324 			(void) restarter_instance_update_states(h, inst,
1325 			    RESTARTER_STATE_OFFLINE, RESTARTER_STATE_NONE,
1326 			    RERR_NONE, NULL);
1327 		} else {
1328 			log_framework(LOG_DEBUG, "Restarter: "
1329 			    "Not changing state of %s for enable command.\n",
1330 			    inst->ri_i.i_fmri);
1331 		}
1332 	} else {
1333 		inst->ri_i.i_enabled = 0;
1334 
1335 		switch (state) {
1336 		case RESTARTER_STATE_ONLINE:
1337 		case RESTARTER_STATE_DEGRADED:
1338 			r = stop_instance(h, inst, RSTOP_DISABLE);
1339 			return (r == ECONNRESET ? 0 : r);
1340 
1341 		case RESTARTER_STATE_OFFLINE:
1342 		case RESTARTER_STATE_UNINIT:
1343 			if (inst->ri_i.i_primary_ctid != 0) {
1344 				inst->ri_m_inst = safe_scf_instance_create(h);
1345 				inst->ri_mi_deleted = B_FALSE;
1346 
1347 				libscf_reget_instance(inst);
1348 				method_remove_contract(inst, B_TRUE, B_TRUE);
1349 
1350 				scf_instance_destroy(inst->ri_m_inst);
1351 			}
1352 			/* B_FALSE: See log_instance(..., "Enabled."); above */
1353 			log_instance(inst, B_FALSE, "Disabled.");
1354 			log_framework(LOG_DEBUG, "%s: Instance disabled.\n",
1355 			    inst->ri_i.i_fmri);
1356 			(void) restarter_instance_update_states(h, inst,
1357 			    RESTARTER_STATE_DISABLED, RESTARTER_STATE_NONE,
1358 			    RERR_RESTART, NULL);
1359 			return (0);
1360 
1361 		case RESTARTER_STATE_DISABLED:
1362 			break;
1363 
1364 		case RESTARTER_STATE_MAINT:
1365 			/*
1366 			 * We only want to pull the instance out of maintenance
1367 			 * if the disable is on adminstrative request.  The
1368 			 * graph engine sends _DISABLE events whenever a
1369 			 * service isn't in the disabled state, and we don't
1370 			 * want to pull the service out of maintenance if,
1371 			 * for example, it is there due to a dependency cycle.
1372 			 */
1373 			if (e == RESTARTER_EVENT_TYPE_ADMIN_DISABLE)
1374 				unmaintain_instance(h, inst, RUNMAINT_DISABLE);
1375 			break;
1376 
1377 		default:
1378 #ifndef NDEBUG
1379 			(void) fprintf(stderr, "Restarter instance %s has "
1380 			    "unknown state %d.\n", inst->ri_i.i_fmri, state);
1381 #endif
1382 			abort();
1383 		}
1384 	}
1385 
1386 	return (0);
1387 }
1388 
1389 static void
1390 start_instance(scf_handle_t *local_handle, restarter_inst_t *inst)
1391 {
1392 	fork_info_t *info;
1393 
1394 	assert(MUTEX_HELD(&inst->ri_lock));
1395 	assert(instance_in_transition(inst) == 0);
1396 	assert(inst->ri_method_thread == 0);
1397 
1398 	log_framework(LOG_DEBUG, "%s: trying to start instance\n",
1399 	    inst->ri_i.i_fmri);
1400 
1401 	/* Services in the disabled and maintenance state are ignored */
1402 	if (inst->ri_i.i_state == RESTARTER_STATE_MAINT ||
1403 	    inst->ri_i.i_state == RESTARTER_STATE_DISABLED ||
1404 	    inst->ri_i.i_enabled == 0) {
1405 		log_framework(LOG_DEBUG,
1406 		    "%s: start_instance -> is maint/disabled\n",
1407 		    inst->ri_i.i_fmri);
1408 		return;
1409 	}
1410 
1411 	/* Already started instances are left alone */
1412 	if (instance_started(inst) == 1) {
1413 		log_framework(LOG_DEBUG,
1414 		    "%s: start_instance -> is already started\n",
1415 		    inst->ri_i.i_fmri);
1416 		return;
1417 	}
1418 
1419 	log_framework(LOG_DEBUG, "%s: starting instance.\n", inst->ri_i.i_fmri);
1420 
1421 	(void) restarter_instance_update_states(local_handle, inst,
1422 	    inst->ri_i.i_state, RESTARTER_STATE_ONLINE, RERR_NONE, "none");
1423 
1424 	info = startd_zalloc(sizeof (fork_info_t));
1425 
1426 	info->sf_id = inst->ri_id;
1427 	info->sf_method_type = METHOD_START;
1428 	info->sf_event_type = RERR_NONE;
1429 	inst->ri_method_thread = startd_thread_create(method_thread, info);
1430 }
1431 
1432 static int
1433 event_from_tty(scf_handle_t *h, restarter_inst_t *rip)
1434 {
1435 	scf_instance_t *inst;
1436 	int ret = 0;
1437 
1438 	if (libscf_fmri_get_instance(h, rip->ri_i.i_fmri, &inst))
1439 		return (-1);
1440 
1441 	ret = restarter_inst_ractions_from_tty(inst);
1442 
1443 	scf_instance_destroy(inst);
1444 	return (ret);
1445 }
1446 
1447 static void
1448 maintain_instance(scf_handle_t *h, restarter_inst_t *rip, int immediate,
1449     const char *aux)
1450 {
1451 	fork_info_t *info;
1452 	scf_instance_t *scf_inst = NULL;
1453 
1454 	assert(MUTEX_HELD(&rip->ri_lock));
1455 	assert(aux != NULL);
1456 	assert(rip->ri_method_thread == 0);
1457 
1458 	log_instance(rip, B_TRUE, "Stopping for maintenance due to %s.", aux);
1459 	log_framework(LOG_DEBUG, "%s: stopping for maintenance due to %s.\n",
1460 	    rip->ri_i.i_fmri, aux);
1461 
1462 	/* Services in the maintenance state are ignored */
1463 	if (rip->ri_i.i_state == RESTARTER_STATE_MAINT) {
1464 		log_framework(LOG_DEBUG,
1465 		    "%s: maintain_instance -> is already in maintenance\n",
1466 		    rip->ri_i.i_fmri);
1467 		return;
1468 	}
1469 
1470 	/*
1471 	 * If aux state is "service_request" and
1472 	 * restarter_actions/auxiliary_fmri property is set with a valid fmri,
1473 	 * copy the fmri to restarter/auxiliary_fmri so svcs -x can use.
1474 	 */
1475 	if (strcmp(aux, "service_request") == 0 && libscf_fmri_get_instance(h,
1476 	    rip->ri_i.i_fmri, &scf_inst) == 0) {
1477 		if (restarter_inst_validate_ractions_aux_fmri(scf_inst) == 0) {
1478 			if (restarter_inst_set_aux_fmri(scf_inst))
1479 				log_framework(LOG_DEBUG, "%s: "
1480 				    "restarter_inst_set_aux_fmri failed: ",
1481 				    rip->ri_i.i_fmri);
1482 		} else {
1483 			log_framework(LOG_DEBUG, "%s: "
1484 			    "restarter_inst_validate_ractions_aux_fmri "
1485 			    "failed: ", rip->ri_i.i_fmri);
1486 
1487 			if (restarter_inst_reset_aux_fmri(scf_inst))
1488 				log_framework(LOG_DEBUG, "%s: "
1489 				    "restarter_inst_reset_aux_fmri failed: ",
1490 				    rip->ri_i.i_fmri);
1491 		}
1492 		scf_instance_destroy(scf_inst);
1493 	}
1494 
1495 	if (immediate || !instance_started(rip)) {
1496 		if (rip->ri_i.i_primary_ctid != 0) {
1497 			rip->ri_m_inst = safe_scf_instance_create(h);
1498 			rip->ri_mi_deleted = B_FALSE;
1499 
1500 			libscf_reget_instance(rip);
1501 			method_remove_contract(rip, B_TRUE, B_TRUE);
1502 
1503 			scf_instance_destroy(rip->ri_m_inst);
1504 		}
1505 
1506 		(void) restarter_instance_update_states(h, rip,
1507 		    RESTARTER_STATE_MAINT, RESTARTER_STATE_NONE, RERR_RESTART,
1508 		    (char *)aux);
1509 		return;
1510 	}
1511 
1512 	(void) restarter_instance_update_states(h, rip, rip->ri_i.i_state,
1513 	    RESTARTER_STATE_MAINT, RERR_NONE, (char *)aux);
1514 
1515 	log_transition(rip, MAINT_REQUESTED);
1516 
1517 	info = startd_zalloc(sizeof (*info));
1518 	info->sf_id = rip->ri_id;
1519 	info->sf_method_type = METHOD_STOP;
1520 	info->sf_event_type = RERR_RESTART;
1521 	rip->ri_method_thread = startd_thread_create(method_thread, info);
1522 }
1523 
1524 static void
1525 refresh_instance(scf_handle_t *h, restarter_inst_t *rip)
1526 {
1527 	scf_instance_t *inst;
1528 	scf_snapshot_t *snap;
1529 	fork_info_t *info;
1530 	int r;
1531 
1532 	assert(MUTEX_HELD(&rip->ri_lock));
1533 
1534 	log_instance(rip, B_TRUE, "Rereading configuration.");
1535 	log_framework(LOG_DEBUG, "%s: rereading configuration.\n",
1536 	    rip->ri_i.i_fmri);
1537 
1538 rep_retry:
1539 	r = libscf_fmri_get_instance(h, rip->ri_i.i_fmri, &inst);
1540 	switch (r) {
1541 	case 0:
1542 		break;
1543 
1544 	case ECONNABORTED:
1545 		libscf_handle_rebind(h);
1546 		goto rep_retry;
1547 
1548 	case ENOENT:
1549 		/* Must have been deleted. */
1550 		return;
1551 
1552 	case EINVAL:
1553 	case ENOTSUP:
1554 	default:
1555 		bad_error("libscf_fmri_get_instance", r);
1556 	}
1557 
1558 	snap = libscf_get_running_snapshot(inst);
1559 
1560 	r = libscf_get_startd_properties(inst, snap, &rip->ri_flags,
1561 	    &rip->ri_utmpx_prefix);
1562 	switch (r) {
1563 	case 0:
1564 		log_framework(LOG_DEBUG, "%s is a %s-style service\n",
1565 		    rip->ri_i.i_fmri, service_style(rip->ri_flags));
1566 		break;
1567 
1568 	case ECONNABORTED:
1569 		scf_instance_destroy(inst);
1570 		scf_snapshot_destroy(snap);
1571 		libscf_handle_rebind(h);
1572 		goto rep_retry;
1573 
1574 	case ECANCELED:
1575 	case ENOENT:
1576 		/* Succeed in anticipation of REMOVE_INSTANCE. */
1577 		break;
1578 
1579 	default:
1580 		bad_error("libscf_get_startd_properties", r);
1581 	}
1582 
1583 	if (instance_started(rip)) {
1584 		/* Refresh does not change the state. */
1585 		(void) restarter_instance_update_states(h, rip,
1586 		    rip->ri_i.i_state, rip->ri_i.i_state, RERR_NONE, NULL);
1587 
1588 		info = startd_zalloc(sizeof (*info));
1589 		info->sf_id = rip->ri_id;
1590 		info->sf_method_type = METHOD_REFRESH;
1591 		info->sf_event_type = RERR_REFRESH;
1592 
1593 		assert(rip->ri_method_thread == 0);
1594 		rip->ri_method_thread =
1595 		    startd_thread_create(method_thread, info);
1596 	}
1597 
1598 	scf_snapshot_destroy(snap);
1599 	scf_instance_destroy(inst);
1600 }
1601 
1602 const char *event_names[] = { "INVALID", "ADD_INSTANCE", "REMOVE_INSTANCE",
1603 	"ENABLE", "DISABLE", "ADMIN_DEGRADED", "ADMIN_REFRESH",
1604 	"ADMIN_RESTART", "ADMIN_MAINT_OFF", "ADMIN_MAINT_ON",
1605 	"ADMIN_MAINT_ON_IMMEDIATE", "STOP", "START", "DEPENDENCY_CYCLE",
1606 	"INVALID_DEPENDENCY", "ADMIN_DISABLE", "STOP_RESET"
1607 };
1608 
1609 /*
1610  * void *restarter_process_events()
1611  *
1612  *   Called in a separate thread to process the events on an instance's
1613  *   queue.  Empties the queue completely, and tries to keep the thread
1614  *   around for a little while after the queue is empty to save on
1615  *   startup costs.
1616  */
1617 static void *
1618 restarter_process_events(void *arg)
1619 {
1620 	scf_handle_t *h;
1621 	restarter_instance_qentry_t *event;
1622 	restarter_inst_t *rip;
1623 	char *fmri = (char *)arg;
1624 	struct timespec to;
1625 
1626 	assert(fmri != NULL);
1627 
1628 	h = libscf_handle_create_bound_loop();
1629 
1630 	/* grab the queue lock */
1631 	rip = inst_lookup_queue(fmri);
1632 	if (rip == NULL)
1633 		goto out;
1634 
1635 again:
1636 
1637 	while ((event = uu_list_first(rip->ri_queue)) != NULL) {
1638 		restarter_inst_t *inst;
1639 
1640 		/* drop the queue lock */
1641 		MUTEX_UNLOCK(&rip->ri_queue_lock);
1642 
1643 		/*
1644 		 * Grab the inst lock -- this waits until any outstanding
1645 		 * method finishes running.
1646 		 */
1647 		inst = inst_lookup_by_name(fmri);
1648 		if (inst == NULL) {
1649 			/* Getting deleted in the middle isn't an error. */
1650 			goto cont;
1651 		}
1652 
1653 		assert(instance_in_transition(inst) == 0);
1654 
1655 		/* process the event */
1656 		switch (event->riq_type) {
1657 		case RESTARTER_EVENT_TYPE_ENABLE:
1658 		case RESTARTER_EVENT_TYPE_DISABLE:
1659 			(void) enable_inst(h, inst, event->riq_type);
1660 			break;
1661 
1662 		case RESTARTER_EVENT_TYPE_ADMIN_DISABLE:
1663 			if (enable_inst(h, inst, event->riq_type) == 0)
1664 				reset_start_times(inst);
1665 			break;
1666 
1667 		case RESTARTER_EVENT_TYPE_REMOVE_INSTANCE:
1668 			restarter_delete_inst(inst);
1669 			inst = NULL;
1670 			goto cont;
1671 
1672 		case RESTARTER_EVENT_TYPE_STOP_RESET:
1673 			reset_start_times(inst);
1674 			/* FALLTHROUGH */
1675 		case RESTARTER_EVENT_TYPE_STOP:
1676 			(void) stop_instance(h, inst, RSTOP_DEPENDENCY);
1677 			break;
1678 
1679 		case RESTARTER_EVENT_TYPE_START:
1680 			start_instance(h, inst);
1681 			break;
1682 
1683 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
1684 			maintain_instance(h, inst, 0, "dependency_cycle");
1685 			break;
1686 
1687 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
1688 			maintain_instance(h, inst, 0, "invalid_dependency");
1689 			break;
1690 
1691 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1692 			if (event_from_tty(h, inst) == 0)
1693 				maintain_instance(h, inst, 0,
1694 				    "service_request");
1695 			else
1696 				maintain_instance(h, inst, 0,
1697 				    "administrative_request");
1698 			break;
1699 
1700 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON_IMMEDIATE:
1701 			if (event_from_tty(h, inst) == 0)
1702 				maintain_instance(h, inst, 1,
1703 				    "service_request");
1704 			else
1705 				maintain_instance(h, inst, 1,
1706 				    "administrative_request");
1707 			break;
1708 
1709 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_OFF:
1710 			unmaintain_instance(h, inst, RUNMAINT_CLEAR);
1711 			break;
1712 
1713 		case RESTARTER_EVENT_TYPE_ADMIN_REFRESH:
1714 			refresh_instance(h, inst);
1715 			break;
1716 
1717 		case RESTARTER_EVENT_TYPE_ADMIN_DEGRADED:
1718 			log_framework(LOG_WARNING, "Restarter: "
1719 			    "%s command (for %s) unimplemented.\n",
1720 			    event_names[event->riq_type], inst->ri_i.i_fmri);
1721 			break;
1722 
1723 		case RESTARTER_EVENT_TYPE_ADMIN_RESTART:
1724 			if (!instance_started(inst)) {
1725 				log_framework(LOG_DEBUG, "Restarter: "
1726 				    "Not restarting %s; not running.\n",
1727 				    inst->ri_i.i_fmri);
1728 			} else {
1729 				/*
1730 				 * Stop the instance.  If it can be restarted,
1731 				 * the graph engine will send a new event.
1732 				 */
1733 				if (stop_instance(h, inst, RSTOP_RESTART) == 0)
1734 					reset_start_times(inst);
1735 			}
1736 			break;
1737 
1738 		case RESTARTER_EVENT_TYPE_ADD_INSTANCE:
1739 		default:
1740 #ifndef NDEBUG
1741 			uu_warn("%s:%d: Bad restarter event %d.  "
1742 			    "Aborting.\n", __FILE__, __LINE__, event->riq_type);
1743 #endif
1744 			abort();
1745 		}
1746 
1747 		assert(inst != NULL);
1748 		MUTEX_UNLOCK(&inst->ri_lock);
1749 
1750 cont:
1751 		/* grab the queue lock */
1752 		rip = inst_lookup_queue(fmri);
1753 		if (rip == NULL)
1754 			goto out;
1755 
1756 		/* delete the event */
1757 		uu_list_remove(rip->ri_queue, event);
1758 		startd_free(event, sizeof (restarter_instance_qentry_t));
1759 	}
1760 
1761 	assert(rip != NULL);
1762 
1763 	/*
1764 	 * Try to preserve the thread for a little while for future use.
1765 	 */
1766 	to.tv_sec = 3;
1767 	to.tv_nsec = 0;
1768 	(void) pthread_cond_reltimedwait_np(&rip->ri_queue_cv,
1769 	    &rip->ri_queue_lock, &to);
1770 
1771 	if (uu_list_first(rip->ri_queue) != NULL)
1772 		goto again;
1773 
1774 	rip->ri_queue_thread = 0;
1775 	MUTEX_UNLOCK(&rip->ri_queue_lock);
1776 out:
1777 	(void) scf_handle_unbind(h);
1778 	scf_handle_destroy(h);
1779 	free(fmri);
1780 	return (NULL);
1781 }
1782 
1783 static int
1784 is_admin_event(restarter_event_type_t t) {
1785 
1786 	switch (t) {
1787 	case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1788 	case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON_IMMEDIATE:
1789 	case RESTARTER_EVENT_TYPE_ADMIN_MAINT_OFF:
1790 	case RESTARTER_EVENT_TYPE_ADMIN_REFRESH:
1791 	case RESTARTER_EVENT_TYPE_ADMIN_DEGRADED:
1792 	case RESTARTER_EVENT_TYPE_ADMIN_RESTART:
1793 		return (1);
1794 	default:
1795 		return (0);
1796 	}
1797 }
1798 
1799 static void
1800 restarter_queue_event(restarter_inst_t *ri, restarter_protocol_event_t *e)
1801 {
1802 	restarter_instance_qentry_t *qe;
1803 	int r;
1804 
1805 	assert(MUTEX_HELD(&ri->ri_queue_lock));
1806 	assert(!MUTEX_HELD(&ri->ri_lock));
1807 
1808 	qe = startd_zalloc(sizeof (restarter_instance_qentry_t));
1809 	qe->riq_type = e->rpe_type;
1810 
1811 	uu_list_node_init(qe, &qe->riq_link, restarter_queue_pool);
1812 	r = uu_list_insert_before(ri->ri_queue, NULL, qe);
1813 	assert(r == 0);
1814 }
1815 
1816 /*
1817  * void *restarter_event_thread()
1818  *
1819  *  Handle incoming graph events by placing them on a per-instance
1820  *  queue.  We can't lock the main part of the instance structure, so
1821  *  just modify the seprarately locked event queue portion.
1822  */
1823 /*ARGSUSED*/
1824 static void *
1825 restarter_event_thread(void *unused)
1826 {
1827 	scf_handle_t *h;
1828 
1829 	/*
1830 	 * This is a new thread, and thus, gets its own handle
1831 	 * to the repository.
1832 	 */
1833 	h = libscf_handle_create_bound_loop();
1834 
1835 	MUTEX_LOCK(&ru->restarter_update_lock);
1836 
1837 	/*CONSTCOND*/
1838 	while (1) {
1839 		restarter_protocol_event_t *e;
1840 
1841 		while (ru->restarter_update_wakeup == 0)
1842 			(void) pthread_cond_wait(&ru->restarter_update_cv,
1843 			    &ru->restarter_update_lock);
1844 
1845 		ru->restarter_update_wakeup = 0;
1846 
1847 		while ((e = restarter_event_dequeue()) != NULL) {
1848 			restarter_inst_t *rip;
1849 			char *fmri;
1850 
1851 			MUTEX_UNLOCK(&ru->restarter_update_lock);
1852 
1853 			/*
1854 			 * ADD_INSTANCE is special: there's likely no
1855 			 * instance structure yet, so we need to handle the
1856 			 * addition synchronously.
1857 			 */
1858 			switch (e->rpe_type) {
1859 			case RESTARTER_EVENT_TYPE_ADD_INSTANCE:
1860 				if (restarter_insert_inst(h, e->rpe_inst) != 0)
1861 					log_error(LOG_INFO, "Restarter: "
1862 					    "Could not add %s.\n", e->rpe_inst);
1863 
1864 				MUTEX_LOCK(&st->st_load_lock);
1865 				if (--st->st_load_instances == 0)
1866 					(void) pthread_cond_broadcast(
1867 					    &st->st_load_cv);
1868 				MUTEX_UNLOCK(&st->st_load_lock);
1869 
1870 				goto nolookup;
1871 			}
1872 
1873 			/*
1874 			 * Lookup the instance, locking only the event queue.
1875 			 * Can't grab ri_lock here because it might be held
1876 			 * by a long-running method.
1877 			 */
1878 			rip = inst_lookup_queue(e->rpe_inst);
1879 			if (rip == NULL) {
1880 				log_error(LOG_INFO, "Restarter: "
1881 				    "Ignoring %s command for unknown service "
1882 				    "%s.\n", event_names[e->rpe_type],
1883 				    e->rpe_inst);
1884 				goto nolookup;
1885 			}
1886 
1887 			/* Keep ADMIN events from filling up the queue. */
1888 			if (is_admin_event(e->rpe_type) &&
1889 			    uu_list_numnodes(rip->ri_queue) >
1890 			    RINST_QUEUE_THRESHOLD) {
1891 				MUTEX_UNLOCK(&rip->ri_queue_lock);
1892 				log_instance(rip, B_TRUE, "Instance event "
1893 				    "queue overflow.  Dropping administrative "
1894 				    "request.");
1895 				log_framework(LOG_DEBUG, "%s: Instance event "
1896 				    "queue overflow.  Dropping administrative "
1897 				    "request.\n", rip->ri_i.i_fmri);
1898 				goto nolookup;
1899 			}
1900 
1901 			/* Now add the event to the instance queue. */
1902 			restarter_queue_event(rip, e);
1903 
1904 			if (rip->ri_queue_thread == 0) {
1905 				/*
1906 				 * Start a thread if one isn't already
1907 				 * running.
1908 				 */
1909 				fmri = safe_strdup(e->rpe_inst);
1910 				rip->ri_queue_thread =  startd_thread_create(
1911 				    restarter_process_events, (void *)fmri);
1912 			} else {
1913 				/*
1914 				 * Signal the existing thread that there's
1915 				 * a new event.
1916 				 */
1917 				(void) pthread_cond_broadcast(
1918 				    &rip->ri_queue_cv);
1919 			}
1920 
1921 			MUTEX_UNLOCK(&rip->ri_queue_lock);
1922 nolookup:
1923 			restarter_event_release(e);
1924 
1925 			MUTEX_LOCK(&ru->restarter_update_lock);
1926 		}
1927 	}
1928 
1929 	/*
1930 	 * Unreachable for now -- there's currently no graceful cleanup
1931 	 * called on exit().
1932 	 */
1933 	(void) scf_handle_unbind(h);
1934 	scf_handle_destroy(h);
1935 	return (NULL);
1936 }
1937 
1938 static restarter_inst_t *
1939 contract_to_inst(ctid_t ctid)
1940 {
1941 	restarter_inst_t *inst;
1942 	int id;
1943 
1944 	id = lookup_inst_by_contract(ctid);
1945 	if (id == -1)
1946 		return (NULL);
1947 
1948 	inst = inst_lookup_by_id(id);
1949 	if (inst != NULL) {
1950 		/*
1951 		 * Since ri_lock isn't held by the contract id lookup, this
1952 		 * instance may have been restarted and now be in a new
1953 		 * contract, making the old contract no longer valid for this
1954 		 * instance.
1955 		 */
1956 		if (ctid != inst->ri_i.i_primary_ctid) {
1957 			MUTEX_UNLOCK(&inst->ri_lock);
1958 			inst = NULL;
1959 		}
1960 	}
1961 	return (inst);
1962 }
1963 
1964 /*
1965  * void contract_action()
1966  *   Take action on contract events.
1967  */
1968 static void
1969 contract_action(scf_handle_t *h, restarter_inst_t *inst, ctid_t id,
1970     uint32_t type)
1971 {
1972 	const char *fmri = inst->ri_i.i_fmri;
1973 
1974 	assert(MUTEX_HELD(&inst->ri_lock));
1975 
1976 	/*
1977 	 * If startd has stopped this contract, there is no need to
1978 	 * stop it again.
1979 	 */
1980 	if (inst->ri_i.i_primary_ctid > 0 &&
1981 	    inst->ri_i.i_primary_ctid_stopped)
1982 		return;
1983 
1984 	if ((type & (CT_PR_EV_EMPTY | CT_PR_EV_CORE | CT_PR_EV_SIGNAL
1985 	    | CT_PR_EV_HWERR)) == 0) {
1986 		/*
1987 		 * There shouldn't be other events, since that's not how we set
1988 		 * the terms. Thus, just log an error and drive on.
1989 		 */
1990 		log_framework(LOG_NOTICE,
1991 		    "%s: contract %ld received unexpected critical event "
1992 		    "(%d)\n", fmri, id, type);
1993 		return;
1994 	}
1995 
1996 	assert(instance_in_transition(inst) == 0);
1997 
1998 	if (instance_is_wait_style(inst)) {
1999 		/*
2000 		 * We ignore all events; if they impact the
2001 		 * process we're monitoring, then the
2002 		 * wait_thread will stop the instance.
2003 		 */
2004 		log_framework(LOG_DEBUG,
2005 		    "%s: ignoring contract event on wait-style service\n",
2006 		    fmri);
2007 	} else {
2008 		/*
2009 		 * A CT_PR_EV_EMPTY event is an RSTOP_EXIT request.
2010 		 */
2011 		switch (type) {
2012 		case CT_PR_EV_EMPTY:
2013 			(void) stop_instance(h, inst, RSTOP_EXIT);
2014 			break;
2015 		case CT_PR_EV_CORE:
2016 			(void) stop_instance(h, inst, RSTOP_CORE);
2017 			break;
2018 		case CT_PR_EV_SIGNAL:
2019 			(void) stop_instance(h, inst, RSTOP_SIGNAL);
2020 			break;
2021 		case CT_PR_EV_HWERR:
2022 			(void) stop_instance(h, inst, RSTOP_HWERR);
2023 			break;
2024 		}
2025 	}
2026 }
2027 
2028 /*
2029  * void *restarter_contract_event_thread(void *)
2030  *   Listens to the process contract bundle for critical events, taking action
2031  *   on events from contracts we know we are responsible for.
2032  */
2033 /*ARGSUSED*/
2034 static void *
2035 restarter_contracts_event_thread(void *unused)
2036 {
2037 	int fd, err;
2038 	scf_handle_t *local_handle;
2039 
2040 	/*
2041 	 * Await graph load completion.  That is, stop here, until we've scanned
2042 	 * the repository for contract - instance associations.
2043 	 */
2044 	MUTEX_LOCK(&st->st_load_lock);
2045 	while (!(st->st_load_complete && st->st_load_instances == 0))
2046 		(void) pthread_cond_wait(&st->st_load_cv, &st->st_load_lock);
2047 	MUTEX_UNLOCK(&st->st_load_lock);
2048 
2049 	/*
2050 	 * This is a new thread, and thus, gets its own handle
2051 	 * to the repository.
2052 	 */
2053 	if ((local_handle = libscf_handle_create_bound(SCF_VERSION)) == NULL)
2054 		uu_die("Unable to bind a new repository handle: %s\n",
2055 		    scf_strerror(scf_error()));
2056 
2057 	fd = open64(CTFS_ROOT "/process/pbundle", O_RDONLY);
2058 	if (fd == -1)
2059 		uu_die("process bundle open failed");
2060 
2061 	/*
2062 	 * Make sure we get all events (including those generated by configd
2063 	 * before this thread was started).
2064 	 */
2065 	err = ct_event_reset(fd);
2066 	assert(err == 0);
2067 
2068 	for (;;) {
2069 		int efd, sfd;
2070 		ct_evthdl_t ev;
2071 		uint32_t type;
2072 		ctevid_t evid;
2073 		ct_stathdl_t status;
2074 		ctid_t ctid;
2075 		restarter_inst_t *inst;
2076 		uint64_t cookie;
2077 
2078 		if (err = ct_event_read_critical(fd, &ev)) {
2079 			log_error(LOG_WARNING,
2080 			    "Error reading next contract event: %s",
2081 			    strerror(err));
2082 			continue;
2083 		}
2084 
2085 		evid = ct_event_get_evid(ev);
2086 		ctid = ct_event_get_ctid(ev);
2087 		type = ct_event_get_type(ev);
2088 
2089 		/* Fetch cookie. */
2090 		if ((sfd = contract_open(ctid, "process", "status", O_RDONLY))
2091 		    < 0) {
2092 			ct_event_free(ev);
2093 			continue;
2094 		}
2095 
2096 		if (err = ct_status_read(sfd, CTD_COMMON, &status)) {
2097 			log_framework(LOG_WARNING, "Could not get status for "
2098 			    "contract %ld: %s\n", ctid, strerror(err));
2099 
2100 			startd_close(sfd);
2101 			ct_event_free(ev);
2102 			continue;
2103 		}
2104 
2105 		cookie = ct_status_get_cookie(status);
2106 
2107 		log_framework(LOG_DEBUG, "Received event %d for ctid %ld "
2108 		    "cookie %lld\n", type, ctid, cookie);
2109 
2110 		ct_status_free(status);
2111 
2112 		startd_close(sfd);
2113 
2114 		/*
2115 		 * svc.configd(1M) restart handling performed by the
2116 		 * fork_configd_thread.  We don't acknowledge, as that thread
2117 		 * will do so.
2118 		 */
2119 		if (cookie == CONFIGD_COOKIE) {
2120 			ct_event_free(ev);
2121 			continue;
2122 		}
2123 
2124 		inst = NULL;
2125 		if (storing_contract != 0 &&
2126 		    (inst = contract_to_inst(ctid)) == NULL) {
2127 			/*
2128 			 * This can happen for two reasons:
2129 			 * - method_run() has not yet stored the
2130 			 *    the contract into the internal hash table.
2131 			 * - we receive an EMPTY event for an abandoned
2132 			 *    contract.
2133 			 * If there is any contract in the process of
2134 			 * being stored into the hash table then re-read
2135 			 * the event later.
2136 			 */
2137 			log_framework(LOG_DEBUG,
2138 			    "Reset event %d for unknown "
2139 			    "contract id %ld\n", type, ctid);
2140 
2141 			/* don't go too fast */
2142 			(void) poll(NULL, 0, 100);
2143 
2144 			(void) ct_event_reset(fd);
2145 			ct_event_free(ev);
2146 			continue;
2147 		}
2148 
2149 		/*
2150 		 * Do not call contract_to_inst() again if first
2151 		 * call succeeded.
2152 		 */
2153 		if (inst == NULL)
2154 			inst = contract_to_inst(ctid);
2155 		if (inst == NULL) {
2156 			/*
2157 			 * This can happen if we receive an EMPTY
2158 			 * event for an abandoned contract.
2159 			 */
2160 			log_framework(LOG_DEBUG,
2161 			    "Received event %d for unknown contract id "
2162 			    "%ld\n", type, ctid);
2163 		} else {
2164 			log_framework(LOG_DEBUG,
2165 			    "Received event %d for contract id "
2166 			    "%ld (%s)\n", type, ctid,
2167 			    inst->ri_i.i_fmri);
2168 
2169 			contract_action(local_handle, inst, ctid, type);
2170 
2171 			MUTEX_UNLOCK(&inst->ri_lock);
2172 		}
2173 
2174 		efd = contract_open(ct_event_get_ctid(ev), "process", "ctl",
2175 		    O_WRONLY);
2176 		if (efd != -1) {
2177 			(void) ct_ctl_ack(efd, evid);
2178 			startd_close(efd);
2179 		}
2180 
2181 		ct_event_free(ev);
2182 
2183 	}
2184 
2185 	/*NOTREACHED*/
2186 	return (NULL);
2187 }
2188 
2189 /*
2190  * Timeout queue, processed by restarter_timeouts_event_thread().
2191  */
2192 timeout_queue_t *timeouts;
2193 static uu_list_pool_t *timeout_pool;
2194 
2195 typedef struct timeout_update {
2196 	pthread_mutex_t		tu_lock;
2197 	pthread_cond_t		tu_cv;
2198 	int			tu_wakeup;
2199 } timeout_update_t;
2200 
2201 timeout_update_t *tu;
2202 
2203 static const char *timeout_ovr_svcs[] = {
2204 	"svc:/system/manifest-import:default",
2205 	"svc:/network/initial:default",
2206 	"svc:/network/service:default",
2207 	"svc:/system/rmtmpfiles:default",
2208 	"svc:/network/loopback:default",
2209 	"svc:/network/physical:default",
2210 	"svc:/system/device/local:default",
2211 	"svc:/system/metainit:default",
2212 	"svc:/system/filesystem/usr:default",
2213 	"svc:/system/filesystem/minimal:default",
2214 	"svc:/system/filesystem/local:default",
2215 	NULL
2216 };
2217 
2218 int
2219 is_timeout_ovr(restarter_inst_t *inst)
2220 {
2221 	int i;
2222 
2223 	for (i = 0; timeout_ovr_svcs[i] != NULL; ++i) {
2224 		if (strcmp(inst->ri_i.i_fmri, timeout_ovr_svcs[i]) == 0) {
2225 			log_instance(inst, B_TRUE, "Timeout override by "
2226 			    "svc.startd.  Using infinite timeout.");
2227 			return (1);
2228 		}
2229 	}
2230 
2231 	return (0);
2232 }
2233 
2234 /*ARGSUSED*/
2235 static int
2236 timeout_compare(const void *lc_arg, const void *rc_arg, void *private)
2237 {
2238 	hrtime_t t1 = ((const timeout_entry_t *)lc_arg)->te_timeout;
2239 	hrtime_t t2 = ((const timeout_entry_t *)rc_arg)->te_timeout;
2240 
2241 	if (t1 > t2)
2242 		return (1);
2243 	else if (t1 < t2)
2244 		return (-1);
2245 	return (0);
2246 }
2247 
2248 void
2249 timeout_init()
2250 {
2251 	timeouts = startd_zalloc(sizeof (timeout_queue_t));
2252 
2253 	(void) pthread_mutex_init(&timeouts->tq_lock, &mutex_attrs);
2254 
2255 	timeout_pool = startd_list_pool_create("timeouts",
2256 	    sizeof (timeout_entry_t), offsetof(timeout_entry_t, te_link),
2257 	    timeout_compare, UU_LIST_POOL_DEBUG);
2258 	assert(timeout_pool != NULL);
2259 
2260 	timeouts->tq_list = startd_list_create(timeout_pool,
2261 	    timeouts, UU_LIST_SORTED);
2262 	assert(timeouts->tq_list != NULL);
2263 
2264 	tu = startd_zalloc(sizeof (timeout_update_t));
2265 	(void) pthread_cond_init(&tu->tu_cv, NULL);
2266 	(void) pthread_mutex_init(&tu->tu_lock, &mutex_attrs);
2267 }
2268 
2269 void
2270 timeout_insert(restarter_inst_t *inst, ctid_t cid, uint64_t timeout_sec)
2271 {
2272 	hrtime_t now, timeout;
2273 	timeout_entry_t *entry;
2274 	uu_list_index_t idx;
2275 
2276 	assert(MUTEX_HELD(&inst->ri_lock));
2277 
2278 	now = gethrtime();
2279 
2280 	/*
2281 	 * If we overflow LLONG_MAX, we're never timing out anyways, so
2282 	 * just return.
2283 	 */
2284 	if (timeout_sec >= (LLONG_MAX - now) / 1000000000LL) {
2285 		log_instance(inst, B_TRUE, "timeout_seconds too large, "
2286 		    "treating as infinite.");
2287 		return;
2288 	}
2289 
2290 	/* hrtime is in nanoseconds. Convert timeout_sec. */
2291 	timeout = now + (timeout_sec * 1000000000LL);
2292 
2293 	entry = startd_alloc(sizeof (timeout_entry_t));
2294 	entry->te_timeout = timeout;
2295 	entry->te_ctid = cid;
2296 	entry->te_fmri = safe_strdup(inst->ri_i.i_fmri);
2297 	entry->te_logstem = safe_strdup(inst->ri_logstem);
2298 	entry->te_fired = 0;
2299 	/* Insert the calculated timeout time onto the queue. */
2300 	MUTEX_LOCK(&timeouts->tq_lock);
2301 	(void) uu_list_find(timeouts->tq_list, entry, NULL, &idx);
2302 	uu_list_node_init(entry, &entry->te_link, timeout_pool);
2303 	uu_list_insert(timeouts->tq_list, entry, idx);
2304 	MUTEX_UNLOCK(&timeouts->tq_lock);
2305 
2306 	assert(inst->ri_timeout == NULL);
2307 	inst->ri_timeout = entry;
2308 
2309 	MUTEX_LOCK(&tu->tu_lock);
2310 	tu->tu_wakeup = 1;
2311 	(void) pthread_cond_broadcast(&tu->tu_cv);
2312 	MUTEX_UNLOCK(&tu->tu_lock);
2313 }
2314 
2315 
2316 void
2317 timeout_remove(restarter_inst_t *inst, ctid_t cid)
2318 {
2319 	assert(MUTEX_HELD(&inst->ri_lock));
2320 
2321 	if (inst->ri_timeout == NULL)
2322 		return;
2323 
2324 	assert(inst->ri_timeout->te_ctid == cid);
2325 
2326 	MUTEX_LOCK(&timeouts->tq_lock);
2327 	uu_list_remove(timeouts->tq_list, inst->ri_timeout);
2328 	MUTEX_UNLOCK(&timeouts->tq_lock);
2329 
2330 	free(inst->ri_timeout->te_fmri);
2331 	free(inst->ri_timeout->te_logstem);
2332 	startd_free(inst->ri_timeout, sizeof (timeout_entry_t));
2333 	inst->ri_timeout = NULL;
2334 }
2335 
2336 static int
2337 timeout_now()
2338 {
2339 	timeout_entry_t *e;
2340 	hrtime_t now;
2341 	int ret;
2342 
2343 	now = gethrtime();
2344 
2345 	/*
2346 	 * Walk through the (sorted) timeouts list.  While the timeout
2347 	 * at the head of the list is <= the current time, kill the
2348 	 * method.
2349 	 */
2350 	MUTEX_LOCK(&timeouts->tq_lock);
2351 
2352 	for (e = uu_list_first(timeouts->tq_list);
2353 	    e != NULL && e->te_timeout <= now;
2354 	    e = uu_list_next(timeouts->tq_list, e)) {
2355 		log_framework(LOG_WARNING, "%s: Method or service exit timed "
2356 		    "out.  Killing contract %ld.\n", e->te_fmri, e->te_ctid);
2357 		log_instance_fmri(e->te_fmri, e->te_logstem, B_TRUE,
2358 		    "Method or service exit timed out.  Killing contract %ld.",
2359 		    e->te_ctid);
2360 		e->te_fired = 1;
2361 		(void) contract_kill(e->te_ctid, SIGKILL, e->te_fmri);
2362 	}
2363 
2364 	if (uu_list_numnodes(timeouts->tq_list) > 0)
2365 		ret = 0;
2366 	else
2367 		ret = -1;
2368 
2369 	MUTEX_UNLOCK(&timeouts->tq_lock);
2370 
2371 	return (ret);
2372 }
2373 
2374 /*
2375  * void *restarter_timeouts_event_thread(void *)
2376  *   Responsible for monitoring the method timeouts.  This thread must
2377  *   be started before any methods are called.
2378  */
2379 /*ARGSUSED*/
2380 static void *
2381 restarter_timeouts_event_thread(void *unused)
2382 {
2383 	/*
2384 	 * Timeouts are entered on a priority queue, which is processed by
2385 	 * this thread.  As timeouts are specified in seconds, we'll do
2386 	 * the necessary processing every second, as long as the queue
2387 	 * is not empty.
2388 	 */
2389 
2390 	/*CONSTCOND*/
2391 	while (1) {
2392 		/*
2393 		 * As long as the timeout list isn't empty, process it
2394 		 * every second.
2395 		 */
2396 		if (timeout_now() == 0) {
2397 			(void) sleep(1);
2398 			continue;
2399 		}
2400 
2401 		/* The list is empty, wait until we have more timeouts. */
2402 		MUTEX_LOCK(&tu->tu_lock);
2403 
2404 		while (tu->tu_wakeup == 0)
2405 			(void) pthread_cond_wait(&tu->tu_cv, &tu->tu_lock);
2406 
2407 		tu->tu_wakeup = 0;
2408 		MUTEX_UNLOCK(&tu->tu_lock);
2409 	}
2410 
2411 	return (NULL);
2412 }
2413 
2414 void
2415 restarter_start()
2416 {
2417 	(void) startd_thread_create(restarter_timeouts_event_thread, NULL);
2418 	(void) startd_thread_create(restarter_event_thread, NULL);
2419 	(void) startd_thread_create(restarter_contracts_event_thread, NULL);
2420 	(void) startd_thread_create(wait_thread, NULL);
2421 }
2422 
2423 
2424 void
2425 restarter_init()
2426 {
2427 	restarter_instance_pool = startd_list_pool_create("restarter_instances",
2428 	    sizeof (restarter_inst_t), offsetof(restarter_inst_t,
2429 	    ri_link), restarter_instance_compare, UU_LIST_POOL_DEBUG);
2430 	(void) memset(&instance_list, 0, sizeof (instance_list));
2431 
2432 	(void) pthread_mutex_init(&instance_list.ril_lock, &mutex_attrs);
2433 	instance_list.ril_instance_list = startd_list_create(
2434 	    restarter_instance_pool, &instance_list, UU_LIST_SORTED);
2435 
2436 	restarter_queue_pool = startd_list_pool_create(
2437 	    "restarter_instance_queue", sizeof (restarter_instance_qentry_t),
2438 	    offsetof(restarter_instance_qentry_t,  riq_link), NULL,
2439 	    UU_LIST_POOL_DEBUG);
2440 
2441 	contract_list_pool = startd_list_pool_create(
2442 	    "contract_list", sizeof (contract_entry_t),
2443 	    offsetof(contract_entry_t,  ce_link), NULL,
2444 	    UU_LIST_POOL_DEBUG);
2445 	contract_hash_init();
2446 
2447 	log_framework(LOG_DEBUG, "Initialized restarter\n");
2448 }
2449