xref: /titanic_44/usr/src/uts/common/os/evchannels.c (revision 2a9459bdd821c1cf59590a7a9069ac9c591e8a6b)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * This file contains the source of the general purpose event channel extension
30  * to the sysevent framework. This implementation is made up mainly of four
31  * layers of functionality: the event queues (evch_evq_*()), the handling of
32  * channels (evch_ch*()), the kernel interface (sysevent_evc_*()) and the
33  * interface for the sysevent pseudo driver (evch_usr*()).
34  * Libsysevent.so uses the pseudo driver sysevent's ioctl to access the event
35  * channel extensions. The driver in turn uses the evch_usr*() functions below.
36  *
37  * The interfaces for user land and kernel are declared in sys/sysevent.h
38  * Internal data structures for event channels are defined in
39  * sys/sysevent_impl.h.
40  *
41  * The basic data structure for an event channel is of type evch_chan_t.
42  * All channels are maintained by a list named evch_list. The list head
43  * is of type evch_dlist_t.
44  */
45 
46 #include <sys/types.h>
47 #include <sys/errno.h>
48 #include <sys/stropts.h>
49 #include <sys/debug.h>
50 #include <sys/ddi.h>
51 #include <sys/vmem.h>
52 #include <sys/cmn_err.h>
53 #include <sys/callb.h>
54 #include <sys/sysevent.h>
55 #include <sys/sysevent_impl.h>
56 #include <sys/sysmacros.h>
57 #include <sys/disp.h>
58 #include <sys/atomic.h>
59 #include <sys/door.h>
60 #include <sys/zone.h>
61 #include <sys/sdt.h>
62 
63 /* Back-off delay for door_ki_upcall */
64 #define	EVCH_MIN_PAUSE	8
65 #define	EVCH_MAX_PAUSE	128
66 
67 #define	GEVENT(ev)	((evch_gevent_t *)((char *)ev - \
68 			    offsetof(evch_gevent_t, ge_payload)))
69 
70 #define	EVCH_EVQ_EVCOUNT(x)	((&(x)->eq_eventq)->sq_count)
71 #define	EVCH_EVQ_HIGHWM(x)	((&(x)->eq_eventq)->sq_highwm)
72 
73 struct evch_globals {
74 	evch_dlist_t evch_list;
75 	kmutex_t evch_list_lock;
76 };
77 
78 /* Variables used by event channel routines */
79 static int		evq_initcomplete = 0;
80 static zone_key_t	evch_zone_key;
81 static uint32_t		evch_channels_max;
82 static uint32_t		evch_bindings_max = EVCH_MAX_BINDS_PER_CHANNEL;
83 static uint32_t		evch_events_max;
84 
85 static void evch_evq_unsub(evch_eventq_t *, evch_evqsub_t *);
86 static void evch_evq_destroy(evch_eventq_t *);
87 
88 /*
89  * List handling. These functions handle a doubly linked list. The list has
90  * to be protected by the calling functions. evch_dlist_t is the list head.
91  * Every node of the list has to put a evch_dlelem_t data type in its data
92  * structure as its first element.
93  *
94  * evch_dl_init		- Initialize list head
95  * evch_dl_fini		- Terminate list handling
96  * evch_dl_is_init	- Returns one if list is initialized
97  * evch_dl_add		- Add element to end of list
98  * evch_dl_del		- Remove given element from list
99  * evch_dl_search	- Lookup element in list
100  * evch_dl_getnum	- Get number of elements in list
101  * evch_dl_next		- Get next elements of list
102  */
103 
104 static void
105 evch_dl_init(evch_dlist_t *hp)
106 {
107 	hp->dh_head.dl_prev = hp->dh_head.dl_next = &hp->dh_head;
108 	hp->dh_count = 0;
109 }
110 
111 /*
112  * Assumes that list is empty.
113  */
114 static void
115 evch_dl_fini(evch_dlist_t *hp)
116 {
117 	hp->dh_head.dl_prev = hp->dh_head.dl_next = NULL;
118 }
119 
120 static int
121 evch_dl_is_init(evch_dlist_t *hp)
122 {
123 	return (hp->dh_head.dl_next != NULL ? 1 : 0);
124 }
125 
126 /*
127  * Add an element at the end of the list.
128  */
129 static void
130 evch_dl_add(evch_dlist_t *hp, evch_dlelem_t *el)
131 {
132 	evch_dlelem_t	*x = hp->dh_head.dl_prev;
133 	evch_dlelem_t	*y = &hp->dh_head;
134 
135 	x->dl_next = el;
136 	y->dl_prev = el;
137 	el->dl_next = y;
138 	el->dl_prev = x;
139 	hp->dh_count++;
140 }
141 
142 /*
143  * Remove arbitrary element out of dlist.
144  */
145 static void
146 evch_dl_del(evch_dlist_t *hp, evch_dlelem_t *p)
147 {
148 	ASSERT(hp->dh_count > 0 && p != &hp->dh_head);
149 	p->dl_prev->dl_next = p->dl_next;
150 	p->dl_next->dl_prev = p->dl_prev;
151 	p->dl_prev = NULL;
152 	p->dl_next = NULL;
153 	hp->dh_count--;
154 }
155 
156 /*
157  * Search an element in a list. Caller provides comparison callback function.
158  */
159 static evch_dlelem_t *
160 evch_dl_search(evch_dlist_t *hp, int (*cmp)(evch_dlelem_t *, char *), char *s)
161 {
162 	evch_dlelem_t *p;
163 
164 	for (p = hp->dh_head.dl_next; p != &hp->dh_head; p = p->dl_next) {
165 		if (cmp(p, s) == 0) {
166 			return (p);
167 		}
168 	}
169 	return (NULL);
170 }
171 
172 /*
173  * Return number of elements in the list.
174  */
175 static int
176 evch_dl_getnum(evch_dlist_t *hp)
177 {
178 	return (hp->dh_count);
179 }
180 
181 /*
182  * Find next element of a evch_dlist_t list. Find first element if el == NULL.
183  * Returns NULL if end of list is reached.
184  */
185 static void *
186 evch_dl_next(evch_dlist_t *hp, void *el)
187 {
188 	evch_dlelem_t *ep = (evch_dlelem_t *)el;
189 
190 	if (hp->dh_count == 0) {
191 		return (NULL);
192 	}
193 	if (ep == NULL) {
194 		return (hp->dh_head.dl_next);
195 	}
196 	if ((ep = ep->dl_next) == (evch_dlelem_t *)hp) {
197 		return (NULL);
198 	}
199 	return ((void *)ep);
200 }
201 
202 /*
203  * Queue handling routines. Mutexes have to be entered previously.
204  *
205  * evch_q_init	- Initialize queue head
206  * evch_q_in	- Put element into queue
207  * evch_q_out	- Get element out of queue
208  * evch_q_next	- Iterate over the elements of a queue
209  */
210 static void
211 evch_q_init(evch_squeue_t *q)
212 {
213 	q->sq_head = NULL;
214 	q->sq_tail = (evch_qelem_t *)q;
215 	q->sq_count = 0;
216 	q->sq_highwm = 0;
217 }
218 
219 /*
220  * Put element into the queue q
221  */
222 static void
223 evch_q_in(evch_squeue_t *q, evch_qelem_t *el)
224 {
225 	q->sq_tail->q_next = el;
226 	el->q_next = NULL;
227 	q->sq_tail = el;
228 	q->sq_count++;
229 	if (q->sq_count > q->sq_highwm) {
230 		q->sq_highwm = q->sq_count;
231 	}
232 }
233 
234 /*
235  * Returns NULL if queue is empty.
236  */
237 static evch_qelem_t *
238 evch_q_out(evch_squeue_t *q)
239 {
240 	evch_qelem_t *el;
241 
242 	if ((el = q->sq_head) != NULL) {
243 		q->sq_head = el->q_next;
244 		q->sq_count--;
245 		if (q->sq_head == NULL) {
246 			q->sq_tail = (evch_qelem_t *)q;
247 		}
248 	}
249 	return (el);
250 }
251 
252 /*
253  * Returns element after *el or first if el == NULL. NULL is returned
254  * if queue is empty or *el points to the last element in the queue.
255  */
256 static evch_qelem_t *
257 evch_q_next(evch_squeue_t *q, evch_qelem_t *el)
258 {
259 	if (el == NULL)
260 		return (q->sq_head);
261 	return (el->q_next);
262 }
263 
264 /*
265  * Event queue handling functions. An event queue is the basic building block
266  * of an event channel. One event queue makes up the publisher-side event queue.
267  * Further event queues build the per-subscriber queues of an event channel.
268  * Each queue is associated an event delivery thread.
269  * These functions support a two-step initialization. First step, when kernel
270  * memory is ready and second when threads are ready.
271  * Events consist of an administrating evch_gevent_t structure with the event
272  * data appended as variable length payload.
273  * The internal interface functions for the event queue handling are:
274  *
275  * evch_evq_create	- create an event queue
276  * evch_evq_thrcreate	- create thread for an event queue.
277  * evch_evq_destroy	- delete an event queue
278  * evch_evq_sub		- Subscribe to event delivery from an event queue
279  * evch_evq_unsub	- Unsubscribe
280  * evch_evq_pub		- Post an event into an event queue
281  * evch_evq_stop	- Put delivery thread on hold
282  * evch_evq_continue	- Resume event delivery thread
283  * evch_evq_status	- Return status of delivery thread, running or on hold
284  * evch_evq_evzalloc	- Allocate an event structure
285  * evch_evq_evfree	- Free an event structure
286  * evch_evq_evadd_dest	- Add a destructor function to an event structure
287  * evch_evq_evnext	- Iterate over events non-destructive
288  */
289 
290 /*ARGSUSED*/
291 static void *
292 evch_zoneinit(zoneid_t zoneid)
293 {
294 	struct evch_globals *eg;
295 
296 	eg = kmem_zalloc(sizeof (*eg), KM_SLEEP);
297 	evch_dl_init(&eg->evch_list);
298 	return (eg);
299 }
300 
301 /*ARGSUSED*/
302 static void
303 evch_zonefree(zoneid_t zoneid, void *arg)
304 {
305 	struct evch_globals *eg = arg;
306 	evch_chan_t *chp;
307 	evch_subd_t *sdp;
308 
309 	mutex_enter(&eg->evch_list_lock);
310 
311 	/*
312 	 * Keep picking the head element off the list until there are no
313 	 * more.
314 	 */
315 	while ((chp = evch_dl_next(&eg->evch_list, NULL)) != NULL) {
316 
317 		/*
318 		 * Since all processes are gone, all bindings should be gone,
319 		 * and only channels with SUB_KEEP subscribers should remain.
320 		 */
321 		mutex_enter(&chp->ch_mutex);
322 		ASSERT(chp->ch_bindings == 0);
323 		ASSERT(evch_dl_getnum(&chp->ch_subscr) != 0);
324 
325 		/* Forcibly unsubscribe each remaining subscription */
326 		while ((sdp = evch_dl_next(&chp->ch_subscr, NULL)) != NULL) {
327 			/*
328 			 * We should only be tearing down persistent
329 			 * subscribers at this point, since all processes
330 			 * from this zone are gone.
331 			 */
332 			ASSERT(sdp->sd_active == 0);
333 			ASSERT((sdp->sd_persist & EVCH_SUB_KEEP) != 0);
334 			/*
335 			 * Disconnect subscriber queue from main event queue.
336 			 */
337 			evch_evq_unsub(chp->ch_queue, sdp->sd_msub);
338 
339 			/* Destruct per subscriber queue */
340 			evch_evq_unsub(sdp->sd_queue, sdp->sd_ssub);
341 			evch_evq_destroy(sdp->sd_queue);
342 			/*
343 			 * Eliminate the subscriber data from channel list.
344 			 */
345 			evch_dl_del(&chp->ch_subscr, &sdp->sd_link);
346 			kmem_free(sdp->sd_classname, sdp->sd_clnsize);
347 			kmem_free(sdp->sd_ident, strlen(sdp->sd_ident) + 1);
348 			kmem_free(sdp, sizeof (evch_subd_t));
349 		}
350 
351 		/* Channel must now have no subscribers */
352 		ASSERT(evch_dl_getnum(&chp->ch_subscr) == 0);
353 
354 		/* Just like unbind */
355 		mutex_exit(&chp->ch_mutex);
356 		evch_dl_del(&eg->evch_list, &chp->ch_link);
357 		evch_evq_destroy(chp->ch_queue);
358 		mutex_destroy(&chp->ch_mutex);
359 		mutex_destroy(&chp->ch_pubmx);
360 		cv_destroy(&chp->ch_pubcv);
361 		kmem_free(chp->ch_name, chp->ch_namelen);
362 		kmem_free(chp, sizeof (evch_chan_t));
363 	}
364 
365 	mutex_exit(&eg->evch_list_lock);
366 	/* all channels should now be gone */
367 	ASSERT(evch_dl_getnum(&eg->evch_list) == 0);
368 	kmem_free(eg, sizeof (*eg));
369 }
370 
371 /*
372  * Frees evch_gevent_t structure including the payload, if the reference count
373  * drops to or below zero. Below zero happens when the event is freed
374  * without beeing queued into a queue.
375  */
376 static void
377 evch_gevent_free(evch_gevent_t *evp)
378 {
379 	int32_t refcnt;
380 
381 	refcnt = (int32_t)atomic_add_32_nv(&evp->ge_refcount, -1);
382 	if (refcnt <= 0) {
383 		if (evp->ge_destruct != NULL) {
384 			evp->ge_destruct((void *)&(evp->ge_payload),
385 			    evp->ge_dstcookie);
386 		}
387 		kmem_free(evp, evp->ge_size);
388 	}
389 }
390 
391 /*
392  * Deliver is called for every subscription to the current event
393  * It calls the registered filter function and then the registered delivery
394  * callback routine. Returns 0 on success. The callback routine returns
395  * EVQ_AGAIN or EVQ_SLEEP in case the event could not be delivered.
396  */
397 static int
398 evch_deliver(evch_evqsub_t *sp, evch_gevent_t *ep)
399 {
400 	void		*uep = &ep->ge_payload;
401 	int		res = EVQ_DELIVER;
402 
403 	if (sp->su_filter != NULL) {
404 		res = sp->su_filter(uep, sp->su_fcookie);
405 	}
406 	if (res == EVQ_DELIVER) {
407 		return (sp->su_callb(uep, sp->su_cbcookie));
408 	}
409 	return (0);
410 }
411 
412 /*
413  * Holds event delivery in case of eq_holdmode set or in case the
414  * event queue is empty. Mutex must be held when called.
415  * Wakes up a thread waiting for the delivery thread reaching the hold mode.
416  */
417 static void
418 evch_delivery_hold(evch_eventq_t *eqp, callb_cpr_t *cpip)
419 {
420 	if (eqp->eq_tabortflag == 0) {
421 		do {
422 			if (eqp->eq_holdmode) {
423 				cv_signal(&eqp->eq_onholdcv);
424 			}
425 			CALLB_CPR_SAFE_BEGIN(cpip);
426 			cv_wait(&eqp->eq_thrsleepcv, &eqp->eq_queuemx);
427 			CALLB_CPR_SAFE_END(cpip, &eqp->eq_queuemx);
428 		} while (eqp->eq_holdmode);
429 	}
430 }
431 
432 /*
433  * Event delivery thread. Enumerates all subscribers and calls evch_deliver()
434  * for each one.
435  */
436 static void
437 evch_delivery_thr(evch_eventq_t *eqp)
438 {
439 	evch_qelem_t	*qep;
440 	callb_cpr_t	cprinfo;
441 	int		res;
442 	evch_evqsub_t	*sub;
443 	int		deltime;
444 	int		repeatcount;
445 	char		thnam[32];
446 
447 	(void) snprintf(thnam, sizeof (thnam), "sysevent_chan-%d",
448 	    (int)eqp->eq_thrid);
449 	CALLB_CPR_INIT(&cprinfo, &eqp->eq_queuemx, callb_generic_cpr, thnam);
450 	mutex_enter(&eqp->eq_queuemx);
451 	while (eqp->eq_tabortflag == 0) {
452 		while (eqp->eq_holdmode == 0 && eqp->eq_tabortflag == 0 &&
453 		    (qep = evch_q_out(&eqp->eq_eventq)) != NULL) {
454 
455 			/* Filter and deliver event to all subscribers */
456 			deltime = EVCH_MIN_PAUSE;
457 			repeatcount = EVCH_MAX_TRY_DELIVERY;
458 			eqp->eq_curevent = qep->q_objref;
459 			sub = evch_dl_next(&eqp->eq_subscr, NULL);
460 			while (sub != NULL) {
461 				eqp->eq_dactive = 1;
462 				mutex_exit(&eqp->eq_queuemx);
463 				res = evch_deliver(sub, qep->q_objref);
464 				mutex_enter(&eqp->eq_queuemx);
465 				eqp->eq_dactive = 0;
466 				cv_signal(&eqp->eq_dactivecv);
467 				switch (res) {
468 				case EVQ_SLEEP:
469 					/*
470 					 * Wait for subscriber to return.
471 					 */
472 					eqp->eq_holdmode = 1;
473 					evch_delivery_hold(eqp, &cprinfo);
474 					if (eqp->eq_tabortflag) {
475 						break;
476 					}
477 					continue;
478 				case EVQ_AGAIN:
479 					CALLB_CPR_SAFE_BEGIN(&cprinfo);
480 					mutex_exit(&eqp->eq_queuemx);
481 					delay(deltime);
482 					deltime =
483 					    deltime > EVCH_MAX_PAUSE ?
484 					    deltime : deltime << 1;
485 					mutex_enter(&eqp->eq_queuemx);
486 					CALLB_CPR_SAFE_END(&cprinfo,
487 					    &eqp->eq_queuemx);
488 					if (repeatcount-- > 0) {
489 						continue;
490 					}
491 					break;
492 				}
493 				if (eqp->eq_tabortflag) {
494 					break;
495 				}
496 				sub = evch_dl_next(&eqp->eq_subscr, sub);
497 				repeatcount = EVCH_MAX_TRY_DELIVERY;
498 			}
499 			eqp->eq_curevent = NULL;
500 
501 			/* Free event data and queue element */
502 			evch_gevent_free((evch_gevent_t *)qep->q_objref);
503 			kmem_free(qep, qep->q_objsize);
504 		}
505 
506 		/* Wait for next event or end of hold mode if set */
507 		evch_delivery_hold(eqp, &cprinfo);
508 	}
509 	CALLB_CPR_EXIT(&cprinfo);	/* Does mutex_exit of eqp->eq_queuemx */
510 	thread_exit();
511 }
512 
513 /*
514  * Create the event delivery thread for an existing event queue.
515  */
516 static void
517 evch_evq_thrcreate(evch_eventq_t *eqp)
518 {
519 	kthread_t *thp;
520 
521 	thp = thread_create(NULL, 0, evch_delivery_thr, (char *)eqp, 0, &p0,
522 	    TS_RUN, minclsyspri);
523 	eqp->eq_thrid = thp->t_did;
524 }
525 
526 /*
527  * Create event queue.
528  */
529 static evch_eventq_t *
530 evch_evq_create()
531 {
532 	evch_eventq_t *p;
533 
534 	/* Allocate and initialize event queue descriptor */
535 	p = kmem_zalloc(sizeof (evch_eventq_t), KM_SLEEP);
536 	mutex_init(&p->eq_queuemx, NULL, MUTEX_DEFAULT, NULL);
537 	cv_init(&p->eq_thrsleepcv, NULL, CV_DEFAULT, NULL);
538 	evch_q_init(&p->eq_eventq);
539 	evch_dl_init(&p->eq_subscr);
540 	cv_init(&p->eq_dactivecv, NULL, CV_DEFAULT, NULL);
541 	cv_init(&p->eq_onholdcv, NULL, CV_DEFAULT, NULL);
542 
543 	/* Create delivery thread */
544 	if (evq_initcomplete) {
545 		evch_evq_thrcreate(p);
546 	}
547 	return (p);
548 }
549 
550 /*
551  * Destroy an event queue. All subscribers have to be unsubscribed prior to
552  * this call.
553  */
554 static void
555 evch_evq_destroy(evch_eventq_t *eqp)
556 {
557 	evch_qelem_t *qep;
558 
559 	ASSERT(evch_dl_getnum(&eqp->eq_subscr) == 0);
560 	/* Kill delivery thread */
561 	if (eqp->eq_thrid != NULL) {
562 		mutex_enter(&eqp->eq_queuemx);
563 		eqp->eq_tabortflag = 1;
564 		eqp->eq_holdmode = 0;
565 		cv_signal(&eqp->eq_thrsleepcv);
566 		mutex_exit(&eqp->eq_queuemx);
567 		thread_join(eqp->eq_thrid);
568 	}
569 
570 	/* Get rid of stale events in the event queue */
571 	while ((qep = (evch_qelem_t *)evch_q_out(&eqp->eq_eventq)) != NULL) {
572 		evch_gevent_free((evch_gevent_t *)qep->q_objref);
573 		kmem_free(qep, qep->q_objsize);
574 	}
575 
576 	/* Wrap up event queue structure */
577 	cv_destroy(&eqp->eq_onholdcv);
578 	cv_destroy(&eqp->eq_dactivecv);
579 	cv_destroy(&eqp->eq_thrsleepcv);
580 	evch_dl_fini(&eqp->eq_subscr);
581 	mutex_destroy(&eqp->eq_queuemx);
582 
583 	/* Free descriptor structure */
584 	kmem_free(eqp, sizeof (evch_eventq_t));
585 }
586 
587 /*
588  * Subscribe to an event queue. Every subscriber provides a filter callback
589  * routine and an event delivery callback routine.
590  */
591 static evch_evqsub_t *
592 evch_evq_sub(evch_eventq_t *eqp, filter_f filter, void *fcookie,
593     deliver_f callb, void *cbcookie)
594 {
595 	evch_evqsub_t *sp = kmem_zalloc(sizeof (evch_evqsub_t), KM_SLEEP);
596 
597 	/* Initialize subscriber structure */
598 	sp->su_filter = filter;
599 	sp->su_fcookie = fcookie;
600 	sp->su_callb = callb;
601 	sp->su_cbcookie = cbcookie;
602 
603 	/* Add subscription to queue */
604 	mutex_enter(&eqp->eq_queuemx);
605 	evch_dl_add(&eqp->eq_subscr, &sp->su_link);
606 	mutex_exit(&eqp->eq_queuemx);
607 	return (sp);
608 }
609 
610 /*
611  * Unsubscribe from an event queue.
612  */
613 static void
614 evch_evq_unsub(evch_eventq_t *eqp, evch_evqsub_t *sp)
615 {
616 	mutex_enter(&eqp->eq_queuemx);
617 
618 	/* Wait if delivery is just in progress */
619 	if (eqp->eq_dactive) {
620 		cv_wait(&eqp->eq_dactivecv, &eqp->eq_queuemx);
621 	}
622 	evch_dl_del(&eqp->eq_subscr, &sp->su_link);
623 	mutex_exit(&eqp->eq_queuemx);
624 	kmem_free(sp, sizeof (evch_evqsub_t));
625 }
626 
627 /*
628  * Publish an event. Returns 0 on success and -1 if memory alloc failed.
629  */
630 static int
631 evch_evq_pub(evch_eventq_t *eqp, void *ev, int flags)
632 {
633 	size_t size;
634 	evch_qelem_t	*qep;
635 	evch_gevent_t	*evp = GEVENT(ev);
636 
637 	size = sizeof (evch_qelem_t);
638 	if (flags & EVCH_TRYHARD) {
639 		qep = kmem_alloc_tryhard(size, &size, KM_NOSLEEP);
640 	} else {
641 		qep = kmem_alloc(size, flags & EVCH_NOSLEEP ?
642 		    KM_NOSLEEP : KM_SLEEP);
643 	}
644 	if (qep == NULL) {
645 		return (-1);
646 	}
647 	qep->q_objref = (void *)evp;
648 	qep->q_objsize = size;
649 	atomic_add_32(&evp->ge_refcount, 1);
650 	mutex_enter(&eqp->eq_queuemx);
651 	evch_q_in(&eqp->eq_eventq, qep);
652 
653 	/* Wakeup delivery thread */
654 	cv_signal(&eqp->eq_thrsleepcv);
655 	mutex_exit(&eqp->eq_queuemx);
656 	return (0);
657 }
658 
659 /*
660  * Enter hold mode of an event queue. Event delivery thread stops event
661  * handling after delivery of current event (if any).
662  */
663 static void
664 evch_evq_stop(evch_eventq_t *eqp)
665 {
666 	mutex_enter(&eqp->eq_queuemx);
667 	eqp->eq_holdmode = 1;
668 	if (evq_initcomplete) {
669 		cv_signal(&eqp->eq_thrsleepcv);
670 		cv_wait(&eqp->eq_onholdcv, &eqp->eq_queuemx);
671 	}
672 	mutex_exit(&eqp->eq_queuemx);
673 }
674 
675 /*
676  * Continue event delivery.
677  */
678 static void
679 evch_evq_continue(evch_eventq_t *eqp)
680 {
681 	mutex_enter(&eqp->eq_queuemx);
682 	eqp->eq_holdmode = 0;
683 	cv_signal(&eqp->eq_thrsleepcv);
684 	mutex_exit(&eqp->eq_queuemx);
685 }
686 
687 /*
688  * Returns status of delivery thread. 0 if running and 1 if on hold.
689  */
690 static int
691 evch_evq_status(evch_eventq_t *eqp)
692 {
693 	return (eqp->eq_holdmode);
694 }
695 
696 /*
697  * Add a destructor function to an event structure.
698  */
699 static void
700 evch_evq_evadd_dest(void *ev, destr_f destructor, void *cookie)
701 {
702 	evch_gevent_t *evp = GEVENT(ev);
703 
704 	evp->ge_destruct = destructor;
705 	evp->ge_dstcookie = cookie;
706 }
707 
708 /*
709  * Allocate evch_gevent_t structure. Return address of payload offset of
710  * evch_gevent_t.  If EVCH_TRYHARD allocation is requested, we use
711  * kmem_alloc_tryhard to alloc memory of at least paylsize bytes.
712  *
713  * If either memory allocation is unsuccessful, we return NULL.
714  */
715 static void *
716 evch_evq_evzalloc(size_t paylsize, int flag)
717 {
718 	evch_gevent_t	*evp;
719 	size_t		rsize, evsize, ge_size;
720 
721 	rsize = offsetof(evch_gevent_t, ge_payload) + paylsize;
722 	if (flag & EVCH_TRYHARD) {
723 		evp = kmem_alloc_tryhard(rsize, &evsize, KM_NOSLEEP);
724 		ge_size = evsize;
725 	} else {
726 		evp = kmem_alloc(rsize, flag & EVCH_NOSLEEP ? KM_NOSLEEP :
727 		    KM_SLEEP);
728 		ge_size = rsize;
729 	}
730 
731 	if (evp) {
732 		bzero(evp, rsize);
733 		evp->ge_size = ge_size;
734 		return (&evp->ge_payload);
735 	}
736 	return (evp);
737 }
738 
739 /*
740  * Free event structure. Argument ev is address of payload offset.
741  */
742 static void
743 evch_evq_evfree(void *ev)
744 {
745 	evch_gevent_free(GEVENT(ev));
746 }
747 
748 /*
749  * Iterate over all events in the event queue. Begin with an event
750  * which is currently being delivered. No mutexes are grabbed and no
751  * resources allocated so that this function can be called in panic
752  * context too. This function has to be called with ev == NULL initially.
753  * Actually argument ev is only a flag. Internally the member eq_nextev
754  * is used to determine the next event. But ev allows for the convenient
755  * use like
756  *	ev = NULL;
757  *	while ((ev = evch_evq_evnext(evp, ev)) != NULL) ...
758  */
759 static void *
760 evch_evq_evnext(evch_eventq_t *evq, void *ev)
761 {
762 	if (ev == NULL) {
763 		evq->eq_nextev = NULL;
764 		if (evq->eq_curevent != NULL)
765 			return (&evq->eq_curevent->ge_payload);
766 	}
767 	evq->eq_nextev = evch_q_next(&evq->eq_eventq, evq->eq_nextev);
768 	if (evq->eq_nextev == NULL)
769 		return (NULL);
770 	return (&((evch_gevent_t *)evq->eq_nextev->q_objref)->ge_payload);
771 }
772 
773 /*
774  * Channel handling functions. First some support functions. Functions belonging
775  * to the channel handling interface start with evch_ch. The following functions
776  * make up the channel handling internal interfaces:
777  *
778  * evch_chinit		- Initialize channel handling
779  * evch_chinitthr	- Second step init: initialize threads
780  * evch_chbind		- Bind to a channel
781  * evch_chunbind	- Unbind from a channel
782  * evch_chsubscribe	- Subscribe to a sysevent class
783  * evch_chunsubscribe	- Unsubscribe
784  * evch_chpublish	- Publish an event
785  * evch_chgetnames	- Get names of all channels
786  * evch_chgetchdata	- Get data of a channel
787  * evch_chrdevent_init  - Init event q traversal
788  * evch_chgetnextev	- Read out events queued for a subscriber
789  * evch_chrdevent_fini  - Finish event q traversal
790  */
791 
792 /*
793  * Compare channel name. Used for evch_dl_search to find a channel with the
794  * name s.
795  */
796 static int
797 evch_namecmp(evch_dlelem_t *ep, char *s)
798 {
799 	return (strcmp(((evch_chan_t *)ep)->ch_name, s));
800 }
801 
802 /*
803  * Sysevent filter callback routine. Enables event delivery only if it matches
804  * the event class string given by parameter cookie.
805  */
806 static int
807 evch_class_filter(void *ev, void *cookie)
808 {
809 	char *class = (char *)cookie;
810 
811 	if (class == NULL || strcmp(SE_CLASS_NAME(ev), class) == 0) {
812 		return (EVQ_DELIVER);
813 	}
814 	return (EVQ_IGNORE);
815 }
816 
817 /*
818  * Callback routine to propagate the event into a per subscriber queue.
819  */
820 static int
821 evch_subq_deliver(void *evp, void *cookie)
822 {
823 	evch_subd_t *p = (evch_subd_t *)cookie;
824 
825 	(void) evch_evq_pub(p->sd_queue, evp, EVCH_SLEEP);
826 	return (EVQ_CONT);
827 }
828 
829 /*
830  * Call kernel callback routine for sysevent kernel delivery.
831  */
832 static int
833 evch_kern_deliver(void *evp, void *cookie)
834 {
835 	sysevent_impl_t	*ev = (sysevent_impl_t *)evp;
836 	evch_subd_t	*sdp = (evch_subd_t *)cookie;
837 
838 	return (sdp->sd_callback(ev, sdp->sd_cbcookie));
839 }
840 
841 /*
842  * Door upcall for user land sysevent delivery.
843  */
844 static int
845 evch_door_deliver(void *evp, void *cookie)
846 {
847 	int		error;
848 	size_t		size;
849 	sysevent_impl_t	*ev = (sysevent_impl_t *)evp;
850 	door_arg_t	darg;
851 	evch_subd_t	*sdp = (evch_subd_t *)cookie;
852 	int		nticks = EVCH_MIN_PAUSE;
853 	uint32_t	retval;
854 	int		retry = 20;
855 
856 	/* Initialize door args */
857 	size = sizeof (sysevent_impl_t) + SE_PAYLOAD_SZ(ev);
858 
859 	darg.rbuf = (char *)&retval;
860 	darg.rsize = sizeof (retval);
861 	darg.data_ptr = (char *)ev;
862 	darg.data_size = size;
863 	darg.desc_ptr = NULL;
864 	darg.desc_num = 0;
865 
866 	for (;;) {
867 		if ((error = door_ki_upcall(sdp->sd_door, &darg)) == 0) {
868 			break;
869 		}
870 		switch (error) {
871 		case EAGAIN:
872 			/* Cannot deliver event - process may be forking */
873 			delay(nticks);
874 			nticks <<= 1;
875 			if (nticks > EVCH_MAX_PAUSE) {
876 				nticks = EVCH_MAX_PAUSE;
877 			}
878 			if (retry-- <= 0) {
879 				cmn_err(CE_CONT, "event delivery thread: "
880 				    "door_ki_upcall error EAGAIN\n");
881 				return (EVQ_CONT);
882 			}
883 			break;
884 		case EINTR:
885 		case EBADF:
886 			/* Process died */
887 			return (EVQ_SLEEP);
888 		default:
889 			cmn_err(CE_CONT,
890 			    "event delivery thread: door_ki_upcall error %d\n",
891 			    error);
892 			return (EVQ_CONT);
893 		}
894 	}
895 	if (retval == EAGAIN) {
896 		return (EVQ_AGAIN);
897 	}
898 	return (EVQ_CONT);
899 }
900 
901 /*
902  * Callback routine for evch_dl_search() to compare subscriber id's. Used by
903  * evch_subscribe() and evch_chrdevent_init().
904  */
905 static int
906 evch_subidcmp(evch_dlelem_t *ep, char *s)
907 {
908 	return (strcmp(((evch_subd_t *)ep)->sd_ident, s));
909 }
910 
911 /*
912  * Callback routine for evch_dl_search() to find a subscriber with EVCH_SUB_DUMP
913  * set (indicated by sub->sd_dump != 0). Used by evch_chrdevent_init() and
914  * evch_subscribe(). Needs to returns 0 if subscriber with sd_dump set is
915  * found.
916  */
917 /*ARGSUSED1*/
918 static int
919 evch_dumpflgcmp(evch_dlelem_t *ep, char *s)
920 {
921 	return (((evch_subd_t *)ep)->sd_dump ? 0 : 1);
922 }
923 
924 /*
925  * Event destructor function. Used to maintain the number of events per channel.
926  */
927 /*ARGSUSED*/
928 static void
929 evch_destr_event(void *ev, void *ch)
930 {
931 	evch_chan_t *chp = (evch_chan_t *)ch;
932 
933 	mutex_enter(&chp->ch_pubmx);
934 	chp->ch_nevents--;
935 	cv_signal(&chp->ch_pubcv);
936 	mutex_exit(&chp->ch_pubmx);
937 }
938 
939 /*
940  * Integer square root according to Newton's iteration.
941  */
942 static uint32_t
943 evch_isqrt(uint64_t n)
944 {
945 	uint64_t	x = n >> 1;
946 	uint64_t	xn = x - 1;
947 	static uint32_t	lowval[] = { 0, 1, 1, 2 };
948 
949 	if (n < 4) {
950 		return (lowval[n]);
951 	}
952 	while (xn < x) {
953 		x = xn;
954 		xn = (x + n / x) / 2;
955 	}
956 	return ((uint32_t)xn);
957 }
958 
959 /*
960  * First step sysevent channel initialization. Called when kernel memory
961  * allocator is initialized.
962  */
963 static void
964 evch_chinit()
965 {
966 	size_t k;
967 
968 	/*
969 	 * Calculate limits: max no of channels and max no of events per
970 	 * channel. The smallest machine with 128 MByte will allow for
971 	 * >= 8 channels and an upper limit of 2048 events per channel.
972 	 * The event limit is the number of channels times 256 (hence
973 	 * the shift factor of 8). These number where selected arbitrarily.
974 	 */
975 	k = kmem_maxavail() >> 20;
976 	evch_channels_max = min(evch_isqrt(k), EVCH_MAX_CHANNELS);
977 	evch_events_max = evch_channels_max << 8;
978 
979 	/*
980 	 * Will trigger creation of the global zone's evch state.
981 	 */
982 	zone_key_create(&evch_zone_key, evch_zoneinit, NULL, evch_zonefree);
983 }
984 
985 /*
986  * Second step sysevent channel initialization. Called when threads are ready.
987  */
988 static void
989 evch_chinitthr()
990 {
991 	struct evch_globals *eg;
992 	evch_chan_t	*chp;
993 	evch_subd_t	*sdp;
994 
995 	/*
996 	 * We're early enough in boot that we know that only the global
997 	 * zone exists; we only need to initialize its threads.
998 	 */
999 	eg = zone_getspecific(evch_zone_key, global_zone);
1000 	ASSERT(eg != NULL);
1001 
1002 	for (chp = evch_dl_next(&eg->evch_list, NULL); chp != NULL;
1003 	    chp = evch_dl_next(&eg->evch_list, chp)) {
1004 		for (sdp = evch_dl_next(&chp->ch_subscr, NULL); sdp;
1005 		    sdp = evch_dl_next(&chp->ch_subscr, sdp)) {
1006 			evch_evq_thrcreate(sdp->sd_queue);
1007 		}
1008 		evch_evq_thrcreate(chp->ch_queue);
1009 	}
1010 	evq_initcomplete = 1;
1011 }
1012 
1013 /*
1014  * Sysevent channel bind. Create channel and allocate binding structure.
1015  */
1016 static int
1017 evch_chbind(const char *chnam, evch_bind_t **scpp, uint32_t flags)
1018 {
1019 	struct evch_globals *eg;
1020 	evch_bind_t	*bp;
1021 	evch_chan_t	*p;
1022 	char		*chn;
1023 	size_t		namlen;
1024 	int		rv;
1025 
1026 	eg = zone_getspecific(evch_zone_key, curproc->p_zone);
1027 	ASSERT(eg != NULL);
1028 
1029 	/* Create channel if it does not exist */
1030 	ASSERT(evch_dl_is_init(&eg->evch_list));
1031 	if ((namlen = strlen(chnam) + 1) > MAX_CHNAME_LEN) {
1032 		return (EINVAL);
1033 	}
1034 	mutex_enter(&eg->evch_list_lock);
1035 	if ((p = (evch_chan_t *)evch_dl_search(&eg->evch_list, evch_namecmp,
1036 	    (char *)chnam)) == NULL) {
1037 		if (flags & EVCH_CREAT) {
1038 			if (evch_dl_getnum(&eg->evch_list) >=
1039 			    evch_channels_max) {
1040 				mutex_exit(&eg->evch_list_lock);
1041 				return (ENOMEM);
1042 			}
1043 			chn = kmem_alloc(namlen, KM_SLEEP);
1044 			bcopy(chnam, chn, namlen);
1045 
1046 			/* Allocate and initialize channel descriptor */
1047 			p = kmem_zalloc(sizeof (evch_chan_t), KM_SLEEP);
1048 			p->ch_name = chn;
1049 			p->ch_namelen = namlen;
1050 			mutex_init(&p->ch_mutex, NULL, MUTEX_DEFAULT, NULL);
1051 			p->ch_queue = evch_evq_create();
1052 			evch_dl_init(&p->ch_subscr);
1053 			if (evq_initcomplete) {
1054 				p->ch_uid = crgetuid(curthread->t_cred);
1055 				p->ch_gid = crgetgid(curthread->t_cred);
1056 			}
1057 			cv_init(&p->ch_pubcv, NULL, CV_DEFAULT, NULL);
1058 			mutex_init(&p->ch_pubmx, NULL, MUTEX_DEFAULT, NULL);
1059 			p->ch_maxev = min(EVCH_DEFAULT_EVENTS, evch_events_max);
1060 			p->ch_maxsubscr = EVCH_MAX_SUBSCRIPTIONS;
1061 			p->ch_maxbinds = evch_bindings_max;
1062 			p->ch_ctime = gethrestime_sec();
1063 			if (flags & EVCH_HOLD_PEND) {
1064 				p->ch_holdpend = 1;
1065 				evch_evq_stop(p->ch_queue);
1066 			}
1067 
1068 			/* Put new descriptor into channel list */
1069 			evch_dl_add(&eg->evch_list, (evch_dlelem_t *)p);
1070 		} else {
1071 			mutex_exit(&eg->evch_list_lock);
1072 			return (ENOENT);
1073 		}
1074 	}
1075 
1076 	/* Check for max binds and create binding */
1077 	mutex_enter(&p->ch_mutex);
1078 	if (p->ch_bindings >= p->ch_maxbinds) {
1079 		rv = ENOMEM;
1080 		/*
1081 		 * No need to destroy the channel because this call did not
1082 		 * create it. Other bindings will be present if ch_maxbinds
1083 		 * is exceeded.
1084 		 */
1085 		goto errorexit;
1086 	}
1087 	bp = kmem_alloc(sizeof (evch_bind_t), KM_SLEEP);
1088 	bp->bd_channel = p;
1089 	bp->bd_sublst = NULL;
1090 	p->ch_bindings++;
1091 	rv = 0;
1092 	*scpp = bp;
1093 errorexit:
1094 	mutex_exit(&p->ch_mutex);
1095 	mutex_exit(&eg->evch_list_lock);
1096 	return (rv);
1097 }
1098 
1099 /*
1100  * Unbind: Free bind structure. Remove channel if last binding was freed.
1101  */
1102 static void
1103 evch_chunbind(evch_bind_t *bp)
1104 {
1105 	struct evch_globals *eg;
1106 	evch_chan_t *chp = bp->bd_channel;
1107 
1108 	eg = zone_getspecific(evch_zone_key, curproc->p_zone);
1109 	ASSERT(eg != NULL);
1110 
1111 	mutex_enter(&eg->evch_list_lock);
1112 	mutex_enter(&chp->ch_mutex);
1113 	ASSERT(chp->ch_bindings > 0);
1114 	chp->ch_bindings--;
1115 	kmem_free(bp, sizeof (evch_bind_t));
1116 	if (chp->ch_bindings == 0 && evch_dl_getnum(&chp->ch_subscr) == 0) {
1117 		/*
1118 		 * No more bindings or persistent subscriber, destroy channel.
1119 		 */
1120 		mutex_exit(&chp->ch_mutex);
1121 		evch_dl_del(&eg->evch_list, &chp->ch_link);
1122 		evch_evq_destroy(chp->ch_queue);
1123 		mutex_destroy(&chp->ch_mutex);
1124 		mutex_destroy(&chp->ch_pubmx);
1125 		cv_destroy(&chp->ch_pubcv);
1126 		kmem_free(chp->ch_name, chp->ch_namelen);
1127 		kmem_free(chp, sizeof (evch_chan_t));
1128 	} else
1129 		mutex_exit(&chp->ch_mutex);
1130 	mutex_exit(&eg->evch_list_lock);
1131 }
1132 
1133 /*
1134  * Subscribe to a channel. dtype is either EVCH_DELKERN for kernel callbacks
1135  * or EVCH_DELDOOR for door upcall delivery to user land. Depending on dtype
1136  * dinfo gives the call back routine address or the door handle.
1137  */
1138 static int
1139 evch_chsubscribe(evch_bind_t *bp, int dtype, const char *sid, const char *class,
1140     void *dinfo, void *cookie, int flags, pid_t pid)
1141 {
1142 	evch_chan_t	*chp = bp->bd_channel;
1143 	evch_eventq_t	*eqp = chp->ch_queue;
1144 	evch_subd_t	*sdp;
1145 	evch_subd_t	*esp;
1146 	int		(*delivfkt)();
1147 	char		*clb = NULL;
1148 	int		clblen = 0;
1149 	char		*subid;
1150 	int		subidblen;
1151 
1152 	/*
1153 	 * Check if only known flags are set.
1154 	 */
1155 	if (flags & ~(EVCH_SUB_KEEP | EVCH_SUB_DUMP))
1156 		return (EINVAL);
1157 	/*
1158 	 * Check if we have already a subscription with that name and if we
1159 	 * have to reconnect the subscriber to a persistent subscription.
1160 	 */
1161 	mutex_enter(&chp->ch_mutex);
1162 	if ((esp = (evch_subd_t *)evch_dl_search(&chp->ch_subscr,
1163 	    evch_subidcmp, (char *)sid)) != NULL) {
1164 		int error = 0;
1165 		if ((flags & EVCH_SUB_KEEP) && (esp->sd_active == 0)) {
1166 			/*
1167 			 * Subscription with the name on hold, reconnect to
1168 			 * existing queue.
1169 			 */
1170 			ASSERT(dtype == EVCH_DELDOOR);
1171 			esp->sd_subnxt = bp->bd_sublst;
1172 			bp->bd_sublst = esp;
1173 			esp->sd_pid = pid;
1174 			esp->sd_door = (door_handle_t)dinfo;
1175 			esp->sd_active++;
1176 			evch_evq_continue(esp->sd_queue);
1177 		} else {
1178 			/* Subscriber with given name already exists */
1179 			error = EEXIST;
1180 		}
1181 		mutex_exit(&chp->ch_mutex);
1182 		return (error);
1183 	}
1184 
1185 	if (evch_dl_getnum(&chp->ch_subscr) >= chp->ch_maxsubscr) {
1186 		mutex_exit(&chp->ch_mutex);
1187 		return (ENOMEM);
1188 	}
1189 
1190 	if (flags & EVCH_SUB_DUMP && evch_dl_search(&chp->ch_subscr,
1191 	    evch_dumpflgcmp, NULL) != NULL) {
1192 		/*
1193 		 * Subscription with EVCH_SUB_DUMP flagged already exists.
1194 		 * Only one subscription with EVCH_SUB_DUMP possible. Return
1195 		 * error.
1196 		 */
1197 		mutex_exit(&chp->ch_mutex);
1198 		return (EINVAL);
1199 	}
1200 
1201 	if (class != NULL) {
1202 		clblen = strlen(class) + 1;
1203 		clb = kmem_alloc(clblen, KM_SLEEP);
1204 		bcopy(class, clb, clblen);
1205 	}
1206 
1207 	subidblen = strlen(sid) + 1;
1208 	subid = kmem_alloc(subidblen, KM_SLEEP);
1209 	bcopy(sid, subid, subidblen);
1210 
1211 	/* Create per subscriber queue */
1212 	sdp = kmem_zalloc(sizeof (evch_subd_t), KM_SLEEP);
1213 	sdp->sd_queue = evch_evq_create();
1214 
1215 	/* Subscribe to subscriber queue */
1216 	sdp->sd_persist = flags & EVCH_SUB_KEEP ? 1 : 0;
1217 	sdp->sd_dump = flags & EVCH_SUB_DUMP ? 1 : 0;
1218 	sdp->sd_type = dtype;
1219 	sdp->sd_cbcookie = cookie;
1220 	sdp->sd_ident = subid;
1221 	if (dtype == EVCH_DELKERN) {
1222 		sdp->sd_callback = (kerndlv_f)dinfo;
1223 		delivfkt = evch_kern_deliver;
1224 	} else {
1225 		sdp->sd_door = (door_handle_t)dinfo;
1226 		delivfkt = evch_door_deliver;
1227 	}
1228 	sdp->sd_ssub =
1229 	    evch_evq_sub(sdp->sd_queue, NULL, NULL, delivfkt, (void *)sdp);
1230 
1231 	/* Connect per subscriber queue to main event queue */
1232 	sdp->sd_msub = evch_evq_sub(eqp, evch_class_filter, clb,
1233 	    evch_subq_deliver, (void *)sdp);
1234 	sdp->sd_classname = clb;
1235 	sdp->sd_clnsize = clblen;
1236 	sdp->sd_pid = pid;
1237 	sdp->sd_active++;
1238 
1239 	/* Add subscription to binding */
1240 	sdp->sd_subnxt = bp->bd_sublst;
1241 	bp->bd_sublst = sdp;
1242 
1243 	/* Add subscription to channel */
1244 	evch_dl_add(&chp->ch_subscr, &sdp->sd_link);
1245 	if (chp->ch_holdpend && evch_dl_getnum(&chp->ch_subscr) == 1) {
1246 
1247 		/* Let main event queue run in case of HOLDPEND */
1248 		evch_evq_continue(eqp);
1249 	}
1250 	mutex_exit(&chp->ch_mutex);
1251 
1252 	return (0);
1253 }
1254 
1255 /*
1256  * If flag == EVCH_SUB_KEEP only non-persistent subscriptions are deleted.
1257  * When sid == NULL all subscriptions except the ones with EVCH_SUB_KEEP set
1258  * are removed.
1259  */
1260 static void
1261 evch_chunsubscribe(evch_bind_t *bp, const char *sid, uint32_t flags)
1262 {
1263 	evch_subd_t	*sdp;
1264 	evch_subd_t	*next;
1265 	evch_subd_t	*prev;
1266 	evch_chan_t	*chp = bp->bd_channel;
1267 
1268 	mutex_enter(&chp->ch_mutex);
1269 	if (chp->ch_holdpend) {
1270 		evch_evq_stop(chp->ch_queue);	/* Hold main event queue */
1271 	}
1272 	prev = NULL;
1273 	for (sdp = bp->bd_sublst; sdp; sdp = next) {
1274 		if (sid == NULL || strcmp(sid, sdp->sd_ident) == 0) {
1275 			if (flags == 0 || sdp->sd_persist == 0) {
1276 				/*
1277 				 * Disconnect subscriber queue from main event
1278 				 * queue.
1279 				 */
1280 				evch_evq_unsub(chp->ch_queue, sdp->sd_msub);
1281 
1282 				/* Destruct per subscriber queue */
1283 				evch_evq_unsub(sdp->sd_queue, sdp->sd_ssub);
1284 				evch_evq_destroy(sdp->sd_queue);
1285 				/*
1286 				 * Eliminate the subscriber data from channel
1287 				 * list.
1288 				 */
1289 				evch_dl_del(&chp->ch_subscr, &sdp->sd_link);
1290 				kmem_free(sdp->sd_classname, sdp->sd_clnsize);
1291 				if (sdp->sd_type == EVCH_DELDOOR) {
1292 					door_ki_rele(sdp->sd_door);
1293 				}
1294 				next = sdp->sd_subnxt;
1295 				if (prev) {
1296 					prev->sd_subnxt = next;
1297 				} else {
1298 					bp->bd_sublst = next;
1299 				}
1300 				kmem_free(sdp->sd_ident,
1301 				    strlen(sdp->sd_ident) + 1);
1302 				kmem_free(sdp, sizeof (evch_subd_t));
1303 			} else {
1304 				/*
1305 				 * EVCH_SUB_KEEP case
1306 				 */
1307 				evch_evq_stop(sdp->sd_queue);
1308 				if (sdp->sd_type == EVCH_DELDOOR) {
1309 					door_ki_rele(sdp->sd_door);
1310 				}
1311 				sdp->sd_active--;
1312 				ASSERT(sdp->sd_active == 0);
1313 				next = sdp->sd_subnxt;
1314 				prev = sdp;
1315 			}
1316 			if (sid != NULL) {
1317 				break;
1318 			}
1319 		} else {
1320 			next = sdp->sd_subnxt;
1321 			prev = sdp;
1322 		}
1323 	}
1324 	if (!(chp->ch_holdpend && evch_dl_getnum(&chp->ch_subscr) == 0)) {
1325 		/*
1326 		 * Continue dispatch thread except if no subscribers are present
1327 		 * in HOLDPEND mode.
1328 		 */
1329 		evch_evq_continue(chp->ch_queue);
1330 	}
1331 	mutex_exit(&chp->ch_mutex);
1332 }
1333 
1334 /*
1335  * Publish an event. Returns zero on success and an error code else.
1336  */
1337 static int
1338 evch_chpublish(evch_bind_t *bp, sysevent_impl_t *ev, int flags)
1339 {
1340 	evch_chan_t *chp = bp->bd_channel;
1341 
1342 	DTRACE_SYSEVENT2(post, evch_bind_t *, bp, sysevent_impl_t *, ev);
1343 
1344 	mutex_enter(&chp->ch_pubmx);
1345 	if (chp->ch_nevents >= chp->ch_maxev) {
1346 		if (!(flags & EVCH_QWAIT)) {
1347 			evch_evq_evfree(ev);
1348 			mutex_exit(&chp->ch_pubmx);
1349 			return (EAGAIN);
1350 		} else {
1351 			while (chp->ch_nevents >= chp->ch_maxev) {
1352 				if (cv_wait_sig(&chp->ch_pubcv,
1353 				    &chp->ch_pubmx) == 0) {
1354 
1355 					/* Got Signal, return EINTR */
1356 					evch_evq_evfree(ev);
1357 					mutex_exit(&chp->ch_pubmx);
1358 					return (EINTR);
1359 				}
1360 			}
1361 		}
1362 	}
1363 	chp->ch_nevents++;
1364 	mutex_exit(&chp->ch_pubmx);
1365 	SE_TIME(ev) = gethrtime();
1366 	SE_SEQ(ev) = log_sysevent_new_id();
1367 	/*
1368 	 * Add the destructor function to the event structure, now that the
1369 	 * event is accounted for. The only task of the descructor is to
1370 	 * decrement the channel event count. The evq_*() routines (including
1371 	 * the event delivery thread) do not have knowledge of the channel
1372 	 * data. So the anonymous destructor handles the channel data for it.
1373 	 */
1374 	evch_evq_evadd_dest(ev, evch_destr_event, (void *)chp);
1375 	return (evch_evq_pub(chp->ch_queue, ev, flags) == 0 ? 0 : EAGAIN);
1376 }
1377 
1378 /*
1379  * Fills a buffer consecutive with the names of all available channels.
1380  * Returns the length of all name strings or -1 if buffer size was unsufficient.
1381  */
1382 static int
1383 evch_chgetnames(char *buf, size_t size)
1384 {
1385 	struct evch_globals *eg;
1386 	int		len = 0;
1387 	char		*addr = buf;
1388 	int		max = size;
1389 	evch_chan_t	*chp;
1390 
1391 	eg = zone_getspecific(evch_zone_key, curproc->p_zone);
1392 	ASSERT(eg != NULL);
1393 
1394 	mutex_enter(&eg->evch_list_lock);
1395 	for (chp = evch_dl_next(&eg->evch_list, NULL); chp != NULL;
1396 	    chp = evch_dl_next(&eg->evch_list, chp)) {
1397 		len += chp->ch_namelen;
1398 		if (len >= max) {
1399 			mutex_exit(&eg->evch_list_lock);
1400 			return (-1);
1401 		}
1402 		bcopy(chp->ch_name, addr, chp->ch_namelen);
1403 		addr += chp->ch_namelen;
1404 	}
1405 	mutex_exit(&eg->evch_list_lock);
1406 	addr[0] = 0;
1407 	return (len + 1);
1408 }
1409 
1410 /*
1411  * Fills the data of one channel and all subscribers of that channel into
1412  * a buffer. Returns -1 if the channel name is invalid and 0 on buffer overflow.
1413  */
1414 static int
1415 evch_chgetchdata(char *chname, void *buf, size_t size)
1416 {
1417 	struct evch_globals *eg;
1418 	char		*cpaddr;
1419 	int		bufmax;
1420 	int		buflen;
1421 	evch_chan_t	*chp;
1422 	sev_chinfo_t	*p = (sev_chinfo_t *)buf;
1423 	int		chdlen;
1424 	evch_subd_t	*sdp;
1425 	sev_subinfo_t	*subp;
1426 	int		idlen;
1427 	int		len;
1428 
1429 	eg = zone_getspecific(evch_zone_key, curproc->p_zone);
1430 	ASSERT(eg != NULL);
1431 
1432 	mutex_enter(&eg->evch_list_lock);
1433 	chp = (evch_chan_t *)evch_dl_search(&eg->evch_list, evch_namecmp,
1434 	    chname);
1435 	if (chp == NULL) {
1436 		mutex_exit(&eg->evch_list_lock);
1437 		return (-1);
1438 	}
1439 	chdlen = offsetof(sev_chinfo_t, cd_subinfo);
1440 	if (size < chdlen) {
1441 		mutex_exit(&eg->evch_list_lock);
1442 		return (0);
1443 	}
1444 	p->cd_version = 0;
1445 	p->cd_suboffs = chdlen;
1446 	p->cd_uid = chp->ch_uid;
1447 	p->cd_gid = chp->ch_gid;
1448 	p->cd_perms = 0;
1449 	p->cd_ctime = chp->ch_ctime;
1450 	p->cd_maxev = chp->ch_maxev;
1451 	p->cd_evhwm = EVCH_EVQ_HIGHWM(chp->ch_queue);
1452 	p->cd_nevents = EVCH_EVQ_EVCOUNT(chp->ch_queue);
1453 	p->cd_maxsub = chp->ch_maxsubscr;
1454 	p->cd_nsub = evch_dl_getnum(&chp->ch_subscr);
1455 	p->cd_maxbinds = chp->ch_maxbinds;
1456 	p->cd_nbinds = chp->ch_bindings;
1457 	p->cd_holdpend = chp->ch_holdpend;
1458 	p->cd_limev = evch_events_max;
1459 	cpaddr = (char *)p + chdlen;
1460 	bufmax = size - chdlen;
1461 	buflen = 0;
1462 
1463 	for (sdp = evch_dl_next(&chp->ch_subscr, NULL); sdp != NULL;
1464 	    sdp = evch_dl_next(&chp->ch_subscr, sdp)) {
1465 		idlen = strlen(sdp->sd_ident) + 1;
1466 		len = SE_ALIGN(offsetof(sev_subinfo_t, sb_strings) + idlen +
1467 		    sdp->sd_clnsize);
1468 		buflen += len;
1469 		if (buflen >= bufmax) {
1470 			mutex_exit(&eg->evch_list_lock);
1471 			return (0);
1472 		}
1473 		subp = (sev_subinfo_t *)cpaddr;
1474 		subp->sb_nextoff = len;
1475 		subp->sb_stroff = offsetof(sev_subinfo_t, sb_strings);
1476 		if (sdp->sd_classname) {
1477 			bcopy(sdp->sd_classname, subp->sb_strings + idlen,
1478 			    sdp->sd_clnsize);
1479 			subp->sb_clnamoff = idlen;
1480 		} else {
1481 			subp->sb_clnamoff = idlen - 1;
1482 		}
1483 		subp->sb_pid = sdp->sd_pid;
1484 		subp->sb_nevents = EVCH_EVQ_EVCOUNT(sdp->sd_queue);
1485 		subp->sb_evhwm = EVCH_EVQ_HIGHWM(sdp->sd_queue);
1486 		subp->sb_persist = sdp->sd_persist;
1487 		subp->sb_status = evch_evq_status(sdp->sd_queue);
1488 		subp->sb_active = sdp->sd_active;
1489 		subp->sb_dump = sdp->sd_dump;
1490 		bcopy(sdp->sd_ident, subp->sb_strings, idlen);
1491 		cpaddr += len;
1492 	}
1493 	mutex_exit(&eg->evch_list_lock);
1494 	return (chdlen + buflen);
1495 }
1496 
1497 /*
1498  * Init iteration of all events of a channel. This function creates a new
1499  * event queue and puts all events from the channel into that queue.
1500  * Subsequent calls to evch_chgetnextev will deliver the events from that
1501  * queue. Only one thread per channel is allowed to read through the events.
1502  * Returns 0 on success and 1 if there is already someone reading the
1503  * events.
1504  * If argument subid == NULL, we look for a subscriber which has
1505  * flag EVCH_SUB_DUMP set.
1506  */
1507 /*
1508  * Static variables that are used to traverse events of a channel in panic case.
1509  */
1510 static evch_chan_t	*evch_chan;
1511 static evch_eventq_t	*evch_subq;
1512 static sysevent_impl_t	*evch_curev;
1513 
1514 static evchanq_t *
1515 evch_chrdevent_init(evch_chan_t *chp, char *subid)
1516 {
1517 	evch_subd_t	*sdp;
1518 	void		*ev;
1519 	int		pmqstat;	/* Prev status of main queue */
1520 	int		psqstat;	/* Prev status of subscriber queue */
1521 	evchanq_t	*snp;		/* Pointer to q with snapshot of ev */
1522 	compare_f	compfunc;
1523 
1524 	compfunc = subid == NULL ? evch_dumpflgcmp : evch_subidcmp;
1525 	if (panicstr != NULL) {
1526 		evch_chan = chp;
1527 		evch_subq = NULL;
1528 		evch_curev = NULL;
1529 		if ((sdp = (evch_subd_t *)evch_dl_search(&chp->ch_subscr,
1530 		    compfunc, subid)) != NULL) {
1531 			evch_subq = sdp->sd_queue;
1532 		}
1533 		return (NULL);
1534 	}
1535 	mutex_enter(&chp->ch_mutex);
1536 	sdp = (evch_subd_t *)evch_dl_search(&chp->ch_subscr, compfunc, subid);
1537 	/*
1538 	 * Stop main event queue and subscriber queue if not already
1539 	 * in stop mode.
1540 	 */
1541 	pmqstat = evch_evq_status(chp->ch_queue);
1542 	if (pmqstat == 0)
1543 		evch_evq_stop(chp->ch_queue);
1544 	if (sdp != NULL) {
1545 		psqstat = evch_evq_status(sdp->sd_queue);
1546 		if (psqstat == 0)
1547 			evch_evq_stop(sdp->sd_queue);
1548 	}
1549 	/*
1550 	 * Create event queue to make a snapshot of all events in the
1551 	 * channel.
1552 	 */
1553 	snp = kmem_alloc(sizeof (evchanq_t), KM_SLEEP);
1554 	snp->sn_queue = evch_evq_create();
1555 	evch_evq_stop(snp->sn_queue);
1556 	/*
1557 	 * Make a snapshot of the subscriber queue and the main event queue.
1558 	 */
1559 	if (sdp != NULL) {
1560 		ev = NULL;
1561 		while ((ev = evch_evq_evnext(sdp->sd_queue, ev)) != NULL) {
1562 			(void) evch_evq_pub(snp->sn_queue, ev, EVCH_SLEEP);
1563 		}
1564 	}
1565 	ev = NULL;
1566 	while ((ev = evch_evq_evnext(chp->ch_queue, ev)) != NULL) {
1567 		(void) evch_evq_pub(snp->sn_queue, ev, EVCH_SLEEP);
1568 	}
1569 	snp->sn_nxtev = NULL;
1570 	/*
1571 	 * Restart main and subscriber queue if previously stopped
1572 	 */
1573 	if (sdp != NULL && psqstat == 0)
1574 		evch_evq_continue(sdp->sd_queue);
1575 	if (pmqstat == 0)
1576 		evch_evq_continue(chp->ch_queue);
1577 	mutex_exit(&chp->ch_mutex);
1578 	return (snp);
1579 }
1580 
1581 /*
1582  * Free all resources of the event queue snapshot. In case of panic
1583  * context snp must be NULL and no resources need to be free'ed.
1584  */
1585 static void
1586 evch_chrdevent_fini(evchanq_t *snp)
1587 {
1588 	if (snp != NULL) {
1589 		evch_evq_destroy(snp->sn_queue);
1590 		kmem_free(snp, sizeof (evchanq_t));
1591 	}
1592 }
1593 
1594 /*
1595  * Get address of next event from an event channel.
1596  * This function might be called in a panic context. In that case
1597  * no resources will be allocated and no locks grabbed.
1598  * In normal operation context a snapshot of the event queues of the
1599  * specified event channel will be taken.
1600  */
1601 static sysevent_impl_t *
1602 evch_chgetnextev(evchanq_t *snp)
1603 {
1604 	if (panicstr != NULL) {
1605 		if (evch_chan == NULL)
1606 			return (NULL);
1607 		if (evch_subq != NULL) {
1608 			/*
1609 			 * We have a subscriber queue. Traverse this queue
1610 			 * first.
1611 			 */
1612 			if ((evch_curev = (sysevent_impl_t *)
1613 			    evch_evq_evnext(evch_subq, evch_curev)) != NULL) {
1614 				return (evch_curev);
1615 			} else {
1616 				/*
1617 				 * All subscriber events traversed. evch_subq
1618 				 * == NULL indicates to take the main event
1619 				 * queue now.
1620 				 */
1621 				evch_subq = NULL;
1622 			}
1623 		}
1624 		/*
1625 		 * Traverse the main event queue.
1626 		 */
1627 		if ((evch_curev = (sysevent_impl_t *)
1628 		    evch_evq_evnext(evch_chan->ch_queue, evch_curev)) ==
1629 		    NULL) {
1630 			evch_chan = NULL;
1631 		}
1632 		return (evch_curev);
1633 	}
1634 	ASSERT(snp != NULL);
1635 	snp->sn_nxtev = (sysevent_impl_t *)evch_evq_evnext(snp->sn_queue,
1636 	    snp->sn_nxtev);
1637 	return (snp->sn_nxtev);
1638 }
1639 
1640 /*
1641  * The functions below build up the interface for the kernel to bind/unbind,
1642  * subscribe/unsubscribe and publish to event channels. It consists of the
1643  * following functions:
1644  *
1645  * sysevent_evc_bind	    - Bind to a channel. Create a channel if required
1646  * sysevent_evc_unbind	    - Unbind from a channel. Destroy ch. if last unbind
1647  * sysevent_evc_subscribe   - Subscribe to events from a channel
1648  * sysevent_evc_unsubscribe - Unsubscribe from an event class
1649  * sysevent_evc_publish	    - Publish an event to an event channel
1650  * sysevent_evc_control	    - Various control operation on event channel
1651  *
1652  * The function below are for evaluating a sysevent:
1653  *
1654  * sysevent_get_class_name  - Get pointer to event class string
1655  * sysevent_get_subclass_name - Get pointer to event subclass string
1656  * sysevent_get_seq	    - Get unique event sequence number
1657  * sysevent_get_time	    - Get hrestime of event publish
1658  * sysevent_get_size	    - Get size of event structure
1659  * sysevent_get_pub	    - Get publisher string
1660  * sysevent_get_attr_list   - Get copy of attribute list
1661  *
1662  * The following interfaces represent stability level project privat
1663  * and allow to save the events of an event channel even in a panic case.
1664  *
1665  * sysevent_evc_walk_init   - Take a snapshot of the events in a channel
1666  * sysevent_evc_walk_step   - Read next event from snapshot
1667  * sysevent_evc_walk_fini   - Free resources from event channel snapshot
1668  * sysevent_evc_event_attr  - Get event payload address and size
1669  */
1670 /*
1671  * allocate sysevent structure with optional space for attributes
1672  */
1673 static sysevent_impl_t *
1674 sysevent_evc_alloc(const char *class, const char *subclass, const char *pub,
1675     size_t pub_sz, size_t atsz, uint32_t flag)
1676 {
1677 	int		payload_sz;
1678 	int		class_sz, subclass_sz;
1679 	int 		aligned_class_sz, aligned_subclass_sz, aligned_pub_sz;
1680 	sysevent_impl_t	*ev;
1681 
1682 	/*
1683 	 * Calculate and reserve space for the class, subclass and
1684 	 * publisher strings in the event buffer
1685 	 */
1686 	class_sz = strlen(class) + 1;
1687 	subclass_sz = strlen(subclass) + 1;
1688 
1689 	ASSERT((class_sz <= MAX_CLASS_LEN) && (subclass_sz <=
1690 	    MAX_SUBCLASS_LEN) && (pub_sz <= MAX_PUB_LEN));
1691 
1692 	/* String sizes must be 64-bit aligned in the event buffer */
1693 	aligned_class_sz = SE_ALIGN(class_sz);
1694 	aligned_subclass_sz = SE_ALIGN(subclass_sz);
1695 	aligned_pub_sz = SE_ALIGN(pub_sz);
1696 
1697 	/*
1698 	 * Calculate payload size. Consider the space needed for alignment
1699 	 * and subtract the size of the uint64_t placeholder variables of
1700 	 * sysevent_impl_t.
1701 	 */
1702 	payload_sz = (aligned_class_sz - sizeof (uint64_t)) +
1703 	    (aligned_subclass_sz - sizeof (uint64_t)) +
1704 	    (aligned_pub_sz - sizeof (uint64_t)) - sizeof (uint64_t) +
1705 	    atsz;
1706 
1707 	/*
1708 	 * Allocate event buffer plus additional payload overhead
1709 	 */
1710 	if ((ev = evch_evq_evzalloc(sizeof (sysevent_impl_t) +
1711 	    payload_sz, flag)) == NULL) {
1712 		return (NULL);
1713 	}
1714 
1715 	/* Initialize the event buffer data */
1716 	SE_VERSION(ev) = SYS_EVENT_VERSION;
1717 	bcopy(class, SE_CLASS_NAME(ev), class_sz);
1718 
1719 	SE_SUBCLASS_OFF(ev) = SE_ALIGN(offsetof(sysevent_impl_t,
1720 	    se_class_name)) + aligned_class_sz;
1721 	bcopy(subclass, SE_SUBCLASS_NAME(ev), subclass_sz);
1722 
1723 	SE_PUB_OFF(ev) = SE_SUBCLASS_OFF(ev) + aligned_subclass_sz;
1724 	bcopy(pub, SE_PUB_NAME(ev), pub_sz);
1725 
1726 	SE_ATTR_PTR(ev) = (uint64_t)0;
1727 	SE_PAYLOAD_SZ(ev) = payload_sz;
1728 
1729 	return (ev);
1730 }
1731 
1732 /*
1733  * Initialize event channel handling queues.
1734  */
1735 void
1736 sysevent_evc_init()
1737 {
1738 	evch_chinit();
1739 }
1740 
1741 /*
1742  * Second initialization step: create threads, if event channels are already
1743  * created
1744  */
1745 void
1746 sysevent_evc_thrinit()
1747 {
1748 	evch_chinitthr();
1749 }
1750 
1751 int
1752 sysevent_evc_bind(const char *ch_name, evchan_t **scpp, uint32_t flags)
1753 {
1754 	ASSERT(ch_name != NULL && scpp != NULL);
1755 	ASSERT((flags & ~EVCH_B_FLAGS) == 0);
1756 	return (evch_chbind(ch_name, (evch_bind_t **)scpp, flags));
1757 }
1758 
1759 void
1760 sysevent_evc_unbind(evchan_t *scp)
1761 {
1762 	evch_bind_t *bp = (evch_bind_t *)scp;
1763 
1764 	ASSERT(scp != NULL);
1765 	evch_chunsubscribe(bp, NULL, 0);
1766 	evch_chunbind(bp);
1767 }
1768 
1769 int
1770 sysevent_evc_subscribe(evchan_t *scp, const char *sid, const char *class,
1771     int (*callb)(sysevent_t *ev, void *cookie),
1772     void *cookie, uint32_t flags)
1773 {
1774 	ASSERT(scp != NULL && sid != NULL && class != NULL && callb != NULL);
1775 	ASSERT(flags == 0);
1776 	if (strlen(sid) > MAX_SUBID_LEN) {
1777 		return (EINVAL);
1778 	}
1779 	if (strcmp(class, EC_ALL) == 0) {
1780 		class = NULL;
1781 	}
1782 	return (evch_chsubscribe((evch_bind_t *)scp, EVCH_DELKERN, sid, class,
1783 	    (void *)callb, cookie, 0, 0));
1784 }
1785 
1786 void
1787 sysevent_evc_unsubscribe(evchan_t *scp, const char *sid)
1788 {
1789 	ASSERT(scp != NULL && sid != NULL);
1790 	if (strcmp(sid, EVCH_ALLSUB) == 0) {
1791 		sid = NULL;
1792 	}
1793 	evch_chunsubscribe((evch_bind_t *)scp, sid, 0);
1794 }
1795 
1796 /*
1797  * Publish kernel event. Returns 0 on success, error code else.
1798  * Optional attribute data is packed into the event structure.
1799  */
1800 int
1801 sysevent_evc_publish(evchan_t *scp, const char *class, const char *subclass,
1802     const char *vendor, const char *pubs, nvlist_t *attr, uint32_t flags)
1803 {
1804 	sysevent_impl_t	*evp;
1805 	char		pub[MAX_PUB_LEN];
1806 	int		pub_sz;		/* includes terminating 0 */
1807 	int		km_flags;
1808 	size_t		asz = 0;
1809 	uint64_t	attr_offset;
1810 	caddr_t		patt;
1811 	int		err;
1812 
1813 	ASSERT(scp != NULL && class != NULL && subclass != NULL &&
1814 	    vendor != NULL && pubs != NULL);
1815 
1816 	ASSERT((flags & ~(EVCH_SLEEP | EVCH_NOSLEEP | EVCH_TRYHARD |
1817 	    EVCH_QWAIT)) == 0);
1818 
1819 	km_flags = flags & (EVCH_SLEEP | EVCH_NOSLEEP | EVCH_TRYHARD);
1820 	ASSERT(km_flags == EVCH_SLEEP || km_flags == EVCH_NOSLEEP ||
1821 	    km_flags == EVCH_TRYHARD);
1822 
1823 	pub_sz = snprintf(pub, MAX_PUB_LEN, "%s:kern:%s", vendor, pubs) + 1;
1824 	if (pub_sz > MAX_PUB_LEN)
1825 		return (EINVAL);
1826 
1827 	if (attr != NULL) {
1828 		if ((err = nvlist_size(attr, &asz, NV_ENCODE_NATIVE)) != 0) {
1829 			return (err);
1830 		}
1831 	}
1832 	evp = sysevent_evc_alloc(class, subclass, pub, pub_sz, asz, km_flags);
1833 	if (evp == NULL) {
1834 		return (ENOMEM);
1835 	}
1836 	if (attr != NULL) {
1837 		/*
1838 		 * Pack attributes into event buffer. Event buffer already
1839 		 * has enough room for the packed nvlist.
1840 		 */
1841 		attr_offset = SE_ATTR_OFF(evp);
1842 		patt = (caddr_t)evp + attr_offset;
1843 
1844 		err = nvlist_pack(attr, &patt, &asz, NV_ENCODE_NATIVE,
1845 		    km_flags & EVCH_SLEEP ? KM_SLEEP : KM_NOSLEEP);
1846 
1847 		ASSERT(err != ENOMEM);
1848 
1849 		if (err != 0) {
1850 			return (EINVAL);
1851 		}
1852 
1853 		evp->seh_attr_off = attr_offset;
1854 		SE_FLAG(evp) = SE_PACKED_BUF;
1855 	}
1856 	return (evch_chpublish((evch_bind_t *)scp, evp, flags));
1857 }
1858 
1859 int
1860 sysevent_evc_control(evchan_t *scp, int cmd, ...)
1861 {
1862 	va_list		ap;
1863 	evch_chan_t	*chp = ((evch_bind_t *)scp)->bd_channel;
1864 	uint32_t	*chlenp;
1865 	uint32_t	chlen;
1866 	uint32_t	ochlen;
1867 	int		rc = 0;
1868 
1869 	if (scp == NULL) {
1870 		return (EINVAL);
1871 	}
1872 
1873 	va_start(ap, cmd);
1874 	mutex_enter(&chp->ch_mutex);
1875 	switch (cmd) {
1876 	case EVCH_GET_CHAN_LEN:
1877 		chlenp = va_arg(ap, uint32_t *);
1878 		*chlenp = chp->ch_maxev;
1879 		break;
1880 	case EVCH_SET_CHAN_LEN:
1881 		chlen = va_arg(ap, uint32_t);
1882 		ochlen = chp->ch_maxev;
1883 		chp->ch_maxev = min(chlen, evch_events_max);
1884 		if (ochlen < chp->ch_maxev) {
1885 			cv_signal(&chp->ch_pubcv);
1886 		}
1887 		break;
1888 	case EVCH_GET_CHAN_LEN_MAX:
1889 		*va_arg(ap, uint32_t *) = evch_events_max;
1890 		break;
1891 	default:
1892 		rc = EINVAL;
1893 	}
1894 
1895 	mutex_exit(&chp->ch_mutex);
1896 	va_end(ap);
1897 	return (rc);
1898 }
1899 
1900 /*
1901  * Project private interface to take a snapshot of all events of the
1902  * specified event channel. Argument subscr may be a subscriber id, the empty
1903  * string "", or NULL. The empty string indicates that no subscriber is
1904  * selected, for example if a previous subscriber died. sysevent_evc_walk_next()
1905  * will deliver events from the main event queue in this case. If subscr is
1906  * NULL, the subscriber with the EVCH_SUB_DUMP flag set (subd->sd_dump != 0)
1907  * will be selected.
1908  *
1909  * In panic case this function returns NULL. This is legal. The NULL has
1910  * to be delivered to sysevent_evc_walk_step() and sysevent_evc_walk_fini().
1911  */
1912 evchanq_t *
1913 sysevent_evc_walk_init(evchan_t *scp, char *subscr)
1914 {
1915 	if (panicstr != NULL && scp == NULL)
1916 		return (NULL);
1917 	ASSERT(scp != NULL);
1918 	return (evch_chrdevent_init(((evch_bind_t *)scp)->bd_channel, subscr));
1919 }
1920 
1921 /*
1922  * Project private interface to read events from a previously taken
1923  * snapshot (with sysevent_evc_walk_init). In case of panic events
1924  * are retrieved directly from the channel data structures. No resources
1925  * are allocated and no mutexes are grabbed in panic context.
1926  */
1927 sysevent_t *
1928 sysevent_evc_walk_step(evchanq_t *evcq)
1929 {
1930 	return ((sysevent_t *)evch_chgetnextev(evcq));
1931 }
1932 
1933 /*
1934  * Project private interface to free a previously taken snapshot.
1935  */
1936 void
1937 sysevent_evc_walk_fini(evchanq_t *evcq)
1938 {
1939 	evch_chrdevent_fini(evcq);
1940 }
1941 
1942 /*
1943  * Get address and size of an event payload. Returns NULL when no
1944  * payload present.
1945  */
1946 char *
1947 sysevent_evc_event_attr(sysevent_t *ev, size_t *plsize)
1948 {
1949 	char	*attrp;
1950 	size_t	aoff;
1951 	size_t	asz;
1952 
1953 	aoff = SE_ATTR_OFF(ev);
1954 	attrp = (char *)ev + aoff;
1955 	asz = *plsize = SE_SIZE(ev) - aoff;
1956 	return (asz ? attrp : NULL);
1957 }
1958 
1959 /*
1960  * sysevent_get_class_name - Get class name string
1961  */
1962 char *
1963 sysevent_get_class_name(sysevent_t *ev)
1964 {
1965 	return (SE_CLASS_NAME(ev));
1966 }
1967 
1968 /*
1969  * sysevent_get_subclass_name - Get subclass name string
1970  */
1971 char *
1972 sysevent_get_subclass_name(sysevent_t *ev)
1973 {
1974 	return (SE_SUBCLASS_NAME(ev));
1975 }
1976 
1977 /*
1978  * sysevent_get_seq - Get event sequence id
1979  */
1980 uint64_t
1981 sysevent_get_seq(sysevent_t *ev)
1982 {
1983 	return (SE_SEQ(ev));
1984 }
1985 
1986 /*
1987  * sysevent_get_time - Get event timestamp
1988  */
1989 void
1990 sysevent_get_time(sysevent_t *ev, hrtime_t *etime)
1991 {
1992 	*etime = SE_TIME(ev);
1993 }
1994 
1995 /*
1996  * sysevent_get_size - Get event buffer size
1997  */
1998 size_t
1999 sysevent_get_size(sysevent_t *ev)
2000 {
2001 	return ((size_t)SE_SIZE(ev));
2002 }
2003 
2004 /*
2005  * sysevent_get_pub - Get publisher name string
2006  */
2007 char *
2008 sysevent_get_pub(sysevent_t *ev)
2009 {
2010 	return (SE_PUB_NAME(ev));
2011 }
2012 
2013 /*
2014  * sysevent_get_attr_list - stores address of a copy of the attribute list
2015  * associated with the given sysevent buffer. The list must be freed by the
2016  * caller.
2017  */
2018 int
2019 sysevent_get_attr_list(sysevent_t *ev, nvlist_t **nvlist)
2020 {
2021 	int		error;
2022 	caddr_t		attr;
2023 	size_t		attr_len;
2024 	uint64_t	attr_offset;
2025 
2026 	*nvlist = NULL;
2027 	if (SE_FLAG(ev) != SE_PACKED_BUF) {
2028 		return (EINVAL);
2029 	}
2030 	attr_offset = SE_ATTR_OFF(ev);
2031 	if (SE_SIZE(ev) == attr_offset) {
2032 		return (EINVAL);
2033 	}
2034 
2035 	/* unpack nvlist */
2036 	attr = (caddr_t)ev + attr_offset;
2037 	attr_len = SE_SIZE(ev) - attr_offset;
2038 	if ((error = nvlist_unpack(attr, attr_len, nvlist, 0)) != 0) {
2039 		error = error != ENOMEM ? EINVAL : error;
2040 		return (error);
2041 	}
2042 	return (0);
2043 }
2044 
2045 /*
2046  * Functions called by the sysevent driver for general purpose event channels
2047  *
2048  * evch_usrchanopen	- Create/Bind to an event channel
2049  * evch_usrchanclose	- Unbind/Destroy event channel
2050  * evch_usrallocev	- Allocate event data structure
2051  * evch_usrfreeev	- Free event data structure
2052  * evch_usrpostevent	- Publish event
2053  * evch_usrsubscribe	- Subscribe (register callback function)
2054  * evch_usrunsubscribe	- Unsubscribe
2055  * evch_usrcontrol_set	- Set channel properties
2056  * evch_usrcontrol_get	- Get channel properties
2057  * evch_usrgetchnames	- Get list of channel names
2058  * evch_usrgetchdata	- Get data of an event channel
2059  */
2060 evchan_t *
2061 evch_usrchanopen(const char *name, uint32_t flags, int *err)
2062 {
2063 	evch_bind_t *bp = NULL;
2064 
2065 	*err = evch_chbind(name, &bp, flags);
2066 	return ((evchan_t *)bp);
2067 }
2068 
2069 /*
2070  * Unbind from the channel.
2071  */
2072 void
2073 evch_usrchanclose(evchan_t *cbp)
2074 {
2075 	evch_chunbind((evch_bind_t *)cbp);
2076 }
2077 
2078 /*
2079  * Allocates log_evch_eventq_t structure but returns the pointer of the embedded
2080  * sysevent_impl_t structure as the opaque sysevent_t * data type
2081  */
2082 sysevent_impl_t *
2083 evch_usrallocev(size_t evsize, uint32_t flags)
2084 {
2085 	return ((sysevent_impl_t *)evch_evq_evzalloc(evsize, flags));
2086 }
2087 
2088 /*
2089  * Free evch_eventq_t structure
2090  */
2091 void
2092 evch_usrfreeev(sysevent_impl_t *ev)
2093 {
2094 	evch_evq_evfree((void *)ev);
2095 }
2096 
2097 /*
2098  * Posts an event to the given channel. The event structure has to be
2099  * allocated by evch_usrallocev(). Returns zero on success and an error
2100  * code else. Attributes have to be packed and included in the event structure.
2101  *
2102  */
2103 int
2104 evch_usrpostevent(evchan_t *bp, sysevent_impl_t *ev, uint32_t flags)
2105 {
2106 	return (evch_chpublish((evch_bind_t *)bp, ev, flags));
2107 }
2108 
2109 /*
2110  * Subscribe function for user land subscriptions
2111  */
2112 int
2113 evch_usrsubscribe(evchan_t *bp, const char *sid, const char *class,
2114     int d, uint32_t flags)
2115 {
2116 	door_handle_t	dh = door_ki_lookup(d);
2117 	int		rv;
2118 
2119 	if (dh == NULL) {
2120 		return (EINVAL);
2121 	}
2122 	if ((rv = evch_chsubscribe((evch_bind_t *)bp, EVCH_DELDOOR, sid, class,
2123 	    (void *)dh, NULL, flags, curproc->p_pid)) != 0) {
2124 		door_ki_rele(dh);
2125 	}
2126 	return (rv);
2127 }
2128 
2129 /*
2130  * Flag can be EVCH_SUB_KEEP or 0. EVCH_SUB_KEEP preserves persistent
2131  * subscribers
2132  */
2133 void
2134 evch_usrunsubscribe(evchan_t *bp, const char *subid, uint32_t flags)
2135 {
2136 	evch_chunsubscribe((evch_bind_t *)bp, subid, flags);
2137 }
2138 
2139 /*ARGSUSED*/
2140 int
2141 evch_usrcontrol_set(evchan_t *bp, int cmd, uint32_t value)
2142 {
2143 	evch_chan_t	*chp = ((evch_bind_t *)bp)->bd_channel;
2144 	uid_t		uid = crgetuid(curthread->t_cred);
2145 	int		rc = 0;
2146 
2147 	mutex_enter(&chp->ch_mutex);
2148 	switch (cmd) {
2149 	case EVCH_SET_CHAN_LEN:
2150 		if (uid && uid != chp->ch_uid) {
2151 			rc = EACCES;
2152 			break;
2153 		}
2154 		chp->ch_maxev = min(value, evch_events_max);
2155 		break;
2156 	default:
2157 		rc = EINVAL;
2158 	}
2159 	mutex_exit(&chp->ch_mutex);
2160 	return (rc);
2161 }
2162 
2163 /*ARGSUSED*/
2164 int
2165 evch_usrcontrol_get(evchan_t *bp, int cmd, uint32_t *value)
2166 {
2167 	evch_chan_t	*chp = ((evch_bind_t *)bp)->bd_channel;
2168 	int		rc = 0;
2169 
2170 	mutex_enter(&chp->ch_mutex);
2171 	switch (cmd) {
2172 	case EVCH_GET_CHAN_LEN:
2173 		*value = chp->ch_maxev;
2174 		break;
2175 	case EVCH_GET_CHAN_LEN_MAX:
2176 		*value = evch_events_max;
2177 		break;
2178 	default:
2179 		rc = EINVAL;
2180 	}
2181 	mutex_exit(&chp->ch_mutex);
2182 	return (rc);
2183 }
2184 
2185 int
2186 evch_usrgetchnames(char *buf, size_t size)
2187 {
2188 	return (evch_chgetnames(buf, size));
2189 }
2190 
2191 int
2192 evch_usrgetchdata(char *chname, void *buf, size_t size)
2193 {
2194 	return (evch_chgetchdata(chname, buf, size));
2195 }
2196