xref: /titanic_51/usr/src/uts/common/os/contract.c (revision 62c6006265c37877b7a5b3c8ffce913ef559b955)
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  * Contracts
30  * ---------
31  *
32  * Contracts are a primitive which enrich the relationships between
33  * processes and system resources.  The primary purpose of contracts is
34  * to provide a means for the system to negotiate the departure from a
35  * binding relationship (e.g. pages locked in memory or a thread bound
36  * to processor), but they can also be used as a purely asynchronous
37  * error reporting mechanism as they are with process contracts.
38  *
39  * More information on how one interfaces with contracts and what
40  * contracts can do for you can be found in:
41  *   PSARC 2003/193 Solaris Contracts
42  *   PSARC 2004/460 Contracts addendum
43  *
44  * This file contains the core contracts framework.  By itself it is
45  * useless: it depends the contracts filesystem (ctfs) to provide an
46  * interface to user processes and individual contract types to
47  * implement the process/resource relationships.
48  *
49  * Data structure overview
50  * -----------------------
51  *
52  * A contract is represented by a contract_t, which itself points to an
53  * encapsulating contract-type specific contract object.  A contract_t
54  * contains the contract's static identity (including its terms), its
55  * linkage to various bookkeeping structures, the contract-specific
56  * event queue, and a reference count.
57  *
58  * A contract template is represented by a ct_template_t, which, like a
59  * contract, points to an encapsulating contract-type specific template
60  * object.  A ct_template_t contains the template's terms.
61  *
62  * An event queue is represented by a ct_equeue_t, and consists of a
63  * list of events, a list of listeners, and a list of listeners who are
64  * waiting for new events (affectionately referred to as "tail
65  * listeners").  There are three queue types, defined by ct_listnum_t
66  * (an enum).  An event may be on one of each type of queue
67  * simultaneously; the list linkage used by a queue is determined by
68  * its type.
69  *
70  * An event is represented by a ct_kevent_t, which contains mostly
71  * static event data (e.g. id, payload).  It also has an array of
72  * ct_member_t structures, each of which contains a list_node_t and
73  * represent the event's linkage in a specific event queue.
74  *
75  * Each open of an event endpoint results in the creation of a new
76  * listener, represented by a ct_listener_t.  In addition to linkage
77  * into the aforementioned lists in the event_queue, a ct_listener_t
78  * contains a pointer to the ct_kevent_t it is currently positioned at
79  * as well as a set of status flags and other administrative data.
80  *
81  * Each process has a list of contracts it owns, p_ct_held; a pointer
82  * to the process contract it is a member of, p_ct_process; the linkage
83  * for that membership, p_ct_member; and an array of event queue
84  * structures representing the process bundle queues.
85  *
86  * Each LWP has an array of its active templates, lwp_ct_active; and
87  * the most recently created contracts, lwp_ct_latest.
88  *
89  * A process contract has a list of member processes and a list of
90  * inherited contracts.
91  *
92  * There is a system-wide list of all contracts, as well as per-type
93  * lists of contracts.
94  *
95  * Lock ordering overview
96  * ----------------------
97  *
98  * Locks at the top are taken first:
99  *
100  *                   ct_evtlock
101  *                   regent ct_lock
102  *                   member ct_lock
103  *                   pidlock
104  *                   p_lock
105  *    contract ctq_lock         contract_lock
106  *    pbundle ctq_lock
107  *    cte_lock
108  *                   ct_reflock
109  *
110  * contract_lock and ctq_lock/cte_lock are not currently taken at the
111  * same time.
112  *
113  * Reference counting and locking
114  * ------------------------------
115  *
116  * A contract has a reference count, protected by ct_reflock.
117  * (ct_reflock is also used in a couple other places where atomic
118  * access to a variable is needed in an innermost context).  A process
119  * maintains a hold on each contract it owns.  A process contract has a
120  * hold on each contract is has inherited.  Each event has a hold on
121  * the contract which generated it.  Process contract templates have
122  * holds on the contracts referred to by their transfer terms.  CTFS
123  * contract directory nodes have holds on contracts.  Lastly, various
124  * code paths may temporarily take holds on contracts to prevent them
125  * from disappearing while other processing is going on.  It is
126  * important to note that the global contract lists do not hold
127  * references on contracts; a contract is removed from these structures
128  * atomically with the release of its last reference.
129  *
130  * At a given point in time, a contract can either be owned by a
131  * process, inherited by a regent process contract, or orphaned.  A
132  * contract_t's  owner and regent pointers, ct_owner and ct_regent, are
133  * protected by its ct_lock.  The linkage in the holder's (holder =
134  * owner or regent) list of contracts, ct_ctlist, is protected by
135  * whatever lock protects the holder's data structure.  In order for
136  * these two directions to remain consistent, changing the holder of a
137  * contract requires that both locks be held.
138  *
139  * Events also have reference counts.  There is one hold on an event
140  * per queue it is present on, in addition to those needed for the
141  * usual sundry reasons.  Individual listeners are associated with
142  * specific queues, and increase a queue-specific reference count
143  * stored in the ct_member_t structure.
144  *
145  * The dynamic contents of an event (reference count and flags) are
146  * protected by its cte_lock, while the contents of the embedded
147  * ct_member_t structures are protected by the locks of the queues they
148  * are linked into.  A ct_listener_t's contents are also protected by
149  * its event queue's ctq_lock.
150  *
151  * Resource controls
152  * -----------------
153  *
154  * Control:      project.max-contracts (rc_project_contract)
155  * Description:  Maximum number of contracts allowed a project.
156  *
157  *   When a contract is created, the project's allocation is tested and
158  *   (assuming success) increased.  When the last reference to a
159  *   contract is released, the creating project's allocation is
160  *   decreased.
161  */
162 
163 #include <sys/mutex.h>
164 #include <sys/debug.h>
165 #include <sys/types.h>
166 #include <sys/param.h>
167 #include <sys/kmem.h>
168 #include <sys/thread.h>
169 #include <sys/id_space.h>
170 #include <sys/avl.h>
171 #include <sys/list.h>
172 #include <sys/sysmacros.h>
173 #include <sys/proc.h>
174 #include <sys/contract_impl.h>
175 #include <sys/contract/process_impl.h>
176 #include <sys/dditypes.h>
177 #include <sys/contract/device_impl.h>
178 #include <sys/systm.h>
179 #include <sys/atomic.h>
180 #include <sys/cmn_err.h>
181 #include <sys/model.h>
182 #include <sys/policy.h>
183 #include <sys/zone.h>
184 #include <sys/task.h>
185 #include <sys/ddi.h>
186 #include <sys/sunddi.h>
187 
188 extern rctl_hndl_t rc_project_contract;
189 
190 static id_space_t	*contract_ids;
191 static avl_tree_t	contract_avl;
192 static kmutex_t		contract_lock;
193 
194 int			ct_ntypes = CTT_MAXTYPE;
195 static ct_type_t	*ct_types_static[CTT_MAXTYPE];
196 ct_type_t		**ct_types = ct_types_static;
197 int			ct_debug;
198 
199 static void cte_queue_create(ct_equeue_t *, ct_listnum_t, int, int);
200 static void cte_queue_destroy(ct_equeue_t *);
201 static void cte_queue_drain(ct_equeue_t *, int);
202 static void cte_trim(ct_equeue_t *, contract_t *);
203 static void cte_copy(ct_equeue_t *, ct_equeue_t *);
204 
205 /*
206  * contract_compar
207  *
208  * A contract comparator which sorts on contract ID.
209  */
210 int
211 contract_compar(const void *x, const void *y)
212 {
213 	const contract_t *ct1 = x;
214 	const contract_t *ct2 = y;
215 
216 	if (ct1->ct_id < ct2->ct_id)
217 		return (-1);
218 	if (ct1->ct_id > ct2->ct_id)
219 		return (1);
220 	return (0);
221 }
222 
223 /*
224  * contract_init
225  *
226  * Initializes the contract subsystem, the specific contract types, and
227  * process 0.
228  */
229 void
230 contract_init(void)
231 {
232 	/*
233 	 * Initialize contract subsystem.
234 	 */
235 	contract_ids = id_space_create("contracts", 1, INT_MAX);
236 	avl_create(&contract_avl, contract_compar, sizeof (contract_t),
237 	    offsetof(contract_t, ct_ctavl));
238 	mutex_init(&contract_lock, NULL, MUTEX_DEFAULT, NULL);
239 
240 	/*
241 	 * Initialize contract types.
242 	 */
243 	contract_process_init();
244 	contract_device_init();
245 
246 	/*
247 	 * Initialize p0/lwp0 contract state.
248 	 */
249 	avl_create(&p0.p_ct_held, contract_compar, sizeof (contract_t),
250 	    offsetof(contract_t, ct_ctlist));
251 }
252 
253 /*
254  * contract_dtor
255  *
256  * Performs basic destruction of the common portions of a contract.
257  * Called from the failure path of contract_ctor and from
258  * contract_rele.
259  */
260 static void
261 contract_dtor(contract_t *ct)
262 {
263 	cte_queue_destroy(&ct->ct_events);
264 	list_destroy(&ct->ct_vnodes);
265 	mutex_destroy(&ct->ct_reflock);
266 	mutex_destroy(&ct->ct_lock);
267 	mutex_destroy(&ct->ct_evtlock);
268 }
269 
270 /*
271  * contract_ctor
272  *
273  * Called by a contract type to initialize a contract.  Fails if the
274  * max-contract resource control would have been exceeded.  After a
275  * successful call to contract_ctor, the contract is unlocked and
276  * visible in all namespaces; any type-specific initialization should
277  * be completed before calling contract_ctor.  Returns 0 on success.
278  *
279  * Because not all callers can tolerate failure, a 0 value for canfail
280  * instructs contract_ctor to ignore the project.max-contracts resource
281  * control.  Obviously, this "out" should only be employed by callers
282  * who are sufficiently constrained in other ways (e.g. newproc).
283  */
284 int
285 contract_ctor(contract_t *ct, ct_type_t *type, ct_template_t *tmpl, void *data,
286     ctflags_t flags, proc_t *author, int canfail)
287 {
288 	avl_index_t where;
289 	klwp_t *curlwp = ttolwp(curthread);
290 
291 	ASSERT(author == curproc);
292 
293 	mutex_init(&ct->ct_lock, NULL, MUTEX_DEFAULT, NULL);
294 	mutex_init(&ct->ct_reflock, NULL, MUTEX_DEFAULT, NULL);
295 	mutex_init(&ct->ct_evtlock, NULL, MUTEX_DEFAULT, NULL);
296 	ct->ct_id = id_alloc(contract_ids);
297 
298 	cte_queue_create(&ct->ct_events, CTEL_CONTRACT, 20, 0);
299 	list_create(&ct->ct_vnodes, sizeof (contract_vnode_t),
300 	    offsetof(contract_vnode_t, ctv_node));
301 
302 	/*
303 	 * Instance data
304 	 */
305 	ct->ct_ref = 2;		/* one for the holder, one for "latest" */
306 	ct->ct_cuid = crgetuid(CRED());
307 	ct->ct_type = type;
308 	ct->ct_data = data;
309 	gethrestime(&ct->ct_ctime);
310 	ct->ct_state = CTS_OWNED;
311 	ct->ct_flags = flags;
312 	ct->ct_regent = author->p_ct_process ?
313 	    &author->p_ct_process->conp_contract : NULL;
314 	ct->ct_ev_info = tmpl->ctmpl_ev_info;
315 	ct->ct_ev_crit = tmpl->ctmpl_ev_crit;
316 	ct->ct_cookie = tmpl->ctmpl_cookie;
317 	ct->ct_owner = author;
318 	ct->ct_ntime.ctm_total = -1;
319 	ct->ct_qtime.ctm_total = -1;
320 	ct->ct_nevent = NULL;
321 
322 	/*
323 	 * Test project.max-contracts.
324 	 */
325 	mutex_enter(&author->p_lock);
326 	mutex_enter(&contract_lock);
327 	if (canfail && rctl_test(rc_project_contract,
328 	    author->p_task->tk_proj->kpj_rctls, author, 1,
329 	    RCA_SAFE) & RCT_DENY) {
330 		id_free(contract_ids, ct->ct_id);
331 		mutex_exit(&contract_lock);
332 		mutex_exit(&author->p_lock);
333 		ct->ct_events.ctq_flags |= CTQ_DEAD;
334 		contract_dtor(ct);
335 		return (1);
336 	}
337 	ct->ct_proj = author->p_task->tk_proj;
338 	ct->ct_proj->kpj_data.kpd_contract++;
339 	(void) project_hold(ct->ct_proj);
340 	mutex_exit(&contract_lock);
341 
342 	/*
343 	 * Insert into holder's avl of contracts.
344 	 * We use an avl not because order is important, but because
345 	 * readdir of /proc/contracts requires we be able to use a
346 	 * scalar as an index into the process's list of contracts
347 	 */
348 	ct->ct_zoneid = author->p_zone->zone_id;
349 	ct->ct_czuniqid = ct->ct_mzuniqid = author->p_zone->zone_uniqid;
350 	VERIFY(avl_find(&author->p_ct_held, ct, &where) == NULL);
351 	avl_insert(&author->p_ct_held, ct, where);
352 	mutex_exit(&author->p_lock);
353 
354 	/*
355 	 * Insert into global contract AVL
356 	 */
357 	mutex_enter(&contract_lock);
358 	VERIFY(avl_find(&contract_avl, ct, &where) == NULL);
359 	avl_insert(&contract_avl, ct, where);
360 	mutex_exit(&contract_lock);
361 
362 	/*
363 	 * Insert into type AVL
364 	 */
365 	mutex_enter(&type->ct_type_lock);
366 	VERIFY(avl_find(&type->ct_type_avl, ct, &where) == NULL);
367 	avl_insert(&type->ct_type_avl, ct, where);
368 	type->ct_type_timestruc = ct->ct_ctime;
369 	mutex_exit(&type->ct_type_lock);
370 
371 	if (curlwp->lwp_ct_latest[type->ct_type_index])
372 		contract_rele(curlwp->lwp_ct_latest[type->ct_type_index]);
373 	curlwp->lwp_ct_latest[type->ct_type_index] = ct;
374 
375 	return (0);
376 }
377 
378 /*
379  * contract_rele
380  *
381  * Releases a reference to a contract.  If the caller had the last
382  * reference, the contract is removed from all namespaces, its
383  * allocation against the max-contracts resource control is released,
384  * and the contract type's free entry point is invoked for any
385  * type-specific deconstruction and to (presumably) free the object.
386  */
387 void
388 contract_rele(contract_t *ct)
389 {
390 	uint64_t nref;
391 
392 	mutex_enter(&ct->ct_reflock);
393 	ASSERT(ct->ct_ref > 0);
394 	nref = --ct->ct_ref;
395 	mutex_exit(&ct->ct_reflock);
396 	if (nref == 0) {
397 		/*
398 		 * ct_owner is cleared when it drops its reference.
399 		 */
400 		ASSERT(ct->ct_owner == NULL);
401 		ASSERT(ct->ct_evcnt == 0);
402 
403 		/*
404 		 * Remove from global contract AVL
405 		 */
406 		mutex_enter(&contract_lock);
407 		avl_remove(&contract_avl, ct);
408 		mutex_exit(&contract_lock);
409 
410 		/*
411 		 * Remove from type AVL
412 		 */
413 		mutex_enter(&ct->ct_type->ct_type_lock);
414 		avl_remove(&ct->ct_type->ct_type_avl, ct);
415 		mutex_exit(&ct->ct_type->ct_type_lock);
416 
417 		/*
418 		 * Release the contract's ID
419 		 */
420 		id_free(contract_ids, ct->ct_id);
421 
422 		/*
423 		 * Release project hold
424 		 */
425 		mutex_enter(&contract_lock);
426 		ct->ct_proj->kpj_data.kpd_contract--;
427 		project_rele(ct->ct_proj);
428 		mutex_exit(&contract_lock);
429 
430 		/*
431 		 * Free the contract
432 		 */
433 		contract_dtor(ct);
434 		ct->ct_type->ct_type_ops->contop_free(ct);
435 	}
436 }
437 
438 /*
439  * contract_hold
440  *
441  * Adds a reference to a contract
442  */
443 void
444 contract_hold(contract_t *ct)
445 {
446 	mutex_enter(&ct->ct_reflock);
447 	ASSERT(ct->ct_ref < UINT64_MAX);
448 	ct->ct_ref++;
449 	mutex_exit(&ct->ct_reflock);
450 }
451 
452 /*
453  * contract_getzuniqid
454  *
455  * Get a contract's zone unique ID.  Needed because 64-bit reads and
456  * writes aren't atomic on x86.  Since there are contexts where we are
457  * unable to take ct_lock, we instead use ct_reflock; in actuality any
458  * lock would do.
459  */
460 uint64_t
461 contract_getzuniqid(contract_t *ct)
462 {
463 	uint64_t zuniqid;
464 
465 	mutex_enter(&ct->ct_reflock);
466 	zuniqid = ct->ct_mzuniqid;
467 	mutex_exit(&ct->ct_reflock);
468 
469 	return (zuniqid);
470 }
471 
472 /*
473  * contract_setzuniqid
474  *
475  * Sets a contract's zone unique ID.   See contract_getzuniqid.
476  */
477 void
478 contract_setzuniqid(contract_t *ct, uint64_t zuniqid)
479 {
480 	mutex_enter(&ct->ct_reflock);
481 	ct->ct_mzuniqid = zuniqid;
482 	mutex_exit(&ct->ct_reflock);
483 }
484 
485 /*
486  * contract_abandon
487  *
488  * Abandons the specified contract.  If "explicit" is clear, the
489  * contract was implicitly abandoned (by process exit) and should be
490  * inherited if its terms allow it and its owner was a member of a
491  * regent contract.  Otherwise, the contract type's abandon entry point
492  * is invoked to either destroy or orphan the contract.
493  */
494 int
495 contract_abandon(contract_t *ct, proc_t *p, int explicit)
496 {
497 	ct_equeue_t *q = NULL;
498 	contract_t *parent = &p->p_ct_process->conp_contract;
499 	int inherit = 0;
500 
501 	ASSERT(p == curproc);
502 
503 	mutex_enter(&ct->ct_lock);
504 
505 	/*
506 	 * Multiple contract locks are taken contract -> subcontract.
507 	 * Check if the contract will be inherited so we can acquire
508 	 * all the necessary locks before making sensitive changes.
509 	 */
510 	if (!explicit && (ct->ct_flags & CTF_INHERIT) &&
511 	    contract_process_accept(parent)) {
512 		mutex_exit(&ct->ct_lock);
513 		mutex_enter(&parent->ct_lock);
514 		mutex_enter(&ct->ct_lock);
515 		inherit = 1;
516 	}
517 
518 	if (ct->ct_owner != p) {
519 		mutex_exit(&ct->ct_lock);
520 		if (inherit)
521 			mutex_exit(&parent->ct_lock);
522 		return (EINVAL);
523 	}
524 
525 	mutex_enter(&p->p_lock);
526 	if (explicit)
527 		avl_remove(&p->p_ct_held, ct);
528 	ct->ct_owner = NULL;
529 	mutex_exit(&p->p_lock);
530 
531 	/*
532 	 * Since we can't call cte_trim with the contract lock held,
533 	 * we grab the queue pointer here.
534 	 */
535 	if (p->p_ct_equeue)
536 		q = p->p_ct_equeue[ct->ct_type->ct_type_index];
537 
538 	/*
539 	 * contop_abandon may destroy the contract so we rely on it to
540 	 * drop ct_lock.  We retain a reference on the contract so that
541 	 * the cte_trim which follows functions properly.  Even though
542 	 * cte_trim doesn't dereference the contract pointer, it is
543 	 * still necessary to retain a reference to the contract so
544 	 * that we don't trim events which are sent by a subsequently
545 	 * allocated contract infortuitously located at the same address.
546 	 */
547 	contract_hold(ct);
548 
549 	if (inherit) {
550 		ct->ct_state = CTS_INHERITED;
551 		ASSERT(ct->ct_regent == parent);
552 		contract_process_take(parent, ct);
553 
554 		/*
555 		 * We are handing off the process's reference to the
556 		 * parent contract.  For this reason, the order in
557 		 * which we drop the contract locks is also important.
558 		 */
559 		mutex_exit(&ct->ct_lock);
560 		mutex_exit(&parent->ct_lock);
561 	} else {
562 		ct->ct_regent = NULL;
563 		ct->ct_type->ct_type_ops->contop_abandon(ct);
564 	}
565 
566 	/*
567 	 * ct_lock has been dropped; we can safely trim the event
568 	 * queue now.
569 	 */
570 	if (q) {
571 		mutex_enter(&q->ctq_lock);
572 		cte_trim(q, ct);
573 		mutex_exit(&q->ctq_lock);
574 	}
575 
576 	contract_rele(ct);
577 
578 	return (0);
579 }
580 
581 int
582 contract_newct(contract_t *ct)
583 {
584 	return (ct->ct_type->ct_type_ops->contop_newct(ct));
585 }
586 
587 /*
588  * contract_adopt
589  *
590  * Adopts a contract.  After a successful call to this routine, the
591  * previously inherited contract will belong to the calling process,
592  * and its events will have been appended to its new owner's process
593  * bundle queue.
594  */
595 int
596 contract_adopt(contract_t *ct, proc_t *p)
597 {
598 	avl_index_t where;
599 	ct_equeue_t *q;
600 	contract_t *parent;
601 
602 	ASSERT(p == curproc);
603 
604 	/*
605 	 * Ensure the process has an event queue.  Checked by ASSERTs
606 	 * below.
607 	 */
608 	(void) contract_type_pbundle(ct->ct_type, p);
609 
610 	mutex_enter(&ct->ct_lock);
611 	parent = ct->ct_regent;
612 	if (ct->ct_state != CTS_INHERITED ||
613 	    &p->p_ct_process->conp_contract != parent ||
614 	    p->p_zone->zone_uniqid != ct->ct_czuniqid) {
615 		mutex_exit(&ct->ct_lock);
616 		return (EINVAL);
617 	}
618 
619 	/*
620 	 * Multiple contract locks are taken contract -> subcontract.
621 	 */
622 	mutex_exit(&ct->ct_lock);
623 	mutex_enter(&parent->ct_lock);
624 	mutex_enter(&ct->ct_lock);
625 
626 	/*
627 	 * It is possible that the contract was adopted by someone else
628 	 * while its lock was dropped.  It isn't possible for the
629 	 * contract to have been inherited by a different regent
630 	 * contract.
631 	 */
632 	if (ct->ct_state != CTS_INHERITED) {
633 		mutex_exit(&parent->ct_lock);
634 		mutex_exit(&ct->ct_lock);
635 		return (EBUSY);
636 	}
637 	ASSERT(ct->ct_regent == parent);
638 
639 	ct->ct_state = CTS_OWNED;
640 
641 	contract_process_adopt(ct, p);
642 
643 	mutex_enter(&p->p_lock);
644 	ct->ct_owner = p;
645 	VERIFY(avl_find(&p->p_ct_held, ct, &where) == NULL);
646 	avl_insert(&p->p_ct_held, ct, where);
647 	mutex_exit(&p->p_lock);
648 
649 	ASSERT(ct->ct_owner->p_ct_equeue);
650 	ASSERT(ct->ct_owner->p_ct_equeue[ct->ct_type->ct_type_index]);
651 	q = ct->ct_owner->p_ct_equeue[ct->ct_type->ct_type_index];
652 	cte_copy(&ct->ct_events, q);
653 	mutex_exit(&ct->ct_lock);
654 
655 	return (0);
656 }
657 
658 /*
659  * contract_ack
660  *
661  * Acknowledges receipt of a critical event.
662  */
663 int
664 contract_ack(contract_t *ct, uint64_t evid, int ack)
665 {
666 	ct_kevent_t *ev;
667 	list_t *queue = &ct->ct_events.ctq_events;
668 	int error = ESRCH;
669 	int nego = 0;
670 	uint_t evtype;
671 
672 	ASSERT(ack == CT_ACK || ack == CT_NACK);
673 
674 	mutex_enter(&ct->ct_lock);
675 	mutex_enter(&ct->ct_events.ctq_lock);
676 	/*
677 	 * We are probably ACKing something near the head of the queue.
678 	 */
679 	for (ev = list_head(queue); ev; ev = list_next(queue, ev)) {
680 		if (ev->cte_id == evid) {
681 			if (ev->cte_flags & CTE_NEG)
682 				nego = 1;
683 			else if (ack == CT_NACK)
684 				break;
685 			if ((ev->cte_flags & (CTE_INFO | CTE_ACK)) == 0) {
686 				ev->cte_flags |= CTE_ACK;
687 				ct->ct_evcnt--;
688 				evtype = ev->cte_type;
689 				error = 0;
690 			}
691 			break;
692 		}
693 	}
694 	mutex_exit(&ct->ct_events.ctq_lock);
695 	mutex_exit(&ct->ct_lock);
696 
697 	/*
698 	 * Not all critical events are negotiation events, however
699 	 * every negotiation event is a critical event. NEGEND events
700 	 * are critical events but are not negotiation events
701 	 */
702 	if (error || !nego)
703 		return (error);
704 
705 	if (ack == CT_ACK)
706 		error = ct->ct_type->ct_type_ops->contop_ack(ct, evtype, evid);
707 	else
708 		error = ct->ct_type->ct_type_ops->contop_nack(ct, evtype, evid);
709 
710 	return (error);
711 }
712 
713 /*ARGSUSED*/
714 int
715 contract_ack_inval(contract_t *ct, uint_t evtype, uint64_t evid)
716 {
717 	cmn_err(CE_PANIC, "contract_ack_inval: unsupported call: ctid: %u",
718 	    ct->ct_id);
719 	return (ENOSYS);
720 }
721 
722 /*ARGSUSED*/
723 int
724 contract_qack_inval(contract_t *ct, uint_t evtype, uint64_t evid)
725 {
726 	cmn_err(CE_PANIC, "contract_ack_inval: unsupported call: ctid: %u",
727 	    ct->ct_id);
728 	return (ENOSYS);
729 }
730 
731 /*ARGSUSED*/
732 int
733 contract_qack_notsup(contract_t *ct, uint_t evtype, uint64_t evid)
734 {
735 	return (ERANGE);
736 }
737 
738 /*
739  * contract_qack
740  *
741  * Asks that negotiations be extended by another time quantum
742  */
743 int
744 contract_qack(contract_t *ct, uint64_t evid)
745 {
746 	ct_kevent_t *ev;
747 	list_t *queue = &ct->ct_events.ctq_events;
748 	int nego = 0;
749 	uint_t evtype;
750 
751 	mutex_enter(&ct->ct_lock);
752 	mutex_enter(&ct->ct_events.ctq_lock);
753 
754 	for (ev = list_head(queue); ev; ev = list_next(queue, ev)) {
755 		if (ev->cte_id == evid) {
756 			if ((ev->cte_flags & (CTE_NEG | CTE_ACK)) == CTE_NEG) {
757 				evtype = ev->cte_type;
758 				nego = 1;
759 			}
760 			break;
761 		}
762 	}
763 	mutex_exit(&ct->ct_events.ctq_lock);
764 	mutex_exit(&ct->ct_lock);
765 
766 	/*
767 	 * Only a negotiated event (which is by definition also a critical
768 	 * event) which has not yet been acknowledged can provide
769 	 * time quanta to a negotiating owner process.
770 	 */
771 	if (!nego)
772 		return (ESRCH);
773 
774 	return (ct->ct_type->ct_type_ops->contop_qack(ct, evtype, evid));
775 }
776 
777 /*
778  * contract_orphan
779  *
780  * Icky-poo.  This is a process-contract special, used to ACK all
781  * critical messages when a contract is orphaned.
782  */
783 void
784 contract_orphan(contract_t *ct)
785 {
786 	ct_kevent_t *ev;
787 	list_t *queue = &ct->ct_events.ctq_events;
788 
789 	ASSERT(MUTEX_HELD(&ct->ct_lock));
790 	ASSERT(ct->ct_state != CTS_ORPHAN);
791 
792 	mutex_enter(&ct->ct_events.ctq_lock);
793 	ct->ct_state = CTS_ORPHAN;
794 	for (ev = list_head(queue); ev; ev = list_next(queue, ev)) {
795 		if ((ev->cte_flags & (CTE_INFO | CTE_ACK)) == 0) {
796 			ev->cte_flags |= CTE_ACK;
797 			ct->ct_evcnt--;
798 		}
799 	}
800 	mutex_exit(&ct->ct_events.ctq_lock);
801 
802 	ASSERT(ct->ct_evcnt == 0);
803 }
804 
805 /*
806  * contract_destroy
807  *
808  * Explicit contract destruction.  Called when contract is empty.
809  * The contract will actually stick around until all of its events are
810  * removed from the bundle and and process bundle queues, and all fds
811  * which refer to it are closed.  See contract_dtor if you are looking
812  * for what destroys the contract structure.
813  */
814 void
815 contract_destroy(contract_t *ct)
816 {
817 	ASSERT(MUTEX_HELD(&ct->ct_lock));
818 	ASSERT(ct->ct_state != CTS_DEAD);
819 	ASSERT(ct->ct_owner == NULL);
820 
821 	ct->ct_state = CTS_DEAD;
822 	cte_queue_drain(&ct->ct_events, 1);
823 	mutex_exit(&ct->ct_lock);
824 	mutex_enter(&ct->ct_type->ct_type_events.ctq_lock);
825 	cte_trim(&ct->ct_type->ct_type_events, ct);
826 	mutex_exit(&ct->ct_type->ct_type_events.ctq_lock);
827 	mutex_enter(&ct->ct_lock);
828 	ct->ct_type->ct_type_ops->contop_destroy(ct);
829 	mutex_exit(&ct->ct_lock);
830 	contract_rele(ct);
831 }
832 
833 /*
834  * contract_vnode_get
835  *
836  * Obtains the contract directory vnode for this contract, if there is
837  * one.  The caller must VN_RELE the vnode when they are through using
838  * it.
839  */
840 vnode_t *
841 contract_vnode_get(contract_t *ct, vfs_t *vfsp)
842 {
843 	contract_vnode_t *ctv;
844 	vnode_t *vp = NULL;
845 
846 	mutex_enter(&ct->ct_lock);
847 	for (ctv = list_head(&ct->ct_vnodes); ctv != NULL;
848 	    ctv = list_next(&ct->ct_vnodes, ctv))
849 		if (ctv->ctv_vnode->v_vfsp == vfsp) {
850 			vp = ctv->ctv_vnode;
851 			VN_HOLD(vp);
852 			break;
853 		}
854 	mutex_exit(&ct->ct_lock);
855 	return (vp);
856 }
857 
858 /*
859  * contract_vnode_set
860  *
861  * Sets the contract directory vnode for this contract.  We don't hold
862  * a reference on the vnode because we don't want to prevent it from
863  * being freed.  The vnode's inactive entry point will take care of
864  * notifying us when it should be removed.
865  */
866 void
867 contract_vnode_set(contract_t *ct, contract_vnode_t *ctv, vnode_t *vnode)
868 {
869 	mutex_enter(&ct->ct_lock);
870 	ctv->ctv_vnode = vnode;
871 	list_insert_head(&ct->ct_vnodes, ctv);
872 	mutex_exit(&ct->ct_lock);
873 }
874 
875 /*
876  * contract_vnode_clear
877  *
878  * Removes this vnode as the contract directory vnode for this
879  * contract.  Called from a contract directory's inactive entry point,
880  * this may return 0 indicating that the vnode gained another reference
881  * because of a simultaneous call to contract_vnode_get.
882  */
883 int
884 contract_vnode_clear(contract_t *ct, contract_vnode_t *ctv)
885 {
886 	vnode_t *vp = ctv->ctv_vnode;
887 	int result;
888 
889 	mutex_enter(&ct->ct_lock);
890 	mutex_enter(&vp->v_lock);
891 	if (vp->v_count == 1) {
892 		list_remove(&ct->ct_vnodes, ctv);
893 		result = 1;
894 	} else {
895 		vp->v_count--;
896 		result = 0;
897 	}
898 	mutex_exit(&vp->v_lock);
899 	mutex_exit(&ct->ct_lock);
900 
901 	return (result);
902 }
903 
904 /*
905  * contract_exit
906  *
907  * Abandons all contracts held by process p, and drains process p's
908  * bundle queues.  Called on process exit.
909  */
910 void
911 contract_exit(proc_t *p)
912 {
913 	contract_t *ct;
914 	void *cookie = NULL;
915 	int i;
916 
917 	ASSERT(p == curproc);
918 
919 	/*
920 	 * Abandon held contracts.  contract_abandon knows enough not
921 	 * to remove the contract from the list a second time.  We are
922 	 * exiting, so no locks are needed here.  But because
923 	 * contract_abandon will take p_lock, we need to make sure we
924 	 * aren't holding it.
925 	 */
926 	ASSERT(MUTEX_NOT_HELD(&p->p_lock));
927 	while ((ct = avl_destroy_nodes(&p->p_ct_held, &cookie)) != NULL)
928 		VERIFY(contract_abandon(ct, p, 0) == 0);
929 
930 	/*
931 	 * Drain pbundles.  Because a process bundle queue could have
932 	 * been passed to another process, they may not be freed right
933 	 * away.
934 	 */
935 	if (p->p_ct_equeue) {
936 		for (i = 0; i < CTT_MAXTYPE; i++)
937 			if (p->p_ct_equeue[i])
938 				cte_queue_drain(p->p_ct_equeue[i], 0);
939 		kmem_free(p->p_ct_equeue, CTT_MAXTYPE * sizeof (ct_equeue_t *));
940 	}
941 }
942 
943 static int
944 get_time_left(struct ct_time *t)
945 {
946 	clock_t ticks_elapsed;
947 	int secs_elapsed;
948 
949 	if (t->ctm_total == -1)
950 		return (-1);
951 
952 	ticks_elapsed = ddi_get_lbolt() - t->ctm_start;
953 	secs_elapsed = t->ctm_total - (drv_hztousec(ticks_elapsed)/MICROSEC);
954 	return (secs_elapsed > 0 ? secs_elapsed : 0);
955 }
956 
957 /*
958  * contract_status_common
959  *
960  * Populates a ct_status structure.  Used by contract types in their
961  * status entry points and ctfs when only common information is
962  * requested.
963  */
964 void
965 contract_status_common(contract_t *ct, zone_t *zone, void *status,
966     model_t model)
967 {
968 	STRUCT_HANDLE(ct_status, lstatus);
969 
970 	STRUCT_SET_HANDLE(lstatus, model, status);
971 	ASSERT(MUTEX_HELD(&ct->ct_lock));
972 	if (zone->zone_uniqid == GLOBAL_ZONEUNIQID ||
973 	    zone->zone_uniqid == ct->ct_czuniqid) {
974 		zone_t *czone;
975 		zoneid_t zoneid = -1;
976 
977 		/*
978 		 * Contracts don't have holds on the zones they were
979 		 * created by.  If the contract's zone no longer
980 		 * exists, we say its zoneid is -1.
981 		 */
982 		if (zone->zone_uniqid == ct->ct_czuniqid ||
983 		    ct->ct_czuniqid == GLOBAL_ZONEUNIQID) {
984 			zoneid = ct->ct_zoneid;
985 		} else if ((czone = zone_find_by_id(ct->ct_zoneid)) != NULL) {
986 			if (czone->zone_uniqid == ct->ct_mzuniqid)
987 				zoneid = ct->ct_zoneid;
988 			zone_rele(czone);
989 		}
990 
991 		STRUCT_FSET(lstatus, ctst_zoneid, zoneid);
992 		STRUCT_FSET(lstatus, ctst_holder,
993 		    (ct->ct_state == CTS_OWNED) ? ct->ct_owner->p_pid :
994 		    (ct->ct_state == CTS_INHERITED) ? ct->ct_regent->ct_id : 0);
995 		STRUCT_FSET(lstatus, ctst_state, ct->ct_state);
996 	} else {
997 		/*
998 		 * We are looking at a contract which was created by a
999 		 * process outside of our zone.  We provide fake zone,
1000 		 * holder, and state information.
1001 		 */
1002 
1003 		STRUCT_FSET(lstatus, ctst_zoneid, zone->zone_id);
1004 		/*
1005 		 * Since "zone" can't disappear until the calling ctfs
1006 		 * is unmounted, zone_zsched must be valid.
1007 		 */
1008 		STRUCT_FSET(lstatus, ctst_holder, (ct->ct_state < CTS_ORPHAN) ?
1009 		    zone->zone_zsched->p_pid : 0);
1010 		STRUCT_FSET(lstatus, ctst_state, (ct->ct_state < CTS_ORPHAN) ?
1011 		    CTS_OWNED : ct->ct_state);
1012 	}
1013 	STRUCT_FSET(lstatus, ctst_nevents, ct->ct_evcnt);
1014 	STRUCT_FSET(lstatus, ctst_ntime, get_time_left(&ct->ct_ntime));
1015 	STRUCT_FSET(lstatus, ctst_qtime, get_time_left(&ct->ct_qtime));
1016 	STRUCT_FSET(lstatus, ctst_nevid,
1017 	    ct->ct_nevent ? ct->ct_nevent->cte_id : 0);
1018 	STRUCT_FSET(lstatus, ctst_critical, ct->ct_ev_crit);
1019 	STRUCT_FSET(lstatus, ctst_informative, ct->ct_ev_info);
1020 	STRUCT_FSET(lstatus, ctst_cookie, ct->ct_cookie);
1021 	STRUCT_FSET(lstatus, ctst_type, ct->ct_type->ct_type_index);
1022 	STRUCT_FSET(lstatus, ctst_id, ct->ct_id);
1023 }
1024 
1025 /*
1026  * contract_checkcred
1027  *
1028  * Determines if the specified contract is owned by a process with the
1029  * same effective uid as the specified credential.  The caller must
1030  * ensure that the uid spaces are the same.  Returns 1 on success.
1031  */
1032 static int
1033 contract_checkcred(contract_t *ct, const cred_t *cr)
1034 {
1035 	proc_t *p;
1036 	int fail = 1;
1037 
1038 	mutex_enter(&ct->ct_lock);
1039 	if ((p = ct->ct_owner) != NULL) {
1040 		mutex_enter(&p->p_crlock);
1041 		fail = crgetuid(cr) != crgetuid(p->p_cred);
1042 		mutex_exit(&p->p_crlock);
1043 	}
1044 	mutex_exit(&ct->ct_lock);
1045 
1046 	return (!fail);
1047 }
1048 
1049 /*
1050  * contract_owned
1051  *
1052  * Determines if the specified credential can view an event generated
1053  * by the specified contract.  If locked is set, the contract's ct_lock
1054  * is held and the caller will need to do additional work to determine
1055  * if they truly can see the event.  Returns 1 on success.
1056  */
1057 int
1058 contract_owned(contract_t *ct, const cred_t *cr, int locked)
1059 {
1060 	int owner, cmatch, zmatch;
1061 	uint64_t zuniqid, mzuniqid;
1062 	uid_t euid;
1063 
1064 	ASSERT(locked || MUTEX_NOT_HELD(&ct->ct_lock));
1065 
1066 	zuniqid = curproc->p_zone->zone_uniqid;
1067 	mzuniqid = contract_getzuniqid(ct);
1068 	euid = crgetuid(cr);
1069 
1070 	/*
1071 	 * owner: we own the contract
1072 	 * cmatch: we are in the creator's (and holder's) zone and our
1073 	 *   uid matches the creator's or holder's
1074 	 * zmatch: we are in the effective zone of a contract created
1075 	 *   in the global zone, and our uid matches that of the
1076 	 *   virtualized holder's (zsched/kcred)
1077 	 */
1078 	owner = (ct->ct_owner == curproc);
1079 	cmatch = (zuniqid == ct->ct_czuniqid) &&
1080 	    ((ct->ct_cuid == euid) || (!locked && contract_checkcred(ct, cr)));
1081 	zmatch = (ct->ct_czuniqid != mzuniqid) && (zuniqid == mzuniqid) &&
1082 	    (crgetuid(kcred) == euid);
1083 
1084 	return (owner || cmatch || zmatch);
1085 }
1086 
1087 
1088 /*
1089  * contract_type_init
1090  *
1091  * Called by contract types to register themselves with the contracts
1092  * framework.
1093  */
1094 ct_type_t *
1095 contract_type_init(ct_typeid_t type, const char *name, contops_t *ops,
1096     ct_f_default_t *dfault)
1097 {
1098 	ct_type_t *result;
1099 
1100 	ASSERT(type < CTT_MAXTYPE);
1101 
1102 	result = kmem_alloc(sizeof (ct_type_t), KM_SLEEP);
1103 
1104 	mutex_init(&result->ct_type_lock, NULL, MUTEX_DEFAULT, NULL);
1105 	avl_create(&result->ct_type_avl, contract_compar, sizeof (contract_t),
1106 	    offsetof(contract_t, ct_cttavl));
1107 	cte_queue_create(&result->ct_type_events, CTEL_BUNDLE, 20, 0);
1108 	result->ct_type_name = name;
1109 	result->ct_type_ops = ops;
1110 	result->ct_type_default = dfault;
1111 	result->ct_type_evid = 0;
1112 	gethrestime(&result->ct_type_timestruc);
1113 	result->ct_type_index = type;
1114 
1115 	ct_types[type] = result;
1116 
1117 	return (result);
1118 }
1119 
1120 /*
1121  * contract_type_count
1122  *
1123  * Obtains the number of contracts of a particular type.
1124  */
1125 int
1126 contract_type_count(ct_type_t *type)
1127 {
1128 	ulong_t count;
1129 
1130 	mutex_enter(&type->ct_type_lock);
1131 	count = avl_numnodes(&type->ct_type_avl);
1132 	mutex_exit(&type->ct_type_lock);
1133 
1134 	return (count);
1135 }
1136 
1137 /*
1138  * contract_type_max
1139  *
1140  * Obtains the maximum contract id of of a particular type.
1141  */
1142 ctid_t
1143 contract_type_max(ct_type_t *type)
1144 {
1145 	contract_t *ct;
1146 	ctid_t res;
1147 
1148 	mutex_enter(&type->ct_type_lock);
1149 	ct = avl_last(&type->ct_type_avl);
1150 	res = ct ? ct->ct_id : -1;
1151 	mutex_exit(&type->ct_type_lock);
1152 
1153 	return (res);
1154 }
1155 
1156 /*
1157  * contract_max
1158  *
1159  * Obtains the maximum contract id.
1160  */
1161 ctid_t
1162 contract_max(void)
1163 {
1164 	contract_t *ct;
1165 	ctid_t res;
1166 
1167 	mutex_enter(&contract_lock);
1168 	ct = avl_last(&contract_avl);
1169 	res = ct ? ct->ct_id : -1;
1170 	mutex_exit(&contract_lock);
1171 
1172 	return (res);
1173 }
1174 
1175 /*
1176  * contract_lookup_common
1177  *
1178  * Common code for contract_lookup and contract_type_lookup.  Takes a
1179  * pointer to an AVL tree to search in.  Should be called with the
1180  * appropriate tree-protecting lock held (unfortunately unassertable).
1181  */
1182 static ctid_t
1183 contract_lookup_common(avl_tree_t *tree, uint64_t zuniqid, ctid_t current)
1184 {
1185 	contract_t template, *ct;
1186 	avl_index_t where;
1187 	ctid_t res;
1188 
1189 	template.ct_id = current;
1190 	ct = avl_find(tree, &template, &where);
1191 	if (ct == NULL)
1192 		ct = avl_nearest(tree, where, AVL_AFTER);
1193 	if (zuniqid != GLOBAL_ZONEUNIQID)
1194 		while (ct && (contract_getzuniqid(ct) != zuniqid))
1195 			ct = AVL_NEXT(tree, ct);
1196 	res = ct ? ct->ct_id : -1;
1197 
1198 	return (res);
1199 }
1200 
1201 /*
1202  * contract_type_lookup
1203  *
1204  * Returns the next type contract after the specified id, visible from
1205  * the specified zone.
1206  */
1207 ctid_t
1208 contract_type_lookup(ct_type_t *type, uint64_t zuniqid, ctid_t current)
1209 {
1210 	ctid_t res;
1211 
1212 	mutex_enter(&type->ct_type_lock);
1213 	res = contract_lookup_common(&type->ct_type_avl, zuniqid, current);
1214 	mutex_exit(&type->ct_type_lock);
1215 
1216 	return (res);
1217 }
1218 
1219 /*
1220  * contract_lookup
1221  *
1222  * Returns the next contract after the specified id, visible from the
1223  * specified zone.
1224  */
1225 ctid_t
1226 contract_lookup(uint64_t zuniqid, ctid_t current)
1227 {
1228 	ctid_t res;
1229 
1230 	mutex_enter(&contract_lock);
1231 	res = contract_lookup_common(&contract_avl, zuniqid, current);
1232 	mutex_exit(&contract_lock);
1233 
1234 	return (res);
1235 }
1236 
1237 /*
1238  * contract_plookup
1239  *
1240  * Returns the next contract held by process p after the specified id,
1241  * visible from the specified zone.  Made complicated by the fact that
1242  * contracts visible in a zone but held by processes outside of the
1243  * zone need to appear as being held by zsched to zone members.
1244  */
1245 ctid_t
1246 contract_plookup(proc_t *p, ctid_t current, uint64_t zuniqid)
1247 {
1248 	contract_t template, *ct;
1249 	avl_index_t where;
1250 	ctid_t res;
1251 
1252 	template.ct_id = current;
1253 	if (zuniqid != GLOBAL_ZONEUNIQID &&
1254 	    (p->p_flag & (SSYS|SZONETOP)) == (SSYS|SZONETOP)) {
1255 		/* This is inelegant. */
1256 		mutex_enter(&contract_lock);
1257 		ct = avl_find(&contract_avl, &template, &where);
1258 		if (ct == NULL)
1259 			ct = avl_nearest(&contract_avl, where, AVL_AFTER);
1260 		while (ct && !(ct->ct_state < CTS_ORPHAN &&
1261 		    contract_getzuniqid(ct) == zuniqid &&
1262 		    ct->ct_czuniqid == GLOBAL_ZONEUNIQID))
1263 			ct = AVL_NEXT(&contract_avl, ct);
1264 		res = ct ? ct->ct_id : -1;
1265 		mutex_exit(&contract_lock);
1266 	} else {
1267 		mutex_enter(&p->p_lock);
1268 		ct = avl_find(&p->p_ct_held, &template, &where);
1269 		if (ct == NULL)
1270 			ct = avl_nearest(&p->p_ct_held, where, AVL_AFTER);
1271 		res = ct ? ct->ct_id : -1;
1272 		mutex_exit(&p->p_lock);
1273 	}
1274 
1275 	return (res);
1276 }
1277 
1278 /*
1279  * contract_ptr_common
1280  *
1281  * Common code for contract_ptr and contract_type_ptr.  Takes a pointer
1282  * to an AVL tree to search in.  Should be called with the appropriate
1283  * tree-protecting lock held (unfortunately unassertable).
1284  */
1285 static contract_t *
1286 contract_ptr_common(avl_tree_t *tree, ctid_t id, uint64_t zuniqid)
1287 {
1288 	contract_t template, *ct;
1289 
1290 	template.ct_id = id;
1291 	ct = avl_find(tree, &template, NULL);
1292 	if (ct == NULL || (zuniqid != GLOBAL_ZONEUNIQID &&
1293 	    contract_getzuniqid(ct) != zuniqid)) {
1294 		return (NULL);
1295 	}
1296 
1297 	/*
1298 	 * Check to see if a thread is in the window in contract_rele
1299 	 * between dropping the reference count and removing the
1300 	 * contract from the type AVL.
1301 	 */
1302 	mutex_enter(&ct->ct_reflock);
1303 	if (ct->ct_ref) {
1304 		ct->ct_ref++;
1305 		mutex_exit(&ct->ct_reflock);
1306 	} else {
1307 		mutex_exit(&ct->ct_reflock);
1308 		ct = NULL;
1309 	}
1310 
1311 	return (ct);
1312 }
1313 
1314 /*
1315  * contract_type_ptr
1316  *
1317  * Returns a pointer to the contract with the specified id.  The
1318  * contract is held, so the caller needs to release the reference when
1319  * it is through with the contract.
1320  */
1321 contract_t *
1322 contract_type_ptr(ct_type_t *type, ctid_t id, uint64_t zuniqid)
1323 {
1324 	contract_t *ct;
1325 
1326 	mutex_enter(&type->ct_type_lock);
1327 	ct = contract_ptr_common(&type->ct_type_avl, id, zuniqid);
1328 	mutex_exit(&type->ct_type_lock);
1329 
1330 	return (ct);
1331 }
1332 
1333 /*
1334  * contract_ptr
1335  *
1336  * Returns a pointer to the contract with the specified id.  The
1337  * contract is held, so the caller needs to release the reference when
1338  * it is through with the contract.
1339  */
1340 contract_t *
1341 contract_ptr(ctid_t id, uint64_t zuniqid)
1342 {
1343 	contract_t *ct;
1344 
1345 	mutex_enter(&contract_lock);
1346 	ct = contract_ptr_common(&contract_avl, id, zuniqid);
1347 	mutex_exit(&contract_lock);
1348 
1349 	return (ct);
1350 }
1351 
1352 /*
1353  * contract_type_time
1354  *
1355  * Obtains the last time a contract of a particular type was created.
1356  */
1357 void
1358 contract_type_time(ct_type_t *type, timestruc_t *time)
1359 {
1360 	mutex_enter(&type->ct_type_lock);
1361 	*time = type->ct_type_timestruc;
1362 	mutex_exit(&type->ct_type_lock);
1363 }
1364 
1365 /*
1366  * contract_type_bundle
1367  *
1368  * Obtains a type's bundle queue.
1369  */
1370 ct_equeue_t *
1371 contract_type_bundle(ct_type_t *type)
1372 {
1373 	return (&type->ct_type_events);
1374 }
1375 
1376 /*
1377  * contract_type_pbundle
1378  *
1379  * Obtain's a process's bundle queue.  If one doesn't exist, one is
1380  * created.  Often used simply to ensure that a bundle queue is
1381  * allocated.
1382  */
1383 ct_equeue_t *
1384 contract_type_pbundle(ct_type_t *type, proc_t *pp)
1385 {
1386 	/*
1387 	 * If there isn't an array of bundle queues, allocate one.
1388 	 */
1389 	if (pp->p_ct_equeue == NULL) {
1390 		size_t size = CTT_MAXTYPE * sizeof (ct_equeue_t *);
1391 		ct_equeue_t **qa = kmem_zalloc(size, KM_SLEEP);
1392 
1393 		mutex_enter(&pp->p_lock);
1394 		if (pp->p_ct_equeue)
1395 			kmem_free(qa, size);
1396 		else
1397 			pp->p_ct_equeue = qa;
1398 		mutex_exit(&pp->p_lock);
1399 	}
1400 
1401 	/*
1402 	 * If there isn't a bundle queue of the required type, allocate
1403 	 * one.
1404 	 */
1405 	if (pp->p_ct_equeue[type->ct_type_index] == NULL) {
1406 		ct_equeue_t *q = kmem_zalloc(sizeof (ct_equeue_t), KM_SLEEP);
1407 		cte_queue_create(q, CTEL_PBUNDLE, 20, 1);
1408 
1409 		mutex_enter(&pp->p_lock);
1410 		if (pp->p_ct_equeue[type->ct_type_index])
1411 			cte_queue_drain(q, 0);
1412 		else
1413 			pp->p_ct_equeue[type->ct_type_index] = q;
1414 		mutex_exit(&pp->p_lock);
1415 	}
1416 
1417 	return (pp->p_ct_equeue[type->ct_type_index]);
1418 }
1419 
1420 /*
1421  * ctmpl_free
1422  *
1423  * Frees a template.
1424  */
1425 void
1426 ctmpl_free(ct_template_t *template)
1427 {
1428 	mutex_destroy(&template->ctmpl_lock);
1429 	template->ctmpl_ops->ctop_free(template);
1430 }
1431 
1432 /*
1433  * ctmpl_dup
1434  *
1435  * Creates a copy of a template.
1436  */
1437 ct_template_t *
1438 ctmpl_dup(ct_template_t *template)
1439 {
1440 	ct_template_t *new;
1441 
1442 	if (template == NULL)
1443 		return (NULL);
1444 
1445 	new = template->ctmpl_ops->ctop_dup(template);
1446 	/*
1447 	 * ctmpl_lock was taken by ctop_dup's call to ctmpl_copy and
1448 	 * should have remain held until now.
1449 	 */
1450 	mutex_exit(&template->ctmpl_lock);
1451 
1452 	return (new);
1453 }
1454 
1455 /*
1456  * ctmpl_set
1457  *
1458  * Sets the requested terms of a template.
1459  */
1460 int
1461 ctmpl_set(ct_template_t *template, ct_param_t *param, const cred_t *cr)
1462 {
1463 	int result = 0;
1464 
1465 	mutex_enter(&template->ctmpl_lock);
1466 	switch (param->ctpm_id) {
1467 	case CTP_COOKIE:
1468 		template->ctmpl_cookie = param->ctpm_value;
1469 		break;
1470 	case CTP_EV_INFO:
1471 		if (param->ctpm_value &
1472 		    ~(uint64_t)template->ctmpl_ops->allevents)
1473 			result = EINVAL;
1474 		else
1475 			template->ctmpl_ev_info = param->ctpm_value;
1476 		break;
1477 	case CTP_EV_CRITICAL:
1478 		if (param->ctpm_value &
1479 		    ~(uint64_t)template->ctmpl_ops->allevents) {
1480 			result = EINVAL;
1481 			break;
1482 		} else if ((~template->ctmpl_ev_crit &
1483 		    param->ctpm_value) == 0) {
1484 			/*
1485 			 * Assume that a pure reduction of the critical
1486 			 * set is allowed by the contract type.
1487 			 */
1488 			template->ctmpl_ev_crit = param->ctpm_value;
1489 			break;
1490 		}
1491 		/*
1492 		 * There may be restrictions on what we can make
1493 		 * critical, so we defer to the judgement of the
1494 		 * contract type.
1495 		 */
1496 		/* FALLTHROUGH */
1497 	default:
1498 		result = template->ctmpl_ops->ctop_set(template, param, cr);
1499 	}
1500 	mutex_exit(&template->ctmpl_lock);
1501 
1502 	return (result);
1503 }
1504 
1505 /*
1506  * ctmpl_get
1507  *
1508  * Obtains the requested terms from a template.
1509  */
1510 int
1511 ctmpl_get(ct_template_t *template, ct_param_t *param)
1512 {
1513 	int result = 0;
1514 
1515 	mutex_enter(&template->ctmpl_lock);
1516 	switch (param->ctpm_id) {
1517 	case CTP_COOKIE:
1518 		param->ctpm_value = template->ctmpl_cookie;
1519 		break;
1520 	case CTP_EV_INFO:
1521 		param->ctpm_value = template->ctmpl_ev_info;
1522 		break;
1523 	case CTP_EV_CRITICAL:
1524 		param->ctpm_value = template->ctmpl_ev_crit;
1525 		break;
1526 	default:
1527 		result = template->ctmpl_ops->ctop_get(template, param);
1528 	}
1529 	mutex_exit(&template->ctmpl_lock);
1530 
1531 	return (result);
1532 }
1533 
1534 /*
1535  * ctmpl_makecurrent
1536  *
1537  * Used by ctmpl_activate and ctmpl_clear to set the current thread's
1538  * active template.  Frees the old active template, if there was one.
1539  */
1540 static void
1541 ctmpl_makecurrent(ct_template_t *template, ct_template_t *new)
1542 {
1543 	klwp_t *curlwp = ttolwp(curthread);
1544 	proc_t *p = curproc;
1545 	ct_template_t *old;
1546 
1547 	mutex_enter(&p->p_lock);
1548 	old = curlwp->lwp_ct_active[template->ctmpl_type->ct_type_index];
1549 	curlwp->lwp_ct_active[template->ctmpl_type->ct_type_index] = new;
1550 	mutex_exit(&p->p_lock);
1551 
1552 	if (old)
1553 		ctmpl_free(old);
1554 }
1555 
1556 /*
1557  * ctmpl_activate
1558  *
1559  * Copy the specified template as the current thread's activate
1560  * template of that type.
1561  */
1562 void
1563 ctmpl_activate(ct_template_t *template)
1564 {
1565 	ctmpl_makecurrent(template, ctmpl_dup(template));
1566 }
1567 
1568 /*
1569  * ctmpl_clear
1570  *
1571  * Clears the current thread's activate template of the same type as
1572  * the specified template.
1573  */
1574 void
1575 ctmpl_clear(ct_template_t *template)
1576 {
1577 	ctmpl_makecurrent(template, NULL);
1578 }
1579 
1580 /*
1581  * ctmpl_create
1582  *
1583  * Creates a new contract using the specified template.
1584  */
1585 int
1586 ctmpl_create(ct_template_t *template, ctid_t *ctidp)
1587 {
1588 	return (template->ctmpl_ops->ctop_create(template, ctidp));
1589 }
1590 
1591 /*
1592  * ctmpl_init
1593  *
1594  * Initializes the common portion of a new contract template.
1595  */
1596 void
1597 ctmpl_init(ct_template_t *new, ctmplops_t *ops, ct_type_t *type, void *data)
1598 {
1599 	mutex_init(&new->ctmpl_lock, NULL, MUTEX_DEFAULT, NULL);
1600 	new->ctmpl_ops = ops;
1601 	new->ctmpl_type = type;
1602 	new->ctmpl_data = data;
1603 	new->ctmpl_ev_info = new->ctmpl_ev_crit = 0;
1604 	new->ctmpl_cookie = 0;
1605 }
1606 
1607 /*
1608  * ctmpl_copy
1609  *
1610  * Copies the common portions of a contract template.  Intended for use
1611  * by a contract type's ctop_dup template op.  Returns with the old
1612  * template's lock held, which will should remain held until the
1613  * template op returns (it is dropped by ctmpl_dup).
1614  */
1615 void
1616 ctmpl_copy(ct_template_t *new, ct_template_t *old)
1617 {
1618 	mutex_init(&new->ctmpl_lock, NULL, MUTEX_DEFAULT, NULL);
1619 	mutex_enter(&old->ctmpl_lock);
1620 	new->ctmpl_ops = old->ctmpl_ops;
1621 	new->ctmpl_type = old->ctmpl_type;
1622 	new->ctmpl_ev_crit = old->ctmpl_ev_crit;
1623 	new->ctmpl_ev_info = old->ctmpl_ev_info;
1624 	new->ctmpl_cookie = old->ctmpl_cookie;
1625 }
1626 
1627 /*
1628  * ctmpl_create_inval
1629  *
1630  * Returns EINVAL.  Provided for the convenience of those contract
1631  * types which don't support ct_tmpl_create(3contract) and would
1632  * otherwise need to create their own stub for the ctop_create template
1633  * op.
1634  */
1635 /*ARGSUSED*/
1636 int
1637 ctmpl_create_inval(ct_template_t *template, ctid_t *ctidp)
1638 {
1639 	return (EINVAL);
1640 }
1641 
1642 
1643 /*
1644  * cte_queue_create
1645  *
1646  * Initializes a queue of a particular type.  If dynamic is set, the
1647  * queue is to be freed when its last listener is removed after being
1648  * drained.
1649  */
1650 static void
1651 cte_queue_create(ct_equeue_t *q, ct_listnum_t list, int maxinf, int dynamic)
1652 {
1653 	mutex_init(&q->ctq_lock, NULL, MUTEX_DEFAULT, NULL);
1654 	q->ctq_listno = list;
1655 	list_create(&q->ctq_events, sizeof (ct_kevent_t),
1656 	    offsetof(ct_kevent_t, cte_nodes[list].ctm_node));
1657 	list_create(&q->ctq_listeners, sizeof (ct_listener_t),
1658 	    offsetof(ct_listener_t, ctl_allnode));
1659 	list_create(&q->ctq_tail, sizeof (ct_listener_t),
1660 	    offsetof(ct_listener_t, ctl_tailnode));
1661 	gethrestime(&q->ctq_atime);
1662 	q->ctq_nlisteners = 0;
1663 	q->ctq_nreliable = 0;
1664 	q->ctq_ninf = 0;
1665 	q->ctq_max = maxinf;
1666 
1667 	/*
1668 	 * Bundle queues and contract queues are embedded in other
1669 	 * structures and are implicitly referenced counted by virtue
1670 	 * of their vnodes' indirect hold on their contracts.  Process
1671 	 * bundle queues are dynamically allocated and may persist
1672 	 * after the death of the process, so they must be explicitly
1673 	 * reference counted.
1674 	 */
1675 	q->ctq_flags = dynamic ? CTQ_REFFED : 0;
1676 }
1677 
1678 /*
1679  * cte_queue_destroy
1680  *
1681  * Destroys the specified queue.  The queue is freed if referenced
1682  * counted.
1683  */
1684 static void
1685 cte_queue_destroy(ct_equeue_t *q)
1686 {
1687 	ASSERT(q->ctq_flags & CTQ_DEAD);
1688 	ASSERT(q->ctq_nlisteners == 0);
1689 	ASSERT(q->ctq_nreliable == 0);
1690 	list_destroy(&q->ctq_events);
1691 	list_destroy(&q->ctq_listeners);
1692 	list_destroy(&q->ctq_tail);
1693 	mutex_destroy(&q->ctq_lock);
1694 	if (q->ctq_flags & CTQ_REFFED)
1695 		kmem_free(q, sizeof (ct_equeue_t));
1696 }
1697 
1698 /*
1699  * cte_hold
1700  *
1701  * Takes a hold on the specified event.
1702  */
1703 static void
1704 cte_hold(ct_kevent_t *e)
1705 {
1706 	mutex_enter(&e->cte_lock);
1707 	ASSERT(e->cte_refs > 0);
1708 	e->cte_refs++;
1709 	mutex_exit(&e->cte_lock);
1710 }
1711 
1712 /*
1713  * cte_rele
1714  *
1715  * Releases a hold on the specified event.  If the caller had the last
1716  * reference, frees the event and releases its hold on the contract
1717  * that generated it.
1718  */
1719 static void
1720 cte_rele(ct_kevent_t *e)
1721 {
1722 	mutex_enter(&e->cte_lock);
1723 	ASSERT(e->cte_refs > 0);
1724 	if (--e->cte_refs) {
1725 		mutex_exit(&e->cte_lock);
1726 		return;
1727 	}
1728 
1729 	contract_rele(e->cte_contract);
1730 
1731 	mutex_destroy(&e->cte_lock);
1732 	if (e->cte_data)
1733 		nvlist_free(e->cte_data);
1734 	if (e->cte_gdata)
1735 		nvlist_free(e->cte_gdata);
1736 	kmem_free(e, sizeof (ct_kevent_t));
1737 }
1738 
1739 /*
1740  * cte_qrele
1741  *
1742  * Remove this listener's hold on the specified event, removing and
1743  * releasing the queue's hold on the event if appropriate.
1744  */
1745 static void
1746 cte_qrele(ct_equeue_t *q, ct_listener_t *l, ct_kevent_t *e)
1747 {
1748 	ct_member_t *member = &e->cte_nodes[q->ctq_listno];
1749 
1750 	ASSERT(MUTEX_HELD(&q->ctq_lock));
1751 
1752 	if (l->ctl_flags & CTLF_RELIABLE)
1753 		member->ctm_nreliable--;
1754 	if ((--member->ctm_refs == 0) && member->ctm_trimmed) {
1755 		member->ctm_trimmed = 0;
1756 		list_remove(&q->ctq_events, e);
1757 		cte_rele(e);
1758 	}
1759 }
1760 
1761 /*
1762  * cte_qmove
1763  *
1764  * Move this listener to the specified event in the queue.
1765  */
1766 static ct_kevent_t *
1767 cte_qmove(ct_equeue_t *q, ct_listener_t *l, ct_kevent_t *e)
1768 {
1769 	ct_kevent_t *olde;
1770 
1771 	ASSERT(MUTEX_HELD(&q->ctq_lock));
1772 	ASSERT(l->ctl_equeue == q);
1773 
1774 	if ((olde = l->ctl_position) == NULL)
1775 		list_remove(&q->ctq_tail, l);
1776 
1777 	while (e != NULL && e->cte_nodes[q->ctq_listno].ctm_trimmed)
1778 		e = list_next(&q->ctq_events, e);
1779 
1780 	if (e != NULL) {
1781 		e->cte_nodes[q->ctq_listno].ctm_refs++;
1782 		if (l->ctl_flags & CTLF_RELIABLE)
1783 			e->cte_nodes[q->ctq_listno].ctm_nreliable++;
1784 	} else {
1785 		list_insert_tail(&q->ctq_tail, l);
1786 	}
1787 
1788 	l->ctl_position = e;
1789 	if (olde)
1790 		cte_qrele(q, l, olde);
1791 
1792 	return (e);
1793 }
1794 
1795 /*
1796  * cte_checkcred
1797  *
1798  * Determines if the specified event's contract is owned by a process
1799  * with the same effective uid as the specified credential.  Called
1800  * after a failed call to contract_owned with locked set.  Because it
1801  * drops the queue lock, its caller (cte_qreadable) needs to make sure
1802  * we're still in the same place after we return.  Returns 1 on
1803  * success.
1804  */
1805 static int
1806 cte_checkcred(ct_equeue_t *q, ct_kevent_t *e, const cred_t *cr)
1807 {
1808 	int result;
1809 	contract_t *ct = e->cte_contract;
1810 
1811 	cte_hold(e);
1812 	mutex_exit(&q->ctq_lock);
1813 	result = curproc->p_zone->zone_uniqid == ct->ct_czuniqid &&
1814 	    contract_checkcred(ct, cr);
1815 	mutex_enter(&q->ctq_lock);
1816 	cte_rele(e);
1817 
1818 	return (result);
1819 }
1820 
1821 /*
1822  * cte_qreadable
1823  *
1824  * Ensures that the listener is pointing to a valid event that the
1825  * caller has the credentials to read.  Returns 0 if we can read the
1826  * event we're pointing to.
1827  */
1828 static int
1829 cte_qreadable(ct_equeue_t *q, ct_listener_t *l, const cred_t *cr,
1830     uint64_t zuniqid, int crit)
1831 {
1832 	ct_kevent_t *e, *next;
1833 	contract_t *ct;
1834 
1835 	ASSERT(MUTEX_HELD(&q->ctq_lock));
1836 	ASSERT(l->ctl_equeue == q);
1837 
1838 	if (l->ctl_flags & CTLF_COPYOUT)
1839 		return (1);
1840 
1841 	next = l->ctl_position;
1842 	while (e = cte_qmove(q, l, next)) {
1843 		ct = e->cte_contract;
1844 		/*
1845 		 * Check obvious things first.  If we are looking for a
1846 		 * critical message, is this one?  If we aren't in the
1847 		 * global zone, is this message meant for us?
1848 		 */
1849 		if ((crit && (e->cte_flags & (CTE_INFO | CTE_ACK))) ||
1850 		    (cr != NULL && zuniqid != GLOBAL_ZONEUNIQID &&
1851 		    zuniqid != contract_getzuniqid(ct))) {
1852 
1853 			next = list_next(&q->ctq_events, e);
1854 
1855 		/*
1856 		 * Next, see if our effective uid equals that of owner
1857 		 * or author of the contract.  Since we are holding the
1858 		 * queue lock, contract_owned can't always check if we
1859 		 * have the same effective uid as the contract's
1860 		 * owner.  If it comes to that, it fails and we take
1861 		 * the slow(er) path.
1862 		 */
1863 		} else if (cr != NULL && !contract_owned(ct, cr, B_TRUE)) {
1864 
1865 			/*
1866 			 * At this point we either don't have any claim
1867 			 * to this contract or we match the effective
1868 			 * uid of the owner but couldn't tell.  We
1869 			 * first test for a NULL holder so that events
1870 			 * from orphans and inherited contracts avoid
1871 			 * the penalty phase.
1872 			 */
1873 			if (e->cte_contract->ct_owner == NULL &&
1874 			    !secpolicy_contract_observer_choice(cr))
1875 				next = list_next(&q->ctq_events, e);
1876 
1877 			/*
1878 			 * cte_checkcred will juggle locks to see if we
1879 			 * have the same uid as the event's contract's
1880 			 * current owner.  If it succeeds, we have to
1881 			 * make sure we are in the same point in the
1882 			 * queue.
1883 			 */
1884 			else if (cte_checkcred(q, e, cr) &&
1885 			    l->ctl_position == e)
1886 				break;
1887 
1888 			/*
1889 			 * cte_checkcred failed; see if we're in the
1890 			 * same place.
1891 			 */
1892 			else if (l->ctl_position == e)
1893 				if (secpolicy_contract_observer_choice(cr))
1894 					break;
1895 				else
1896 					next = list_next(&q->ctq_events, e);
1897 
1898 			/*
1899 			 * cte_checkcred failed, and our position was
1900 			 * changed.  Start from there.
1901 			 */
1902 			else
1903 				next = l->ctl_position;
1904 		} else {
1905 			break;
1906 		}
1907 	}
1908 
1909 	/*
1910 	 * We check for CTLF_COPYOUT again in case we dropped the queue
1911 	 * lock in cte_checkcred.
1912 	 */
1913 	return ((l->ctl_flags & CTLF_COPYOUT) || (l->ctl_position == NULL));
1914 }
1915 
1916 /*
1917  * cte_qwakeup
1918  *
1919  * Wakes up any waiting listeners and points them at the specified event.
1920  */
1921 static void
1922 cte_qwakeup(ct_equeue_t *q, ct_kevent_t *e)
1923 {
1924 	ct_listener_t *l;
1925 
1926 	ASSERT(MUTEX_HELD(&q->ctq_lock));
1927 
1928 	while (l = list_head(&q->ctq_tail)) {
1929 		list_remove(&q->ctq_tail, l);
1930 		e->cte_nodes[q->ctq_listno].ctm_refs++;
1931 		if (l->ctl_flags & CTLF_RELIABLE)
1932 			e->cte_nodes[q->ctq_listno].ctm_nreliable++;
1933 		l->ctl_position = e;
1934 		cv_signal(&l->ctl_cv);
1935 		pollwakeup(&l->ctl_pollhead, POLLIN);
1936 	}
1937 }
1938 
1939 /*
1940  * cte_copy
1941  *
1942  * Copies events from the specified contract event queue to the
1943  * end of the specified process bundle queue.  Only called from
1944  * contract_adopt.
1945  *
1946  * We copy to the end of the target queue instead of mixing the events
1947  * in their proper order because otherwise the act of adopting a
1948  * contract would require a process to reset all process bundle
1949  * listeners it needed to see the new events.  This would, in turn,
1950  * require the process to keep track of which preexisting events had
1951  * already been processed.
1952  */
1953 static void
1954 cte_copy(ct_equeue_t *q, ct_equeue_t *newq)
1955 {
1956 	ct_kevent_t *e, *first = NULL;
1957 
1958 	ASSERT(q->ctq_listno == CTEL_CONTRACT);
1959 	ASSERT(newq->ctq_listno == CTEL_PBUNDLE);
1960 
1961 	mutex_enter(&q->ctq_lock);
1962 	mutex_enter(&newq->ctq_lock);
1963 
1964 	/*
1965 	 * For now, only copy critical events.
1966 	 */
1967 	for (e = list_head(&q->ctq_events); e != NULL;
1968 	    e = list_next(&q->ctq_events, e)) {
1969 		if ((e->cte_flags & (CTE_INFO | CTE_ACK)) == 0) {
1970 			if (first == NULL)
1971 				first = e;
1972 			list_insert_tail(&newq->ctq_events, e);
1973 			cte_hold(e);
1974 		}
1975 	}
1976 
1977 	mutex_exit(&q->ctq_lock);
1978 
1979 	if (first)
1980 		cte_qwakeup(newq, first);
1981 
1982 	mutex_exit(&newq->ctq_lock);
1983 }
1984 
1985 /*
1986  * cte_trim
1987  *
1988  * Trims unneeded events from an event queue.  Algorithm works as
1989  * follows:
1990  *
1991  *   Removes all informative and acknowledged critical events until the
1992  *   first referenced event is found.
1993  *
1994  *   If a contract is specified, removes all events (regardless of
1995  *   acknowledgement) generated by that contract until the first event
1996  *   referenced by a reliable listener is found.  Reference events are
1997  *   removed by marking them "trimmed".  Such events will be removed
1998  *   when the last reference is dropped and will be skipped by future
1999  *   listeners.
2000  *
2001  * This is pretty basic.  Ideally this should remove from the middle of
2002  * the list (i.e. beyond the first referenced event), and even
2003  * referenced events.
2004  */
2005 static void
2006 cte_trim(ct_equeue_t *q, contract_t *ct)
2007 {
2008 	ct_kevent_t *e, *next;
2009 	int flags, stopper;
2010 	int start = 1;
2011 
2012 	ASSERT(MUTEX_HELD(&q->ctq_lock));
2013 
2014 	for (e = list_head(&q->ctq_events); e != NULL; e = next) {
2015 		next = list_next(&q->ctq_events, e);
2016 		flags = e->cte_flags;
2017 		stopper = (q->ctq_listno != CTEL_PBUNDLE) &&
2018 		    (e->cte_nodes[q->ctq_listno].ctm_nreliable > 0);
2019 		if (e->cte_nodes[q->ctq_listno].ctm_refs == 0) {
2020 			if ((start && (flags & (CTE_INFO | CTE_ACK))) ||
2021 			    (e->cte_contract == ct)) {
2022 				/*
2023 				 * Toss informative and ACKed critical messages.
2024 				 */
2025 				list_remove(&q->ctq_events, e);
2026 				cte_rele(e);
2027 			}
2028 		} else if ((e->cte_contract == ct) && !stopper) {
2029 			ASSERT(q->ctq_nlisteners != 0);
2030 			e->cte_nodes[q->ctq_listno].ctm_trimmed = 1;
2031 		} else if (ct && !stopper) {
2032 			start = 0;
2033 		} else {
2034 			/*
2035 			 * Don't free messages past the first reader.
2036 			 */
2037 			break;
2038 		}
2039 	}
2040 }
2041 
2042 /*
2043  * cte_queue_drain
2044  *
2045  * Drain all events from the specified queue, and mark it dead.  If
2046  * "ack" is set, acknowledge any critical events we find along the
2047  * way.
2048  */
2049 static void
2050 cte_queue_drain(ct_equeue_t *q, int ack)
2051 {
2052 	ct_kevent_t *e, *next;
2053 	ct_listener_t *l;
2054 
2055 	mutex_enter(&q->ctq_lock);
2056 
2057 	for (e = list_head(&q->ctq_events); e != NULL; e = next) {
2058 		next = list_next(&q->ctq_events, e);
2059 		if (ack && ((e->cte_flags & (CTE_INFO | CTE_ACK)) == 0)) {
2060 			/*
2061 			 * Make sure critical messages are eventually
2062 			 * removed from the bundle queues.
2063 			 */
2064 			mutex_enter(&e->cte_lock);
2065 			e->cte_flags |= CTE_ACK;
2066 			mutex_exit(&e->cte_lock);
2067 			ASSERT(MUTEX_HELD(&e->cte_contract->ct_lock));
2068 			e->cte_contract->ct_evcnt--;
2069 		}
2070 		list_remove(&q->ctq_events, e);
2071 		e->cte_nodes[q->ctq_listno].ctm_refs = 0;
2072 		e->cte_nodes[q->ctq_listno].ctm_nreliable = 0;
2073 		e->cte_nodes[q->ctq_listno].ctm_trimmed = 0;
2074 		cte_rele(e);
2075 	}
2076 
2077 	/*
2078 	 * This is necessary only because of CTEL_PBUNDLE listeners;
2079 	 * the events they point to can move from one pbundle to
2080 	 * another.  Fortunately, this only happens if the contract is
2081 	 * inherited, which (in turn) only happens if the process
2082 	 * exits, which means it's an all-or-nothing deal.  If this
2083 	 * wasn't the case, we would instead need to keep track of
2084 	 * listeners on a per-event basis, not just a per-queue basis.
2085 	 * This would have the side benefit of letting us clean up
2086 	 * trimmed events sooner (i.e. immediately), but would
2087 	 * unfortunately make events even bigger than they already
2088 	 * are.
2089 	 */
2090 	for (l = list_head(&q->ctq_listeners); l;
2091 	    l = list_next(&q->ctq_listeners, l)) {
2092 		l->ctl_flags |= CTLF_DEAD;
2093 		if (l->ctl_position) {
2094 			l->ctl_position = NULL;
2095 			list_insert_tail(&q->ctq_tail, l);
2096 		}
2097 		cv_broadcast(&l->ctl_cv);
2098 	}
2099 
2100 	/*
2101 	 * Disallow events.
2102 	 */
2103 	q->ctq_flags |= CTQ_DEAD;
2104 
2105 	/*
2106 	 * If we represent the last reference to a reference counted
2107 	 * process bundle queue, free it.
2108 	 */
2109 	if ((q->ctq_flags & CTQ_REFFED) && (q->ctq_nlisteners == 0))
2110 		cte_queue_destroy(q);
2111 	else
2112 		mutex_exit(&q->ctq_lock);
2113 }
2114 
2115 /*
2116  * cte_publish
2117  *
2118  * Publishes an event to a specific queue.  Only called by
2119  * cte_publish_all.
2120  */
2121 static void
2122 cte_publish(ct_equeue_t *q, ct_kevent_t *e, timespec_t *tsp)
2123 {
2124 	ASSERT(MUTEX_HELD(&q->ctq_lock));
2125 
2126 	q->ctq_atime = *tsp;
2127 
2128 	/*
2129 	 * Don't publish if the event is informative and there aren't
2130 	 * any listeners, or if the queue has been shut down.
2131 	 */
2132 	if (((q->ctq_nlisteners == 0) && (e->cte_flags & (CTE_INFO|CTE_ACK))) ||
2133 	    (q->ctq_flags & CTQ_DEAD)) {
2134 		mutex_exit(&q->ctq_lock);
2135 		cte_rele(e);
2136 		return;
2137 	}
2138 
2139 	/*
2140 	 * Enqueue event
2141 	 */
2142 	list_insert_tail(&q->ctq_events, e);
2143 
2144 	/*
2145 	 * Check for waiting listeners
2146 	 */
2147 	cte_qwakeup(q, e);
2148 
2149 	/*
2150 	 * Trim unnecessary events from the queue.
2151 	 */
2152 	cte_trim(q, NULL);
2153 	mutex_exit(&q->ctq_lock);
2154 }
2155 
2156 /*
2157  * cte_publish_all
2158  *
2159  * Publish an event to all necessary event queues.  The event, e, must
2160  * be zallocated by the caller, and the event's flags and type must be
2161  * set.  The rest of the event's fields are initialized here.
2162  */
2163 uint64_t
2164 cte_publish_all(contract_t *ct, ct_kevent_t *e, nvlist_t *data, nvlist_t *gdata)
2165 {
2166 	ct_equeue_t *q;
2167 	timespec_t ts;
2168 	uint64_t evid;
2169 	ct_kevent_t *negev;
2170 	int negend;
2171 
2172 	e->cte_contract = ct;
2173 	e->cte_data = data;
2174 	e->cte_gdata = gdata;
2175 	e->cte_refs = 3;
2176 	evid = e->cte_id = atomic_add_64_nv(&ct->ct_type->ct_type_evid, 1);
2177 	contract_hold(ct);
2178 
2179 	/*
2180 	 * For a negotiation event we set the ct->ct_nevent field of the
2181 	 * contract for the duration of the negotiation
2182 	 */
2183 	negend = 0;
2184 	if (e->cte_flags & CTE_NEG) {
2185 		cte_hold(e);
2186 		ct->ct_nevent = e;
2187 	} else if (e->cte_type == CT_EV_NEGEND) {
2188 		negend = 1;
2189 	}
2190 
2191 	gethrestime(&ts);
2192 
2193 	/*
2194 	 * ct_evtlock simply (and only) ensures that two events sent
2195 	 * from the same contract are delivered to all queues in the
2196 	 * same order.
2197 	 */
2198 	mutex_enter(&ct->ct_evtlock);
2199 
2200 	/*
2201 	 * CTEL_CONTRACT - First deliver to the contract queue, acking
2202 	 * the event if the contract has been orphaned.
2203 	 */
2204 	mutex_enter(&ct->ct_lock);
2205 	mutex_enter(&ct->ct_events.ctq_lock);
2206 	if ((e->cte_flags & CTE_INFO) == 0) {
2207 		if (ct->ct_state >= CTS_ORPHAN)
2208 			e->cte_flags |= CTE_ACK;
2209 		else
2210 			ct->ct_evcnt++;
2211 	}
2212 	mutex_exit(&ct->ct_lock);
2213 	cte_publish(&ct->ct_events, e, &ts);
2214 
2215 	/*
2216 	 * CTEL_BUNDLE - Next deliver to the contract type's bundle
2217 	 * queue.
2218 	 */
2219 	mutex_enter(&ct->ct_type->ct_type_events.ctq_lock);
2220 	cte_publish(&ct->ct_type->ct_type_events, e, &ts);
2221 
2222 	/*
2223 	 * CTEL_PBUNDLE - Finally, if the contract has an owner,
2224 	 * deliver to the owner's process bundle queue.
2225 	 */
2226 	mutex_enter(&ct->ct_lock);
2227 	if (ct->ct_owner) {
2228 		/*
2229 		 * proc_exit doesn't free event queues until it has
2230 		 * abandoned all contracts.
2231 		 */
2232 		ASSERT(ct->ct_owner->p_ct_equeue);
2233 		ASSERT(ct->ct_owner->p_ct_equeue[ct->ct_type->ct_type_index]);
2234 		q = ct->ct_owner->p_ct_equeue[ct->ct_type->ct_type_index];
2235 		mutex_enter(&q->ctq_lock);
2236 		mutex_exit(&ct->ct_lock);
2237 		cte_publish(q, e, &ts);
2238 	} else {
2239 		mutex_exit(&ct->ct_lock);
2240 		cte_rele(e);
2241 	}
2242 
2243 	if (negend) {
2244 		mutex_enter(&ct->ct_lock);
2245 		negev = ct->ct_nevent;
2246 		ct->ct_nevent = NULL;
2247 		cte_rele(negev);
2248 		mutex_exit(&ct->ct_lock);
2249 	}
2250 
2251 	mutex_exit(&ct->ct_evtlock);
2252 
2253 	return (evid);
2254 }
2255 
2256 /*
2257  * cte_add_listener
2258  *
2259  * Add a new listener to an event queue.
2260  */
2261 void
2262 cte_add_listener(ct_equeue_t *q, ct_listener_t *l)
2263 {
2264 	cv_init(&l->ctl_cv, NULL, CV_DEFAULT, NULL);
2265 	l->ctl_equeue = q;
2266 	l->ctl_position = NULL;
2267 	l->ctl_flags = 0;
2268 
2269 	mutex_enter(&q->ctq_lock);
2270 	list_insert_head(&q->ctq_tail, l);
2271 	list_insert_head(&q->ctq_listeners, l);
2272 	q->ctq_nlisteners++;
2273 	mutex_exit(&q->ctq_lock);
2274 }
2275 
2276 /*
2277  * cte_remove_listener
2278  *
2279  * Remove a listener from an event queue.  No other queue activities
2280  * (e.g. cte_get event) may be in progress at this endpoint when this
2281  * is called.
2282  */
2283 void
2284 cte_remove_listener(ct_listener_t *l)
2285 {
2286 	ct_equeue_t *q = l->ctl_equeue;
2287 	ct_kevent_t *e;
2288 
2289 	mutex_enter(&q->ctq_lock);
2290 
2291 	ASSERT((l->ctl_flags & (CTLF_COPYOUT|CTLF_RESET)) == 0);
2292 
2293 	if ((e = l->ctl_position) != NULL)
2294 		cte_qrele(q, l, e);
2295 	else
2296 		list_remove(&q->ctq_tail, l);
2297 	l->ctl_position = NULL;
2298 
2299 	q->ctq_nlisteners--;
2300 	list_remove(&q->ctq_listeners, l);
2301 
2302 	if (l->ctl_flags & CTLF_RELIABLE)
2303 		q->ctq_nreliable--;
2304 
2305 	/*
2306 	 * If we are a the last listener of a dead reference counted
2307 	 * queue (i.e. a process bundle) we free it.  Otherwise we just
2308 	 * trim any events which may have been kept around for our
2309 	 * benefit.
2310 	 */
2311 	if ((q->ctq_flags & CTQ_REFFED) && (q->ctq_flags & CTQ_DEAD) &&
2312 	    (q->ctq_nlisteners == 0)) {
2313 		cte_queue_destroy(q);
2314 	} else {
2315 		cte_trim(q, NULL);
2316 		mutex_exit(&q->ctq_lock);
2317 	}
2318 }
2319 
2320 /*
2321  * cte_reset_listener
2322  *
2323  * Moves a listener's queue pointer to the beginning of the queue.
2324  */
2325 void
2326 cte_reset_listener(ct_listener_t *l)
2327 {
2328 	ct_equeue_t *q = l->ctl_equeue;
2329 
2330 	mutex_enter(&q->ctq_lock);
2331 
2332 	/*
2333 	 * We allow an asynchronous reset because it doesn't make a
2334 	 * whole lot of sense to make reset block or fail.  We already
2335 	 * have most of the mechanism needed thanks to queue trimming,
2336 	 * so implementing it isn't a big deal.
2337 	 */
2338 	if (l->ctl_flags & CTLF_COPYOUT)
2339 		l->ctl_flags |= CTLF_RESET;
2340 
2341 	(void) cte_qmove(q, l, list_head(&q->ctq_events));
2342 
2343 	/*
2344 	 * Inform blocked readers.
2345 	 */
2346 	cv_broadcast(&l->ctl_cv);
2347 	pollwakeup(&l->ctl_pollhead, POLLIN);
2348 	mutex_exit(&q->ctq_lock);
2349 }
2350 
2351 /*
2352  * cte_next_event
2353  *
2354  * Moves the event pointer for the specified listener to the next event
2355  * on the queue.  To avoid races, this movement only occurs if the
2356  * specified event id matches that of the current event.  This is used
2357  * primarily to skip events that have been read but whose extended data
2358  * haven't been copied out.
2359  */
2360 int
2361 cte_next_event(ct_listener_t *l, uint64_t id)
2362 {
2363 	ct_equeue_t *q = l->ctl_equeue;
2364 	ct_kevent_t *old;
2365 
2366 	mutex_enter(&q->ctq_lock);
2367 
2368 	if (l->ctl_flags & CTLF_COPYOUT)
2369 		l->ctl_flags |= CTLF_RESET;
2370 
2371 	if (((old = l->ctl_position) != NULL) && (old->cte_id == id))
2372 		(void) cte_qmove(q, l, list_next(&q->ctq_events, old));
2373 
2374 	mutex_exit(&q->ctq_lock);
2375 
2376 	return (0);
2377 }
2378 
2379 /*
2380  * cte_get_event
2381  *
2382  * Reads an event from an event endpoint.  If "nonblock" is clear, we
2383  * block until a suitable event is ready.  If "crit" is set, we only
2384  * read critical events.  Note that while "cr" is the caller's cred,
2385  * "zuniqid" is the unique id of the zone the calling contract
2386  * filesystem was mounted in.
2387  */
2388 int
2389 cte_get_event(ct_listener_t *l, int nonblock, void *uaddr, const cred_t *cr,
2390     uint64_t zuniqid, int crit)
2391 {
2392 	ct_equeue_t *q = l->ctl_equeue;
2393 	ct_kevent_t *temp;
2394 	int result = 0;
2395 	int partial = 0;
2396 	size_t size, gsize, len;
2397 	model_t mdl = get_udatamodel();
2398 	STRUCT_DECL(ct_event, ev);
2399 	STRUCT_INIT(ev, mdl);
2400 
2401 	/*
2402 	 * cte_qreadable checks for CTLF_COPYOUT as well as ensures
2403 	 * that there exists, and we are pointing to, an appropriate
2404 	 * event.  It may temporarily drop ctq_lock, but that doesn't
2405 	 * really matter to us.
2406 	 */
2407 	mutex_enter(&q->ctq_lock);
2408 	while (cte_qreadable(q, l, cr, zuniqid, crit)) {
2409 		if (nonblock) {
2410 			result = EAGAIN;
2411 			goto error;
2412 		}
2413 		if (q->ctq_flags & CTQ_DEAD) {
2414 			result = EIDRM;
2415 			goto error;
2416 		}
2417 		result = cv_wait_sig(&l->ctl_cv, &q->ctq_lock);
2418 		if (result == 0) {
2419 			result = EINTR;
2420 			goto error;
2421 		}
2422 	}
2423 	temp = l->ctl_position;
2424 	cte_hold(temp);
2425 	l->ctl_flags |= CTLF_COPYOUT;
2426 	mutex_exit(&q->ctq_lock);
2427 
2428 	/*
2429 	 * We now have an event.  Copy in the user event structure to
2430 	 * see how much space we have to work with.
2431 	 */
2432 	result = copyin(uaddr, STRUCT_BUF(ev), STRUCT_SIZE(ev));
2433 	if (result)
2434 		goto copyerr;
2435 
2436 	/*
2437 	 * Determine what data we have and what the user should be
2438 	 * allowed to see.
2439 	 */
2440 	size = gsize = 0;
2441 	if (temp->cte_data) {
2442 		VERIFY(nvlist_size(temp->cte_data, &size,
2443 		    NV_ENCODE_NATIVE) == 0);
2444 		ASSERT(size != 0);
2445 	}
2446 	if (zuniqid == GLOBAL_ZONEUNIQID && temp->cte_gdata) {
2447 		VERIFY(nvlist_size(temp->cte_gdata, &gsize,
2448 		    NV_ENCODE_NATIVE) == 0);
2449 		ASSERT(gsize != 0);
2450 	}
2451 
2452 	/*
2453 	 * If we have enough space, copy out the extended event data.
2454 	 */
2455 	len = size + gsize;
2456 	if (len) {
2457 		if (STRUCT_FGET(ev, ctev_nbytes) >= len) {
2458 			char *buf = kmem_alloc(len, KM_SLEEP);
2459 
2460 			if (size)
2461 				VERIFY(nvlist_pack(temp->cte_data, &buf, &size,
2462 				    NV_ENCODE_NATIVE, KM_SLEEP) == 0);
2463 			if (gsize) {
2464 				char *tmp = buf + size;
2465 
2466 				VERIFY(nvlist_pack(temp->cte_gdata, &tmp,
2467 				    &gsize, NV_ENCODE_NATIVE, KM_SLEEP) == 0);
2468 			}
2469 
2470 			/* This shouldn't have changed */
2471 			ASSERT(size + gsize == len);
2472 			result = copyout(buf, STRUCT_FGETP(ev, ctev_buffer),
2473 			    len);
2474 			kmem_free(buf, len);
2475 			if (result)
2476 				goto copyerr;
2477 		} else {
2478 			partial = 1;
2479 		}
2480 	}
2481 
2482 	/*
2483 	 * Copy out the common event data.
2484 	 */
2485 	STRUCT_FSET(ev, ctev_id, temp->cte_contract->ct_id);
2486 	STRUCT_FSET(ev, ctev_evid, temp->cte_id);
2487 	STRUCT_FSET(ev, ctev_cttype,
2488 	    temp->cte_contract->ct_type->ct_type_index);
2489 	STRUCT_FSET(ev, ctev_flags, temp->cte_flags &
2490 	    (CTE_ACK|CTE_INFO|CTE_NEG));
2491 	STRUCT_FSET(ev, ctev_type, temp->cte_type);
2492 	STRUCT_FSET(ev, ctev_nbytes, len);
2493 	STRUCT_FSET(ev, ctev_goffset, size);
2494 	result = copyout(STRUCT_BUF(ev), uaddr, STRUCT_SIZE(ev));
2495 
2496 copyerr:
2497 	/*
2498 	 * Only move our location in the queue if all copyouts were
2499 	 * successful, the caller provided enough space for the entire
2500 	 * event, and our endpoint wasn't reset or otherwise moved by
2501 	 * another thread.
2502 	 */
2503 	mutex_enter(&q->ctq_lock);
2504 	if (result)
2505 		result = EFAULT;
2506 	else if (!partial && ((l->ctl_flags & CTLF_RESET) == 0) &&
2507 	    (l->ctl_position == temp))
2508 		(void) cte_qmove(q, l, list_next(&q->ctq_events, temp));
2509 	l->ctl_flags &= ~(CTLF_COPYOUT|CTLF_RESET);
2510 	/*
2511 	 * Signal any readers blocked on our CTLF_COPYOUT.
2512 	 */
2513 	cv_signal(&l->ctl_cv);
2514 	cte_rele(temp);
2515 
2516 error:
2517 	mutex_exit(&q->ctq_lock);
2518 	return (result);
2519 }
2520 
2521 /*
2522  * cte_set_reliable
2523  *
2524  * Requests that events be reliably delivered to an event endpoint.
2525  * Unread informative and acknowledged critical events will not be
2526  * removed from the queue until this listener reads or skips them.
2527  * Because a listener could maliciously request reliable delivery and
2528  * then do nothing, this requires that PRIV_CONTRACT_EVENT be in the
2529  * caller's effective set.
2530  */
2531 int
2532 cte_set_reliable(ct_listener_t *l, const cred_t *cr)
2533 {
2534 	ct_equeue_t *q = l->ctl_equeue;
2535 	int error;
2536 
2537 	if ((error = secpolicy_contract_event(cr)) != 0)
2538 		return (error);
2539 
2540 	mutex_enter(&q->ctq_lock);
2541 	if ((l->ctl_flags & CTLF_RELIABLE) == 0) {
2542 		l->ctl_flags |= CTLF_RELIABLE;
2543 		q->ctq_nreliable++;
2544 		if (l->ctl_position != NULL)
2545 			l->ctl_position->cte_nodes[q->ctq_listno].
2546 			    ctm_nreliable++;
2547 	}
2548 	mutex_exit(&q->ctq_lock);
2549 
2550 	return (0);
2551 }
2552