xref: /illumos-gate/usr/src/cmd/fm/fmd/common/fmd.c (revision a07094369b21309434206d9b3601d162693466fc)
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 
564 	fmd_module_unlock(dp->d_rmod);
565 	fmd_free(dp->d_rmod->mod_stats, sizeof (fmd_modstat_t));
566 	dp->d_rmod->mod_stats = NULL;
567 
568 	(void) pthread_mutex_lock(&dp->d_rmod->mod_lock);
569 	dp->d_rmod->mod_flags |= FMD_MOD_FINI;
570 	(void) pthread_mutex_unlock(&dp->d_rmod->mod_lock);
571 
572 	fmd_module_rele(dp->d_rmod);
573 	ASSERT(fmd_list_next(&dp->d_mod_list) == NULL);
574 
575 	/*
576 	 * Now destroy the remaining global data structures.  If 'core' was
577 	 * set to true, force a core dump so we can check for memory leaks.
578 	 */
579 	if (dp->d_cases != NULL)
580 		fmd_case_hash_destroy(dp->d_cases);
581 	if (dp->d_disp != NULL)
582 		fmd_dispq_destroy(dp->d_disp);
583 	if (dp->d_timers != NULL)
584 		fmd_timerq_destroy(dp->d_timers);
585 	if (dp->d_schemes != NULL)
586 		fmd_scheme_hash_destroy(dp->d_schemes);
587 	if (dp->d_xprt_ids != NULL)
588 		fmd_idspace_destroy(dp->d_xprt_ids);
589 
590 	if (dp->d_errstats != NULL) {
591 		fmd_free(dp->d_errstats,
592 		    sizeof (fmd_stat_t) * (EFMD_END - EFMD_UNKNOWN));
593 	}
594 
595 	if (dp->d_conf != NULL)
596 		fmd_conf_close(dp->d_conf);
597 
598 	if (dp->d_topo != NULL)
599 		topo_close(dp->d_topo);
600 
601 	nvlist_free(dp->d_auth);
602 	(void) nv_alloc_fini(&dp->d_nva);
603 	dp->d_clockops->fto_fini(dp->d_clockptr);
604 
605 	(void) pthread_key_delete(dp->d_key);
606 	bzero(dp, sizeof (fmd_t));
607 
608 	if (core)
609 		fmd_panic("forcing core dump at user request\n");
610 }
611 
612 /*ARGSUSED*/
613 static void
614 fmd_gc(fmd_t *dp, id_t id, hrtime_t hrt)
615 {
616 	hrtime_t delta;
617 
618 	if (id != 0) {
619 		TRACE((FMD_DBG_MOD, "garbage collect start"));
620 		fmd_modhash_apply(dp->d_mod_hash, fmd_module_gc);
621 		TRACE((FMD_DBG_MOD, "garbage collect end"));
622 
623 		(void) pthread_rwlock_rdlock(&dp->d_log_lock);
624 		fmd_log_update(dp->d_errlog);
625 		(void) pthread_rwlock_unlock(&dp->d_log_lock);
626 	}
627 
628 	(void) fmd_conf_getprop(dp->d_conf, "gc_interval", &delta);
629 	(void) fmd_timerq_install(dp->d_timers, dp->d_rmod->mod_timerids,
630 	    (fmd_timer_f *)fmd_gc, dp, NULL, delta);
631 }
632 
633 /*
634  * Events are committed to the errlog after cases are checkpointed.  If fmd
635  * crashes before an event is ever associated with a module, this function will
636  * be called to replay it to all subscribers.  If fmd crashes in between the
637  * subscriber checkpointing and committing the event in the error log, the
638  * module will have seen the event and we don't want to replay it.  So we look
639  * for the event in all modules and transition it to the proper state.  If
640  * it is found, we commit it to the error log and do not replay it.  The in-
641  * memory case search used by fmd_module_contains() et al isn't particularly
642  * efficient, but it is faster than doing read i/o's on every case event to
643  * check their status or write i/o's on every event to replay to update states.
644  * We can improve the efficiency of this lookup algorithm later if necessary.
645  */
646 /*ARGSUSED*/
647 static void
648 fmd_err_replay(fmd_log_t *lp, fmd_event_t *ep, fmd_t *dp)
649 {
650 	fmd_module_t *mp;
651 	fmd_stat_t *sp;
652 
653 	(void) pthread_mutex_lock(&dp->d_mod_lock);
654 
655 	for (mp = fmd_list_next(&dp->d_mod_list);
656 	    mp != NULL; mp = fmd_list_next(mp)) {
657 		if (fmd_module_contains(mp, ep)) {
658 			fmd_module_hold(mp);
659 			break;
660 		}
661 	}
662 
663 	(void) pthread_mutex_unlock(&dp->d_mod_lock);
664 
665 	if (mp != NULL) {
666 		fmd_event_commit(ep);
667 		fmd_module_rele(mp);
668 		sp = &dp->d_stats->ds_log_partials;
669 	} else {
670 		fmd_dispq_dispatch(dp->d_disp, ep, FMD_EVENT_DATA(ep));
671 		sp = &dp->d_stats->ds_log_replayed;
672 	}
673 
674 	(void) pthread_mutex_lock(&dp->d_stats_lock);
675 	sp->fmds_value.ui64++;
676 	(void) pthread_mutex_unlock(&dp->d_stats_lock);
677 }
678 
679 void
680 fmd_door_server(void *dip)
681 {
682 	fmd_dprintf(FMD_DBG_XPRT, "door server starting for %p\n", dip);
683 	(void) pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
684 	(void) door_return(NULL, 0, NULL, 0);
685 }
686 
687 /*
688  * Custom door server create callback.  Any fmd services that use doors will
689  * require those threads to have their fmd-specific TSD initialized, etc.
690  */
691 static void
692 fmd_door(door_info_t *dip)
693 {
694 	if (fmd_thread_create(fmd.d_rmod, fmd_door_server, dip) == NULL)
695 		fmd_panic("failed to create server for door %p", (void *)dip);
696 }
697 
698 /*
699  * This signal handler is installed for the client.thrsig signal to be used to
700  * force an auxiliary thread to wake up from a system call and return EINTR in
701  * response to a module's use of fmd_thr_signal().  We also trace the event.
702  */
703 static void
704 fmd_signal(int sig)
705 {
706 	TRACE((FMD_DBG_MOD, "module thread received sig #%d", sig));
707 }
708 
709 void
710 fmd_run(fmd_t *dp, int pfd)
711 {
712 	char *nodc_key[] = { FMD_FLT_NODC, NULL };
713 	char nodc_str[128];
714 	struct sigaction act;
715 
716 	int status = FMD_EXIT_SUCCESS;
717 	const char *name;
718 	fmd_conf_path_t *pap;
719 	fmd_event_t *e;
720 	int dbout, err;
721 
722 	/*
723 	 * Cache all the current debug property settings in d_fmd_debug,
724 	 * d_fmd_dbout, d_hdl_debug, and d_hdl_dbout.  If a given debug mask
725 	 * is non-zero and the corresponding dbout mask is zero, set dbout
726 	 * to a sensible default value based on whether we have daemonized.
727 	 */
728 	(void) fmd_conf_getprop(dp->d_conf, "dbout", &dbout);
729 
730 	if (dp->d_fmd_debug != 0 && dbout == 0)
731 		dp->d_fmd_dbout = dp->d_fg? FMD_DBOUT_STDERR : FMD_DBOUT_SYSLOG;
732 	else
733 		dp->d_fmd_dbout = dbout;
734 
735 	(void) fmd_conf_getprop(dp->d_conf, "client.debug", &dp->d_hdl_debug);
736 	(void) fmd_conf_getprop(dp->d_conf, "client.dbout", &dbout);
737 
738 	if (dp->d_hdl_debug != 0 && dbout == 0)
739 		dp->d_hdl_dbout = dp->d_fg? FMD_DBOUT_STDERR : FMD_DBOUT_SYSLOG;
740 	else
741 		dp->d_hdl_dbout = dbout;
742 
743 	/*
744 	 * Initialize remaining major program data structures such as the
745 	 * clock, dispatch queues, log files, module hash collections, etc.
746 	 * This work is done here rather than in fmd_create() to permit the -o
747 	 * command-line option to modify properties after fmd_create() is done.
748 	 */
749 	name = dp->d_rootdir != NULL &&
750 	    *dp->d_rootdir != '\0' ? dp->d_rootdir : NULL;
751 
752 	if ((dp->d_topo = topo_open(TOPO_VERSION, name, &err)) == NULL) {
753 		fmd_error(EFMD_EXIT, "failed to initialize "
754 		    "topology library: %s\n", topo_strerror(err));
755 	}
756 
757 	dp->d_clockptr = dp->d_clockops->fto_init();
758 	dp->d_xprt_ids = fmd_idspace_create("xprt_ids", 1, INT_MAX);
759 	fmd_xprt_suspend_all();
760 
761 	(void) door_server_create(fmd_door);
762 	fmd_dr_init();
763 
764 	dp->d_rmod->mod_timerids = fmd_idspace_create(dp->d_pname, 1, 16);
765 	dp->d_timers = fmd_timerq_create();
766 	dp->d_disp = fmd_dispq_create();
767 	dp->d_cases = fmd_case_hash_create();
768 
769 	/*
770 	 * The root module's mod_queue is created with limit zero, making it
771 	 * act like /dev/null; anything inserted here is simply ignored.
772 	 */
773 	dp->d_rmod->mod_queue = fmd_eventq_create(dp->d_rmod,
774 	    &dp->d_rmod->mod_stats->ms_evqstat, &dp->d_rmod->mod_stats_lock, 0);
775 
776 	/*
777 	 * Once our subsystems that use signals have been set up, install the
778 	 * signal handler for the fmd_thr_signal() API.  Verify that the signal
779 	 * being used for this purpose doesn't conflict with something else.
780 	 */
781 	(void) fmd_conf_getprop(dp->d_conf, "client.thrsig", &dp->d_thr_sig);
782 
783 	if (sigaction(dp->d_thr_sig, NULL, &act) != 0) {
784 		fmd_error(EFMD_EXIT, "invalid signal selected for "
785 		    "client.thrsig property: %d\n", dp->d_thr_sig);
786 	}
787 
788 	if (act.sa_handler != SIG_IGN && act.sa_handler != SIG_DFL) {
789 		fmd_error(EFMD_EXIT, "signal selected for client.thrsig "
790 		    "property is already in use: %d\n", dp->d_thr_sig);
791 	}
792 
793 	act.sa_handler = fmd_signal;
794 	act.sa_flags = 0;
795 
796 	(void) sigemptyset(&act.sa_mask);
797 	(void) sigaction(dp->d_thr_sig, &act, NULL);
798 
799 	(void) fmd_conf_getprop(dp->d_conf, "schemedir", &name);
800 	dp->d_schemes = fmd_scheme_hash_create(dp->d_rootdir, name);
801 
802 	(void) fmd_conf_getprop(dp->d_conf, "log.rsrc", &name);
803 	dp->d_asrus = fmd_asru_hash_create(dp->d_rootdir, name);
804 
805 	(void) fmd_conf_getprop(dp->d_conf, "log.error", &name);
806 	dp->d_errlog = fmd_log_open(dp->d_rootdir, name, FMD_LOG_ERROR);
807 
808 	(void) fmd_conf_getprop(dp->d_conf, "log.fault", &name);
809 	dp->d_fltlog = fmd_log_open(dp->d_rootdir, name, FMD_LOG_FAULT);
810 
811 	if (dp->d_asrus == NULL || dp->d_errlog == NULL || dp->d_fltlog == NULL)
812 		fmd_error(EFMD_EXIT, "failed to initialize log files\n");
813 
814 	/*
815 	 * Before loading modules, create an empty control event which will act
816 	 * as a global barrier for module event processing.  Each module we
817 	 * load successfully will insert it at their head of their event queue,
818 	 * and then pause inside of fmd_ctl_rele() after dequeuing the event.
819 	 * This module barrier is required for two reasons:
820 	 *
821 	 * (a) During module loading, the restoration of case checkpoints may
822 	 *    result in a list.* event being recreated for which the intended
823 	 *    subscriber has not yet loaded depending on the load order. Such
824 	 *    events could then result in spurious "no subscriber" errors.
825 	 *
826 	 * (b) During errlog replay, a sequence of errors from a long time ago
827 	 *    may be replayed, and the module may attempt to install relative
828 	 *    timers associated with one or more of these events.  If errlog
829 	 *    replay were "racing" with active module threads, an event E1
830 	 *    that resulted in a relative timer T at time E1 + N nsec could
831 	 *    fire prior to an event E2 being enqueued, even if the relative
832 	 *    time ordering was E1 < E2 < E1 + N, causing mis-diagnosis.
833 	 */
834 	dp->d_mod_event = e = fmd_event_create(FMD_EVT_CTL,
835 	    FMD_HRT_NOW, NULL, fmd_ctl_init(NULL));
836 
837 	fmd_event_hold(e);
838 
839 	/*
840 	 * Once all data structures are initialized, we load all of our modules
841 	 * in order according to class in order to load up any subscriptions.
842 	 * Once built-in modules are loaded, we detach from our waiting parent.
843 	 */
844 	dp->d_mod_hash = fmd_modhash_create();
845 
846 	if (fmd_builtin_loadall(dp->d_mod_hash) != 0 && !dp->d_fg)
847 		fmd_error(EFMD_EXIT, "failed to initialize fault manager\n");
848 
849 	(void) fmd_conf_getprop(dp->d_conf, "self.name", &name);
850 	dp->d_self = fmd_modhash_lookup(dp->d_mod_hash, name);
851 
852 	if (dp->d_self != NULL && fmd_module_dc_key2code(dp->d_self,
853 	    nodc_key, nodc_str, sizeof (nodc_str)) == 0)
854 		(void) fmd_conf_setprop(dp->d_conf, "nodiagcode", nodc_str);
855 
856 	fmd_rpc_init();
857 	dp->d_running = 1; /* we are now officially an active fmd */
858 
859 	/*
860 	 * Now that we're running, if a pipe fd was specified, write an exit
861 	 * status to it to indicate that our parent process can safely detach.
862 	 * Then proceed to loading the remaining non-built-in modules.
863 	 */
864 	if (pfd >= 0)
865 		(void) write(pfd, &status, sizeof (status));
866 
867 	(void) fmd_conf_getprop(dp->d_conf, "plugin.path", &pap);
868 	fmd_modhash_loadall(dp->d_mod_hash, pap, &fmd_rtld_ops, ".so");
869 
870 	(void) fmd_conf_getprop(dp->d_conf, "agent.path", &pap);
871 	fmd_modhash_loadall(dp->d_mod_hash, pap, &fmd_proc_ops, NULL);
872 
873 	/*
874 	 * With all modules loaded, replay fault events from the ASRU cache for
875 	 * any ASRUs that must be retired, replay error events from the errlog
876 	 * that did not finish processing the last time ran, and then release
877 	 * the global module barrier by executing a final rele on d_mod_event.
878 	 */
879 	fmd_asru_hash_refresh(dp->d_asrus);
880 
881 	(void) pthread_rwlock_rdlock(&dp->d_log_lock);
882 	fmd_log_replay(dp->d_errlog, (fmd_log_f *)fmd_err_replay, dp);
883 	fmd_log_update(dp->d_errlog);
884 	(void) pthread_rwlock_unlock(&dp->d_log_lock);
885 
886 	dp->d_mod_event = NULL;
887 	fmd_event_rele(e);
888 
889 	/*
890 	 * Finally, awaken any threads associated with receiving events from
891 	 * open transports and tell them to proceed with fmd_xprt_recv().
892 	 */
893 	fmd_xprt_resume_all();
894 	fmd_gc(dp, 0, 0);
895 
896 	dp->d_booted = 1;
897 }
898 
899 void
900 fmd_help(fmd_t *dp)
901 {
902 	const fmd_conf_mode_t *cmp;
903 
904 	(void) printf("Usage: %s -o debug=mode[,mode]\n", dp->d_pname);
905 
906 	for (cmp = _fmd_debug_modes; cmp->cm_name != NULL; cmp++)
907 		(void) printf("\t%s\t%s\n", cmp->cm_name, cmp->cm_desc);
908 }
909