xref: /titanic_44/usr/src/cmd/svc/startd/restarter.c (revision 3c112a2b34403220c06c3e2fcac403358cfba168)
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  */
25 
26 /*
27  * restarter.c - service manipulation
28  *
29  * This component manages services whose restarter is svc.startd, the standard
30  * restarter.  It translates restarter protocol events from the graph engine
31  * into actions on processes, as a delegated restarter would do.
32  *
33  * The master restarter manages a number of always-running threads:
34  *   - restarter event thread: events from the graph engine
35  *   - timeout thread: thread to fire queued timeouts
36  *   - contract thread: thread to handle contract events
37  *   - wait thread: thread to handle wait-based services
38  *
39  * The other threads are created as-needed:
40  *   - per-instance method threads
41  *   - per-instance event processing threads
42  *
43  * The interaction of all threads must result in the following conditions
44  * being satisfied (on a per-instance basis):
45  *   - restarter events must be processed in order
46  *   - method execution must be serialized
47  *   - instance delete must be held until outstanding methods are complete
48  *   - contract events shouldn't be processed while a method is running
49  *   - timeouts should fire even when a method is running
50  *
51  * Service instances are represented by restarter_inst_t's and are kept in the
52  * instance_list list.
53  *
54  * Service States
55  *   The current state of a service instance is kept in
56  *   restarter_inst_t->ri_i.i_state.  If transition to a new state could take
57  *   some time, then before we effect the transition we set
58  *   restarter_inst_t->ri_i.i_next_state to the target state, and afterwards we
59  *   rotate i_next_state to i_state and set i_next_state to
60  *   RESTARTER_STATE_NONE.  So usually i_next_state is _NONE when ri_lock is not
61  *   held.  The exception is when we launch methods, which are done with
62  *   a separate thread.  To keep any other threads from grabbing ri_lock before
63  *   method_thread() does, we set ri_method_thread to the thread id of the
64  *   method thread, and when it is nonzero any thread with a different thread id
65  *   waits on ri_method_cv.
66  *
67  * Method execution is serialized by blocking on ri_method_cv in
68  * inst_lookup_by_id() and waiting for a 0 value of ri_method_thread.  This
69  * also prevents the instance structure from being deleted until all
70  * outstanding operations such as method_thread() have finished.
71  *
72  * Lock ordering:
73  *
74  * dgraph_lock [can be held when taking:]
75  *   utmpx_lock
76  *   dictionary->dict_lock
77  *   st->st_load_lock
78  *   wait_info_lock
79  *   ru->restarter_update_lock
80  *     restarter_queue->rpeq_lock
81  *   instance_list.ril_lock
82  *     inst->ri_lock
83  *   st->st_configd_live_lock
84  *
85  * instance_list.ril_lock
86  *   graph_queue->gpeq_lock
87  *   gu->gu_lock
88  *   st->st_configd_live_lock
89  *   dictionary->dict_lock
90  *   inst->ri_lock
91  *     graph_queue->gpeq_lock
92  *     gu->gu_lock
93  *     tu->tu_lock
94  *     tq->tq_lock
95  *     inst->ri_queue_lock
96  *       wait_info_lock
97  *       bp->cb_lock
98  *     utmpx_lock
99  *
100  * single_user_thread_lock
101  *   wait_info_lock
102  *   utmpx_lock
103  *
104  * gu_freeze_lock
105  *
106  * logbuf_mutex nests inside pretty much everything.
107  */
108 
109 #include <sys/contract/process.h>
110 #include <sys/ctfs.h>
111 #include <sys/stat.h>
112 #include <sys/time.h>
113 #include <sys/types.h>
114 #include <sys/uio.h>
115 #include <sys/wait.h>
116 #include <assert.h>
117 #include <errno.h>
118 #include <fcntl.h>
119 #include <libcontract.h>
120 #include <libcontract_priv.h>
121 #include <libintl.h>
122 #include <librestart.h>
123 #include <librestart_priv.h>
124 #include <libuutil.h>
125 #include <limits.h>
126 #include <poll.h>
127 #include <port.h>
128 #include <pthread.h>
129 #include <stdarg.h>
130 #include <stdio.h>
131 #include <strings.h>
132 #include <unistd.h>
133 
134 #include "startd.h"
135 #include "protocol.h"
136 
137 static uu_list_pool_t *restarter_instance_pool;
138 static restarter_instance_list_t instance_list;
139 
140 static uu_list_pool_t *restarter_queue_pool;
141 
142 /*
143  * Function used to reset the restart times for an instance, when
144  * an administrative task comes along and essentially makes the times
145  * in this array ineffective.
146  */
147 static void
148 reset_start_times(restarter_inst_t *inst)
149 {
150 	inst->ri_start_index = 0;
151 	bzero(inst->ri_start_time, sizeof (inst->ri_start_time));
152 }
153 
154 /*ARGSUSED*/
155 static int
156 restarter_instance_compare(const void *lc_arg, const void *rc_arg,
157     void *private)
158 {
159 	int lc_id = ((const restarter_inst_t *)lc_arg)->ri_id;
160 	int rc_id = *(int *)rc_arg;
161 
162 	if (lc_id > rc_id)
163 		return (1);
164 	if (lc_id < rc_id)
165 		return (-1);
166 	return (0);
167 }
168 
169 static restarter_inst_t *
170 inst_lookup_by_name(const char *name)
171 {
172 	int id;
173 
174 	id = dict_lookup_byname(name);
175 	if (id == -1)
176 		return (NULL);
177 
178 	return (inst_lookup_by_id(id));
179 }
180 
181 restarter_inst_t *
182 inst_lookup_by_id(int id)
183 {
184 	restarter_inst_t *inst;
185 
186 	MUTEX_LOCK(&instance_list.ril_lock);
187 	inst = uu_list_find(instance_list.ril_instance_list, &id, NULL, NULL);
188 	if (inst != NULL)
189 		MUTEX_LOCK(&inst->ri_lock);
190 	MUTEX_UNLOCK(&instance_list.ril_lock);
191 
192 	if (inst != NULL) {
193 		while (inst->ri_method_thread != 0 &&
194 		    !pthread_equal(inst->ri_method_thread, pthread_self())) {
195 			++inst->ri_method_waiters;
196 			(void) pthread_cond_wait(&inst->ri_method_cv,
197 			    &inst->ri_lock);
198 			assert(inst->ri_method_waiters > 0);
199 			--inst->ri_method_waiters;
200 		}
201 	}
202 
203 	return (inst);
204 }
205 
206 static restarter_inst_t *
207 inst_lookup_queue(const char *name)
208 {
209 	int id;
210 	restarter_inst_t *inst;
211 
212 	id = dict_lookup_byname(name);
213 	if (id == -1)
214 		return (NULL);
215 
216 	MUTEX_LOCK(&instance_list.ril_lock);
217 	inst = uu_list_find(instance_list.ril_instance_list, &id, NULL, NULL);
218 	if (inst != NULL)
219 		MUTEX_LOCK(&inst->ri_queue_lock);
220 	MUTEX_UNLOCK(&instance_list.ril_lock);
221 
222 	return (inst);
223 }
224 
225 const char *
226 service_style(int flags)
227 {
228 	switch (flags & RINST_STYLE_MASK) {
229 	case RINST_CONTRACT:	return ("contract");
230 	case RINST_TRANSIENT:	return ("transient");
231 	case RINST_WAIT:	return ("wait");
232 
233 	default:
234 #ifndef NDEBUG
235 		uu_warn("%s:%d: Bad flags 0x%x.\n", __FILE__, __LINE__, flags);
236 #endif
237 		abort();
238 		/* NOTREACHED */
239 	}
240 }
241 
242 /*
243  * Fails with ECONNABORTED or ECANCELED.
244  */
245 static int
246 check_contract(restarter_inst_t *inst, boolean_t primary,
247     scf_instance_t *scf_inst)
248 {
249 	ctid_t *ctidp;
250 	int fd, r;
251 
252 	ctidp = primary ? &inst->ri_i.i_primary_ctid :
253 	    &inst->ri_i.i_transient_ctid;
254 
255 	assert(*ctidp >= 1);
256 
257 	fd = contract_open(*ctidp, NULL, "status", O_RDONLY);
258 	if (fd >= 0) {
259 		r = close(fd);
260 		assert(r == 0);
261 		return (0);
262 	}
263 
264 	r = restarter_remove_contract(scf_inst, *ctidp, primary ?
265 	    RESTARTER_CONTRACT_PRIMARY : RESTARTER_CONTRACT_TRANSIENT);
266 	switch (r) {
267 	case 0:
268 	case ECONNABORTED:
269 	case ECANCELED:
270 		*ctidp = 0;
271 		return (r);
272 
273 	case ENOMEM:
274 		uu_die("Out of memory\n");
275 		/* NOTREACHED */
276 
277 	case EPERM:
278 		uu_die("Insufficient privilege.\n");
279 		/* NOTREACHED */
280 
281 	case EACCES:
282 		uu_die("Repository backend access denied.\n");
283 		/* NOTREACHED */
284 
285 	case EROFS:
286 		log_error(LOG_INFO, "Could not remove unusable contract id %ld "
287 		    "for %s from repository.\n", *ctidp, inst->ri_i.i_fmri);
288 		return (0);
289 
290 	case EINVAL:
291 	case EBADF:
292 	default:
293 		assert(0);
294 		abort();
295 		/* NOTREACHED */
296 	}
297 }
298 
299 static int stop_instance(scf_handle_t *, restarter_inst_t *, stop_cause_t);
300 
301 /*
302  * int restarter_insert_inst(scf_handle_t *, char *)
303  *   If the inst is already in the restarter list, return its id.  If the inst
304  *   is not in the restarter list, initialize a restarter_inst_t, initialize its
305  *   states, insert it into the list, and return 0.
306  *
307  *   Fails with
308  *     ENOENT - name is not in the repository
309  */
310 static int
311 restarter_insert_inst(scf_handle_t *h, const char *name)
312 {
313 	int id, r;
314 	restarter_inst_t *inst;
315 	uu_list_index_t idx;
316 	scf_service_t *scf_svc;
317 	scf_instance_t *scf_inst;
318 	scf_snapshot_t *snap = NULL;
319 	scf_propertygroup_t *pg;
320 	char *svc_name, *inst_name;
321 	char logfilebuf[PATH_MAX];
322 	char *c;
323 	boolean_t do_commit_states;
324 	restarter_instance_state_t state, next_state;
325 	protocol_states_t *ps;
326 	pid_t start_pid;
327 
328 	MUTEX_LOCK(&instance_list.ril_lock);
329 
330 	/*
331 	 * We don't use inst_lookup_by_name() here because we want the lookup
332 	 * & insert to be atomic.
333 	 */
334 	id = dict_lookup_byname(name);
335 	if (id != -1) {
336 		inst = uu_list_find(instance_list.ril_instance_list, &id, NULL,
337 		    &idx);
338 		if (inst != NULL) {
339 			MUTEX_UNLOCK(&instance_list.ril_lock);
340 			return (0);
341 		}
342 	}
343 
344 	/* Allocate an instance */
345 	inst = startd_zalloc(sizeof (restarter_inst_t));
346 	inst->ri_utmpx_prefix = startd_alloc(max_scf_value_size);
347 	inst->ri_utmpx_prefix[0] = '\0';
348 
349 	inst->ri_i.i_fmri = startd_alloc(strlen(name) + 1);
350 	(void) strcpy((char *)inst->ri_i.i_fmri, name);
351 
352 	inst->ri_queue = startd_list_create(restarter_queue_pool, inst, 0);
353 
354 	/*
355 	 * id shouldn't be -1 since we use the same dictionary as graph.c, but
356 	 * just in case.
357 	 */
358 	inst->ri_id = (id != -1 ? id : dict_insert(name));
359 
360 	special_online_hooks_get(name, &inst->ri_pre_online_hook,
361 	    &inst->ri_post_online_hook, &inst->ri_post_offline_hook);
362 
363 	scf_svc = safe_scf_service_create(h);
364 	scf_inst = safe_scf_instance_create(h);
365 	pg = safe_scf_pg_create(h);
366 	svc_name = startd_alloc(max_scf_name_size);
367 	inst_name = startd_alloc(max_scf_name_size);
368 
369 rep_retry:
370 	if (snap != NULL)
371 		scf_snapshot_destroy(snap);
372 	if (inst->ri_logstem != NULL)
373 		startd_free(inst->ri_logstem, PATH_MAX);
374 	if (inst->ri_common_name != NULL)
375 		startd_free(inst->ri_common_name, max_scf_value_size);
376 	if (inst->ri_C_common_name != NULL)
377 		startd_free(inst->ri_C_common_name, max_scf_value_size);
378 	snap = NULL;
379 	inst->ri_logstem = NULL;
380 	inst->ri_common_name = NULL;
381 	inst->ri_C_common_name = NULL;
382 
383 	if (scf_handle_decode_fmri(h, name, NULL, scf_svc, scf_inst, NULL,
384 	    NULL, SCF_DECODE_FMRI_EXACT) != 0) {
385 		switch (scf_error()) {
386 		case SCF_ERROR_CONNECTION_BROKEN:
387 			libscf_handle_rebind(h);
388 			goto rep_retry;
389 
390 		case SCF_ERROR_NOT_FOUND:
391 			goto deleted;
392 		}
393 
394 		uu_die("Can't decode FMRI %s: %s\n", name,
395 		    scf_strerror(scf_error()));
396 	}
397 
398 	/*
399 	 * If there's no running snapshot, then we execute using the editing
400 	 * snapshot.  Pending snapshots will be taken later.
401 	 */
402 	snap = libscf_get_running_snapshot(scf_inst);
403 
404 	if ((scf_service_get_name(scf_svc, svc_name, max_scf_name_size) < 0) ||
405 	    (scf_instance_get_name(scf_inst, inst_name, max_scf_name_size) <
406 	    0)) {
407 		switch (scf_error()) {
408 		case SCF_ERROR_NOT_SET:
409 			break;
410 
411 		case SCF_ERROR_CONNECTION_BROKEN:
412 			libscf_handle_rebind(h);
413 			goto rep_retry;
414 
415 		default:
416 			assert(0);
417 			abort();
418 		}
419 
420 		goto deleted;
421 	}
422 
423 	(void) snprintf(logfilebuf, PATH_MAX, "%s:%s", svc_name, inst_name);
424 	for (c = logfilebuf; *c != '\0'; c++)
425 		if (*c == '/')
426 			*c = '-';
427 
428 	inst->ri_logstem = startd_alloc(PATH_MAX);
429 	(void) snprintf(inst->ri_logstem, PATH_MAX, "%s%s", logfilebuf,
430 	    LOG_SUFFIX);
431 
432 	/*
433 	 * If the restarter group is missing, use uninit/none.  Otherwise,
434 	 * we're probably being restarted & don't want to mess up the states
435 	 * that are there.
436 	 */
437 	state = RESTARTER_STATE_UNINIT;
438 	next_state = RESTARTER_STATE_NONE;
439 
440 	r = scf_instance_get_pg(scf_inst, SCF_PG_RESTARTER, pg);
441 	if (r != 0) {
442 		switch (scf_error()) {
443 		case SCF_ERROR_CONNECTION_BROKEN:
444 			libscf_handle_rebind(h);
445 			goto rep_retry;
446 
447 		case SCF_ERROR_NOT_SET:
448 			goto deleted;
449 
450 		case SCF_ERROR_NOT_FOUND:
451 			/*
452 			 * This shouldn't happen since the graph engine should
453 			 * have initialized the state to uninitialized/none if
454 			 * there was no restarter pg.  In case somebody
455 			 * deleted it, though....
456 			 */
457 			do_commit_states = B_TRUE;
458 			break;
459 
460 		default:
461 			assert(0);
462 			abort();
463 		}
464 	} else {
465 		r = libscf_read_states(pg, &state, &next_state);
466 		if (r != 0) {
467 			do_commit_states = B_TRUE;
468 		} else {
469 			if (next_state != RESTARTER_STATE_NONE) {
470 				/*
471 				 * Force next_state to _NONE since we
472 				 * don't look for method processes.
473 				 */
474 				next_state = RESTARTER_STATE_NONE;
475 				do_commit_states = B_TRUE;
476 			} else {
477 				/*
478 				 * Inform the restarter of our state without
479 				 * changing the STIME in the repository.
480 				 */
481 				ps = startd_alloc(sizeof (*ps));
482 				inst->ri_i.i_state = ps->ps_state = state;
483 				inst->ri_i.i_next_state = ps->ps_state_next =
484 				    next_state;
485 
486 				graph_protocol_send_event(inst->ri_i.i_fmri,
487 				    GRAPH_UPDATE_STATE_CHANGE, ps);
488 
489 				do_commit_states = B_FALSE;
490 			}
491 		}
492 	}
493 
494 	switch (libscf_get_startd_properties(scf_inst, snap, &inst->ri_flags,
495 	    &inst->ri_utmpx_prefix)) {
496 	case 0:
497 		break;
498 
499 	case ECONNABORTED:
500 		libscf_handle_rebind(h);
501 		goto rep_retry;
502 
503 	case ECANCELED:
504 		goto deleted;
505 
506 	case ENOENT:
507 		/*
508 		 * This is odd, because the graph engine should have required
509 		 * the general property group.  So we'll just use default
510 		 * flags in anticipation of the graph engine sending us
511 		 * REMOVE_INSTANCE when it finds out that the general property
512 		 * group has been deleted.
513 		 */
514 		inst->ri_flags = RINST_CONTRACT;
515 		break;
516 
517 	default:
518 		assert(0);
519 		abort();
520 	}
521 
522 	switch (libscf_get_template_values(scf_inst, snap,
523 	    &inst->ri_common_name, &inst->ri_C_common_name)) {
524 	case 0:
525 		break;
526 
527 	case ECONNABORTED:
528 		libscf_handle_rebind(h);
529 		goto rep_retry;
530 
531 	case ECANCELED:
532 		goto deleted;
533 
534 	case ECHILD:
535 	case ENOENT:
536 		break;
537 
538 	default:
539 		assert(0);
540 		abort();
541 	}
542 
543 	switch (libscf_read_method_ids(h, scf_inst, inst->ri_i.i_fmri,
544 	    &inst->ri_i.i_primary_ctid, &inst->ri_i.i_transient_ctid,
545 	    &start_pid)) {
546 	case 0:
547 		break;
548 
549 	case ECONNABORTED:
550 		libscf_handle_rebind(h);
551 		goto rep_retry;
552 
553 	case ECANCELED:
554 		goto deleted;
555 
556 	default:
557 		assert(0);
558 		abort();
559 	}
560 
561 	if (inst->ri_i.i_primary_ctid >= 1) {
562 		contract_hash_store(inst->ri_i.i_primary_ctid, inst->ri_id);
563 
564 		switch (check_contract(inst, B_TRUE, scf_inst)) {
565 		case 0:
566 			break;
567 
568 		case ECONNABORTED:
569 			libscf_handle_rebind(h);
570 			goto rep_retry;
571 
572 		case ECANCELED:
573 			goto deleted;
574 
575 		default:
576 			assert(0);
577 			abort();
578 		}
579 	}
580 
581 	if (inst->ri_i.i_transient_ctid >= 1) {
582 		switch (check_contract(inst, B_FALSE, scf_inst)) {
583 		case 0:
584 			break;
585 
586 		case ECONNABORTED:
587 			libscf_handle_rebind(h);
588 			goto rep_retry;
589 
590 		case ECANCELED:
591 			goto deleted;
592 
593 		default:
594 			assert(0);
595 			abort();
596 		}
597 	}
598 
599 	/* No more failures we live through, so add it to the list. */
600 	(void) pthread_mutex_init(&inst->ri_lock, &mutex_attrs);
601 	(void) pthread_mutex_init(&inst->ri_queue_lock, &mutex_attrs);
602 	MUTEX_LOCK(&inst->ri_lock);
603 	MUTEX_LOCK(&inst->ri_queue_lock);
604 
605 	(void) pthread_cond_init(&inst->ri_method_cv, NULL);
606 
607 	uu_list_node_init(inst, &inst->ri_link, restarter_instance_pool);
608 	uu_list_insert(instance_list.ril_instance_list, inst, idx);
609 	MUTEX_UNLOCK(&instance_list.ril_lock);
610 
611 	if (start_pid != -1 &&
612 	    (inst->ri_flags & RINST_STYLE_MASK) == RINST_WAIT) {
613 		int ret;
614 		ret = wait_register(start_pid, inst->ri_i.i_fmri, 0, 1);
615 		if (ret == -1) {
616 			/*
617 			 * Implication:  if we can't reregister the
618 			 * instance, we will start another one.  Two
619 			 * instances may or may not result in a resource
620 			 * conflict.
621 			 */
622 			log_error(LOG_WARNING,
623 			    "%s: couldn't reregister %ld for wait\n",
624 			    inst->ri_i.i_fmri, start_pid);
625 		} else if (ret == 1) {
626 			/*
627 			 * Leading PID has exited.
628 			 */
629 			(void) stop_instance(h, inst, RSTOP_EXIT);
630 		}
631 	}
632 
633 
634 	scf_pg_destroy(pg);
635 
636 	if (do_commit_states)
637 		(void) restarter_instance_update_states(h, inst, state,
638 		    next_state, RERR_NONE, NULL);
639 
640 	log_framework(LOG_DEBUG, "%s is a %s-style service\n", name,
641 	    service_style(inst->ri_flags));
642 
643 	MUTEX_UNLOCK(&inst->ri_queue_lock);
644 	MUTEX_UNLOCK(&inst->ri_lock);
645 
646 	startd_free(svc_name, max_scf_name_size);
647 	startd_free(inst_name, max_scf_name_size);
648 	scf_snapshot_destroy(snap);
649 	scf_instance_destroy(scf_inst);
650 	scf_service_destroy(scf_svc);
651 
652 	log_framework(LOG_DEBUG, "%s: inserted instance into restarter list\n",
653 	    name);
654 
655 	return (0);
656 
657 deleted:
658 	MUTEX_UNLOCK(&instance_list.ril_lock);
659 	startd_free(inst_name, max_scf_name_size);
660 	startd_free(svc_name, max_scf_name_size);
661 	if (snap != NULL)
662 		scf_snapshot_destroy(snap);
663 	scf_pg_destroy(pg);
664 	scf_instance_destroy(scf_inst);
665 	scf_service_destroy(scf_svc);
666 	startd_free((void *)inst->ri_i.i_fmri, strlen(inst->ri_i.i_fmri) + 1);
667 	uu_list_destroy(inst->ri_queue);
668 	if (inst->ri_logstem != NULL)
669 		startd_free(inst->ri_logstem, PATH_MAX);
670 	if (inst->ri_common_name != NULL)
671 		startd_free(inst->ri_common_name, max_scf_value_size);
672 	if (inst->ri_C_common_name != NULL)
673 		startd_free(inst->ri_C_common_name, max_scf_value_size);
674 	startd_free(inst->ri_utmpx_prefix, max_scf_value_size);
675 	startd_free(inst, sizeof (restarter_inst_t));
676 	return (ENOENT);
677 }
678 
679 static void
680 restarter_delete_inst(restarter_inst_t *ri)
681 {
682 	int id;
683 	restarter_inst_t *rip;
684 	void *cookie = NULL;
685 	restarter_instance_qentry_t *e;
686 
687 	assert(MUTEX_HELD(&ri->ri_lock));
688 
689 	/*
690 	 * Must drop the instance lock so we can pick up the instance_list
691 	 * lock & remove the instance.
692 	 */
693 	id = ri->ri_id;
694 	MUTEX_UNLOCK(&ri->ri_lock);
695 
696 	MUTEX_LOCK(&instance_list.ril_lock);
697 
698 	rip = uu_list_find(instance_list.ril_instance_list, &id, NULL, NULL);
699 	if (rip == NULL) {
700 		MUTEX_UNLOCK(&instance_list.ril_lock);
701 		return;
702 	}
703 
704 	assert(ri == rip);
705 
706 	uu_list_remove(instance_list.ril_instance_list, ri);
707 
708 	log_framework(LOG_DEBUG, "%s: deleted instance from restarter list\n",
709 	    ri->ri_i.i_fmri);
710 
711 	MUTEX_UNLOCK(&instance_list.ril_lock);
712 
713 	/*
714 	 * We can lock the instance without holding the instance_list lock
715 	 * since we removed the instance from the list.
716 	 */
717 	MUTEX_LOCK(&ri->ri_lock);
718 	MUTEX_LOCK(&ri->ri_queue_lock);
719 
720 	if (ri->ri_i.i_primary_ctid >= 1)
721 		contract_hash_remove(ri->ri_i.i_primary_ctid);
722 
723 	while (ri->ri_method_thread != 0 || ri->ri_method_waiters > 0)
724 		(void) pthread_cond_wait(&ri->ri_method_cv, &ri->ri_lock);
725 
726 	while ((e = uu_list_teardown(ri->ri_queue, &cookie)) != NULL)
727 		startd_free(e, sizeof (*e));
728 	uu_list_destroy(ri->ri_queue);
729 
730 	startd_free((void *)ri->ri_i.i_fmri, strlen(ri->ri_i.i_fmri) + 1);
731 	startd_free(ri->ri_logstem, PATH_MAX);
732 	if (ri->ri_common_name != NULL)
733 		startd_free(ri->ri_common_name, max_scf_value_size);
734 	if (ri->ri_C_common_name != NULL)
735 		startd_free(ri->ri_C_common_name, max_scf_value_size);
736 	startd_free(ri->ri_utmpx_prefix, max_scf_value_size);
737 	(void) pthread_mutex_destroy(&ri->ri_lock);
738 	(void) pthread_mutex_destroy(&ri->ri_queue_lock);
739 	startd_free(ri, sizeof (restarter_inst_t));
740 }
741 
742 /*
743  * instance_is_wait_style()
744  *
745  *   Returns 1 if the given instance is a "wait-style" service instance.
746  */
747 int
748 instance_is_wait_style(restarter_inst_t *inst)
749 {
750 	assert(MUTEX_HELD(&inst->ri_lock));
751 	return ((inst->ri_flags & RINST_STYLE_MASK) == RINST_WAIT);
752 }
753 
754 /*
755  * instance_is_transient_style()
756  *
757  *   Returns 1 if the given instance is a transient service instance.
758  */
759 int
760 instance_is_transient_style(restarter_inst_t *inst)
761 {
762 	assert(MUTEX_HELD(&inst->ri_lock));
763 	return ((inst->ri_flags & RINST_STYLE_MASK) == RINST_TRANSIENT);
764 }
765 
766 /*
767  * instance_in_transition()
768  * Returns 1 if instance is in transition, 0 if not
769  */
770 int
771 instance_in_transition(restarter_inst_t *inst)
772 {
773 	assert(MUTEX_HELD(&inst->ri_lock));
774 	if (inst->ri_i.i_next_state == RESTARTER_STATE_NONE)
775 		return (0);
776 	return (1);
777 }
778 
779 /*
780  * returns 1 if instance is already started, 0 if not
781  */
782 static int
783 instance_started(restarter_inst_t *inst)
784 {
785 	int ret;
786 
787 	assert(MUTEX_HELD(&inst->ri_lock));
788 
789 	if (inst->ri_i.i_state == RESTARTER_STATE_ONLINE ||
790 	    inst->ri_i.i_state == RESTARTER_STATE_DEGRADED)
791 		ret = 1;
792 	else
793 		ret = 0;
794 
795 	return (ret);
796 }
797 
798 /*
799  * Returns
800  *   0 - success
801  *   ECONNRESET - success, but h was rebound
802  */
803 int
804 restarter_instance_update_states(scf_handle_t *h, restarter_inst_t *ri,
805     restarter_instance_state_t new_state,
806     restarter_instance_state_t new_state_next, restarter_error_t err, char *aux)
807 {
808 	protocol_states_t *states;
809 	int e;
810 	uint_t retry_count = 0, msecs = ALLOC_DELAY;
811 	boolean_t rebound = B_FALSE;
812 	int prev_state_online;
813 	int state_online;
814 
815 	assert(MUTEX_HELD(&ri->ri_lock));
816 
817 	prev_state_online = instance_started(ri);
818 
819 retry:
820 	e = _restarter_commit_states(h, &ri->ri_i, new_state, new_state_next,
821 	    aux);
822 	switch (e) {
823 	case 0:
824 		break;
825 
826 	case ENOMEM:
827 		++retry_count;
828 		if (retry_count < ALLOC_RETRY) {
829 			(void) poll(NULL, 0, msecs);
830 			msecs *= ALLOC_DELAY_MULT;
831 			goto retry;
832 		}
833 
834 		/* Like startd_alloc(). */
835 		uu_die("Insufficient memory.\n");
836 		/* NOTREACHED */
837 
838 	case ECONNABORTED:
839 		libscf_handle_rebind(h);
840 		rebound = B_TRUE;
841 		goto retry;
842 
843 	case EPERM:
844 	case EACCES:
845 	case EROFS:
846 		log_error(LOG_NOTICE, "Could not commit state change for %s "
847 		    "to repository: %s.\n", ri->ri_i.i_fmri, strerror(e));
848 		/* FALLTHROUGH */
849 
850 	case ENOENT:
851 		ri->ri_i.i_state = new_state;
852 		ri->ri_i.i_next_state = new_state_next;
853 		break;
854 
855 	case EINVAL:
856 	default:
857 		bad_error("_restarter_commit_states", e);
858 	}
859 
860 	states = startd_alloc(sizeof (protocol_states_t));
861 	states->ps_state = new_state;
862 	states->ps_state_next = new_state_next;
863 	states->ps_err = err;
864 	graph_protocol_send_event(ri->ri_i.i_fmri, GRAPH_UPDATE_STATE_CHANGE,
865 	    (void *)states);
866 
867 	state_online = instance_started(ri);
868 
869 	if (prev_state_online && !state_online)
870 		ri->ri_post_offline_hook();
871 	else if (!prev_state_online && state_online)
872 		ri->ri_post_online_hook();
873 
874 	return (rebound ? ECONNRESET : 0);
875 }
876 
877 void
878 restarter_mark_pending_snapshot(const char *fmri, uint_t flag)
879 {
880 	restarter_inst_t *inst;
881 
882 	assert(flag == RINST_RETAKE_RUNNING || flag == RINST_RETAKE_START);
883 
884 	inst = inst_lookup_by_name(fmri);
885 	if (inst == NULL)
886 		return;
887 
888 	inst->ri_flags |= flag;
889 
890 	MUTEX_UNLOCK(&inst->ri_lock);
891 }
892 
893 static void
894 restarter_take_pending_snapshots(scf_handle_t *h)
895 {
896 	restarter_inst_t *inst;
897 	int r;
898 
899 	MUTEX_LOCK(&instance_list.ril_lock);
900 
901 	for (inst = uu_list_first(instance_list.ril_instance_list);
902 	    inst != NULL;
903 	    inst = uu_list_next(instance_list.ril_instance_list, inst)) {
904 		const char *fmri;
905 		scf_instance_t *sinst = NULL;
906 
907 		MUTEX_LOCK(&inst->ri_lock);
908 
909 		/*
910 		 * This is where we'd check inst->ri_method_thread and if it
911 		 * were nonzero we'd wait in anticipation of another thread
912 		 * executing a method for inst.  Doing so with the instance_list
913 		 * locked, though, leads to deadlock.  Since taking a snapshot
914 		 * during that window won't hurt anything, we'll just continue.
915 		 */
916 
917 		fmri = inst->ri_i.i_fmri;
918 
919 		if (inst->ri_flags & RINST_RETAKE_RUNNING) {
920 			scf_snapshot_t *rsnap;
921 
922 			(void) libscf_fmri_get_instance(h, fmri, &sinst);
923 
924 			rsnap = libscf_get_or_make_running_snapshot(sinst,
925 			    fmri, B_FALSE);
926 
927 			scf_instance_destroy(sinst);
928 
929 			if (rsnap != NULL)
930 				inst->ri_flags &= ~RINST_RETAKE_RUNNING;
931 
932 			scf_snapshot_destroy(rsnap);
933 		}
934 
935 		if (inst->ri_flags & RINST_RETAKE_START) {
936 			switch (r = libscf_snapshots_poststart(h, fmri,
937 			    B_FALSE)) {
938 			case 0:
939 			case ENOENT:
940 				inst->ri_flags &= ~RINST_RETAKE_START;
941 				break;
942 
943 			case ECONNABORTED:
944 				break;
945 
946 			case EACCES:
947 			default:
948 				bad_error("libscf_snapshots_poststart", r);
949 			}
950 		}
951 
952 		MUTEX_UNLOCK(&inst->ri_lock);
953 	}
954 
955 	MUTEX_UNLOCK(&instance_list.ril_lock);
956 }
957 
958 /* ARGSUSED */
959 void *
960 restarter_post_fsminimal_thread(void *unused)
961 {
962 	scf_handle_t *h;
963 	int r;
964 
965 	h = libscf_handle_create_bound_loop();
966 
967 	for (;;) {
968 		r = libscf_create_self(h);
969 		if (r == 0)
970 			break;
971 
972 		assert(r == ECONNABORTED);
973 		libscf_handle_rebind(h);
974 	}
975 
976 	restarter_take_pending_snapshots(h);
977 
978 	(void) scf_handle_unbind(h);
979 	scf_handle_destroy(h);
980 
981 	return (NULL);
982 }
983 
984 /*
985  * int stop_instance()
986  *
987  *   Stop the instance identified by the instance given as the second argument,
988  *   for the cause stated.
989  *
990  *   Returns
991  *     0 - success
992  *     -1 - inst is in transition
993  */
994 static int
995 stop_instance(scf_handle_t *local_handle, restarter_inst_t *inst,
996     stop_cause_t cause)
997 {
998 	fork_info_t *info;
999 	const char *cp;
1000 	int err;
1001 	restarter_error_t re;
1002 
1003 	assert(MUTEX_HELD(&inst->ri_lock));
1004 	assert(inst->ri_method_thread == 0);
1005 
1006 	switch (cause) {
1007 	case RSTOP_EXIT:
1008 		re = RERR_RESTART;
1009 		cp = "all processes in service exited";
1010 		break;
1011 	case RSTOP_CORE:
1012 		re = RERR_FAULT;
1013 		cp = "process dumped core";
1014 		break;
1015 	case RSTOP_SIGNAL:
1016 		re = RERR_FAULT;
1017 		cp = "process received fatal signal from outside the service";
1018 		break;
1019 	case RSTOP_HWERR:
1020 		re = RERR_FAULT;
1021 		cp = "process killed due to uncorrectable hardware error";
1022 		break;
1023 	case RSTOP_DEPENDENCY:
1024 		re = RERR_RESTART;
1025 		cp = "dependency activity requires stop";
1026 		break;
1027 	case RSTOP_DISABLE:
1028 		re = RERR_RESTART;
1029 		cp = "service disabled";
1030 		break;
1031 	case RSTOP_RESTART:
1032 		re = RERR_RESTART;
1033 		cp = "service restarting";
1034 		break;
1035 	default:
1036 #ifndef NDEBUG
1037 		(void) fprintf(stderr, "Unknown cause %d at %s:%d.\n",
1038 		    cause, __FILE__, __LINE__);
1039 #endif
1040 		abort();
1041 	}
1042 
1043 	/* Services in the disabled and maintenance state are ignored */
1044 	if (inst->ri_i.i_state == RESTARTER_STATE_MAINT ||
1045 	    inst->ri_i.i_state == RESTARTER_STATE_DISABLED) {
1046 		log_framework(LOG_DEBUG,
1047 		    "%s: stop_instance -> is maint/disabled\n",
1048 		    inst->ri_i.i_fmri);
1049 		return (0);
1050 	}
1051 
1052 	/* Already stopped instances are left alone */
1053 	if (instance_started(inst) == 0) {
1054 		log_framework(LOG_DEBUG, "Restarter: %s is already stopped.\n",
1055 		    inst->ri_i.i_fmri);
1056 		return (0);
1057 	}
1058 
1059 	if (instance_in_transition(inst)) {
1060 		/* requeue event by returning -1 */
1061 		log_framework(LOG_DEBUG,
1062 		    "Restarter: Not stopping %s, in transition.\n",
1063 		    inst->ri_i.i_fmri);
1064 		return (-1);
1065 	}
1066 
1067 	log_instance(inst, B_TRUE, "Stopping because %s.", cp);
1068 
1069 	log_framework(re == RERR_FAULT ? LOG_INFO : LOG_DEBUG,
1070 	    "%s: Instance stopping because %s.\n", inst->ri_i.i_fmri, cp);
1071 
1072 	if (instance_is_wait_style(inst) && cause == RSTOP_EXIT) {
1073 		/*
1074 		 * No need to stop instance, as child has exited; remove
1075 		 * contract and move the instance to the offline state.
1076 		 */
1077 		switch (err = restarter_instance_update_states(local_handle,
1078 		    inst, inst->ri_i.i_state, RESTARTER_STATE_OFFLINE, re,
1079 		    NULL)) {
1080 		case 0:
1081 		case ECONNRESET:
1082 			break;
1083 
1084 		default:
1085 			bad_error("restarter_instance_update_states", err);
1086 		}
1087 
1088 		(void) update_fault_count(inst, FAULT_COUNT_RESET);
1089 		reset_start_times(inst);
1090 
1091 		if (inst->ri_i.i_primary_ctid != 0) {
1092 			inst->ri_m_inst =
1093 			    safe_scf_instance_create(local_handle);
1094 			inst->ri_mi_deleted = B_FALSE;
1095 
1096 			libscf_reget_instance(inst);
1097 			method_remove_contract(inst, B_TRUE, B_TRUE);
1098 
1099 			scf_instance_destroy(inst->ri_m_inst);
1100 			inst->ri_m_inst = NULL;
1101 		}
1102 
1103 		switch (err = restarter_instance_update_states(local_handle,
1104 		    inst, inst->ri_i.i_next_state, RESTARTER_STATE_NONE, re,
1105 		    NULL)) {
1106 		case 0:
1107 		case ECONNRESET:
1108 			break;
1109 
1110 		default:
1111 			bad_error("restarter_instance_update_states", err);
1112 		}
1113 
1114 		return (0);
1115 	} else if (instance_is_wait_style(inst) && re == RERR_RESTART) {
1116 		/*
1117 		 * Stopping a wait service through means other than the pid
1118 		 * exiting should keep wait_thread() from restarting the
1119 		 * service, by removing it from the wait list.
1120 		 * We cannot remove it right now otherwise the process will
1121 		 * end up <defunct> so mark it to be ignored.
1122 		 */
1123 		wait_ignore_by_fmri(inst->ri_i.i_fmri);
1124 	}
1125 
1126 	switch (err = restarter_instance_update_states(local_handle, inst,
1127 	    inst->ri_i.i_state, inst->ri_i.i_enabled ? RESTARTER_STATE_OFFLINE :
1128 	    RESTARTER_STATE_DISABLED, RERR_NONE, NULL)) {
1129 	case 0:
1130 	case ECONNRESET:
1131 		break;
1132 
1133 	default:
1134 		bad_error("restarter_instance_update_states", err);
1135 	}
1136 
1137 	info = startd_zalloc(sizeof (fork_info_t));
1138 
1139 	info->sf_id = inst->ri_id;
1140 	info->sf_method_type = METHOD_STOP;
1141 	info->sf_event_type = re;
1142 	inst->ri_method_thread = startd_thread_create(method_thread, info);
1143 
1144 	return (0);
1145 }
1146 
1147 /*
1148  * Returns
1149  *   ENOENT - fmri is not in instance_list
1150  *   0 - success
1151  *   ECONNRESET - success, though handle was rebound
1152  *   -1 - instance is in transition
1153  */
1154 int
1155 stop_instance_fmri(scf_handle_t *h, const char *fmri, uint_t flags)
1156 {
1157 	restarter_inst_t *rip;
1158 	int r;
1159 
1160 	rip = inst_lookup_by_name(fmri);
1161 	if (rip == NULL)
1162 		return (ENOENT);
1163 
1164 	r = stop_instance(h, rip, flags);
1165 
1166 	MUTEX_UNLOCK(&rip->ri_lock);
1167 
1168 	return (r);
1169 }
1170 
1171 static void
1172 unmaintain_instance(scf_handle_t *h, restarter_inst_t *rip,
1173     unmaint_cause_t cause)
1174 {
1175 	ctid_t ctid;
1176 	scf_instance_t *inst;
1177 	int r;
1178 	uint_t tries = 0, msecs = ALLOC_DELAY;
1179 	const char *cp;
1180 
1181 	assert(MUTEX_HELD(&rip->ri_lock));
1182 
1183 	if (rip->ri_i.i_state != RESTARTER_STATE_MAINT) {
1184 		log_error(LOG_DEBUG, "Restarter: "
1185 		    "Ignoring maintenance off command because %s is not in the "
1186 		    "maintenance state.\n", rip->ri_i.i_fmri);
1187 		return;
1188 	}
1189 
1190 	switch (cause) {
1191 	case RUNMAINT_CLEAR:
1192 		cp = "clear requested";
1193 		break;
1194 	case RUNMAINT_DISABLE:
1195 		cp = "disable requested";
1196 		break;
1197 	default:
1198 #ifndef NDEBUG
1199 		(void) fprintf(stderr, "Uncaught case for %d at %s:%d.\n",
1200 		    cause, __FILE__, __LINE__);
1201 #endif
1202 		abort();
1203 	}
1204 
1205 	log_instance(rip, B_TRUE, "Leaving maintenance because %s.",
1206 	    cp);
1207 	log_framework(LOG_DEBUG, "%s: Instance leaving maintenance because "
1208 	    "%s.\n", rip->ri_i.i_fmri, cp);
1209 
1210 	(void) restarter_instance_update_states(h, rip, RESTARTER_STATE_UNINIT,
1211 	    RESTARTER_STATE_NONE, RERR_RESTART, "none");
1212 
1213 	/*
1214 	 * If we did ADMIN_MAINT_ON_IMMEDIATE, then there might still be
1215 	 * a primary contract.
1216 	 */
1217 	if (rip->ri_i.i_primary_ctid == 0)
1218 		return;
1219 
1220 	ctid = rip->ri_i.i_primary_ctid;
1221 	contract_abandon(ctid);
1222 	rip->ri_i.i_primary_ctid = 0;
1223 
1224 rep_retry:
1225 	switch (r = libscf_fmri_get_instance(h, rip->ri_i.i_fmri, &inst)) {
1226 	case 0:
1227 		break;
1228 
1229 	case ECONNABORTED:
1230 		libscf_handle_rebind(h);
1231 		goto rep_retry;
1232 
1233 	case ENOENT:
1234 		/* Must have been deleted. */
1235 		return;
1236 
1237 	case EINVAL:
1238 	case ENOTSUP:
1239 	default:
1240 		bad_error("libscf_handle_rebind", r);
1241 	}
1242 
1243 again:
1244 	r = restarter_remove_contract(inst, ctid, RESTARTER_CONTRACT_PRIMARY);
1245 	switch (r) {
1246 	case 0:
1247 		break;
1248 
1249 	case ENOMEM:
1250 		++tries;
1251 		if (tries < ALLOC_RETRY) {
1252 			(void) poll(NULL, 0, msecs);
1253 			msecs *= ALLOC_DELAY_MULT;
1254 			goto again;
1255 		}
1256 
1257 		uu_die("Insufficient memory.\n");
1258 		/* NOTREACHED */
1259 
1260 	case ECONNABORTED:
1261 		scf_instance_destroy(inst);
1262 		libscf_handle_rebind(h);
1263 		goto rep_retry;
1264 
1265 	case ECANCELED:
1266 		break;
1267 
1268 	case EPERM:
1269 	case EACCES:
1270 	case EROFS:
1271 		log_error(LOG_INFO,
1272 		    "Could not remove contract id %lu for %s (%s).\n", ctid,
1273 		    rip->ri_i.i_fmri, strerror(r));
1274 		break;
1275 
1276 	case EINVAL:
1277 	case EBADF:
1278 	default:
1279 		bad_error("restarter_remove_contract", r);
1280 	}
1281 
1282 	scf_instance_destroy(inst);
1283 }
1284 
1285 /*
1286  * enable_inst()
1287  *   Set inst->ri_i.i_enabled.  Expects 'e' to be _ENABLE, _DISABLE, or
1288  *   _ADMIN_DISABLE.  If the event is _ENABLE and inst is uninitialized or
1289  *   disabled, move it to offline.  If the event is _DISABLE or
1290  *   _ADMIN_DISABLE, make sure inst will move to disabled.
1291  *
1292  *   Returns
1293  *     0 - success
1294  *     ECONNRESET - h was rebound
1295  */
1296 static int
1297 enable_inst(scf_handle_t *h, restarter_inst_t *inst, restarter_event_type_t e)
1298 {
1299 	restarter_instance_state_t state;
1300 	int r;
1301 
1302 	assert(MUTEX_HELD(&inst->ri_lock));
1303 	assert(e == RESTARTER_EVENT_TYPE_ADMIN_DISABLE ||
1304 	    e == RESTARTER_EVENT_TYPE_DISABLE ||
1305 	    e == RESTARTER_EVENT_TYPE_ENABLE);
1306 	assert(instance_in_transition(inst) == 0);
1307 
1308 	state = inst->ri_i.i_state;
1309 
1310 	if (e == RESTARTER_EVENT_TYPE_ENABLE) {
1311 		inst->ri_i.i_enabled = 1;
1312 
1313 		if (state == RESTARTER_STATE_UNINIT ||
1314 		    state == RESTARTER_STATE_DISABLED) {
1315 			/*
1316 			 * B_FALSE: Don't log an error if the log_instance()
1317 			 * fails because it will fail on the miniroot before
1318 			 * install-discovery runs.
1319 			 */
1320 			log_instance(inst, B_FALSE, "Enabled.");
1321 			log_framework(LOG_DEBUG, "%s: Instance enabled.\n",
1322 			    inst->ri_i.i_fmri);
1323 			(void) restarter_instance_update_states(h, inst,
1324 			    RESTARTER_STATE_OFFLINE, RESTARTER_STATE_NONE,
1325 			    RERR_NONE, NULL);
1326 		} else {
1327 			log_framework(LOG_DEBUG, "Restarter: "
1328 			    "Not changing state of %s for enable command.\n",
1329 			    inst->ri_i.i_fmri);
1330 		}
1331 	} else {
1332 		inst->ri_i.i_enabled = 0;
1333 
1334 		switch (state) {
1335 		case RESTARTER_STATE_ONLINE:
1336 		case RESTARTER_STATE_DEGRADED:
1337 			r = stop_instance(h, inst, RSTOP_DISABLE);
1338 			return (r == ECONNRESET ? 0 : r);
1339 
1340 		case RESTARTER_STATE_OFFLINE:
1341 		case RESTARTER_STATE_UNINIT:
1342 			if (inst->ri_i.i_primary_ctid != 0) {
1343 				inst->ri_m_inst = safe_scf_instance_create(h);
1344 				inst->ri_mi_deleted = B_FALSE;
1345 
1346 				libscf_reget_instance(inst);
1347 				method_remove_contract(inst, B_TRUE, B_TRUE);
1348 
1349 				scf_instance_destroy(inst->ri_m_inst);
1350 			}
1351 			/* B_FALSE: See log_instance(..., "Enabled."); above */
1352 			log_instance(inst, B_FALSE, "Disabled.");
1353 			log_framework(LOG_DEBUG, "%s: Instance disabled.\n",
1354 			    inst->ri_i.i_fmri);
1355 			(void) restarter_instance_update_states(h, inst,
1356 			    RESTARTER_STATE_DISABLED, RESTARTER_STATE_NONE,
1357 			    RERR_RESTART, NULL);
1358 			return (0);
1359 
1360 		case RESTARTER_STATE_DISABLED:
1361 			break;
1362 
1363 		case RESTARTER_STATE_MAINT:
1364 			/*
1365 			 * We only want to pull the instance out of maintenance
1366 			 * if the disable is on adminstrative request.  The
1367 			 * graph engine sends _DISABLE events whenever a
1368 			 * service isn't in the disabled state, and we don't
1369 			 * want to pull the service out of maintenance if,
1370 			 * for example, it is there due to a dependency cycle.
1371 			 */
1372 			if (e == RESTARTER_EVENT_TYPE_ADMIN_DISABLE)
1373 				unmaintain_instance(h, inst, RUNMAINT_DISABLE);
1374 			break;
1375 
1376 		default:
1377 #ifndef NDEBUG
1378 			(void) fprintf(stderr, "Restarter instance %s has "
1379 			    "unknown state %d.\n", inst->ri_i.i_fmri, state);
1380 #endif
1381 			abort();
1382 		}
1383 	}
1384 
1385 	return (0);
1386 }
1387 
1388 static void
1389 start_instance(scf_handle_t *local_handle, restarter_inst_t *inst)
1390 {
1391 	fork_info_t *info;
1392 
1393 	assert(MUTEX_HELD(&inst->ri_lock));
1394 	assert(instance_in_transition(inst) == 0);
1395 	assert(inst->ri_method_thread == 0);
1396 
1397 	log_framework(LOG_DEBUG, "%s: trying to start instance\n",
1398 	    inst->ri_i.i_fmri);
1399 
1400 	/* Services in the disabled and maintenance state are ignored */
1401 	if (inst->ri_i.i_state == RESTARTER_STATE_MAINT ||
1402 	    inst->ri_i.i_state == RESTARTER_STATE_DISABLED ||
1403 	    inst->ri_i.i_enabled == 0) {
1404 		log_framework(LOG_DEBUG,
1405 		    "%s: start_instance -> is maint/disabled\n",
1406 		    inst->ri_i.i_fmri);
1407 		return;
1408 	}
1409 
1410 	/* Already started instances are left alone */
1411 	if (instance_started(inst) == 1) {
1412 		log_framework(LOG_DEBUG,
1413 		    "%s: start_instance -> is already started\n",
1414 		    inst->ri_i.i_fmri);
1415 		return;
1416 	}
1417 
1418 	log_framework(LOG_DEBUG, "%s: starting instance.\n", inst->ri_i.i_fmri);
1419 
1420 	(void) restarter_instance_update_states(local_handle, inst,
1421 	    inst->ri_i.i_state, RESTARTER_STATE_ONLINE, RERR_NONE, "none");
1422 
1423 	info = startd_zalloc(sizeof (fork_info_t));
1424 
1425 	info->sf_id = inst->ri_id;
1426 	info->sf_method_type = METHOD_START;
1427 	info->sf_event_type = RERR_NONE;
1428 	inst->ri_method_thread = startd_thread_create(method_thread, info);
1429 }
1430 
1431 static int
1432 event_from_tty(scf_handle_t *h, restarter_inst_t *rip)
1433 {
1434 	scf_instance_t *inst;
1435 	int ret = 0;
1436 
1437 	if (libscf_fmri_get_instance(h, rip->ri_i.i_fmri, &inst))
1438 		return (-1);
1439 
1440 	ret = restarter_inst_ractions_from_tty(inst);
1441 
1442 	scf_instance_destroy(inst);
1443 	return (ret);
1444 }
1445 
1446 static void
1447 maintain_instance(scf_handle_t *h, restarter_inst_t *rip, int immediate,
1448     const char *aux)
1449 {
1450 	fork_info_t *info;
1451 	scf_instance_t *scf_inst = NULL;
1452 
1453 	assert(MUTEX_HELD(&rip->ri_lock));
1454 	assert(aux != NULL);
1455 	assert(rip->ri_method_thread == 0);
1456 
1457 	log_instance(rip, B_TRUE, "Stopping for maintenance due to %s.", aux);
1458 	log_framework(LOG_DEBUG, "%s: stopping for maintenance due to %s.\n",
1459 	    rip->ri_i.i_fmri, aux);
1460 
1461 	/* Services in the maintenance state are ignored */
1462 	if (rip->ri_i.i_state == RESTARTER_STATE_MAINT) {
1463 		log_framework(LOG_DEBUG,
1464 		    "%s: maintain_instance -> is already in maintenance\n",
1465 		    rip->ri_i.i_fmri);
1466 		return;
1467 	}
1468 
1469 	/*
1470 	 * If aux state is "service_request" and
1471 	 * restarter_actions/auxiliary_fmri property is set with a valid fmri,
1472 	 * copy the fmri to restarter/auxiliary_fmri so svcs -x can use.
1473 	 */
1474 	if (strcmp(aux, "service_request") == 0 && libscf_fmri_get_instance(h,
1475 	    rip->ri_i.i_fmri, &scf_inst) == 0) {
1476 		if (restarter_inst_validate_ractions_aux_fmri(scf_inst) == 0) {
1477 			if (restarter_inst_set_aux_fmri(scf_inst))
1478 				log_framework(LOG_DEBUG, "%s: "
1479 				    "restarter_inst_set_aux_fmri failed: ",
1480 				    rip->ri_i.i_fmri);
1481 		} else {
1482 			log_framework(LOG_DEBUG, "%s: "
1483 			    "restarter_inst_validate_ractions_aux_fmri "
1484 			    "failed: ", rip->ri_i.i_fmri);
1485 
1486 			if (restarter_inst_reset_aux_fmri(scf_inst))
1487 				log_framework(LOG_DEBUG, "%s: "
1488 				    "restarter_inst_reset_aux_fmri failed: ",
1489 				    rip->ri_i.i_fmri);
1490 		}
1491 		scf_instance_destroy(scf_inst);
1492 	}
1493 
1494 	if (immediate || !instance_started(rip)) {
1495 		if (rip->ri_i.i_primary_ctid != 0) {
1496 			rip->ri_m_inst = safe_scf_instance_create(h);
1497 			rip->ri_mi_deleted = B_FALSE;
1498 
1499 			libscf_reget_instance(rip);
1500 			method_remove_contract(rip, B_TRUE, B_TRUE);
1501 
1502 			scf_instance_destroy(rip->ri_m_inst);
1503 		}
1504 
1505 		(void) restarter_instance_update_states(h, rip,
1506 		    RESTARTER_STATE_MAINT, RESTARTER_STATE_NONE, RERR_RESTART,
1507 		    (char *)aux);
1508 		return;
1509 	}
1510 
1511 	(void) restarter_instance_update_states(h, rip, rip->ri_i.i_state,
1512 	    RESTARTER_STATE_MAINT, RERR_NONE, (char *)aux);
1513 
1514 	log_transition(rip, MAINT_REQUESTED);
1515 
1516 	info = startd_zalloc(sizeof (*info));
1517 	info->sf_id = rip->ri_id;
1518 	info->sf_method_type = METHOD_STOP;
1519 	info->sf_event_type = RERR_RESTART;
1520 	rip->ri_method_thread = startd_thread_create(method_thread, info);
1521 }
1522 
1523 static void
1524 refresh_instance(scf_handle_t *h, restarter_inst_t *rip)
1525 {
1526 	scf_instance_t *inst;
1527 	scf_snapshot_t *snap;
1528 	fork_info_t *info;
1529 	int r;
1530 
1531 	assert(MUTEX_HELD(&rip->ri_lock));
1532 
1533 	log_instance(rip, B_TRUE, "Rereading configuration.");
1534 	log_framework(LOG_DEBUG, "%s: rereading configuration.\n",
1535 	    rip->ri_i.i_fmri);
1536 
1537 rep_retry:
1538 	r = libscf_fmri_get_instance(h, rip->ri_i.i_fmri, &inst);
1539 	switch (r) {
1540 	case 0:
1541 		break;
1542 
1543 	case ECONNABORTED:
1544 		libscf_handle_rebind(h);
1545 		goto rep_retry;
1546 
1547 	case ENOENT:
1548 		/* Must have been deleted. */
1549 		return;
1550 
1551 	case EINVAL:
1552 	case ENOTSUP:
1553 	default:
1554 		bad_error("libscf_fmri_get_instance", r);
1555 	}
1556 
1557 	snap = libscf_get_running_snapshot(inst);
1558 
1559 	r = libscf_get_startd_properties(inst, snap, &rip->ri_flags,
1560 	    &rip->ri_utmpx_prefix);
1561 	switch (r) {
1562 	case 0:
1563 		log_framework(LOG_DEBUG, "%s is a %s-style service\n",
1564 		    rip->ri_i.i_fmri, service_style(rip->ri_flags));
1565 		break;
1566 
1567 	case ECONNABORTED:
1568 		scf_instance_destroy(inst);
1569 		scf_snapshot_destroy(snap);
1570 		libscf_handle_rebind(h);
1571 		goto rep_retry;
1572 
1573 	case ECANCELED:
1574 	case ENOENT:
1575 		/* Succeed in anticipation of REMOVE_INSTANCE. */
1576 		break;
1577 
1578 	default:
1579 		bad_error("libscf_get_startd_properties", r);
1580 	}
1581 
1582 	if (instance_started(rip)) {
1583 		/* Refresh does not change the state. */
1584 		(void) restarter_instance_update_states(h, rip,
1585 		    rip->ri_i.i_state, rip->ri_i.i_state, RERR_NONE, NULL);
1586 
1587 		info = startd_zalloc(sizeof (*info));
1588 		info->sf_id = rip->ri_id;
1589 		info->sf_method_type = METHOD_REFRESH;
1590 		info->sf_event_type = RERR_REFRESH;
1591 
1592 		assert(rip->ri_method_thread == 0);
1593 		rip->ri_method_thread =
1594 		    startd_thread_create(method_thread, info);
1595 	}
1596 
1597 	scf_snapshot_destroy(snap);
1598 	scf_instance_destroy(inst);
1599 }
1600 
1601 const char *event_names[] = { "INVALID", "ADD_INSTANCE", "REMOVE_INSTANCE",
1602 	"ENABLE", "DISABLE", "ADMIN_DEGRADED", "ADMIN_REFRESH",
1603 	"ADMIN_RESTART", "ADMIN_MAINT_OFF", "ADMIN_MAINT_ON",
1604 	"ADMIN_MAINT_ON_IMMEDIATE", "STOP", "START", "DEPENDENCY_CYCLE",
1605 	"INVALID_DEPENDENCY", "ADMIN_DISABLE", "STOP_RESET"
1606 };
1607 
1608 /*
1609  * void *restarter_process_events()
1610  *
1611  *   Called in a separate thread to process the events on an instance's
1612  *   queue.  Empties the queue completely, and tries to keep the thread
1613  *   around for a little while after the queue is empty to save on
1614  *   startup costs.
1615  */
1616 static void *
1617 restarter_process_events(void *arg)
1618 {
1619 	scf_handle_t *h;
1620 	restarter_instance_qentry_t *event;
1621 	restarter_inst_t *rip;
1622 	char *fmri = (char *)arg;
1623 	struct timespec to;
1624 
1625 	assert(fmri != NULL);
1626 
1627 	h = libscf_handle_create_bound_loop();
1628 
1629 	/* grab the queue lock */
1630 	rip = inst_lookup_queue(fmri);
1631 	if (rip == NULL)
1632 		goto out;
1633 
1634 again:
1635 
1636 	while ((event = uu_list_first(rip->ri_queue)) != NULL) {
1637 		restarter_inst_t *inst;
1638 
1639 		/* drop the queue lock */
1640 		MUTEX_UNLOCK(&rip->ri_queue_lock);
1641 
1642 		/*
1643 		 * Grab the inst lock -- this waits until any outstanding
1644 		 * method finishes running.
1645 		 */
1646 		inst = inst_lookup_by_name(fmri);
1647 		if (inst == NULL) {
1648 			/* Getting deleted in the middle isn't an error. */
1649 			goto cont;
1650 		}
1651 
1652 		assert(instance_in_transition(inst) == 0);
1653 
1654 		/* process the event */
1655 		switch (event->riq_type) {
1656 		case RESTARTER_EVENT_TYPE_ENABLE:
1657 		case RESTARTER_EVENT_TYPE_DISABLE:
1658 			(void) enable_inst(h, inst, event->riq_type);
1659 			break;
1660 
1661 		case RESTARTER_EVENT_TYPE_ADMIN_DISABLE:
1662 			if (enable_inst(h, inst, event->riq_type) == 0)
1663 				reset_start_times(inst);
1664 			break;
1665 
1666 		case RESTARTER_EVENT_TYPE_REMOVE_INSTANCE:
1667 			restarter_delete_inst(inst);
1668 			inst = NULL;
1669 			goto cont;
1670 
1671 		case RESTARTER_EVENT_TYPE_STOP_RESET:
1672 			reset_start_times(inst);
1673 			/* FALLTHROUGH */
1674 		case RESTARTER_EVENT_TYPE_STOP:
1675 			(void) stop_instance(h, inst, RSTOP_DEPENDENCY);
1676 			break;
1677 
1678 		case RESTARTER_EVENT_TYPE_START:
1679 			start_instance(h, inst);
1680 			break;
1681 
1682 		case RESTARTER_EVENT_TYPE_DEPENDENCY_CYCLE:
1683 			maintain_instance(h, inst, 0, "dependency_cycle");
1684 			break;
1685 
1686 		case RESTARTER_EVENT_TYPE_INVALID_DEPENDENCY:
1687 			maintain_instance(h, inst, 0, "invalid_dependency");
1688 			break;
1689 
1690 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON:
1691 			if (event_from_tty(h, inst) == 0)
1692 				maintain_instance(h, inst, 0,
1693 				    "service_request");
1694 			else
1695 				maintain_instance(h, inst, 0,
1696 				    "administrative_request");
1697 			break;
1698 
1699 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_ON_IMMEDIATE:
1700 			if (event_from_tty(h, inst) == 0)
1701 				maintain_instance(h, inst, 1,
1702 				    "service_request");
1703 			else
1704 				maintain_instance(h, inst, 1,
1705 				    "administrative_request");
1706 			break;
1707 
1708 		case RESTARTER_EVENT_TYPE_ADMIN_MAINT_OFF:
1709 			unmaintain_instance(h, inst, RUNMAINT_CLEAR);
1710 			reset_start_times(inst);
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