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