xref: /illumos-gate/usr/src/cmd/fm/fmd/common/fmd_api.c (revision 567cc2e6a4ceb0e421e1cf9bead0f43c55603d27)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/fm/protocol.h>
31 
32 #include <unistd.h>
33 #include <signal.h>
34 #include <limits.h>
35 #include <syslog.h>
36 #include <alloca.h>
37 #include <stddef.h>
38 #include <search.h>
39 
40 #include <fmd_module.h>
41 #include <fmd_api.h>
42 #include <fmd_string.h>
43 #include <fmd_subr.h>
44 #include <fmd_error.h>
45 #include <fmd_event.h>
46 #include <fmd_eventq.h>
47 #include <fmd_dispq.h>
48 #include <fmd_timerq.h>
49 #include <fmd_thread.h>
50 #include <fmd_ustat.h>
51 #include <fmd_case.h>
52 #include <fmd_protocol.h>
53 #include <fmd_buf.h>
54 #include <fmd_asru.h>
55 #include <fmd_fmri.h>
56 #include <fmd_topo.h>
57 #include <fmd_ckpt.h>
58 #include <fmd_xprt.h>
59 
60 #include <fmd.h>
61 
62 /*
63  * Table of configuration file variable types ops-vector pointers.  We use this
64  * to convert from the property description array specified by the module to an
65  * array of fmd_conf_formal_t's.  The order of this array must match the order
66  * of #define values specified in <fmd_api.h> (i.e. FMD_TYPE_BOOL must be 0).
67  * For now, the fmd_conf_list and fmd_conf_path types are not supported as we
68  * do not believe modules need them and they would require more complexity.
69  */
70 static const fmd_conf_ops_t *const _fmd_prop_ops[] = {
71 	&fmd_conf_bool,		/* FMD_TYPE_BOOL */
72 	&fmd_conf_int32,	/* FMD_TYPE_INT32 */
73 	&fmd_conf_uint32,	/* FMD_TYPE_UINT32 */
74 	&fmd_conf_int64,	/* FMD_TYPE_INT64 */
75 	&fmd_conf_uint64,	/* FMD_TYPE_UINT64 */
76 	&fmd_conf_string,	/* FMD_TYPE_STRING */
77 	&fmd_conf_time,		/* FMD_TYPE_TIME */
78 	&fmd_conf_size,		/* FMD_TYPE_SIZE */
79 };
80 
81 static void fmd_api_verror(fmd_module_t *, int, const char *, va_list)
82     __NORETURN;
83 static void fmd_api_error(fmd_module_t *, int, const char *, ...) __NORETURN;
84 
85 /*
86  * fmd_api_vxerror() provides the engine underlying the fmd_hdl_[v]error() API
87  * calls and the fmd_api_[v]error() utility routine defined below.  The routine
88  * formats the error, optionally associated with a particular errno code 'err',
89  * and logs it as an ereport associated with the calling module.  Depending on
90  * other optional properties, we also emit a message to stderr and to syslog.
91  */
92 static void
93 fmd_api_vxerror(fmd_module_t *mp, int err, const char *format, va_list ap)
94 {
95 	int raw_err = err;
96 	nvlist_t *nvl;
97 	fmd_event_t *e;
98 	char *class, *msg;
99 	size_t len1, len2;
100 	char c;
101 
102 	/*
103 	 * fmd_api_vxerror() counts as both an error of class EFMD_MODULE
104 	 * as well as an instance of 'err' w.r.t. our internal bean counters.
105 	 */
106 	(void) pthread_mutex_lock(&fmd.d_err_lock);
107 	fmd.d_errstats[EFMD_MODULE - EFMD_UNKNOWN].fmds_value.ui64++;
108 
109 	if (err > EFMD_UNKNOWN && err < EFMD_END)
110 		fmd.d_errstats[err - EFMD_UNKNOWN].fmds_value.ui64++;
111 
112 	(void) pthread_mutex_unlock(&fmd.d_err_lock);
113 
114 	/*
115 	 * Format the message using vsnprintf().  As usual, if the format has a
116 	 * newline in it, it is printed alone; otherwise strerror() is added.
117 	 */
118 	if (strchr(format, '\n') != NULL)
119 		err = 0; /* err is not relevant in the message */
120 
121 	len1 = vsnprintf(&c, 1, format, ap);
122 	len2 = err != 0 ? snprintf(&c, 1, ": %s\n", fmd_strerror(err)) : 0;
123 
124 	msg = fmd_alloc(len1 + len2 + 1, FMD_SLEEP);
125 	(void) vsnprintf(msg, len1 + 1, format, ap);
126 
127 	if (err != 0) {
128 		(void) snprintf(&msg[len1], len2 + 1,
129 		    ": %s\n", fmd_strerror(err));
130 	}
131 
132 	/*
133 	 * Create an error event corresponding to the error, insert it into the
134 	 * error log, and dispatch it to the fmd-self-diagnosis engine.
135 	 */
136 	if (mp != fmd.d_self && (raw_err != EFMD_HDL_ABORT || fmd.d_running)) {
137 		if ((c = msg[len1 + len2 - 1]) == '\n')
138 			msg[len1 + len2 - 1] = '\0'; /* strip \n for event */
139 
140 		nvl = fmd_protocol_moderror(mp, err, msg);
141 
142 		if (c == '\n')
143 			msg[len1 + len2 - 1] = c;
144 
145 		(void) nvlist_lookup_string(nvl, FM_CLASS, &class);
146 		e = fmd_event_create(FMD_EVT_PROTOCOL, FMD_HRT_NOW, nvl, class);
147 
148 		(void) pthread_rwlock_rdlock(&fmd.d_log_lock);
149 		fmd_log_append(fmd.d_errlog, e, NULL);
150 		(void) pthread_rwlock_unlock(&fmd.d_log_lock);
151 
152 		fmd_event_transition(e, FMD_EVS_ACCEPTED);
153 		fmd_event_commit(e);
154 
155 		fmd_dispq_dispatch(fmd.d_disp, e, class);
156 	}
157 
158 	/*
159 	 * Similar to fmd_vdebug(), if the debugging switches are enabled we
160 	 * echo the module name and message to stderr and/or syslog.  Unlike
161 	 * fmd_vdebug(), we also print to stderr if foreground mode is enabled.
162 	 * We also print the message if a built-in module is aborting before
163 	 * fmd has detached from its parent (e.g. default transport failure).
164 	 */
165 	if (fmd.d_fg || (fmd.d_hdl_dbout & FMD_DBOUT_STDERR) || (
166 	    raw_err == EFMD_HDL_ABORT && !fmd.d_running)) {
167 		(void) pthread_mutex_lock(&fmd.d_err_lock);
168 		(void) fprintf(stderr, "%s: %s: %s",
169 		    fmd.d_pname, mp->mod_name, msg);
170 		(void) pthread_mutex_unlock(&fmd.d_err_lock);
171 	}
172 
173 	if (fmd.d_hdl_dbout & FMD_DBOUT_SYSLOG) {
174 		syslog(LOG_ERR | LOG_DAEMON, "%s ERROR: %s: %s",
175 		    fmd.d_pname, mp->mod_name, msg);
176 	}
177 
178 	fmd_free(msg, len1 + len2 + 1);
179 }
180 
181 /*PRINTFLIKE3*/
182 static void
183 fmd_api_xerror(fmd_module_t *mp, int err, const char *format, ...)
184 {
185 	va_list ap;
186 
187 	va_start(ap, format);
188 	fmd_api_vxerror(mp, err, format, ap);
189 	va_end(ap);
190 }
191 
192 /*
193  * fmd_api_verror() is a wrapper around fmd_api_vxerror() for API subroutines.
194  * It calls fmd_module_unlock() on behalf of its caller, logs the error, and
195  * then aborts the API call and the surrounding module entry point by doing an
196  * fmd_module_abort(), which longjmps to the place where we entered the module.
197  */
198 static void
199 fmd_api_verror(fmd_module_t *mp, int err, const char *format, va_list ap)
200 {
201 	if (fmd_module_locked(mp))
202 		fmd_module_unlock(mp);
203 
204 	fmd_api_vxerror(mp, err, format, ap);
205 	fmd_module_abort(mp, err);
206 }
207 
208 /*PRINTFLIKE3*/
209 static void
210 fmd_api_error(fmd_module_t *mp, int err, const char *format, ...)
211 {
212 	va_list ap;
213 
214 	va_start(ap, format);
215 	fmd_api_verror(mp, err, format, ap);
216 	va_end(ap);
217 }
218 
219 /*
220  * Common code for fmd_api_module_lock() and fmd_api_transport_impl().  This
221  * code verifies that the handle is valid and associated with a proper thread.
222  */
223 static fmd_module_t *
224 fmd_api_module(fmd_hdl_t *hdl)
225 {
226 	fmd_thread_t *tp;
227 	fmd_module_t *mp;
228 
229 	/*
230 	 * If our TSD is not present at all, this is either a serious bug or
231 	 * someone has created a thread behind our back and is using fmd's API.
232 	 * We can't call fmd_api_error() because we can't be sure that we can
233 	 * unwind our state back to an enclosing fmd_module_dispatch(), so we
234 	 * must panic instead.  This is likely a module design or coding error.
235 	 */
236 	if ((tp = pthread_getspecific(fmd.d_key)) == NULL) {
237 		fmd_panic("fmd module api call made using "
238 		    "client handle %p from unknown thread\n", (void *)hdl);
239 	}
240 
241 	/*
242 	 * If our TSD refers to the root module and is a door server thread,
243 	 * then it was created asynchronously at the request of a module but
244 	 * is using now the module API as an auxiliary module thread.  We reset
245 	 * tp->thr_mod to the module handle so it can act as a module thread.
246 	 */
247 	if (tp->thr_mod == fmd.d_rmod && tp->thr_func == &fmd_door_server)
248 		tp->thr_mod = (fmd_module_t *)hdl;
249 
250 	if ((mp = tp->thr_mod) != (fmd_module_t *)hdl) {
251 		fmd_api_error(mp, EFMD_HDL_INVAL,
252 		    "client handle %p is not valid\n", (void *)hdl);
253 	}
254 
255 	if (mp->mod_flags & FMD_MOD_FAIL) {
256 		fmd_api_error(mp, EFMD_MOD_FAIL,
257 		    "module has experienced an unrecoverable error\n");
258 	}
259 
260 	return (mp);
261 }
262 
263 /*
264  * fmd_api_module_lock() is used as a wrapper around fmd_module_lock() and a
265  * common prologue to each fmd_api.c routine.  It verifies that the handle is
266  * valid and owned by the current server thread, locks the handle, and then
267  * verifies that the caller is performing an operation on a registered handle.
268  * If any tests fail, the entire API call is aborted by fmd_api_error().
269  */
270 static fmd_module_t *
271 fmd_api_module_lock(fmd_hdl_t *hdl)
272 {
273 	fmd_module_t *mp = fmd_api_module(hdl);
274 
275 	fmd_module_lock(mp);
276 
277 	if (mp->mod_info == NULL) {
278 		fmd_api_error(mp, EFMD_HDL_NOTREG,
279 		    "client handle %p has not been registered\n", (void *)hdl);
280 	}
281 
282 	return (mp);
283 }
284 
285 /*
286  * Utility function for API entry points that accept fmd_case_t's.  We cast cp
287  * to fmd_case_impl_t and check to make sure the case is owned by the caller.
288  */
289 static fmd_case_impl_t *
290 fmd_api_case_impl(fmd_module_t *mp, fmd_case_t *cp)
291 {
292 	fmd_case_impl_t *cip = (fmd_case_impl_t *)cp;
293 
294 	if (cip == NULL || cip->ci_mod != mp) {
295 		fmd_api_error(mp, EFMD_CASE_OWNER,
296 		    "case %p is invalid or not owned by caller\n", (void *)cip);
297 	}
298 
299 	return (cip);
300 }
301 
302 /*
303  * Utility function for API entry points that accept fmd_xprt_t's.  We cast xp
304  * to fmd_transport_t and check to make sure the case is owned by the caller.
305  * Note that we could make this check safer by actually walking mp's transport
306  * list, but that requires holding the module lock and this routine needs to be
307  * MT-hot w.r.t. auxiliary module threads.  Ultimately any loadable module can
308  * cause us to crash anyway, so we optimize for scalability over safety here.
309  */
310 static fmd_xprt_impl_t *
311 fmd_api_transport_impl(fmd_hdl_t *hdl, fmd_xprt_t *xp)
312 {
313 	fmd_module_t *mp = fmd_api_module(hdl);
314 	fmd_xprt_impl_t *xip = (fmd_xprt_impl_t *)xp;
315 
316 	if (xip == NULL || xip->xi_queue->eq_mod != mp) {
317 		fmd_api_error(mp, EFMD_XPRT_OWNER,
318 		    "xprt %p is invalid or not owned by caller\n", (void *)xp);
319 	}
320 
321 	return (xip);
322 }
323 
324 /*
325  * fmd_hdl_register() is the one function which cannot use fmd_api_error() to
326  * report errors, because that routine causes the module to abort.  Failure to
327  * register is instead handled by having fmd_hdl_register() return an error to
328  * the _fmd_init() function and then detecting no registration when it returns.
329  * So we use this routine for fmd_hdl_register() error paths instead.
330  */
331 static int
332 fmd_hdl_register_error(fmd_module_t *mp, int err)
333 {
334 	if (fmd_module_locked(mp))
335 		fmd_module_unlock(mp);
336 
337 	fmd_api_xerror(mp, err, "failed to register");
338 	return (fmd_set_errno(err));
339 }
340 
341 static void
342 fmd_hdl_nop(void)
343 {
344 	/* empty function for use with unspecified module entry points */
345 }
346 
347 int
348 fmd_hdl_register(fmd_hdl_t *hdl, int version, const fmd_hdl_info_t *mip)
349 {
350 	fmd_thread_t *tp = pthread_getspecific(fmd.d_key);
351 	fmd_module_t *mp = tp->thr_mod;
352 
353 	const fmd_prop_t *prop;
354 	const fmd_conf_path_t *pap;
355 	fmd_conf_formal_t *cfp;
356 	fmd_hdl_ops_t ops;
357 
358 	const char *conf = NULL;
359 	char buf[PATH_MAX];
360 	int i;
361 
362 	if (mp != (fmd_module_t *)hdl)
363 		return (fmd_hdl_register_error(mp, EFMD_HDL_INVAL));
364 
365 	fmd_module_lock(mp);
366 
367 	/*
368 	 * First perform some sanity checks on our input.  The API version must
369 	 * be supported by FMD and the handle can only be registered once by
370 	 * the module thread to which we assigned this client handle.  The info
371 	 * provided for the handle must be valid and have the minimal settings.
372 	 */
373 	if (version > FMD_API_VERSION_4)
374 		return (fmd_hdl_register_error(mp, EFMD_VER_NEW));
375 
376 	if (version < FMD_API_VERSION_1)
377 		return (fmd_hdl_register_error(mp, EFMD_VER_OLD));
378 
379 	if (mp->mod_conf != NULL)
380 		return (fmd_hdl_register_error(mp, EFMD_HDL_REG));
381 
382 	if (pthread_self() != mp->mod_thread->thr_tid)
383 		return (fmd_hdl_register_error(mp, EFMD_HDL_TID));
384 
385 	if (mip == NULL || mip->fmdi_desc == NULL ||
386 	    mip->fmdi_vers == NULL || mip->fmdi_ops == NULL)
387 		return (fmd_hdl_register_error(mp, EFMD_HDL_INFO));
388 
389 	/*
390 	 * Copy the module's ops vector into a local variable to account for
391 	 * changes in the module ABI.  Then if any of the optional entry points
392 	 * are NULL, set them to nop so we don't have to check before calling.
393 	 */
394 	bzero(&ops, sizeof (ops));
395 
396 	if (version < FMD_API_VERSION_3)
397 		bcopy(mip->fmdi_ops, &ops, offsetof(fmd_hdl_ops_t, fmdo_send));
398 	else if (version < FMD_API_VERSION_4)
399 		bcopy(mip->fmdi_ops, &ops,
400 		    offsetof(fmd_hdl_ops_t, fmdo_topo));
401 	else
402 		bcopy(mip->fmdi_ops, &ops, sizeof (ops));
403 
404 	if (ops.fmdo_recv == NULL)
405 		ops.fmdo_recv = (void (*)())fmd_hdl_nop;
406 	if (ops.fmdo_timeout == NULL)
407 		ops.fmdo_timeout = (void (*)())fmd_hdl_nop;
408 	if (ops.fmdo_close == NULL)
409 		ops.fmdo_close = (void (*)())fmd_hdl_nop;
410 	if (ops.fmdo_stats == NULL)
411 		ops.fmdo_stats = (void (*)())fmd_hdl_nop;
412 	if (ops.fmdo_gc == NULL)
413 		ops.fmdo_gc = (void (*)())fmd_hdl_nop;
414 	if (ops.fmdo_send == NULL)
415 		ops.fmdo_send = (int (*)())fmd_hdl_nop;
416 	if (ops.fmdo_topo == NULL)
417 		ops.fmdo_topo = (void (*)())fmd_hdl_nop;
418 
419 	/*
420 	 * Make two passes through the property array to initialize the formals
421 	 * to use for processing the module's .conf file.  In the first pass,
422 	 * we validate the types and count the number of properties.  In the
423 	 * second pass we copy the strings and fill in the appropriate ops.
424 	 */
425 	for (prop = mip->fmdi_props, i = 0; prop != NULL &&
426 	    prop->fmdp_name != NULL; prop++, i++) {
427 		if (prop->fmdp_type >=
428 		    sizeof (_fmd_prop_ops) / sizeof (_fmd_prop_ops[0])) {
429 			fmd_api_xerror(mp, EFMD_HDL_PROP,
430 			    "property %s uses invalid type %u\n",
431 			    prop->fmdp_name, prop->fmdp_type);
432 			return (fmd_hdl_register_error(mp, EFMD_HDL_PROP));
433 		}
434 	}
435 
436 	mp->mod_argc = i;
437 	mp->mod_argv = fmd_zalloc(sizeof (fmd_conf_formal_t) * i, FMD_SLEEP);
438 
439 	prop = mip->fmdi_props;
440 	cfp = mp->mod_argv;
441 
442 	for (i = 0; i < mp->mod_argc; i++, prop++, cfp++) {
443 		cfp->cf_name = fmd_strdup(prop->fmdp_name, FMD_SLEEP);
444 		cfp->cf_ops = _fmd_prop_ops[prop->fmdp_type];
445 		cfp->cf_default = fmd_strdup(prop->fmdp_defv, FMD_SLEEP);
446 	}
447 
448 	/*
449 	 * If this module came from an on-disk file, compute the name of the
450 	 * corresponding .conf file and parse properties from it if it exists.
451 	 */
452 	if (mp->mod_path != NULL) {
453 		(void) strlcpy(buf, mp->mod_path, sizeof (buf));
454 		(void) fmd_strdirname(buf);
455 
456 		(void) strlcat(buf, "/", sizeof (buf));
457 		(void) strlcat(buf, mp->mod_name, sizeof (buf));
458 		(void) strlcat(buf, ".conf", sizeof (buf));
459 
460 		if (access(buf, F_OK) == 0)
461 			conf = buf;
462 	}
463 
464 	if ((mp->mod_conf = fmd_conf_open(conf,
465 	    mp->mod_argc, mp->mod_argv, 0)) == NULL)
466 		return (fmd_hdl_register_error(mp, EFMD_MOD_CONF));
467 
468 	fmd_conf_propagate(fmd.d_conf, mp->mod_conf, mp->mod_name);
469 
470 	/*
471 	 * Look up the list of the libdiagcode dictionaries associated with the
472 	 * module.  If none were specified, use the value from daemon's config.
473 	 * We only fail if the module specified an explicit dictionary.
474 	 */
475 	(void) fmd_conf_getprop(mp->mod_conf, FMD_PROP_DICTIONARIES, &pap);
476 	if (pap->cpa_argc == 0 && mp->mod_ops == &fmd_bltin_ops)
477 		(void) fmd_conf_getprop(fmd.d_conf, "self.dict", &pap);
478 
479 	for (i = 0; i < pap->cpa_argc; i++) {
480 		if (fmd_module_dc_opendict(mp, pap->cpa_argv[i]) != 0) {
481 			fmd_api_xerror(mp, errno,
482 			    "failed to open dictionary %s", pap->cpa_argv[i]);
483 			return (fmd_hdl_register_error(mp, EFMD_MOD_CONF));
484 		}
485 	}
486 
487 	/*
488 	 * Make a copy of the handle information and store it in mod_info.  We
489 	 * do not need to bother copying fmdi_props since they're already read.
490 	 */
491 	mp->mod_info = fmd_alloc(sizeof (fmd_hdl_info_t), FMD_SLEEP);
492 	mp->mod_info->fmdi_desc = fmd_strdup(mip->fmdi_desc, FMD_SLEEP);
493 	mp->mod_info->fmdi_vers = fmd_strdup(mip->fmdi_vers, FMD_SLEEP);
494 	mp->mod_info->fmdi_ops = fmd_alloc(sizeof (fmd_hdl_ops_t), FMD_SLEEP);
495 	bcopy(&ops, (void *)mp->mod_info->fmdi_ops, sizeof (fmd_hdl_ops_t));
496 	mp->mod_info->fmdi_props = NULL;
497 
498 	/*
499 	 * Allocate an FMRI representing this module.  We'll use this later
500 	 * if the module decides to publish any events (e.g. list.suspects).
501 	 */
502 	mp->mod_fmri = fmd_protocol_fmri_module(mp);
503 
504 	/*
505 	 * Any subscriptions specified in the conf file are now stored in the
506 	 * corresponding property.  Add all of these to the dispatch queue.
507 	 */
508 	(void) fmd_conf_getprop(mp->mod_conf, FMD_PROP_SUBSCRIPTIONS, &pap);
509 
510 	for (i = 0; i < pap->cpa_argc; i++) {
511 		fmd_dispq_insert(fmd.d_disp, mp->mod_queue, pap->cpa_argv[i]);
512 		fmd_xprt_subscribe_all(pap->cpa_argv[i]);
513 	}
514 
515 	/*
516 	 * Unlock the module and restore any pre-existing module checkpoint.
517 	 * If the checkpoint is missing or corrupt, we just keep going.
518 	 */
519 	fmd_module_unlock(mp);
520 	fmd_ckpt_restore(mp);
521 	return (0);
522 }
523 
524 /*
525  * If an auxiliary thread exists for the specified module at unregistration
526  * time, send it an asynchronous cancellation to force it to exit and then
527  * join with it (we expect this to either succeed quickly or return ESRCH).
528  * Once this is complete we can destroy the associated fmd_thread_t data.
529  */
530 static void
531 fmd_module_thrcancel(fmd_idspace_t *ids, id_t id, fmd_module_t *mp)
532 {
533 	fmd_thread_t *tp = fmd_idspace_getspecific(ids, id);
534 
535 	fmd_dprintf(FMD_DBG_MOD, "cancelling %s auxiliary thread %u\n",
536 	    mp->mod_name, tp->thr_tid);
537 
538 	ASSERT(tp->thr_tid == id);
539 	(void) pthread_cancel(tp->thr_tid);
540 	(void) pthread_join(tp->thr_tid, NULL);
541 
542 	fmd_thread_destroy(tp, FMD_THREAD_NOJOIN);
543 }
544 
545 void
546 fmd_module_unregister(fmd_module_t *mp)
547 {
548 	fmd_conf_formal_t *cfp = mp->mod_argv;
549 	const fmd_conf_path_t *pap;
550 	fmd_case_t *cp;
551 	fmd_xprt_t *xp;
552 	int i;
553 
554 	TRACE((FMD_DBG_MOD, "unregister %p (%s)", (void *)mp, mp->mod_name));
555 	ASSERT(fmd_module_locked(mp));
556 
557 	/*
558 	 * If any transports are still open, they have send threads that are
559 	 * using the module handle: shut them down and join with these threads.
560 	 */
561 	while ((xp = fmd_list_next(&mp->mod_transports)) != NULL)
562 		fmd_xprt_destroy(xp);
563 
564 	/*
565 	 * If any auxiliary threads exist, they may be using our module handle,
566 	 * and therefore could cause a fault as soon as we start destroying it.
567 	 * Module writers should clean up any threads before unregistering: we
568 	 * forcibly cancel any remaining auxiliary threads before proceeding.
569 	 */
570 	fmd_idspace_apply(mp->mod_threads,
571 	    (void (*)())fmd_module_thrcancel, mp);
572 
573 	if (mp->mod_error == 0)
574 		fmd_ckpt_save(mp); /* take one more checkpoint if needed */
575 
576 	/*
577 	 * Delete any cases associated with the module (UNSOLVED, SOLVED, or
578 	 * CLOSE_WAIT) as if fmdo_close() has finished processing them.
579 	 */
580 	while ((cp = fmd_list_next(&mp->mod_cases)) != NULL)
581 		fmd_case_delete(cp);
582 
583 	fmd_ustat_delete_references(mp->mod_ustat);
584 	(void) fmd_conf_getprop(mp->mod_conf, FMD_PROP_SUBSCRIPTIONS, &pap);
585 
586 	for (i = 0; i < pap->cpa_argc; i++) {
587 		fmd_xprt_unsubscribe_all(pap->cpa_argv[i]);
588 		fmd_dispq_delete(fmd.d_disp, mp->mod_queue, pap->cpa_argv[i]);
589 	}
590 
591 	fmd_conf_close(mp->mod_conf);
592 	mp->mod_conf = NULL;
593 
594 	for (i = 0; i < mp->mod_argc; i++, cfp++) {
595 		fmd_strfree((char *)cfp->cf_name);
596 		fmd_strfree((char *)cfp->cf_default);
597 	}
598 
599 	fmd_free(mp->mod_argv, sizeof (fmd_conf_formal_t) * mp->mod_argc);
600 	mp->mod_argv = NULL;
601 	mp->mod_argc = 0;
602 
603 	nvlist_free(mp->mod_fmri);
604 	mp->mod_fmri = NULL;
605 
606 	fmd_strfree((char *)mp->mod_info->fmdi_desc);
607 	fmd_strfree((char *)mp->mod_info->fmdi_vers);
608 	fmd_free((void *)mp->mod_info->fmdi_ops, sizeof (fmd_hdl_ops_t));
609 	fmd_free(mp->mod_info, sizeof (fmd_hdl_info_t));
610 	mp->mod_info = NULL;
611 
612 	fmd_eventq_abort(mp->mod_queue);
613 }
614 
615 void
616 fmd_hdl_unregister(fmd_hdl_t *hdl)
617 {
618 	fmd_module_t *mp = fmd_api_module_lock(hdl);
619 	fmd_module_unregister(mp);
620 	fmd_module_unlock(mp);
621 }
622 
623 void
624 fmd_hdl_subscribe(fmd_hdl_t *hdl, const char *class)
625 {
626 	fmd_module_t *mp = fmd_api_module_lock(hdl);
627 
628 	if (fmd_conf_setprop(mp->mod_conf,
629 	    FMD_PROP_SUBSCRIPTIONS, class) == 0) {
630 		fmd_dispq_insert(fmd.d_disp, mp->mod_queue, class);
631 		fmd_xprt_subscribe_all(class);
632 	}
633 
634 	fmd_module_unlock(mp);
635 }
636 
637 
638 void
639 fmd_hdl_unsubscribe(fmd_hdl_t *hdl, const char *class)
640 {
641 	fmd_module_t *mp = fmd_api_module_lock(hdl);
642 
643 	if (fmd_conf_delprop(mp->mod_conf,
644 	    FMD_PROP_SUBSCRIPTIONS, class) == 0) {
645 		fmd_xprt_unsubscribe_all(class);
646 		fmd_dispq_delete(fmd.d_disp, mp->mod_queue, class);
647 	}
648 
649 	fmd_module_unlock(mp);
650 	fmd_eventq_cancel(mp->mod_queue, FMD_EVT_PROTOCOL, (void *)class);
651 }
652 
653 void
654 fmd_hdl_setspecific(fmd_hdl_t *hdl, void *spec)
655 {
656 	fmd_module_t *mp = fmd_api_module_lock(hdl);
657 
658 	mp->mod_spec = spec;
659 	fmd_module_unlock(mp);
660 }
661 
662 void *
663 fmd_hdl_getspecific(fmd_hdl_t *hdl)
664 {
665 	fmd_module_t *mp = fmd_api_module_lock(hdl);
666 	void *spec = mp->mod_spec;
667 
668 	fmd_module_unlock(mp);
669 	return (spec);
670 }
671 
672 void
673 fmd_hdl_opendict(fmd_hdl_t *hdl, const char *dict)
674 {
675 	fmd_module_t *mp = fmd_api_module_lock(hdl);
676 	const fmd_conf_path_t *pap;
677 	int i;
678 
679 	/*
680 	 * Update the dictionary property in order to preserve the list of
681 	 * pathnames and expand any % tokens in the path.  Then retrieve the
682 	 * new dictionary names from cpa_argv[] and open them one at a time.
683 	 */
684 	(void) fmd_conf_setprop(mp->mod_conf, FMD_PROP_DICTIONARIES, dict);
685 	(void) fmd_conf_getprop(mp->mod_conf, FMD_PROP_DICTIONARIES, &pap);
686 
687 	ASSERT(pap->cpa_argc > mp->mod_dictc);
688 
689 	for (i = mp->mod_dictc; i < pap->cpa_argc; i++) {
690 		if (fmd_module_dc_opendict(mp, pap->cpa_argv[i]) != 0) {
691 			fmd_api_error(mp, EFMD_MOD_DICT,
692 			    "failed to open dictionary %s for module %s",
693 			    pap->cpa_argv[i], mp->mod_name);
694 		}
695 	}
696 
697 	fmd_module_unlock(mp);
698 }
699 
700 topo_hdl_t *
701 fmd_hdl_topo_hold(fmd_hdl_t *hdl, int v)
702 {
703 	fmd_module_t *mp = fmd_api_module_lock(hdl);
704 	topo_hdl_t *thp;
705 
706 	if (v != TOPO_VERSION) {
707 		fmd_api_error(mp, EFMD_MOD_TOPO, "libtopo version mismatch: "
708 		    "fmd version %d != client version %d\n", TOPO_VERSION, v);
709 	}
710 
711 	thp = fmd_module_topo_hold(mp);
712 	ASSERT(thp != NULL);
713 
714 	fmd_module_unlock(mp);
715 	return (thp);
716 }
717 
718 void
719 fmd_hdl_topo_rele(fmd_hdl_t *hdl, topo_hdl_t *thp)
720 {
721 	fmd_module_t *mp = fmd_api_module_lock(hdl);
722 
723 	if (fmd_module_topo_rele(mp, thp) != 0)
724 		fmd_api_error(mp, EFMD_MOD_TOPO, "failed to release invalid "
725 		    "topo handle: %p\n", (void *)thp);
726 
727 	fmd_module_unlock(mp);
728 }
729 
730 void *
731 fmd_hdl_alloc(fmd_hdl_t *hdl, size_t size, int flags)
732 {
733 	fmd_module_t *mp = fmd_api_module_lock(hdl);
734 	void *data;
735 
736 	if (mp->mod_stats->ms_memlimit.fmds_value.ui64 -
737 	    mp->mod_stats->ms_memtotal.fmds_value.ui64 < size) {
738 		fmd_api_error(mp, EFMD_HDL_NOMEM, "%s's allocation of %lu "
739 		    "bytes exceeds module memory limit (%llu)\n",
740 		    mp->mod_name, (ulong_t)size, (u_longlong_t)
741 		    mp->mod_stats->ms_memtotal.fmds_value.ui64);
742 	}
743 
744 	if ((data = fmd_alloc(size, flags)) != NULL)
745 		mp->mod_stats->ms_memtotal.fmds_value.ui64 += size;
746 
747 	fmd_module_unlock(mp);
748 	return (data);
749 }
750 
751 void *
752 fmd_hdl_zalloc(fmd_hdl_t *hdl, size_t size, int flags)
753 {
754 	void *data = fmd_hdl_alloc(hdl, size, flags);
755 
756 	if (data != NULL)
757 		bzero(data, size);
758 
759 	return (data);
760 }
761 
762 void
763 fmd_hdl_free(fmd_hdl_t *hdl, void *data, size_t size)
764 {
765 	fmd_module_t *mp = fmd_api_module_lock(hdl);
766 
767 	fmd_free(data, size);
768 	mp->mod_stats->ms_memtotal.fmds_value.ui64 -= size;
769 
770 	fmd_module_unlock(mp);
771 }
772 
773 char *
774 fmd_hdl_strdup(fmd_hdl_t *hdl, const char *s, int flags)
775 {
776 	char *p;
777 
778 	if (s != NULL)
779 		p = fmd_hdl_alloc(hdl, strlen(s) + 1, flags);
780 	else
781 		p = NULL;
782 
783 	if (p != NULL)
784 		(void) strcpy(p, s);
785 
786 	return (p);
787 }
788 
789 void
790 fmd_hdl_strfree(fmd_hdl_t *hdl, char *s)
791 {
792 	if (s != NULL)
793 		fmd_hdl_free(hdl, s, strlen(s) + 1);
794 }
795 
796 void
797 fmd_hdl_vabort(fmd_hdl_t *hdl, const char *format, va_list ap)
798 {
799 	fmd_api_verror(fmd_api_module_lock(hdl), EFMD_HDL_ABORT, format, ap);
800 }
801 
802 /*PRINTFLIKE2*/
803 void
804 fmd_hdl_abort(fmd_hdl_t *hdl, const char *format, ...)
805 {
806 	fmd_module_t *mp = fmd_api_module_lock(hdl);
807 	va_list ap;
808 
809 	va_start(ap, format);
810 	fmd_api_verror(mp, EFMD_HDL_ABORT, format, ap);
811 	va_end(ap);
812 }
813 
814 void
815 fmd_hdl_verror(fmd_hdl_t *hdl, const char *format, va_list ap)
816 {
817 	fmd_module_t *mp = fmd_api_module_lock(hdl);
818 	fmd_api_vxerror(mp, errno, format, ap);
819 	fmd_module_unlock(mp);
820 }
821 
822 /*PRINTFLIKE2*/
823 void
824 fmd_hdl_error(fmd_hdl_t *hdl, const char *format, ...)
825 {
826 	va_list ap;
827 
828 	va_start(ap, format);
829 	fmd_hdl_verror(hdl, format, ap);
830 	va_end(ap);
831 }
832 
833 void
834 fmd_hdl_vdebug(fmd_hdl_t *hdl, const char *format, va_list ap)
835 {
836 	fmd_module_t *mp = fmd_api_module_lock(hdl);
837 
838 	char *msg;
839 	size_t len;
840 	char c;
841 
842 	if (!(fmd.d_hdl_debug)) {
843 		mp->mod_stats->ms_debugdrop.fmds_value.ui64++;
844 		fmd_module_unlock(mp);
845 		return;
846 	}
847 
848 	len = vsnprintf(&c, 1, format, ap);
849 
850 	if ((msg = fmd_alloc(len + 2, FMD_NOSLEEP)) == NULL) {
851 		mp->mod_stats->ms_debugdrop.fmds_value.ui64++;
852 		fmd_module_unlock(mp);
853 		return;
854 	}
855 
856 	(void) vsnprintf(msg, len + 1, format, ap);
857 
858 	if (msg[len - 1] != '\n')
859 		(void) strcpy(&msg[len], "\n");
860 
861 	if (fmd.d_hdl_dbout & FMD_DBOUT_STDERR) {
862 		(void) pthread_mutex_lock(&fmd.d_err_lock);
863 		(void) fprintf(stderr, "%s DEBUG: %s: %s",
864 		    fmd.d_pname, mp->mod_name, msg);
865 		(void) pthread_mutex_unlock(&fmd.d_err_lock);
866 	}
867 
868 	if (fmd.d_hdl_dbout & FMD_DBOUT_SYSLOG) {
869 		syslog(LOG_DEBUG | LOG_DAEMON, "%s DEBUG: %s: %s",
870 		    fmd.d_pname, mp->mod_name, msg);
871 	}
872 
873 	fmd_free(msg, len + 2);
874 	fmd_module_unlock(mp);
875 }
876 
877 /*PRINTFLIKE2*/
878 void
879 fmd_hdl_debug(fmd_hdl_t *hdl, const char *format, ...)
880 {
881 	va_list ap;
882 
883 	va_start(ap, format);
884 	fmd_hdl_vdebug(hdl, format, ap);
885 	va_end(ap);
886 }
887 
888 int32_t
889 fmd_prop_get_int32(fmd_hdl_t *hdl, const char *name)
890 {
891 	fmd_module_t *mp = fmd_api_module_lock(hdl);
892 	const fmd_conf_ops_t *ops = fmd_conf_gettype(mp->mod_conf, name);
893 	int32_t value = 0;
894 
895 	if (ops == &fmd_conf_bool || ops == &fmd_conf_int32 ||
896 	    ops == &fmd_conf_uint32)
897 		(void) fmd_conf_getprop(mp->mod_conf, name, &value);
898 	else if (ops != NULL) {
899 		fmd_api_error(mp, EFMD_PROP_TYPE,
900 		    "property %s is not of int32 type\n", name);
901 	} else {
902 		fmd_api_error(mp, EFMD_PROP_DEFN,
903 		    "property %s is not defined\n", name);
904 	}
905 
906 	fmd_module_unlock(mp);
907 	return (value);
908 }
909 
910 int64_t
911 fmd_prop_get_int64(fmd_hdl_t *hdl, const char *name)
912 {
913 	fmd_module_t *mp = fmd_api_module_lock(hdl);
914 	const fmd_conf_ops_t *ops = fmd_conf_gettype(mp->mod_conf, name);
915 	int64_t value = 0;
916 
917 	if (ops == &fmd_conf_int64 || ops == &fmd_conf_uint64 ||
918 	    ops == &fmd_conf_time || ops == &fmd_conf_size)
919 		(void) fmd_conf_getprop(mp->mod_conf, name, &value);
920 	else if (ops != NULL) {
921 		fmd_api_error(mp, EFMD_PROP_TYPE,
922 		    "property %s is not of int64 type\n", name);
923 	} else {
924 		fmd_api_error(mp, EFMD_PROP_DEFN,
925 		    "property %s is not defined\n", name);
926 	}
927 
928 	fmd_module_unlock(mp);
929 	return (value);
930 }
931 
932 char *
933 fmd_prop_get_string(fmd_hdl_t *hdl, const char *name)
934 {
935 	fmd_module_t *mp = fmd_api_module_lock(hdl);
936 	const fmd_conf_ops_t *ops = fmd_conf_gettype(mp->mod_conf, name);
937 	char *value = NULL;
938 	const char *s;
939 
940 	if (ops == &fmd_conf_string) {
941 		(void) fmd_conf_getprop(mp->mod_conf, name, &s);
942 		value = fmd_strdup(s, FMD_SLEEP);
943 	} else if (ops != NULL) {
944 		fmd_api_error(mp, EFMD_PROP_TYPE,
945 		    "property %s is not of string type\n", name);
946 	} else {
947 		fmd_api_error(mp, EFMD_PROP_DEFN,
948 		    "property %s is not defined\n", name);
949 	}
950 
951 	fmd_module_unlock(mp);
952 	return (value);
953 }
954 
955 void
956 fmd_prop_free_string(fmd_hdl_t *hdl, char *s)
957 {
958 	fmd_module_t *mp = fmd_api_module_lock(hdl);
959 	fmd_strfree(s);
960 	fmd_module_unlock(mp);
961 }
962 
963 fmd_stat_t *
964 fmd_stat_create(fmd_hdl_t *hdl, uint_t flags, uint_t argc, fmd_stat_t *argv)
965 {
966 	fmd_module_t *mp = fmd_api_module_lock(hdl);
967 	fmd_stat_t *ep, *sp;
968 
969 	if (flags & ~FMD_STAT_ALLOC) {
970 		fmd_api_error(mp, EFMD_STAT_FLAGS,
971 		    "invalid flags 0x%x passed to fmd_stat_create\n", flags);
972 	}
973 
974 	if ((sp = fmd_ustat_insert(mp->mod_ustat,
975 	    flags | FMD_USTAT_VALIDATE, argc, argv, &ep)) == NULL) {
976 		fmd_api_error(mp, errno,
977 		    "failed to publish stat '%s'", ep->fmds_name);
978 	}
979 
980 	fmd_module_unlock(mp);
981 	return (sp);
982 }
983 
984 void
985 fmd_stat_destroy(fmd_hdl_t *hdl, uint_t argc, fmd_stat_t *argv)
986 {
987 	fmd_module_t *mp = fmd_api_module_lock(hdl);
988 	fmd_ustat_delete(mp->mod_ustat, argc, argv);
989 	fmd_module_unlock(mp);
990 }
991 
992 void
993 fmd_stat_setstr(fmd_hdl_t *hdl, fmd_stat_t *sp, const char *s)
994 {
995 	char *str = fmd_strdup(s, FMD_SLEEP);
996 	fmd_module_t *mp = fmd_api_module_lock(hdl);
997 
998 	if (sp->fmds_type != FMD_TYPE_STRING) {
999 		fmd_strfree(str);
1000 		fmd_api_error(mp, EFMD_STAT_TYPE,
1001 		    "stat '%s' is not a string\n", sp->fmds_name);
1002 	}
1003 
1004 	fmd_strfree(sp->fmds_value.str);
1005 	sp->fmds_value.str = str;
1006 
1007 	fmd_module_unlock(mp);
1008 }
1009 
1010 fmd_case_t *
1011 fmd_case_open(fmd_hdl_t *hdl, void *data)
1012 {
1013 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1014 	fmd_case_t *cp = fmd_case_create(mp, data);
1015 	fmd_module_unlock(mp);
1016 	return (cp);
1017 }
1018 
1019 void
1020 fmd_case_reset(fmd_hdl_t *hdl, fmd_case_t *cp)
1021 {
1022 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1023 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1024 
1025 	if (cip->ci_state >= FMD_CASE_SOLVED) {
1026 		fmd_api_error(mp, EFMD_CASE_STATE, "cannot solve %s: "
1027 		    "case is already solved or closed\n", cip->ci_uuid);
1028 	}
1029 
1030 	fmd_case_reset_suspects(cp);
1031 	fmd_module_unlock(mp);
1032 }
1033 
1034 void
1035 fmd_case_solve(fmd_hdl_t *hdl, fmd_case_t *cp)
1036 {
1037 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1038 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1039 
1040 	if (cip->ci_state >= FMD_CASE_SOLVED) {
1041 		fmd_api_error(mp, EFMD_CASE_STATE, "cannot solve %s: "
1042 		    "case is already solved or closed\n", cip->ci_uuid);
1043 	}
1044 
1045 	fmd_case_transition(cp, FMD_CASE_SOLVED, FMD_CF_SOLVED);
1046 	fmd_module_unlock(mp);
1047 }
1048 
1049 void
1050 fmd_case_close(fmd_hdl_t *hdl, fmd_case_t *cp)
1051 {
1052 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1053 
1054 	(void) fmd_api_case_impl(mp, cp); /* validate 'cp' */
1055 	fmd_case_transition(cp, FMD_CASE_CLOSE_WAIT, FMD_CF_ISOLATED);
1056 
1057 	fmd_module_unlock(mp);
1058 }
1059 
1060 const char *
1061 fmd_case_uuid(fmd_hdl_t *hdl, fmd_case_t *cp)
1062 {
1063 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1064 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1065 	const char *uuid = cip->ci_uuid;
1066 
1067 	fmd_module_unlock(mp);
1068 	return (uuid);
1069 }
1070 
1071 fmd_case_t *
1072 fmd_case_uulookup(fmd_hdl_t *hdl, const char *uuid)
1073 {
1074 	fmd_module_t *cmp, *mp = fmd_api_module_lock(hdl);
1075 	fmd_case_t *cp = fmd_case_hash_lookup(fmd.d_cases, uuid);
1076 
1077 	if (cp != NULL) {
1078 		cmp = ((fmd_case_impl_t *)cp)->ci_mod;
1079 		fmd_case_rele(cp);
1080 	} else
1081 		cmp = NULL;
1082 
1083 	fmd_module_unlock(mp);
1084 	return (cmp == mp ? cp : NULL);
1085 }
1086 
1087 void
1088 fmd_case_uuclose(fmd_hdl_t *hdl, const char *uuid)
1089 {
1090 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1091 	fmd_case_t *cp = fmd_case_hash_lookup(fmd.d_cases, uuid);
1092 
1093 	if (cp != NULL) {
1094 		fmd_case_transition(cp, FMD_CASE_CLOSE_WAIT, FMD_CF_ISOLATED);
1095 		fmd_case_rele(cp);
1096 	}
1097 
1098 	fmd_module_unlock(mp);
1099 }
1100 
1101 int
1102 fmd_case_uuclosed(fmd_hdl_t *hdl, const char *uuid)
1103 {
1104 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1105 	fmd_case_t *cp = fmd_case_hash_lookup(fmd.d_cases, uuid);
1106 	fmd_case_impl_t *cip = (fmd_case_impl_t *)cp;
1107 	int rv = FMD_B_TRUE;
1108 
1109 	if (cip != NULL) {
1110 		rv = cip->ci_state >= FMD_CASE_CLOSE_WAIT;
1111 		fmd_case_rele(cp);
1112 	}
1113 
1114 	fmd_module_unlock(mp);
1115 	return (rv);
1116 }
1117 
1118 static int
1119 fmd_case_instate(fmd_hdl_t *hdl, fmd_case_t *cp, uint_t state)
1120 {
1121 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1122 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1123 	int rv = cip->ci_state >= state;
1124 
1125 	fmd_module_unlock(mp);
1126 	return (rv);
1127 }
1128 
1129 int
1130 fmd_case_solved(fmd_hdl_t *hdl, fmd_case_t *cp)
1131 {
1132 	return (fmd_case_instate(hdl, cp, FMD_CASE_SOLVED));
1133 }
1134 
1135 int
1136 fmd_case_closed(fmd_hdl_t *hdl, fmd_case_t *cp)
1137 {
1138 	return (fmd_case_instate(hdl, cp, FMD_CASE_CLOSE_WAIT));
1139 }
1140 
1141 void
1142 fmd_case_add_ereport(fmd_hdl_t *hdl, fmd_case_t *cp, fmd_event_t *ep)
1143 {
1144 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1145 
1146 	(void) fmd_api_case_impl(mp, cp); /* validate 'cp' */
1147 
1148 	if (fmd_case_insert_event(cp, ep))
1149 		mp->mod_stats->ms_accepted.fmds_value.ui64++;
1150 
1151 	fmd_module_unlock(mp);
1152 }
1153 
1154 void
1155 fmd_case_add_serd(fmd_hdl_t *hdl, fmd_case_t *cp, const char *name)
1156 {
1157 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1158 	fmd_serd_elem_t *sep;
1159 	fmd_serd_eng_t *sgp;
1160 
1161 	if ((sgp = fmd_serd_eng_lookup(&mp->mod_serds, name)) == NULL) {
1162 		fmd_api_error(mp, EFMD_SERD_NAME,
1163 		    "failed to add events from serd engine '%s'", name);
1164 	}
1165 
1166 	(void) fmd_api_case_impl(mp, cp); /* validate 'cp' */
1167 
1168 	for (sep = fmd_list_next(&sgp->sg_list);
1169 	    sep != NULL; sep = fmd_list_next(sep)) {
1170 		if (fmd_case_insert_event(cp, sep->se_event))
1171 			mp->mod_stats->ms_accepted.fmds_value.ui64++;
1172 	}
1173 
1174 	fmd_module_unlock(mp);
1175 }
1176 
1177 void
1178 fmd_case_add_suspect(fmd_hdl_t *hdl, fmd_case_t *cp, nvlist_t *nvl)
1179 {
1180 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1181 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1182 	char *class;
1183 
1184 	if (cip->ci_state >= FMD_CASE_SOLVED) {
1185 		fmd_api_error(mp, EFMD_CASE_STATE, "cannot add suspect to "
1186 		    "%s: case is already solved or closed\n", cip->ci_uuid);
1187 	}
1188 
1189 	if (nvlist_lookup_string(nvl, FM_CLASS, &class) != 0 ||
1190 	    class == NULL || *class == '\0') {
1191 		fmd_api_error(mp, EFMD_CASE_EVENT, "cannot add suspect to "
1192 		    "%s: suspect event is missing a class\n", cip->ci_uuid);
1193 	}
1194 
1195 	fmd_case_insert_suspect(cp, nvl);
1196 	fmd_module_unlock(mp);
1197 }
1198 
1199 void
1200 fmd_case_setspecific(fmd_hdl_t *hdl, fmd_case_t *cp, void *data)
1201 {
1202 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1203 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1204 
1205 	(void) pthread_mutex_lock(&cip->ci_lock);
1206 	cip->ci_data = data;
1207 	(void) pthread_mutex_unlock(&cip->ci_lock);
1208 
1209 	fmd_module_unlock(mp);
1210 }
1211 
1212 void *
1213 fmd_case_getspecific(fmd_hdl_t *hdl, fmd_case_t *cp)
1214 {
1215 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1216 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1217 	void *data;
1218 
1219 	(void) pthread_mutex_lock(&cip->ci_lock);
1220 	data = cip->ci_data;
1221 	(void) pthread_mutex_unlock(&cip->ci_lock);
1222 
1223 	fmd_module_unlock(mp);
1224 	return (data);
1225 }
1226 
1227 void
1228 fmd_case_setprincipal(fmd_hdl_t *hdl, fmd_case_t *cp, fmd_event_t *ep)
1229 {
1230 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1231 
1232 	(void) fmd_api_case_impl(mp, cp); /* validate 'cp' */
1233 
1234 	if (fmd_case_insert_principal(cp, ep))
1235 		mp->mod_stats->ms_accepted.fmds_value.ui64++;
1236 
1237 	fmd_module_unlock(mp);
1238 }
1239 
1240 fmd_event_t *
1241 fmd_case_getprincipal(fmd_hdl_t *hdl, fmd_case_t *cp)
1242 {
1243 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1244 	fmd_case_impl_t *cip = fmd_api_case_impl(mp, cp);
1245 	fmd_event_t *ep;
1246 
1247 	(void) pthread_mutex_lock(&cip->ci_lock);
1248 	ep = cip->ci_principal;
1249 	(void) pthread_mutex_unlock(&cip->ci_lock);
1250 
1251 	fmd_module_unlock(mp);
1252 	return (ep);
1253 }
1254 
1255 fmd_case_t *
1256 fmd_case_next(fmd_hdl_t *hdl, fmd_case_t *cp)
1257 {
1258 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1259 
1260 	if (cp != NULL)
1261 		cp = fmd_list_next(fmd_api_case_impl(mp, cp));
1262 	else
1263 		cp = fmd_list_next(&mp->mod_cases);
1264 
1265 	fmd_module_unlock(mp);
1266 	return (cp);
1267 }
1268 
1269 fmd_case_t *
1270 fmd_case_prev(fmd_hdl_t *hdl, fmd_case_t *cp)
1271 {
1272 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1273 
1274 	if (cp != NULL)
1275 		cp = fmd_list_prev(fmd_api_case_impl(mp, cp));
1276 	else
1277 		cp = fmd_list_prev(&mp->mod_cases);
1278 
1279 	fmd_module_unlock(mp);
1280 	return (cp);
1281 }
1282 
1283 /*
1284  * This function returns TRUE IFF all the ereports relating to a case is from a
1285  * PCI/PCIe device.  If true, the rc_detector variable will be returned in DEV
1286  * Scheme format.
1287  */
1288 boolean_t
1289 fmd_case_is_pcie(fmd_hdl_t *hdl, fmd_case_t *cp, nvlist_t **rc_detector) {
1290 	fmd_case_impl_t *cip = (fmd_case_impl_t *)cp;
1291 	fmd_case_item_t *cit;
1292 	fmd_event_impl_t *ep;
1293 	nvlist_t	*nvl, *detector;
1294 	char		*scheme, *path, rcpath[PATH_MAX];
1295 	int		err, i;
1296 	boolean_t ret = B_FALSE;
1297 
1298 	syslog(LOG_ERR | LOG_DAEMON, "[PCIE] Checking if case is PCI/PCIe\n");
1299 
1300 	for (cit = cip->ci_items; cit != NULL; cit = cit->cit_next) {
1301 		ep = (fmd_event_impl_t *)cit->cit_event;
1302 		nvl = ep->ev_nvl;
1303 
1304 		if (!fmd_nvl_class_match(hdl, nvl, "ereport.io.pci.*") &&
1305 		    !fmd_nvl_class_match(hdl, nvl, "ereport.io.pciex.*"))
1306 			return (B_FALSE);
1307 
1308 		if (nvlist_lookup_nvlist(nvl, FM_EREPORT_DETECTOR,
1309 		    &detector) != 0) {
1310 			syslog(LOG_ERR | LOG_DAEMON,
1311 			    "[PCIE] Getting detector failed \n");
1312 			return (B_FALSE);
1313 		}
1314 
1315 		/* Find the RC PATH, this only works for dev scheme ereports */
1316 		err = nvlist_lookup_string(detector, FM_FMRI_SCHEME, &scheme);
1317 		if (ret == B_TRUE || err || strcmp(scheme, FM_FMRI_SCHEME_DEV))
1318 			continue;
1319 
1320 		ret = B_TRUE;
1321 		(void) nvlist_lookup_string(detector, FM_FMRI_DEV_PATH, &path);
1322 
1323 		(void) strncpy(rcpath, path, PATH_MAX);
1324 		for (i = 1; (i < PATH_MAX) && (rcpath[i] != '/') &&
1325 		    (rcpath[i] != '\0'); i++);
1326 
1327 		if (i == PATH_MAX) {
1328 			rcpath[i-1] = '\0';
1329 			syslog(LOG_ERR | LOG_DAEMON,
1330 			    "[PCIE] Could not get full RC path %s\n", rcpath);
1331 		} else {
1332 			rcpath[i] = '\0';
1333 		}
1334 
1335 		syslog(LOG_ERR | LOG_DAEMON, "[PCIE] Got RC Path %s\n", rcpath);
1336 
1337 		if (nvlist_dup(detector, rc_detector, NV_UNIQUE_NAME) != 0)
1338 			return (B_FALSE);
1339 		(void) nvlist_remove(*rc_detector, FM_FMRI_DEV_PATH,
1340 		    DATA_TYPE_STRING);
1341 		(void) nvlist_add_string(*rc_detector, FM_VERSION,
1342 		    FM_DEV_SCHEME_VERSION);
1343 		(void) nvlist_add_string(*rc_detector, FM_FMRI_DEV_PATH,
1344 		    rcpath);
1345 	}
1346 
1347 	return (ret);
1348 }
1349 
1350 /*
1351  * Path comparison function used in fmd_case_pci_undiagnosable
1352  */
1353 int
1354 fmd_case_pci_cmp(const void *path1, const void *path2) {
1355 	return (strcmp((const char *)path1, (const char *)path2));
1356 }
1357 
1358 /*
1359  * Populates an unknown pci defect/fault with a list of suspects. This is
1360  * temporary code until a generic way to do this for all "UNDIAG FAULTS"
1361  * is designed.
1362  */
1363 /* ARGSUSED */
1364 void
1365 fmd_case_pci_undiagnosable(fmd_hdl_t *hdl, fmd_case_t *cp, nvlist_t *defect) {
1366 	fmd_case_impl_t *cip = (fmd_case_impl_t *)cp;
1367 	fmd_case_item_t *cit;
1368 	fmd_event_impl_t *ep;
1369 	nvlist_t	*nvl, *detector;
1370 	char		*scheme, *path, **tbl;
1371 	int		err, i = 0;
1372 	size_t		tbl_sz = 0;
1373 
1374 	syslog(LOG_ERR | LOG_DAEMON, "[PCIE UNDIAG] START %d\n",
1375 	    cip->ci_nitems);
1376 
1377 	tbl = alloca(cip->ci_nitems * sizeof (char *));
1378 	path = alloca(cip->ci_nitems * sizeof (char *) * PATH_MAX);
1379 
1380 	for (i = 0; i < cip->ci_nitems; i++) {
1381 		tbl[i] = path + (i * PATH_MAX);
1382 	}
1383 
1384 	for (cit = cip->ci_items; cit != NULL; cit = cit->cit_next) {
1385 		ep = (fmd_event_impl_t *)cit->cit_event;
1386 		nvl = ep->ev_nvl;
1387 
1388 		(void) nvlist_lookup_nvlist(nvl, FM_EREPORT_DETECTOR,
1389 		    &detector);
1390 
1391 		/* Only get dev scheme paths */
1392 		err = nvlist_lookup_string(detector, FM_FMRI_SCHEME, &scheme);
1393 		if (err || strcmp(scheme, FM_FMRI_SCHEME_DEV) != 0)
1394 			continue;
1395 
1396 		if (nvlist_lookup_string(detector, FM_FMRI_DEV_PATH,
1397 		    &path) != 0) {
1398 			syslog(LOG_ERR | LOG_DAEMON,
1399 			    "[PCIE UNDIAG] Path is NULL");
1400 			continue;
1401 		}
1402 		scheme = lsearch(path, *tbl, &tbl_sz, PATH_MAX,
1403 		    fmd_case_pci_cmp);
1404 	}
1405 
1406 	qsort((void *)*tbl, tbl_sz, PATH_MAX, fmd_case_pci_cmp);
1407 
1408 	for (i = 0; i < tbl_sz; i++) {
1409 		syslog(LOG_ERR | LOG_DAEMON, "[PCIE UNDIAG] Path %s size %d %d",
1410 		    tbl[i], tbl_sz, strlen(tbl[i]));
1411 	}
1412 
1413 	(void) nvlist_add_string_array(defect, "suspect-devices", tbl, tbl_sz);
1414 }
1415 
1416 /*
1417  * Utility function for fmd_buf_* routines.  If a case is specified, use the
1418  * case's ci_bufs hash; otherwise use the module's global mod_bufs hash.
1419  */
1420 static fmd_buf_hash_t *
1421 fmd_buf_gethash(fmd_module_t *mp, fmd_case_t *cp)
1422 {
1423 	return (cp ? &fmd_api_case_impl(mp, cp)->ci_bufs : &mp->mod_bufs);
1424 }
1425 
1426 void
1427 fmd_buf_create(fmd_hdl_t *hdl, fmd_case_t *cp, const char *name, size_t size)
1428 {
1429 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1430 	fmd_buf_hash_t *bhp = fmd_buf_gethash(mp, cp);
1431 	fmd_buf_t *bp = fmd_buf_lookup(bhp, name);
1432 
1433 	if (bp == NULL) {
1434 		if (fmd_strbadid(name, FMD_B_TRUE) != NULL || size == 0) {
1435 			fmd_api_error(mp, EFMD_BUF_INVAL, "cannot create '%s' "
1436 			    "(size %lu): %s\n", name, (ulong_t)size,
1437 			    fmd_strerror(EFMD_BUF_INVAL));
1438 		}
1439 
1440 		if (mp->mod_stats->ms_buflimit.fmds_value.ui64 -
1441 		    mp->mod_stats->ms_buftotal.fmds_value.ui64 < size) {
1442 			fmd_api_error(mp, EFMD_BUF_LIMIT, "cannot create '%s': "
1443 			    "buf limit exceeded (%llu)\n", name, (u_longlong_t)
1444 			    mp->mod_stats->ms_buflimit.fmds_value.ui64);
1445 		}
1446 
1447 		mp->mod_stats->ms_buftotal.fmds_value.ui64 += size;
1448 		bp = fmd_buf_insert(bhp, name, size);
1449 
1450 	} else {
1451 		fmd_api_error(mp, EFMD_BUF_EXISTS,
1452 		    "cannot create '%s': buffer already exists\n", name);
1453 	}
1454 
1455 	if (cp != NULL)
1456 		fmd_case_setdirty(cp);
1457 	else
1458 		fmd_module_setdirty(mp);
1459 
1460 	fmd_module_unlock(mp);
1461 }
1462 
1463 void
1464 fmd_buf_destroy(fmd_hdl_t *hdl, fmd_case_t *cp, const char *name)
1465 {
1466 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1467 	fmd_buf_hash_t *bhp = fmd_buf_gethash(mp, cp);
1468 	fmd_buf_t *bp = fmd_buf_lookup(bhp, name);
1469 
1470 	if (bp != NULL) {
1471 		mp->mod_stats->ms_buftotal.fmds_value.ui64 -= bp->buf_size;
1472 		fmd_buf_delete(bhp, name);
1473 
1474 		if (cp != NULL)
1475 			fmd_case_setdirty(cp);
1476 		else
1477 			fmd_module_setdirty(mp);
1478 	}
1479 
1480 	fmd_module_unlock(mp);
1481 }
1482 
1483 void
1484 fmd_buf_read(fmd_hdl_t *hdl, fmd_case_t *cp,
1485     const char *name, void *buf, size_t size)
1486 {
1487 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1488 	fmd_buf_t *bp = fmd_buf_lookup(fmd_buf_gethash(mp, cp), name);
1489 
1490 	if (bp == NULL) {
1491 		fmd_api_error(mp, EFMD_BUF_NOENT, "no buf named '%s' is "
1492 		    "associated with %s\n", name, cp ? "case" : "module");
1493 	}
1494 
1495 	bcopy(bp->buf_data, buf, MIN(bp->buf_size, size));
1496 	if (size > bp->buf_size)
1497 		bzero((char *)buf + bp->buf_size, size - bp->buf_size);
1498 
1499 	fmd_module_unlock(mp);
1500 }
1501 
1502 void
1503 fmd_buf_write(fmd_hdl_t *hdl, fmd_case_t *cp,
1504     const char *name, const void *buf, size_t size)
1505 {
1506 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1507 	fmd_buf_hash_t *bhp = fmd_buf_gethash(mp, cp);
1508 	fmd_buf_t *bp = fmd_buf_lookup(bhp, name);
1509 
1510 	if (bp == NULL) {
1511 		if (fmd_strbadid(name, FMD_B_TRUE) != NULL || size == 0) {
1512 			fmd_api_error(mp, EFMD_BUF_INVAL, "cannot write '%s' "
1513 			    "(size %lu): %s\n", name, (ulong_t)size,
1514 			    fmd_strerror(EFMD_BUF_INVAL));
1515 		}
1516 
1517 		if (mp->mod_stats->ms_buflimit.fmds_value.ui64 -
1518 		    mp->mod_stats->ms_buftotal.fmds_value.ui64 < size) {
1519 			fmd_api_error(mp, EFMD_BUF_LIMIT, "cannot write '%s': "
1520 			    "buf limit exceeded (%llu)\n", name, (u_longlong_t)
1521 			    mp->mod_stats->ms_buflimit.fmds_value.ui64);
1522 		}
1523 
1524 		mp->mod_stats->ms_buftotal.fmds_value.ui64 += size;
1525 		bp = fmd_buf_insert(bhp, name, size);
1526 
1527 	} else if (size > bp->buf_size) {
1528 		fmd_api_error(mp, EFMD_BUF_OFLOW,
1529 		    "write to buf '%s' overflows buf size (%lu > %lu)\n",
1530 		    name, (ulong_t)size, (ulong_t)bp->buf_size);
1531 	}
1532 
1533 	bcopy(buf, bp->buf_data, MIN(bp->buf_size, size));
1534 	bp->buf_flags |= FMD_BUF_DIRTY;
1535 
1536 	if (cp != NULL)
1537 		fmd_case_setdirty(cp);
1538 	else
1539 		fmd_module_setdirty(mp);
1540 
1541 	fmd_module_unlock(mp);
1542 }
1543 
1544 size_t
1545 fmd_buf_size(fmd_hdl_t *hdl, fmd_case_t *cp, const char *name)
1546 {
1547 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1548 	fmd_buf_hash_t *bhp = fmd_buf_gethash(mp, cp);
1549 
1550 	fmd_buf_t *bp;
1551 	size_t size;
1552 
1553 	if ((bp = fmd_buf_lookup(bhp, name)) != NULL)
1554 		size = bp->buf_size;
1555 	else
1556 		size = 0;
1557 
1558 	fmd_module_unlock(mp);
1559 	return (size);
1560 }
1561 
1562 void
1563 fmd_serd_create(fmd_hdl_t *hdl, const char *name, uint_t n, hrtime_t t)
1564 {
1565 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1566 
1567 	if (fmd_serd_eng_lookup(&mp->mod_serds, name) != NULL) {
1568 		fmd_api_error(mp, EFMD_SERD_EXISTS,
1569 		    "failed to create serd engine '%s': %s\n",
1570 		    name, fmd_strerror(EFMD_SERD_EXISTS));
1571 	}
1572 
1573 	(void) fmd_serd_eng_insert(&mp->mod_serds, name, n, t);
1574 	fmd_module_setdirty(mp);
1575 	fmd_module_unlock(mp);
1576 }
1577 
1578 void
1579 fmd_serd_destroy(fmd_hdl_t *hdl, const char *name)
1580 {
1581 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1582 
1583 	fmd_serd_eng_delete(&mp->mod_serds, name);
1584 	fmd_module_setdirty(mp);
1585 	fmd_module_unlock(mp);
1586 }
1587 
1588 int
1589 fmd_serd_exists(fmd_hdl_t *hdl, const char *name)
1590 {
1591 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1592 	int rv = (fmd_serd_eng_lookup(&mp->mod_serds, name) != NULL);
1593 	fmd_module_unlock(mp);
1594 
1595 	return (rv);
1596 }
1597 
1598 void
1599 fmd_serd_reset(fmd_hdl_t *hdl, const char *name)
1600 {
1601 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1602 	fmd_serd_eng_t *sgp;
1603 
1604 	if ((sgp = fmd_serd_eng_lookup(&mp->mod_serds, name)) == NULL) {
1605 		fmd_api_error(mp, EFMD_SERD_NAME,
1606 		    "serd engine '%s' does not exist\n", name);
1607 	}
1608 
1609 	fmd_serd_eng_reset(sgp);
1610 	fmd_module_setdirty(mp);
1611 	fmd_module_unlock(mp);
1612 }
1613 
1614 int
1615 fmd_serd_record(fmd_hdl_t *hdl, const char *name, fmd_event_t *ep)
1616 {
1617 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1618 	fmd_serd_eng_t *sgp;
1619 	int err;
1620 
1621 	if ((sgp = fmd_serd_eng_lookup(&mp->mod_serds, name)) == NULL) {
1622 		fmd_api_error(mp, EFMD_SERD_NAME,
1623 		    "failed to add record to serd engine '%s'", name);
1624 	}
1625 
1626 	err = fmd_serd_eng_record(sgp, ep);
1627 
1628 	if (sgp->sg_flags & FMD_SERD_DIRTY)
1629 		fmd_module_setdirty(mp);
1630 
1631 	fmd_module_unlock(mp);
1632 	return (err);
1633 }
1634 
1635 int
1636 fmd_serd_fired(fmd_hdl_t *hdl, const char *name)
1637 {
1638 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1639 	fmd_serd_eng_t *sgp;
1640 	int err;
1641 
1642 	if ((sgp = fmd_serd_eng_lookup(&mp->mod_serds, name)) == NULL) {
1643 		fmd_api_error(mp, EFMD_SERD_NAME,
1644 		    "serd engine '%s' does not exist\n", name);
1645 	}
1646 
1647 	err = fmd_serd_eng_fired(sgp);
1648 	fmd_module_unlock(mp);
1649 	return (err);
1650 }
1651 
1652 int
1653 fmd_serd_empty(fmd_hdl_t *hdl, const char *name)
1654 {
1655 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1656 	fmd_serd_eng_t *sgp;
1657 	int empty;
1658 
1659 	if ((sgp = fmd_serd_eng_lookup(&mp->mod_serds, name)) == NULL) {
1660 		fmd_api_error(mp, EFMD_SERD_NAME,
1661 		    "serd engine '%s' does not exist\n", name);
1662 	}
1663 
1664 	empty = fmd_serd_eng_empty(sgp);
1665 	fmd_module_unlock(mp);
1666 	return (empty);
1667 }
1668 
1669 pthread_t
1670 fmd_thr_create(fmd_hdl_t *hdl, void (*func)(void *), void *arg)
1671 {
1672 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1673 	fmd_thread_t *tp;
1674 	pthread_t tid;
1675 
1676 	if (mp->mod_stats->ms_thrtotal.fmds_value.ui32 >=
1677 	    mp->mod_stats->ms_thrlimit.fmds_value.ui32) {
1678 		fmd_api_error(mp, EFMD_THR_LIMIT, "%s request to create an "
1679 		    "auxiliary thread exceeds module thread limit (%u)\n",
1680 		    mp->mod_name, mp->mod_stats->ms_thrlimit.fmds_value.ui32);
1681 	}
1682 
1683 	if ((tp = fmd_thread_create(mp, func, arg)) == NULL) {
1684 		fmd_api_error(mp, EFMD_THR_CREATE,
1685 		    "failed to create auxiliary thread");
1686 	}
1687 
1688 	tid = tp->thr_tid;
1689 	mp->mod_stats->ms_thrtotal.fmds_value.ui32++;
1690 	(void) fmd_idspace_xalloc(mp->mod_threads, tid, tp);
1691 
1692 	fmd_module_unlock(mp);
1693 	return (tid);
1694 }
1695 
1696 void
1697 fmd_thr_destroy(fmd_hdl_t *hdl, pthread_t tid)
1698 {
1699 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1700 	fmd_thread_t *tp;
1701 	int err;
1702 
1703 	if (pthread_self() == tid) {
1704 		fmd_api_error(mp, EFMD_THR_INVAL, "auxiliary thread tried to "
1705 		    "destroy itself (tid %u)\n", tid);
1706 	}
1707 
1708 	if ((tp = fmd_idspace_getspecific(mp->mod_threads, tid)) == NULL) {
1709 		fmd_api_error(mp, EFMD_THR_INVAL, "auxiliary thread tried to "
1710 		    "destroy an invalid thread (tid %u)\n", tid);
1711 	}
1712 
1713 	/*
1714 	 * Wait for the specified thread to exit and then join with it.  Since
1715 	 * the thread may need to make API calls in order to complete its work
1716 	 * we must sleep with the module lock unheld, and then reacquire it.
1717 	 */
1718 	fmd_module_unlock(mp);
1719 	err = pthread_join(tid, NULL);
1720 	mp = fmd_api_module_lock(hdl);
1721 
1722 	/*
1723 	 * Since pthread_join() was called without the module lock held, if
1724 	 * multiple callers attempted to destroy the same auxiliary thread
1725 	 * simultaneously, one will succeed and the others will get ESRCH.
1726 	 * Therefore we silently ignore ESRCH but only allow the caller who
1727 	 * succeessfully joined with the auxiliary thread to destroy it.
1728 	 */
1729 	if (err != 0 && err != ESRCH) {
1730 		fmd_api_error(mp, EFMD_THR_JOIN,
1731 		    "failed to join with auxiliary thread %u\n", tid);
1732 	}
1733 
1734 	if (err == 0) {
1735 		fmd_thread_destroy(tp, FMD_THREAD_NOJOIN);
1736 		mp->mod_stats->ms_thrtotal.fmds_value.ui32--;
1737 		(void) fmd_idspace_free(mp->mod_threads, tid);
1738 	}
1739 
1740 	fmd_module_unlock(mp);
1741 }
1742 
1743 void
1744 fmd_thr_signal(fmd_hdl_t *hdl, pthread_t tid)
1745 {
1746 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1747 
1748 	if (tid != mp->mod_thread->thr_tid &&
1749 	    fmd_idspace_getspecific(mp->mod_threads, tid) == NULL) {
1750 		fmd_api_error(mp, EFMD_THR_INVAL, "tid %u is not a valid "
1751 		    "thread id for module %s\n", tid, mp->mod_name);
1752 	}
1753 
1754 	(void) pthread_kill(tid, fmd.d_thr_sig);
1755 	fmd_module_unlock(mp);
1756 }
1757 
1758 id_t
1759 fmd_timer_install(fmd_hdl_t *hdl, void *arg, fmd_event_t *ep, hrtime_t delta)
1760 {
1761 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1762 	fmd_modtimer_t *t;
1763 	id_t id;
1764 
1765 	if (delta < 0) {
1766 		fmd_api_error(mp, EFMD_TIMER_INVAL,
1767 		    "timer delta %lld is not a valid interval\n", delta);
1768 	}
1769 
1770 	t = fmd_alloc(sizeof (fmd_modtimer_t), FMD_SLEEP);
1771 	t->mt_mod = mp;
1772 	t->mt_arg = arg;
1773 	t->mt_id = -1;
1774 
1775 	if ((id = fmd_timerq_install(fmd.d_timers, mp->mod_timerids,
1776 	    (fmd_timer_f *)fmd_module_timeout, t, ep, delta)) == -1) {
1777 		fmd_free(t, sizeof (fmd_modtimer_t));
1778 		fmd_api_error(mp, EFMD_TIMER_LIMIT,
1779 		    "failed to install timer +%lld", delta);
1780 	}
1781 
1782 	fmd_module_unlock(mp);
1783 	return (id);
1784 }
1785 
1786 void
1787 fmd_timer_remove(fmd_hdl_t *hdl, id_t id)
1788 {
1789 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1790 	fmd_modtimer_t *t;
1791 
1792 	if (!fmd_idspace_valid(mp->mod_timerids, id)) {
1793 		fmd_api_error(mp, EFMD_TIMER_INVAL,
1794 		    "id %ld is not a valid timer id\n", id);
1795 	}
1796 
1797 	/*
1798 	 * If the timer has not fired (t != NULL), remove it from the timer
1799 	 * queue.  If the timer has fired (t == NULL), we could be in one of
1800 	 * two situations: a) we are processing the timer callback or b)
1801 	 * the timer event is on the module queue awaiting dispatch.  For a),
1802 	 * fmd_timerq_remove() will wait for the timer callback function
1803 	 * to complete and queue an event for dispatch.  For a) and b),
1804 	 * we cancel the outstanding timer event from the module's dispatch
1805 	 * queue.
1806 	 */
1807 	if ((t = fmd_timerq_remove(fmd.d_timers, mp->mod_timerids, id)) != NULL)
1808 		fmd_free(t, sizeof (fmd_modtimer_t));
1809 	fmd_module_unlock(mp);
1810 
1811 	fmd_eventq_cancel(mp->mod_queue, FMD_EVT_TIMEOUT, (void *)id);
1812 }
1813 
1814 nvlist_t *
1815 fmd_nvl_create_fault(fmd_hdl_t *hdl, const char *class,
1816     uint8_t certainty, nvlist_t *asru, nvlist_t *fru, nvlist_t *rsrc)
1817 {
1818 	fmd_module_t *mp;
1819 	topo_hdl_t *thp;
1820 	nvlist_t *nvl;
1821 	char *loc = NULL;
1822 	int err;
1823 
1824 	mp = fmd_api_module_lock(hdl);
1825 	if (class == NULL || class[0] == '\0')
1826 		fmd_api_error(mp, EFMD_NVL_INVAL, "invalid fault class\n");
1827 
1828 	thp = fmd_module_topo_hold(mp);
1829 
1830 	/*
1831 	 * Try to find the location label for this resource
1832 	 */
1833 	(void) topo_fmri_label(thp, fru, &loc, &err);
1834 
1835 	nvl = fmd_protocol_fault(class, certainty, asru, fru, rsrc, loc);
1836 
1837 	if (loc != NULL)
1838 		topo_hdl_strfree(thp, loc);
1839 
1840 	err = fmd_module_topo_rele(mp, thp);
1841 	ASSERT(err == 0);
1842 
1843 	fmd_module_unlock(mp);
1844 
1845 	return (nvl);
1846 }
1847 
1848 int
1849 fmd_nvl_class_match(fmd_hdl_t *hdl, nvlist_t *nvl, const char *pattern)
1850 {
1851 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1852 	char *class;
1853 	int rv;
1854 
1855 	rv = (nvl != NULL && nvlist_lookup_string(nvl,
1856 	    FM_CLASS, &class) == 0 && fmd_strmatch(class, pattern));
1857 
1858 	fmd_module_unlock(mp);
1859 	return (rv);
1860 }
1861 
1862 int
1863 fmd_nvl_fmri_expand(fmd_hdl_t *hdl, nvlist_t *nvl)
1864 {
1865 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1866 	int rv;
1867 
1868 	if (nvl == NULL) {
1869 		fmd_api_error(mp, EFMD_NVL_INVAL,
1870 		    "invalid nvlist %p\n", (void *)nvl);
1871 	}
1872 
1873 	rv = fmd_fmri_expand(nvl);
1874 	fmd_module_unlock(mp);
1875 	return (rv);
1876 }
1877 
1878 int
1879 fmd_nvl_fmri_present(fmd_hdl_t *hdl, nvlist_t *nvl)
1880 {
1881 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1882 	int rv;
1883 
1884 	if (nvl == NULL) {
1885 		fmd_api_error(mp, EFMD_NVL_INVAL,
1886 		    "invalid nvlist %p\n", (void *)nvl);
1887 	}
1888 
1889 	rv = fmd_fmri_present(nvl);
1890 	fmd_module_unlock(mp);
1891 
1892 	if (rv < 0) {
1893 		fmd_api_error(mp, EFMD_FMRI_OP, "invalid fmri for "
1894 		    "fmd_nvl_fmri_present\n");
1895 	}
1896 
1897 	return (rv);
1898 }
1899 
1900 int
1901 fmd_nvl_fmri_unusable(fmd_hdl_t *hdl, nvlist_t *nvl)
1902 {
1903 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1904 	int rv;
1905 
1906 	if (nvl == NULL) {
1907 		fmd_api_error(mp, EFMD_NVL_INVAL,
1908 		    "invalid nvlist %p\n", (void *)nvl);
1909 	}
1910 
1911 	rv = fmd_fmri_unusable(nvl);
1912 	fmd_module_unlock(mp);
1913 
1914 	if (rv < 0) {
1915 		fmd_api_error(mp, EFMD_FMRI_OP, "invalid fmri for "
1916 		    "fmd_nvl_fmri_unusable\n");
1917 	}
1918 
1919 	return (rv);
1920 }
1921 
1922 int
1923 fmd_nvl_fmri_faulty(fmd_hdl_t *hdl, nvlist_t *nvl)
1924 {
1925 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1926 	fmd_asru_hash_t *ahp = fmd.d_asrus;
1927 	fmd_asru_t *ap;
1928 	int rv = 0;
1929 
1930 	if (nvl == NULL) {
1931 		fmd_api_error(mp, EFMD_NVL_INVAL,
1932 		    "invalid nvlist %p\n", (void *)nvl);
1933 	}
1934 
1935 	if ((ap = fmd_asru_hash_lookup_nvl(ahp, nvl)) != NULL) {
1936 		rv = (ap->asru_flags & FMD_ASRU_FAULTY) != 0;
1937 		fmd_asru_hash_release(ahp, ap);
1938 	}
1939 
1940 	fmd_module_unlock(mp);
1941 	return (rv);
1942 }
1943 
1944 int
1945 fmd_nvl_fmri_contains(fmd_hdl_t *hdl, nvlist_t *n1, nvlist_t *n2)
1946 {
1947 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1948 	int rv;
1949 
1950 	if (n1 == NULL || n2 == NULL) {
1951 		fmd_api_error(mp, EFMD_NVL_INVAL,
1952 		    "invalid nvlist(s): %p, %p\n", (void *)n1, (void *)n2);
1953 	}
1954 
1955 	rv = fmd_fmri_contains(n1, n2);
1956 	fmd_module_unlock(mp);
1957 
1958 	if (rv < 0) {
1959 		fmd_api_error(mp, EFMD_FMRI_OP, "invalid fmri for "
1960 		    "fmd_nvl_fmri_contains\n");
1961 	}
1962 
1963 	return (rv);
1964 }
1965 
1966 nvlist_t *
1967 fmd_nvl_fmri_translate(fmd_hdl_t *hdl, nvlist_t *fmri, nvlist_t *auth)
1968 {
1969 	fmd_module_t *mp = fmd_api_module_lock(hdl);
1970 	nvlist_t *xfmri;
1971 
1972 	if (fmri == NULL || auth == NULL) {
1973 		fmd_api_error(mp, EFMD_NVL_INVAL,
1974 		    "invalid nvlist(s): %p, %p\n", (void *)fmri, (void *)auth);
1975 	}
1976 
1977 	xfmri = fmd_fmri_translate(fmri, auth);
1978 	fmd_module_unlock(mp);
1979 	return (xfmri);
1980 }
1981 
1982 int
1983 fmd_event_local(fmd_hdl_t *hdl, fmd_event_t *ep)
1984 {
1985 	if (hdl == NULL || ep == NULL) {
1986 		fmd_api_error(fmd_api_module_lock(hdl), EFMD_EVENT_INVAL,
1987 		    "NULL parameter specified to fmd_event_local\n");
1988 	}
1989 
1990 	return (((fmd_event_impl_t *)ep)->ev_flags & FMD_EVF_LOCAL);
1991 }
1992 
1993 /*ARGSUSED*/
1994 uint64_t
1995 fmd_event_ena_create(fmd_hdl_t *hdl)
1996 {
1997 	return (fmd_ena());
1998 }
1999 
2000 fmd_xprt_t *
2001 fmd_xprt_open(fmd_hdl_t *hdl, uint_t flags, nvlist_t *auth, void *data)
2002 {
2003 	fmd_module_t *mp = fmd_api_module_lock(hdl);
2004 	fmd_xprt_t *xp;
2005 
2006 	if (flags & ~FMD_XPRT_CMASK) {
2007 		fmd_api_error(mp, EFMD_XPRT_INVAL,
2008 		    "invalid transport flags 0x%x\n", flags);
2009 	}
2010 
2011 	if ((flags & FMD_XPRT_RDWR) != FMD_XPRT_RDWR &&
2012 	    (flags & FMD_XPRT_RDWR) != FMD_XPRT_RDONLY) {
2013 		fmd_api_error(mp, EFMD_XPRT_INVAL,
2014 		    "cannot open write-only transport\n");
2015 	}
2016 
2017 	if (mp->mod_stats->ms_xprtopen.fmds_value.ui32 >=
2018 	    mp->mod_stats->ms_xprtlimit.fmds_value.ui32) {
2019 		fmd_api_error(mp, EFMD_XPRT_LIMIT, "%s request to create a "
2020 		    "transport exceeds module transport limit (%u)\n",
2021 		    mp->mod_name, mp->mod_stats->ms_xprtlimit.fmds_value.ui32);
2022 	}
2023 
2024 	if ((xp = fmd_xprt_create(mp, flags, auth, data)) == NULL)
2025 		fmd_api_error(mp, errno, "cannot create transport");
2026 
2027 	fmd_module_unlock(mp);
2028 	return (xp);
2029 }
2030 
2031 void
2032 fmd_xprt_close(fmd_hdl_t *hdl, fmd_xprt_t *xp)
2033 {
2034 	fmd_module_t *mp = fmd_api_module_lock(hdl);
2035 	fmd_xprt_impl_t *xip = fmd_api_transport_impl(hdl, xp);
2036 
2037 	/*
2038 	 * Although this could be supported, it doesn't seem necessary or worth
2039 	 * the trouble.  For now, just detect this and trigger a module abort.
2040 	 * If it is needed, transports should grow reference counts and a new
2041 	 * event type will need to be enqueued for the main thread to reap it.
2042 	 */
2043 	if (xip->xi_thread != NULL &&
2044 	    xip->xi_thread->thr_tid == pthread_self()) {
2045 		fmd_api_error(mp, EFMD_XPRT_INVAL,
2046 		    "fmd_xprt_close() cannot be called from fmdo_send()\n");
2047 	}
2048 
2049 	fmd_xprt_destroy(xp);
2050 	fmd_module_unlock(mp);
2051 }
2052 
2053 void
2054 fmd_xprt_post(fmd_hdl_t *hdl, fmd_xprt_t *xp, nvlist_t *nvl, hrtime_t hrt)
2055 {
2056 	fmd_xprt_impl_t *xip = fmd_api_transport_impl(hdl, xp);
2057 
2058 	/*
2059 	 * fmd_xprt_recv() must block during startup waiting for fmd to globally
2060 	 * clear FMD_XPRT_DSUSPENDED.  As such, we can't allow it to be called
2061 	 * from a module's _fmd_init() routine, because that would block
2062 	 * fmd from completing initial module loading, resulting in a deadlock.
2063 	 */
2064 	if ((xip->xi_flags & FMD_XPRT_ISUSPENDED) &&
2065 	    (pthread_self() == xip->xi_queue->eq_mod->mod_thread->thr_tid)) {
2066 		fmd_api_error(fmd_api_module_lock(hdl), EFMD_XPRT_INVAL,
2067 		    "fmd_xprt_post() cannot be called from _fmd_init()\n");
2068 	}
2069 
2070 	fmd_xprt_recv(xp, nvl, hrt);
2071 }
2072 
2073 void
2074 fmd_xprt_suspend(fmd_hdl_t *hdl, fmd_xprt_t *xp)
2075 {
2076 	(void) fmd_api_transport_impl(hdl, xp); /* validate 'xp' */
2077 	fmd_xprt_xsuspend(xp, FMD_XPRT_SUSPENDED);
2078 }
2079 
2080 void
2081 fmd_xprt_resume(fmd_hdl_t *hdl, fmd_xprt_t *xp)
2082 {
2083 	(void) fmd_api_transport_impl(hdl, xp); /* validate 'xp' */
2084 	fmd_xprt_xresume(xp, FMD_XPRT_SUSPENDED);
2085 }
2086 
2087 int
2088 fmd_xprt_error(fmd_hdl_t *hdl, fmd_xprt_t *xp)
2089 {
2090 	fmd_xprt_impl_t *xip = fmd_api_transport_impl(hdl, xp);
2091 	return (xip->xi_state == _fmd_xprt_state_err);
2092 }
2093 
2094 /*
2095  * Translate all FMRIs in the specified name-value pair list for the specified
2096  * FMRI authority, and return a new name-value pair list for the translation.
2097  * This function is the recursive engine used by fmd_xprt_translate(), below.
2098  */
2099 static nvlist_t *
2100 fmd_xprt_xtranslate(nvlist_t *nvl, nvlist_t *auth)
2101 {
2102 	uint_t i, j, n;
2103 	nvpair_t *nvp, **nvps;
2104 	uint_t nvpslen = 0;
2105 	char *name;
2106 	size_t namelen = 0;
2107 
2108 	nvlist_t **a, **b;
2109 	nvlist_t *l, *r;
2110 	data_type_t type;
2111 	char *s;
2112 	int err;
2113 
2114 	(void) nvlist_xdup(nvl, &nvl, &fmd.d_nva);
2115 
2116 	/*
2117 	 * Count up the number of name-value pairs in 'nvl' and compute the
2118 	 * maximum length of a name used in this list for use below.
2119 	 */
2120 	for (nvp = nvlist_next_nvpair(nvl, NULL);
2121 	    nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp), nvpslen++) {
2122 		size_t len = strlen(nvpair_name(nvp));
2123 		namelen = MAX(namelen, len);
2124 	}
2125 
2126 	nvps = alloca(sizeof (nvpair_t *) * nvpslen);
2127 	name = alloca(namelen + 1);
2128 
2129 	/*
2130 	 * Store a snapshot of the name-value pairs in 'nvl' into nvps[] so
2131 	 * that we can iterate over the original pairs in the loop below while
2132 	 * performing arbitrary insert and delete operations on 'nvl' itself.
2133 	 */
2134 	for (i = 0, nvp = nvlist_next_nvpair(nvl, NULL);
2135 	    nvp != NULL; nvp = nvlist_next_nvpair(nvl, nvp))
2136 		nvps[i++] = nvp;
2137 
2138 	/*
2139 	 * Now iterate over the snapshot of the name-value pairs.  If we find a
2140 	 * value that is of type NVLIST or NVLIST_ARRAY, we translate that
2141 	 * object by either calling ourself recursively on it, or calling into
2142 	 * fmd_fmri_translate() if the object is an FMRI.  We then rip out the
2143 	 * original name-value pair and replace it with the translated one.
2144 	 */
2145 	for (i = 0; i < nvpslen; i++) {
2146 		nvp = nvps[i];
2147 		type = nvpair_type(nvp);
2148 
2149 		switch (type) {
2150 		case DATA_TYPE_NVLIST_ARRAY:
2151 			if (nvpair_value_nvlist_array(nvp, &a, &n) != 0 ||
2152 			    a == NULL || n == 0)
2153 				continue; /* array is zero-sized; skip it */
2154 
2155 			b = fmd_alloc(sizeof (nvlist_t *) * n, FMD_SLEEP);
2156 
2157 			/*
2158 			 * If the first array nvlist element looks like an FMRI
2159 			 * then assume the other elements are FMRIs as well.
2160 			 * If any b[j]'s can't be translated, then EINVAL will
2161 			 * be returned from nvlist_add_nvlist_array() below.
2162 			 */
2163 			if (nvlist_lookup_string(*a, FM_FMRI_SCHEME, &s) == 0) {
2164 				for (j = 0; j < n; j++)
2165 					b[j] = fmd_fmri_translate(a[j], auth);
2166 			} else {
2167 				for (j = 0; j < n; j++)
2168 					b[j] = fmd_xprt_xtranslate(a[j], auth);
2169 			}
2170 
2171 			(void) strcpy(name, nvpair_name(nvp));
2172 			(void) nvlist_remove(nvl, name, type);
2173 			err = nvlist_add_nvlist_array(nvl, name, b, n);
2174 
2175 			for (j = 0; j < n; j++)
2176 				nvlist_free(b[j]);
2177 
2178 			fmd_free(b, sizeof (nvlist_t *) * n);
2179 
2180 			if (err != 0) {
2181 				nvlist_free(nvl);
2182 				errno = err;
2183 				return (NULL);
2184 			}
2185 			break;
2186 
2187 		case DATA_TYPE_NVLIST:
2188 			if (nvpair_value_nvlist(nvp, &l) == 0 &&
2189 			    nvlist_lookup_string(l, FM_FMRI_SCHEME, &s) == 0)
2190 				r = fmd_fmri_translate(l, auth);
2191 			else
2192 				r = fmd_xprt_xtranslate(l, auth);
2193 
2194 			if (r == NULL) {
2195 				nvlist_free(nvl);
2196 				return (NULL);
2197 			}
2198 
2199 			(void) strcpy(name, nvpair_name(nvp));
2200 			(void) nvlist_remove(nvl, name, type);
2201 			(void) nvlist_add_nvlist(nvl, name, r);
2202 
2203 			nvlist_free(r);
2204 			break;
2205 		}
2206 	}
2207 
2208 	return (nvl);
2209 }
2210 
2211 nvlist_t *
2212 fmd_xprt_translate(fmd_hdl_t *hdl, fmd_xprt_t *xp, fmd_event_t *ep)
2213 {
2214 	fmd_xprt_impl_t *xip = fmd_api_transport_impl(hdl, xp);
2215 
2216 	if (xip->xi_auth == NULL) {
2217 		fmd_api_error(fmd_api_module_lock(hdl), EFMD_XPRT_INVAL,
2218 		    "no authority defined for transport %p\n", (void *)xp);
2219 	}
2220 
2221 	return (fmd_xprt_xtranslate(FMD_EVENT_NVL(ep), xip->xi_auth));
2222 }
2223 
2224 void
2225 fmd_xprt_setspecific(fmd_hdl_t *hdl, fmd_xprt_t *xp, void *data)
2226 {
2227 	fmd_api_transport_impl(hdl, xp)->xi_data = data;
2228 }
2229 
2230 void *
2231 fmd_xprt_getspecific(fmd_hdl_t *hdl, fmd_xprt_t *xp)
2232 {
2233 	return (fmd_api_transport_impl(hdl, xp)->xi_data);
2234 }
2235