xref: /titanic_41/usr/src/cmd/fm/fmd/common/fmd.c (revision 0adc16190e36914964740716575460dda750de39)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/utsname.h>
32 #include <sys/param.h>
33 #include <sys/systeminfo.h>
34 #include <sys/fm/util.h>
35 
36 #include <limits.h>
37 #include <unistd.h>
38 #include <signal.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <door.h>
42 
43 #include <fmd_conf.h>
44 #include <fmd_dispq.h>
45 #include <fmd_timerq.h>
46 #include <fmd_subr.h>
47 #include <fmd_error.h>
48 #include <fmd_module.h>
49 #include <fmd_thread.h>
50 #include <fmd_alloc.h>
51 #include <fmd_string.h>
52 #include <fmd_builtin.h>
53 #include <fmd_ustat.h>
54 #include <fmd_protocol.h>
55 #include <fmd_scheme.h>
56 #include <fmd_asru.h>
57 #include <fmd_case.h>
58 #include <fmd_log.h>
59 #include <fmd_idspace.h>
60 #include <fmd_rpc.h>
61 #include <fmd_dr.h>
62 #include <fmd_xprt.h>
63 #include <fmd_ctl.h>
64 
65 #include <fmd.h>
66 
67 extern const nv_alloc_ops_t fmd_nv_alloc_ops;	/* see fmd_nv.c */
68 
69 const char _fmd_version[] = "1.1";		/* daemon version string */
70 static char _fmd_plat[MAXNAMELEN];		/* native platform string */
71 static char _fmd_isa[MAXNAMELEN];		/* native instruction set */
72 static struct utsname _fmd_uts;			/* native uname(2) info */
73 
74 /*
75  * Note: the configuration file path is ordered from most common to most host-
76  * specific because new conf files are merged/override previous ones.  The
77  * module paths are in the opposite order, from most specific to most common,
78  * because once a module is loaded fmd will not try to load over the same name.
79  */
80 
81 static const char _fmd_conf_path[] =
82 	"%r/usr/lib/fm/fmd:"
83 	"%r/usr/platform/%m/lib/fm/fmd:"
84 	"%r/usr/platform/%i/lib/fm/fmd:"
85 	"%r/etc/fm/fmd";
86 
87 static const char _fmd_agent_path[] =
88 	"%r/usr/platform/%i/lib/fm/fmd/agents:"
89 	"%r/usr/platform/%m/lib/fm/fmd/agents:"
90 	"%r/usr/lib/fm/fmd/agents";
91 
92 static const char _fmd_plugin_path[] =
93 	"%r/usr/platform/%i/lib/fm/fmd/plugins:"
94 	"%r/usr/platform/%m/lib/fm/fmd/plugins:"
95 	"%r/usr/lib/fm/fmd/plugins";
96 
97 static const char _fmd_scheme_path[] =
98 	"usr/lib/fm/fmd/schemes";
99 
100 static const fmd_conf_mode_t _fmd_cerror_modes[] = {
101 	{ "unload", "unload offending client module", FMD_CERROR_UNLOAD },
102 	{ "stop", "stop daemon for debugger attach", FMD_CERROR_STOP },
103 	{ "abort", "abort daemon and force core dump", FMD_CERROR_ABORT },
104 	{ NULL, NULL, 0 }
105 };
106 
107 static const fmd_conf_mode_t _fmd_dbout_modes[] = {
108 	{ "stderr", "send debug messages to stderr", FMD_DBOUT_STDERR },
109 	{ "syslog", "send debug messages to syslog", FMD_DBOUT_SYSLOG },
110 	{ NULL, NULL, 0 }
111 };
112 
113 static const fmd_conf_mode_t _fmd_debug_modes[] = {
114 	{ "help", "display debugging modes and exit", FMD_DBG_HELP },
115 	{ "mod", "debug module load/unload/locking", FMD_DBG_MOD },
116 	{ "disp", "debug dispatch queue processing", FMD_DBG_DISP },
117 	{ "xprt", "debug transport-specific routines", FMD_DBG_XPRT },
118 	{ "evt", "debug event subsystem routines", FMD_DBG_EVT },
119 	{ "log", "debug log subsystem routines", FMD_DBG_LOG },
120 	{ "tmr", "debug timer subsystem routines", FMD_DBG_TMR },
121 	{ "fmri", "debug fmri subsystem routines", FMD_DBG_FMRI },
122 	{ "asru", "debug asru subsystem routines", FMD_DBG_ASRU },
123 	{ "case", "debug case subsystem routines", FMD_DBG_CASE },
124 	{ "ckpt", "debug checkpoint routines", FMD_DBG_CKPT },
125 	{ "rpc", "debug rpc service routines", FMD_DBG_RPC },
126 	{ "trace", "display matching trace calls", FMD_DBG_TRACE },
127 	{ "all", "enable all available debug modes", FMD_DBG_ALL },
128 	{ NULL, NULL, 0 }
129 };
130 
131 static int
132 fmd_cerror_set(fmd_conf_param_t *pp, const char *value)
133 {
134 	return (fmd_conf_mode_set(_fmd_cerror_modes, pp, value));
135 }
136 
137 static int
138 fmd_dbout_set(fmd_conf_param_t *pp, const char *value)
139 {
140 	return (fmd_conf_mode_set(_fmd_dbout_modes, pp, value));
141 }
142 
143 static int
144 fmd_debug_set(fmd_conf_param_t *pp, const char *value)
145 {
146 	int err = fmd_conf_mode_set(_fmd_debug_modes, pp, value);
147 
148 	if (err == 0)
149 		fmd.d_fmd_debug = pp->cp_value.cpv_num;
150 
151 	return (err);
152 }
153 
154 static int
155 fmd_trmode_set(fmd_conf_param_t *pp, const char *value)
156 {
157 	fmd_tracebuf_f *func;
158 
159 	if (strcasecmp(value, "none") == 0)
160 		func = fmd_trace_none;
161 	else if (strcasecmp(value, "lite") == 0)
162 		func = fmd_trace_lite;
163 	else if (strcasecmp(value, "full") == 0)
164 		func = fmd_trace_full;
165 	else
166 		return (fmd_set_errno(EFMD_CONF_INVAL));
167 
168 	fmd.d_thr_trace = (void (*)())func;
169 	pp->cp_value.cpv_ptr = (void *)func;
170 	return (0);
171 }
172 
173 static void
174 fmd_trmode_get(const fmd_conf_param_t *pp, void *ptr)
175 {
176 	*((void **)ptr) = pp->cp_value.cpv_ptr;
177 }
178 
179 static int
180 fmd_clkmode_set(fmd_conf_param_t *pp, const char *value)
181 {
182 	const fmd_timeops_t *ops;
183 
184 	if (strcasecmp(value, "native") == 0)
185 		ops = &fmd_timeops_native;
186 	else if (strcasecmp(value, "simulated") == 0)
187 		ops = &fmd_timeops_simulated;
188 	else
189 		return (fmd_set_errno(EFMD_CONF_INVAL));
190 
191 	fmd.d_clockops = ops;
192 	pp->cp_value.cpv_ptr = (void *)ops;
193 	return (0);
194 }
195 
196 static void
197 fmd_clkmode_get(const fmd_conf_param_t *pp, void *ptr)
198 {
199 	*((void **)ptr) = pp->cp_value.cpv_ptr;
200 }
201 
202 static const fmd_conf_ops_t fmd_cerror_ops = {
203 	fmd_cerror_set, fmd_conf_mode_get, fmd_conf_notsup, fmd_conf_nop
204 };
205 
206 static const fmd_conf_ops_t fmd_dbout_ops = {
207 	fmd_dbout_set, fmd_conf_mode_get, fmd_conf_notsup, fmd_conf_nop
208 };
209 
210 static const fmd_conf_ops_t fmd_debug_ops = {
211 	fmd_debug_set, fmd_conf_mode_get, fmd_conf_notsup, fmd_conf_nop
212 };
213 
214 static const fmd_conf_ops_t fmd_trmode_ops = {
215 	fmd_trmode_set, fmd_trmode_get, fmd_conf_notsup, fmd_conf_nop
216 };
217 
218 static const fmd_conf_ops_t fmd_clkmode_ops = {
219 	fmd_clkmode_set, fmd_clkmode_get, fmd_conf_notsup, fmd_conf_nop
220 };
221 
222 static const fmd_conf_formal_t _fmd_conf[] = {
223 { "agent.path", &fmd_conf_path, _fmd_agent_path }, /* path for agents */
224 { "alloc_msecs", &fmd_conf_uint32, "10" },	/* msecs before alloc retry */
225 { "alloc_tries", &fmd_conf_uint32, "3" },	/* max # of alloc retries */
226 { "chassis", &fmd_conf_string, NULL },		/* chassis serial number */
227 { "ckpt.dir", &fmd_conf_string, "var/fm/fmd/ckpt" }, /* ckpt directory path */
228 { "ckpt.dirmode", &fmd_conf_int32, "0700" },	/* ckpt directory perm mode */
229 { "ckpt.mode", &fmd_conf_int32, "0400" },	/* ckpt file perm mode */
230 { "ckpt.restore", &fmd_conf_bool, "true" },	/* restore checkpoints? */
231 { "ckpt.save", &fmd_conf_bool, "true" },	/* save checkpoints? */
232 { "ckpt.zero", &fmd_conf_bool, "false" },	/* zero checkpoints on start? */
233 { "client.buflim", &fmd_conf_size, "10m" },	/* client buffer space limit */
234 { "client.dbout", &fmd_dbout_ops, NULL },	/* client debug output sinks */
235 { "client.debug", &fmd_conf_bool, NULL },	/* client debug enable */
236 { "client.error", &fmd_cerror_ops, "unload" },	/* client error policy */
237 { "client.memlim", &fmd_conf_size, "10m" },	/* client allocation limit */
238 { "client.evqlim", &fmd_conf_uint32, "256" },	/* client event queue limit */
239 { "client.thrlim", &fmd_conf_uint32, "8" },	/* client aux thread limit */
240 { "client.thrsig", &fmd_conf_signal, "SIGUSR1" }, /* fmd_thr_signal() value */
241 { "client.tmrlim", &fmd_conf_uint32, "1024" },	/* client pending timer limit */
242 { "client.xprtlim", &fmd_conf_uint32, "256" },	/* client transport limit */
243 { "client.xprtlog", &fmd_conf_bool, NULL },	/* client transport logging? */
244 { "client.xprtqlim", &fmd_conf_uint32, "256" }, /* client transport queue lim */
245 { "clock", &fmd_clkmode_ops, "native" },	/* clock operation mode */
246 { "conf_path", &fmd_conf_path, _fmd_conf_path }, /* root config file path */
247 { "conf_file", &fmd_conf_string, "fmd.conf" },	/* root config file name */
248 { "core", &fmd_conf_bool, "false" },		/* force core dump on quit */
249 { "dbout", &fmd_dbout_ops, NULL },		/* daemon debug output sinks */
250 { "debug", &fmd_debug_ops, NULL },		/* daemon debugging flags */
251 { "dictdir", &fmd_conf_string, "usr/lib/fm/dict" }, /* default diagcode dir */
252 { "domain", &fmd_conf_string, NULL },		/* domain id for de auth */
253 { "fg", &fmd_conf_bool, "false" },		/* run daemon in foreground */
254 { "gc_interval", &fmd_conf_time, "1d" },	/* garbage collection intvl */
255 { "ids.avg", &fmd_conf_uint32, "4" },		/* desired idspace chain len */
256 { "ids.max", &fmd_conf_uint32, "1024" },	/* maximum idspace buckets */
257 { "isaname", &fmd_conf_string, _fmd_isa },	/* instruction set (uname -p) */
258 { "log.creator", &fmd_conf_string, "fmd" },	/* exacct log creator string */
259 { "log.error", &fmd_conf_string, "var/fm/fmd/errlog" }, /* error log path */
260 { "log.fault", &fmd_conf_string, "var/fm/fmd/fltlog" }, /* fault log path */
261 { "log.minfree", &fmd_conf_size, "2m" },	/* min log fsys free space */
262 { "log.rsrc", &fmd_conf_string, "var/fm/fmd/rsrc" }, /* asru log dir path */
263 { "log.tryrotate", &fmd_conf_uint32, "10" },	/* max log rotation attempts */
264 { "log.waitrotate", &fmd_conf_time, "200ms" },	/* log rotation retry delay */
265 { "log.xprt", &fmd_conf_string, "var/fm/fmd/xprt" }, /* transport log dir */
266 { "machine", &fmd_conf_string, _fmd_uts.machine }, /* machine name (uname -m) */
267 { "nodiagcode", &fmd_conf_string, "-" },	/* diagcode to use if error */
268 { "osrelease", &fmd_conf_string, _fmd_uts.release }, /* release (uname -r) */
269 { "osversion", &fmd_conf_string, _fmd_uts.version }, /* version (uname -v) */
270 { "platform", &fmd_conf_string, _fmd_plat },	/* platform string (uname -i) */
271 { "plugin.close", &fmd_conf_bool, "true" },	/* dlclose plugins on fini */
272 { "plugin.path", &fmd_conf_path, _fmd_plugin_path }, /* path for plugin mods */
273 { "rootdir", &fmd_conf_string, "" },		/* root directory for paths */
274 { "rpc.adm.path", &fmd_conf_string, NULL },	/* FMD_ADM rendezvous file */
275 { "rpc.adm.prog", &fmd_conf_uint32, "100169" },	/* FMD_ADM rpc program num */
276 { "rpc.api.path", &fmd_conf_string, NULL },	/* FMD_API rendezvous file */
277 { "rpc.api.prog", &fmd_conf_uint32, "100170" },	/* FMD_API rpc program num */
278 { "rpc.rcvsize", &fmd_conf_size, "128k" },	/* rpc receive buffer size */
279 { "rpc.sndsize", &fmd_conf_size, "128k" },	/* rpc send buffer size */
280 { "rsrc.age", &fmd_conf_time, "30d" },		/* max age of old rsrc log */
281 { "rsrc.zero", &fmd_conf_bool, "false" },	/* zero rsrc cache on start? */
282 { "schemedir", &fmd_conf_string, _fmd_scheme_path }, /* path for scheme mods */
283 { "self.name", &fmd_conf_string, "fmd-self-diagnosis" }, /* self-diag module */
284 { "self.dict", &fmd_conf_list, "FMD.dict" },	/* self-diag dictionary list */
285 { "server", &fmd_conf_string, _fmd_uts.nodename }, /* server id for de auth */
286 { "strbuckets", &fmd_conf_uint32, "211" },	/* size of string hashes */
287 #ifdef DEBUG
288 { "trace.mode", &fmd_trmode_ops, "full" },	/* trace mode: none/lite/full */
289 #else
290 { "trace.mode", &fmd_trmode_ops, "lite" },	/* trace mode: none/lite/full */
291 #endif
292 { "trace.recs", &fmd_conf_uint32, "128" },	/* trace records per thread */
293 { "trace.frames", &fmd_conf_uint32, "16" },	/* max trace rec stack frames */
294 { "uuidlen", &fmd_conf_uint32, "36" },		/* UUID ASCII string length */
295 { "xprt.ttl", &fmd_conf_uint8, "1" },		/* default event time-to-live */
296 };
297 
298 /*
299  * Statistics maintained by fmd itself on behalf of various global subsystems.
300  * NOTE: FMD_TYPE_STRING statistics should not be used here.  If they are
301  * required in the future, the FMD_ADM_MODGSTAT service routine must change.
302  */
303 static fmd_statistics_t _fmd_stats = {
304 { "errlog.replayed", FMD_TYPE_UINT64, "total events replayed from errlog" },
305 { "errlog.partials", FMD_TYPE_UINT64, "events partially committed in errlog" },
306 { "errlog.enospc", FMD_TYPE_UINT64, "events not appended to errlog (ENOSPC)" },
307 { "fltlog.enospc", FMD_TYPE_UINT64, "events not appended to fltlog (ENOSPC)" },
308 { "log.enospc", FMD_TYPE_UINT64, "events not appended to other logs (ENOSPC)" },
309 { "dr.gen", FMD_TYPE_UINT64, "dynamic reconfiguration generation" },
310 };
311 
312 void
313 fmd_create(fmd_t *dp, const char *arg0, const char *root, const char *conf)
314 {
315 	fmd_conf_path_t *pap;
316 	char file[PATH_MAX];
317 	const char *name;
318 	fmd_stat_t *sp;
319 	int i;
320 
321 	(void) sysinfo(SI_PLATFORM, _fmd_plat, sizeof (_fmd_plat));
322 	(void) sysinfo(SI_ARCHITECTURE, _fmd_isa, sizeof (_fmd_isa));
323 	(void) uname(&_fmd_uts);
324 
325 	bzero(dp, sizeof (fmd_t));
326 
327 	dp->d_version = _fmd_version;
328 	dp->d_pname = fmd_strbasename(arg0);
329 	dp->d_pid = getpid();
330 
331 	if (pthread_key_create(&dp->d_key, NULL) != 0)
332 		fmd_error(EFMD_EXIT, "failed to create pthread key");
333 
334 	(void) pthread_mutex_init(&dp->d_xprt_lock, NULL);
335 	(void) pthread_mutex_init(&dp->d_err_lock, NULL);
336 	(void) pthread_mutex_init(&dp->d_thr_lock, NULL);
337 	(void) pthread_mutex_init(&dp->d_mod_lock, NULL);
338 	(void) pthread_mutex_init(&dp->d_stats_lock, NULL);
339 	(void) pthread_rwlock_init(&dp->d_log_lock, NULL);
340 
341 	/*
342 	 * A small number of properties must be set manually before we open
343 	 * the root configuration file.  These include any settings for our
344 	 * memory allocator and path expansion token values, because these
345 	 * values are needed by the routines in fmd_conf.c itself.  After
346 	 * the root configuration file is processed, we reset these properties
347 	 * based upon the latest values from the configuration file.
348 	 */
349 	dp->d_alloc_msecs = 10;
350 	dp->d_alloc_tries = 3;
351 	dp->d_str_buckets = 211;
352 
353 	dp->d_rootdir = root ? root : "";
354 	dp->d_platform = _fmd_plat;
355 	dp->d_machine = _fmd_uts.machine;
356 	dp->d_isaname = _fmd_isa;
357 
358 	dp->d_conf = fmd_conf_open(conf, sizeof (_fmd_conf) /
359 	    sizeof (_fmd_conf[0]), _fmd_conf, FMD_CONF_DEFER);
360 
361 	if (dp->d_conf == NULL) {
362 		fmd_error(EFMD_EXIT,
363 		    "failed to load required configuration properties\n");
364 	}
365 
366 	(void) fmd_conf_getprop(dp->d_conf, "alloc.msecs", &dp->d_alloc_msecs);
367 	(void) fmd_conf_getprop(dp->d_conf, "alloc.tries", &dp->d_alloc_tries);
368 	(void) fmd_conf_getprop(dp->d_conf, "strbuckets", &dp->d_str_buckets);
369 
370 	(void) fmd_conf_getprop(dp->d_conf, "platform", &dp->d_platform);
371 	(void) fmd_conf_getprop(dp->d_conf, "machine", &dp->d_machine);
372 	(void) fmd_conf_getprop(dp->d_conf, "isaname", &dp->d_isaname);
373 
374 	/*
375 	 * Manually specified rootdirs override config files, so only update
376 	 * d_rootdir based on the config files we parsed if no 'root' was set.
377 	 */
378 	if (root == NULL)
379 		(void) fmd_conf_getprop(dp->d_conf, "rootdir", &dp->d_rootdir);
380 	else
381 		(void) fmd_conf_setprop(dp->d_conf, "rootdir", dp->d_rootdir);
382 
383 	/*
384 	 * Once the base conf file properties are loaded, lookup the values
385 	 * of $conf_path and $conf_file and merge in any other conf files.
386 	 */
387 	(void) fmd_conf_getprop(dp->d_conf, "conf_path", &pap);
388 	(void) fmd_conf_getprop(dp->d_conf, "conf_file", &name);
389 
390 	for (i = 0; i < pap->cpa_argc; i++) {
391 		(void) snprintf(file, sizeof (file),
392 		    "%s/%s", pap->cpa_argv[i], name);
393 		if (access(file, F_OK) == 0)
394 			fmd_conf_merge(dp->d_conf, file);
395 	}
396 
397 	/*
398 	 * Update the value of fmd.d_fg based on "fg".  We cache this property
399 	 * because it must be accessed deep within fmd at fmd_verror() time.
400 	 * Update any other properties that must be cached for performance.
401 	 */
402 	(void) fmd_conf_getprop(fmd.d_conf, "fg", &fmd.d_fg);
403 	(void) fmd_conf_getprop(fmd.d_conf, "xprt.ttl", &fmd.d_xprt_ttl);
404 
405 	/*
406 	 * Initialize our custom libnvpair allocator and create an nvlist for
407 	 * authority elements corresponding to this instance of the daemon.
408 	 */
409 	(void) nv_alloc_init(&dp->d_nva, &fmd_nv_alloc_ops);
410 	dp->d_auth = fmd_protocol_authority();
411 
412 	/*
413 	 * The fmd_module_t for the root module must be created manually.  Most
414 	 * of it remains unused and zero, except for the few things we fill in.
415 	 */
416 	dp->d_rmod = fmd_zalloc(sizeof (fmd_module_t), FMD_SLEEP);
417 	dp->d_rmod->mod_name = fmd_strdup(dp->d_pname, FMD_SLEEP);
418 	dp->d_rmod->mod_fmri = fmd_protocol_fmri_module(dp->d_rmod);
419 
420 	fmd_list_append(&dp->d_mod_list, dp->d_rmod);
421 	fmd_module_hold(dp->d_rmod);
422 
423 	(void) pthread_mutex_init(&dp->d_rmod->mod_lock, NULL);
424 	(void) pthread_cond_init(&dp->d_rmod->mod_cv, NULL);
425 	(void) pthread_mutex_init(&dp->d_rmod->mod_stats_lock, NULL);
426 
427 	dp->d_rmod->mod_thread = fmd_thread_xcreate(dp->d_rmod, pthread_self());
428 	dp->d_rmod->mod_stats = fmd_zalloc(sizeof (fmd_modstat_t), FMD_SLEEP);
429 	dp->d_rmod->mod_ustat = fmd_ustat_create();
430 
431 	if (pthread_setspecific(dp->d_key, dp->d_rmod->mod_thread) != 0)
432 		fmd_error(EFMD_EXIT, "failed to attach main thread key");
433 
434 	if ((dp->d_stats = (fmd_statistics_t *)fmd_ustat_insert(
435 	    dp->d_rmod->mod_ustat, FMD_USTAT_NOALLOC, sizeof (_fmd_stats) /
436 	    sizeof (fmd_stat_t), (fmd_stat_t *)&_fmd_stats, NULL)) == NULL)
437 		fmd_error(EFMD_EXIT, "failed to initialize statistics");
438 
439 	(void) pthread_mutex_lock(&dp->d_rmod->mod_lock);
440 	dp->d_rmod->mod_flags |= FMD_MOD_INIT;
441 	(void) pthread_mutex_unlock(&dp->d_rmod->mod_lock);
442 
443 	/*
444 	 * In addition to inserting the _fmd_stats collection of program-wide
445 	 * statistics, we also insert a statistic named after each of our
446 	 * errors and update these counts in fmd_verror() (see fmd_subr.c).
447 	 */
448 	dp->d_errstats = sp = fmd_zalloc(sizeof (fmd_stat_t) *
449 	    (EFMD_END - EFMD_UNKNOWN), FMD_SLEEP);
450 
451 	for (i = 0; i < EFMD_END - EFMD_UNKNOWN; i++, sp++) {
452 		(void) snprintf(sp->fmds_name, sizeof (sp->fmds_name), "err.%s",
453 		    strrchr(fmd_errclass(EFMD_UNKNOWN + i), '.') + 1);
454 		sp->fmds_type = FMD_TYPE_UINT64;
455 	}
456 
457 	(void) fmd_ustat_insert(dp->d_rmod->mod_ustat, FMD_USTAT_NOALLOC,
458 	    EFMD_END - EFMD_UNKNOWN, dp->d_errstats, NULL);
459 }
460 
461 void
462 fmd_destroy(fmd_t *dp)
463 {
464 	fmd_module_t *mp;
465 	fmd_case_t *cp;
466 	int core;
467 
468 	(void) fmd_conf_getprop(fmd.d_conf, "core", &core);
469 
470 	fmd_rpc_fini();
471 	fmd_dr_fini();
472 
473 	if (dp->d_xprt_ids != NULL)
474 		fmd_xprt_suspend_all();
475 
476 	/*
477 	 * Unload the self-diagnosis module first.  This ensures that it does
478 	 * not get confused as we start unloading other modules, etc.  We must
479 	 * hold the dispq lock as a writer while doing so since it uses d_self.
480 	 */
481 	if (dp->d_self != NULL) {
482 		(void) pthread_rwlock_wrlock(&dp->d_disp->dq_lock);
483 		fmd_module_unload(dp->d_self);
484 		fmd_module_rele(dp->d_self);
485 		dp->d_self = NULL;
486 		(void) pthread_rwlock_unlock(&dp->d_disp->dq_lock);
487 	}
488 
489 	/*
490 	 * Unload modules in reverse order *except* for the root module, which
491 	 * is first in the list.  This allows it to keep its thread and trace.
492 	 */
493 	for (mp = fmd_list_prev(&dp->d_mod_list); mp != dp->d_rmod; ) {
494 		fmd_module_unload(mp);
495 		mp = fmd_list_prev(mp);
496 	}
497 
498 	if (dp->d_mod_hash != NULL) {
499 		fmd_modhash_destroy(dp->d_mod_hash);
500 		dp->d_mod_hash = NULL;
501 	}
502 
503 	/*
504 	 * Close both log files now that modules are no longer active.  We must
505 	 * set these pointers to NULL in case any subsequent errors occur.
506 	 */
507 	if (dp->d_errlog != NULL) {
508 		fmd_log_rele(dp->d_errlog);
509 		dp->d_errlog = NULL;
510 	}
511 
512 	if (dp->d_fltlog != NULL) {
513 		fmd_log_rele(dp->d_fltlog);
514 		dp->d_fltlog = NULL;
515 	}
516 
517 	/*
518 	 * Now destroy the resource cache: each ASRU contains a case reference,
519 	 * which may in turn contain a pointer to a referenced owning module.
520 	 */
521 	if (dp->d_asrus != NULL) {
522 		fmd_asru_hash_destroy(dp->d_asrus);
523 		dp->d_asrus = NULL;
524 	}
525 
526 	/*
527 	 * Now that all data structures that refer to modules are torn down,
528 	 * no modules should be remaining on the module list except for d_rmod.
529 	 * If we trip one of these assertions, we're missing a rele somewhere.
530 	 */
531 	ASSERT(fmd_list_prev(&dp->d_mod_list) == dp->d_rmod);
532 	ASSERT(fmd_list_next(&dp->d_mod_list) == dp->d_rmod);
533 
534 	/*
535 	 * Now destroy the root module.  We clear its thread key first so any
536 	 * calls to fmd_trace() inside of the module code will be ignored.
537 	 */
538 	(void) pthread_setspecific(dp->d_key, NULL);
539 	fmd_module_lock(dp->d_rmod);
540 
541 	while ((cp = fmd_list_next(&dp->d_rmod->mod_cases)) != NULL)
542 		fmd_case_discard(cp);
543 
544 	fmd_module_unlock(dp->d_rmod);
545 	fmd_free(dp->d_rmod->mod_stats, sizeof (fmd_modstat_t));
546 	dp->d_rmod->mod_stats = NULL;
547 
548 	(void) pthread_mutex_lock(&dp->d_rmod->mod_lock);
549 	dp->d_rmod->mod_flags |= FMD_MOD_FINI;
550 	(void) pthread_mutex_unlock(&dp->d_rmod->mod_lock);
551 
552 	fmd_module_rele(dp->d_rmod);
553 	ASSERT(fmd_list_next(&dp->d_mod_list) == NULL);
554 
555 	/*
556 	 * Now destroy the remaining global data structures.  If 'core' was
557 	 * set to true, force a core dump so we can check for memory leaks.
558 	 */
559 	if (dp->d_cases != NULL)
560 		fmd_case_hash_destroy(dp->d_cases);
561 	if (dp->d_disp != NULL)
562 		fmd_dispq_destroy(dp->d_disp);
563 	if (dp->d_timers != NULL)
564 		fmd_timerq_destroy(dp->d_timers);
565 	if (dp->d_schemes != NULL)
566 		fmd_scheme_hash_destroy(dp->d_schemes);
567 	if (dp->d_xprt_ids != NULL)
568 		fmd_idspace_destroy(dp->d_xprt_ids);
569 
570 	if (dp->d_errstats != NULL) {
571 		fmd_free(dp->d_errstats,
572 		    sizeof (fmd_stat_t) * (EFMD_END - EFMD_UNKNOWN));
573 	}
574 
575 	if (dp->d_conf != NULL)
576 		fmd_conf_close(dp->d_conf);
577 
578 	nvlist_free(dp->d_auth);
579 	(void) nv_alloc_fini(&dp->d_nva);
580 	dp->d_clockops->fto_fini(dp->d_clockptr);
581 
582 	(void) pthread_key_delete(dp->d_key);
583 	bzero(dp, sizeof (fmd_t));
584 
585 	if (core)
586 		fmd_panic("forcing core dump at user request\n");
587 }
588 
589 /*ARGSUSED*/
590 static void
591 fmd_gc(fmd_t *dp, id_t id, hrtime_t hrt)
592 {
593 	hrtime_t delta;
594 
595 	if (id != 0) {
596 		TRACE((FMD_DBG_MOD, "garbage collect start"));
597 		fmd_modhash_apply(dp->d_mod_hash, fmd_module_gc);
598 		TRACE((FMD_DBG_MOD, "garbage collect end"));
599 
600 		(void) pthread_rwlock_rdlock(&dp->d_log_lock);
601 		fmd_log_update(dp->d_errlog);
602 		(void) pthread_rwlock_unlock(&dp->d_log_lock);
603 	}
604 
605 	(void) fmd_conf_getprop(dp->d_conf, "gc_interval", &delta);
606 	(void) fmd_timerq_install(dp->d_timers, dp->d_rmod->mod_timerids,
607 	    (fmd_timer_f *)fmd_gc, dp, NULL, delta);
608 }
609 
610 /*
611  * Events are committed to the errlog after cases are checkpointed.  If fmd
612  * crashes before an event is ever associated with a module, this function will
613  * be called to replay it to all subscribers.  If fmd crashes in between the
614  * subscriber checkpointing and committing the event in the error log, the
615  * module will have seen the event and we don't want to replay it.  So we look
616  * for the event in all modules and transition it to the proper state.  If
617  * it is found, we commit it to the error log and do not replay it.  The in-
618  * memory case search used by fmd_module_contains() et al isn't particularly
619  * efficient, but it is faster than doing read i/o's on every case event to
620  * check their status or write i/o's on every event to replay to update states.
621  * We can improve the efficiency of this lookup algorithm later if necessary.
622  */
623 /*ARGSUSED*/
624 static void
625 fmd_err_replay(fmd_log_t *lp, fmd_event_t *ep, fmd_t *dp)
626 {
627 	fmd_module_t *mp;
628 	fmd_stat_t *sp;
629 
630 	(void) pthread_mutex_lock(&dp->d_mod_lock);
631 
632 	for (mp = fmd_list_next(&dp->d_mod_list);
633 	    mp != NULL; mp = fmd_list_next(mp)) {
634 		if (fmd_module_contains(mp, ep)) {
635 			fmd_module_hold(mp);
636 			break;
637 		}
638 	}
639 
640 	(void) pthread_mutex_unlock(&dp->d_mod_lock);
641 
642 	if (mp != NULL) {
643 		fmd_event_commit(ep);
644 		fmd_module_rele(mp);
645 		sp = &dp->d_stats->ds_log_partials;
646 	} else {
647 		fmd_dispq_dispatch(dp->d_disp, ep, FMD_EVENT_DATA(ep));
648 		sp = &dp->d_stats->ds_log_replayed;
649 	}
650 
651 	(void) pthread_mutex_lock(&dp->d_stats_lock);
652 	sp->fmds_value.ui64++;
653 	(void) pthread_mutex_unlock(&dp->d_stats_lock);
654 }
655 
656 void
657 fmd_door_server(void *dip)
658 {
659 	fmd_dprintf(FMD_DBG_XPRT, "door server starting for %p\n", dip);
660 	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
661 	(void) door_return(NULL, 0, NULL, 0);
662 }
663 
664 /*
665  * Custom door server create callback.  Any fmd services that use doors will
666  * require those threads to have their fmd-specific TSD initialized, etc.
667  */
668 static void
669 fmd_door(door_info_t *dip)
670 {
671 	if (fmd_thread_create(fmd.d_rmod, fmd_door_server, dip) == NULL)
672 		fmd_panic("failed to create server for door %p", (void *)dip);
673 }
674 
675 /*
676  * This signal handler is installed for the client.thrsig signal to be used to
677  * force an auxiliary thread to wake up from a system call and return EINTR in
678  * response to a module's use of fmd_thr_signal().  We also trace the event.
679  */
680 static void
681 fmd_signal(int sig)
682 {
683 	TRACE((FMD_DBG_MOD, "module thread received sig #%d", sig));
684 }
685 
686 void
687 fmd_run(fmd_t *dp, int pfd)
688 {
689 	char *nodc_key[] = { FMD_FLT_NODC, NULL };
690 	char nodc_str[128];
691 	struct sigaction act;
692 
693 	int status = FMD_EXIT_SUCCESS;
694 	const char *name;
695 	fmd_conf_path_t *pap;
696 	fmd_event_t *e;
697 	int dbout;
698 
699 	/*
700 	 * Cache all the current debug property settings in d_fmd_debug,
701 	 * d_fmd_dbout, d_hdl_debug, and d_hdl_dbout.  If a given debug mask
702 	 * is non-zero and the corresponding dbout mask is zero, set dbout
703 	 * to a sensible default value based on whether we have daemonized.
704 	 */
705 	(void) fmd_conf_getprop(dp->d_conf, "dbout", &dbout);
706 
707 	if (dp->d_fmd_debug != 0 && dbout == 0)
708 		dp->d_fmd_dbout = dp->d_fg? FMD_DBOUT_STDERR : FMD_DBOUT_SYSLOG;
709 	else
710 		dp->d_fmd_dbout = dbout;
711 
712 	(void) fmd_conf_getprop(dp->d_conf, "client.debug", &dp->d_hdl_debug);
713 	(void) fmd_conf_getprop(dp->d_conf, "client.dbout", &dbout);
714 
715 	if (dp->d_hdl_debug != 0 && dbout == 0)
716 		dp->d_hdl_dbout = dp->d_fg? FMD_DBOUT_STDERR : FMD_DBOUT_SYSLOG;
717 	else
718 		dp->d_hdl_dbout = dbout;
719 
720 	/*
721 	 * Initialize remaining major program data structures such as the
722 	 * clock, dispatch queues, log files, module hash collections, etc.
723 	 * This work is done here rather than in fmd_create() to permit the -o
724 	 * command-line option to modify properties after fmd_create() is done.
725 	 */
726 	dp->d_clockptr = dp->d_clockops->fto_init();
727 	dp->d_xprt_ids = fmd_idspace_create("xprt_ids", 1, INT_MAX);
728 	fmd_xprt_suspend_all();
729 
730 	(void) door_server_create(fmd_door);
731 	fmd_dr_init();
732 
733 	dp->d_rmod->mod_timerids = fmd_idspace_create(dp->d_pname, 1, 16);
734 	dp->d_timers = fmd_timerq_create();
735 	dp->d_disp = fmd_dispq_create();
736 	dp->d_cases = fmd_case_hash_create();
737 
738 	/*
739 	 * The root module's mod_queue is created with limit zero, making it
740 	 * act like /dev/null; anything inserted here is simply ignored.
741 	 */
742 	dp->d_rmod->mod_queue = fmd_eventq_create(dp->d_rmod,
743 	    &dp->d_rmod->mod_stats->ms_evqstat, &dp->d_rmod->mod_stats_lock, 0);
744 
745 	/*
746 	 * Once our subsystems that use signals have been set up, install the
747 	 * signal handler for the fmd_thr_signal() API.  Verify that the signal
748 	 * being used for this purpose doesn't conflict with something else.
749 	 */
750 	(void) fmd_conf_getprop(dp->d_conf, "client.thrsig", &dp->d_thr_sig);
751 
752 	if (sigaction(dp->d_thr_sig, NULL, &act) != 0) {
753 		fmd_error(EFMD_EXIT, "invalid signal selected for "
754 		    "client.thrsig property: %d\n", dp->d_thr_sig);
755 	}
756 
757 	if (act.sa_handler != SIG_IGN && act.sa_handler != SIG_DFL) {
758 		fmd_error(EFMD_EXIT, "signal selected for client.thrsig "
759 		    "property is already in use: %d\n", dp->d_thr_sig);
760 	}
761 
762 	act.sa_handler = fmd_signal;
763 	act.sa_flags = 0;
764 
765 	(void) sigemptyset(&act.sa_mask);
766 	(void) sigaction(dp->d_thr_sig, &act, NULL);
767 
768 	(void) fmd_conf_getprop(dp->d_conf, "schemedir", &name);
769 	dp->d_schemes = fmd_scheme_hash_create(dp->d_rootdir, name);
770 
771 	(void) fmd_conf_getprop(dp->d_conf, "log.rsrc", &name);
772 	dp->d_asrus = fmd_asru_hash_create(dp->d_rootdir, name);
773 
774 	(void) fmd_conf_getprop(dp->d_conf, "log.error", &name);
775 	dp->d_errlog = fmd_log_open(dp->d_rootdir, name, FMD_LOG_ERROR);
776 
777 	(void) fmd_conf_getprop(dp->d_conf, "log.fault", &name);
778 	dp->d_fltlog = fmd_log_open(dp->d_rootdir, name, FMD_LOG_FAULT);
779 
780 	if (dp->d_asrus == NULL || dp->d_errlog == NULL || dp->d_fltlog == NULL)
781 		fmd_error(EFMD_EXIT, "failed to initialize log files\n");
782 
783 	/*
784 	 * Before loading modules, create an empty control event which will act
785 	 * as a global barrier for module event processing.  Each module we
786 	 * load successfully will insert it at their head of their event queue,
787 	 * and then pause inside of fmd_ctl_rele() after dequeuing the event.
788 	 * This module barrier is required for two reasons:
789 	 *
790 	 * (a) During module loading, the restoration of case checkpoints may
791 	 *    result in a list.* event being recreated for which the intended
792 	 *    subscriber has not yet loaded depending on the load order. Such
793 	 *    events could then result in spurious "no subscriber" errors.
794 	 *
795 	 * (b) During errlog replay, a sequence of errors from a long time ago
796 	 *    may be replayed, and the module may attempt to install relative
797 	 *    timers associated with one or more of these events.  If errlog
798 	 *    replay were "racing" with active module threads, an event E1
799 	 *    that resulted in a relative timer T at time E1 + N nsec could
800 	 *    fire prior to an event E2 being enqueued, even if the relative
801 	 *    time ordering was E1 < E2 < E1 + N, causing mis-diagnosis.
802 	 */
803 	dp->d_mod_event = e = fmd_event_create(FMD_EVT_CTL,
804 	    FMD_HRT_NOW, NULL, fmd_ctl_init(NULL));
805 
806 	fmd_event_hold(e);
807 
808 	/*
809 	 * Once all data structures are initialized, we load all of our modules
810 	 * in order according to class in order to load up any subscriptions.
811 	 * Once built-in modules are loaded, we detach from our waiting parent.
812 	 */
813 	dp->d_mod_hash = fmd_modhash_create();
814 
815 	if (fmd_builtin_loadall(dp->d_mod_hash) != 0 && !dp->d_fg)
816 		fmd_error(EFMD_EXIT, "failed to initialize fault manager\n");
817 
818 	(void) fmd_conf_getprop(dp->d_conf, "self.name", &name);
819 	dp->d_self = fmd_modhash_lookup(dp->d_mod_hash, name);
820 
821 	if (dp->d_self != NULL && fmd_module_dc_key2code(dp->d_self,
822 	    nodc_key, nodc_str, sizeof (nodc_str)) == 0)
823 		(void) fmd_conf_setprop(dp->d_conf, "nodiagcode", nodc_str);
824 
825 	fmd_rpc_init();
826 	dp->d_running = 1; /* we are now officially an active fmd */
827 
828 	/*
829 	 * Now that we're running, if a pipe fd was specified, write an exit
830 	 * status to it to indicate that our parent process can safely detach.
831 	 * Then proceed to loading the remaining non-built-in modules.
832 	 */
833 	if (pfd >= 0)
834 		(void) write(pfd, &status, sizeof (status));
835 
836 	(void) fmd_conf_getprop(dp->d_conf, "plugin.path", &pap);
837 	fmd_modhash_loadall(dp->d_mod_hash, pap, &fmd_rtld_ops);
838 
839 	(void) fmd_conf_getprop(dp->d_conf, "agent.path", &pap);
840 	fmd_modhash_loadall(dp->d_mod_hash, pap, &fmd_proc_ops);
841 
842 	/*
843 	 * With all modules loaded, replay fault events from the ASRU cache for
844 	 * any ASRUs that must be retired, replay error events from the errlog
845 	 * that did not finish processing the last time ran, and then release
846 	 * the global module barrier by executing a final rele on d_mod_event.
847 	 */
848 	fmd_asru_hash_refresh(dp->d_asrus);
849 
850 	(void) pthread_rwlock_rdlock(&dp->d_log_lock);
851 	fmd_log_replay(dp->d_errlog, (fmd_log_f *)fmd_err_replay, dp);
852 	fmd_log_update(dp->d_errlog);
853 	(void) pthread_rwlock_unlock(&dp->d_log_lock);
854 
855 	dp->d_mod_event = NULL;
856 	fmd_event_rele(e);
857 
858 	/*
859 	 * Finally, awaken any threads associated with receiving events from
860 	 * open transports and tell them to proceed with fmd_xprt_recv().
861 	 */
862 	fmd_xprt_resume_all();
863 	fmd_gc(dp, 0, 0);
864 
865 	dp->d_booted = 1;
866 }
867 
868 void
869 fmd_help(fmd_t *dp)
870 {
871 	const fmd_conf_mode_t *cmp;
872 
873 	(void) printf("Usage: %s -o debug=mode[,mode]\n", dp->d_pname);
874 
875 	for (cmp = _fmd_debug_modes; cmp->cm_name != NULL; cmp++)
876 		(void) printf("\t%s\t%s\n", cmp->cm_name, cmp->cm_desc);
877 }
878