xref: /titanic_52/usr/src/uts/common/os/evchannels.c (revision 1a7c1b724419d3cb5fa6eea75123c6b2060ba31b)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 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 /*
30  * This file contains the source of the general purpose event channel extension
31  * to the sysevent framework. This implementation is made up mainly of four
32  * layers of functionality: the event queues (evch_evq_*()), the handling of
33  * channels (evch_ch*()), the kernel interface (sysevent_evc_*()) and the
34  * interface for the sysevent pseudo driver (evch_usr*()).
35  * Libsysevent.so uses the pseudo driver sysevent's ioctl to access the event
36  * channel extensions. The driver in turn uses the evch_usr*() functions below.
37  *
38  * The interfaces for user land and kernel are declared in sys/sysevent.h
39  * Internal data structures for event channels are defined in
40  * sys/sysevent_impl.h.
41  *
42  * The basic data structure for an event channel is of type evch_chan_t.
43  * All channels are maintained by a list named evch_list. The list head
44  * is of type evch_dlist_t.
45  */
46 
47 #include <sys/types.h>
48 #include <sys/errno.h>
49 #include <sys/stropts.h>
50 #include <sys/debug.h>
51 #include <sys/ddi.h>
52 #include <sys/vmem.h>
53 #include <sys/cmn_err.h>
54 #include <sys/callb.h>
55 #include <sys/sysevent.h>
56 #include <sys/sysevent_impl.h>
57 #include <sys/sysmacros.h>
58 #include <sys/disp.h>
59 #include <sys/atomic.h>
60 #include <sys/door.h>
61 #include <sys/zone.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;
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 		bzero(evp, rsize);
725 		evp->ge_size = evsize;
726 	} else {
727 		evp = kmem_alloc(rsize, flag & EVCH_NOSLEEP ? KM_NOSLEEP :
728 		    KM_SLEEP);
729 		bzero(evp, rsize);
730 		evp->ge_size = rsize;
731 	}
732 
733 	if (evp) {
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 	mutex_enter(&chp->ch_pubmx);
1343 	if (chp->ch_nevents >= chp->ch_maxev) {
1344 		if (!(flags & EVCH_QWAIT)) {
1345 			evch_evq_evfree(ev);
1346 			mutex_exit(&chp->ch_pubmx);
1347 			return (EAGAIN);
1348 		} else {
1349 			while (chp->ch_nevents >= chp->ch_maxev) {
1350 				if (cv_wait_sig(&chp->ch_pubcv,
1351 				    &chp->ch_pubmx) == 0) {
1352 
1353 					/* Got Signal, return EINTR */
1354 					evch_evq_evfree(ev);
1355 					mutex_exit(&chp->ch_pubmx);
1356 					return (EINTR);
1357 				}
1358 			}
1359 		}
1360 	}
1361 	chp->ch_nevents++;
1362 	mutex_exit(&chp->ch_pubmx);
1363 	SE_TIME(ev) = gethrtime();
1364 	SE_SEQ(ev) = log_sysevent_new_id();
1365 	/*
1366 	 * Add the destructor function to the event structure, now that the
1367 	 * event is accounted for. The only task of the descructor is to
1368 	 * decrement the channel event count. The evq_*() routines (including
1369 	 * the event delivery thread) do not have knowledge of the channel
1370 	 * data. So the anonymous destructor handles the channel data for it.
1371 	 */
1372 	evch_evq_evadd_dest(ev, evch_destr_event, (void *)chp);
1373 	return (evch_evq_pub(chp->ch_queue, ev, flags) == 0 ? 0 : EAGAIN);
1374 }
1375 
1376 /*
1377  * Fills a buffer consecutive with the names of all available channels.
1378  * Returns the length of all name strings or -1 if buffer size was unsufficient.
1379  */
1380 static int
1381 evch_chgetnames(char *buf, size_t size)
1382 {
1383 	struct evch_globals *eg;
1384 	int		len = 0;
1385 	char		*addr = buf;
1386 	int		max = size;
1387 	evch_chan_t	*chp;
1388 
1389 	eg = zone_getspecific(evch_zone_key, curproc->p_zone);
1390 	ASSERT(eg != NULL);
1391 
1392 	mutex_enter(&eg->evch_list_lock);
1393 	for (chp = evch_dl_next(&eg->evch_list, NULL); chp != NULL;
1394 	    chp = evch_dl_next(&eg->evch_list, chp)) {
1395 		len += chp->ch_namelen;
1396 		if (len >= max) {
1397 			mutex_exit(&eg->evch_list_lock);
1398 			return (-1);
1399 		}
1400 		bcopy(chp->ch_name, addr, chp->ch_namelen);
1401 		addr += chp->ch_namelen;
1402 	}
1403 	mutex_exit(&eg->evch_list_lock);
1404 	addr[0] = 0;
1405 	return (len + 1);
1406 }
1407 
1408 /*
1409  * Fills the data of one channel and all subscribers of that channel into
1410  * a buffer. Returns -1 if the channel name is invalid and 0 on buffer overflow.
1411  */
1412 static int
1413 evch_chgetchdata(char *chname, void *buf, size_t size)
1414 {
1415 	struct evch_globals *eg;
1416 	char		*cpaddr;
1417 	int		bufmax;
1418 	int		buflen;
1419 	evch_chan_t	*chp;
1420 	sev_chinfo_t	*p = (sev_chinfo_t *)buf;
1421 	int		chdlen;
1422 	evch_subd_t	*sdp;
1423 	sev_subinfo_t	*subp;
1424 	int		idlen;
1425 	int		len;
1426 
1427 	eg = zone_getspecific(evch_zone_key, curproc->p_zone);
1428 	ASSERT(eg != NULL);
1429 
1430 	mutex_enter(&eg->evch_list_lock);
1431 	chp = (evch_chan_t *)evch_dl_search(&eg->evch_list, evch_namecmp,
1432 	    chname);
1433 	if (chp == NULL) {
1434 		mutex_exit(&eg->evch_list_lock);
1435 		return (-1);
1436 	}
1437 	chdlen = offsetof(sev_chinfo_t, cd_subinfo);
1438 	if (size < chdlen) {
1439 		mutex_exit(&eg->evch_list_lock);
1440 		return (0);
1441 	}
1442 	p->cd_version = 0;
1443 	p->cd_suboffs = chdlen;
1444 	p->cd_uid = chp->ch_uid;
1445 	p->cd_gid = chp->ch_gid;
1446 	p->cd_perms = 0;
1447 	p->cd_ctime = chp->ch_ctime;
1448 	p->cd_maxev = chp->ch_maxev;
1449 	p->cd_evhwm = EVCH_EVQ_HIGHWM(chp->ch_queue);
1450 	p->cd_nevents = EVCH_EVQ_EVCOUNT(chp->ch_queue);
1451 	p->cd_maxsub = chp->ch_maxsubscr;
1452 	p->cd_nsub = evch_dl_getnum(&chp->ch_subscr);
1453 	p->cd_maxbinds = chp->ch_maxbinds;
1454 	p->cd_nbinds = chp->ch_bindings;
1455 	p->cd_holdpend = chp->ch_holdpend;
1456 	p->cd_limev = evch_events_max;
1457 	cpaddr = (char *)p + chdlen;
1458 	bufmax = size - chdlen;
1459 	buflen = 0;
1460 
1461 	for (sdp = evch_dl_next(&chp->ch_subscr, NULL); sdp != NULL;
1462 	    sdp = evch_dl_next(&chp->ch_subscr, sdp)) {
1463 		idlen = strlen(sdp->sd_ident) + 1;
1464 		len = SE_ALIGN(offsetof(sev_subinfo_t, sb_strings) + idlen +
1465 		    sdp->sd_clnsize);
1466 		buflen += len;
1467 		if (buflen >= bufmax) {
1468 			mutex_exit(&eg->evch_list_lock);
1469 			return (0);
1470 		}
1471 		subp = (sev_subinfo_t *)cpaddr;
1472 		subp->sb_nextoff = len;
1473 		subp->sb_stroff = offsetof(sev_subinfo_t, sb_strings);
1474 		if (sdp->sd_classname) {
1475 			bcopy(sdp->sd_classname, subp->sb_strings + idlen,
1476 			    sdp->sd_clnsize);
1477 			subp->sb_clnamoff = idlen;
1478 		} else {
1479 			subp->sb_clnamoff = idlen - 1;
1480 		}
1481 		subp->sb_pid = sdp->sd_pid;
1482 		subp->sb_nevents = EVCH_EVQ_EVCOUNT(sdp->sd_queue);
1483 		subp->sb_evhwm = EVCH_EVQ_HIGHWM(sdp->sd_queue);
1484 		subp->sb_persist = sdp->sd_persist;
1485 		subp->sb_status = evch_evq_status(sdp->sd_queue);
1486 		subp->sb_active = sdp->sd_active;
1487 		subp->sb_dump = sdp->sd_dump;
1488 		bcopy(sdp->sd_ident, subp->sb_strings, idlen);
1489 		cpaddr += len;
1490 	}
1491 	mutex_exit(&eg->evch_list_lock);
1492 	return (chdlen + buflen);
1493 }
1494 
1495 /*
1496  * Init iteration of all events of a channel. This function creates a new
1497  * event queue and puts all events from the channel into that queue.
1498  * Subsequent calls to evch_chgetnextev will deliver the events from that
1499  * queue. Only one thread per channel is allowed to read through the events.
1500  * Returns 0 on success and 1 if there is already someone reading the
1501  * events.
1502  * If argument subid == NULL, we look for a subscriber which has
1503  * flag EVCH_SUB_DUMP set.
1504  */
1505 /*
1506  * Static variables that are used to traverse events of a channel in panic case.
1507  */
1508 static evch_chan_t	*evch_chan;
1509 static evch_eventq_t	*evch_subq;
1510 static sysevent_impl_t	*evch_curev;
1511 
1512 static evchanq_t *
1513 evch_chrdevent_init(evch_chan_t *chp, char *subid)
1514 {
1515 	evch_subd_t	*sdp;
1516 	void		*ev;
1517 	int		pmqstat;	/* Prev status of main queue */
1518 	int		psqstat;	/* Prev status of subscriber queue */
1519 	evchanq_t	*snp;		/* Pointer to q with snapshot of ev */
1520 	compare_f	compfunc;
1521 
1522 	compfunc = subid == NULL ? evch_dumpflgcmp : evch_subidcmp;
1523 	if (panicstr != NULL) {
1524 		evch_chan = chp;
1525 		evch_subq = NULL;
1526 		evch_curev = NULL;
1527 		if ((sdp = (evch_subd_t *)evch_dl_search(&chp->ch_subscr,
1528 		    compfunc, subid)) != NULL) {
1529 			evch_subq = sdp->sd_queue;
1530 		}
1531 		return (NULL);
1532 	}
1533 	mutex_enter(&chp->ch_mutex);
1534 	sdp = (evch_subd_t *)evch_dl_search(&chp->ch_subscr, compfunc, subid);
1535 	/*
1536 	 * Stop main event queue and subscriber queue if not already
1537 	 * in stop mode.
1538 	 */
1539 	pmqstat = evch_evq_status(chp->ch_queue);
1540 	if (pmqstat == 0)
1541 		evch_evq_stop(chp->ch_queue);
1542 	if (sdp != NULL) {
1543 		psqstat = evch_evq_status(sdp->sd_queue);
1544 		if (psqstat == 0)
1545 			evch_evq_stop(sdp->sd_queue);
1546 	}
1547 	/*
1548 	 * Create event queue to make a snapshot of all events in the
1549 	 * channel.
1550 	 */
1551 	snp = kmem_alloc(sizeof (evchanq_t), KM_SLEEP);
1552 	snp->sn_queue = evch_evq_create();
1553 	evch_evq_stop(snp->sn_queue);
1554 	/*
1555 	 * Make a snapshot of the subscriber queue and the main event queue.
1556 	 */
1557 	if (sdp != NULL) {
1558 		ev = NULL;
1559 		while ((ev = evch_evq_evnext(sdp->sd_queue, ev)) != NULL) {
1560 			(void) evch_evq_pub(snp->sn_queue, ev, EVCH_SLEEP);
1561 		}
1562 	}
1563 	ev = NULL;
1564 	while ((ev = evch_evq_evnext(chp->ch_queue, ev)) != NULL) {
1565 		(void) evch_evq_pub(snp->sn_queue, ev, EVCH_SLEEP);
1566 	}
1567 	snp->sn_nxtev = NULL;
1568 	/*
1569 	 * Restart main and subscriber queue if previously stopped
1570 	 */
1571 	if (sdp != NULL && psqstat == 0)
1572 		evch_evq_continue(sdp->sd_queue);
1573 	if (pmqstat == 0)
1574 		evch_evq_continue(chp->ch_queue);
1575 	mutex_exit(&chp->ch_mutex);
1576 	return (snp);
1577 }
1578 
1579 /*
1580  * Free all resources of the event queue snapshot. In case of panic
1581  * context snp must be NULL and no resources need to be free'ed.
1582  */
1583 static void
1584 evch_chrdevent_fini(evchanq_t *snp)
1585 {
1586 	if (snp != NULL) {
1587 		evch_evq_destroy(snp->sn_queue);
1588 		kmem_free(snp, sizeof (evchanq_t));
1589 	}
1590 }
1591 
1592 /*
1593  * Get address of next event from an event channel.
1594  * This function might be called in a panic context. In that case
1595  * no resources will be allocated and no locks grabbed.
1596  * In normal operation context a snapshot of the event queues of the
1597  * specified event channel will be taken.
1598  */
1599 static sysevent_impl_t *
1600 evch_chgetnextev(evchanq_t *snp)
1601 {
1602 	if (panicstr != NULL) {
1603 		if (evch_chan == NULL)
1604 			return (NULL);
1605 		if (evch_subq != NULL) {
1606 			/*
1607 			 * We have a subscriber queue. Traverse this queue
1608 			 * first.
1609 			 */
1610 			if ((evch_curev = (sysevent_impl_t *)
1611 			    evch_evq_evnext(evch_subq, evch_curev)) != NULL) {
1612 				return (evch_curev);
1613 			} else {
1614 				/*
1615 				 * All subscriber events traversed. evch_subq
1616 				 * == NULL indicates to take the main event
1617 				 * queue now.
1618 				 */
1619 				evch_subq = NULL;
1620 			}
1621 		}
1622 		/*
1623 		 * Traverse the main event queue.
1624 		 */
1625 		if ((evch_curev = (sysevent_impl_t *)
1626 		    evch_evq_evnext(evch_chan->ch_queue, evch_curev)) ==
1627 		    NULL) {
1628 			evch_chan = NULL;
1629 		}
1630 		return (evch_curev);
1631 	}
1632 	ASSERT(snp != NULL);
1633 	snp->sn_nxtev = (sysevent_impl_t *)evch_evq_evnext(snp->sn_queue,
1634 	    snp->sn_nxtev);
1635 	return (snp->sn_nxtev);
1636 }
1637 
1638 /*
1639  * The functions below build up the interface for the kernel to bind/unbind,
1640  * subscribe/unsubscribe and publish to event channels. It consists of the
1641  * following functions:
1642  *
1643  * sysevent_evc_bind	    - Bind to a channel. Create a channel if required
1644  * sysevent_evc_unbind	    - Unbind from a channel. Destroy ch. if last unbind
1645  * sysevent_evc_subscribe   - Subscribe to events from a channel
1646  * sysevent_evc_unsubscribe - Unsubscribe from an event class
1647  * sysevent_evc_publish	    - Publish an event to an event channel
1648  * sysevent_evc_control	    - Various control operation on event channel
1649  *
1650  * The function below are for evaluating a sysevent:
1651  *
1652  * sysevent_get_class_name  - Get pointer to event class string
1653  * sysevent_get_subclass_name - Get pointer to event subclass string
1654  * sysevent_get_seq	    - Get unique event sequence number
1655  * sysevent_get_time	    - Get hrestime of event publish
1656  * sysevent_get_size	    - Get size of event structure
1657  * sysevent_get_pub	    - Get publisher string
1658  * sysevent_get_attr_list   - Get copy of attribute list
1659  *
1660  * The following interfaces represent stability level project privat
1661  * and allow to save the events of an event channel even in a panic case.
1662  *
1663  * sysevent_evc_walk_init   - Take a snapshot of the events in a channel
1664  * sysevent_evc_walk_step   - Read next event from snapshot
1665  * sysevent_evc_walk_fini   - Free resources from event channel snapshot
1666  * sysevent_evc_event_attr  - Get event payload address and size
1667  */
1668 /*
1669  * allocate sysevent structure with optional space for attributes
1670  */
1671 static sysevent_impl_t *
1672 sysevent_evc_alloc(const char *class, const char *subclass, const char *pub,
1673     size_t pub_sz, size_t atsz, uint32_t flag)
1674 {
1675 	int		payload_sz;
1676 	int		class_sz, subclass_sz;
1677 	int 		aligned_class_sz, aligned_subclass_sz, aligned_pub_sz;
1678 	sysevent_impl_t	*ev;
1679 
1680 	/*
1681 	 * Calculate and reserve space for the class, subclass and
1682 	 * publisher strings in the event buffer
1683 	 */
1684 	class_sz = strlen(class) + 1;
1685 	subclass_sz = strlen(subclass) + 1;
1686 
1687 	ASSERT((class_sz <= MAX_CLASS_LEN) && (subclass_sz <=
1688 	    MAX_SUBCLASS_LEN) && (pub_sz <= MAX_PUB_LEN));
1689 
1690 	/* String sizes must be 64-bit aligned in the event buffer */
1691 	aligned_class_sz = SE_ALIGN(class_sz);
1692 	aligned_subclass_sz = SE_ALIGN(subclass_sz);
1693 	aligned_pub_sz = SE_ALIGN(pub_sz);
1694 
1695 	/*
1696 	 * Calculate payload size. Consider the space needed for alignment
1697 	 * and subtract the size of the uint64_t placeholder variables of
1698 	 * sysevent_impl_t.
1699 	 */
1700 	payload_sz = (aligned_class_sz - sizeof (uint64_t)) +
1701 	    (aligned_subclass_sz - sizeof (uint64_t)) +
1702 	    (aligned_pub_sz - sizeof (uint64_t)) - sizeof (uint64_t) +
1703 	    atsz;
1704 
1705 	/*
1706 	 * Allocate event buffer plus additional payload overhead
1707 	 */
1708 	if ((ev = evch_evq_evzalloc(sizeof (sysevent_impl_t) +
1709 	    payload_sz, flag)) == NULL) {
1710 		return (NULL);
1711 	}
1712 
1713 	/* Initialize the event buffer data */
1714 	SE_VERSION(ev) = SYS_EVENT_VERSION;
1715 	bcopy(class, SE_CLASS_NAME(ev), class_sz);
1716 
1717 	SE_SUBCLASS_OFF(ev) = SE_ALIGN(offsetof(sysevent_impl_t,
1718 	    se_class_name)) + aligned_class_sz;
1719 	bcopy(subclass, SE_SUBCLASS_NAME(ev), subclass_sz);
1720 
1721 	SE_PUB_OFF(ev) = SE_SUBCLASS_OFF(ev) + aligned_subclass_sz;
1722 	bcopy(pub, SE_PUB_NAME(ev), pub_sz);
1723 
1724 	SE_ATTR_PTR(ev) = (uint64_t)0;
1725 	SE_PAYLOAD_SZ(ev) = payload_sz;
1726 
1727 	return (ev);
1728 }
1729 
1730 /*
1731  * Initialize event channel handling queues.
1732  */
1733 void
1734 sysevent_evc_init()
1735 {
1736 	evch_chinit();
1737 }
1738 
1739 /*
1740  * Second initialization step: create threads, if event channels are already
1741  * created
1742  */
1743 void
1744 sysevent_evc_thrinit()
1745 {
1746 	evch_chinitthr();
1747 }
1748 
1749 int
1750 sysevent_evc_bind(const char *ch_name, evchan_t **scpp, uint32_t flags)
1751 {
1752 	ASSERT(ch_name != NULL && scpp != NULL);
1753 	ASSERT((flags & ~EVCH_B_FLAGS) == 0);
1754 	return (evch_chbind(ch_name, (evch_bind_t **)scpp, flags));
1755 }
1756 
1757 void
1758 sysevent_evc_unbind(evchan_t *scp)
1759 {
1760 	evch_bind_t *bp = (evch_bind_t *)scp;
1761 
1762 	ASSERT(scp != NULL);
1763 	evch_chunsubscribe(bp, NULL, 0);
1764 	evch_chunbind(bp);
1765 }
1766 
1767 int
1768 sysevent_evc_subscribe(evchan_t *scp, const char *sid, const char *class,
1769     int (*callb)(sysevent_t *ev, void *cookie),
1770     void *cookie, uint32_t flags)
1771 {
1772 	ASSERT(scp != NULL && sid != NULL && class != NULL && callb != NULL);
1773 	ASSERT(flags == 0);
1774 	if (strlen(sid) > MAX_SUBID_LEN) {
1775 		return (EINVAL);
1776 	}
1777 	if (strcmp(class, EC_ALL) == 0) {
1778 		class = NULL;
1779 	}
1780 	return (evch_chsubscribe((evch_bind_t *)scp, EVCH_DELKERN, sid, class,
1781 	    (void *)callb, cookie, 0, 0));
1782 }
1783 
1784 void
1785 sysevent_evc_unsubscribe(evchan_t *scp, const char *sid)
1786 {
1787 	ASSERT(scp != NULL && sid != NULL);
1788 	if (strcmp(sid, EVCH_ALLSUB) == 0) {
1789 		sid = NULL;
1790 	}
1791 	evch_chunsubscribe((evch_bind_t *)scp, sid, 0);
1792 }
1793 
1794 /*
1795  * Publish kernel event. Returns 0 on success, error code else.
1796  * Optional attribute data is packed into the event structure.
1797  */
1798 int
1799 sysevent_evc_publish(evchan_t *scp, const char *class, const char *subclass,
1800     const char *vendor, const char *pubs, nvlist_t *attr, uint32_t flags)
1801 {
1802 	sysevent_impl_t	*evp;
1803 	char		pub[MAX_PUB_LEN];
1804 	int		pub_sz;		/* includes terminating 0 */
1805 	int		km_flags;
1806 	size_t		asz = 0;
1807 	uint64_t	attr_offset;
1808 	caddr_t		patt;
1809 	int		err;
1810 
1811 	ASSERT(scp != NULL && class != NULL && subclass != NULL &&
1812 	    vendor != NULL && pubs != NULL);
1813 
1814 	ASSERT((flags & ~(EVCH_SLEEP | EVCH_NOSLEEP | EVCH_TRYHARD |
1815 	    EVCH_QWAIT)) == 0);
1816 
1817 	km_flags = flags & (EVCH_SLEEP | EVCH_NOSLEEP | EVCH_TRYHARD);
1818 	ASSERT(km_flags == EVCH_SLEEP || km_flags == EVCH_NOSLEEP ||
1819 	    km_flags == EVCH_TRYHARD);
1820 
1821 	pub_sz = snprintf(pub, MAX_PUB_LEN, "%s:kern:%s", vendor, pubs) + 1;
1822 	if (pub_sz > MAX_PUB_LEN)
1823 		return (EINVAL);
1824 
1825 	if (attr != NULL) {
1826 		if ((err = nvlist_size(attr, &asz, NV_ENCODE_NATIVE)) != 0) {
1827 			return (err);
1828 		}
1829 	}
1830 	evp = sysevent_evc_alloc(class, subclass, pub, pub_sz, asz, km_flags);
1831 	if (evp == NULL) {
1832 		return (ENOMEM);
1833 	}
1834 	if (attr != NULL) {
1835 		/*
1836 		 * Pack attributes into event buffer. Event buffer already
1837 		 * has enough room for the packed nvlist.
1838 		 */
1839 		attr_offset = SE_ATTR_OFF(evp);
1840 		patt = (caddr_t)evp + attr_offset;
1841 
1842 		err = nvlist_pack(attr, &patt, &asz, NV_ENCODE_NATIVE,
1843 		    km_flags & EVCH_SLEEP ? KM_SLEEP : KM_NOSLEEP);
1844 
1845 		ASSERT(err != ENOMEM);
1846 
1847 		if (err != 0) {
1848 			return (EINVAL);
1849 		}
1850 
1851 		evp->seh_attr_off = attr_offset;
1852 		SE_FLAG(evp) = SE_PACKED_BUF;
1853 	}
1854 	return (evch_chpublish((evch_bind_t *)scp, evp, flags));
1855 }
1856 
1857 int
1858 sysevent_evc_control(evchan_t *scp, int cmd, ...)
1859 {
1860 	va_list		ap;
1861 	evch_chan_t	*chp = ((evch_bind_t *)scp)->bd_channel;
1862 	uint32_t	*chlenp;
1863 	uint32_t	chlen;
1864 	uint32_t	ochlen;
1865 	int		rc = 0;
1866 
1867 	if (scp == NULL) {
1868 		return (EINVAL);
1869 	}
1870 
1871 	va_start(ap, cmd);
1872 	mutex_enter(&chp->ch_mutex);
1873 	switch (cmd) {
1874 	case EVCH_GET_CHAN_LEN:
1875 		chlenp = va_arg(ap, uint32_t *);
1876 		*chlenp = chp->ch_maxev;
1877 		break;
1878 	case EVCH_SET_CHAN_LEN:
1879 		chlen = va_arg(ap, uint32_t);
1880 		ochlen = chp->ch_maxev;
1881 		chp->ch_maxev = min(chlen, evch_events_max);
1882 		if (ochlen < chp->ch_maxev) {
1883 			cv_signal(&chp->ch_pubcv);
1884 		}
1885 		break;
1886 	case EVCH_GET_CHAN_LEN_MAX:
1887 		*va_arg(ap, uint32_t *) = evch_events_max;
1888 		break;
1889 	default:
1890 		rc = EINVAL;
1891 	}
1892 
1893 	mutex_exit(&chp->ch_mutex);
1894 	va_end(ap);
1895 	return (rc);
1896 }
1897 
1898 /*
1899  * Project private interface to take a snapshot of all events of the
1900  * specified event channel. Argument subscr may be a subscriber id, the empty
1901  * string "", or NULL. The empty string indicates that no subscriber is
1902  * selected, for example if a previous subscriber died. sysevent_evc_walk_next()
1903  * will deliver events from the main event queue in this case. If subscr is
1904  * NULL, the subscriber with the EVCH_SUB_DUMP flag set (subd->sd_dump != 0)
1905  * will be selected.
1906  *
1907  * In panic case this function returns NULL. This is legal. The NULL has
1908  * to be delivered to sysevent_evc_walk_step() and sysevent_evc_walk_fini().
1909  */
1910 evchanq_t *
1911 sysevent_evc_walk_init(evchan_t *scp, char *subscr)
1912 {
1913 	if (panicstr != NULL && scp == NULL)
1914 		return (NULL);
1915 	ASSERT(scp != NULL);
1916 	return (evch_chrdevent_init(((evch_bind_t *)scp)->bd_channel, subscr));
1917 }
1918 
1919 /*
1920  * Project private interface to read events from a previously taken
1921  * snapshot (with sysevent_evc_walk_init). In case of panic events
1922  * are retrieved directly from the channel data structures. No resources
1923  * are allocated and no mutexes are grabbed in panic context.
1924  */
1925 sysevent_t *
1926 sysevent_evc_walk_step(evchanq_t *evcq)
1927 {
1928 	return ((sysevent_t *)evch_chgetnextev(evcq));
1929 }
1930 
1931 /*
1932  * Project private interface to free a previously taken snapshot.
1933  */
1934 void
1935 sysevent_evc_walk_fini(evchanq_t *evcq)
1936 {
1937 	evch_chrdevent_fini(evcq);
1938 }
1939 
1940 /*
1941  * Get address and size of an event payload. Returns NULL when no
1942  * payload present.
1943  */
1944 char *
1945 sysevent_evc_event_attr(sysevent_t *ev, size_t *plsize)
1946 {
1947 	char	*attrp;
1948 	size_t	aoff;
1949 	size_t	asz;
1950 
1951 	aoff = SE_ATTR_OFF(ev);
1952 	attrp = (char *)ev + aoff;
1953 	asz = *plsize = SE_SIZE(ev) - aoff;
1954 	return (asz ? attrp : NULL);
1955 }
1956 
1957 /*
1958  * sysevent_get_class_name - Get class name string
1959  */
1960 char *
1961 sysevent_get_class_name(sysevent_t *ev)
1962 {
1963 	return (SE_CLASS_NAME(ev));
1964 }
1965 
1966 /*
1967  * sysevent_get_subclass_name - Get subclass name string
1968  */
1969 char *
1970 sysevent_get_subclass_name(sysevent_t *ev)
1971 {
1972 	return (SE_SUBCLASS_NAME(ev));
1973 }
1974 
1975 /*
1976  * sysevent_get_seq - Get event sequence id
1977  */
1978 uint64_t
1979 sysevent_get_seq(sysevent_t *ev)
1980 {
1981 	return (SE_SEQ(ev));
1982 }
1983 
1984 /*
1985  * sysevent_get_time - Get event timestamp
1986  */
1987 void
1988 sysevent_get_time(sysevent_t *ev, hrtime_t *etime)
1989 {
1990 	*etime = SE_TIME(ev);
1991 }
1992 
1993 /*
1994  * sysevent_get_size - Get event buffer size
1995  */
1996 size_t
1997 sysevent_get_size(sysevent_t *ev)
1998 {
1999 	return ((size_t)SE_SIZE(ev));
2000 }
2001 
2002 /*
2003  * sysevent_get_pub - Get publisher name string
2004  */
2005 char *
2006 sysevent_get_pub(sysevent_t *ev)
2007 {
2008 	return (SE_PUB_NAME(ev));
2009 }
2010 
2011 /*
2012  * sysevent_get_attr_list - stores address of a copy of the attribute list
2013  * associated with the given sysevent buffer. The list must be freed by the
2014  * caller.
2015  */
2016 int
2017 sysevent_get_attr_list(sysevent_t *ev, nvlist_t **nvlist)
2018 {
2019 	int		error;
2020 	caddr_t		attr;
2021 	size_t		attr_len;
2022 	uint64_t	attr_offset;
2023 
2024 	*nvlist = NULL;
2025 	if (SE_FLAG(ev) != SE_PACKED_BUF) {
2026 		return (EINVAL);
2027 	}
2028 	attr_offset = SE_ATTR_OFF(ev);
2029 	if (SE_SIZE(ev) == attr_offset) {
2030 		return (EINVAL);
2031 	}
2032 
2033 	/* unpack nvlist */
2034 	attr = (caddr_t)ev + attr_offset;
2035 	attr_len = SE_SIZE(ev) - attr_offset;
2036 	if ((error = nvlist_unpack(attr, attr_len, nvlist, 0)) != 0) {
2037 		error = error != ENOMEM ? EINVAL : error;
2038 		return (error);
2039 	}
2040 	return (0);
2041 }
2042 
2043 /*
2044  * Functions called by the sysevent driver for general purpose event channels
2045  *
2046  * evch_usrchanopen	- Create/Bind to an event channel
2047  * evch_usrchanclose	- Unbind/Destroy event channel
2048  * evch_usrallocev	- Allocate event data structure
2049  * evch_usrfreeev	- Free event data structure
2050  * evch_usrpostevent	- Publish event
2051  * evch_usrsubscribe	- Subscribe (register callback function)
2052  * evch_usrunsubscribe	- Unsubscribe
2053  * evch_usrcontrol_set	- Set channel properties
2054  * evch_usrcontrol_get	- Get channel properties
2055  * evch_usrgetchnames	- Get list of channel names
2056  * evch_usrgetchdata	- Get data of an event channel
2057  */
2058 evchan_t *
2059 evch_usrchanopen(const char *name, uint32_t flags, int *err)
2060 {
2061 	evch_bind_t *bp = NULL;
2062 
2063 	*err = evch_chbind(name, &bp, flags);
2064 	return ((evchan_t *)bp);
2065 }
2066 
2067 /*
2068  * Unbind from the channel.
2069  */
2070 void
2071 evch_usrchanclose(evchan_t *cbp)
2072 {
2073 	evch_chunbind((evch_bind_t *)cbp);
2074 }
2075 
2076 /*
2077  * Allocates log_evch_eventq_t structure but returns the pointer of the embedded
2078  * sysevent_impl_t structure as the opaque sysevent_t * data type
2079  */
2080 sysevent_impl_t *
2081 evch_usrallocev(size_t evsize, uint32_t flags)
2082 {
2083 	return ((sysevent_impl_t *)evch_evq_evzalloc(evsize, flags));
2084 }
2085 
2086 /*
2087  * Free evch_eventq_t structure
2088  */
2089 void
2090 evch_usrfreeev(sysevent_impl_t *ev)
2091 {
2092 	evch_evq_evfree((void *)ev);
2093 }
2094 
2095 /*
2096  * Posts an event to the given channel. The event structure has to be
2097  * allocated by evch_usrallocev(). Returns zero on success and an error
2098  * code else. Attributes have to be packed and included in the event structure.
2099  *
2100  */
2101 int
2102 evch_usrpostevent(evchan_t *bp, sysevent_impl_t *ev, uint32_t flags)
2103 {
2104 	return (evch_chpublish((evch_bind_t *)bp, ev, flags));
2105 }
2106 
2107 /*
2108  * Subscribe function for user land subscriptions
2109  */
2110 int
2111 evch_usrsubscribe(evchan_t *bp, const char *sid, const char *class,
2112     int d, uint32_t flags)
2113 {
2114 	door_handle_t	dh = door_ki_lookup(d);
2115 	int		rv;
2116 
2117 	if (dh == NULL) {
2118 		return (EINVAL);
2119 	}
2120 	if ((rv = evch_chsubscribe((evch_bind_t *)bp, EVCH_DELDOOR, sid, class,
2121 	    (void *)dh, NULL, flags, curproc->p_pid)) != 0) {
2122 		door_ki_rele(dh);
2123 	}
2124 	return (rv);
2125 }
2126 
2127 /*
2128  * Flag can be EVCH_SUB_KEEP or 0. EVCH_SUB_KEEP preserves persistent
2129  * subscribers
2130  */
2131 void
2132 evch_usrunsubscribe(evchan_t *bp, const char *subid, uint32_t flags)
2133 {
2134 	evch_chunsubscribe((evch_bind_t *)bp, subid, flags);
2135 }
2136 
2137 /*ARGSUSED*/
2138 int
2139 evch_usrcontrol_set(evchan_t *bp, int cmd, uint32_t value)
2140 {
2141 	evch_chan_t	*chp = ((evch_bind_t *)bp)->bd_channel;
2142 	uid_t		uid = crgetuid(curthread->t_cred);
2143 	int		rc = 0;
2144 
2145 	mutex_enter(&chp->ch_mutex);
2146 	switch (cmd) {
2147 	case EVCH_SET_CHAN_LEN:
2148 		if (uid && uid != chp->ch_uid) {
2149 			rc = EACCES;
2150 			break;
2151 		}
2152 		chp->ch_maxev = min(value, evch_events_max);
2153 		break;
2154 	default:
2155 		rc = EINVAL;
2156 	}
2157 	mutex_exit(&chp->ch_mutex);
2158 	return (rc);
2159 }
2160 
2161 /*ARGSUSED*/
2162 int
2163 evch_usrcontrol_get(evchan_t *bp, int cmd, uint32_t *value)
2164 {
2165 	evch_chan_t	*chp = ((evch_bind_t *)bp)->bd_channel;
2166 	int		rc = 0;
2167 
2168 	mutex_enter(&chp->ch_mutex);
2169 	switch (cmd) {
2170 	case EVCH_GET_CHAN_LEN:
2171 		*value = chp->ch_maxev;
2172 		break;
2173 	case EVCH_GET_CHAN_LEN_MAX:
2174 		*value = evch_events_max;
2175 		break;
2176 	default:
2177 		rc = EINVAL;
2178 	}
2179 	mutex_exit(&chp->ch_mutex);
2180 	return (rc);
2181 }
2182 
2183 int
2184 evch_usrgetchnames(char *buf, size_t size)
2185 {
2186 	return (evch_chgetnames(buf, size));
2187 }
2188 
2189 int
2190 evch_usrgetchdata(char *chname, void *buf, size_t size)
2191 {
2192 	return (evch_chgetchdata(chname, buf, size));
2193 }
2194