xref: /titanic_50/usr/src/cmd/svc/startd/method.c (revision 2fcbc377041d659446ded306a92901b4b0753b68)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * method.c - method execution functions
30  *
31  * This file contains the routines needed to run a method:  a fork(2)-exec(2)
32  * invocation monitored using either the contract filesystem or waitpid(2).
33  * (Plain fork1(2) support is provided in fork.c.)
34  *
35  * Contract Transfer
36  *   When we restart a service, we want to transfer any contracts that the old
37  *   service's contract inherited.  This means that (a) we must not abandon the
38  *   old contract when the service dies and (b) we must write the id of the old
39  *   contract into the terms of the new contract.  There should be limits to
40  *   (a), though, since we don't want to keep the contract around forever.  To
41  *   this end we'll say that services in the offline state may have a contract
42  *   to be transfered and services in the disabled or maintenance states cannot.
43  *   This means that when a service transitions from online (or degraded) to
44  *   offline, the contract should be preserved, and when the service transitions
45  *   from offline to online (i.e., the start method), we'll transfer inherited
46  *   contracts.
47  */
48 
49 #include <sys/contract/process.h>
50 #include <sys/ctfs.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53 #include <sys/types.h>
54 #include <sys/uio.h>
55 #include <sys/wait.h>
56 #include <alloca.h>
57 #include <assert.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <libcontract.h>
61 #include <libcontract_priv.h>
62 #include <libgen.h>
63 #include <librestart.h>
64 #include <libscf.h>
65 #include <limits.h>
66 #include <port.h>
67 #include <sac.h>
68 #include <signal.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <strings.h>
72 #include <unistd.h>
73 
74 #include "startd.h"
75 
76 #define	SBIN_SH		"/sbin/sh"
77 
78 /*
79  * Mapping from restart_on method-type to contract events.  Must correspond to
80  * enum method_restart_t.
81  */
82 static uint_t method_events[] = {
83 	/* METHOD_RESTART_ALL */
84 	CT_PR_EV_HWERR | CT_PR_EV_SIGNAL | CT_PR_EV_CORE | CT_PR_EV_EMPTY,
85 	/* METHOD_RESTART_EXTERNAL_FAULT */
86 	CT_PR_EV_HWERR | CT_PR_EV_SIGNAL,
87 	/* METHOD_RESTART_ANY_FAULT */
88 	CT_PR_EV_HWERR | CT_PR_EV_SIGNAL | CT_PR_EV_CORE
89 };
90 
91 /*
92  * method_record_start(restarter_inst_t *)
93  *   Record a service start for rate limiting.  Place the current time
94  *   in the circular array of instance starts.
95  */
96 static void
97 method_record_start(restarter_inst_t *inst)
98 {
99 	int index = inst->ri_start_index++ % RINST_START_TIMES;
100 
101 	inst->ri_start_time[index] = gethrtime();
102 }
103 
104 /*
105  * method_rate_critical(restarter_inst_t *)
106  *    Return true if the average start interval is less than the permitted
107  *    interval.  Implicit success if insufficient measurements for an
108  *    average exist.
109  */
110 static int
111 method_rate_critical(restarter_inst_t *inst)
112 {
113 	uint_t n = inst->ri_start_index;
114 	hrtime_t avg_ns = 0;
115 
116 	if (inst->ri_start_index < RINST_START_TIMES)
117 		return (0);
118 
119 	avg_ns =
120 	    (inst->ri_start_time[(n - 1) % RINST_START_TIMES] -
121 	    inst->ri_start_time[n % RINST_START_TIMES]) /
122 	    (RINST_START_TIMES - 1);
123 
124 	return (avg_ns < RINST_FAILURE_RATE_NS);
125 }
126 
127 /*
128  * int method_is_transient()
129  *   Determine if the method for the given instance is transient,
130  *   from a contract perspective. Return 1 if it is, and 0 if it isn't.
131  */
132 static int
133 method_is_transient(restarter_inst_t *inst, int type)
134 {
135 	if (instance_is_transient_style(inst) || type != METHOD_START)
136 		return (1);
137 	else
138 		return (0);
139 }
140 
141 /*
142  * void method_store_contract()
143  *   Store the newly created contract id into local structures and
144  *   the repository.  If the repository connection is broken it is rebound.
145  */
146 static void
147 method_store_contract(restarter_inst_t *inst, int type, ctid_t *cid)
148 {
149 	int r;
150 	boolean_t primary;
151 
152 	if (errno = contract_latest(cid))
153 		uu_die("%s: Couldn't get new contract's id", inst->ri_i.i_fmri);
154 
155 	primary = !method_is_transient(inst, type);
156 
157 	if (!primary) {
158 		if (inst->ri_i.i_transient_ctid != 0) {
159 			log_framework(LOG_INFO,
160 			    "%s: transient ctid expected to be 0 but "
161 			    "was set to %ld\n", inst->ri_i.i_fmri,
162 			    inst->ri_i.i_transient_ctid);
163 		}
164 
165 		inst->ri_i.i_transient_ctid = *cid;
166 	} else {
167 		if (inst->ri_i.i_primary_ctid != 0) {
168 			/*
169 			 * There was an old contract that we transferred.
170 			 * Remove it.
171 			 */
172 			method_remove_contract(inst, B_TRUE, B_FALSE);
173 		}
174 
175 		if (inst->ri_i.i_primary_ctid != 0) {
176 			log_framework(LOG_INFO,
177 			    "%s: primary ctid expected to be 0 but "
178 			    "was set to %ld\n", inst->ri_i.i_fmri,
179 			    inst->ri_i.i_primary_ctid);
180 		}
181 
182 		inst->ri_i.i_primary_ctid = *cid;
183 		inst->ri_i.i_primary_ctid_stopped = 0;
184 
185 		contract_hash_store(*cid, inst->ri_id);
186 	}
187 
188 again:
189 	if (inst->ri_mi_deleted)
190 		return;
191 
192 	r = restarter_store_contract(inst->ri_m_inst, *cid, primary ?
193 	    RESTARTER_CONTRACT_PRIMARY : RESTARTER_CONTRACT_TRANSIENT);
194 	switch (r) {
195 	case 0:
196 		break;
197 
198 	case ECANCELED:
199 		inst->ri_mi_deleted = B_TRUE;
200 		break;
201 
202 	case ECONNABORTED:
203 		libscf_handle_rebind(scf_instance_handle(inst->ri_m_inst));
204 		/* FALLTHROUGH */
205 
206 	case EBADF:
207 		libscf_reget_instance(inst);
208 		goto again;
209 
210 	case ENOMEM:
211 	case EPERM:
212 	case EACCES:
213 	case EROFS:
214 		uu_die("%s: Couldn't store contract id %ld",
215 		    inst->ri_i.i_fmri, *cid);
216 		/* NOTREACHED */
217 
218 	case EINVAL:
219 	default:
220 		bad_error("restarter_store_contract", r);
221 	}
222 }
223 
224 /*
225  * void method_remove_contract()
226  *   Remove any non-permanent contracts from internal structures and
227  *   the repository, then abandon them.
228  *   Returns
229  *     0 - success
230  *     ECANCELED - inst was deleted from the repository
231  *
232  *   If the repository connection was broken, it is rebound.
233  */
234 void
235 method_remove_contract(restarter_inst_t *inst, boolean_t primary,
236     boolean_t abandon)
237 {
238 	ctid_t * const ctidp = primary ? &inst->ri_i.i_primary_ctid :
239 	    &inst->ri_i.i_transient_ctid;
240 
241 	int r;
242 
243 	assert(*ctidp != 0);
244 
245 	log_framework(LOG_DEBUG, "Removing %s contract %lu for %s.\n",
246 	    primary ? "primary" : "transient", *ctidp, inst->ri_i.i_fmri);
247 
248 	if (abandon)
249 		contract_abandon(*ctidp);
250 
251 again:
252 	if (inst->ri_mi_deleted) {
253 		r = ECANCELED;
254 		goto out;
255 	}
256 
257 	r = restarter_remove_contract(inst->ri_m_inst, *ctidp, primary ?
258 	    RESTARTER_CONTRACT_PRIMARY : RESTARTER_CONTRACT_TRANSIENT);
259 	switch (r) {
260 	case 0:
261 		break;
262 
263 	case ECANCELED:
264 		inst->ri_mi_deleted = B_TRUE;
265 		break;
266 
267 	case ECONNABORTED:
268 		libscf_handle_rebind(scf_instance_handle(inst->ri_m_inst));
269 		/* FALLTHROUGH */
270 
271 	case EBADF:
272 		libscf_reget_instance(inst);
273 		goto again;
274 
275 	case ENOMEM:
276 	case EPERM:
277 	case EACCES:
278 	case EROFS:
279 		log_error(LOG_INFO, "%s: Couldn't remove contract id %ld: "
280 		    "%s.\n", inst->ri_i.i_fmri, *ctidp, strerror(r));
281 		break;
282 
283 	case EINVAL:
284 	default:
285 		bad_error("restarter_remove_contract", r);
286 	}
287 
288 out:
289 	if (primary)
290 		contract_hash_remove(*ctidp);
291 
292 	*ctidp = 0;
293 }
294 
295 /*
296  * int method_ready_contract(restarter_inst_t *, int, method_restart_t, int)
297  *
298  *   Activate a contract template for the type method of inst.  type,
299  *   restart_on, and cte_mask dictate the critical events term of the contract.
300  *   Returns
301  *     0 - success
302  *     ECANCELED - inst has been deleted from the repository
303  */
304 static int
305 method_ready_contract(restarter_inst_t *inst, int type,
306     method_restart_t restart_on, uint_t cte_mask)
307 {
308 	int tmpl, err, istrans, iswait, ret;
309 	uint_t cevents, fevents;
310 
311 	/*
312 	 * Correctly supporting wait-style services is tricky without
313 	 * rearchitecting startd to cope with multiple event sources
314 	 * simultaneously trying to stop an instance.  Until a better
315 	 * solution is implemented, we avoid this problem for
316 	 * wait-style services by making contract events fatal and
317 	 * letting the wait code alone handle stopping the service.
318 	 */
319 	iswait = instance_is_wait_style(inst);
320 	istrans = method_is_transient(inst, type);
321 
322 	tmpl = open64(CTFS_ROOT "/process/template", O_RDWR);
323 	if (tmpl == -1)
324 		uu_die("Could not create contract template");
325 
326 	/*
327 	 * We assume non-login processes are unlikely to create
328 	 * multiple process groups, and set CT_PR_PGRPONLY for all
329 	 * wait-style services' contracts.
330 	 */
331 	err = ct_pr_tmpl_set_param(tmpl, CT_PR_INHERIT | CT_PR_REGENT |
332 	    (iswait ? CT_PR_PGRPONLY : 0));
333 	assert(err == 0);
334 
335 	if (istrans) {
336 		cevents = 0;
337 		fevents = 0;
338 	} else {
339 		assert(restart_on >= 0);
340 		assert(restart_on <= METHOD_RESTART_ANY_FAULT);
341 		cevents = method_events[restart_on] & ~cte_mask;
342 		fevents = iswait ?
343 		    (method_events[restart_on] & ~cte_mask & CT_PR_ALLFATAL) :
344 		    0;
345 	}
346 
347 	err = ct_tmpl_set_critical(tmpl, cevents);
348 	assert(err == 0);
349 
350 	err = ct_tmpl_set_informative(tmpl, 0);
351 	assert(err == 0);
352 	err = ct_pr_tmpl_set_fatal(tmpl, fevents);
353 	assert(err == 0);
354 
355 	err = ct_tmpl_set_cookie(tmpl, istrans ?  METHOD_OTHER_COOKIE :
356 	    METHOD_START_COOKIE);
357 	assert(err == 0);
358 
359 	if (type == METHOD_START && inst->ri_i.i_primary_ctid != 0) {
360 		ret = ct_pr_tmpl_set_transfer(tmpl, inst->ri_i.i_primary_ctid);
361 		switch (ret) {
362 		case 0:
363 			break;
364 
365 		case ENOTEMPTY:
366 			/* No contracts for you! */
367 			method_remove_contract(inst, B_TRUE, B_TRUE);
368 			if (inst->ri_mi_deleted) {
369 				ret = ECANCELED;
370 				goto out;
371 			}
372 			break;
373 
374 		case EINVAL:
375 		case ESRCH:
376 		case EACCES:
377 		default:
378 			bad_error("ct_pr_tmpl_set_transfer", ret);
379 		}
380 	}
381 
382 	err = ct_tmpl_activate(tmpl);
383 	assert(err == 0);
384 
385 	ret = 0;
386 
387 out:
388 	err = close(tmpl);
389 	assert(err == 0);
390 
391 	return (ret);
392 }
393 
394 static const char *method_names[] = { "start", "stop", "refresh" };
395 
396 static void
397 exec_method(const restarter_inst_t *inst, int type, const char *method,
398     struct method_context *mcp, uint8_t need_session)
399 {
400 	char *cmd;
401 	const char *errf;
402 	char **nenv;
403 
404 	cmd = uu_msprintf("exec %s", method);
405 
406 	if (inst->ri_utmpx_prefix[0] != '\0' && inst->ri_utmpx_prefix != NULL)
407 		(void) utmpx_mark_init(getpid(), inst->ri_utmpx_prefix);
408 
409 	setlog(inst->ri_logstem);
410 	log_instance(inst, B_FALSE, "Executing %s method (\"%s\")",
411 	    method_names[type], method);
412 
413 	if (need_session)
414 		(void) setpgrp();
415 
416 	/* Set credentials. */
417 	errno = restarter_set_method_context(mcp, &errf);
418 	if (errno != 0) {
419 		(void) fputs("svc.startd could not set context for method: ",
420 		    stderr);
421 
422 		if (errno == -1) {
423 			if (strcmp(errf, "core_set_process_path") == 0) {
424 				(void) fputs("Could not set corefile path.\n",
425 				    stderr);
426 			} else if (strcmp(errf, "setproject") == 0) {
427 				(void) fprintf(stderr, "%s: a resource control "
428 				    "assignment failed\n", errf);
429 			} else if (strcmp(errf, "pool_set_binding") == 0) {
430 				(void) fprintf(stderr, "%s: a system error "
431 				    "occurred\n", errf);
432 			} else {
433 #ifndef NDEBUG
434 				uu_warn("%s:%d: Bad function name \"%s\" for "
435 				    "error %d from "
436 				    "restarter_set_method_context().\n",
437 				    __FILE__, __LINE__, errf, errno);
438 #endif
439 				abort();
440 			}
441 
442 			exit(1);
443 		}
444 
445 		if (errf != NULL && strcmp(errf, "pool_set_binding") == 0) {
446 			switch (errno) {
447 			case ENOENT:
448 				(void) fprintf(stderr, "%s: the pool could not "
449 				    "be found\n", errf);
450 				break;
451 
452 			case EBADF:
453 				(void) fprintf(stderr, "%s: the configuration "
454 				    "is invalid\n", errf);
455 				break;
456 
457 			case EINVAL:
458 				(void) fprintf(stderr, "%s: pool name \"%s\" "
459 				    "is invalid\n", errf, mcp->resource_pool);
460 				break;
461 
462 			default:
463 #ifndef NDEBUG
464 				uu_warn("%s:%d: Bad error %d for function %s "
465 				    "in restarter_set_method_context().\n",
466 				    __FILE__, __LINE__, errno, errf);
467 #endif
468 				abort();
469 			}
470 
471 			exit(SMF_EXIT_ERR_CONFIG);
472 		}
473 
474 		if (errf != NULL) {
475 			perror(errf);
476 
477 			switch (errno) {
478 			case EINVAL:
479 			case EPERM:
480 			case ENOENT:
481 			case ENAMETOOLONG:
482 			case ERANGE:
483 			case ESRCH:
484 				exit(SMF_EXIT_ERR_CONFIG);
485 				/* NOTREACHED */
486 
487 			default:
488 				exit(1);
489 			}
490 		}
491 
492 		switch (errno) {
493 		case ENOMEM:
494 			(void) fputs("Out of memory.\n", stderr);
495 			exit(1);
496 			/* NOTREACHED */
497 
498 		case ENOENT:
499 			(void) fputs("Missing passwd entry for user.\n",
500 			    stderr);
501 			exit(SMF_EXIT_ERR_CONFIG);
502 			/* NOTREACHED */
503 
504 		default:
505 #ifndef NDEBUG
506 			uu_warn("%s:%d: Bad miscellaneous error %d from "
507 			    "restarter_set_method_context().\n", __FILE__,
508 			    __LINE__, errno);
509 #endif
510 			abort();
511 		}
512 	}
513 
514 	nenv = set_smf_env(mcp->env, mcp->env_sz, NULL, inst, method);
515 
516 	log_preexec();
517 
518 	(void) execle(SBIN_SH, SBIN_SH, "-c", cmd, NULL, nenv);
519 
520 	exit(10);
521 }
522 
523 static void
524 write_status(restarter_inst_t *inst, const char *mname, int stat)
525 {
526 	int r;
527 
528 again:
529 	if (inst->ri_mi_deleted)
530 		return;
531 
532 	r = libscf_write_method_status(inst->ri_m_inst, mname, stat);
533 	switch (r) {
534 	case 0:
535 		break;
536 
537 	case ECONNABORTED:
538 		libscf_reget_instance(inst);
539 		goto again;
540 
541 	case ECANCELED:
542 		inst->ri_mi_deleted = 1;
543 		break;
544 
545 	case EPERM:
546 	case EACCES:
547 	case EROFS:
548 		log_framework(LOG_INFO, "Could not write exit status "
549 		    "for %s method of %s: %s.\n", mname,
550 		    inst->ri_i.i_fmri, strerror(r));
551 		break;
552 
553 	case ENAMETOOLONG:
554 	default:
555 		bad_error("libscf_write_method_status", r);
556 	}
557 }
558 
559 /*
560  * int method_run()
561  *   Execute the type method of instp.  If it requires a fork(), wait for it
562  *   to return and return its exit code in *exit_code.  Otherwise set
563  *   *exit_code to 0 if the method succeeds & -1 if it fails.  If the
564  *   repository connection is broken, it is rebound, but inst may not be
565  *   reset.
566  *   Returns
567  *     0 - success
568  *     EINVAL - A correct method or method context couldn't be retrieved.
569  *     EIO - Contract kill failed.
570  *     EFAULT - Method couldn't be executed successfully.
571  *     ELOOP - Retry threshold exceeded.
572  *     ECANCELED - inst was deleted from the repository before method was run
573  *     ERANGE - Timeout retry threshold exceeded.
574  *     EAGAIN - Failed due to external cause, retry.
575  */
576 int
577 method_run(restarter_inst_t **instp, int type, int *exit_code)
578 {
579 	char *method;
580 	int ret_status;
581 	pid_t pid;
582 	method_restart_t restart_on;
583 	uint_t cte_mask;
584 	uint8_t need_session;
585 	scf_handle_t *h;
586 	scf_snapshot_t *snap;
587 	const char *mname;
588 	const char *errstr;
589 	struct method_context *mcp;
590 	int result = 0, timeout_fired = 0;
591 	int sig, r;
592 	boolean_t transient;
593 	uint64_t timeout;
594 	uint8_t timeout_retry;
595 	ctid_t ctid;
596 	int ctfd = -1;
597 	ct_evthdl_t ctev;
598 	uint_t evtype;
599 	restarter_inst_t *inst = *instp;
600 	int id = inst->ri_id;
601 	int forkerr;
602 
603 	assert(PTHREAD_MUTEX_HELD(&inst->ri_lock));
604 	assert(instance_in_transition(inst));
605 
606 	if (inst->ri_mi_deleted)
607 		return (ECANCELED);
608 
609 	*exit_code = 0;
610 
611 	assert(0 <= type && type <= 2);
612 	mname = method_names[type];
613 
614 	if (type == METHOD_START)
615 		inst->ri_pre_online_hook();
616 
617 	h = scf_instance_handle(inst->ri_m_inst);
618 
619 	snap = scf_snapshot_create(h);
620 	if (snap == NULL ||
621 	    scf_instance_get_snapshot(inst->ri_m_inst, "running", snap) != 0) {
622 		log_framework(LOG_DEBUG,
623 		    "Could not get running snapshot for %s.  "
624 		    "Using editing version to run method %s.\n",
625 		    inst->ri_i.i_fmri, mname);
626 		scf_snapshot_destroy(snap);
627 		snap = NULL;
628 	}
629 
630 	/*
631 	 * After this point, we may be logging to the instance log.
632 	 * Make sure we've noted where that log is as a property of
633 	 * the instance.
634 	 */
635 	r = libscf_note_method_log(inst->ri_m_inst, st->st_log_prefix,
636 	    inst->ri_logstem);
637 	if (r != 0) {
638 		log_framework(LOG_WARNING,
639 		    "%s: couldn't note log location: %s\n",
640 		    inst->ri_i.i_fmri, strerror(r));
641 	}
642 
643 	if ((method = libscf_get_method(h, type, inst, snap, &restart_on,
644 	    &cte_mask, &need_session, &timeout, &timeout_retry)) == NULL) {
645 		if (errno == LIBSCF_PGROUP_ABSENT)  {
646 			log_framework(LOG_DEBUG,
647 			    "%s: instance has no method property group '%s'.\n",
648 			    inst->ri_i.i_fmri, mname);
649 			if (type == METHOD_REFRESH)
650 				log_instance(inst, B_TRUE, "No '%s' method "
651 				    "defined.  Treating as :true.", mname);
652 			else
653 				log_instance(inst, B_TRUE, "Method property "
654 				    "group '%s' is not present.", mname);
655 			scf_snapshot_destroy(snap);
656 			return (0);
657 		} else if (errno == LIBSCF_PROPERTY_ABSENT)  {
658 			log_framework(LOG_DEBUG,
659 			    "%s: instance has no '%s/exec' method property.\n",
660 			    inst->ri_i.i_fmri, mname);
661 			log_instance(inst, B_TRUE, "Method property '%s/exec "
662 			    "is not present.", mname);
663 			scf_snapshot_destroy(snap);
664 			return (0);
665 		} else {
666 			log_error(LOG_WARNING,
667 			    "%s: instance libscf_get_method failed\n",
668 			    inst->ri_i.i_fmri);
669 			scf_snapshot_destroy(snap);
670 			return (EINVAL);
671 		}
672 	}
673 
674 	/* open service contract if stopping a non-transient service */
675 	if (type == METHOD_STOP && (!instance_is_transient_style(inst))) {
676 		if (inst->ri_i.i_primary_ctid == 0) {
677 			/* service is not running, nothing to stop */
678 			log_framework(LOG_DEBUG, "%s: instance has no primary "
679 			    "contract, no service to stop.\n",
680 			    inst->ri_i.i_fmri);
681 			scf_snapshot_destroy(snap);
682 			return (0);
683 		}
684 		if ((ctfd = contract_open(inst->ri_i.i_primary_ctid, "process",
685 		    "events", O_RDONLY)) < 0) {
686 			result = EFAULT;
687 			log_instance(inst, B_TRUE, "Could not open service "
688 			    "contract %ld.  Stop method not run.\n",
689 			    inst->ri_i.i_primary_ctid);
690 			goto out;
691 		}
692 	}
693 
694 	if (restarter_is_null_method(method)) {
695 		log_framework(LOG_DEBUG, "%s: null method succeeds\n",
696 		    inst->ri_i.i_fmri);
697 
698 		log_instance(inst, B_TRUE, "Executing %s method (null)", mname);
699 
700 		if (type == METHOD_START)
701 			write_status(inst, mname, 0);
702 		goto out;
703 	}
704 
705 	sig = restarter_is_kill_method(method);
706 	if (sig >= 0) {
707 
708 		if (inst->ri_i.i_primary_ctid == 0) {
709 			log_error(LOG_ERR, "%s: :kill with no contract\n",
710 			    inst->ri_i.i_fmri);
711 			result = EINVAL;
712 			goto out;
713 		}
714 
715 		log_framework(LOG_DEBUG,
716 		    "%s: :killing contract with signal %d\n",
717 		    inst->ri_i.i_fmri, sig);
718 
719 		log_instance(inst, B_TRUE, "Executing %s method (:kill)",
720 		    mname);
721 
722 		if (contract_kill(inst->ri_i.i_primary_ctid, sig,
723 		    inst->ri_i.i_fmri) != 0) {
724 			result = EIO;
725 			goto out;
726 		} else
727 			goto assured_kill;
728 	}
729 
730 	log_framework(LOG_DEBUG, "%s: forking to run method %s\n",
731 	    inst->ri_i.i_fmri, method);
732 
733 	errstr = restarter_get_method_context(RESTARTER_METHOD_CONTEXT_VERSION,
734 	    inst->ri_m_inst, snap, mname, method, &mcp);
735 
736 	if (errstr != NULL) {
737 		log_error(LOG_WARNING, "%s: %s\n", inst->ri_i.i_fmri, errstr);
738 		result = EINVAL;
739 		goto out;
740 	}
741 
742 	r = method_ready_contract(inst, type, restart_on, cte_mask);
743 	if (r != 0) {
744 		assert(r == ECANCELED);
745 		assert(inst->ri_mi_deleted);
746 		restarter_free_method_context(mcp);
747 		result = ECANCELED;
748 		goto out;
749 	}
750 
751 	/*
752 	 * Validate safety of method contexts, to save children work.
753 	 */
754 	if (!restarter_rm_libs_loadable())
755 		log_framework(LOG_DEBUG, "%s: method contexts limited "
756 		    "to root-accessible libraries\n", inst->ri_i.i_fmri);
757 
758 	/*
759 	 * If the service is restarting too quickly, send it to
760 	 * maintenance.
761 	 */
762 	if (type == METHOD_START) {
763 		method_record_start(inst);
764 		if (method_rate_critical(inst)) {
765 			log_instance(inst, B_TRUE, "Restarting too quickly, "
766 			    "changing state to maintenance");
767 			result = ELOOP;
768 			restarter_free_method_context(mcp);
769 			goto out;
770 		}
771 	}
772 
773 	pid = startd_fork1(&forkerr);
774 	if (pid == 0)
775 		exec_method(inst, type, method, mcp, need_session);
776 
777 	restarter_free_method_context(mcp);
778 	if (pid == -1) {
779 		if (forkerr == EAGAIN)
780 			result = EAGAIN;
781 		else
782 			result = EFAULT;
783 
784 		log_error(LOG_WARNING,
785 		    "%s: Couldn't fork to execute method %s: %s\n",
786 		    inst->ri_i.i_fmri, method, strerror(forkerr));
787 
788 		goto out;
789 	}
790 
791 
792 	/*
793 	 * Get the contract id, decide whether it is primary or transient, and
794 	 * stash it in inst & the repository.
795 	 */
796 	method_store_contract(inst, type, &ctid);
797 
798 	/*
799 	 * Similarly for the start method PID.
800 	 */
801 	if (type == METHOD_START && !inst->ri_mi_deleted)
802 		(void) libscf_write_start_pid(inst->ri_m_inst, pid);
803 
804 	if (instance_is_wait_style(inst) && type == METHOD_START) {
805 		/* Wait style instances don't get timeouts on start methods. */
806 		if (wait_register(pid, inst->ri_i.i_fmri, 1, 0)) {
807 			log_error(LOG_WARNING,
808 			    "%s: couldn't register %ld for wait\n",
809 			    inst->ri_i.i_fmri, pid);
810 			result = EFAULT;
811 			goto contract_out;
812 		}
813 		write_status(inst, mname, 0);
814 
815 	} else {
816 		int r, err;
817 		time_t start_time;
818 		time_t end_time;
819 
820 		/*
821 		 * Because on upgrade/live-upgrade we may have no chance
822 		 * to override faulty timeout values on the way to
823 		 * manifest import, all services on the path to manifest
824 		 * import are treated the same as INFINITE timeout services.
825 		 */
826 
827 		start_time = time(NULL);
828 		if (timeout != METHOD_TIMEOUT_INFINITE && !is_timeout_ovr(inst))
829 			timeout_insert(inst, ctid, timeout);
830 		else
831 			timeout = METHOD_TIMEOUT_INFINITE;
832 
833 		/* Unlock the instance while waiting for the method. */
834 		MUTEX_UNLOCK(&inst->ri_lock);
835 
836 		do
837 			r = waitpid(pid, &ret_status, NULL);
838 		while (r == -1 && errno == EINTR);
839 		if (r == -1)
840 			err = errno;
841 
842 		/* Re-grab the lock. */
843 		inst = inst_lookup_by_id(id);
844 
845 		/*
846 		 * inst can't be removed, as the removal thread waits
847 		 * for completion of this one.
848 		 */
849 		assert(inst != NULL);
850 		*instp = inst;
851 
852 		if (inst->ri_timeout != NULL && inst->ri_timeout->te_fired)
853 			timeout_fired = 1;
854 
855 		timeout_remove(inst, ctid);
856 
857 		log_framework(LOG_DEBUG,
858 		    "%s method for %s exited with status %d.\n", mname,
859 		    inst->ri_i.i_fmri, WEXITSTATUS(ret_status));
860 
861 		if (r == -1) {
862 			log_error(LOG_WARNING,
863 			    "Couldn't waitpid() for %s method of %s (%s).\n",
864 			    mname, inst->ri_i.i_fmri, strerror(err));
865 			result = EFAULT;
866 			goto contract_out;
867 		}
868 
869 		if (type == METHOD_START)
870 			write_status(inst, mname, ret_status);
871 
872 		/* return ERANGE if this service doesn't retry on timeout */
873 		if (timeout_fired == 1 && timeout_retry == 0) {
874 			result = ERANGE;
875 			goto contract_out;
876 		}
877 
878 		if (!WIFEXITED(ret_status)) {
879 			/*
880 			 * If method didn't exit itself (it was killed by an
881 			 * external entity, etc.), consider the entire
882 			 * method_run as failed.
883 			 */
884 			if (WIFSIGNALED(ret_status)) {
885 				char buf[SIG2STR_MAX];
886 				(void) sig2str(WTERMSIG(ret_status), buf);
887 
888 				log_error(LOG_WARNING, "%s: Method \"%s\" "
889 				    "failed due to signal %s.\n",
890 				    inst->ri_i.i_fmri, method, buf);
891 				log_instance(inst, B_TRUE, "Method \"%s\" "
892 				    "failed due to signal %s", mname, buf);
893 			} else {
894 				log_error(LOG_WARNING, "%s: Method \"%s\" "
895 				    "failed with exit status %d.\n",
896 				    inst->ri_i.i_fmri, method,
897 				    WEXITSTATUS(ret_status));
898 				log_instance(inst, B_TRUE, "Method \"%s\" "
899 				    "failed with exit status %d", mname,
900 				    WEXITSTATUS(ret_status));
901 			}
902 			result = EAGAIN;
903 			goto contract_out;
904 		}
905 
906 		*exit_code = WEXITSTATUS(ret_status);
907 		if (*exit_code != 0) {
908 			log_error(LOG_WARNING,
909 			    "%s: Method \"%s\" failed with exit status %d.\n",
910 			    inst->ri_i.i_fmri, method, WEXITSTATUS(ret_status));
911 		}
912 
913 		log_instance(inst, B_TRUE, "Method \"%s\" exited with status "
914 		    "%d", mname, *exit_code);
915 
916 		if (*exit_code != 0)
917 			goto contract_out;
918 
919 		end_time = time(NULL);
920 
921 		/* Give service contract remaining seconds to empty */
922 		if (timeout != METHOD_TIMEOUT_INFINITE)
923 			timeout -= (end_time - start_time);
924 	}
925 
926 assured_kill:
927 	/*
928 	 * For stop methods, assure that the service contract has emptied
929 	 * before returning.
930 	 */
931 	if (type == METHOD_STOP && (!instance_is_transient_style(inst)) &&
932 	    !(contract_is_empty(inst->ri_i.i_primary_ctid))) {
933 
934 		if (timeout != METHOD_TIMEOUT_INFINITE)
935 			timeout_insert(inst, inst->ri_i.i_primary_ctid,
936 			    timeout);
937 
938 		for (;;) {
939 			do {
940 				r = ct_event_read_critical(ctfd, &ctev);
941 			} while (r == EINTR);
942 			if (r != 0)
943 				break;
944 
945 			evtype = ct_event_get_type(ctev);
946 			ct_event_free(ctev);
947 			if (evtype == CT_PR_EV_EMPTY)
948 				break;
949 		}
950 		if (r) {
951 			result = EFAULT;
952 			log_instance(inst, B_TRUE, "Error reading service "
953 			    "contract %ld.\n", inst->ri_i.i_primary_ctid);
954 		}
955 
956 		if (timeout != METHOD_TIMEOUT_INFINITE)
957 			if (inst->ri_timeout->te_fired)
958 				result = EFAULT;
959 
960 		timeout_remove(inst, inst->ri_i.i_primary_ctid);
961 	}
962 
963 contract_out:
964 	/* Abandon contracts for transient methods & methods that fail. */
965 	transient = method_is_transient(inst, type);
966 	if ((transient || *exit_code != 0 || result != 0) &&
967 	    (restarter_is_kill_method(method) < 0))
968 		method_remove_contract(inst, !transient, B_TRUE);
969 
970 out:
971 	if (ctfd >= 0)
972 		(void) close(ctfd);
973 	scf_snapshot_destroy(snap);
974 	free(method);
975 	return (result);
976 }
977 
978 /*
979  * The method thread executes a service method to effect a state transition.
980  * The next_state of info->sf_id should be non-_NONE on entrance, and it will
981  * be _NONE on exit (state will either be what next_state was (on success), or
982  * it will be _MAINT (on error)).
983  *
984  * There are six classes of methods to consider: start & other (stop, refresh)
985  * for each of "normal" services, wait services, and transient services.  For
986  * each, the method must be fetched from the repository & executed.  fork()ed
987  * methods must be waited on, except for the start method of wait services
988  * (which must be registered with the wait subsystem via wait_register()).  If
989  * the method succeeded (returned 0), then for start methods its contract
990  * should be recorded as the primary contract for the service.  For other
991  * methods, it should be abandoned.  If the method fails, then depending on
992  * the failure, either the method should be reexecuted or the service should
993  * be put into maintenance.  Either way the contract should be abandoned.
994  */
995 void *
996 method_thread(void *arg)
997 {
998 	fork_info_t *info = arg;
999 	restarter_inst_t *inst;
1000 	scf_handle_t	*local_handle;
1001 	scf_instance_t	*s_inst = NULL;
1002 	int r, exit_code;
1003 	boolean_t retryable;
1004 	const char *aux;
1005 
1006 	assert(0 <= info->sf_method_type && info->sf_method_type <= 2);
1007 
1008 	/* Get (and lock) the restarter_inst_t. */
1009 	inst = inst_lookup_by_id(info->sf_id);
1010 
1011 	assert(inst->ri_method_thread != 0);
1012 	assert(instance_in_transition(inst) == 1);
1013 
1014 	/*
1015 	 * We cannot leave this function with inst in transition, because
1016 	 * protocol.c withholds messages for inst otherwise.
1017 	 */
1018 
1019 	log_framework(LOG_DEBUG, "method_thread() running %s method for %s.\n",
1020 	    method_names[info->sf_method_type], inst->ri_i.i_fmri);
1021 
1022 	local_handle = libscf_handle_create_bound_loop();
1023 
1024 rebind_retry:
1025 	/* get scf_instance_t */
1026 	switch (r = libscf_fmri_get_instance(local_handle, inst->ri_i.i_fmri,
1027 	    &s_inst)) {
1028 	case 0:
1029 		break;
1030 
1031 	case ECONNABORTED:
1032 		libscf_handle_rebind(local_handle);
1033 		goto rebind_retry;
1034 
1035 	case ENOENT:
1036 		/*
1037 		 * It's not there, but we need to call this so protocol.c
1038 		 * doesn't think it's in transition anymore.
1039 		 */
1040 		(void) restarter_instance_update_states(local_handle, inst,
1041 		    inst->ri_i.i_state, RESTARTER_STATE_NONE, RERR_NONE,
1042 		    NULL);
1043 		goto out;
1044 
1045 	case EINVAL:
1046 	case ENOTSUP:
1047 	default:
1048 		bad_error("libscf_fmri_get_instance", r);
1049 	}
1050 
1051 	inst->ri_m_inst = s_inst;
1052 	inst->ri_mi_deleted = B_FALSE;
1053 
1054 retry:
1055 	if (info->sf_method_type == METHOD_START)
1056 		log_transition(inst, START_REQUESTED);
1057 
1058 	r = method_run(&inst, info->sf_method_type, &exit_code);
1059 
1060 	if (r == 0 && exit_code == 0) {
1061 		/* Success! */
1062 		assert(inst->ri_i.i_next_state != RESTARTER_STATE_NONE);
1063 
1064 		/*
1065 		 * When a stop method succeeds, remove the primary contract of
1066 		 * the service, unless we're going to offline, in which case
1067 		 * retain the contract so we can transfer inherited contracts to
1068 		 * the replacement service.
1069 		 */
1070 
1071 		if (info->sf_method_type == METHOD_STOP &&
1072 		    inst->ri_i.i_primary_ctid != 0) {
1073 			if (inst->ri_i.i_next_state == RESTARTER_STATE_OFFLINE)
1074 				inst->ri_i.i_primary_ctid_stopped = 1;
1075 			else
1076 				method_remove_contract(inst, B_TRUE, B_TRUE);
1077 		}
1078 		/*
1079 		 * We don't care whether the handle was rebound because this is
1080 		 * the last thing we do with it.
1081 		 */
1082 		(void) restarter_instance_update_states(local_handle, inst,
1083 		    inst->ri_i.i_next_state, RESTARTER_STATE_NONE,
1084 		    info->sf_event_type, NULL);
1085 
1086 		(void) update_fault_count(inst, FAULT_COUNT_RESET);
1087 
1088 		goto out;
1089 	}
1090 
1091 	/* Failure.  Retry or go to maintenance. */
1092 
1093 	if (r != 0 && r != EAGAIN) {
1094 		retryable = B_FALSE;
1095 	} else {
1096 		switch (exit_code) {
1097 		case SMF_EXIT_ERR_CONFIG:
1098 		case SMF_EXIT_ERR_NOSMF:
1099 		case SMF_EXIT_ERR_PERM:
1100 		case SMF_EXIT_ERR_FATAL:
1101 			retryable = B_FALSE;
1102 			break;
1103 
1104 		default:
1105 			retryable = B_TRUE;
1106 		}
1107 	}
1108 
1109 	if (retryable && update_fault_count(inst, FAULT_COUNT_INCR) != 1)
1110 		goto retry;
1111 
1112 	/* maintenance */
1113 	if (r == ELOOP)
1114 		log_transition(inst, START_FAILED_REPEATEDLY);
1115 	else if (r == ERANGE)
1116 		log_transition(inst, START_FAILED_TIMEOUT_FATAL);
1117 	else if (exit_code == SMF_EXIT_ERR_CONFIG)
1118 		log_transition(inst, START_FAILED_CONFIGURATION);
1119 	else if (exit_code == SMF_EXIT_ERR_FATAL)
1120 		log_transition(inst, START_FAILED_FATAL);
1121 	else
1122 		log_transition(inst, START_FAILED_OTHER);
1123 
1124 	if (r == ELOOP)
1125 		aux = "restarting_too_quickly";
1126 	else if (retryable)
1127 		aux = "fault_threshold_reached";
1128 	else
1129 		aux = "method_failed";
1130 
1131 	(void) restarter_instance_update_states(local_handle, inst,
1132 	    RESTARTER_STATE_MAINT, RESTARTER_STATE_NONE, RERR_FAULT,
1133 	    (char *)aux);
1134 
1135 	if (!method_is_transient(inst, info->sf_method_type) &&
1136 	    inst->ri_i.i_primary_ctid != 0)
1137 		method_remove_contract(inst, B_TRUE, B_TRUE);
1138 
1139 out:
1140 	inst->ri_method_thread = 0;
1141 	MUTEX_UNLOCK(&inst->ri_lock);
1142 	(void) pthread_cond_broadcast(&inst->ri_method_cv);
1143 
1144 	scf_instance_destroy(s_inst);
1145 	scf_handle_destroy(local_handle);
1146 	startd_free(info, sizeof (fork_info_t));
1147 	return (NULL);
1148 }
1149