xref: /titanic_51/usr/src/uts/common/os/strsubr.c (revision 505d05c73a6e56769f263d4803b22eddd168ee24)
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 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
23 /*	  All Rights Reserved  	*/
24 
25 
26 /*
27  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
28  * Use is subject to license terms.
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/types.h>
34 #include <sys/sysmacros.h>
35 #include <sys/param.h>
36 #include <sys/errno.h>
37 #include <sys/signal.h>
38 #include <sys/proc.h>
39 #include <sys/conf.h>
40 #include <sys/cred.h>
41 #include <sys/user.h>
42 #include <sys/vnode.h>
43 #include <sys/file.h>
44 #include <sys/session.h>
45 #include <sys/stream.h>
46 #include <sys/strsubr.h>
47 #include <sys/stropts.h>
48 #include <sys/poll.h>
49 #include <sys/systm.h>
50 #include <sys/cpuvar.h>
51 #include <sys/uio.h>
52 #include <sys/cmn_err.h>
53 #include <sys/priocntl.h>
54 #include <sys/procset.h>
55 #include <sys/vmem.h>
56 #include <sys/bitmap.h>
57 #include <sys/kmem.h>
58 #include <sys/siginfo.h>
59 #include <sys/vtrace.h>
60 #include <sys/callb.h>
61 #include <sys/debug.h>
62 #include <sys/modctl.h>
63 #include <sys/vmsystm.h>
64 #include <vm/page.h>
65 #include <sys/atomic.h>
66 #include <sys/suntpi.h>
67 #include <sys/strlog.h>
68 #include <sys/promif.h>
69 #include <sys/project.h>
70 #include <sys/vm.h>
71 #include <sys/taskq.h>
72 #include <sys/sunddi.h>
73 #include <sys/sunldi_impl.h>
74 #include <sys/strsun.h>
75 #include <sys/isa_defs.h>
76 #include <sys/multidata.h>
77 #include <sys/pattr.h>
78 #include <sys/strft.h>
79 #include <sys/fs/snode.h>
80 #include <sys/zone.h>
81 
82 #define	O_SAMESTR(q)	(((q)->q_next) && \
83 	(((q)->q_flag & QREADR) == ((q)->q_next->q_flag & QREADR)))
84 
85 /*
86  * WARNING:
87  * The variables and routines in this file are private, belonging
88  * to the STREAMS subsystem. These should not be used by modules
89  * or drivers. Compatibility will not be guaranteed.
90  */
91 
92 /*
93  * Id value used to distinguish between different multiplexor links.
94  */
95 static int32_t lnk_id = 0;
96 
97 #define	STREAMS_LOPRI MINCLSYSPRI
98 static pri_t streams_lopri = STREAMS_LOPRI;
99 
100 #define	STRSTAT(x)	(str_statistics.x.value.ui64++)
101 typedef struct str_stat {
102 	kstat_named_t	sqenables;
103 	kstat_named_t	stenables;
104 	kstat_named_t	syncqservice;
105 	kstat_named_t	freebs;
106 	kstat_named_t	qwr_outer;
107 	kstat_named_t	rservice;
108 	kstat_named_t	strwaits;
109 	kstat_named_t	taskqfails;
110 	kstat_named_t	bufcalls;
111 	kstat_named_t	qhelps;
112 	kstat_named_t	qremoved;
113 	kstat_named_t	sqremoved;
114 	kstat_named_t	bcwaits;
115 	kstat_named_t	sqtoomany;
116 } str_stat_t;
117 
118 static str_stat_t str_statistics = {
119 	{ "sqenables",		KSTAT_DATA_UINT64 },
120 	{ "stenables",		KSTAT_DATA_UINT64 },
121 	{ "syncqservice",	KSTAT_DATA_UINT64 },
122 	{ "freebs",		KSTAT_DATA_UINT64 },
123 	{ "qwr_outer",		KSTAT_DATA_UINT64 },
124 	{ "rservice",		KSTAT_DATA_UINT64 },
125 	{ "strwaits",		KSTAT_DATA_UINT64 },
126 	{ "taskqfails",		KSTAT_DATA_UINT64 },
127 	{ "bufcalls",		KSTAT_DATA_UINT64 },
128 	{ "qhelps",		KSTAT_DATA_UINT64 },
129 	{ "qremoved",		KSTAT_DATA_UINT64 },
130 	{ "sqremoved",		KSTAT_DATA_UINT64 },
131 	{ "bcwaits",		KSTAT_DATA_UINT64 },
132 	{ "sqtoomany",		KSTAT_DATA_UINT64 },
133 };
134 
135 static kstat_t *str_kstat;
136 
137 /*
138  * qrunflag was used previously to control background scheduling of queues. It
139  * is not used anymore, but kept here in case some module still wants to access
140  * it via qready() and setqsched macros.
141  */
142 char qrunflag;			/*  Unused */
143 
144 /*
145  * Most of the streams scheduling is done via task queues. Task queues may fail
146  * for non-sleep dispatches, so there are two backup threads servicing failed
147  * requests for queues and syncqs. Both of these threads also service failed
148  * dispatches freebs requests. Queues are put in the list specified by `qhead'
149  * and `qtail' pointers, syncqs use `sqhead' and `sqtail' pointers and freebs
150  * requests are put into `freebs_list' which has no tail pointer. All three
151  * lists are protected by a single `service_queue' lock and use
152  * `services_to_run' condition variable for signaling background threads. Use of
153  * a single lock should not be a problem because it is only used under heavy
154  * loads when task queues start to fail and at that time it may be a good idea
155  * to throttle scheduling requests.
156  *
157  * NOTE: queues and syncqs should be scheduled by two separate threads because
158  * queue servicing may be blocked waiting for a syncq which may be also
159  * scheduled for background execution. This may create a deadlock when only one
160  * thread is used for both.
161  */
162 
163 static taskq_t *streams_taskq;		/* Used for most STREAMS scheduling */
164 
165 static kmutex_t service_queue;		/* protects all of servicing vars */
166 static kcondvar_t services_to_run;	/* wake up background service thread */
167 static kcondvar_t syncqs_to_run;	/* wake up background service thread */
168 
169 /*
170  * List of queues scheduled for background processing dueue to lack of resources
171  * in the task queues. Protected by service_queue lock;
172  */
173 static struct queue *qhead;
174 static struct queue *qtail;
175 
176 /*
177  * Same list for syncqs
178  */
179 static syncq_t *sqhead;
180 static syncq_t *sqtail;
181 
182 static mblk_t *freebs_list;	/* list of buffers to free */
183 
184 /*
185  * Backup threads for servicing queues and syncqs
186  */
187 kthread_t *streams_qbkgrnd_thread;
188 kthread_t *streams_sqbkgrnd_thread;
189 
190 /*
191  * Bufcalls related variables.
192  */
193 struct bclist	strbcalls;	/* list of waiting bufcalls */
194 kmutex_t	strbcall_lock;	/* protects bufcall list (strbcalls) */
195 kcondvar_t	strbcall_cv;	/* Signaling when a bufcall is added */
196 kmutex_t	bcall_monitor;	/* sleep/wakeup style monitor */
197 kcondvar_t	bcall_cv;	/* wait 'till executing bufcall completes */
198 kthread_t	*bc_bkgrnd_thread; /* Thread to service bufcall requests */
199 
200 kmutex_t	strresources;	/* protects global resources */
201 kmutex_t	muxifier;	/* single-threads multiplexor creation */
202 
203 extern void	time_to_wait(clock_t *, clock_t);
204 
205 /*
206  * run_queues is no longer used, but is kept in case some 3-d party
207  * module/driver decides to use it.
208  */
209 int run_queues = 0;
210 
211 /*
212  * sq_max_size is the depth of the syncq (in number of messages) before
213  * qfill_syncq() starts QFULL'ing destination queues. As its primary
214  * consumer - IP is no longer D_MTPERMOD, but there may be other
215  * modules/drivers depend on this syncq flow control, we prefer to
216  * choose a large number as the default value. For potential
217  * performance gain, this value is tunable in /etc/system.
218  */
219 int sq_max_size = 10000;
220 
221 /*
222  * the number of ciputctrl structures per syncq and stream we create when
223  * needed.
224  */
225 int n_ciputctrl;
226 int max_n_ciputctrl = 16;
227 /*
228  * if n_ciputctrl is < min_n_ciputctrl don't even create ciputctrl_cache.
229  */
230 int min_n_ciputctrl = 2;
231 
232 static struct mux_node *mux_nodes;	/* mux info for cycle checking */
233 
234 /*
235  * Per-driver/module syncqs
236  * ========================
237  *
238  * For drivers/modules that use PERMOD or outer syncqs we keep a list of
239  * perdm structures, new entries being added (and new syncqs allocated) when
240  * setq() encounters a module/driver with a streamtab that it hasn't seen
241  * before.
242  * The reason for this mechanism is that some modules and drivers share a
243  * common streamtab and it is necessary for those modules and drivers to also
244  * share a common PERMOD syncq.
245  *
246  * perdm_list --> dm_str == streamtab_1
247  *                dm_sq == syncq_1
248  *                dm_ref
249  *                dm_next --> dm_str == streamtab_2
250  *                            dm_sq == syncq_2
251  *                            dm_ref
252  *                            dm_next --> ... NULL
253  *
254  * The dm_ref field is incremented for each new driver/module that takes
255  * a reference to the perdm structure and hence shares the syncq.
256  * References are held in the fmodsw_impl_t structure for each STREAMS module
257  * or the dev_impl array (indexed by device major number) for each driver.
258  *
259  * perdm_list -> [dm_ref == 1] -> [dm_ref == 2] -> [dm_ref == 1] -> NULL
260  *		     ^                 ^ ^               ^
261  *                   |  ______________/  |               |
262  *                   | /                 |               |
263  * dev_impl:     ...|x|y|...          module A	      module B
264  *
265  * When a module/driver is unloaded the reference count is decremented and,
266  * when it falls to zero, the perdm structure is removed from the list and
267  * the syncq is freed (see rele_dm()).
268  */
269 perdm_t *perdm_list = NULL;
270 static krwlock_t perdm_rwlock;
271 cdevsw_impl_t *devimpl;
272 
273 extern struct qinit strdata;
274 extern struct qinit stwdata;
275 
276 static void runservice(queue_t *);
277 static void streams_bufcall_service(void);
278 static void streams_qbkgrnd_service(void);
279 static void streams_sqbkgrnd_service(void);
280 static syncq_t *new_syncq(void);
281 static void free_syncq(syncq_t *);
282 static void outer_insert(syncq_t *, syncq_t *);
283 static void outer_remove(syncq_t *, syncq_t *);
284 static void write_now(syncq_t *);
285 static void clr_qfull(queue_t *);
286 static void enable_svc(queue_t *);
287 static void runbufcalls(void);
288 static void sqenable(syncq_t *);
289 static void sqfill_events(syncq_t *, queue_t *, mblk_t *, void (*)());
290 static void wait_q_syncq(queue_t *);
291 static void backenable_insertedq(queue_t *);
292 
293 static void queue_service(queue_t *);
294 static void stream_service(stdata_t *);
295 static void syncq_service(syncq_t *);
296 static void qwriter_outer_service(syncq_t *);
297 static void mblk_free(mblk_t *);
298 #ifdef DEBUG
299 static int qprocsareon(queue_t *);
300 #endif
301 
302 static void set_nfsrv_ptr(queue_t *, queue_t *, queue_t *, queue_t *);
303 static void reset_nfsrv_ptr(queue_t *, queue_t *);
304 
305 static void sq_run_events(syncq_t *);
306 static int propagate_syncq(queue_t *);
307 
308 static void	blocksq(syncq_t *, ushort_t, int);
309 static void	unblocksq(syncq_t *, ushort_t, int);
310 static int	dropsq(syncq_t *, uint16_t);
311 static void	emptysq(syncq_t *);
312 static sqlist_t *sqlist_alloc(struct stdata *, int);
313 static void	sqlist_free(sqlist_t *);
314 static sqlist_t	*sqlist_build(queue_t *, struct stdata *, boolean_t);
315 static void	sqlist_insert(sqlist_t *, syncq_t *);
316 static void	sqlist_insertall(sqlist_t *, queue_t *);
317 
318 static void	strsetuio(stdata_t *);
319 
320 struct kmem_cache *stream_head_cache;
321 struct kmem_cache *queue_cache;
322 struct kmem_cache *syncq_cache;
323 struct kmem_cache *qband_cache;
324 struct kmem_cache *linkinfo_cache;
325 struct kmem_cache *ciputctrl_cache = NULL;
326 
327 static linkinfo_t *linkinfo_list;
328 
329 /*
330  *  Qinit structure and Module_info structures
331  *	for passthru read and write queues
332  */
333 
334 static void pass_wput(queue_t *, mblk_t *);
335 static queue_t *link_addpassthru(stdata_t *);
336 static void link_rempassthru(queue_t *);
337 
338 struct  module_info passthru_info = {
339 	0,
340 	"passthru",
341 	0,
342 	INFPSZ,
343 	STRHIGH,
344 	STRLOW
345 };
346 
347 struct  qinit passthru_rinit = {
348 	(int (*)())putnext,
349 	NULL,
350 	NULL,
351 	NULL,
352 	NULL,
353 	&passthru_info,
354 	NULL
355 };
356 
357 struct  qinit passthru_winit = {
358 	(int (*)()) pass_wput,
359 	NULL,
360 	NULL,
361 	NULL,
362 	NULL,
363 	&passthru_info,
364 	NULL
365 };
366 
367 /*
368  * Special form of assertion: verify that X implies Y i.e. when X is true Y
369  * should also be true.
370  */
371 #define	IMPLY(X, Y)	ASSERT(!(X) || (Y))
372 
373 /*
374  * Logical equivalence. Verify that both X and Y are either TRUE or FALSE.
375  */
376 #define	EQUIV(X, Y)	{ IMPLY(X, Y); IMPLY(Y, X); }
377 
378 /*
379  * Verify correctness of list head/tail pointers.
380  */
381 #define	LISTCHECK(head, tail, link) {				\
382 	EQUIV(head, tail);					\
383 	IMPLY(tail != NULL, tail->link == NULL);		\
384 }
385 
386 /*
387  * Enqueue a list element `el' in the end of a list denoted by `head' and `tail'
388  * using a `link' field.
389  */
390 #define	ENQUEUE(el, head, tail, link) {				\
391 	ASSERT(el->link == NULL);				\
392 	LISTCHECK(head, tail, link);				\
393 	if (head == NULL)					\
394 		head = el;					\
395 	else							\
396 		tail->link = el;				\
397 	tail = el;						\
398 }
399 
400 /*
401  * Dequeue the first element of the list denoted by `head' and `tail' pointers
402  * using a `link' field and put result into `el'.
403  */
404 #define	DQ(el, head, tail, link) {				\
405 	LISTCHECK(head, tail, link);				\
406 	el = head;						\
407 	if (head != NULL) {					\
408 		head = head->link;				\
409 		if (head == NULL)				\
410 			tail = NULL;				\
411 		el->link = NULL;				\
412 	}							\
413 }
414 
415 /*
416  * Remove `el' from the list using `chase' and `curr' pointers and return result
417  * in `succeed'.
418  */
419 #define	RMQ(el, head, tail, link, chase, curr, succeed) {	\
420 	LISTCHECK(head, tail, link);				\
421 	chase = NULL;						\
422 	succeed = 0;						\
423 	for (curr = head; (curr != el) && (curr != NULL); curr = curr->link) \
424 		chase = curr;					\
425 	if (curr != NULL) {					\
426 		succeed = 1;					\
427 		ASSERT(curr == el);				\
428 		if (chase != NULL)				\
429 			chase->link = curr->link;		\
430 		else						\
431 			head = curr->link;			\
432 		curr->link = NULL;				\
433 		if (curr == tail)				\
434 			tail = chase;				\
435 	}							\
436 	LISTCHECK(head, tail, link);				\
437 }
438 
439 /* Handling of delayed messages on the inner syncq. */
440 
441 /*
442  * DEBUG versions should use function versions (to simplify tracing) and
443  * non-DEBUG kernels should use macro versions.
444  */
445 
446 /*
447  * Put a queue on the syncq list of queues.
448  * Assumes SQLOCK held.
449  */
450 #define	SQPUT_Q(sq, qp)							\
451 {									\
452 	ASSERT(MUTEX_HELD(SQLOCK(sq)));					\
453 	if (!(qp->q_sqflags & Q_SQQUEUED)) {				\
454 		/* The queue should not be linked anywhere */		\
455 		ASSERT((qp->q_sqprev == NULL) && (qp->q_sqnext == NULL)); \
456 		/* Head and tail may only be NULL simultaneously */	\
457 		EQUIV(sq->sq_head, sq->sq_tail);			\
458 		/* Queue may be only enqueyed on its syncq */		\
459 		ASSERT(sq == qp->q_syncq);				\
460 		/* Check the correctness of SQ_MESSAGES flag */		\
461 		EQUIV(sq->sq_head, (sq->sq_flags & SQ_MESSAGES));	\
462 		/* Sanity check first/last elements of the list */	\
463 		IMPLY(sq->sq_head != NULL, sq->sq_head->q_sqprev == NULL);\
464 		IMPLY(sq->sq_tail != NULL, sq->sq_tail->q_sqnext == NULL);\
465 		/*							\
466 		 * Sanity check of priority field: empty queue should	\
467 		 * have zero priority					\
468 		 * and nqueues equal to zero.				\
469 		 */							\
470 		IMPLY(sq->sq_head == NULL, sq->sq_pri == 0);		\
471 		/* Sanity check of sq_nqueues field */			\
472 		EQUIV(sq->sq_head, sq->sq_nqueues);			\
473 		if (sq->sq_head == NULL) {				\
474 			sq->sq_head = sq->sq_tail = qp;			\
475 			sq->sq_flags |= SQ_MESSAGES;			\
476 		} else if (qp->q_spri == 0) {				\
477 			qp->q_sqprev = sq->sq_tail;			\
478 			sq->sq_tail->q_sqnext = qp;			\
479 			sq->sq_tail = qp;				\
480 		} else {						\
481 			/*						\
482 			 * Put this queue in priority order: higher	\
483 			 * priority gets closer to the head.		\
484 			 */						\
485 			queue_t **qpp = &sq->sq_tail;			\
486 			queue_t *qnext = NULL;				\
487 									\
488 			while (*qpp != NULL && qp->q_spri > (*qpp)->q_spri) { \
489 				qnext = *qpp;				\
490 				qpp = &(*qpp)->q_sqprev;		\
491 			}						\
492 			qp->q_sqnext = qnext;				\
493 			qp->q_sqprev = *qpp;				\
494 			if (*qpp != NULL) {				\
495 				(*qpp)->q_sqnext = qp;			\
496 			} else {					\
497 				sq->sq_head = qp;			\
498 				sq->sq_pri = sq->sq_head->q_spri;	\
499 			}						\
500 			*qpp = qp;					\
501 		}							\
502 		qp->q_sqflags |= Q_SQQUEUED;				\
503 		qp->q_sqtstamp = lbolt;					\
504 		sq->sq_nqueues++;					\
505 	}								\
506 }
507 
508 /*
509  * Remove a queue from the syncq list
510  * Assumes SQLOCK held.
511  */
512 #define	SQRM_Q(sq, qp)							\
513 	{								\
514 		ASSERT(MUTEX_HELD(SQLOCK(sq)));				\
515 		ASSERT(qp->q_sqflags & Q_SQQUEUED);			\
516 		ASSERT(sq->sq_head != NULL && sq->sq_tail != NULL);	\
517 		ASSERT((sq->sq_flags & SQ_MESSAGES) != 0);		\
518 		/* Check that the queue is actually in the list */	\
519 		ASSERT(qp->q_sqnext != NULL || sq->sq_tail == qp);	\
520 		ASSERT(qp->q_sqprev != NULL || sq->sq_head == qp);	\
521 		ASSERT(sq->sq_nqueues != 0);				\
522 		if (qp->q_sqprev == NULL) {				\
523 			/* First queue on list, make head q_sqnext */	\
524 			sq->sq_head = qp->q_sqnext;			\
525 		} else {						\
526 			/* Make prev->next == next */			\
527 			qp->q_sqprev->q_sqnext = qp->q_sqnext;		\
528 		}							\
529 		if (qp->q_sqnext == NULL) {				\
530 			/* Last queue on list, make tail sqprev */	\
531 			sq->sq_tail = qp->q_sqprev;			\
532 		} else {						\
533 			/* Make next->prev == prev */			\
534 			qp->q_sqnext->q_sqprev = qp->q_sqprev;		\
535 		}							\
536 		/* clear out references on this queue */		\
537 		qp->q_sqprev = qp->q_sqnext = NULL;			\
538 		qp->q_sqflags &= ~Q_SQQUEUED;				\
539 		/* If there is nothing queued, clear SQ_MESSAGES */	\
540 		if (sq->sq_head != NULL) {				\
541 			sq->sq_pri = sq->sq_head->q_spri;		\
542 		} else	{						\
543 			sq->sq_flags &= ~SQ_MESSAGES;			\
544 			sq->sq_pri = 0;					\
545 		}							\
546 		sq->sq_nqueues--;					\
547 		ASSERT(sq->sq_head != NULL || sq->sq_evhead != NULL ||	\
548 		    (sq->sq_flags & SQ_QUEUED) == 0);			\
549 	}
550 
551 /* Hide the definition from the header file. */
552 #ifdef SQPUT_MP
553 #undef SQPUT_MP
554 #endif
555 
556 /*
557  * Put a message on the queue syncq.
558  * Assumes QLOCK held.
559  */
560 #define	SQPUT_MP(qp, mp)						\
561 	{								\
562 		ASSERT(MUTEX_HELD(QLOCK(qp)));				\
563 		ASSERT(qp->q_sqhead == NULL ||				\
564 		    (qp->q_sqtail != NULL &&				\
565 		    qp->q_sqtail->b_next == NULL));			\
566 		qp->q_syncqmsgs++;					\
567 		ASSERT(qp->q_syncqmsgs != 0);	/* Wraparound */	\
568 		if (qp->q_sqhead == NULL) {				\
569 			qp->q_sqhead = qp->q_sqtail = mp;		\
570 		} else {						\
571 			qp->q_sqtail->b_next = mp;			\
572 			qp->q_sqtail = mp;				\
573 		}							\
574 		ASSERT(qp->q_syncqmsgs > 0);				\
575 	}
576 
577 #define	SQ_PUTCOUNT_SETFAST_LOCKED(sq) {				\
578 		ASSERT(MUTEX_HELD(SQLOCK(sq)));				\
579 		if ((sq)->sq_ciputctrl != NULL) {			\
580 			int i;						\
581 			int nlocks = (sq)->sq_nciputctrl;		\
582 			ciputctrl_t *cip = (sq)->sq_ciputctrl;		\
583 			ASSERT((sq)->sq_type & SQ_CIPUT);		\
584 			for (i = 0; i <= nlocks; i++) {			\
585 				ASSERT(MUTEX_HELD(&cip[i].ciputctrl_lock)); \
586 				cip[i].ciputctrl_count |= SQ_FASTPUT;	\
587 			}						\
588 		}							\
589 	}
590 
591 
592 #define	SQ_PUTCOUNT_CLRFAST_LOCKED(sq) {				\
593 		ASSERT(MUTEX_HELD(SQLOCK(sq)));				\
594 		if ((sq)->sq_ciputctrl != NULL) {			\
595 			int i;						\
596 			int nlocks = (sq)->sq_nciputctrl;		\
597 			ciputctrl_t *cip = (sq)->sq_ciputctrl;		\
598 			ASSERT((sq)->sq_type & SQ_CIPUT);		\
599 			for (i = 0; i <= nlocks; i++) {			\
600 				ASSERT(MUTEX_HELD(&cip[i].ciputctrl_lock)); \
601 				cip[i].ciputctrl_count &= ~SQ_FASTPUT;	\
602 			}						\
603 		}							\
604 	}
605 
606 /*
607  * Run service procedures for all queues in the stream head.
608  */
609 #define	STR_SERVICE(stp, q) {						\
610 	ASSERT(MUTEX_HELD(&stp->sd_qlock));				\
611 	while (stp->sd_qhead != NULL) {					\
612 		DQ(q, stp->sd_qhead, stp->sd_qtail, q_link);		\
613 		ASSERT(stp->sd_nqueues > 0);				\
614 		stp->sd_nqueues--;					\
615 		ASSERT(!(q->q_flag & QINSERVICE));			\
616 		mutex_exit(&stp->sd_qlock);				\
617 		queue_service(q);					\
618 		mutex_enter(&stp->sd_qlock);				\
619 	}								\
620 	ASSERT(stp->sd_nqueues == 0);					\
621 	ASSERT((stp->sd_qhead == NULL) && (stp->sd_qtail == NULL));	\
622 }
623 
624 /*
625  * constructor/destructor routines for the stream head cache
626  */
627 /* ARGSUSED */
628 static int
629 stream_head_constructor(void *buf, void *cdrarg, int kmflags)
630 {
631 	stdata_t *stp = buf;
632 
633 	mutex_init(&stp->sd_lock, NULL, MUTEX_DEFAULT, NULL);
634 	mutex_init(&stp->sd_reflock, NULL, MUTEX_DEFAULT, NULL);
635 	mutex_init(&stp->sd_qlock, NULL, MUTEX_DEFAULT, NULL);
636 	cv_init(&stp->sd_monitor, NULL, CV_DEFAULT, NULL);
637 	cv_init(&stp->sd_iocmonitor, NULL, CV_DEFAULT, NULL);
638 	cv_init(&stp->sd_refmonitor, NULL, CV_DEFAULT, NULL);
639 	cv_init(&stp->sd_qcv, NULL, CV_DEFAULT, NULL);
640 	cv_init(&stp->sd_zcopy_wait, NULL, CV_DEFAULT, NULL);
641 	stp->sd_wrq = NULL;
642 
643 	return (0);
644 }
645 
646 /* ARGSUSED */
647 static void
648 stream_head_destructor(void *buf, void *cdrarg)
649 {
650 	stdata_t *stp = buf;
651 
652 	mutex_destroy(&stp->sd_lock);
653 	mutex_destroy(&stp->sd_reflock);
654 	mutex_destroy(&stp->sd_qlock);
655 	cv_destroy(&stp->sd_monitor);
656 	cv_destroy(&stp->sd_iocmonitor);
657 	cv_destroy(&stp->sd_refmonitor);
658 	cv_destroy(&stp->sd_qcv);
659 	cv_destroy(&stp->sd_zcopy_wait);
660 }
661 
662 /*
663  * constructor/destructor routines for the queue cache
664  */
665 /* ARGSUSED */
666 static int
667 queue_constructor(void *buf, void *cdrarg, int kmflags)
668 {
669 	queinfo_t *qip = buf;
670 	queue_t *qp = &qip->qu_rqueue;
671 	queue_t *wqp = &qip->qu_wqueue;
672 	syncq_t	*sq = &qip->qu_syncq;
673 
674 	qp->q_first = NULL;
675 	qp->q_link = NULL;
676 	qp->q_count = 0;
677 	qp->q_mblkcnt = 0;
678 	qp->q_sqhead = NULL;
679 	qp->q_sqtail = NULL;
680 	qp->q_sqnext = NULL;
681 	qp->q_sqprev = NULL;
682 	qp->q_sqflags = 0;
683 	qp->q_rwcnt = 0;
684 	qp->q_spri = 0;
685 
686 	mutex_init(QLOCK(qp), NULL, MUTEX_DEFAULT, NULL);
687 	cv_init(&qp->q_wait, NULL, CV_DEFAULT, NULL);
688 
689 	wqp->q_first = NULL;
690 	wqp->q_link = NULL;
691 	wqp->q_count = 0;
692 	wqp->q_mblkcnt = 0;
693 	wqp->q_sqhead = NULL;
694 	wqp->q_sqtail = NULL;
695 	wqp->q_sqnext = NULL;
696 	wqp->q_sqprev = NULL;
697 	wqp->q_sqflags = 0;
698 	wqp->q_rwcnt = 0;
699 	wqp->q_spri = 0;
700 
701 	mutex_init(QLOCK(wqp), NULL, MUTEX_DEFAULT, NULL);
702 	cv_init(&wqp->q_wait, NULL, CV_DEFAULT, NULL);
703 
704 	sq->sq_head = NULL;
705 	sq->sq_tail = NULL;
706 	sq->sq_evhead = NULL;
707 	sq->sq_evtail = NULL;
708 	sq->sq_callbpend = NULL;
709 	sq->sq_outer = NULL;
710 	sq->sq_onext = NULL;
711 	sq->sq_oprev = NULL;
712 	sq->sq_next = NULL;
713 	sq->sq_svcflags = 0;
714 	sq->sq_servcount = 0;
715 	sq->sq_needexcl = 0;
716 	sq->sq_nqueues = 0;
717 	sq->sq_pri = 0;
718 
719 	mutex_init(&sq->sq_lock, NULL, MUTEX_DEFAULT, NULL);
720 	cv_init(&sq->sq_wait, NULL, CV_DEFAULT, NULL);
721 	cv_init(&sq->sq_exitwait, NULL, CV_DEFAULT, NULL);
722 
723 	return (0);
724 }
725 
726 /* ARGSUSED */
727 static void
728 queue_destructor(void *buf, void *cdrarg)
729 {
730 	queinfo_t *qip = buf;
731 	queue_t *qp = &qip->qu_rqueue;
732 	queue_t *wqp = &qip->qu_wqueue;
733 	syncq_t	*sq = &qip->qu_syncq;
734 
735 	ASSERT(qp->q_sqhead == NULL);
736 	ASSERT(wqp->q_sqhead == NULL);
737 	ASSERT(qp->q_sqnext == NULL);
738 	ASSERT(wqp->q_sqnext == NULL);
739 	ASSERT(qp->q_rwcnt == 0);
740 	ASSERT(wqp->q_rwcnt == 0);
741 
742 	mutex_destroy(&qp->q_lock);
743 	cv_destroy(&qp->q_wait);
744 
745 	mutex_destroy(&wqp->q_lock);
746 	cv_destroy(&wqp->q_wait);
747 
748 	mutex_destroy(&sq->sq_lock);
749 	cv_destroy(&sq->sq_wait);
750 	cv_destroy(&sq->sq_exitwait);
751 }
752 
753 /*
754  * constructor/destructor routines for the syncq cache
755  */
756 /* ARGSUSED */
757 static int
758 syncq_constructor(void *buf, void *cdrarg, int kmflags)
759 {
760 	syncq_t	*sq = buf;
761 
762 	bzero(buf, sizeof (syncq_t));
763 
764 	mutex_init(&sq->sq_lock, NULL, MUTEX_DEFAULT, NULL);
765 	cv_init(&sq->sq_wait, NULL, CV_DEFAULT, NULL);
766 	cv_init(&sq->sq_exitwait, NULL, CV_DEFAULT, NULL);
767 
768 	return (0);
769 }
770 
771 /* ARGSUSED */
772 static void
773 syncq_destructor(void *buf, void *cdrarg)
774 {
775 	syncq_t	*sq = buf;
776 
777 	ASSERT(sq->sq_head == NULL);
778 	ASSERT(sq->sq_tail == NULL);
779 	ASSERT(sq->sq_evhead == NULL);
780 	ASSERT(sq->sq_evtail == NULL);
781 	ASSERT(sq->sq_callbpend == NULL);
782 	ASSERT(sq->sq_callbflags == 0);
783 	ASSERT(sq->sq_outer == NULL);
784 	ASSERT(sq->sq_onext == NULL);
785 	ASSERT(sq->sq_oprev == NULL);
786 	ASSERT(sq->sq_next == NULL);
787 	ASSERT(sq->sq_needexcl == 0);
788 	ASSERT(sq->sq_svcflags == 0);
789 	ASSERT(sq->sq_servcount == 0);
790 	ASSERT(sq->sq_nqueues == 0);
791 	ASSERT(sq->sq_pri == 0);
792 	ASSERT(sq->sq_count == 0);
793 	ASSERT(sq->sq_rmqcount == 0);
794 	ASSERT(sq->sq_cancelid == 0);
795 	ASSERT(sq->sq_ciputctrl == NULL);
796 	ASSERT(sq->sq_nciputctrl == 0);
797 	ASSERT(sq->sq_type == 0);
798 	ASSERT(sq->sq_flags == 0);
799 
800 	mutex_destroy(&sq->sq_lock);
801 	cv_destroy(&sq->sq_wait);
802 	cv_destroy(&sq->sq_exitwait);
803 }
804 
805 /* ARGSUSED */
806 static int
807 ciputctrl_constructor(void *buf, void *cdrarg, int kmflags)
808 {
809 	ciputctrl_t *cip = buf;
810 	int i;
811 
812 	for (i = 0; i < n_ciputctrl; i++) {
813 		cip[i].ciputctrl_count = SQ_FASTPUT;
814 		mutex_init(&cip[i].ciputctrl_lock, NULL, MUTEX_DEFAULT, NULL);
815 	}
816 
817 	return (0);
818 }
819 
820 /* ARGSUSED */
821 static void
822 ciputctrl_destructor(void *buf, void *cdrarg)
823 {
824 	ciputctrl_t *cip = buf;
825 	int i;
826 
827 	for (i = 0; i < n_ciputctrl; i++) {
828 		ASSERT(cip[i].ciputctrl_count & SQ_FASTPUT);
829 		mutex_destroy(&cip[i].ciputctrl_lock);
830 	}
831 }
832 
833 /*
834  * Init routine run from main at boot time.
835  */
836 void
837 strinit(void)
838 {
839 	int i;
840 	int ncpus = ((boot_max_ncpus == -1) ? max_ncpus : boot_max_ncpus);
841 
842 	/*
843 	 * Set up mux_node structures.
844 	 */
845 	mux_nodes = kmem_zalloc((sizeof (struct mux_node) * devcnt), KM_SLEEP);
846 	for (i = 0; i < devcnt; i++)
847 		mux_nodes[i].mn_imaj = i;
848 
849 	stream_head_cache = kmem_cache_create("stream_head_cache",
850 		sizeof (stdata_t), 0,
851 		stream_head_constructor, stream_head_destructor, NULL,
852 		NULL, NULL, 0);
853 
854 	queue_cache = kmem_cache_create("queue_cache", sizeof (queinfo_t), 0,
855 		queue_constructor, queue_destructor, NULL, NULL, NULL, 0);
856 
857 	syncq_cache = kmem_cache_create("syncq_cache", sizeof (syncq_t), 0,
858 		syncq_constructor, syncq_destructor, NULL, NULL, NULL, 0);
859 
860 	qband_cache = kmem_cache_create("qband_cache",
861 		sizeof (qband_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
862 
863 	linkinfo_cache = kmem_cache_create("linkinfo_cache",
864 		sizeof (linkinfo_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
865 
866 	n_ciputctrl = ncpus;
867 	n_ciputctrl = 1 << highbit(n_ciputctrl - 1);
868 	ASSERT(n_ciputctrl >= 1);
869 	n_ciputctrl = MIN(n_ciputctrl, max_n_ciputctrl);
870 	if (n_ciputctrl >= min_n_ciputctrl) {
871 		ciputctrl_cache = kmem_cache_create("ciputctrl_cache",
872 			sizeof (ciputctrl_t) * n_ciputctrl,
873 			sizeof (ciputctrl_t), ciputctrl_constructor,
874 			ciputctrl_destructor, NULL, NULL, NULL, 0);
875 	}
876 
877 	streams_taskq = system_taskq;
878 
879 	if (streams_taskq == NULL)
880 		panic("strinit: no memory for streams taskq!");
881 
882 	bc_bkgrnd_thread = thread_create(NULL, 0,
883 	    streams_bufcall_service, NULL, 0, &p0, TS_RUN, streams_lopri);
884 
885 	streams_qbkgrnd_thread = thread_create(NULL, 0,
886 	    streams_qbkgrnd_service, NULL, 0, &p0, TS_RUN, streams_lopri);
887 
888 	streams_sqbkgrnd_thread = thread_create(NULL, 0,
889 	    streams_sqbkgrnd_service, NULL, 0, &p0, TS_RUN, streams_lopri);
890 
891 	/*
892 	 * Create STREAMS kstats.
893 	 */
894 	str_kstat = kstat_create("streams", 0, "strstat",
895 	    "net", KSTAT_TYPE_NAMED,
896 	    sizeof (str_statistics) / sizeof (kstat_named_t),
897 	    KSTAT_FLAG_VIRTUAL);
898 
899 	if (str_kstat != NULL) {
900 		str_kstat->ks_data = &str_statistics;
901 		kstat_install(str_kstat);
902 	}
903 
904 	/*
905 	 * TPI support routine initialisation.
906 	 */
907 	tpi_init();
908 }
909 
910 void
911 str_sendsig(vnode_t *vp, int event, uchar_t band, int error)
912 {
913 	struct stdata *stp;
914 
915 	ASSERT(vp->v_stream);
916 	stp = vp->v_stream;
917 	/* Have to hold sd_lock to prevent siglist from changing */
918 	mutex_enter(&stp->sd_lock);
919 	if (stp->sd_sigflags & event)
920 		strsendsig(stp->sd_siglist, event, band, error);
921 	mutex_exit(&stp->sd_lock);
922 }
923 
924 /*
925  * Send the "sevent" set of signals to a process.
926  * This might send more than one signal if the process is registered
927  * for multiple events. The caller should pass in an sevent that only
928  * includes the events for which the process has registered.
929  */
930 static void
931 dosendsig(proc_t *proc, int events, int sevent, k_siginfo_t *info,
932 	uchar_t band, int error)
933 {
934 	ASSERT(MUTEX_HELD(&proc->p_lock));
935 
936 	info->si_band = 0;
937 	info->si_errno = 0;
938 
939 	if (sevent & S_ERROR) {
940 		sevent &= ~S_ERROR;
941 		info->si_code = POLL_ERR;
942 		info->si_errno = error;
943 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRSENDSIG,
944 			"strsendsig:proc %p info %p", proc, info);
945 		sigaddq(proc, NULL, info, KM_NOSLEEP);
946 		info->si_errno = 0;
947 	}
948 	if (sevent & S_HANGUP) {
949 		sevent &= ~S_HANGUP;
950 		info->si_code = POLL_HUP;
951 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRSENDSIG,
952 			"strsendsig:proc %p info %p", proc, info);
953 		sigaddq(proc, NULL, info, KM_NOSLEEP);
954 	}
955 	if (sevent & S_HIPRI) {
956 		sevent &= ~S_HIPRI;
957 		info->si_code = POLL_PRI;
958 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRSENDSIG,
959 			"strsendsig:proc %p info %p", proc, info);
960 		sigaddq(proc, NULL, info, KM_NOSLEEP);
961 	}
962 	if (sevent & S_RDBAND) {
963 		sevent &= ~S_RDBAND;
964 		if (events & S_BANDURG)
965 			sigtoproc(proc, NULL, SIGURG);
966 		else
967 			sigtoproc(proc, NULL, SIGPOLL);
968 	}
969 	if (sevent & S_WRBAND) {
970 		sevent &= ~S_WRBAND;
971 		sigtoproc(proc, NULL, SIGPOLL);
972 	}
973 	if (sevent & S_INPUT) {
974 		sevent &= ~S_INPUT;
975 		info->si_code = POLL_IN;
976 		info->si_band = band;
977 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRSENDSIG,
978 			"strsendsig:proc %p info %p", proc, info);
979 		sigaddq(proc, NULL, info, KM_NOSLEEP);
980 		info->si_band = 0;
981 	}
982 	if (sevent & S_OUTPUT) {
983 		sevent &= ~S_OUTPUT;
984 		info->si_code = POLL_OUT;
985 		info->si_band = band;
986 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRSENDSIG,
987 			"strsendsig:proc %p info %p", proc, info);
988 		sigaddq(proc, NULL, info, KM_NOSLEEP);
989 		info->si_band = 0;
990 	}
991 	if (sevent & S_MSG) {
992 		sevent &= ~S_MSG;
993 		info->si_code = POLL_MSG;
994 		info->si_band = band;
995 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRSENDSIG,
996 			"strsendsig:proc %p info %p", proc, info);
997 		sigaddq(proc, NULL, info, KM_NOSLEEP);
998 		info->si_band = 0;
999 	}
1000 	if (sevent & S_RDNORM) {
1001 		sevent &= ~S_RDNORM;
1002 		sigtoproc(proc, NULL, SIGPOLL);
1003 	}
1004 	if (sevent != 0) {
1005 		panic("strsendsig: unknown event(s) %x", sevent);
1006 	}
1007 }
1008 
1009 /*
1010  * Send SIGPOLL/SIGURG signal to all processes and process groups
1011  * registered on the given signal list that want a signal for at
1012  * least one of the specified events.
1013  *
1014  * Must be called with exclusive access to siglist (caller holding sd_lock).
1015  *
1016  * strioctl(I_SETSIG/I_ESETSIG) will only change siglist when holding
1017  * sd_lock and the ioctl code maintains a PID_HOLD on the pid structure
1018  * while it is in the siglist.
1019  *
1020  * For performance reasons (MP scalability) the code drops pidlock
1021  * when sending signals to a single process.
1022  * When sending to a process group the code holds
1023  * pidlock to prevent the membership in the process group from changing
1024  * while walking the p_pglink list.
1025  */
1026 void
1027 strsendsig(strsig_t *siglist, int event, uchar_t band, int error)
1028 {
1029 	strsig_t *ssp;
1030 	k_siginfo_t info;
1031 	struct pid *pidp;
1032 	proc_t  *proc;
1033 
1034 	info.si_signo = SIGPOLL;
1035 	info.si_errno = 0;
1036 	for (ssp = siglist; ssp; ssp = ssp->ss_next) {
1037 		int sevent;
1038 
1039 		sevent = ssp->ss_events & event;
1040 		if (sevent == 0)
1041 			continue;
1042 
1043 		if ((pidp = ssp->ss_pidp) == NULL) {
1044 			/* pid was released but still on event list */
1045 			continue;
1046 		}
1047 
1048 
1049 		if (ssp->ss_pid > 0) {
1050 			/*
1051 			 * XXX This unfortunately still generates
1052 			 * a signal when a fd is closed but
1053 			 * the proc is active.
1054 			 */
1055 			ASSERT(ssp->ss_pid == pidp->pid_id);
1056 
1057 			mutex_enter(&pidlock);
1058 			proc = prfind_zone(pidp->pid_id, ALL_ZONES);
1059 			if (proc == NULL) {
1060 				mutex_exit(&pidlock);
1061 				continue;
1062 			}
1063 			mutex_enter(&proc->p_lock);
1064 			mutex_exit(&pidlock);
1065 			dosendsig(proc, ssp->ss_events, sevent, &info,
1066 				band, error);
1067 			mutex_exit(&proc->p_lock);
1068 		} else {
1069 			/*
1070 			 * Send to process group. Hold pidlock across
1071 			 * calls to dosendsig().
1072 			 */
1073 			pid_t pgrp = -ssp->ss_pid;
1074 
1075 			mutex_enter(&pidlock);
1076 			proc = pgfind_zone(pgrp, ALL_ZONES);
1077 			while (proc != NULL) {
1078 				mutex_enter(&proc->p_lock);
1079 				dosendsig(proc, ssp->ss_events, sevent,
1080 					&info, band, error);
1081 				mutex_exit(&proc->p_lock);
1082 				proc = proc->p_pglink;
1083 			}
1084 			mutex_exit(&pidlock);
1085 		}
1086 	}
1087 }
1088 
1089 /*
1090  * Attach a stream device or module.
1091  * qp is a read queue; the new queue goes in so its next
1092  * read ptr is the argument, and the write queue corresponding
1093  * to the argument points to this queue. Return 0 on success,
1094  * or a non-zero errno on failure.
1095  */
1096 int
1097 qattach(queue_t *qp, dev_t *devp, int oflag, cred_t *crp, fmodsw_impl_t *fp,
1098     boolean_t is_insert)
1099 {
1100 	major_t			major;
1101 	cdevsw_impl_t		*dp;
1102 	struct streamtab	*str;
1103 	queue_t			*rq;
1104 	queue_t			*wrq;
1105 	uint32_t		qflag;
1106 	uint32_t		sqtype;
1107 	perdm_t			*dmp;
1108 	int			error;
1109 	int			sflag;
1110 
1111 	rq = allocq();
1112 	wrq = _WR(rq);
1113 	STREAM(rq) = STREAM(wrq) = STREAM(qp);
1114 
1115 	if (fp != NULL) {
1116 		str = fp->f_str;
1117 		qflag = fp->f_qflag;
1118 		sqtype = fp->f_sqtype;
1119 		dmp = fp->f_dmp;
1120 		IMPLY((qflag & (QPERMOD | QMTOUTPERIM)), dmp != NULL);
1121 		sflag = MODOPEN;
1122 
1123 		/*
1124 		 * stash away a pointer to the module structure so we can
1125 		 * unref it in qdetach.
1126 		 */
1127 		rq->q_fp = fp;
1128 	} else {
1129 		ASSERT(!is_insert);
1130 
1131 		major = getmajor(*devp);
1132 		dp = &devimpl[major];
1133 
1134 		str = dp->d_str;
1135 		ASSERT(str == STREAMSTAB(major));
1136 
1137 		qflag = dp->d_qflag;
1138 		ASSERT(qflag & QISDRV);
1139 		sqtype = dp->d_sqtype;
1140 
1141 		/* create perdm_t if needed */
1142 		if (NEED_DM(dp->d_dmp, qflag))
1143 			dp->d_dmp = hold_dm(str, qflag, sqtype);
1144 
1145 		dmp = dp->d_dmp;
1146 		sflag = 0;
1147 	}
1148 
1149 	TRACE_2(TR_FAC_STREAMS_FR, TR_QATTACH_FLAGS,
1150 	    "qattach:qflag == %X(%X)", qflag, *devp);
1151 
1152 	/* setq might sleep in allocator - avoid holding locks. */
1153 	setq(rq, str->st_rdinit, str->st_wrinit, dmp, qflag, sqtype, B_FALSE);
1154 
1155 	/*
1156 	 * Before calling the module's open routine, set up the q_next
1157 	 * pointer for inserting a module in the middle of a stream.
1158 	 *
1159 	 * Note that we can always set _QINSERTING and set up q_next
1160 	 * pointer for both inserting and pushing a module.  Then there
1161 	 * is no need for the is_insert parameter.  In insertq(), called
1162 	 * by qprocson(), assume that q_next of the new module always points
1163 	 * to the correct queue and use it for insertion.  Everything should
1164 	 * work out fine.  But in the first release of _I_INSERT, we
1165 	 * distinguish between inserting and pushing to make sure that
1166 	 * pushing a module follows the same code path as before.
1167 	 */
1168 	if (is_insert) {
1169 		rq->q_flag |= _QINSERTING;
1170 		rq->q_next = qp;
1171 	}
1172 
1173 	/*
1174 	 * If there is an outer perimeter get exclusive access during
1175 	 * the open procedure.  Bump up the reference count on the queue.
1176 	 */
1177 	entersq(rq->q_syncq, SQ_OPENCLOSE);
1178 	error = (*rq->q_qinfo->qi_qopen)(rq, devp, oflag, sflag, crp);
1179 	if (error != 0)
1180 		goto failed;
1181 	leavesq(rq->q_syncq, SQ_OPENCLOSE);
1182 	ASSERT(qprocsareon(rq));
1183 	return (0);
1184 
1185 failed:
1186 	rq->q_flag &= ~_QINSERTING;
1187 	if (backq(wrq) != NULL && backq(wrq)->q_next == wrq)
1188 		qprocsoff(rq);
1189 	leavesq(rq->q_syncq, SQ_OPENCLOSE);
1190 	rq->q_next = wrq->q_next = NULL;
1191 	qdetach(rq, 0, 0, crp, B_FALSE);
1192 	return (error);
1193 }
1194 
1195 /*
1196  * Handle second open of stream. For modules, set the
1197  * last argument to MODOPEN and do not pass any open flags.
1198  * Ignore dummydev since this is not the first open.
1199  */
1200 int
1201 qreopen(queue_t *qp, dev_t *devp, int flag, cred_t *crp)
1202 {
1203 	int	error;
1204 	dev_t dummydev;
1205 	queue_t *wqp = _WR(qp);
1206 
1207 	ASSERT(qp->q_flag & QREADR);
1208 	entersq(qp->q_syncq, SQ_OPENCLOSE);
1209 
1210 	dummydev = *devp;
1211 	if (error = ((*qp->q_qinfo->qi_qopen)(qp, &dummydev,
1212 	    (wqp->q_next ? 0 : flag), (wqp->q_next ? MODOPEN : 0), crp))) {
1213 		leavesq(qp->q_syncq, SQ_OPENCLOSE);
1214 		mutex_enter(&STREAM(qp)->sd_lock);
1215 		qp->q_stream->sd_flag |= STREOPENFAIL;
1216 		mutex_exit(&STREAM(qp)->sd_lock);
1217 		return (error);
1218 	}
1219 	leavesq(qp->q_syncq, SQ_OPENCLOSE);
1220 
1221 	/*
1222 	 * successful open should have done qprocson()
1223 	 */
1224 	ASSERT(qprocsareon(_RD(qp)));
1225 	return (0);
1226 }
1227 
1228 /*
1229  * Detach a stream module or device.
1230  * If clmode == 1 then the module or driver was opened and its
1231  * close routine must be called. If clmode == 0, the module
1232  * or driver was never opened or the open failed, and so its close
1233  * should not be called.
1234  */
1235 void
1236 qdetach(queue_t *qp, int clmode, int flag, cred_t *crp, boolean_t is_remove)
1237 {
1238 	queue_t *wqp = _WR(qp);
1239 	ASSERT(STREAM(qp)->sd_flag & (STRCLOSE|STWOPEN|STRPLUMB));
1240 
1241 	if (STREAM_NEEDSERVICE(STREAM(qp)))
1242 		stream_runservice(STREAM(qp));
1243 
1244 	if (clmode) {
1245 		/*
1246 		 * Make sure that all the messages on the write side syncq are
1247 		 * processed and nothing is left. Since we are closing, no new
1248 		 * messages may appear there.
1249 		 */
1250 		wait_q_syncq(wqp);
1251 
1252 		entersq(qp->q_syncq, SQ_OPENCLOSE);
1253 		if (is_remove) {
1254 			mutex_enter(QLOCK(qp));
1255 			qp->q_flag |= _QREMOVING;
1256 			mutex_exit(QLOCK(qp));
1257 		}
1258 		(*qp->q_qinfo->qi_qclose)(qp, flag, crp);
1259 		/*
1260 		 * Check that qprocsoff() was actually called.
1261 		 */
1262 		ASSERT((qp->q_flag & QWCLOSE) && (wqp->q_flag & QWCLOSE));
1263 
1264 		leavesq(qp->q_syncq, SQ_OPENCLOSE);
1265 	} else {
1266 		disable_svc(qp);
1267 	}
1268 
1269 	/*
1270 	 * Allow any threads blocked in entersq to proceed and discover
1271 	 * the QWCLOSE is set.
1272 	 * Note: This assumes that all users of entersq check QWCLOSE.
1273 	 * Currently runservice is the only entersq that can happen
1274 	 * after removeq has finished.
1275 	 * Removeq will have discarded all messages destined to the closing
1276 	 * pair of queues from the syncq.
1277 	 * NOTE: Calling a function inside an assert is unconventional.
1278 	 * However, it does not cause any problem since flush_syncq() does
1279 	 * not change any state except when it returns non-zero i.e.
1280 	 * when the assert will trigger.
1281 	 */
1282 	ASSERT(flush_syncq(qp->q_syncq, qp) == 0);
1283 	ASSERT(flush_syncq(wqp->q_syncq, wqp) == 0);
1284 	ASSERT((qp->q_flag & QPERMOD) ||
1285 		((qp->q_syncq->sq_head == NULL) &&
1286 		(wqp->q_syncq->sq_head == NULL)));
1287 
1288 	/*
1289 	 * Flush the queues before q_next is set to NULL. This is needed
1290 	 * in order to backenable any downstream queue before we go away.
1291 	 * Note: we are already removed from the stream so that the
1292 	 * backenabling will not cause any messages to be delivered to our
1293 	 * put procedures.
1294 	 */
1295 	flushq(qp, FLUSHALL);
1296 	flushq(wqp, FLUSHALL);
1297 
1298 	/*
1299 	 * wait for any pending service processing to complete
1300 	 */
1301 	wait_svc(qp);
1302 
1303 	/* Tidy up - removeq only does a half-remove from stream */
1304 	qp->q_next = wqp->q_next = NULL;
1305 	ASSERT(!(qp->q_flag & QENAB));
1306 	ASSERT(!(wqp->q_flag & QENAB));
1307 
1308 	/* release any fmodsw_impl_t structure held on behalf of the queue */
1309 
1310 	ASSERT(qp->q_fp != NULL || qp->q_flag & QISDRV);
1311 	if (qp->q_fp != NULL)
1312 		fmodsw_rele(qp->q_fp);
1313 
1314 	/* freeq removes us from the outer perimeter if any */
1315 	freeq(qp);
1316 }
1317 
1318 /* Prevent service procedures from being called */
1319 void
1320 disable_svc(queue_t *qp)
1321 {
1322 	queue_t *wqp = _WR(qp);
1323 
1324 	ASSERT(qp->q_flag & QREADR);
1325 	mutex_enter(QLOCK(qp));
1326 	qp->q_flag |= QWCLOSE;
1327 	mutex_exit(QLOCK(qp));
1328 	mutex_enter(QLOCK(wqp));
1329 	wqp->q_flag |= QWCLOSE;
1330 	mutex_exit(QLOCK(wqp));
1331 }
1332 
1333 /* allow service procedures to be called again */
1334 void
1335 enable_svc(queue_t *qp)
1336 {
1337 	queue_t *wqp = _WR(qp);
1338 
1339 	ASSERT(qp->q_flag & QREADR);
1340 	mutex_enter(QLOCK(qp));
1341 	qp->q_flag &= ~QWCLOSE;
1342 	mutex_exit(QLOCK(qp));
1343 	mutex_enter(QLOCK(wqp));
1344 	wqp->q_flag &= ~QWCLOSE;
1345 	mutex_exit(QLOCK(wqp));
1346 }
1347 
1348 /*
1349  * Remove queue from qhead/qtail if it is enabled.
1350  * Only reset QENAB if the queue was removed from the runlist.
1351  * A queue goes through 3 stages:
1352  *	It is on the service list and QENAB is set.
1353  *	It is removed from the service list but QENAB is still set.
1354  *	QENAB gets changed to QINSERVICE.
1355  *	QINSERVICE is reset (when the service procedure is done)
1356  * Thus we can not reset QENAB unless we actually removed it from the service
1357  * queue.
1358  */
1359 void
1360 remove_runlist(queue_t *qp)
1361 {
1362 	if (qp->q_flag & QENAB && qhead != NULL) {
1363 		queue_t *q_chase;
1364 		queue_t *q_curr;
1365 		int removed;
1366 
1367 		mutex_enter(&service_queue);
1368 		RMQ(qp, qhead, qtail, q_link, q_chase, q_curr, removed);
1369 		mutex_exit(&service_queue);
1370 		if (removed) {
1371 			STRSTAT(qremoved);
1372 			qp->q_flag &= ~QENAB;
1373 		}
1374 	}
1375 }
1376 
1377 
1378 /*
1379  * wait for any pending service processing to complete.
1380  * The removal of queues from the runlist is not atomic with the
1381  * clearing of the QENABLED flag and setting the INSERVICE flag.
1382  * consequently it is possible for remove_runlist in strclose
1383  * to not find the queue on the runlist but for it to be QENABLED
1384  * and not yet INSERVICE -> hence wait_svc needs to check QENABLED
1385  * as well as INSERVICE.
1386  */
1387 void
1388 wait_svc(queue_t *qp)
1389 {
1390 	queue_t *wqp = _WR(qp);
1391 
1392 	ASSERT(qp->q_flag & QREADR);
1393 
1394 	/*
1395 	 * Try to remove queues from qhead/qtail list.
1396 	 */
1397 	if (qhead != NULL) {
1398 		remove_runlist(qp);
1399 		remove_runlist(wqp);
1400 	}
1401 	/*
1402 	 * Wait till the syncqs associated with the queue
1403 	 * will dissapear from background processing list.
1404 	 * This only needs to be done for non-PERMOD perimeters since
1405 	 * for PERMOD perimeters the syncq may be shared and will only be freed
1406 	 * when the last module/driver is unloaded.
1407 	 * If for PERMOD perimeters queue was on the syncq list, removeq()
1408 	 * should call propagate_syncq() or drain_syncq() for it. Both of these
1409 	 * function remove the queue from its syncq list, so sqthread will not
1410 	 * try to access the queue.
1411 	 */
1412 	if (!(qp->q_flag & QPERMOD)) {
1413 		syncq_t *rsq = qp->q_syncq;
1414 		syncq_t *wsq = wqp->q_syncq;
1415 
1416 		/*
1417 		 * Disable rsq and wsq and wait for any background processing of
1418 		 * syncq to complete.
1419 		 */
1420 		wait_sq_svc(rsq);
1421 		if (wsq != rsq)
1422 			wait_sq_svc(wsq);
1423 	}
1424 
1425 	mutex_enter(QLOCK(qp));
1426 	while (qp->q_flag & (QINSERVICE|QENAB))
1427 		cv_wait(&qp->q_wait, QLOCK(qp));
1428 	mutex_exit(QLOCK(qp));
1429 	mutex_enter(QLOCK(wqp));
1430 	while (wqp->q_flag & (QINSERVICE|QENAB))
1431 		cv_wait(&wqp->q_wait, QLOCK(wqp));
1432 	mutex_exit(QLOCK(wqp));
1433 }
1434 
1435 /*
1436  * Put ioctl data from userland buffer `arg' into the mblk chain `bp'.
1437  * `flag' must always contain either K_TO_K or U_TO_K; STR_NOSIG may
1438  * also be set, and is passed through to allocb_cred_wait().
1439  *
1440  * Returns errno on failure, zero on success.
1441  */
1442 int
1443 putiocd(mblk_t *bp, char *arg, int flag, cred_t *cr)
1444 {
1445 	mblk_t *tmp;
1446 	ssize_t  count;
1447 	size_t n;
1448 	int error = 0;
1449 
1450 	ASSERT((flag & (U_TO_K | K_TO_K)) == U_TO_K ||
1451 		(flag & (U_TO_K | K_TO_K)) == K_TO_K);
1452 
1453 	if (bp->b_datap->db_type == M_IOCTL) {
1454 		count = ((struct iocblk *)bp->b_rptr)->ioc_count;
1455 	} else {
1456 		ASSERT(bp->b_datap->db_type == M_COPYIN);
1457 		count = ((struct copyreq *)bp->b_rptr)->cq_size;
1458 	}
1459 	/*
1460 	 * strdoioctl validates ioc_count, so if this assert fails it
1461 	 * cannot be due to user error.
1462 	 */
1463 	ASSERT(count >= 0);
1464 
1465 	while (count > 0) {
1466 		n = MIN(MAXIOCBSZ, count);
1467 		if ((tmp = allocb_cred_wait(n, (flag & STR_NOSIG), &error,
1468 		    cr)) == NULL) {
1469 			return (error);
1470 		}
1471 		error = strcopyin(arg, tmp->b_wptr, n, flag & (U_TO_K|K_TO_K));
1472 		if (error != 0) {
1473 			freeb(tmp);
1474 			return (error);
1475 		}
1476 		arg += n;
1477 		DB_CPID(tmp) = curproc->p_pid;
1478 		tmp->b_wptr += n;
1479 		count -= n;
1480 		bp = (bp->b_cont = tmp);
1481 	}
1482 
1483 	return (0);
1484 }
1485 
1486 /*
1487  * Copy ioctl data to user-land. Return non-zero errno on failure,
1488  * 0 for success.
1489  */
1490 int
1491 getiocd(mblk_t *bp, char *arg, int copymode)
1492 {
1493 	ssize_t count;
1494 	size_t  n;
1495 	int	error;
1496 
1497 	if (bp->b_datap->db_type == M_IOCACK)
1498 		count = ((struct iocblk *)bp->b_rptr)->ioc_count;
1499 	else {
1500 		ASSERT(bp->b_datap->db_type == M_COPYOUT);
1501 		count = ((struct copyreq *)bp->b_rptr)->cq_size;
1502 	}
1503 	ASSERT(count >= 0);
1504 
1505 	for (bp = bp->b_cont; bp && count;
1506 	    count -= n, bp = bp->b_cont, arg += n) {
1507 		n = MIN(count, bp->b_wptr - bp->b_rptr);
1508 		error = strcopyout(bp->b_rptr, arg, n, copymode);
1509 		if (error)
1510 			return (error);
1511 	}
1512 	ASSERT(count == 0);
1513 	return (0);
1514 }
1515 
1516 /*
1517  * Allocate a linkinfo entry given the write queue of the
1518  * bottom module of the top stream and the write queue of the
1519  * stream head of the bottom stream.
1520  */
1521 linkinfo_t *
1522 alloclink(queue_t *qup, queue_t *qdown, file_t *fpdown)
1523 {
1524 	linkinfo_t *linkp;
1525 
1526 	linkp = kmem_cache_alloc(linkinfo_cache, KM_SLEEP);
1527 
1528 	linkp->li_lblk.l_qtop = qup;
1529 	linkp->li_lblk.l_qbot = qdown;
1530 	linkp->li_fpdown = fpdown;
1531 
1532 	mutex_enter(&strresources);
1533 	linkp->li_next = linkinfo_list;
1534 	linkp->li_prev = NULL;
1535 	if (linkp->li_next)
1536 		linkp->li_next->li_prev = linkp;
1537 	linkinfo_list = linkp;
1538 	linkp->li_lblk.l_index = ++lnk_id;
1539 	ASSERT(lnk_id != 0);	/* this should never wrap in practice */
1540 	mutex_exit(&strresources);
1541 
1542 	return (linkp);
1543 }
1544 
1545 /*
1546  * Free a linkinfo entry.
1547  */
1548 void
1549 lbfree(linkinfo_t *linkp)
1550 {
1551 	mutex_enter(&strresources);
1552 	if (linkp->li_next)
1553 		linkp->li_next->li_prev = linkp->li_prev;
1554 	if (linkp->li_prev)
1555 		linkp->li_prev->li_next = linkp->li_next;
1556 	else
1557 		linkinfo_list = linkp->li_next;
1558 	mutex_exit(&strresources);
1559 
1560 	kmem_cache_free(linkinfo_cache, linkp);
1561 }
1562 
1563 /*
1564  * Check for a potential linking cycle.
1565  * Return 1 if a link will result in a cycle,
1566  * and 0 otherwise.
1567  */
1568 int
1569 linkcycle(stdata_t *upstp, stdata_t *lostp)
1570 {
1571 	struct mux_node *np;
1572 	struct mux_edge *ep;
1573 	int i;
1574 	major_t lomaj;
1575 	major_t upmaj;
1576 	/*
1577 	 * if the lower stream is a pipe/FIFO, return, since link
1578 	 * cycles can not happen on pipes/FIFOs
1579 	 */
1580 	if (lostp->sd_vnode->v_type == VFIFO)
1581 		return (0);
1582 
1583 	for (i = 0; i < devcnt; i++) {
1584 		np = &mux_nodes[i];
1585 		MUX_CLEAR(np);
1586 	}
1587 	lomaj = getmajor(lostp->sd_vnode->v_rdev);
1588 	upmaj = getmajor(upstp->sd_vnode->v_rdev);
1589 	np = &mux_nodes[lomaj];
1590 	for (;;) {
1591 		if (!MUX_DIDVISIT(np)) {
1592 			if (np->mn_imaj == upmaj)
1593 				return (1);
1594 			if (np->mn_outp == NULL) {
1595 				MUX_VISIT(np);
1596 				if (np->mn_originp == NULL)
1597 					return (0);
1598 				np = np->mn_originp;
1599 				continue;
1600 			}
1601 			MUX_VISIT(np);
1602 			np->mn_startp = np->mn_outp;
1603 		} else {
1604 			if (np->mn_startp == NULL) {
1605 				if (np->mn_originp == NULL)
1606 					return (0);
1607 				else {
1608 					np = np->mn_originp;
1609 					continue;
1610 				}
1611 			}
1612 			/*
1613 			 * If ep->me_nodep is a FIFO (me_nodep == NULL),
1614 			 * ignore the edge and move on. ep->me_nodep gets
1615 			 * set to NULL in mux_addedge() if it is a FIFO.
1616 			 *
1617 			 */
1618 			ep = np->mn_startp;
1619 			np->mn_startp = ep->me_nextp;
1620 			if (ep->me_nodep == NULL)
1621 				continue;
1622 			ep->me_nodep->mn_originp = np;
1623 			np = ep->me_nodep;
1624 		}
1625 	}
1626 }
1627 
1628 /*
1629  * Find linkinfo entry corresponding to the parameters.
1630  */
1631 linkinfo_t *
1632 findlinks(stdata_t *stp, int index, int type)
1633 {
1634 	linkinfo_t *linkp;
1635 	struct mux_edge *mep;
1636 	struct mux_node *mnp;
1637 	queue_t *qup;
1638 
1639 	mutex_enter(&strresources);
1640 	if ((type & LINKTYPEMASK) == LINKNORMAL) {
1641 		qup = getendq(stp->sd_wrq);
1642 		for (linkp = linkinfo_list; linkp; linkp = linkp->li_next) {
1643 			if ((qup == linkp->li_lblk.l_qtop) &&
1644 			    (!index || (index == linkp->li_lblk.l_index))) {
1645 				mutex_exit(&strresources);
1646 				return (linkp);
1647 			}
1648 		}
1649 	} else {
1650 		ASSERT((type & LINKTYPEMASK) == LINKPERSIST);
1651 		mnp = &mux_nodes[getmajor(stp->sd_vnode->v_rdev)];
1652 		mep = mnp->mn_outp;
1653 		while (mep) {
1654 			if ((index == 0) || (index == mep->me_muxid))
1655 				break;
1656 			mep = mep->me_nextp;
1657 		}
1658 		if (!mep) {
1659 			mutex_exit(&strresources);
1660 			return (NULL);
1661 		}
1662 		for (linkp = linkinfo_list; linkp; linkp = linkp->li_next) {
1663 			if ((!linkp->li_lblk.l_qtop) &&
1664 			    (mep->me_muxid == linkp->li_lblk.l_index)) {
1665 				mutex_exit(&strresources);
1666 				return (linkp);
1667 			}
1668 		}
1669 	}
1670 	mutex_exit(&strresources);
1671 	return (NULL);
1672 }
1673 
1674 /*
1675  * Given a queue ptr, follow the chain of q_next pointers until you reach the
1676  * last queue on the chain and return it.
1677  */
1678 queue_t *
1679 getendq(queue_t *q)
1680 {
1681 	ASSERT(q != NULL);
1682 	while (_SAMESTR(q))
1683 		q = q->q_next;
1684 	return (q);
1685 }
1686 
1687 /*
1688  * wait for the syncq count to drop to zero.
1689  * sq could be either outer or inner.
1690  */
1691 
1692 static void
1693 wait_syncq(syncq_t *sq)
1694 {
1695 	uint16_t count;
1696 
1697 	mutex_enter(SQLOCK(sq));
1698 	count = sq->sq_count;
1699 	SQ_PUTLOCKS_ENTER(sq);
1700 	SUM_SQ_PUTCOUNTS(sq, count);
1701 	while (count != 0) {
1702 		sq->sq_flags |= SQ_WANTWAKEUP;
1703 		SQ_PUTLOCKS_EXIT(sq);
1704 		cv_wait(&sq->sq_wait, SQLOCK(sq));
1705 		count = sq->sq_count;
1706 		SQ_PUTLOCKS_ENTER(sq);
1707 		SUM_SQ_PUTCOUNTS(sq, count);
1708 	}
1709 	SQ_PUTLOCKS_EXIT(sq);
1710 	mutex_exit(SQLOCK(sq));
1711 }
1712 
1713 /*
1714  * Wait while there are any messages for the queue in its syncq.
1715  */
1716 static void
1717 wait_q_syncq(queue_t *q)
1718 {
1719 	if ((q->q_sqflags & Q_SQQUEUED) || (q->q_syncqmsgs > 0)) {
1720 		syncq_t *sq = q->q_syncq;
1721 
1722 		mutex_enter(SQLOCK(sq));
1723 		while ((q->q_sqflags & Q_SQQUEUED) || (q->q_syncqmsgs > 0)) {
1724 			sq->sq_flags |= SQ_WANTWAKEUP;
1725 			cv_wait(&sq->sq_wait, SQLOCK(sq));
1726 		}
1727 		mutex_exit(SQLOCK(sq));
1728 	}
1729 }
1730 
1731 
1732 int
1733 mlink_file(vnode_t *vp, int cmd, struct file *fpdown, cred_t *crp, int *rvalp,
1734     int lhlink)
1735 {
1736 	struct stdata *stp;
1737 	struct strioctl strioc;
1738 	struct linkinfo *linkp;
1739 	struct stdata *stpdown;
1740 	struct streamtab *str;
1741 	queue_t *passq;
1742 	syncq_t *passyncq;
1743 	queue_t *rq;
1744 	cdevsw_impl_t *dp;
1745 	uint32_t qflag;
1746 	uint32_t sqtype;
1747 	perdm_t *dmp;
1748 	int error = 0;
1749 
1750 	stp = vp->v_stream;
1751 	TRACE_1(TR_FAC_STREAMS_FR,
1752 		TR_I_LINK, "I_LINK/I_PLINK:stp %p", stp);
1753 	/*
1754 	 * Test for invalid upper stream
1755 	 */
1756 	if (stp->sd_flag & STRHUP) {
1757 		return (ENXIO);
1758 	}
1759 	if (vp->v_type == VFIFO) {
1760 		return (EINVAL);
1761 	}
1762 	if (stp->sd_strtab == NULL) {
1763 		return (EINVAL);
1764 	}
1765 	if (!stp->sd_strtab->st_muxwinit) {
1766 		return (EINVAL);
1767 	}
1768 	if (fpdown == NULL) {
1769 		return (EBADF);
1770 	}
1771 	if (getmajor(stp->sd_vnode->v_rdev) >= devcnt) {
1772 		return (EINVAL);
1773 	}
1774 	mutex_enter(&muxifier);
1775 	if (stp->sd_flag & STPLEX) {
1776 		mutex_exit(&muxifier);
1777 		return (ENXIO);
1778 	}
1779 
1780 	/*
1781 	 * Test for invalid lower stream.
1782 	 * The check for the v_type != VFIFO and having a major
1783 	 * number not >= devcnt is done to avoid problems with
1784 	 * adding mux_node entry past the end of mux_nodes[].
1785 	 * For FIFO's we don't add an entry so this isn't a
1786 	 * problem.
1787 	 */
1788 	if (((stpdown = fpdown->f_vnode->v_stream) == NULL) ||
1789 	    (stpdown == stp) || (stpdown->sd_flag &
1790 	    (STPLEX|STRHUP|STRDERR|STWRERR|IOCWAIT|STRPLUMB)) ||
1791 	    ((stpdown->sd_vnode->v_type != VFIFO) &&
1792 	    (getmajor(stpdown->sd_vnode->v_rdev) >= devcnt)) ||
1793 	    linkcycle(stp, stpdown)) {
1794 		mutex_exit(&muxifier);
1795 		return (EINVAL);
1796 	}
1797 	TRACE_1(TR_FAC_STREAMS_FR,
1798 		TR_STPDOWN, "stpdown:%p", stpdown);
1799 	rq = getendq(stp->sd_wrq);
1800 	if (cmd == I_PLINK)
1801 		rq = NULL;
1802 
1803 	linkp = alloclink(rq, stpdown->sd_wrq, fpdown);
1804 
1805 	strioc.ic_cmd = cmd;
1806 	strioc.ic_timout = INFTIM;
1807 	strioc.ic_len = sizeof (struct linkblk);
1808 	strioc.ic_dp = (char *)&linkp->li_lblk;
1809 
1810 	/*
1811 	 * STRPLUMB protects plumbing changes and should be set before
1812 	 * link_addpassthru()/link_rempassthru() are called, so it is set here
1813 	 * and cleared in the end of mlink when passthru queue is removed.
1814 	 * Setting of STRPLUMB prevents reopens of the stream while passthru
1815 	 * queue is in-place (it is not a proper module and doesn't have open
1816 	 * entry point).
1817 	 *
1818 	 * STPLEX prevents any threads from entering the stream from above. It
1819 	 * can't be set before the call to link_addpassthru() because putnext
1820 	 * from below may cause stream head I/O routines to be called and these
1821 	 * routines assert that STPLEX is not set. After link_addpassthru()
1822 	 * nothing may come from below since the pass queue syncq is blocked.
1823 	 * Note also that STPLEX should be cleared before the call to
1824 	 * link_remmpassthru() since when messages start flowing to the stream
1825 	 * head (e.g. because of message propagation from the pass queue) stream
1826 	 * head I/O routines may be called with STPLEX flag set.
1827 	 *
1828 	 * When STPLEX is set, nothing may come into the stream from above and
1829 	 * it is safe to do a setq which will change stream head. So, the
1830 	 * correct sequence of actions is:
1831 	 *
1832 	 * 1) Set STRPLUMB
1833 	 * 2) Call link_addpassthru()
1834 	 * 3) Set STPLEX
1835 	 * 4) Call setq and update the stream state
1836 	 * 5) Clear STPLEX
1837 	 * 6) Call link_rempassthru()
1838 	 * 7) Clear STRPLUMB
1839 	 *
1840 	 * The same sequence applies to munlink() code.
1841 	 */
1842 	mutex_enter(&stpdown->sd_lock);
1843 	stpdown->sd_flag |= STRPLUMB;
1844 	mutex_exit(&stpdown->sd_lock);
1845 	/*
1846 	 * Add passthru queue below lower mux. This will block
1847 	 * syncqs of lower muxs read queue during I_LINK/I_UNLINK.
1848 	 */
1849 	passq = link_addpassthru(stpdown);
1850 
1851 	mutex_enter(&stpdown->sd_lock);
1852 	stpdown->sd_flag |= STPLEX;
1853 	mutex_exit(&stpdown->sd_lock);
1854 
1855 	rq = _RD(stpdown->sd_wrq);
1856 	/*
1857 	 * There may be messages in the streamhead's syncq due to messages
1858 	 * that arrived before link_addpassthru() was done. To avoid
1859 	 * background processing of the syncq happening simultaneous with
1860 	 * setq processing, we disable the streamhead syncq and wait until
1861 	 * existing background thread finishes working on it.
1862 	 */
1863 	wait_sq_svc(rq->q_syncq);
1864 	passyncq = passq->q_syncq;
1865 	if (!(passyncq->sq_flags & SQ_BLOCKED))
1866 		blocksq(passyncq, SQ_BLOCKED, 0);
1867 
1868 	ASSERT((rq->q_flag & QMT_TYPEMASK) == QMTSAFE);
1869 	ASSERT(rq->q_syncq == SQ(rq) && _WR(rq)->q_syncq == SQ(rq));
1870 	rq->q_ptr = _WR(rq)->q_ptr = NULL;
1871 
1872 	/* setq might sleep in allocator - avoid holding locks. */
1873 	/* Note: we are holding muxifier here. */
1874 
1875 	str = stp->sd_strtab;
1876 	dp = &devimpl[getmajor(vp->v_rdev)];
1877 	ASSERT(dp->d_str == str);
1878 
1879 	qflag = dp->d_qflag;
1880 	sqtype = dp->d_sqtype;
1881 
1882 	/* create perdm_t if needed */
1883 	if (NEED_DM(dp->d_dmp, qflag))
1884 		dp->d_dmp = hold_dm(str, qflag, sqtype);
1885 
1886 	dmp = dp->d_dmp;
1887 
1888 	setq(rq, str->st_muxrinit, str->st_muxwinit, dmp, qflag, sqtype,
1889 	    B_TRUE);
1890 
1891 	/*
1892 	 * XXX Remove any "odd" messages from the queue.
1893 	 * Keep only M_DATA, M_PROTO, M_PCPROTO.
1894 	 */
1895 	error = strdoioctl(stp, &strioc, FNATIVE,
1896 	    K_TO_K | STR_NOERROR | STR_NOSIG, crp, rvalp);
1897 	if (error != 0) {
1898 		lbfree(linkp);
1899 
1900 		if (!(passyncq->sq_flags & SQ_BLOCKED))
1901 			blocksq(passyncq, SQ_BLOCKED, 0);
1902 		/*
1903 		 * Restore the stream head queue and then remove
1904 		 * the passq. Turn off STPLEX before we turn on
1905 		 * the stream by removing the passq.
1906 		 */
1907 		rq->q_ptr = _WR(rq)->q_ptr = stpdown;
1908 		setq(rq, &strdata, &stwdata, NULL, QMTSAFE, SQ_CI|SQ_CO,
1909 		    B_TRUE);
1910 
1911 		mutex_enter(&stpdown->sd_lock);
1912 		stpdown->sd_flag &= ~STPLEX;
1913 		mutex_exit(&stpdown->sd_lock);
1914 
1915 		link_rempassthru(passq);
1916 
1917 		mutex_enter(&stpdown->sd_lock);
1918 		stpdown->sd_flag &= ~STRPLUMB;
1919 		/* Wakeup anyone waiting for STRPLUMB to clear. */
1920 		cv_broadcast(&stpdown->sd_monitor);
1921 		mutex_exit(&stpdown->sd_lock);
1922 
1923 		mutex_exit(&muxifier);
1924 		return (error);
1925 	}
1926 	mutex_enter(&fpdown->f_tlock);
1927 	fpdown->f_count++;
1928 	mutex_exit(&fpdown->f_tlock);
1929 
1930 	/*
1931 	 * if we've made it here the linkage is all set up so we should also
1932 	 * set up the layered driver linkages
1933 	 */
1934 
1935 	ASSERT((cmd == I_LINK) || (cmd == I_PLINK));
1936 	if (cmd == I_LINK) {
1937 		ldi_mlink_fp(stp, fpdown, lhlink, LINKNORMAL);
1938 	} else {
1939 		ldi_mlink_fp(stp, fpdown, lhlink, LINKPERSIST);
1940 	}
1941 
1942 	link_rempassthru(passq);
1943 
1944 	mux_addedge(stp, stpdown, linkp->li_lblk.l_index);
1945 
1946 	/*
1947 	 * Mark the upper stream as having dependent links
1948 	 * so that strclose can clean it up.
1949 	 */
1950 	if (cmd == I_LINK) {
1951 		mutex_enter(&stp->sd_lock);
1952 		stp->sd_flag |= STRHASLINKS;
1953 		mutex_exit(&stp->sd_lock);
1954 	}
1955 	/*
1956 	 * Wake up any other processes that may have been
1957 	 * waiting on the lower stream. These will all
1958 	 * error out.
1959 	 */
1960 	mutex_enter(&stpdown->sd_lock);
1961 	/* The passthru module is removed so we may release STRPLUMB */
1962 	stpdown->sd_flag &= ~STRPLUMB;
1963 	cv_broadcast(&rq->q_wait);
1964 	cv_broadcast(&_WR(rq)->q_wait);
1965 	cv_broadcast(&stpdown->sd_monitor);
1966 	mutex_exit(&stpdown->sd_lock);
1967 	mutex_exit(&muxifier);
1968 	*rvalp = linkp->li_lblk.l_index;
1969 	return (0);
1970 }
1971 
1972 int
1973 mlink(vnode_t *vp, int cmd, int arg, cred_t *crp, int *rvalp, int lhlink)
1974 {
1975 	int		ret;
1976 	struct file	*fpdown;
1977 
1978 	fpdown = getf(arg);
1979 	ret = mlink_file(vp, cmd, fpdown, crp, rvalp, lhlink);
1980 	if (fpdown != NULL)
1981 		releasef(arg);
1982 	return (ret);
1983 }
1984 
1985 /*
1986  * Unlink a multiplexor link. Stp is the controlling stream for the
1987  * link, and linkp points to the link's entry in the linkinfo list.
1988  * The muxifier lock must be held on entry and is dropped on exit.
1989  *
1990  * NOTE : Currently it is assumed that mux would process all the messages
1991  * sitting on it's queue before ACKing the UNLINK. It is the responsibility
1992  * of the mux to handle all the messages that arrive before UNLINK.
1993  * If the mux has to send down messages on its lower stream before
1994  * ACKing I_UNLINK, then it *should* know to handle messages even
1995  * after the UNLINK is acked (actually it should be able to handle till we
1996  * re-block the read side of the pass queue here). If the mux does not
1997  * open up the lower stream, any messages that arrive during UNLINK
1998  * will be put in the stream head. In the case of lower stream opening
1999  * up, some messages might land in the stream head depending on when
2000  * the message arrived and when the read side of the pass queue was
2001  * re-blocked.
2002  */
2003 int
2004 munlink(stdata_t *stp, linkinfo_t *linkp, int flag, cred_t *crp, int *rvalp)
2005 {
2006 	struct strioctl strioc;
2007 	struct stdata *stpdown;
2008 	queue_t *rq, *wrq;
2009 	queue_t	*passq;
2010 	syncq_t *passyncq;
2011 	int error = 0;
2012 	file_t *fpdown;
2013 
2014 	ASSERT(MUTEX_HELD(&muxifier));
2015 
2016 	stpdown = linkp->li_fpdown->f_vnode->v_stream;
2017 
2018 	/*
2019 	 * See the comment in mlink() concerning STRPLUMB/STPLEX flags.
2020 	 */
2021 	mutex_enter(&stpdown->sd_lock);
2022 	stpdown->sd_flag |= STRPLUMB;
2023 	mutex_exit(&stpdown->sd_lock);
2024 
2025 	/*
2026 	 * Add passthru queue below lower mux. This will block
2027 	 * syncqs of lower muxs read queue during I_LINK/I_UNLINK.
2028 	 */
2029 	passq = link_addpassthru(stpdown);
2030 
2031 	if ((flag & LINKTYPEMASK) == LINKNORMAL)
2032 		strioc.ic_cmd = I_UNLINK;
2033 	else
2034 		strioc.ic_cmd = I_PUNLINK;
2035 	strioc.ic_timout = INFTIM;
2036 	strioc.ic_len = sizeof (struct linkblk);
2037 	strioc.ic_dp = (char *)&linkp->li_lblk;
2038 
2039 	error = strdoioctl(stp, &strioc, FNATIVE,
2040 	    K_TO_K | STR_NOERROR | STR_NOSIG, crp, rvalp);
2041 
2042 	/*
2043 	 * If there was an error and this is not called via strclose,
2044 	 * return to the user. Otherwise, pretend there was no error
2045 	 * and close the link.
2046 	 */
2047 	if (error) {
2048 		if (flag & LINKCLOSE) {
2049 			cmn_err(CE_WARN, "KERNEL: munlink: could not perform "
2050 			    "unlink ioctl, closing anyway (%d)\n", error);
2051 		} else {
2052 			link_rempassthru(passq);
2053 			mutex_enter(&stpdown->sd_lock);
2054 			stpdown->sd_flag &= ~STRPLUMB;
2055 			cv_broadcast(&stpdown->sd_monitor);
2056 			mutex_exit(&stpdown->sd_lock);
2057 			mutex_exit(&muxifier);
2058 			return (error);
2059 		}
2060 	}
2061 
2062 	mux_rmvedge(stp, linkp->li_lblk.l_index);
2063 	fpdown = linkp->li_fpdown;
2064 	lbfree(linkp);
2065 
2066 	/*
2067 	 * We go ahead and drop muxifier here--it's a nasty global lock that
2068 	 * can slow others down. It's okay to since attempts to mlink() this
2069 	 * stream will be stopped because STPLEX is still set in the stdata
2070 	 * structure, and munlink() is stopped because mux_rmvedge() and
2071 	 * lbfree() have removed it from mux_nodes[] and linkinfo_list,
2072 	 * respectively.  Note that we defer the closef() of fpdown until
2073 	 * after we drop muxifier since strclose() can call munlinkall().
2074 	 */
2075 	mutex_exit(&muxifier);
2076 
2077 	wrq = stpdown->sd_wrq;
2078 	rq = _RD(wrq);
2079 
2080 	/*
2081 	 * Get rid of outstanding service procedure runs, before we make
2082 	 * it a stream head, since a stream head doesn't have any service
2083 	 * procedure.
2084 	 */
2085 	disable_svc(rq);
2086 	wait_svc(rq);
2087 
2088 	/*
2089 	 * Since we don't disable the syncq for QPERMOD, we wait for whatever
2090 	 * is queued up to be finished. mux should take care that nothing is
2091 	 * send down to this queue. We should do it now as we're going to block
2092 	 * passyncq if it was unblocked.
2093 	 */
2094 	if (wrq->q_flag & QPERMOD) {
2095 		syncq_t	*sq = wrq->q_syncq;
2096 
2097 		mutex_enter(SQLOCK(sq));
2098 		while (wrq->q_sqflags & Q_SQQUEUED) {
2099 			sq->sq_flags |= SQ_WANTWAKEUP;
2100 			cv_wait(&sq->sq_wait, SQLOCK(sq));
2101 		}
2102 		mutex_exit(SQLOCK(sq));
2103 	}
2104 	passyncq = passq->q_syncq;
2105 	if (!(passyncq->sq_flags & SQ_BLOCKED)) {
2106 
2107 		syncq_t *sq, *outer;
2108 
2109 		/*
2110 		 * Messages could be flowing from underneath. We will
2111 		 * block the read side of the passq. This would be
2112 		 * sufficient for QPAIR and QPERQ muxes to ensure
2113 		 * that no data is flowing up into this queue
2114 		 * and hence no thread active in this instance of
2115 		 * lower mux. But for QPERMOD and QMTOUTPERIM there
2116 		 * could be messages on the inner and outer/inner
2117 		 * syncqs respectively. We will wait for them to drain.
2118 		 * Because passq is blocked messages end up in the syncq
2119 		 * And qfill_syncq could possibly end up setting QFULL
2120 		 * which will access the rq->q_flag. Hence, we have to
2121 		 * acquire the QLOCK in setq.
2122 		 *
2123 		 * XXX Messages can also flow from top into this
2124 		 * queue though the unlink is over (Ex. some instance
2125 		 * in putnext() called from top that has still not
2126 		 * accessed this queue. And also putq(lowerq) ?).
2127 		 * Solution : How about blocking the l_qtop queue ?
2128 		 * Do we really care about such pure D_MP muxes ?
2129 		 */
2130 
2131 		blocksq(passyncq, SQ_BLOCKED, 0);
2132 
2133 		sq = rq->q_syncq;
2134 		if ((outer = sq->sq_outer) != NULL) {
2135 
2136 			/*
2137 			 * We have to just wait for the outer sq_count
2138 			 * drop to zero. As this does not prevent new
2139 			 * messages to enter the outer perimeter, this
2140 			 * is subject to starvation.
2141 			 *
2142 			 * NOTE :Because of blocksq above, messages could
2143 			 * be in the inner syncq only because of some
2144 			 * thread holding the outer perimeter exclusively.
2145 			 * Hence it would be sufficient to wait for the
2146 			 * exclusive holder of the outer perimeter to drain
2147 			 * the inner and outer syncqs. But we will not depend
2148 			 * on this feature and hence check the inner syncqs
2149 			 * separately.
2150 			 */
2151 			wait_syncq(outer);
2152 		}
2153 
2154 
2155 		/*
2156 		 * There could be messages destined for
2157 		 * this queue. Let the exclusive holder
2158 		 * drain it.
2159 		 */
2160 
2161 		wait_syncq(sq);
2162 		ASSERT((rq->q_flag & QPERMOD) ||
2163 			((rq->q_syncq->sq_head == NULL) &&
2164 			(_WR(rq)->q_syncq->sq_head == NULL)));
2165 	}
2166 
2167 	/*
2168 	 * We haven't taken care of QPERMOD case yet. QPERMOD is a special
2169 	 * case as we don't disable its syncq or remove it off the syncq
2170 	 * service list.
2171 	 */
2172 	if (rq->q_flag & QPERMOD) {
2173 		syncq_t	*sq = rq->q_syncq;
2174 
2175 		mutex_enter(SQLOCK(sq));
2176 		while (rq->q_sqflags & Q_SQQUEUED) {
2177 			sq->sq_flags |= SQ_WANTWAKEUP;
2178 			cv_wait(&sq->sq_wait, SQLOCK(sq));
2179 		}
2180 		mutex_exit(SQLOCK(sq));
2181 	}
2182 
2183 	/*
2184 	 * flush_syncq changes states only when there is some messages to
2185 	 * free. ie when it returns non-zero value to return.
2186 	 */
2187 	ASSERT(flush_syncq(rq->q_syncq, rq) == 0);
2188 	ASSERT(flush_syncq(wrq->q_syncq, wrq) == 0);
2189 
2190 	/*
2191 	 * No body else should know about this queue now.
2192 	 * If the mux did not process the messages before
2193 	 * acking the I_UNLINK, free them now.
2194 	 */
2195 
2196 	flushq(rq, FLUSHALL);
2197 	flushq(_WR(rq), FLUSHALL);
2198 
2199 	/*
2200 	 * Convert the mux lower queue into a stream head queue.
2201 	 * Turn off STPLEX before we turn on the stream by removing the passq.
2202 	 */
2203 	rq->q_ptr = wrq->q_ptr = stpdown;
2204 	setq(rq, &strdata, &stwdata, NULL, QMTSAFE, SQ_CI|SQ_CO, B_TRUE);
2205 
2206 	ASSERT((rq->q_flag & QMT_TYPEMASK) == QMTSAFE);
2207 	ASSERT(rq->q_syncq == SQ(rq) && _WR(rq)->q_syncq == SQ(rq));
2208 
2209 	enable_svc(rq);
2210 
2211 	/*
2212 	 * Now it is a proper stream, so STPLEX is cleared. But STRPLUMB still
2213 	 * needs to be set to prevent reopen() of the stream - such reopen may
2214 	 * try to call non-existent pass queue open routine and panic.
2215 	 */
2216 	mutex_enter(&stpdown->sd_lock);
2217 	stpdown->sd_flag &= ~STPLEX;
2218 	mutex_exit(&stpdown->sd_lock);
2219 
2220 	ASSERT(((flag & LINKTYPEMASK) == LINKNORMAL) ||
2221 	    ((flag & LINKTYPEMASK) == LINKPERSIST));
2222 
2223 	/* clean up the layered driver linkages */
2224 	if ((flag & LINKTYPEMASK) == LINKNORMAL) {
2225 		ldi_munlink_fp(stp, fpdown, LINKNORMAL);
2226 	} else {
2227 		ldi_munlink_fp(stp, fpdown, LINKPERSIST);
2228 	}
2229 
2230 	link_rempassthru(passq);
2231 
2232 	/*
2233 	 * Now all plumbing changes are finished and STRPLUMB is no
2234 	 * longer needed.
2235 	 */
2236 	mutex_enter(&stpdown->sd_lock);
2237 	stpdown->sd_flag &= ~STRPLUMB;
2238 	cv_broadcast(&stpdown->sd_monitor);
2239 	mutex_exit(&stpdown->sd_lock);
2240 
2241 	(void) closef(fpdown);
2242 	return (0);
2243 }
2244 
2245 /*
2246  * Unlink all multiplexor links for which stp is the controlling stream.
2247  * Return 0, or a non-zero errno on failure.
2248  */
2249 int
2250 munlinkall(stdata_t *stp, int flag, cred_t *crp, int *rvalp)
2251 {
2252 	linkinfo_t *linkp;
2253 	int error = 0;
2254 
2255 	mutex_enter(&muxifier);
2256 	while (linkp = findlinks(stp, 0, flag)) {
2257 		/*
2258 		 * munlink() releases the muxifier lock.
2259 		 */
2260 		if (error = munlink(stp, linkp, flag, crp, rvalp))
2261 			return (error);
2262 		mutex_enter(&muxifier);
2263 	}
2264 	mutex_exit(&muxifier);
2265 	return (0);
2266 }
2267 
2268 /*
2269  * A multiplexor link has been made. Add an
2270  * edge to the directed graph.
2271  */
2272 void
2273 mux_addedge(stdata_t *upstp, stdata_t *lostp, int muxid)
2274 {
2275 	struct mux_node *np;
2276 	struct mux_edge *ep;
2277 	major_t upmaj;
2278 	major_t lomaj;
2279 
2280 	upmaj = getmajor(upstp->sd_vnode->v_rdev);
2281 	lomaj = getmajor(lostp->sd_vnode->v_rdev);
2282 	np = &mux_nodes[upmaj];
2283 	if (np->mn_outp) {
2284 		ep = np->mn_outp;
2285 		while (ep->me_nextp)
2286 			ep = ep->me_nextp;
2287 		ep->me_nextp = kmem_alloc(sizeof (struct mux_edge), KM_SLEEP);
2288 		ep = ep->me_nextp;
2289 	} else {
2290 		np->mn_outp = kmem_alloc(sizeof (struct mux_edge), KM_SLEEP);
2291 		ep = np->mn_outp;
2292 	}
2293 	ep->me_nextp = NULL;
2294 	ep->me_muxid = muxid;
2295 	if (lostp->sd_vnode->v_type == VFIFO)
2296 		ep->me_nodep = NULL;
2297 	else
2298 		ep->me_nodep = &mux_nodes[lomaj];
2299 }
2300 
2301 /*
2302  * A multiplexor link has been removed. Remove the
2303  * edge in the directed graph.
2304  */
2305 void
2306 mux_rmvedge(stdata_t *upstp, int muxid)
2307 {
2308 	struct mux_node *np;
2309 	struct mux_edge *ep;
2310 	struct mux_edge *pep = NULL;
2311 	major_t upmaj;
2312 
2313 	upmaj = getmajor(upstp->sd_vnode->v_rdev);
2314 	np = &mux_nodes[upmaj];
2315 	ASSERT(np->mn_outp != NULL);
2316 	ep = np->mn_outp;
2317 	while (ep) {
2318 		if (ep->me_muxid == muxid) {
2319 			if (pep)
2320 				pep->me_nextp = ep->me_nextp;
2321 			else
2322 				np->mn_outp = ep->me_nextp;
2323 			kmem_free(ep, sizeof (struct mux_edge));
2324 			return;
2325 		}
2326 		pep = ep;
2327 		ep = ep->me_nextp;
2328 	}
2329 	ASSERT(0);	/* should not reach here */
2330 }
2331 
2332 /*
2333  * Translate the device flags (from conf.h) to the corresponding
2334  * qflag and sq_flag (type) values.
2335  */
2336 int
2337 devflg_to_qflag(struct streamtab *stp, uint32_t devflag, uint32_t *qflagp,
2338 	uint32_t *sqtypep)
2339 {
2340 	uint32_t qflag = 0;
2341 	uint32_t sqtype = 0;
2342 
2343 	if (devflag & _D_OLD)
2344 		goto bad;
2345 
2346 	/* Inner perimeter presence and scope */
2347 	switch (devflag & D_MTINNER_MASK) {
2348 	case D_MP:
2349 		qflag |= QMTSAFE;
2350 		sqtype |= SQ_CI;
2351 		break;
2352 	case D_MTPERQ|D_MP:
2353 		qflag |= QPERQ;
2354 		break;
2355 	case D_MTQPAIR|D_MP:
2356 		qflag |= QPAIR;
2357 		break;
2358 	case D_MTPERMOD|D_MP:
2359 		qflag |= QPERMOD;
2360 		break;
2361 	default:
2362 		goto bad;
2363 	}
2364 
2365 	/* Outer perimeter */
2366 	if (devflag & D_MTOUTPERIM) {
2367 		switch (devflag & D_MTINNER_MASK) {
2368 		case D_MP:
2369 		case D_MTPERQ|D_MP:
2370 		case D_MTQPAIR|D_MP:
2371 			break;
2372 		default:
2373 			goto bad;
2374 		}
2375 		qflag |= QMTOUTPERIM;
2376 	}
2377 
2378 	/* Inner perimeter modifiers */
2379 	if (devflag & D_MTINNER_MOD) {
2380 		switch (devflag & D_MTINNER_MASK) {
2381 		case D_MP:
2382 			goto bad;
2383 		default:
2384 			break;
2385 		}
2386 		if (devflag & D_MTPUTSHARED)
2387 			sqtype |= SQ_CIPUT;
2388 		if (devflag & _D_MTOCSHARED) {
2389 			/*
2390 			 * The code in putnext assumes that it has the
2391 			 * highest concurrency by not checking sq_count.
2392 			 * Thus _D_MTOCSHARED can only be supported when
2393 			 * D_MTPUTSHARED is set.
2394 			 */
2395 			if (!(devflag & D_MTPUTSHARED))
2396 				goto bad;
2397 			sqtype |= SQ_CIOC;
2398 		}
2399 		if (devflag & _D_MTCBSHARED) {
2400 			/*
2401 			 * The code in putnext assumes that it has the
2402 			 * highest concurrency by not checking sq_count.
2403 			 * Thus _D_MTCBSHARED can only be supported when
2404 			 * D_MTPUTSHARED is set.
2405 			 */
2406 			if (!(devflag & D_MTPUTSHARED))
2407 				goto bad;
2408 			sqtype |= SQ_CICB;
2409 		}
2410 		if (devflag & _D_MTSVCSHARED) {
2411 			/*
2412 			 * The code in putnext assumes that it has the
2413 			 * highest concurrency by not checking sq_count.
2414 			 * Thus _D_MTSVCSHARED can only be supported when
2415 			 * D_MTPUTSHARED is set. Also _D_MTSVCSHARED is
2416 			 * supported only for QPERMOD.
2417 			 */
2418 			if (!(devflag & D_MTPUTSHARED) || !(qflag & QPERMOD))
2419 				goto bad;
2420 			sqtype |= SQ_CISVC;
2421 		}
2422 	}
2423 
2424 	/* Default outer perimeter concurrency */
2425 	sqtype |= SQ_CO;
2426 
2427 	/* Outer perimeter modifiers */
2428 	if (devflag & D_MTOCEXCL) {
2429 		if (!(devflag & D_MTOUTPERIM)) {
2430 			/* No outer perimeter */
2431 			goto bad;
2432 		}
2433 		sqtype &= ~SQ_COOC;
2434 	}
2435 
2436 	/* Synchronous Streams extended qinit structure */
2437 	if (devflag & D_SYNCSTR)
2438 		qflag |= QSYNCSTR;
2439 
2440 	/*
2441 	 * Private flag used by a transport module to indicate
2442 	 * to sockfs that it supports direct-access mode without
2443 	 * having to go through STREAMS.
2444 	 */
2445 	if (devflag & _D_DIRECT) {
2446 		/* Reject unless the module is fully-MT (no perimeter) */
2447 		if ((qflag & QMT_TYPEMASK) != QMTSAFE)
2448 			goto bad;
2449 		qflag |= _QDIRECT;
2450 	}
2451 
2452 	*qflagp = qflag;
2453 	*sqtypep = sqtype;
2454 	return (0);
2455 
2456 bad:
2457 	cmn_err(CE_WARN,
2458 	    "stropen: bad MT flags (0x%x) in driver '%s'",
2459 	    (int)(qflag & D_MTSAFETY_MASK),
2460 	    stp->st_rdinit->qi_minfo->mi_idname);
2461 
2462 	return (EINVAL);
2463 }
2464 
2465 /*
2466  * Set the interface values for a pair of queues (qinit structure,
2467  * packet sizes, water marks).
2468  * setq assumes that the caller does not have a claim (entersq or claimq)
2469  * on the queue.
2470  */
2471 void
2472 setq(queue_t *rq, struct qinit *rinit, struct qinit *winit,
2473     perdm_t *dmp, uint32_t qflag, uint32_t sqtype, boolean_t lock_needed)
2474 {
2475 	queue_t *wq;
2476 	syncq_t	*sq, *outer;
2477 
2478 	ASSERT(rq->q_flag & QREADR);
2479 	ASSERT((qflag & QMT_TYPEMASK) != 0);
2480 	IMPLY((qflag & (QPERMOD | QMTOUTPERIM)), dmp != NULL);
2481 
2482 	wq = _WR(rq);
2483 	rq->q_qinfo = rinit;
2484 	rq->q_hiwat = rinit->qi_minfo->mi_hiwat;
2485 	rq->q_lowat = rinit->qi_minfo->mi_lowat;
2486 	rq->q_minpsz = rinit->qi_minfo->mi_minpsz;
2487 	rq->q_maxpsz = rinit->qi_minfo->mi_maxpsz;
2488 	wq->q_qinfo = winit;
2489 	wq->q_hiwat = winit->qi_minfo->mi_hiwat;
2490 	wq->q_lowat = winit->qi_minfo->mi_lowat;
2491 	wq->q_minpsz = winit->qi_minfo->mi_minpsz;
2492 	wq->q_maxpsz = winit->qi_minfo->mi_maxpsz;
2493 
2494 	/* Remove old syncqs */
2495 	sq = rq->q_syncq;
2496 	outer = sq->sq_outer;
2497 	if (outer != NULL) {
2498 		ASSERT(wq->q_syncq->sq_outer == outer);
2499 		outer_remove(outer, rq->q_syncq);
2500 		if (wq->q_syncq != rq->q_syncq)
2501 			outer_remove(outer, wq->q_syncq);
2502 	}
2503 	ASSERT(sq->sq_outer == NULL);
2504 	ASSERT(sq->sq_onext == NULL && sq->sq_oprev == NULL);
2505 
2506 	if (sq != SQ(rq)) {
2507 		if (!(rq->q_flag & QPERMOD))
2508 			free_syncq(sq);
2509 		if (wq->q_syncq == rq->q_syncq)
2510 			wq->q_syncq = NULL;
2511 		rq->q_syncq = NULL;
2512 	}
2513 	if (wq->q_syncq != NULL && wq->q_syncq != sq &&
2514 	    wq->q_syncq != SQ(rq)) {
2515 		free_syncq(wq->q_syncq);
2516 		wq->q_syncq = NULL;
2517 	}
2518 	ASSERT(rq->q_syncq == NULL || (rq->q_syncq->sq_head == NULL &&
2519 				rq->q_syncq->sq_tail == NULL));
2520 	ASSERT(wq->q_syncq == NULL || (wq->q_syncq->sq_head == NULL &&
2521 				wq->q_syncq->sq_tail == NULL));
2522 
2523 	if (!(rq->q_flag & QPERMOD) &&
2524 	    rq->q_syncq != NULL && rq->q_syncq->sq_ciputctrl != NULL) {
2525 		ASSERT(rq->q_syncq->sq_nciputctrl == n_ciputctrl - 1);
2526 		SUMCHECK_CIPUTCTRL_COUNTS(rq->q_syncq->sq_ciputctrl,
2527 		    rq->q_syncq->sq_nciputctrl, 0);
2528 		ASSERT(ciputctrl_cache != NULL);
2529 		kmem_cache_free(ciputctrl_cache, rq->q_syncq->sq_ciputctrl);
2530 		rq->q_syncq->sq_ciputctrl = NULL;
2531 		rq->q_syncq->sq_nciputctrl = 0;
2532 	}
2533 
2534 	if (!(wq->q_flag & QPERMOD) &&
2535 	    wq->q_syncq != NULL && wq->q_syncq->sq_ciputctrl != NULL) {
2536 		ASSERT(wq->q_syncq->sq_nciputctrl == n_ciputctrl - 1);
2537 		SUMCHECK_CIPUTCTRL_COUNTS(wq->q_syncq->sq_ciputctrl,
2538 		    wq->q_syncq->sq_nciputctrl, 0);
2539 		ASSERT(ciputctrl_cache != NULL);
2540 		kmem_cache_free(ciputctrl_cache, wq->q_syncq->sq_ciputctrl);
2541 		wq->q_syncq->sq_ciputctrl = NULL;
2542 		wq->q_syncq->sq_nciputctrl = 0;
2543 	}
2544 
2545 	sq = SQ(rq);
2546 	ASSERT(sq->sq_head == NULL && sq->sq_tail == NULL);
2547 	ASSERT(sq->sq_outer == NULL);
2548 	ASSERT(sq->sq_onext == NULL && sq->sq_oprev == NULL);
2549 
2550 	/*
2551 	 * Create syncqs based on qflag and sqtype. Set the SQ_TYPES_IN_FLAGS
2552 	 * bits in sq_flag based on the sqtype.
2553 	 */
2554 	ASSERT((sq->sq_flags & ~SQ_TYPES_IN_FLAGS) == 0);
2555 
2556 	rq->q_syncq = wq->q_syncq = sq;
2557 	sq->sq_type = sqtype;
2558 	sq->sq_flags = (sqtype & SQ_TYPES_IN_FLAGS);
2559 
2560 	/*
2561 	 *  We are making sq_svcflags zero,
2562 	 *  resetting SQ_DISABLED in case it was set by
2563 	 *  wait_svc() in the munlink path.
2564 	 *
2565 	 */
2566 	ASSERT((sq->sq_svcflags & SQ_SERVICE) == 0);
2567 	sq->sq_svcflags = 0;
2568 
2569 	/*
2570 	 * We need to acquire the lock here for the mlink and munlink case,
2571 	 * where canputnext, backenable, etc can access the q_flag.
2572 	 */
2573 	if (lock_needed) {
2574 		mutex_enter(QLOCK(rq));
2575 		rq->q_flag = (rq->q_flag & ~QMT_TYPEMASK) | QWANTR | qflag;
2576 		mutex_exit(QLOCK(rq));
2577 		mutex_enter(QLOCK(wq));
2578 		wq->q_flag = (wq->q_flag & ~QMT_TYPEMASK) | QWANTR | qflag;
2579 		mutex_exit(QLOCK(wq));
2580 	} else {
2581 		rq->q_flag = (rq->q_flag & ~QMT_TYPEMASK) | QWANTR | qflag;
2582 		wq->q_flag = (wq->q_flag & ~QMT_TYPEMASK) | QWANTR | qflag;
2583 	}
2584 
2585 	if (qflag & QPERQ) {
2586 		/* Allocate a separate syncq for the write side */
2587 		sq = new_syncq();
2588 		sq->sq_type = rq->q_syncq->sq_type;
2589 		sq->sq_flags = rq->q_syncq->sq_flags;
2590 		ASSERT(sq->sq_outer == NULL && sq->sq_onext == NULL &&
2591 		    sq->sq_oprev == NULL);
2592 		wq->q_syncq = sq;
2593 	}
2594 	if (qflag & QPERMOD) {
2595 		sq = dmp->dm_sq;
2596 
2597 		/*
2598 		 * Assert that we do have an inner perimeter syncq and that it
2599 		 * does not have an outer perimeter associated with it.
2600 		 */
2601 		ASSERT(sq->sq_outer == NULL && sq->sq_onext == NULL &&
2602 		    sq->sq_oprev == NULL);
2603 		rq->q_syncq = wq->q_syncq = sq;
2604 	}
2605 	if (qflag & QMTOUTPERIM) {
2606 		outer = dmp->dm_sq;
2607 
2608 		ASSERT(outer->sq_outer == NULL);
2609 		outer_insert(outer, rq->q_syncq);
2610 		if (wq->q_syncq != rq->q_syncq)
2611 			outer_insert(outer, wq->q_syncq);
2612 	}
2613 	ASSERT((rq->q_syncq->sq_flags & SQ_TYPES_IN_FLAGS) ==
2614 		(rq->q_syncq->sq_type & SQ_TYPES_IN_FLAGS));
2615 	ASSERT((wq->q_syncq->sq_flags & SQ_TYPES_IN_FLAGS) ==
2616 		(wq->q_syncq->sq_type & SQ_TYPES_IN_FLAGS));
2617 	ASSERT((rq->q_flag & QMT_TYPEMASK) == (qflag & QMT_TYPEMASK));
2618 
2619 	/*
2620 	 * Initialize struio() types.
2621 	 */
2622 	rq->q_struiot =
2623 	    (rq->q_flag & QSYNCSTR) ? rinit->qi_struiot : STRUIOT_NONE;
2624 	wq->q_struiot =
2625 	    (wq->q_flag & QSYNCSTR) ? winit->qi_struiot : STRUIOT_NONE;
2626 }
2627 
2628 perdm_t *
2629 hold_dm(struct streamtab *str, uint32_t qflag, uint32_t sqtype)
2630 {
2631 	syncq_t	*sq;
2632 	perdm_t	**pp;
2633 	perdm_t	*p;
2634 	perdm_t	*dmp;
2635 
2636 	ASSERT(str != NULL);
2637 	ASSERT(qflag & (QPERMOD | QMTOUTPERIM));
2638 
2639 	rw_enter(&perdm_rwlock, RW_READER);
2640 	for (p = perdm_list; p != NULL; p = p->dm_next) {
2641 		if (p->dm_str == str) {	/* found one */
2642 			atomic_add_32(&(p->dm_ref), 1);
2643 			rw_exit(&perdm_rwlock);
2644 			return (p);
2645 		}
2646 	}
2647 	rw_exit(&perdm_rwlock);
2648 
2649 	sq = new_syncq();
2650 	if (qflag & QPERMOD) {
2651 		sq->sq_type = sqtype | SQ_PERMOD;
2652 		sq->sq_flags = sqtype & SQ_TYPES_IN_FLAGS;
2653 	} else {
2654 		ASSERT(qflag & QMTOUTPERIM);
2655 		sq->sq_onext = sq->sq_oprev = sq;
2656 	}
2657 
2658 	dmp = kmem_alloc(sizeof (perdm_t), KM_SLEEP);
2659 	dmp->dm_sq = sq;
2660 	dmp->dm_str = str;
2661 	dmp->dm_ref = 1;
2662 	dmp->dm_next = NULL;
2663 
2664 	rw_enter(&perdm_rwlock, RW_WRITER);
2665 	for (pp = &perdm_list; (p = *pp) != NULL; pp = &(p->dm_next)) {
2666 		if (p->dm_str == str) {	/* already present */
2667 			p->dm_ref++;
2668 			rw_exit(&perdm_rwlock);
2669 			free_syncq(sq);
2670 			kmem_free(dmp, sizeof (perdm_t));
2671 			return (p);
2672 		}
2673 	}
2674 
2675 	*pp = dmp;
2676 	rw_exit(&perdm_rwlock);
2677 	return (dmp);
2678 }
2679 
2680 void
2681 rele_dm(perdm_t *dmp)
2682 {
2683 	perdm_t **pp;
2684 	perdm_t *p;
2685 
2686 	rw_enter(&perdm_rwlock, RW_WRITER);
2687 	ASSERT(dmp->dm_ref > 0);
2688 
2689 	if (--dmp->dm_ref > 0) {
2690 		rw_exit(&perdm_rwlock);
2691 		return;
2692 	}
2693 
2694 	for (pp = &perdm_list; (p = *pp) != NULL; pp = &(p->dm_next))
2695 		if (p == dmp)
2696 			break;
2697 	ASSERT(p == dmp);
2698 	*pp = p->dm_next;
2699 	rw_exit(&perdm_rwlock);
2700 
2701 	/*
2702 	 * Wait for any background processing that relies on the
2703 	 * syncq to complete before it is freed.
2704 	 */
2705 	wait_sq_svc(p->dm_sq);
2706 	free_syncq(p->dm_sq);
2707 	kmem_free(p, sizeof (perdm_t));
2708 }
2709 
2710 /*
2711  * Make a protocol message given control and data buffers.
2712  * n.b., this can block; be careful of what locks you hold when calling it.
2713  *
2714  * If sd_maxblk is less than *iosize this routine can fail part way through
2715  * (due to an allocation failure). In this case on return *iosize will contain
2716  * the amount that was consumed. Otherwise *iosize will not be modified
2717  * i.e. it will contain the amount that was consumed.
2718  */
2719 int
2720 strmakemsg(
2721 	struct strbuf *mctl,
2722 	ssize_t *iosize,
2723 	struct uio *uiop,
2724 	stdata_t *stp,
2725 	int32_t flag,
2726 	mblk_t **mpp)
2727 {
2728 	mblk_t *mpctl = NULL;
2729 	mblk_t *mpdata = NULL;
2730 	int error;
2731 
2732 	ASSERT(uiop != NULL);
2733 
2734 	*mpp = NULL;
2735 	/* Create control part, if any */
2736 	if ((mctl != NULL) && (mctl->len >= 0)) {
2737 		error = strmakectl(mctl, flag, uiop->uio_fmode, &mpctl);
2738 		if (error)
2739 			return (error);
2740 	}
2741 	/* Create data part, if any */
2742 	if (*iosize >= 0) {
2743 		error = strmakedata(iosize, uiop, stp, flag, &mpdata);
2744 		if (error) {
2745 			freemsg(mpctl);
2746 			return (error);
2747 		}
2748 	}
2749 	if (mpctl != NULL) {
2750 		if (mpdata != NULL)
2751 			linkb(mpctl, mpdata);
2752 		*mpp = mpctl;
2753 	} else {
2754 		*mpp = mpdata;
2755 	}
2756 	return (0);
2757 }
2758 
2759 /*
2760  * Make the control part of a protocol message given a control buffer.
2761  * n.b., this can block; be careful of what locks you hold when calling it.
2762  */
2763 int
2764 strmakectl(
2765 	struct strbuf *mctl,
2766 	int32_t flag,
2767 	int32_t fflag,
2768 	mblk_t **mpp)
2769 {
2770 	mblk_t *bp = NULL;
2771 	unsigned char msgtype;
2772 	int error = 0;
2773 
2774 	*mpp = NULL;
2775 	/*
2776 	 * Create control part of message, if any.
2777 	 */
2778 	if ((mctl != NULL) && (mctl->len >= 0)) {
2779 		caddr_t base;
2780 		int ctlcount;
2781 		int allocsz;
2782 
2783 		if (flag & RS_HIPRI)
2784 			msgtype = M_PCPROTO;
2785 		else
2786 			msgtype = M_PROTO;
2787 
2788 		ctlcount = mctl->len;
2789 		base = mctl->buf;
2790 
2791 		/*
2792 		 * Give modules a better chance to reuse M_PROTO/M_PCPROTO
2793 		 * blocks by increasing the size to something more usable.
2794 		 */
2795 		allocsz = MAX(ctlcount, 64);
2796 
2797 		/*
2798 		 * Range checking has already been done; simply try
2799 		 * to allocate a message block for the ctl part.
2800 		 */
2801 		while (!(bp = allocb(allocsz, BPRI_MED))) {
2802 			if (fflag & (FNDELAY|FNONBLOCK))
2803 				return (EAGAIN);
2804 			if (error = strwaitbuf(allocsz, BPRI_MED))
2805 				return (error);
2806 		}
2807 
2808 		bp->b_datap->db_type = msgtype;
2809 		if (copyin(base, bp->b_wptr, ctlcount)) {
2810 			freeb(bp);
2811 			return (EFAULT);
2812 		}
2813 		bp->b_wptr += ctlcount;
2814 	}
2815 	*mpp = bp;
2816 	return (0);
2817 }
2818 
2819 /*
2820  * Make a protocol message given data buffers.
2821  * n.b., this can block; be careful of what locks you hold when calling it.
2822  *
2823  * If sd_maxblk is less than *iosize this routine can fail part way through
2824  * (due to an allocation failure). In this case on return *iosize will contain
2825  * the amount that was consumed. Otherwise *iosize will not be modified
2826  * i.e. it will contain the amount that was consumed.
2827  */
2828 int
2829 strmakedata(
2830 	ssize_t   *iosize,
2831 	struct uio *uiop,
2832 	stdata_t *stp,
2833 	int32_t flag,
2834 	mblk_t **mpp)
2835 {
2836 	mblk_t *mp = NULL;
2837 	mblk_t *bp;
2838 	int wroff = (int)stp->sd_wroff;
2839 	int error = 0;
2840 	ssize_t maxblk;
2841 	ssize_t count = *iosize;
2842 	cred_t *cr = CRED();
2843 
2844 	*mpp = NULL;
2845 	if (count < 0)
2846 		return (0);
2847 
2848 	maxblk = stp->sd_maxblk;
2849 	if (maxblk == INFPSZ)
2850 		maxblk = count;
2851 
2852 	/*
2853 	 * Create data part of message, if any.
2854 	 */
2855 	do {
2856 		ssize_t size;
2857 		dblk_t  *dp;
2858 
2859 		ASSERT(uiop);
2860 
2861 		size = MIN(count, maxblk);
2862 
2863 		while ((bp = allocb_cred(size + wroff, cr)) == NULL) {
2864 			error = EAGAIN;
2865 			if ((uiop->uio_fmode & (FNDELAY|FNONBLOCK)) ||
2866 			    (error = strwaitbuf(size + wroff, BPRI_MED)) != 0) {
2867 				if (count == *iosize) {
2868 					freemsg(mp);
2869 					return (error);
2870 				} else {
2871 					*iosize -= count;
2872 					*mpp = mp;
2873 					return (0);
2874 				}
2875 			}
2876 		}
2877 		dp = bp->b_datap;
2878 		dp->db_cpid = curproc->p_pid;
2879 		ASSERT(wroff <= dp->db_lim - bp->b_wptr);
2880 		bp->b_wptr = bp->b_rptr = bp->b_rptr + wroff;
2881 
2882 		if (flag & STRUIO_POSTPONE) {
2883 			/*
2884 			 * Setup the stream uio portion of the
2885 			 * dblk for subsequent use by struioget().
2886 			 */
2887 			dp->db_struioflag = STRUIO_SPEC;
2888 			dp->db_cksumstart = 0;
2889 			dp->db_cksumstuff = 0;
2890 			dp->db_cksumend = size;
2891 			*(long long *)dp->db_struioun.data = 0ll;
2892 		} else {
2893 			if (stp->sd_copyflag & STRCOPYCACHED)
2894 				uiop->uio_extflg |= UIO_COPY_CACHED;
2895 
2896 			if (size != 0) {
2897 				error = uiomove(bp->b_wptr, size, UIO_WRITE,
2898 				    uiop);
2899 				if (error != 0) {
2900 					freeb(bp);
2901 					freemsg(mp);
2902 					return (error);
2903 				}
2904 			}
2905 		}
2906 
2907 		bp->b_wptr += size;
2908 		count -= size;
2909 
2910 		if (mp == NULL)
2911 			mp = bp;
2912 		else
2913 			linkb(mp, bp);
2914 	} while (count > 0);
2915 
2916 	*mpp = mp;
2917 	return (0);
2918 }
2919 
2920 /*
2921  * Wait for a buffer to become available. Return non-zero errno
2922  * if not able to wait, 0 if buffer is probably there.
2923  */
2924 int
2925 strwaitbuf(size_t size, int pri)
2926 {
2927 	bufcall_id_t id;
2928 
2929 	mutex_enter(&bcall_monitor);
2930 	if ((id = bufcall(size, pri, (void (*)(void *))cv_broadcast,
2931 	    &ttoproc(curthread)->p_flag_cv)) == 0) {
2932 		mutex_exit(&bcall_monitor);
2933 		return (ENOSR);
2934 	}
2935 	if (!cv_wait_sig(&(ttoproc(curthread)->p_flag_cv), &bcall_monitor)) {
2936 		unbufcall(id);
2937 		mutex_exit(&bcall_monitor);
2938 		return (EINTR);
2939 	}
2940 	unbufcall(id);
2941 	mutex_exit(&bcall_monitor);
2942 	return (0);
2943 }
2944 
2945 /*
2946  * This function waits for a read or write event to happen on a stream.
2947  * fmode can specify FNDELAY and/or FNONBLOCK.
2948  * The timeout is in ms with -1 meaning infinite.
2949  * The flag values work as follows:
2950  *	READWAIT	Check for read side errors, send M_READ
2951  *	GETWAIT		Check for read side errors, no M_READ
2952  *	WRITEWAIT	Check for write side errors.
2953  *	NOINTR		Do not return error if nonblocking or timeout.
2954  * 	STR_NOERROR	Ignore all errors except STPLEX.
2955  *	STR_NOSIG	Ignore/hold signals during the duration of the call.
2956  *	STR_PEEK	Pass through the strgeterr().
2957  */
2958 int
2959 strwaitq(stdata_t *stp, int flag, ssize_t count, int fmode, clock_t timout,
2960     int *done)
2961 {
2962 	int slpflg, errs;
2963 	int error;
2964 	kcondvar_t *sleepon;
2965 	mblk_t *mp;
2966 	ssize_t *rd_count;
2967 	clock_t rval;
2968 
2969 	ASSERT(MUTEX_HELD(&stp->sd_lock));
2970 	if ((flag & READWAIT) || (flag & GETWAIT)) {
2971 		slpflg = RSLEEP;
2972 		sleepon = &_RD(stp->sd_wrq)->q_wait;
2973 		errs = STRDERR|STPLEX;
2974 	} else {
2975 		slpflg = WSLEEP;
2976 		sleepon = &stp->sd_wrq->q_wait;
2977 		errs = STWRERR|STRHUP|STPLEX;
2978 	}
2979 	if (flag & STR_NOERROR)
2980 		errs = STPLEX;
2981 
2982 	if (stp->sd_wakeq & slpflg) {
2983 		/*
2984 		 * A strwakeq() is pending, no need to sleep.
2985 		 */
2986 		stp->sd_wakeq &= ~slpflg;
2987 		*done = 0;
2988 		return (0);
2989 	}
2990 
2991 	if (fmode & (FNDELAY|FNONBLOCK)) {
2992 		if (!(flag & NOINTR))
2993 			error = EAGAIN;
2994 		else
2995 			error = 0;
2996 		*done = 1;
2997 		return (error);
2998 	}
2999 
3000 	if (stp->sd_flag & errs) {
3001 		/*
3002 		 * Check for errors before going to sleep since the
3003 		 * caller might not have checked this while holding
3004 		 * sd_lock.
3005 		 */
3006 		error = strgeterr(stp, errs, (flag & STR_PEEK));
3007 		if (error != 0) {
3008 			*done = 1;
3009 			return (error);
3010 		}
3011 	}
3012 
3013 	/*
3014 	 * If any module downstream has requested read notification
3015 	 * by setting SNDMREAD flag using M_SETOPTS, send a message
3016 	 * down stream.
3017 	 */
3018 	if ((flag & READWAIT) && (stp->sd_flag & SNDMREAD)) {
3019 		mutex_exit(&stp->sd_lock);
3020 		if (!(mp = allocb_wait(sizeof (ssize_t), BPRI_MED,
3021 		    (flag & STR_NOSIG), &error))) {
3022 			mutex_enter(&stp->sd_lock);
3023 			*done = 1;
3024 			return (error);
3025 		}
3026 		mp->b_datap->db_type = M_READ;
3027 		rd_count = (ssize_t *)mp->b_wptr;
3028 		*rd_count = count;
3029 		mp->b_wptr += sizeof (ssize_t);
3030 		/*
3031 		 * Send the number of bytes requested by the
3032 		 * read as the argument to M_READ.
3033 		 */
3034 		stream_willservice(stp);
3035 		putnext(stp->sd_wrq, mp);
3036 		stream_runservice(stp);
3037 		mutex_enter(&stp->sd_lock);
3038 
3039 		/*
3040 		 * If any data arrived due to inline processing
3041 		 * of putnext(), don't sleep.
3042 		 */
3043 		if (_RD(stp->sd_wrq)->q_first != NULL) {
3044 			*done = 0;
3045 			return (0);
3046 		}
3047 	}
3048 
3049 	stp->sd_flag |= slpflg;
3050 	TRACE_5(TR_FAC_STREAMS_FR, TR_STRWAITQ_WAIT2,
3051 		"strwaitq sleeps (2):%p, %X, %lX, %X, %p",
3052 		stp, flag, count, fmode, done);
3053 
3054 	rval = str_cv_wait(sleepon, &stp->sd_lock, timout, flag & STR_NOSIG);
3055 	if (rval > 0) {
3056 		/* EMPTY */
3057 		TRACE_5(TR_FAC_STREAMS_FR, TR_STRWAITQ_WAKE2,
3058 			"strwaitq awakes(2):%X, %X, %X, %X, %X",
3059 			stp, flag, count, fmode, done);
3060 	} else if (rval == 0) {
3061 		TRACE_5(TR_FAC_STREAMS_FR, TR_STRWAITQ_INTR2,
3062 			"strwaitq interrupt #2:%p, %X, %lX, %X, %p",
3063 			stp, flag, count, fmode, done);
3064 		stp->sd_flag &= ~slpflg;
3065 		cv_broadcast(sleepon);
3066 		if (!(flag & NOINTR))
3067 			error = EINTR;
3068 		else
3069 			error = 0;
3070 		*done = 1;
3071 		return (error);
3072 	} else {
3073 		/* timeout */
3074 		TRACE_5(TR_FAC_STREAMS_FR, TR_STRWAITQ_TIME,
3075 			"strwaitq timeout:%p, %X, %lX, %X, %p",
3076 			stp, flag, count, fmode, done);
3077 		*done = 1;
3078 		if (!(flag & NOINTR))
3079 			return (ETIME);
3080 		else
3081 			return (0);
3082 	}
3083 	/*
3084 	 * If the caller implements delayed errors (i.e. queued after data)
3085 	 * we can not check for errors here since data as well as an
3086 	 * error might have arrived at the stream head. We return to
3087 	 * have the caller check the read queue before checking for errors.
3088 	 */
3089 	if ((stp->sd_flag & errs) && !(flag & STR_DELAYERR)) {
3090 		error = strgeterr(stp, errs, (flag & STR_PEEK));
3091 		if (error != 0) {
3092 			*done = 1;
3093 			return (error);
3094 		}
3095 	}
3096 	*done = 0;
3097 	return (0);
3098 }
3099 
3100 /*
3101  * Perform job control discipline access checks.
3102  * Return 0 for success and the errno for failure.
3103  */
3104 
3105 #define	cantsend(p, t, sig) \
3106 	(sigismember(&(p)->p_ignore, sig) || signal_is_blocked((t), sig))
3107 
3108 int
3109 straccess(struct stdata *stp, enum jcaccess mode)
3110 {
3111 	extern kcondvar_t lbolt_cv;	/* XXX: should be in a header file */
3112 	kthread_t *t = curthread;
3113 	proc_t *p = ttoproc(t);
3114 	sess_t *sp;
3115 
3116 	if (stp->sd_sidp == NULL || stp->sd_vnode->v_type == VFIFO)
3117 		return (0);
3118 
3119 	mutex_enter(&p->p_lock);
3120 	sp = p->p_sessp;
3121 
3122 	for (;;) {
3123 		/*
3124 		 * If this is not the calling process's controlling terminal
3125 		 * or if the calling process is already in the foreground
3126 		 * then allow access.
3127 		 */
3128 		if (sp->s_dev != stp->sd_vnode->v_rdev ||
3129 		    p->p_pgidp == stp->sd_pgidp) {
3130 			mutex_exit(&p->p_lock);
3131 			return (0);
3132 		}
3133 
3134 		/*
3135 		 * Check to see if controlling terminal has been deallocated.
3136 		 */
3137 		if (sp->s_vp == NULL) {
3138 			if (!cantsend(p, t, SIGHUP))
3139 				sigtoproc(p, t, SIGHUP);
3140 			mutex_exit(&p->p_lock);
3141 			return (EIO);
3142 		}
3143 
3144 		if (mode == JCGETP) {
3145 			mutex_exit(&p->p_lock);
3146 			return (0);
3147 		}
3148 
3149 		if (mode == JCREAD) {
3150 			if (p->p_detached || cantsend(p, t, SIGTTIN)) {
3151 				mutex_exit(&p->p_lock);
3152 				return (EIO);
3153 			}
3154 			mutex_exit(&p->p_lock);
3155 			pgsignal(p->p_pgidp, SIGTTIN);
3156 			mutex_enter(&p->p_lock);
3157 		} else {  /* mode == JCWRITE or JCSETP */
3158 			if ((mode == JCWRITE && !(stp->sd_flag & STRTOSTOP)) ||
3159 			    cantsend(p, t, SIGTTOU)) {
3160 				mutex_exit(&p->p_lock);
3161 				return (0);
3162 			}
3163 			if (p->p_detached) {
3164 				mutex_exit(&p->p_lock);
3165 				return (EIO);
3166 			}
3167 			mutex_exit(&p->p_lock);
3168 			pgsignal(p->p_pgidp, SIGTTOU);
3169 			mutex_enter(&p->p_lock);
3170 		}
3171 
3172 		/*
3173 		 * We call cv_wait_sig_swap() to cause the appropriate
3174 		 * action for the jobcontrol signal to take place.
3175 		 * If the signal is being caught, we will take the
3176 		 * EINTR error return.  Otherwise, the default action
3177 		 * of causing the process to stop will take place.
3178 		 * In this case, we rely on the periodic cv_broadcast() on
3179 		 * &lbolt_cv to wake us up to loop around and test again.
3180 		 * We can't get here if the signal is ignored or
3181 		 * if the current thread is blocking the signal.
3182 		 */
3183 		if (!cv_wait_sig_swap(&lbolt_cv, &p->p_lock)) {
3184 			mutex_exit(&p->p_lock);
3185 			return (EINTR);
3186 		}
3187 	}
3188 }
3189 
3190 /*
3191  * Return size of message of block type (bp->b_datap->db_type)
3192  */
3193 size_t
3194 xmsgsize(mblk_t *bp)
3195 {
3196 	unsigned char type;
3197 	size_t count = 0;
3198 
3199 	type = bp->b_datap->db_type;
3200 
3201 	for (; bp; bp = bp->b_cont) {
3202 		if (type != bp->b_datap->db_type)
3203 			break;
3204 		ASSERT(bp->b_wptr >= bp->b_rptr);
3205 		count += bp->b_wptr - bp->b_rptr;
3206 	}
3207 	return (count);
3208 }
3209 
3210 /*
3211  * Allocate a stream head.
3212  */
3213 struct stdata *
3214 shalloc(queue_t *qp)
3215 {
3216 	stdata_t *stp;
3217 
3218 	stp = kmem_cache_alloc(stream_head_cache, KM_SLEEP);
3219 
3220 	stp->sd_wrq = _WR(qp);
3221 	stp->sd_strtab = NULL;
3222 	stp->sd_iocid = 0;
3223 	stp->sd_mate = NULL;
3224 	stp->sd_freezer = NULL;
3225 	stp->sd_refcnt = 0;
3226 	stp->sd_wakeq = 0;
3227 	stp->sd_anchor = 0;
3228 	stp->sd_struiowrq = NULL;
3229 	stp->sd_struiordq = NULL;
3230 	stp->sd_struiodnak = 0;
3231 	stp->sd_struionak = NULL;
3232 #ifdef C2_AUDIT
3233 	stp->sd_t_audit_data = NULL;
3234 #endif
3235 	stp->sd_rput_opt = 0;
3236 	stp->sd_wput_opt = 0;
3237 	stp->sd_read_opt = 0;
3238 	stp->sd_rprotofunc = strrput_proto;
3239 	stp->sd_rmiscfunc = strrput_misc;
3240 	stp->sd_rderrfunc = stp->sd_wrerrfunc = NULL;
3241 	stp->sd_ciputctrl = NULL;
3242 	stp->sd_nciputctrl = 0;
3243 	stp->sd_qhead = NULL;
3244 	stp->sd_qtail = NULL;
3245 	stp->sd_servid = NULL;
3246 	stp->sd_nqueues = 0;
3247 	stp->sd_svcflags = 0;
3248 	stp->sd_copyflag = 0;
3249 	return (stp);
3250 }
3251 
3252 /*
3253  * Free a stream head.
3254  */
3255 void
3256 shfree(stdata_t *stp)
3257 {
3258 	ASSERT(MUTEX_NOT_HELD(&stp->sd_lock));
3259 
3260 	stp->sd_wrq = NULL;
3261 
3262 	mutex_enter(&stp->sd_qlock);
3263 	while (stp->sd_svcflags & STRS_SCHEDULED) {
3264 		STRSTAT(strwaits);
3265 		cv_wait(&stp->sd_qcv, &stp->sd_qlock);
3266 	}
3267 	mutex_exit(&stp->sd_qlock);
3268 
3269 	if (stp->sd_ciputctrl != NULL) {
3270 		ASSERT(stp->sd_nciputctrl == n_ciputctrl - 1);
3271 		SUMCHECK_CIPUTCTRL_COUNTS(stp->sd_ciputctrl,
3272 		    stp->sd_nciputctrl, 0);
3273 		ASSERT(ciputctrl_cache != NULL);
3274 		kmem_cache_free(ciputctrl_cache, stp->sd_ciputctrl);
3275 		stp->sd_ciputctrl = NULL;
3276 		stp->sd_nciputctrl = 0;
3277 	}
3278 	ASSERT(stp->sd_qhead == NULL);
3279 	ASSERT(stp->sd_qtail == NULL);
3280 	ASSERT(stp->sd_nqueues == 0);
3281 	kmem_cache_free(stream_head_cache, stp);
3282 }
3283 
3284 /*
3285  * Allocate a pair of queues and a syncq for the pair
3286  */
3287 queue_t *
3288 allocq(void)
3289 {
3290 	queinfo_t *qip;
3291 	queue_t *qp, *wqp;
3292 	syncq_t	*sq;
3293 
3294 	qip = kmem_cache_alloc(queue_cache, KM_SLEEP);
3295 
3296 	qp = &qip->qu_rqueue;
3297 	wqp = &qip->qu_wqueue;
3298 	sq = &qip->qu_syncq;
3299 
3300 	qp->q_last	= NULL;
3301 	qp->q_next	= NULL;
3302 	qp->q_ptr	= NULL;
3303 	qp->q_flag	= QUSE | QREADR;
3304 	qp->q_bandp	= NULL;
3305 	qp->q_stream	= NULL;
3306 	qp->q_syncq	= sq;
3307 	qp->q_nband	= 0;
3308 	qp->q_nfsrv	= NULL;
3309 	qp->q_draining	= 0;
3310 	qp->q_syncqmsgs	= 0;
3311 	qp->q_spri	= 0;
3312 	qp->q_qtstamp	= 0;
3313 	qp->q_sqtstamp	= 0;
3314 	qp->q_fp	= NULL;
3315 
3316 	wqp->q_last	= NULL;
3317 	wqp->q_next	= NULL;
3318 	wqp->q_ptr	= NULL;
3319 	wqp->q_flag	= QUSE;
3320 	wqp->q_bandp	= NULL;
3321 	wqp->q_stream	= NULL;
3322 	wqp->q_syncq	= sq;
3323 	wqp->q_nband	= 0;
3324 	wqp->q_nfsrv	= NULL;
3325 	wqp->q_draining	= 0;
3326 	wqp->q_syncqmsgs = 0;
3327 	wqp->q_qtstamp	= 0;
3328 	wqp->q_sqtstamp	= 0;
3329 	wqp->q_spri	= 0;
3330 
3331 	sq->sq_count	= 0;
3332 	sq->sq_rmqcount	= 0;
3333 	sq->sq_flags	= 0;
3334 	sq->sq_type	= 0;
3335 	sq->sq_callbflags = 0;
3336 	sq->sq_cancelid	= 0;
3337 	sq->sq_ciputctrl = NULL;
3338 	sq->sq_nciputctrl = 0;
3339 	sq->sq_needexcl = 0;
3340 	sq->sq_svcflags = 0;
3341 
3342 	return (qp);
3343 }
3344 
3345 /*
3346  * Free a pair of queues and the "attached" syncq.
3347  * Discard any messages left on the syncq(s), remove the syncq(s) from the
3348  * outer perimeter, and free the syncq(s) if they are not the "attached" syncq.
3349  */
3350 void
3351 freeq(queue_t *qp)
3352 {
3353 	qband_t *qbp, *nqbp;
3354 	syncq_t *sq, *outer;
3355 	queue_t *wqp = _WR(qp);
3356 
3357 	ASSERT(qp->q_flag & QREADR);
3358 
3359 	(void) flush_syncq(qp->q_syncq, qp);
3360 	(void) flush_syncq(wqp->q_syncq, wqp);
3361 	ASSERT(qp->q_syncqmsgs == 0 && wqp->q_syncqmsgs == 0);
3362 
3363 	outer = qp->q_syncq->sq_outer;
3364 	if (outer != NULL) {
3365 		outer_remove(outer, qp->q_syncq);
3366 		if (wqp->q_syncq != qp->q_syncq)
3367 			outer_remove(outer, wqp->q_syncq);
3368 	}
3369 	/*
3370 	 * Free any syncqs that are outside what allocq returned.
3371 	 */
3372 	if (qp->q_syncq != SQ(qp) && !(qp->q_flag & QPERMOD))
3373 		free_syncq(qp->q_syncq);
3374 	if (qp->q_syncq != wqp->q_syncq && wqp->q_syncq != SQ(qp))
3375 		free_syncq(wqp->q_syncq);
3376 
3377 	ASSERT((qp->q_sqflags & (Q_SQQUEUED | Q_SQDRAINING)) == 0);
3378 	ASSERT((wqp->q_sqflags & (Q_SQQUEUED | Q_SQDRAINING)) == 0);
3379 	ASSERT(MUTEX_NOT_HELD(QLOCK(qp)));
3380 	ASSERT(MUTEX_NOT_HELD(QLOCK(wqp)));
3381 	sq = SQ(qp);
3382 	ASSERT(MUTEX_NOT_HELD(SQLOCK(sq)));
3383 	ASSERT(sq->sq_head == NULL && sq->sq_tail == NULL);
3384 	ASSERT(sq->sq_outer == NULL);
3385 	ASSERT(sq->sq_onext == NULL && sq->sq_oprev == NULL);
3386 	ASSERT(sq->sq_callbpend == NULL);
3387 	ASSERT(sq->sq_needexcl == 0);
3388 
3389 	if (sq->sq_ciputctrl != NULL) {
3390 		ASSERT(sq->sq_nciputctrl == n_ciputctrl - 1);
3391 		SUMCHECK_CIPUTCTRL_COUNTS(sq->sq_ciputctrl,
3392 		    sq->sq_nciputctrl, 0);
3393 		ASSERT(ciputctrl_cache != NULL);
3394 		kmem_cache_free(ciputctrl_cache, sq->sq_ciputctrl);
3395 		sq->sq_ciputctrl = NULL;
3396 		sq->sq_nciputctrl = 0;
3397 	}
3398 
3399 	ASSERT(qp->q_first == NULL && wqp->q_first == NULL);
3400 	ASSERT(qp->q_count == 0 && wqp->q_count == 0);
3401 	ASSERT(qp->q_mblkcnt == 0 && wqp->q_mblkcnt == 0);
3402 
3403 	qp->q_flag &= ~QUSE;
3404 	wqp->q_flag &= ~QUSE;
3405 
3406 	/* NOTE: Uncomment the assert below once bugid 1159635 is fixed. */
3407 	/* ASSERT((qp->q_flag & QWANTW) == 0 && (wqp->q_flag & QWANTW) == 0); */
3408 
3409 	qbp = qp->q_bandp;
3410 	while (qbp) {
3411 		nqbp = qbp->qb_next;
3412 		freeband(qbp);
3413 		qbp = nqbp;
3414 	}
3415 	qbp = wqp->q_bandp;
3416 	while (qbp) {
3417 		nqbp = qbp->qb_next;
3418 		freeband(qbp);
3419 		qbp = nqbp;
3420 	}
3421 	kmem_cache_free(queue_cache, qp);
3422 }
3423 
3424 /*
3425  * Allocate a qband structure.
3426  */
3427 qband_t *
3428 allocband(void)
3429 {
3430 	qband_t *qbp;
3431 
3432 	qbp = kmem_cache_alloc(qband_cache, KM_NOSLEEP);
3433 	if (qbp == NULL)
3434 		return (NULL);
3435 
3436 	qbp->qb_next	= NULL;
3437 	qbp->qb_count	= 0;
3438 	qbp->qb_mblkcnt	= 0;
3439 	qbp->qb_first	= NULL;
3440 	qbp->qb_last	= NULL;
3441 	qbp->qb_flag	= 0;
3442 
3443 	return (qbp);
3444 }
3445 
3446 /*
3447  * Free a qband structure.
3448  */
3449 void
3450 freeband(qband_t *qbp)
3451 {
3452 	kmem_cache_free(qband_cache, qbp);
3453 }
3454 
3455 /*
3456  * Just like putnextctl(9F), except that allocb_wait() is used.
3457  *
3458  * Consolidation Private, and of course only callable from the stream head or
3459  * routines that may block.
3460  */
3461 int
3462 putnextctl_wait(queue_t *q, int type)
3463 {
3464 	mblk_t *bp;
3465 	int error;
3466 
3467 	if ((datamsg(type) && (type != M_DELAY)) ||
3468 	    (bp = allocb_wait(0, BPRI_HI, 0, &error)) == NULL)
3469 		return (0);
3470 
3471 	bp->b_datap->db_type = (unsigned char)type;
3472 	putnext(q, bp);
3473 	return (1);
3474 }
3475 
3476 /*
3477  * run any possible bufcalls.
3478  */
3479 void
3480 runbufcalls(void)
3481 {
3482 	strbufcall_t *bcp;
3483 
3484 	mutex_enter(&bcall_monitor);
3485 	mutex_enter(&strbcall_lock);
3486 
3487 	if (strbcalls.bc_head) {
3488 		size_t count;
3489 		int nevent;
3490 
3491 		/*
3492 		 * count how many events are on the list
3493 		 * now so we can check to avoid looping
3494 		 * in low memory situations
3495 		 */
3496 		nevent = 0;
3497 		for (bcp = strbcalls.bc_head; bcp; bcp = bcp->bc_next)
3498 			nevent++;
3499 
3500 		/*
3501 		 * get estimate of available memory from kmem_avail().
3502 		 * awake all bufcall functions waiting for
3503 		 * memory whose request could be satisfied
3504 		 * by 'count' memory and let 'em fight for it.
3505 		 */
3506 		count = kmem_avail();
3507 		while ((bcp = strbcalls.bc_head) != NULL && nevent) {
3508 			STRSTAT(bufcalls);
3509 			--nevent;
3510 			if (bcp->bc_size <= count) {
3511 				bcp->bc_executor = curthread;
3512 				mutex_exit(&strbcall_lock);
3513 				(*bcp->bc_func)(bcp->bc_arg);
3514 				mutex_enter(&strbcall_lock);
3515 				bcp->bc_executor = NULL;
3516 				cv_broadcast(&bcall_cv);
3517 				strbcalls.bc_head = bcp->bc_next;
3518 				kmem_free(bcp, sizeof (strbufcall_t));
3519 			} else {
3520 				/*
3521 				 * too big, try again later - note
3522 				 * that nevent was decremented above
3523 				 * so we won't retry this one on this
3524 				 * iteration of the loop
3525 				 */
3526 				if (bcp->bc_next != NULL) {
3527 					strbcalls.bc_head = bcp->bc_next;
3528 					bcp->bc_next = NULL;
3529 					strbcalls.bc_tail->bc_next = bcp;
3530 					strbcalls.bc_tail = bcp;
3531 				}
3532 			}
3533 		}
3534 		if (strbcalls.bc_head == NULL)
3535 			strbcalls.bc_tail = NULL;
3536 	}
3537 
3538 	mutex_exit(&strbcall_lock);
3539 	mutex_exit(&bcall_monitor);
3540 }
3541 
3542 
3543 /*
3544  * actually run queue's service routine.
3545  */
3546 static void
3547 runservice(queue_t *q)
3548 {
3549 	qband_t *qbp;
3550 
3551 	ASSERT(q->q_qinfo->qi_srvp);
3552 again:
3553 	entersq(q->q_syncq, SQ_SVC);
3554 	TRACE_1(TR_FAC_STREAMS_FR, TR_QRUNSERVICE_START,
3555 		"runservice starts:%p", q);
3556 
3557 	if (!(q->q_flag & QWCLOSE))
3558 		(*q->q_qinfo->qi_srvp)(q);
3559 
3560 	TRACE_1(TR_FAC_STREAMS_FR, TR_QRUNSERVICE_END,
3561 		"runservice ends:(%p)", q);
3562 
3563 	leavesq(q->q_syncq, SQ_SVC);
3564 
3565 	mutex_enter(QLOCK(q));
3566 	if (q->q_flag & QENAB) {
3567 		q->q_flag &= ~QENAB;
3568 		mutex_exit(QLOCK(q));
3569 		goto again;
3570 	}
3571 	q->q_flag &= ~QINSERVICE;
3572 	q->q_flag &= ~QBACK;
3573 	for (qbp = q->q_bandp; qbp; qbp = qbp->qb_next)
3574 		qbp->qb_flag &= ~QB_BACK;
3575 	/*
3576 	 * Wakeup thread waiting for the service procedure
3577 	 * to be run (strclose and qdetach).
3578 	 */
3579 	cv_broadcast(&q->q_wait);
3580 
3581 	mutex_exit(QLOCK(q));
3582 }
3583 
3584 /*
3585  * Background processing of bufcalls.
3586  */
3587 void
3588 streams_bufcall_service(void)
3589 {
3590 	callb_cpr_t	cprinfo;
3591 
3592 	CALLB_CPR_INIT(&cprinfo, &strbcall_lock, callb_generic_cpr,
3593 	    "streams_bufcall_service");
3594 
3595 	mutex_enter(&strbcall_lock);
3596 
3597 	for (;;) {
3598 		if (strbcalls.bc_head != NULL && kmem_avail() > 0) {
3599 			mutex_exit(&strbcall_lock);
3600 			runbufcalls();
3601 			mutex_enter(&strbcall_lock);
3602 		}
3603 		if (strbcalls.bc_head != NULL) {
3604 			clock_t wt, tick;
3605 
3606 			STRSTAT(bcwaits);
3607 			/* Wait for memory to become available */
3608 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
3609 			tick = SEC_TO_TICK(60);
3610 			time_to_wait(&wt, tick);
3611 			(void) cv_timedwait(&memavail_cv, &strbcall_lock, wt);
3612 			CALLB_CPR_SAFE_END(&cprinfo, &strbcall_lock);
3613 		}
3614 
3615 		/* Wait for new work to arrive */
3616 		if (strbcalls.bc_head == NULL) {
3617 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
3618 			cv_wait(&strbcall_cv, &strbcall_lock);
3619 			CALLB_CPR_SAFE_END(&cprinfo, &strbcall_lock);
3620 		}
3621 	}
3622 }
3623 
3624 /*
3625  * Background processing of streams background tasks which failed
3626  * taskq_dispatch.
3627  */
3628 static void
3629 streams_qbkgrnd_service(void)
3630 {
3631 	callb_cpr_t cprinfo;
3632 	queue_t *q;
3633 
3634 	CALLB_CPR_INIT(&cprinfo, &service_queue, callb_generic_cpr,
3635 	    "streams_bkgrnd_service");
3636 
3637 	mutex_enter(&service_queue);
3638 
3639 	for (;;) {
3640 		/*
3641 		 * Wait for work to arrive.
3642 		 */
3643 		while ((freebs_list == NULL) && (qhead == NULL)) {
3644 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
3645 			cv_wait(&services_to_run, &service_queue);
3646 			CALLB_CPR_SAFE_END(&cprinfo, &service_queue);
3647 		}
3648 		/*
3649 		 * Handle all pending freebs requests to free memory.
3650 		 */
3651 		while (freebs_list != NULL) {
3652 			mblk_t *mp = freebs_list;
3653 			freebs_list = mp->b_next;
3654 			mutex_exit(&service_queue);
3655 			mblk_free(mp);
3656 			mutex_enter(&service_queue);
3657 		}
3658 		/*
3659 		 * Run pending queues.
3660 		 */
3661 		while (qhead != NULL) {
3662 			DQ(q, qhead, qtail, q_link);
3663 			ASSERT(q != NULL);
3664 			mutex_exit(&service_queue);
3665 			queue_service(q);
3666 			mutex_enter(&service_queue);
3667 		}
3668 		ASSERT(qhead == NULL && qtail == NULL);
3669 	}
3670 }
3671 
3672 /*
3673  * Background processing of streams background tasks which failed
3674  * taskq_dispatch.
3675  */
3676 static void
3677 streams_sqbkgrnd_service(void)
3678 {
3679 	callb_cpr_t cprinfo;
3680 	syncq_t *sq;
3681 
3682 	CALLB_CPR_INIT(&cprinfo, &service_queue, callb_generic_cpr,
3683 	    "streams_sqbkgrnd_service");
3684 
3685 	mutex_enter(&service_queue);
3686 
3687 	for (;;) {
3688 		/*
3689 		 * Wait for work to arrive.
3690 		 */
3691 		while (sqhead == NULL) {
3692 			CALLB_CPR_SAFE_BEGIN(&cprinfo);
3693 			cv_wait(&syncqs_to_run, &service_queue);
3694 			CALLB_CPR_SAFE_END(&cprinfo, &service_queue);
3695 		}
3696 
3697 		/*
3698 		 * Run pending syncqs.
3699 		 */
3700 		while (sqhead != NULL) {
3701 			DQ(sq, sqhead, sqtail, sq_next);
3702 			ASSERT(sq != NULL);
3703 			ASSERT(sq->sq_svcflags & SQ_BGTHREAD);
3704 			mutex_exit(&service_queue);
3705 			syncq_service(sq);
3706 			mutex_enter(&service_queue);
3707 		}
3708 	}
3709 }
3710 
3711 /*
3712  * Disable the syncq and wait for background syncq processing to complete.
3713  * If the syncq is placed on the sqhead/sqtail queue, try to remove it from the
3714  * list.
3715  */
3716 void
3717 wait_sq_svc(syncq_t *sq)
3718 {
3719 	mutex_enter(SQLOCK(sq));
3720 	sq->sq_svcflags |= SQ_DISABLED;
3721 	if (sq->sq_svcflags & SQ_BGTHREAD) {
3722 		syncq_t *sq_chase;
3723 		syncq_t *sq_curr;
3724 		int removed;
3725 
3726 		ASSERT(sq->sq_servcount == 1);
3727 		mutex_enter(&service_queue);
3728 		RMQ(sq, sqhead, sqtail, sq_next, sq_chase, sq_curr, removed);
3729 		mutex_exit(&service_queue);
3730 		if (removed) {
3731 			sq->sq_svcflags &= ~SQ_BGTHREAD;
3732 			sq->sq_servcount = 0;
3733 			STRSTAT(sqremoved);
3734 			goto done;
3735 		}
3736 	}
3737 	while (sq->sq_servcount != 0) {
3738 		sq->sq_flags |= SQ_WANTWAKEUP;
3739 		cv_wait(&sq->sq_wait, SQLOCK(sq));
3740 	}
3741 done:
3742 	mutex_exit(SQLOCK(sq));
3743 }
3744 
3745 /*
3746  * Put a syncq on the list of syncq's to be serviced by the sqthread.
3747  * Add the argument to the end of the sqhead list and set the flag
3748  * indicating this syncq has been enabled.  If it has already been
3749  * enabled, don't do anything.
3750  * This routine assumes that SQLOCK is held.
3751  * NOTE that the lock order is to have the SQLOCK first,
3752  * so if the service_syncq lock is held, we need to release it
3753  * before aquiring the SQLOCK (mostly relevant for the background
3754  * thread, and this seems to be common among the STREAMS global locks).
3755  * Note the the sq_svcflags are protected by the SQLOCK.
3756  */
3757 void
3758 sqenable(syncq_t *sq)
3759 {
3760 	/*
3761 	 * This is probably not important except for where I believe it
3762 	 * is being called.  At that point, it should be held (and it
3763 	 * is a pain to release it just for this routine, so don't do
3764 	 * it).
3765 	 */
3766 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
3767 
3768 	IMPLY(sq->sq_servcount == 0, sq->sq_next == NULL);
3769 	IMPLY(sq->sq_next != NULL, sq->sq_svcflags & SQ_BGTHREAD);
3770 
3771 	/*
3772 	 * Do not put on list if background thread is scheduled or
3773 	 * syncq is disabled.
3774 	 */
3775 	if (sq->sq_svcflags & (SQ_DISABLED | SQ_BGTHREAD))
3776 		return;
3777 
3778 	/*
3779 	 * Check whether we should enable sq at all.
3780 	 * Non PERMOD syncqs may be drained by at most one thread.
3781 	 * PERMOD syncqs may be drained by several threads but we limit the
3782 	 * total amount to the lesser of
3783 	 *	Number of queues on the squeue and
3784 	 *	Number of CPUs.
3785 	 */
3786 	if (sq->sq_servcount != 0) {
3787 		if (((sq->sq_type & SQ_PERMOD) == 0) ||
3788 		    (sq->sq_servcount >= MIN(sq->sq_nqueues, ncpus_online))) {
3789 			STRSTAT(sqtoomany);
3790 			return;
3791 		}
3792 	}
3793 
3794 	sq->sq_tstamp = lbolt;
3795 	STRSTAT(sqenables);
3796 
3797 	/* Attempt a taskq dispatch */
3798 	sq->sq_servid = (void *)taskq_dispatch(streams_taskq,
3799 	    (task_func_t *)syncq_service, sq, TQ_NOSLEEP | TQ_NOQUEUE);
3800 	if (sq->sq_servid != NULL) {
3801 		sq->sq_servcount++;
3802 		return;
3803 	}
3804 
3805 	/*
3806 	 * This taskq dispatch failed, but a previous one may have succeeded.
3807 	 * Don't try to schedule on the background thread whilst there is
3808 	 * outstanding taskq processing.
3809 	 */
3810 	if (sq->sq_servcount != 0)
3811 		return;
3812 
3813 	/*
3814 	 * System is low on resources and can't perform a non-sleeping
3815 	 * dispatch. Schedule the syncq for a background thread and mark the
3816 	 * syncq to avoid any further taskq dispatch attempts.
3817 	 */
3818 	mutex_enter(&service_queue);
3819 	STRSTAT(taskqfails);
3820 	ENQUEUE(sq, sqhead, sqtail, sq_next);
3821 	sq->sq_svcflags |= SQ_BGTHREAD;
3822 	sq->sq_servcount = 1;
3823 	cv_signal(&syncqs_to_run);
3824 	mutex_exit(&service_queue);
3825 }
3826 
3827 /*
3828  * Note: fifo_close() depends on the mblk_t on the queue being freed
3829  * asynchronously. The asynchronous freeing of messages breaks the
3830  * recursive call chain of fifo_close() while there are I_SENDFD type of
3831  * messages refering other file pointers on the queue. Then when
3832  * closing pipes it can avoid stack overflow in case of daisy-chained
3833  * pipes, and also avoid deadlock in case of fifonode_t pairs (which
3834  * share the same fifolock_t).
3835  */
3836 
3837 /* ARGSUSED */
3838 void
3839 freebs_enqueue(mblk_t *mp, dblk_t *dbp)
3840 {
3841 	ASSERT(dbp->db_mblk == mp);
3842 
3843 	/*
3844 	 * Check data sanity. The dblock should have non-empty free function.
3845 	 * It is better to panic here then later when the dblock is freed
3846 	 * asynchronously when the context is lost.
3847 	 */
3848 	if (dbp->db_frtnp->free_func == NULL) {
3849 		panic("freebs_enqueue: dblock %p has a NULL free callback",
3850 		    (void *) dbp);
3851 	}
3852 
3853 	STRSTAT(freebs);
3854 	if (taskq_dispatch(streams_taskq, (task_func_t *)mblk_free, mp,
3855 	    TQ_NOSLEEP) == NULL) {
3856 		/*
3857 		 * System is low on resources and can't perform a non-sleeping
3858 		 * dispatch. Schedule for a background thread.
3859 		 */
3860 		mutex_enter(&service_queue);
3861 		STRSTAT(taskqfails);
3862 		mp->b_next = freebs_list;
3863 		freebs_list = mp;
3864 		cv_signal(&services_to_run);
3865 		mutex_exit(&service_queue);
3866 	}
3867 }
3868 
3869 /*
3870  * Set the QBACK or QB_BACK flag in the given queue for
3871  * the given priority band.
3872  */
3873 void
3874 setqback(queue_t *q, unsigned char pri)
3875 {
3876 	int i;
3877 	qband_t *qbp;
3878 	qband_t **qbpp;
3879 
3880 	ASSERT(MUTEX_HELD(QLOCK(q)));
3881 	if (pri != 0) {
3882 		if (pri > q->q_nband) {
3883 			qbpp = &q->q_bandp;
3884 			while (*qbpp)
3885 				qbpp = &(*qbpp)->qb_next;
3886 			while (pri > q->q_nband) {
3887 				if ((*qbpp = allocband()) == NULL) {
3888 					cmn_err(CE_WARN,
3889 					    "setqback: can't allocate qband\n");
3890 					return;
3891 				}
3892 				(*qbpp)->qb_hiwat = q->q_hiwat;
3893 				(*qbpp)->qb_lowat = q->q_lowat;
3894 				q->q_nband++;
3895 				qbpp = &(*qbpp)->qb_next;
3896 			}
3897 		}
3898 		qbp = q->q_bandp;
3899 		i = pri;
3900 		while (--i)
3901 			qbp = qbp->qb_next;
3902 		qbp->qb_flag |= QB_BACK;
3903 	} else {
3904 		q->q_flag |= QBACK;
3905 	}
3906 }
3907 
3908 int
3909 strcopyin(void *from, void *to, size_t len, int copyflag)
3910 {
3911 	if (copyflag & U_TO_K) {
3912 		ASSERT((copyflag & K_TO_K) == 0);
3913 		if (copyin(from, to, len))
3914 			return (EFAULT);
3915 	} else {
3916 		ASSERT(copyflag & K_TO_K);
3917 		bcopy(from, to, len);
3918 	}
3919 	return (0);
3920 }
3921 
3922 int
3923 strcopyout(void *from, void *to, size_t len, int copyflag)
3924 {
3925 	if (copyflag & U_TO_K) {
3926 		if (copyout(from, to, len))
3927 			return (EFAULT);
3928 	} else {
3929 		ASSERT(copyflag & K_TO_K);
3930 		bcopy(from, to, len);
3931 	}
3932 	return (0);
3933 }
3934 
3935 /*
3936  * strsignal_nolock() posts a signal to the process(es) at the stream head.
3937  * It assumes that the stream head lock is already held, whereas strsignal()
3938  * acquires the lock first.  This routine was created because a few callers
3939  * release the stream head lock before calling only to re-acquire it after
3940  * it returns.
3941  */
3942 void
3943 strsignal_nolock(stdata_t *stp, int sig, int32_t band)
3944 {
3945 	ASSERT(MUTEX_HELD(&stp->sd_lock));
3946 	switch (sig) {
3947 	case SIGPOLL:
3948 		if (stp->sd_sigflags & S_MSG)
3949 			strsendsig(stp->sd_siglist, S_MSG, (uchar_t)band, 0);
3950 		break;
3951 
3952 	default:
3953 		if (stp->sd_pgidp) {
3954 			pgsignal(stp->sd_pgidp, sig);
3955 		}
3956 		break;
3957 	}
3958 }
3959 
3960 void
3961 strsignal(stdata_t *stp, int sig, int32_t band)
3962 {
3963 	TRACE_3(TR_FAC_STREAMS_FR, TR_SENDSIG,
3964 		"strsignal:%p, %X, %X", stp, sig, band);
3965 
3966 	mutex_enter(&stp->sd_lock);
3967 	switch (sig) {
3968 	case SIGPOLL:
3969 		if (stp->sd_sigflags & S_MSG)
3970 			strsendsig(stp->sd_siglist, S_MSG, (uchar_t)band, 0);
3971 		break;
3972 
3973 	default:
3974 		if (stp->sd_pgidp) {
3975 			pgsignal(stp->sd_pgidp, sig);
3976 		}
3977 		break;
3978 	}
3979 	mutex_exit(&stp->sd_lock);
3980 }
3981 
3982 void
3983 strhup(stdata_t *stp)
3984 {
3985 	pollwakeup(&stp->sd_pollist, POLLHUP);
3986 	mutex_enter(&stp->sd_lock);
3987 	if (stp->sd_sigflags & S_HANGUP)
3988 		strsendsig(stp->sd_siglist, S_HANGUP, 0, 0);
3989 	mutex_exit(&stp->sd_lock);
3990 }
3991 
3992 void
3993 stralloctty(stdata_t *stp)
3994 {
3995 	proc_t *p = curproc;
3996 	sess_t *sp = p->p_sessp;
3997 
3998 	mutex_enter(&stp->sd_lock);
3999 	/*
4000 	 * No need to hold the session lock or do a TTY_HOLD() because
4001 	 * this is the only thread that can be the session leader and not
4002 	 * have a controlling tty.
4003 	 */
4004 	if ((stp->sd_flag &
4005 	    (STRHUP|STRDERR|STWRERR|STPLEX|STRISTTY)) == STRISTTY &&
4006 	    stp->sd_sidp == NULL &&		/* not allocated as ctty */
4007 	    sp->s_sidp == p->p_pidp &&		/* session leader */
4008 	    sp->s_flag != SESS_CLOSE &&		/* session is not closing */
4009 	    sp->s_vp == NULL) {			/* without ctty */
4010 		ASSERT(stp->sd_pgidp == NULL);
4011 		alloctty(p, makectty(stp->sd_vnode));
4012 
4013 		mutex_enter(&pidlock);
4014 		stp->sd_sidp = sp->s_sidp;
4015 		stp->sd_pgidp = sp->s_sidp;
4016 		PID_HOLD(stp->sd_pgidp);
4017 		PID_HOLD(stp->sd_sidp);
4018 		mutex_exit(&pidlock);
4019 	}
4020 	mutex_exit(&stp->sd_lock);
4021 }
4022 
4023 void
4024 strfreectty(stdata_t *stp)
4025 {
4026 	mutex_enter(&stp->sd_lock);
4027 	pgsignal(stp->sd_pgidp, SIGHUP);
4028 	mutex_enter(&pidlock);
4029 	PID_RELE(stp->sd_pgidp);
4030 	PID_RELE(stp->sd_sidp);
4031 	stp->sd_pgidp = NULL;
4032 	stp->sd_sidp = NULL;
4033 	mutex_exit(&pidlock);
4034 	mutex_exit(&stp->sd_lock);
4035 	if (!(stp->sd_flag & STRHUP))
4036 		strhup(stp);
4037 }
4038 /*
4039  * Backenable the first queue upstream from `q' with a service procedure.
4040  */
4041 void
4042 backenable(queue_t *q, uchar_t pri)
4043 {
4044 	queue_t	*nq;
4045 
4046 	/*
4047 	 * our presence might not prevent other modules in our own
4048 	 * stream from popping/pushing since the caller of getq might not
4049 	 * have a claim on the queue (some drivers do a getq on somebody
4050 	 * else's queue - they know that the queue itself is not going away
4051 	 * but the framework has to guarantee q_next in that stream.)
4052 	 */
4053 	claimstr(q);
4054 
4055 	/* find nearest back queue with service proc */
4056 	for (nq = backq(q); nq && !nq->q_qinfo->qi_srvp; nq = backq(nq)) {
4057 		ASSERT(STRMATED(q->q_stream) || STREAM(q) == STREAM(nq));
4058 	}
4059 
4060 	if (nq) {
4061 		kthread_t *freezer;
4062 		/*
4063 		 * backenable can be called either with no locks held
4064 		 * or with the stream frozen (the latter occurs when a module
4065 		 * calls rmvq with the stream frozen.) If the stream is frozen
4066 		 * by the caller the caller will hold all qlocks in the stream.
4067 		 */
4068 		freezer = STREAM(q)->sd_freezer;
4069 		if (freezer != curthread) {
4070 			mutex_enter(QLOCK(nq));
4071 		}
4072 #ifdef DEBUG
4073 		else {
4074 			ASSERT(frozenstr(q));
4075 			ASSERT(MUTEX_HELD(QLOCK(q)));
4076 			ASSERT(MUTEX_HELD(QLOCK(nq)));
4077 		}
4078 #endif
4079 		setqback(nq, pri);
4080 		qenable_locked(nq);
4081 		if (freezer != curthread)
4082 			mutex_exit(QLOCK(nq));
4083 	}
4084 	releasestr(q);
4085 }
4086 
4087 /*
4088  * Return the appropriate errno when one of flags_to_check is set
4089  * in sd_flags. Uses the exported error routines if they are set.
4090  * Will return 0 if non error is set (or if the exported error routines
4091  * do not return an error).
4092  *
4093  * If there is both a read and write error to check we prefer the read error.
4094  * Also, give preference to recorded errno's over the error functions.
4095  * The flags that are handled are:
4096  *	STPLEX		return EINVAL
4097  *	STRDERR		return sd_rerror (and clear if STRDERRNONPERSIST)
4098  *	STWRERR		return sd_werror (and clear if STWRERRNONPERSIST)
4099  *	STRHUP		return sd_werror
4100  *
4101  * If the caller indicates that the operation is a peek a nonpersistent error
4102  * is not cleared.
4103  */
4104 int
4105 strgeterr(stdata_t *stp, int32_t flags_to_check, int ispeek)
4106 {
4107 	int32_t sd_flag = stp->sd_flag & flags_to_check;
4108 	int error = 0;
4109 
4110 	ASSERT(MUTEX_HELD(&stp->sd_lock));
4111 	ASSERT((flags_to_check & ~(STRDERR|STWRERR|STRHUP|STPLEX)) == 0);
4112 	if (sd_flag & STPLEX)
4113 		error = EINVAL;
4114 	else if (sd_flag & STRDERR) {
4115 		error = stp->sd_rerror;
4116 		if ((stp->sd_flag & STRDERRNONPERSIST) && !ispeek) {
4117 			/*
4118 			 * Read errors are non-persistent i.e. discarded once
4119 			 * returned to a non-peeking caller,
4120 			 */
4121 			stp->sd_rerror = 0;
4122 			stp->sd_flag &= ~STRDERR;
4123 		}
4124 		if (error == 0 && stp->sd_rderrfunc != NULL) {
4125 			int clearerr = 0;
4126 
4127 			error = (*stp->sd_rderrfunc)(stp->sd_vnode, ispeek,
4128 						&clearerr);
4129 			if (clearerr) {
4130 				stp->sd_flag &= ~STRDERR;
4131 				stp->sd_rderrfunc = NULL;
4132 			}
4133 		}
4134 	} else if (sd_flag & STWRERR) {
4135 		error = stp->sd_werror;
4136 		if ((stp->sd_flag & STWRERRNONPERSIST) && !ispeek) {
4137 			/*
4138 			 * Write errors are non-persistent i.e. discarded once
4139 			 * returned to a non-peeking caller,
4140 			 */
4141 			stp->sd_werror = 0;
4142 			stp->sd_flag &= ~STWRERR;
4143 		}
4144 		if (error == 0 && stp->sd_wrerrfunc != NULL) {
4145 			int clearerr = 0;
4146 
4147 			error = (*stp->sd_wrerrfunc)(stp->sd_vnode, ispeek,
4148 						&clearerr);
4149 			if (clearerr) {
4150 				stp->sd_flag &= ~STWRERR;
4151 				stp->sd_wrerrfunc = NULL;
4152 			}
4153 		}
4154 	} else if (sd_flag & STRHUP) {
4155 		/* sd_werror set when STRHUP */
4156 		error = stp->sd_werror;
4157 	}
4158 	return (error);
4159 }
4160 
4161 
4162 /*
4163  * single-thread open/close/push/pop
4164  * for twisted streams also
4165  */
4166 int
4167 strstartplumb(stdata_t *stp, int flag, int cmd)
4168 {
4169 	int waited = 1;
4170 	int error = 0;
4171 
4172 	if (STRMATED(stp)) {
4173 		struct stdata *stmatep = stp->sd_mate;
4174 
4175 		STRLOCKMATES(stp);
4176 		while (waited) {
4177 			waited = 0;
4178 			while (stmatep->sd_flag & (STWOPEN|STRCLOSE|STRPLUMB)) {
4179 				if ((cmd == I_POP) &&
4180 				    (flag & (FNDELAY|FNONBLOCK))) {
4181 					STRUNLOCKMATES(stp);
4182 					return (EAGAIN);
4183 				}
4184 				waited = 1;
4185 				mutex_exit(&stp->sd_lock);
4186 				if (!cv_wait_sig(&stmatep->sd_monitor,
4187 				    &stmatep->sd_lock)) {
4188 					mutex_exit(&stmatep->sd_lock);
4189 					return (EINTR);
4190 				}
4191 				mutex_exit(&stmatep->sd_lock);
4192 				STRLOCKMATES(stp);
4193 			}
4194 			while (stp->sd_flag & (STWOPEN|STRCLOSE|STRPLUMB)) {
4195 				if ((cmd == I_POP) &&
4196 					(flag & (FNDELAY|FNONBLOCK))) {
4197 					STRUNLOCKMATES(stp);
4198 					return (EAGAIN);
4199 				}
4200 				waited = 1;
4201 				mutex_exit(&stmatep->sd_lock);
4202 				if (!cv_wait_sig(&stp->sd_monitor,
4203 				    &stp->sd_lock)) {
4204 					mutex_exit(&stp->sd_lock);
4205 					return (EINTR);
4206 				}
4207 				mutex_exit(&stp->sd_lock);
4208 				STRLOCKMATES(stp);
4209 			}
4210 			if (stp->sd_flag & (STRDERR|STWRERR|STRHUP|STPLEX)) {
4211 				error = strgeterr(stp,
4212 					STRDERR|STWRERR|STRHUP|STPLEX, 0);
4213 				if (error != 0) {
4214 					STRUNLOCKMATES(stp);
4215 					return (error);
4216 				}
4217 			}
4218 		}
4219 		stp->sd_flag |= STRPLUMB;
4220 		STRUNLOCKMATES(stp);
4221 	} else {
4222 		mutex_enter(&stp->sd_lock);
4223 		while (stp->sd_flag & (STWOPEN|STRCLOSE|STRPLUMB)) {
4224 			if (((cmd == I_POP) || (cmd == _I_REMOVE)) &&
4225 			    (flag & (FNDELAY|FNONBLOCK))) {
4226 				mutex_exit(&stp->sd_lock);
4227 				return (EAGAIN);
4228 			}
4229 			if (!cv_wait_sig(&stp->sd_monitor, &stp->sd_lock)) {
4230 				mutex_exit(&stp->sd_lock);
4231 				return (EINTR);
4232 			}
4233 			if (stp->sd_flag & (STRDERR|STWRERR|STRHUP|STPLEX)) {
4234 				error = strgeterr(stp,
4235 					STRDERR|STWRERR|STRHUP|STPLEX, 0);
4236 				if (error != 0) {
4237 					mutex_exit(&stp->sd_lock);
4238 					return (error);
4239 				}
4240 			}
4241 		}
4242 		stp->sd_flag |= STRPLUMB;
4243 		mutex_exit(&stp->sd_lock);
4244 	}
4245 	return (0);
4246 }
4247 
4248 /*
4249  * Complete the plumbing operation associated with stream `stp'.
4250  */
4251 void
4252 strendplumb(stdata_t *stp)
4253 {
4254 	ASSERT(MUTEX_HELD(&stp->sd_lock));
4255 	ASSERT(stp->sd_flag & STRPLUMB);
4256 	stp->sd_flag &= ~STRPLUMB;
4257 	cv_broadcast(&stp->sd_monitor);
4258 }
4259 
4260 /*
4261  * This describes how the STREAMS framework handles synchronization
4262  * during open/push and close/pop.
4263  * The key interfaces for open and close are qprocson and qprocsoff,
4264  * respectively. While the close case in general is harder both open
4265  * have close have significant similarities.
4266  *
4267  * During close the STREAMS framework has to both ensure that there
4268  * are no stale references to the queue pair (and syncq) that
4269  * are being closed and also provide the guarantees that are documented
4270  * in qprocsoff(9F).
4271  * If there are stale references to the queue that is closing it can
4272  * result in kernel memory corruption or kernel panics.
4273  *
4274  * Note that is it up to the module/driver to ensure that it itself
4275  * does not have any stale references to the closing queues once its close
4276  * routine returns. This includes:
4277  *  - Cancelling any timeout/bufcall/qtimeout/qbufcall callback routines
4278  *    associated with the queues. For timeout and bufcall callbacks the
4279  *    module/driver also has to ensure (or wait for) any callbacks that
4280  *    are in progress.
4281  *  - If the module/driver is using esballoc it has to ensure that any
4282  *    esballoc free functions do not refer to a queue that has closed.
4283  *    (Note that in general the close routine can not wait for the esballoc'ed
4284  *    messages to be freed since that can cause a deadlock.)
4285  *  - Cancelling any interrupts that refer to the closing queues and
4286  *    also ensuring that there are no interrupts in progress that will
4287  *    refer to the closing queues once the close routine returns.
4288  *  - For multiplexors removing any driver global state that refers to
4289  *    the closing queue and also ensuring that there are no threads in
4290  *    the multiplexor that has picked up a queue pointer but not yet
4291  *    finished using it.
4292  *
4293  * In addition, a driver/module can only reference the q_next pointer
4294  * in its open, close, put, or service procedures or in a
4295  * qtimeout/qbufcall callback procedure executing "on" the correct
4296  * stream. Thus it can not reference the q_next pointer in an interrupt
4297  * routine or a timeout, bufcall or esballoc callback routine. Likewise
4298  * it can not reference q_next of a different queue e.g. in a mux that
4299  * passes messages from one queues put/service procedure to another queue.
4300  * In all the cases when the driver/module can not access the q_next
4301  * field it must use the *next* versions e.g. canputnext instead of
4302  * canput(q->q_next) and putnextctl instead of putctl(q->q_next, ...).
4303  *
4304  *
4305  * Assuming that the driver/module conforms to the above constraints
4306  * the STREAMS framework has to avoid stale references to q_next for all
4307  * the framework internal cases which include (but are not limited to):
4308  *  - Threads in canput/canputnext/backenable and elsewhere that are
4309  *    walking q_next.
4310  *  - Messages on a syncq that have a reference to the queue through b_queue.
4311  *  - Messages on an outer perimeter (syncq) that have a reference to the
4312  *    queue through b_queue.
4313  *  - Threads that use q_nfsrv (e.g. canput) to find a queue.
4314  *    Note that only canput and bcanput use q_nfsrv without any locking.
4315  *
4316  * The STREAMS framework providing the qprocsoff(9F) guarantees means that
4317  * after qprocsoff returns, the framework has to ensure that no threads can
4318  * enter the put or service routines for the closing read or write-side queue.
4319  * In addition to preventing "direct" entry into the put procedures
4320  * the framework also has to prevent messages being drained from
4321  * the syncq or the outer perimeter.
4322  * XXX Note that currently qdetach does relies on D_MTOCEXCL as the only
4323  * mechanism to prevent qwriter(PERIM_OUTER) from running after
4324  * qprocsoff has returned.
4325  * Note that if a module/driver uses put(9F) on one of its own queues
4326  * it is up to the module/driver to ensure that the put() doesn't
4327  * get called when the queue is closing.
4328  *
4329  *
4330  * The framework aspects of the above "contract" is implemented by
4331  * qprocsoff, removeq, and strlock:
4332  *  - qprocsoff (disable_svc) sets QWCLOSE to prevent runservice from
4333  *    entering the service procedures.
4334  *  - strlock acquires the sd_lock and sd_reflock to prevent putnext,
4335  *    canputnext, backenable etc from dereferencing the q_next that will
4336  *    soon change.
4337  *  - strlock waits for sd_refcnt to be zero to wait for e.g. any canputnext
4338  *    or other q_next walker that uses claimstr/releasestr to finish.
4339  *  - optionally for every syncq in the stream strlock acquires all the
4340  *    sq_lock's and waits for all sq_counts to drop to a value that indicates
4341  *    that no thread executes in the put or service procedures and that no
4342  *    thread is draining into the module/driver. This ensures that no
4343  *    open, close, put, service, or qtimeout/qbufcall callback procedure is
4344  *    currently executing hence no such thread can end up with the old stale
4345  *    q_next value and no canput/backenable can have the old stale
4346  *    q_nfsrv/q_next.
4347  *  - qdetach (wait_svc) makes sure that any scheduled or running threads
4348  *    have either finished or observed the QWCLOSE flag and gone away.
4349  */
4350 
4351 
4352 /*
4353  * Get all the locks necessary to change q_next.
4354  *
4355  * Wait for sd_refcnt to reach 0 and, if sqlist is present, wait for  the
4356  * sq_count of each syncq in the list to drop to sq_rmqcount, indicating that
4357  * the only threads inside the sqncq are threads currently calling removeq().
4358  * Since threads calling removeq() are in the process of removing their queues
4359  * from the stream, we do not need to worry about them accessing a stale q_next
4360  * pointer and thus we do not need to wait for them to exit (in fact, waiting
4361  * for them can cause deadlock).
4362  *
4363  * This routine is subject to starvation since it does not set any flag to
4364  * prevent threads from entering a module in the stream(i.e. sq_count can
4365  * increase on some syncq while it is waiting on some other syncq.)
4366  *
4367  * Assumes that only one thread attempts to call strlock for a given
4368  * stream. If this is not the case the two threads would deadlock.
4369  * This assumption is guaranteed since strlock is only called by insertq
4370  * and removeq and streams plumbing changes are single-threaded for
4371  * a given stream using the STWOPEN, STRCLOSE, and STRPLUMB flags.
4372  *
4373  * For pipes, it is not difficult to atomically designate a pair of streams
4374  * to be mated. Once mated atomically by the framework the twisted pair remain
4375  * configured that way until dismantled atomically by the framework.
4376  * When plumbing takes place on a twisted stream it is necessary to ensure that
4377  * this operation is done exclusively on the twisted stream since two such
4378  * operations, each initiated on different ends of the pipe will deadlock
4379  * waiting for each other to complete.
4380  *
4381  * On entry, no locks should be held.
4382  * The locks acquired and held by strlock depends on a few factors.
4383  * - If sqlist is non-NULL all the syncq locks in the sqlist will be acquired
4384  *   and held on exit and all sq_count are at an acceptable level.
4385  * - In all cases, sd_lock and sd_reflock are acquired and held on exit with
4386  *   sd_refcnt being zero.
4387  */
4388 
4389 static void
4390 strlock(struct stdata *stp, sqlist_t *sqlist)
4391 {
4392 	syncql_t *sql, *sql2;
4393 retry:
4394 	/*
4395 	 * Wait for any claimstr to go away.
4396 	 */
4397 	if (STRMATED(stp)) {
4398 		struct stdata *stp1, *stp2;
4399 
4400 		STRLOCKMATES(stp);
4401 		/*
4402 		 * Note that the selection of locking order is not
4403 		 * important, just that they are always aquired in
4404 		 * the same order.  To assure this, we choose this
4405 		 * order based on the value of the pointer, and since
4406 		 * the pointer will not change for the life of this
4407 		 * pair, we will always grab the locks in the same
4408 		 * order (and hence, prevent deadlocks).
4409 		 */
4410 		if (&(stp->sd_lock) > &((stp->sd_mate)->sd_lock)) {
4411 			stp1 = stp;
4412 			stp2 = stp->sd_mate;
4413 		} else {
4414 			stp2 = stp;
4415 			stp1 = stp->sd_mate;
4416 		}
4417 		mutex_enter(&stp1->sd_reflock);
4418 		if (stp1->sd_refcnt > 0) {
4419 			STRUNLOCKMATES(stp);
4420 			cv_wait(&stp1->sd_refmonitor, &stp1->sd_reflock);
4421 			mutex_exit(&stp1->sd_reflock);
4422 			goto retry;
4423 		}
4424 		mutex_enter(&stp2->sd_reflock);
4425 		if (stp2->sd_refcnt > 0) {
4426 			STRUNLOCKMATES(stp);
4427 			mutex_exit(&stp1->sd_reflock);
4428 			cv_wait(&stp2->sd_refmonitor, &stp2->sd_reflock);
4429 			mutex_exit(&stp2->sd_reflock);
4430 			goto retry;
4431 		}
4432 		STREAM_PUTLOCKS_ENTER(stp1);
4433 		STREAM_PUTLOCKS_ENTER(stp2);
4434 	} else {
4435 		mutex_enter(&stp->sd_lock);
4436 		mutex_enter(&stp->sd_reflock);
4437 		while (stp->sd_refcnt > 0) {
4438 			mutex_exit(&stp->sd_lock);
4439 			cv_wait(&stp->sd_refmonitor, &stp->sd_reflock);
4440 			if (mutex_tryenter(&stp->sd_lock) == 0) {
4441 				mutex_exit(&stp->sd_reflock);
4442 				mutex_enter(&stp->sd_lock);
4443 				mutex_enter(&stp->sd_reflock);
4444 			}
4445 		}
4446 		STREAM_PUTLOCKS_ENTER(stp);
4447 	}
4448 
4449 	if (sqlist == NULL)
4450 		return;
4451 
4452 	for (sql = sqlist->sqlist_head; sql; sql = sql->sql_next) {
4453 		syncq_t *sq = sql->sql_sq;
4454 		uint16_t count;
4455 
4456 		mutex_enter(SQLOCK(sq));
4457 		count = sq->sq_count;
4458 		ASSERT(sq->sq_rmqcount <= count);
4459 		SQ_PUTLOCKS_ENTER(sq);
4460 		SUM_SQ_PUTCOUNTS(sq, count);
4461 		if (count == sq->sq_rmqcount)
4462 			continue;
4463 
4464 		/* Failed - drop all locks that we have acquired so far */
4465 		if (STRMATED(stp)) {
4466 			STREAM_PUTLOCKS_EXIT(stp);
4467 			STREAM_PUTLOCKS_EXIT(stp->sd_mate);
4468 			STRUNLOCKMATES(stp);
4469 			mutex_exit(&stp->sd_reflock);
4470 			mutex_exit(&stp->sd_mate->sd_reflock);
4471 		} else {
4472 			STREAM_PUTLOCKS_EXIT(stp);
4473 			mutex_exit(&stp->sd_lock);
4474 			mutex_exit(&stp->sd_reflock);
4475 		}
4476 		for (sql2 = sqlist->sqlist_head; sql2 != sql;
4477 		    sql2 = sql2->sql_next) {
4478 			SQ_PUTLOCKS_EXIT(sql2->sql_sq);
4479 			mutex_exit(SQLOCK(sql2->sql_sq));
4480 		}
4481 
4482 		/*
4483 		 * The wait loop below may starve when there are many threads
4484 		 * claiming the syncq. This is especially a problem with permod
4485 		 * syncqs (IP). To lessen the impact of the problem we increment
4486 		 * sq_needexcl and clear fastbits so that putnexts will slow
4487 		 * down and call sqenable instead of draining right away.
4488 		 */
4489 		sq->sq_needexcl++;
4490 		SQ_PUTCOUNT_CLRFAST_LOCKED(sq);
4491 		while (count > sq->sq_rmqcount) {
4492 			sq->sq_flags |= SQ_WANTWAKEUP;
4493 			SQ_PUTLOCKS_EXIT(sq);
4494 			cv_wait(&sq->sq_wait, SQLOCK(sq));
4495 			count = sq->sq_count;
4496 			SQ_PUTLOCKS_ENTER(sq);
4497 			SUM_SQ_PUTCOUNTS(sq, count);
4498 		}
4499 		sq->sq_needexcl--;
4500 		if (sq->sq_needexcl == 0)
4501 			SQ_PUTCOUNT_SETFAST_LOCKED(sq);
4502 		SQ_PUTLOCKS_EXIT(sq);
4503 		ASSERT(count == sq->sq_rmqcount);
4504 		mutex_exit(SQLOCK(sq));
4505 		goto retry;
4506 	}
4507 }
4508 
4509 /*
4510  * Drop all the locks that strlock acquired.
4511  */
4512 static void
4513 strunlock(struct stdata *stp, sqlist_t *sqlist)
4514 {
4515 	syncql_t *sql;
4516 
4517 	if (STRMATED(stp)) {
4518 		STREAM_PUTLOCKS_EXIT(stp);
4519 		STREAM_PUTLOCKS_EXIT(stp->sd_mate);
4520 		STRUNLOCKMATES(stp);
4521 		mutex_exit(&stp->sd_reflock);
4522 		mutex_exit(&stp->sd_mate->sd_reflock);
4523 	} else {
4524 		STREAM_PUTLOCKS_EXIT(stp);
4525 		mutex_exit(&stp->sd_lock);
4526 		mutex_exit(&stp->sd_reflock);
4527 	}
4528 
4529 	if (sqlist == NULL)
4530 		return;
4531 
4532 	for (sql = sqlist->sqlist_head; sql; sql = sql->sql_next) {
4533 		SQ_PUTLOCKS_EXIT(sql->sql_sq);
4534 		mutex_exit(SQLOCK(sql->sql_sq));
4535 	}
4536 }
4537 
4538 /*
4539  * When the module has service procedure, we need check if the next
4540  * module which has service procedure is in flow control to trigger
4541  * the backenable.
4542  */
4543 static void
4544 backenable_insertedq(queue_t *q)
4545 {
4546 	qband_t	*qbp;
4547 
4548 	claimstr(q);
4549 	if (q->q_qinfo->qi_srvp != NULL && q->q_next != NULL) {
4550 		if (q->q_next->q_nfsrv->q_flag & QWANTW)
4551 			backenable(q, 0);
4552 
4553 		qbp = q->q_next->q_nfsrv->q_bandp;
4554 		for (; qbp != NULL; qbp = qbp->qb_next)
4555 			if ((qbp->qb_flag & QB_WANTW) && qbp->qb_first != NULL)
4556 				backenable(q, qbp->qb_first->b_band);
4557 	}
4558 	releasestr(q);
4559 }
4560 
4561 /*
4562  * Given two read queues, insert a new single one after another.
4563  *
4564  * This routine acquires all the necessary locks in order to change
4565  * q_next and related pointer using strlock().
4566  * It depends on the stream head ensuring that there are no concurrent
4567  * insertq or removeq on the same stream. The stream head ensures this
4568  * using the flags STWOPEN, STRCLOSE, and STRPLUMB.
4569  *
4570  * Note that no syncq locks are held during the q_next change. This is
4571  * applied to all streams since, unlike removeq, there is no problem of stale
4572  * pointers when adding a module to the stream. Thus drivers/modules that do a
4573  * canput(rq->q_next) would never get a closed/freed queue pointer even if we
4574  * applied this optimization to all streams.
4575  */
4576 void
4577 insertq(struct stdata *stp, queue_t *new)
4578 {
4579 	queue_t	*after;
4580 	queue_t *wafter;
4581 	queue_t *wnew = _WR(new);
4582 	boolean_t have_fifo = B_FALSE;
4583 
4584 	if (new->q_flag & _QINSERTING) {
4585 		ASSERT(stp->sd_vnode->v_type != VFIFO);
4586 		after = new->q_next;
4587 		wafter = _WR(new->q_next);
4588 	} else {
4589 		after = _RD(stp->sd_wrq);
4590 		wafter = stp->sd_wrq;
4591 	}
4592 
4593 	TRACE_2(TR_FAC_STREAMS_FR, TR_INSERTQ,
4594 		"insertq:%p, %p", after, new);
4595 	ASSERT(after->q_flag & QREADR);
4596 	ASSERT(new->q_flag & QREADR);
4597 
4598 	strlock(stp, NULL);
4599 
4600 	/* Do we have a FIFO? */
4601 	if (wafter->q_next == after) {
4602 		have_fifo = B_TRUE;
4603 		wnew->q_next = new;
4604 	} else {
4605 		wnew->q_next = wafter->q_next;
4606 	}
4607 	new->q_next = after;
4608 
4609 	set_nfsrv_ptr(new, wnew, after, wafter);
4610 	/*
4611 	 * set_nfsrv_ptr() needs to know if this is an insertion or not,
4612 	 * so only reset this flag after calling it.
4613 	 */
4614 	new->q_flag &= ~_QINSERTING;
4615 
4616 	if (have_fifo) {
4617 		wafter->q_next = wnew;
4618 	} else {
4619 		if (wafter->q_next)
4620 			_OTHERQ(wafter->q_next)->q_next = new;
4621 		wafter->q_next = wnew;
4622 	}
4623 
4624 	set_qend(new);
4625 	/* The QEND flag might have to be updated for the upstream guy */
4626 	set_qend(after);
4627 
4628 	ASSERT(_SAMESTR(new) == O_SAMESTR(new));
4629 	ASSERT(_SAMESTR(wnew) == O_SAMESTR(wnew));
4630 	ASSERT(_SAMESTR(after) == O_SAMESTR(after));
4631 	ASSERT(_SAMESTR(wafter) == O_SAMESTR(wafter));
4632 	strsetuio(stp);
4633 
4634 	/*
4635 	 * If this was a module insertion, bump the push count.
4636 	 */
4637 	if (!(new->q_flag & QISDRV))
4638 		stp->sd_pushcnt++;
4639 
4640 	strunlock(stp, NULL);
4641 
4642 	/* check if the write Q needs backenable */
4643 	backenable_insertedq(wnew);
4644 
4645 	/* check if the read Q needs backenable */
4646 	backenable_insertedq(new);
4647 }
4648 
4649 /*
4650  * Given a read queue, unlink it from any neighbors.
4651  *
4652  * This routine acquires all the necessary locks in order to
4653  * change q_next and related pointers and also guard against
4654  * stale references (e.g. through q_next) to the queue that
4655  * is being removed. It also plays part of the role in ensuring
4656  * that the module's/driver's put procedure doesn't get called
4657  * after qprocsoff returns.
4658  *
4659  * Removeq depends on the stream head ensuring that there are
4660  * no concurrent insertq or removeq on the same stream. The
4661  * stream head ensures this using the flags STWOPEN, STRCLOSE and
4662  * STRPLUMB.
4663  *
4664  * The set of locks needed to remove the queue is different in
4665  * different cases:
4666  *
4667  * Acquire sd_lock, sd_reflock, and all the syncq locks in the stream after
4668  * waiting for the syncq reference count to drop to 0 indicating that no
4669  * non-close threads are present anywhere in the stream. This ensures that any
4670  * module/driver can reference q_next in its open, close, put, or service
4671  * procedures.
4672  *
4673  * The sq_rmqcount counter tracks the number of threads inside removeq().
4674  * strlock() ensures that there is either no threads executing inside perimeter
4675  * or there is only a thread calling qprocsoff().
4676  *
4677  * strlock() compares the value of sq_count with the number of threads inside
4678  * removeq() and waits until sq_count is equal to sq_rmqcount. We need to wakeup
4679  * any threads waiting in strlock() when the sq_rmqcount increases.
4680  */
4681 
4682 void
4683 removeq(queue_t *qp)
4684 {
4685 	queue_t *wqp = _WR(qp);
4686 	struct stdata *stp = STREAM(qp);
4687 	sqlist_t *sqlist = NULL;
4688 	boolean_t isdriver;
4689 	int moved;
4690 	syncq_t *sq = qp->q_syncq;
4691 	syncq_t *wsq = wqp->q_syncq;
4692 
4693 	ASSERT(stp);
4694 
4695 	TRACE_2(TR_FAC_STREAMS_FR, TR_REMOVEQ,
4696 		"removeq:%p %p", qp, wqp);
4697 	ASSERT(qp->q_flag&QREADR);
4698 
4699 	/*
4700 	 * For queues using Synchronous streams, we must wait for all threads in
4701 	 * rwnext() to drain out before proceeding.
4702 	 */
4703 	if (qp->q_flag & QSYNCSTR) {
4704 		/* First, we need wakeup any threads blocked in rwnext() */
4705 		mutex_enter(SQLOCK(sq));
4706 		if (sq->sq_flags & SQ_WANTWAKEUP) {
4707 			sq->sq_flags &= ~SQ_WANTWAKEUP;
4708 			cv_broadcast(&sq->sq_wait);
4709 		}
4710 		mutex_exit(SQLOCK(sq));
4711 
4712 		if (wsq != sq) {
4713 			mutex_enter(SQLOCK(wsq));
4714 			if (wsq->sq_flags & SQ_WANTWAKEUP) {
4715 				wsq->sq_flags &= ~SQ_WANTWAKEUP;
4716 				cv_broadcast(&wsq->sq_wait);
4717 			}
4718 			mutex_exit(SQLOCK(wsq));
4719 		}
4720 
4721 		mutex_enter(QLOCK(qp));
4722 		while (qp->q_rwcnt > 0) {
4723 			qp->q_flag |= QWANTRMQSYNC;
4724 			cv_wait(&qp->q_wait, QLOCK(qp));
4725 		}
4726 		mutex_exit(QLOCK(qp));
4727 
4728 		mutex_enter(QLOCK(wqp));
4729 		while (wqp->q_rwcnt > 0) {
4730 			wqp->q_flag |= QWANTRMQSYNC;
4731 			cv_wait(&wqp->q_wait, QLOCK(wqp));
4732 		}
4733 		mutex_exit(QLOCK(wqp));
4734 	}
4735 
4736 	mutex_enter(SQLOCK(sq));
4737 	sq->sq_rmqcount++;
4738 	if (sq->sq_flags & SQ_WANTWAKEUP) {
4739 		sq->sq_flags &= ~SQ_WANTWAKEUP;
4740 		cv_broadcast(&sq->sq_wait);
4741 	}
4742 	mutex_exit(SQLOCK(sq));
4743 
4744 	isdriver = (qp->q_flag & QISDRV);
4745 
4746 	sqlist = sqlist_build(qp, stp, STRMATED(stp));
4747 	strlock(stp, sqlist);
4748 
4749 	reset_nfsrv_ptr(qp, wqp);
4750 
4751 	ASSERT(wqp->q_next == NULL || backq(qp)->q_next == qp);
4752 	ASSERT(qp->q_next == NULL || backq(wqp)->q_next == wqp);
4753 	/* Do we have a FIFO? */
4754 	if (wqp->q_next == qp) {
4755 		stp->sd_wrq->q_next = _RD(stp->sd_wrq);
4756 	} else {
4757 		if (wqp->q_next)
4758 			backq(qp)->q_next = qp->q_next;
4759 		if (qp->q_next)
4760 			backq(wqp)->q_next = wqp->q_next;
4761 	}
4762 
4763 	/* The QEND flag might have to be updated for the upstream guy */
4764 	if (qp->q_next)
4765 		set_qend(qp->q_next);
4766 
4767 	ASSERT(_SAMESTR(stp->sd_wrq) == O_SAMESTR(stp->sd_wrq));
4768 	ASSERT(_SAMESTR(_RD(stp->sd_wrq)) == O_SAMESTR(_RD(stp->sd_wrq)));
4769 
4770 	/*
4771 	 * Move any messages destined for the put procedures to the next
4772 	 * syncq in line. Otherwise free them.
4773 	 */
4774 	moved = 0;
4775 	/*
4776 	 * Quick check to see whether there are any messages or events.
4777 	 */
4778 	if (qp->q_syncqmsgs != 0 || (qp->q_syncq->sq_flags & SQ_EVENTS))
4779 		moved += propagate_syncq(qp);
4780 	if (wqp->q_syncqmsgs != 0 ||
4781 	    (wqp->q_syncq->sq_flags & SQ_EVENTS))
4782 		moved += propagate_syncq(wqp);
4783 
4784 	strsetuio(stp);
4785 
4786 	/*
4787 	 * If this was a module removal, decrement the push count.
4788 	 */
4789 	if (!isdriver)
4790 		stp->sd_pushcnt--;
4791 
4792 	strunlock(stp, sqlist);
4793 	sqlist_free(sqlist);
4794 
4795 	/*
4796 	 * Make sure any messages that were propagated are drained.
4797 	 * Also clear any QFULL bit caused by messages that were propagated.
4798 	 */
4799 
4800 	if (qp->q_next != NULL) {
4801 		clr_qfull(qp);
4802 		/*
4803 		 * For the driver calling qprocsoff, propagate_syncq
4804 		 * frees all the messages instead of putting it in
4805 		 * the stream head
4806 		 */
4807 		if (!isdriver && (moved > 0))
4808 			emptysq(qp->q_next->q_syncq);
4809 	}
4810 	if (wqp->q_next != NULL) {
4811 		clr_qfull(wqp);
4812 		/*
4813 		 * We come here for any pop of a module except for the
4814 		 * case of driver being removed. We don't call emptysq
4815 		 * if we did not move any messages. This will avoid holding
4816 		 * PERMOD syncq locks in emptysq
4817 		 */
4818 		if (moved > 0)
4819 			emptysq(wqp->q_next->q_syncq);
4820 	}
4821 
4822 	mutex_enter(SQLOCK(sq));
4823 	sq->sq_rmqcount--;
4824 	mutex_exit(SQLOCK(sq));
4825 }
4826 
4827 /*
4828  * Prevent further entry by setting a flag (like SQ_FROZEN, SQ_BLOCKED or
4829  * SQ_WRITER) on a syncq.
4830  * If maxcnt is not -1 it assumes that caller has "maxcnt" claim(s) on the
4831  * sync queue and waits until sq_count reaches maxcnt.
4832  *
4833  * if maxcnt is -1 there's no need to grab sq_putlocks since the caller
4834  * does not care about putnext threads that are in the middle of calling put
4835  * entry points.
4836  *
4837  * This routine is used for both inner and outer syncqs.
4838  */
4839 static void
4840 blocksq(syncq_t *sq, ushort_t flag, int maxcnt)
4841 {
4842 	uint16_t count = 0;
4843 
4844 	mutex_enter(SQLOCK(sq));
4845 	/*
4846 	 * Wait for SQ_FROZEN/SQ_BLOCKED to be reset.
4847 	 * SQ_FROZEN will be set if there is a frozen stream that has a
4848 	 * queue which also refers to this "shared" syncq.
4849 	 * SQ_BLOCKED will be set if there is "off" queue which also
4850 	 * refers to this "shared" syncq.
4851 	 */
4852 	if (maxcnt != -1) {
4853 		count = sq->sq_count;
4854 		SQ_PUTLOCKS_ENTER(sq);
4855 		SQ_PUTCOUNT_CLRFAST_LOCKED(sq);
4856 		SUM_SQ_PUTCOUNTS(sq, count);
4857 	}
4858 	sq->sq_needexcl++;
4859 	ASSERT(sq->sq_needexcl != 0);	/* wraparound */
4860 
4861 	while ((sq->sq_flags & flag) ||
4862 	    (maxcnt != -1 && count > (unsigned)maxcnt)) {
4863 		sq->sq_flags |= SQ_WANTWAKEUP;
4864 		if (maxcnt != -1) {
4865 			SQ_PUTLOCKS_EXIT(sq);
4866 		}
4867 		cv_wait(&sq->sq_wait, SQLOCK(sq));
4868 		if (maxcnt != -1) {
4869 			count = sq->sq_count;
4870 			SQ_PUTLOCKS_ENTER(sq);
4871 			SUM_SQ_PUTCOUNTS(sq, count);
4872 		}
4873 	}
4874 	sq->sq_needexcl--;
4875 	sq->sq_flags |= flag;
4876 	ASSERT(maxcnt == -1 || count == maxcnt);
4877 	if (maxcnt != -1) {
4878 		if (sq->sq_needexcl == 0) {
4879 			SQ_PUTCOUNT_SETFAST_LOCKED(sq);
4880 		}
4881 		SQ_PUTLOCKS_EXIT(sq);
4882 	} else if (sq->sq_needexcl == 0) {
4883 		SQ_PUTCOUNT_SETFAST(sq);
4884 	}
4885 
4886 	mutex_exit(SQLOCK(sq));
4887 }
4888 
4889 /*
4890  * Reset a flag that was set with blocksq.
4891  *
4892  * Can not use this routine to reset SQ_WRITER.
4893  *
4894  * If "isouter" is set then the syncq is assumed to be an outer perimeter
4895  * and drain_syncq is not called. Instead we rely on the qwriter_outer thread
4896  * to handle the queued qwriter operations.
4897  *
4898  * no need to grab sq_putlocks here. See comment in strsubr.h that explains when
4899  * sq_putlocks are used.
4900  */
4901 static void
4902 unblocksq(syncq_t *sq, uint16_t resetflag, int isouter)
4903 {
4904 	uint16_t flags;
4905 
4906 	mutex_enter(SQLOCK(sq));
4907 	ASSERT(resetflag != SQ_WRITER);
4908 	ASSERT(sq->sq_flags & resetflag);
4909 	flags = sq->sq_flags & ~resetflag;
4910 	sq->sq_flags = flags;
4911 	if (flags & (SQ_QUEUED | SQ_WANTWAKEUP)) {
4912 		if (flags & SQ_WANTWAKEUP) {
4913 			flags &= ~SQ_WANTWAKEUP;
4914 			cv_broadcast(&sq->sq_wait);
4915 		}
4916 		sq->sq_flags = flags;
4917 		if ((flags & SQ_QUEUED) && !(flags & (SQ_STAYAWAY|SQ_EXCL))) {
4918 			if (!isouter) {
4919 				/* drain_syncq drops SQLOCK */
4920 				drain_syncq(sq);
4921 				return;
4922 			}
4923 		}
4924 	}
4925 	mutex_exit(SQLOCK(sq));
4926 }
4927 
4928 /*
4929  * Reset a flag that was set with blocksq.
4930  * Does not drain the syncq. Use emptysq() for that.
4931  * Returns 1 if SQ_QUEUED is set. Otherwise 0.
4932  *
4933  * no need to grab sq_putlocks here. See comment in strsubr.h that explains when
4934  * sq_putlocks are used.
4935  */
4936 static int
4937 dropsq(syncq_t *sq, uint16_t resetflag)
4938 {
4939 	uint16_t flags;
4940 
4941 	mutex_enter(SQLOCK(sq));
4942 	ASSERT(sq->sq_flags & resetflag);
4943 	flags = sq->sq_flags & ~resetflag;
4944 	if (flags & SQ_WANTWAKEUP) {
4945 		flags &= ~SQ_WANTWAKEUP;
4946 		cv_broadcast(&sq->sq_wait);
4947 	}
4948 	sq->sq_flags = flags;
4949 	mutex_exit(SQLOCK(sq));
4950 	if (flags & SQ_QUEUED)
4951 		return (1);
4952 	return (0);
4953 }
4954 
4955 /*
4956  * Empty all the messages on a syncq.
4957  *
4958  * no need to grab sq_putlocks here. See comment in strsubr.h that explains when
4959  * sq_putlocks are used.
4960  */
4961 static void
4962 emptysq(syncq_t *sq)
4963 {
4964 	uint16_t flags;
4965 
4966 	mutex_enter(SQLOCK(sq));
4967 	flags = sq->sq_flags;
4968 	if ((flags & SQ_QUEUED) && !(flags & (SQ_STAYAWAY|SQ_EXCL))) {
4969 		/*
4970 		 * To prevent potential recursive invocation of drain_syncq we
4971 		 * do not call drain_syncq if count is non-zero.
4972 		 */
4973 		if (sq->sq_count == 0) {
4974 			/* drain_syncq() drops SQLOCK */
4975 			drain_syncq(sq);
4976 			return;
4977 		} else
4978 			sqenable(sq);
4979 	}
4980 	mutex_exit(SQLOCK(sq));
4981 }
4982 
4983 /*
4984  * Ordered insert while removing duplicates.
4985  */
4986 static void
4987 sqlist_insert(sqlist_t *sqlist, syncq_t *sqp)
4988 {
4989 	syncql_t *sqlp, **prev_sqlpp, *new_sqlp;
4990 
4991 	prev_sqlpp = &sqlist->sqlist_head;
4992 	while ((sqlp = *prev_sqlpp) != NULL) {
4993 		if (sqlp->sql_sq >= sqp) {
4994 			if (sqlp->sql_sq == sqp)	/* duplicate */
4995 				return;
4996 			break;
4997 		}
4998 		prev_sqlpp = &sqlp->sql_next;
4999 	}
5000 	new_sqlp = &sqlist->sqlist_array[sqlist->sqlist_index++];
5001 	ASSERT((char *)new_sqlp < (char *)sqlist + sqlist->sqlist_size);
5002 	new_sqlp->sql_next = sqlp;
5003 	new_sqlp->sql_sq = sqp;
5004 	*prev_sqlpp = new_sqlp;
5005 }
5006 
5007 /*
5008  * Walk the write side queues until we hit either the driver
5009  * or a twist in the stream (_SAMESTR will return false in both
5010  * these cases) then turn around and walk the read side queues
5011  * back up to the stream head.
5012  */
5013 static void
5014 sqlist_insertall(sqlist_t *sqlist, queue_t *q)
5015 {
5016 	while (q != NULL) {
5017 		sqlist_insert(sqlist, q->q_syncq);
5018 
5019 		if (_SAMESTR(q))
5020 			q = q->q_next;
5021 		else if (!(q->q_flag & QREADR))
5022 			q = _RD(q);
5023 		else
5024 			q = NULL;
5025 	}
5026 }
5027 
5028 /*
5029  * Allocate and build a list of all syncqs in a stream and the syncq(s)
5030  * associated with the "q" parameter. The resulting list is sorted in a
5031  * canonical order and is free of duplicates.
5032  * Assumes the passed queue is a _RD(q).
5033  */
5034 static sqlist_t *
5035 sqlist_build(queue_t *q, struct stdata *stp, boolean_t do_twist)
5036 {
5037 	sqlist_t *sqlist = sqlist_alloc(stp, KM_SLEEP);
5038 
5039 	/*
5040 	 * start with the current queue/qpair
5041 	 */
5042 	ASSERT(q->q_flag & QREADR);
5043 
5044 	sqlist_insert(sqlist, q->q_syncq);
5045 	sqlist_insert(sqlist, _WR(q)->q_syncq);
5046 
5047 	sqlist_insertall(sqlist, stp->sd_wrq);
5048 	if (do_twist)
5049 		sqlist_insertall(sqlist, stp->sd_mate->sd_wrq);
5050 
5051 	return (sqlist);
5052 }
5053 
5054 static sqlist_t *
5055 sqlist_alloc(struct stdata *stp, int kmflag)
5056 {
5057 	size_t sqlist_size;
5058 	sqlist_t *sqlist;
5059 
5060 	/*
5061 	 * Allocate 2 syncql_t's for each pushed module. Note that
5062 	 * the sqlist_t structure already has 4 syncql_t's built in:
5063 	 * 2 for the stream head, and 2 for the driver/other stream head.
5064 	 */
5065 	sqlist_size = 2 * sizeof (syncql_t) * stp->sd_pushcnt +
5066 		sizeof (sqlist_t);
5067 	if (STRMATED(stp))
5068 		sqlist_size += 2 * sizeof (syncql_t) * stp->sd_mate->sd_pushcnt;
5069 	sqlist = kmem_alloc(sqlist_size, kmflag);
5070 
5071 	sqlist->sqlist_head = NULL;
5072 	sqlist->sqlist_size = sqlist_size;
5073 	sqlist->sqlist_index = 0;
5074 
5075 	return (sqlist);
5076 }
5077 
5078 /*
5079  * Free the list created by sqlist_alloc()
5080  */
5081 static void
5082 sqlist_free(sqlist_t *sqlist)
5083 {
5084 	kmem_free(sqlist, sqlist->sqlist_size);
5085 }
5086 
5087 /*
5088  * Prevent any new entries into any syncq in this stream.
5089  * Used by freezestr.
5090  */
5091 void
5092 strblock(queue_t *q)
5093 {
5094 	struct stdata	*stp;
5095 	syncql_t	*sql;
5096 	sqlist_t	*sqlist;
5097 
5098 	q = _RD(q);
5099 
5100 	stp = STREAM(q);
5101 	ASSERT(stp != NULL);
5102 
5103 	/*
5104 	 * Get a sorted list with all the duplicates removed containing
5105 	 * all the syncqs referenced by this stream.
5106 	 */
5107 	sqlist = sqlist_build(q, stp, B_FALSE);
5108 	for (sql = sqlist->sqlist_head; sql != NULL; sql = sql->sql_next)
5109 		blocksq(sql->sql_sq, SQ_FROZEN, -1);
5110 	sqlist_free(sqlist);
5111 }
5112 
5113 /*
5114  * Release the block on new entries into this stream
5115  */
5116 void
5117 strunblock(queue_t *q)
5118 {
5119 	struct stdata	*stp;
5120 	syncql_t	*sql;
5121 	sqlist_t	*sqlist;
5122 	int		drain_needed;
5123 
5124 	q = _RD(q);
5125 
5126 	/*
5127 	 * Get a sorted list with all the duplicates removed containing
5128 	 * all the syncqs referenced by this stream.
5129 	 * Have to drop the SQ_FROZEN flag on all the syncqs before
5130 	 * starting to drain them; otherwise the draining might
5131 	 * cause a freezestr in some module on the stream (which
5132 	 * would deadlock.)
5133 	 */
5134 	stp = STREAM(q);
5135 	ASSERT(stp != NULL);
5136 	sqlist = sqlist_build(q, stp, B_FALSE);
5137 	drain_needed = 0;
5138 	for (sql = sqlist->sqlist_head; sql != NULL; sql = sql->sql_next)
5139 		drain_needed += dropsq(sql->sql_sq, SQ_FROZEN);
5140 	if (drain_needed) {
5141 		for (sql = sqlist->sqlist_head; sql != NULL;
5142 		    sql = sql->sql_next)
5143 			emptysq(sql->sql_sq);
5144 	}
5145 	sqlist_free(sqlist);
5146 }
5147 
5148 #ifdef DEBUG
5149 static int
5150 qprocsareon(queue_t *rq)
5151 {
5152 	if (rq->q_next == NULL)
5153 		return (0);
5154 	return (_WR(rq->q_next)->q_next == _WR(rq));
5155 }
5156 
5157 int
5158 qclaimed(queue_t *q)
5159 {
5160 	uint_t count;
5161 
5162 	count = q->q_syncq->sq_count;
5163 	SUM_SQ_PUTCOUNTS(q->q_syncq, count);
5164 	return (count != 0);
5165 }
5166 
5167 /*
5168  * Check if anyone has frozen this stream with freezestr
5169  */
5170 int
5171 frozenstr(queue_t *q)
5172 {
5173 	return ((q->q_syncq->sq_flags & SQ_FROZEN) != 0);
5174 }
5175 #endif /* DEBUG */
5176 
5177 /*
5178  * Enter a queue.
5179  * Obsoleted interface. Should not be used.
5180  */
5181 void
5182 enterq(queue_t *q)
5183 {
5184 	entersq(q->q_syncq, SQ_CALLBACK);
5185 }
5186 
5187 void
5188 leaveq(queue_t *q)
5189 {
5190 	leavesq(q->q_syncq, SQ_CALLBACK);
5191 }
5192 
5193 /*
5194  * Enter a perimeter. c_inner and c_outer specifies which concurrency bits
5195  * to check.
5196  * Wait if SQ_QUEUED is set to preserve ordering between messages and qwriter
5197  * calls and the running of open, close and service procedures.
5198  *
5199  * if c_inner bit is set no need to grab sq_putlocks since we don't care
5200  * if other threads have entered or are entering put entry point.
5201  *
5202  * if c_inner bit is set it might have been posible to use
5203  * sq_putlocks/sq_putcounts instead of SQLOCK/sq_count (e.g. to optimize
5204  * open/close path for IP) but since the count may need to be decremented in
5205  * qwait() we wouldn't know which counter to decrement. Currently counter is
5206  * selected by current cpu_seqid and current CPU can change at any moment. XXX
5207  * in the future we might use curthread id bits to select the counter and this
5208  * would stay constant across routine calls.
5209  */
5210 void
5211 entersq(syncq_t *sq, int entrypoint)
5212 {
5213 	uint16_t	count = 0;
5214 	uint16_t	flags;
5215 	uint16_t	waitflags = SQ_STAYAWAY | SQ_EVENTS | SQ_EXCL;
5216 	uint16_t	type;
5217 	uint_t		c_inner = entrypoint & SQ_CI;
5218 	uint_t		c_outer = entrypoint & SQ_CO;
5219 
5220 	/*
5221 	 * Increment ref count to keep closes out of this queue.
5222 	 */
5223 	ASSERT(sq);
5224 	ASSERT(c_inner && c_outer);
5225 	mutex_enter(SQLOCK(sq));
5226 	flags = sq->sq_flags;
5227 	type = sq->sq_type;
5228 	if (!(type & c_inner)) {
5229 		/* Make sure all putcounts now use slowlock. */
5230 		count = sq->sq_count;
5231 		SQ_PUTLOCKS_ENTER(sq);
5232 		SQ_PUTCOUNT_CLRFAST_LOCKED(sq);
5233 		SUM_SQ_PUTCOUNTS(sq, count);
5234 		sq->sq_needexcl++;
5235 		ASSERT(sq->sq_needexcl != 0);	/* wraparound */
5236 		waitflags |= SQ_MESSAGES;
5237 	}
5238 	/*
5239 	 * Wait until we can enter the inner perimeter.
5240 	 * If we want exclusive access we wait until sq_count is 0.
5241 	 * We have to do this before entering the outer perimeter in order
5242 	 * to preserve put/close message ordering.
5243 	 */
5244 	while ((flags & waitflags) || (!(type & c_inner) && count != 0)) {
5245 		sq->sq_flags = flags | SQ_WANTWAKEUP;
5246 		if (!(type & c_inner)) {
5247 			SQ_PUTLOCKS_EXIT(sq);
5248 		}
5249 		cv_wait(&sq->sq_wait, SQLOCK(sq));
5250 		if (!(type & c_inner)) {
5251 			count = sq->sq_count;
5252 			SQ_PUTLOCKS_ENTER(sq);
5253 			SUM_SQ_PUTCOUNTS(sq, count);
5254 		}
5255 		flags = sq->sq_flags;
5256 	}
5257 
5258 	if (!(type & c_inner)) {
5259 		ASSERT(sq->sq_needexcl > 0);
5260 		sq->sq_needexcl--;
5261 		if (sq->sq_needexcl == 0) {
5262 			SQ_PUTCOUNT_SETFAST_LOCKED(sq);
5263 		}
5264 	}
5265 
5266 	/* Check if we need to enter the outer perimeter */
5267 	if (!(type & c_outer)) {
5268 		/*
5269 		 * We have to enter the outer perimeter exclusively before
5270 		 * we can increment sq_count to avoid deadlock. This implies
5271 		 * that we have to re-check sq_flags and sq_count.
5272 		 *
5273 		 * is it possible to have c_inner set when c_outer is not set?
5274 		 */
5275 		if (!(type & c_inner)) {
5276 			SQ_PUTLOCKS_EXIT(sq);
5277 		}
5278 		mutex_exit(SQLOCK(sq));
5279 		outer_enter(sq->sq_outer, SQ_GOAWAY);
5280 		mutex_enter(SQLOCK(sq));
5281 		flags = sq->sq_flags;
5282 		/*
5283 		 * there should be no need to recheck sq_putcounts
5284 		 * because outer_enter() has already waited for them to clear
5285 		 * after setting SQ_WRITER.
5286 		 */
5287 		count = sq->sq_count;
5288 #ifdef DEBUG
5289 		/*
5290 		 * SUMCHECK_SQ_PUTCOUNTS should return the sum instead
5291 		 * of doing an ASSERT internally. Others should do
5292 		 * something like
5293 		 *	 ASSERT(SUMCHECK_SQ_PUTCOUNTS(sq) == 0);
5294 		 * without the need to #ifdef DEBUG it.
5295 		 */
5296 		SUMCHECK_SQ_PUTCOUNTS(sq, 0);
5297 #endif
5298 		while ((flags & (SQ_EXCL|SQ_BLOCKED|SQ_FROZEN)) ||
5299 		    (!(type & c_inner) && count != 0)) {
5300 			sq->sq_flags = flags | SQ_WANTWAKEUP;
5301 			cv_wait(&sq->sq_wait, SQLOCK(sq));
5302 			count = sq->sq_count;
5303 			flags = sq->sq_flags;
5304 		}
5305 	}
5306 
5307 	sq->sq_count++;
5308 	ASSERT(sq->sq_count != 0);	/* Wraparound */
5309 	if (!(type & c_inner)) {
5310 		/* Exclusive entry */
5311 		ASSERT(sq->sq_count == 1);
5312 		sq->sq_flags |= SQ_EXCL;
5313 		if (type & c_outer) {
5314 			SQ_PUTLOCKS_EXIT(sq);
5315 		}
5316 	}
5317 	mutex_exit(SQLOCK(sq));
5318 }
5319 
5320 /*
5321  * leave a syncq. announce to framework that closes may proceed.
5322  * c_inner and c_outer specifies which concurrency bits
5323  * to check.
5324  *
5325  * must never be called from driver or module put entry point.
5326  *
5327  * no need to grab sq_putlocks here. See comment in strsubr.h that explains when
5328  * sq_putlocks are used.
5329  */
5330 void
5331 leavesq(syncq_t *sq, int entrypoint)
5332 {
5333 	uint16_t	flags;
5334 	uint16_t	type;
5335 	uint_t		c_outer = entrypoint & SQ_CO;
5336 #ifdef DEBUG
5337 	uint_t		c_inner = entrypoint & SQ_CI;
5338 #endif
5339 
5340 	/*
5341 	 * decrement ref count, drain the syncq if possible, and wake up
5342 	 * any waiting close.
5343 	 */
5344 	ASSERT(sq);
5345 	ASSERT(c_inner && c_outer);
5346 	mutex_enter(SQLOCK(sq));
5347 	flags = sq->sq_flags;
5348 	type = sq->sq_type;
5349 	if (flags & (SQ_QUEUED|SQ_WANTWAKEUP|SQ_WANTEXWAKEUP)) {
5350 
5351 		if (flags & SQ_WANTWAKEUP) {
5352 			flags &= ~SQ_WANTWAKEUP;
5353 			cv_broadcast(&sq->sq_wait);
5354 		}
5355 		if (flags & SQ_WANTEXWAKEUP) {
5356 			flags &= ~SQ_WANTEXWAKEUP;
5357 			cv_broadcast(&sq->sq_exitwait);
5358 		}
5359 
5360 		if ((flags & SQ_QUEUED) && !(flags & SQ_STAYAWAY)) {
5361 			/*
5362 			 * The syncq needs to be drained. "Exit" the syncq
5363 			 * before calling drain_syncq.
5364 			 */
5365 			ASSERT(sq->sq_count != 0);
5366 			sq->sq_count--;
5367 			ASSERT((flags & SQ_EXCL) || (type & c_inner));
5368 			sq->sq_flags = flags & ~SQ_EXCL;
5369 			drain_syncq(sq);
5370 			ASSERT(MUTEX_NOT_HELD(SQLOCK(sq)));
5371 			/* Check if we need to exit the outer perimeter */
5372 			/* XXX will this ever be true? */
5373 			if (!(type & c_outer))
5374 				outer_exit(sq->sq_outer);
5375 			return;
5376 		}
5377 	}
5378 	ASSERT(sq->sq_count != 0);
5379 	sq->sq_count--;
5380 	ASSERT((flags & SQ_EXCL) || (type & c_inner));
5381 	sq->sq_flags = flags & ~SQ_EXCL;
5382 	mutex_exit(SQLOCK(sq));
5383 
5384 	/* Check if we need to exit the outer perimeter */
5385 	if (!(sq->sq_type & c_outer))
5386 		outer_exit(sq->sq_outer);
5387 }
5388 
5389 /*
5390  * Prevent q_next from changing in this stream by incrementing sq_count.
5391  *
5392  * no need to grab sq_putlocks here. See comment in strsubr.h that explains when
5393  * sq_putlocks are used.
5394  */
5395 void
5396 claimq(queue_t *qp)
5397 {
5398 	syncq_t	*sq = qp->q_syncq;
5399 
5400 	mutex_enter(SQLOCK(sq));
5401 	sq->sq_count++;
5402 	ASSERT(sq->sq_count != 0);	/* Wraparound */
5403 	mutex_exit(SQLOCK(sq));
5404 }
5405 
5406 /*
5407  * Undo claimq.
5408  *
5409  * no need to grab sq_putlocks here. See comment in strsubr.h that explains when
5410  * sq_putlocks are used.
5411  */
5412 void
5413 releaseq(queue_t *qp)
5414 {
5415 	syncq_t	*sq = qp->q_syncq;
5416 	uint16_t flags;
5417 
5418 	mutex_enter(SQLOCK(sq));
5419 	ASSERT(sq->sq_count > 0);
5420 	sq->sq_count--;
5421 
5422 	flags = sq->sq_flags;
5423 	if (flags & (SQ_WANTWAKEUP|SQ_QUEUED)) {
5424 		if (flags & SQ_WANTWAKEUP) {
5425 			flags &= ~SQ_WANTWAKEUP;
5426 			cv_broadcast(&sq->sq_wait);
5427 		}
5428 		sq->sq_flags = flags;
5429 		if ((flags & SQ_QUEUED) && !(flags & (SQ_STAYAWAY|SQ_EXCL))) {
5430 			/*
5431 			 * To prevent potential recursive invocation of
5432 			 * drain_syncq we do not call drain_syncq if count is
5433 			 * non-zero.
5434 			 */
5435 			if (sq->sq_count == 0) {
5436 				drain_syncq(sq);
5437 				return;
5438 			} else
5439 				sqenable(sq);
5440 		}
5441 	}
5442 	mutex_exit(SQLOCK(sq));
5443 }
5444 
5445 /*
5446  * Prevent q_next from changing in this stream by incrementing sd_refcnt.
5447  */
5448 void
5449 claimstr(queue_t *qp)
5450 {
5451 	struct stdata *stp = STREAM(qp);
5452 
5453 	mutex_enter(&stp->sd_reflock);
5454 	stp->sd_refcnt++;
5455 	ASSERT(stp->sd_refcnt != 0);	/* Wraparound */
5456 	mutex_exit(&stp->sd_reflock);
5457 }
5458 
5459 /*
5460  * Undo claimstr.
5461  */
5462 void
5463 releasestr(queue_t *qp)
5464 {
5465 	struct stdata *stp = STREAM(qp);
5466 
5467 	mutex_enter(&stp->sd_reflock);
5468 	ASSERT(stp->sd_refcnt != 0);
5469 	if (--stp->sd_refcnt == 0)
5470 		cv_broadcast(&stp->sd_refmonitor);
5471 	mutex_exit(&stp->sd_reflock);
5472 }
5473 
5474 static syncq_t *
5475 new_syncq(void)
5476 {
5477 	return (kmem_cache_alloc(syncq_cache, KM_SLEEP));
5478 }
5479 
5480 static void
5481 free_syncq(syncq_t *sq)
5482 {
5483 	ASSERT(sq->sq_head == NULL);
5484 	ASSERT(sq->sq_outer == NULL);
5485 	ASSERT(sq->sq_callbpend == NULL);
5486 	ASSERT((sq->sq_onext == NULL && sq->sq_oprev == NULL) ||
5487 	    (sq->sq_onext == sq && sq->sq_oprev == sq));
5488 
5489 	if (sq->sq_ciputctrl != NULL) {
5490 		ASSERT(sq->sq_nciputctrl == n_ciputctrl - 1);
5491 		SUMCHECK_CIPUTCTRL_COUNTS(sq->sq_ciputctrl,
5492 		    sq->sq_nciputctrl, 0);
5493 		ASSERT(ciputctrl_cache != NULL);
5494 		kmem_cache_free(ciputctrl_cache, sq->sq_ciputctrl);
5495 	}
5496 
5497 	sq->sq_tail = NULL;
5498 	sq->sq_evhead = NULL;
5499 	sq->sq_evtail = NULL;
5500 	sq->sq_ciputctrl = NULL;
5501 	sq->sq_nciputctrl = 0;
5502 	sq->sq_count = 0;
5503 	sq->sq_rmqcount = 0;
5504 	sq->sq_callbflags = 0;
5505 	sq->sq_cancelid = 0;
5506 	sq->sq_next = NULL;
5507 	sq->sq_needexcl = 0;
5508 	sq->sq_svcflags = 0;
5509 	sq->sq_nqueues = 0;
5510 	sq->sq_pri = 0;
5511 	sq->sq_onext = NULL;
5512 	sq->sq_oprev = NULL;
5513 	sq->sq_flags = 0;
5514 	sq->sq_type = 0;
5515 	sq->sq_servcount = 0;
5516 
5517 	kmem_cache_free(syncq_cache, sq);
5518 }
5519 
5520 /* Outer perimeter code */
5521 
5522 /*
5523  * The outer syncq uses the fields and flags in the syncq slightly
5524  * differently from the inner syncqs.
5525  *	sq_count	Incremented when there are pending or running
5526  *			writers at the outer perimeter to prevent the set of
5527  *			inner syncqs that belong to the outer perimeter from
5528  *			changing.
5529  *	sq_head/tail	List of deferred qwriter(OUTER) operations.
5530  *
5531  *	SQ_BLOCKED	Set to prevent traversing of sq_next,sq_prev while
5532  *			inner syncqs are added to or removed from the
5533  *			outer perimeter.
5534  *	SQ_QUEUED	sq_head/tail has messages or eventsqueued.
5535  *
5536  *	SQ_WRITER	A thread is currently traversing all the inner syncqs
5537  *			setting the SQ_WRITER flag.
5538  */
5539 
5540 /*
5541  * Get write access at the outer perimeter.
5542  * Note that read access is done by entersq, putnext, and put by simply
5543  * incrementing sq_count in the inner syncq.
5544  *
5545  * Waits until "flags" is no longer set in the outer to prevent multiple
5546  * threads from having write access at the same time. SQ_WRITER has to be part
5547  * of "flags".
5548  *
5549  * Increases sq_count on the outer syncq to keep away outer_insert/remove
5550  * until the outer_exit is finished.
5551  *
5552  * outer_enter is vulnerable to starvation since it does not prevent new
5553  * threads from entering the inner syncqs while it is waiting for sq_count to
5554  * go to zero.
5555  */
5556 void
5557 outer_enter(syncq_t *outer, uint16_t flags)
5558 {
5559 	syncq_t	*sq;
5560 	int	wait_needed;
5561 	uint16_t	count;
5562 
5563 	ASSERT(outer->sq_outer == NULL && outer->sq_onext != NULL &&
5564 	    outer->sq_oprev != NULL);
5565 	ASSERT(flags & SQ_WRITER);
5566 
5567 retry:
5568 	mutex_enter(SQLOCK(outer));
5569 	while (outer->sq_flags & flags) {
5570 		outer->sq_flags |= SQ_WANTWAKEUP;
5571 		cv_wait(&outer->sq_wait, SQLOCK(outer));
5572 	}
5573 
5574 	ASSERT(!(outer->sq_flags & SQ_WRITER));
5575 	outer->sq_flags |= SQ_WRITER;
5576 	outer->sq_count++;
5577 	ASSERT(outer->sq_count != 0);	/* wraparound */
5578 	wait_needed = 0;
5579 	/*
5580 	 * Set SQ_WRITER on all the inner syncqs while holding
5581 	 * the SQLOCK on the outer syncq. This ensures that the changing
5582 	 * of SQ_WRITER is atomic under the outer SQLOCK.
5583 	 */
5584 	for (sq = outer->sq_onext; sq != outer; sq = sq->sq_onext) {
5585 		mutex_enter(SQLOCK(sq));
5586 		count = sq->sq_count;
5587 		SQ_PUTLOCKS_ENTER(sq);
5588 		sq->sq_flags |= SQ_WRITER;
5589 		SUM_SQ_PUTCOUNTS(sq, count);
5590 		if (count != 0)
5591 			wait_needed = 1;
5592 		SQ_PUTLOCKS_EXIT(sq);
5593 		mutex_exit(SQLOCK(sq));
5594 	}
5595 	mutex_exit(SQLOCK(outer));
5596 
5597 	/*
5598 	 * Get everybody out of the syncqs sequentially.
5599 	 * Note that we don't actually need to aqiure the PUTLOCKS, since
5600 	 * we have already cleared the fastbit, and set QWRITER.  By
5601 	 * definition, the count can not increase since putnext will
5602 	 * take the slowlock path (and the purpose of aquiring the
5603 	 * putlocks was to make sure it didn't increase while we were
5604 	 * waiting).
5605 	 *
5606 	 * Note that we still aquire the PUTLOCKS to be safe.
5607 	 */
5608 	if (wait_needed) {
5609 		for (sq = outer->sq_onext; sq != outer; sq = sq->sq_onext) {
5610 			mutex_enter(SQLOCK(sq));
5611 			count = sq->sq_count;
5612 			SQ_PUTLOCKS_ENTER(sq);
5613 			SUM_SQ_PUTCOUNTS(sq, count);
5614 			while (count != 0) {
5615 				sq->sq_flags |= SQ_WANTWAKEUP;
5616 				SQ_PUTLOCKS_EXIT(sq);
5617 				cv_wait(&sq->sq_wait, SQLOCK(sq));
5618 				count = sq->sq_count;
5619 				SQ_PUTLOCKS_ENTER(sq);
5620 				SUM_SQ_PUTCOUNTS(sq, count);
5621 			}
5622 			SQ_PUTLOCKS_EXIT(sq);
5623 			mutex_exit(SQLOCK(sq));
5624 		}
5625 		/*
5626 		 * Verify that none of the flags got set while we
5627 		 * were waiting for the sq_counts to drop.
5628 		 * If this happens we exit and retry entering the
5629 		 * outer perimeter.
5630 		 */
5631 		mutex_enter(SQLOCK(outer));
5632 		if (outer->sq_flags & (flags & ~SQ_WRITER)) {
5633 			mutex_exit(SQLOCK(outer));
5634 			outer_exit(outer);
5635 			goto retry;
5636 		}
5637 		mutex_exit(SQLOCK(outer));
5638 	}
5639 }
5640 
5641 /*
5642  * Drop the write access at the outer perimeter.
5643  * Read access is dropped implicitly (by putnext, put, and leavesq) by
5644  * decrementing sq_count.
5645  */
5646 void
5647 outer_exit(syncq_t *outer)
5648 {
5649 	syncq_t	*sq;
5650 	int	 drain_needed;
5651 	uint16_t flags;
5652 
5653 	ASSERT(outer->sq_outer == NULL && outer->sq_onext != NULL &&
5654 	    outer->sq_oprev != NULL);
5655 	ASSERT(MUTEX_NOT_HELD(SQLOCK(outer)));
5656 
5657 	/*
5658 	 * Atomically (from the perspective of threads calling become_writer)
5659 	 * drop the write access at the outer perimeter by holding
5660 	 * SQLOCK(outer) across all the dropsq calls and the resetting of
5661 	 * SQ_WRITER.
5662 	 * This defines a locking order between the outer perimeter
5663 	 * SQLOCK and the inner perimeter SQLOCKs.
5664 	 */
5665 	mutex_enter(SQLOCK(outer));
5666 	flags = outer->sq_flags;
5667 	ASSERT(outer->sq_flags & SQ_WRITER);
5668 	if (flags & SQ_QUEUED) {
5669 		write_now(outer);
5670 		flags = outer->sq_flags;
5671 	}
5672 
5673 	/*
5674 	 * sq_onext is stable since sq_count has not yet been decreased.
5675 	 * Reset the SQ_WRITER flags in all syncqs.
5676 	 * After dropping SQ_WRITER on the outer syncq we empty all the
5677 	 * inner syncqs.
5678 	 */
5679 	drain_needed = 0;
5680 	for (sq = outer->sq_onext; sq != outer; sq = sq->sq_onext)
5681 		drain_needed += dropsq(sq, SQ_WRITER);
5682 	ASSERT(!(outer->sq_flags & SQ_QUEUED));
5683 	flags &= ~SQ_WRITER;
5684 	if (drain_needed) {
5685 		outer->sq_flags = flags;
5686 		mutex_exit(SQLOCK(outer));
5687 		for (sq = outer->sq_onext; sq != outer; sq = sq->sq_onext)
5688 			emptysq(sq);
5689 		mutex_enter(SQLOCK(outer));
5690 		flags = outer->sq_flags;
5691 	}
5692 	if (flags & SQ_WANTWAKEUP) {
5693 		flags &= ~SQ_WANTWAKEUP;
5694 		cv_broadcast(&outer->sq_wait);
5695 	}
5696 	outer->sq_flags = flags;
5697 	ASSERT(outer->sq_count > 0);
5698 	outer->sq_count--;
5699 	mutex_exit(SQLOCK(outer));
5700 }
5701 
5702 /*
5703  * Add another syncq to an outer perimeter.
5704  * Block out all other access to the outer perimeter while it is being
5705  * changed using blocksq.
5706  * Assumes that the caller has *not* done an outer_enter.
5707  *
5708  * Vulnerable to starvation in blocksq.
5709  */
5710 static void
5711 outer_insert(syncq_t *outer, syncq_t *sq)
5712 {
5713 	ASSERT(outer->sq_outer == NULL && outer->sq_onext != NULL &&
5714 	    outer->sq_oprev != NULL);
5715 	ASSERT(sq->sq_outer == NULL && sq->sq_onext == NULL &&
5716 	    sq->sq_oprev == NULL);	/* Can't be in an outer perimeter */
5717 
5718 	/* Get exclusive access to the outer perimeter list */
5719 	blocksq(outer, SQ_BLOCKED, 0);
5720 	ASSERT(outer->sq_flags & SQ_BLOCKED);
5721 	ASSERT(!(outer->sq_flags & SQ_WRITER));
5722 
5723 	mutex_enter(SQLOCK(sq));
5724 	sq->sq_outer = outer;
5725 	outer->sq_onext->sq_oprev = sq;
5726 	sq->sq_onext = outer->sq_onext;
5727 	outer->sq_onext = sq;
5728 	sq->sq_oprev = outer;
5729 	mutex_exit(SQLOCK(sq));
5730 	unblocksq(outer, SQ_BLOCKED, 1);
5731 }
5732 
5733 /*
5734  * Remove a syncq from an outer perimeter.
5735  * Block out all other access to the outer perimeter while it is being
5736  * changed using blocksq.
5737  * Assumes that the caller has *not* done an outer_enter.
5738  *
5739  * Vulnerable to starvation in blocksq.
5740  */
5741 static void
5742 outer_remove(syncq_t *outer, syncq_t *sq)
5743 {
5744 	ASSERT(outer->sq_outer == NULL && outer->sq_onext != NULL &&
5745 	    outer->sq_oprev != NULL);
5746 	ASSERT(sq->sq_outer == outer);
5747 
5748 	/* Get exclusive access to the outer perimeter list */
5749 	blocksq(outer, SQ_BLOCKED, 0);
5750 	ASSERT(outer->sq_flags & SQ_BLOCKED);
5751 	ASSERT(!(outer->sq_flags & SQ_WRITER));
5752 
5753 	mutex_enter(SQLOCK(sq));
5754 	sq->sq_outer = NULL;
5755 	sq->sq_onext->sq_oprev = sq->sq_oprev;
5756 	sq->sq_oprev->sq_onext = sq->sq_onext;
5757 	sq->sq_oprev = sq->sq_onext = NULL;
5758 	mutex_exit(SQLOCK(sq));
5759 	unblocksq(outer, SQ_BLOCKED, 1);
5760 }
5761 
5762 /*
5763  * Queue a deferred qwriter(OUTER) callback for this outer perimeter.
5764  * If this is the first callback for this outer perimeter then add
5765  * this outer perimeter to the list of outer perimeters that
5766  * the qwriter_outer_thread will process.
5767  *
5768  * Increments sq_count in the outer syncq to prevent the membership
5769  * of the outer perimeter (in terms of inner syncqs) to change while
5770  * the callback is pending.
5771  */
5772 static void
5773 queue_writer(syncq_t *outer, void (*func)(), queue_t *q, mblk_t *mp)
5774 {
5775 	ASSERT(MUTEX_HELD(SQLOCK(outer)));
5776 
5777 	mp->b_prev = (mblk_t *)func;
5778 	mp->b_queue = q;
5779 	mp->b_next = NULL;
5780 	outer->sq_count++;	/* Decremented when dequeued */
5781 	ASSERT(outer->sq_count != 0);	/* Wraparound */
5782 	if (outer->sq_evhead == NULL) {
5783 		/* First message. */
5784 		outer->sq_evhead = outer->sq_evtail = mp;
5785 		outer->sq_flags |= SQ_EVENTS;
5786 		mutex_exit(SQLOCK(outer));
5787 		STRSTAT(qwr_outer);
5788 		(void) taskq_dispatch(streams_taskq,
5789 		    (task_func_t *)qwriter_outer_service, outer, TQ_SLEEP);
5790 	} else {
5791 		ASSERT(outer->sq_flags & SQ_EVENTS);
5792 		outer->sq_evtail->b_next = mp;
5793 		outer->sq_evtail = mp;
5794 		mutex_exit(SQLOCK(outer));
5795 	}
5796 }
5797 
5798 /*
5799  * Try and upgrade to write access at the outer perimeter. If this can
5800  * not be done without blocking then queue the callback to be done
5801  * by the qwriter_outer_thread.
5802  *
5803  * This routine can only be called from put or service procedures plus
5804  * asynchronous callback routines that have properly entered to
5805  * queue (with entersq.) Thus qwriter(OUTER) assumes the caller has one claim
5806  * on the syncq associated with q.
5807  */
5808 void
5809 qwriter_outer(queue_t *q, mblk_t *mp, void (*func)())
5810 {
5811 	syncq_t	*osq, *sq, *outer;
5812 	int	failed;
5813 	uint16_t flags;
5814 
5815 	osq = q->q_syncq;
5816 	outer = osq->sq_outer;
5817 	if (outer == NULL)
5818 		panic("qwriter(PERIM_OUTER): no outer perimeter");
5819 	ASSERT(outer->sq_outer == NULL && outer->sq_onext != NULL &&
5820 	    outer->sq_oprev != NULL);
5821 
5822 	mutex_enter(SQLOCK(outer));
5823 	flags = outer->sq_flags;
5824 	/*
5825 	 * If some thread is traversing sq_next, or if we are blocked by
5826 	 * outer_insert or outer_remove, or if the we already have queued
5827 	 * callbacks, then queue this callback for later processing.
5828 	 *
5829 	 * Also queue the qwriter for an interrupt thread in order
5830 	 * to reduce the time spent running at high IPL.
5831 	 * to identify there are events.
5832 	 */
5833 	if ((flags & SQ_GOAWAY) || (curthread->t_pri >= kpreemptpri)) {
5834 		/*
5835 		 * Queue the become_writer request.
5836 		 * The queueing is atomic under SQLOCK(outer) in order
5837 		 * to synchronize with outer_exit.
5838 		 * queue_writer will drop the outer SQLOCK
5839 		 */
5840 		if (flags & SQ_BLOCKED) {
5841 			/* Must set SQ_WRITER on inner perimeter */
5842 			mutex_enter(SQLOCK(osq));
5843 			osq->sq_flags |= SQ_WRITER;
5844 			mutex_exit(SQLOCK(osq));
5845 		} else {
5846 			if (!(flags & SQ_WRITER)) {
5847 				/*
5848 				 * The outer could have been SQ_BLOCKED thus
5849 				 * SQ_WRITER might not be set on the inner.
5850 				 */
5851 				mutex_enter(SQLOCK(osq));
5852 				osq->sq_flags |= SQ_WRITER;
5853 				mutex_exit(SQLOCK(osq));
5854 			}
5855 			ASSERT(osq->sq_flags & SQ_WRITER);
5856 		}
5857 		queue_writer(outer, func, q, mp);
5858 		return;
5859 	}
5860 	/*
5861 	 * We are half-way to exclusive access to the outer perimeter.
5862 	 * Prevent any outer_enter, qwriter(OUTER), or outer_insert/remove
5863 	 * while the inner syncqs are traversed.
5864 	 */
5865 	outer->sq_count++;
5866 	ASSERT(outer->sq_count != 0);	/* wraparound */
5867 	flags |= SQ_WRITER;
5868 	/*
5869 	 * Check if we can run the function immediately. Mark all
5870 	 * syncqs with the writer flag to prevent new entries into
5871 	 * put and service procedures.
5872 	 *
5873 	 * Set SQ_WRITER on all the inner syncqs while holding
5874 	 * the SQLOCK on the outer syncq. This ensures that the changing
5875 	 * of SQ_WRITER is atomic under the outer SQLOCK.
5876 	 */
5877 	failed = 0;
5878 	for (sq = outer->sq_onext; sq != outer; sq = sq->sq_onext) {
5879 		uint16_t count;
5880 		uint_t	maxcnt = (sq == osq) ? 1 : 0;
5881 
5882 		mutex_enter(SQLOCK(sq));
5883 		count = sq->sq_count;
5884 		SQ_PUTLOCKS_ENTER(sq);
5885 		SUM_SQ_PUTCOUNTS(sq, count);
5886 		if (sq->sq_count > maxcnt)
5887 			failed = 1;
5888 		sq->sq_flags |= SQ_WRITER;
5889 		SQ_PUTLOCKS_EXIT(sq);
5890 		mutex_exit(SQLOCK(sq));
5891 	}
5892 	if (failed) {
5893 		/*
5894 		 * Some other thread has a read claim on the outer perimeter.
5895 		 * Queue the callback for deferred processing.
5896 		 *
5897 		 * queue_writer will set SQ_QUEUED before we drop SQ_WRITER
5898 		 * so that other qwriter(OUTER) calls will queue their
5899 		 * callbacks as well. queue_writer increments sq_count so we
5900 		 * decrement to compensate for the our increment.
5901 		 *
5902 		 * Dropping SQ_WRITER enables the writer thread to work
5903 		 * on this outer perimeter.
5904 		 */
5905 		outer->sq_flags = flags;
5906 		queue_writer(outer, func, q, mp);
5907 		/* queue_writer dropper the lock */
5908 		mutex_enter(SQLOCK(outer));
5909 		ASSERT(outer->sq_count > 0);
5910 		outer->sq_count--;
5911 		ASSERT(outer->sq_flags & SQ_WRITER);
5912 		flags = outer->sq_flags;
5913 		flags &= ~SQ_WRITER;
5914 		if (flags & SQ_WANTWAKEUP) {
5915 			flags &= ~SQ_WANTWAKEUP;
5916 			cv_broadcast(&outer->sq_wait);
5917 		}
5918 		outer->sq_flags = flags;
5919 		mutex_exit(SQLOCK(outer));
5920 		return;
5921 	} else {
5922 		outer->sq_flags = flags;
5923 		mutex_exit(SQLOCK(outer));
5924 	}
5925 
5926 	/* Can run it immediately */
5927 	(*func)(q, mp);
5928 
5929 	outer_exit(outer);
5930 }
5931 
5932 /*
5933  * Dequeue all writer callbacks from the outer perimeter and run them.
5934  */
5935 static void
5936 write_now(syncq_t *outer)
5937 {
5938 	mblk_t		*mp;
5939 	queue_t		*q;
5940 	void	(*func)();
5941 
5942 	ASSERT(MUTEX_HELD(SQLOCK(outer)));
5943 	ASSERT(outer->sq_outer == NULL && outer->sq_onext != NULL &&
5944 	    outer->sq_oprev != NULL);
5945 	while ((mp = outer->sq_evhead) != NULL) {
5946 		/*
5947 		 * queues cannot be placed on the queuelist on the outer
5948 		 * perimiter.
5949 		 */
5950 		ASSERT(!(outer->sq_flags & SQ_MESSAGES));
5951 		ASSERT((outer->sq_flags & SQ_EVENTS));
5952 
5953 		outer->sq_evhead = mp->b_next;
5954 		if (outer->sq_evhead == NULL) {
5955 			outer->sq_evtail = NULL;
5956 			outer->sq_flags &= ~SQ_EVENTS;
5957 		}
5958 		ASSERT(outer->sq_count != 0);
5959 		outer->sq_count--;	/* Incremented when enqueued. */
5960 		mutex_exit(SQLOCK(outer));
5961 		/*
5962 		 * Drop the message if the queue is closing.
5963 		 * Make sure that the queue is "claimed" when the callback
5964 		 * is run in order to satisfy various ASSERTs.
5965 		 */
5966 		q = mp->b_queue;
5967 		func = (void (*)())mp->b_prev;
5968 		ASSERT(func != NULL);
5969 		mp->b_next = mp->b_prev = NULL;
5970 		if (q->q_flag & QWCLOSE) {
5971 			freemsg(mp);
5972 		} else {
5973 			claimq(q);
5974 			(*func)(q, mp);
5975 			releaseq(q);
5976 		}
5977 		mutex_enter(SQLOCK(outer));
5978 	}
5979 	ASSERT(MUTEX_HELD(SQLOCK(outer)));
5980 }
5981 
5982 /*
5983  * The list of messages on the inner syncq is effectively hashed
5984  * by destination queue.  These destination queues are doubly
5985  * linked lists (hopefully) in priority order.  Messages are then
5986  * put on the queue referenced by the q_sqhead/q_sqtail elements.
5987  * Additional messages are linked together by the b_next/b_prev
5988  * elements in the mblk, with (similar to putq()) the first message
5989  * having a NULL b_prev and the last message having a NULL b_next.
5990  *
5991  * Events, such as qwriter callbacks, are put onto a list in FIFO
5992  * order referenced by sq_evhead, and sq_evtail.  This is a singly
5993  * linked list, and messages here MUST be processed in the order queued.
5994  */
5995 
5996 /*
5997  * Run the events on the syncq event list (sq_evhead).
5998  * Assumes there is only one claim on the syncq, it is
5999  * already exclusive (SQ_EXCL set), and the SQLOCK held.
6000  * Messages here are processed in order, with the SQ_EXCL bit
6001  * held all the way through till the last message is processed.
6002  */
6003 void
6004 sq_run_events(syncq_t *sq)
6005 {
6006 	mblk_t		*bp;
6007 	queue_t		*qp;
6008 	uint16_t	flags = sq->sq_flags;
6009 	void		(*func)();
6010 
6011 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
6012 	ASSERT((sq->sq_outer == NULL && sq->sq_onext == NULL &&
6013 		sq->sq_oprev == NULL) ||
6014 		(sq->sq_outer != NULL && sq->sq_onext != NULL &&
6015 		sq->sq_oprev != NULL));
6016 
6017 	ASSERT(flags & SQ_EXCL);
6018 	ASSERT(sq->sq_count == 1);
6019 
6020 	/*
6021 	 * We need to process all of the events on this list.  It
6022 	 * is possible that new events will be added while we are
6023 	 * away processing a callback, so on every loop, we start
6024 	 * back at the beginning of the list.
6025 	 */
6026 	/*
6027 	 * We have to reaccess sq_evhead since there is a
6028 	 * possibility of a new entry while we were running
6029 	 * the callback.
6030 	 */
6031 	for (bp = sq->sq_evhead; bp != NULL; bp = sq->sq_evhead) {
6032 		ASSERT(bp->b_queue->q_syncq == sq);
6033 		ASSERT(sq->sq_flags & SQ_EVENTS);
6034 
6035 		qp = bp->b_queue;
6036 		func = (void (*)())bp->b_prev;
6037 		ASSERT(func != NULL);
6038 
6039 		/*
6040 		 * Messages from the event queue must be taken off in
6041 		 * FIFO order.
6042 		 */
6043 		ASSERT(sq->sq_evhead == bp);
6044 		sq->sq_evhead = bp->b_next;
6045 
6046 		if (bp->b_next == NULL) {
6047 			/* Deleting last */
6048 			ASSERT(sq->sq_evtail == bp);
6049 			sq->sq_evtail = NULL;
6050 			sq->sq_flags &= ~SQ_EVENTS;
6051 		}
6052 		bp->b_prev = bp->b_next = NULL;
6053 		ASSERT(bp->b_datap->db_ref != 0);
6054 
6055 		mutex_exit(SQLOCK(sq));
6056 
6057 		(*func)(qp, bp);
6058 
6059 		mutex_enter(SQLOCK(sq));
6060 		/*
6061 		 * re-read the flags, since they could have changed.
6062 		 */
6063 		flags = sq->sq_flags;
6064 		ASSERT(flags & SQ_EXCL);
6065 	}
6066 	ASSERT(sq->sq_evhead == NULL && sq->sq_evtail == NULL);
6067 	ASSERT(!(sq->sq_flags & SQ_EVENTS));
6068 
6069 	if (flags & SQ_WANTWAKEUP) {
6070 		flags &= ~SQ_WANTWAKEUP;
6071 		cv_broadcast(&sq->sq_wait);
6072 	}
6073 	if (flags & SQ_WANTEXWAKEUP) {
6074 		flags &= ~SQ_WANTEXWAKEUP;
6075 		cv_broadcast(&sq->sq_exitwait);
6076 	}
6077 	sq->sq_flags = flags;
6078 }
6079 
6080 /*
6081  * Put messages on the event list.
6082  * If we can go exclusive now, do so and process the event list, otherwise
6083  * let the last claim service this list (or wake the sqthread).
6084  * This procedure assumes SQLOCK is held.  To run the event list, it
6085  * must be called with no claims.
6086  */
6087 static void
6088 sqfill_events(syncq_t *sq, queue_t *q, mblk_t *mp, void (*func)())
6089 {
6090 	uint16_t count;
6091 
6092 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
6093 	ASSERT(func != NULL);
6094 
6095 	/*
6096 	 * This is a callback.  Add it to the list of callbacks
6097 	 * and see about upgrading.
6098 	 */
6099 	mp->b_prev = (mblk_t *)func;
6100 	mp->b_queue = q;
6101 	mp->b_next = NULL;
6102 	if (sq->sq_evhead == NULL) {
6103 		sq->sq_evhead = sq->sq_evtail = mp;
6104 		sq->sq_flags |= SQ_EVENTS;
6105 	} else {
6106 		ASSERT(sq->sq_evtail != NULL);
6107 		ASSERT(sq->sq_evtail->b_next == NULL);
6108 		ASSERT(sq->sq_flags & SQ_EVENTS);
6109 		sq->sq_evtail->b_next = mp;
6110 		sq->sq_evtail = mp;
6111 	}
6112 	/*
6113 	 * We have set SQ_EVENTS, so threads will have to
6114 	 * unwind out of the perimiter, and new entries will
6115 	 * not grab a putlock.  But we still need to know
6116 	 * how many threads have already made a claim to the
6117 	 * syncq, so grab the putlocks, and sum the counts.
6118 	 * If there are no claims on the syncq, we can upgrade
6119 	 * to exclusive, and run the event list.
6120 	 * NOTE: We hold the SQLOCK, so we can just grab the
6121 	 * putlocks.
6122 	 */
6123 	count = sq->sq_count;
6124 	SQ_PUTLOCKS_ENTER(sq);
6125 	SUM_SQ_PUTCOUNTS(sq, count);
6126 	/*
6127 	 * We have no claim, so we need to check if there
6128 	 * are no others, then we can upgrade.
6129 	 */
6130 	/*
6131 	 * There are currently no claims on
6132 	 * the syncq by this thread (at least on this entry). The thread who has
6133 	 * the claim should drain syncq.
6134 	 */
6135 	if (count > 0) {
6136 		/*
6137 		 * Can't upgrade - other threads inside.
6138 		 */
6139 		SQ_PUTLOCKS_EXIT(sq);
6140 		mutex_exit(SQLOCK(sq));
6141 		return;
6142 	}
6143 	/*
6144 	 * Need to set SQ_EXCL and make a claim on the syncq.
6145 	 */
6146 	ASSERT((sq->sq_flags & SQ_EXCL) == 0);
6147 	sq->sq_flags |= SQ_EXCL;
6148 	ASSERT(sq->sq_count == 0);
6149 	sq->sq_count++;
6150 	SQ_PUTLOCKS_EXIT(sq);
6151 
6152 	/* Process the events list */
6153 	sq_run_events(sq);
6154 
6155 	/*
6156 	 * Release our claim...
6157 	 */
6158 	sq->sq_count--;
6159 
6160 	/*
6161 	 * And release SQ_EXCL.
6162 	 * We don't need to acquire the putlocks to release
6163 	 * SQ_EXCL, since we are exclusive, and hold the SQLOCK.
6164 	 */
6165 	sq->sq_flags &= ~SQ_EXCL;
6166 
6167 	/*
6168 	 * sq_run_events should have released SQ_EXCL
6169 	 */
6170 	ASSERT(!(sq->sq_flags & SQ_EXCL));
6171 
6172 	/*
6173 	 * If anything happened while we were running the
6174 	 * events (or was there before), we need to process
6175 	 * them now.  We shouldn't be exclusive sine we
6176 	 * released the perimiter above (plus, we asserted
6177 	 * for it).
6178 	 */
6179 	if (!(sq->sq_flags & SQ_STAYAWAY) && (sq->sq_flags & SQ_QUEUED))
6180 		drain_syncq(sq);
6181 	else
6182 		mutex_exit(SQLOCK(sq));
6183 }
6184 
6185 /*
6186  * Perform delayed processing. The caller has to make sure that it is safe
6187  * to enter the syncq (e.g. by checking that none of the SQ_STAYAWAY bits are
6188  * set.)
6189  *
6190  * Assume that the caller has NO claims on the syncq.  However, a claim
6191  * on the syncq does not indicate that a thread is draining the syncq.
6192  * There may be more claims on the syncq than there are threads draining
6193  * (i.e.  #_threads_draining <= sq_count)
6194  *
6195  * drain_syncq has to terminate when one of the SQ_STAYAWAY bits gets set
6196  * in order to preserve qwriter(OUTER) ordering constraints.
6197  *
6198  * sq_putcount only needs to be checked when dispatching the queued
6199  * writer call for CIPUT sync queue, but this is handled in sq_run_events.
6200  */
6201 void
6202 drain_syncq(syncq_t *sq)
6203 {
6204 	queue_t		*qp;
6205 	uint16_t	count;
6206 	uint16_t	type = sq->sq_type;
6207 	uint16_t	flags = sq->sq_flags;
6208 	boolean_t	bg_service = sq->sq_svcflags & SQ_SERVICE;
6209 
6210 	TRACE_1(TR_FAC_STREAMS_FR, TR_DRAIN_SYNCQ_START,
6211 		"drain_syncq start:%p", sq);
6212 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
6213 	ASSERT((sq->sq_outer == NULL && sq->sq_onext == NULL &&
6214 		sq->sq_oprev == NULL) ||
6215 		(sq->sq_outer != NULL && sq->sq_onext != NULL &&
6216 		sq->sq_oprev != NULL));
6217 
6218 	/*
6219 	 * Drop SQ_SERVICE flag.
6220 	 */
6221 	if (bg_service)
6222 		sq->sq_svcflags &= ~SQ_SERVICE;
6223 
6224 	/*
6225 	 * If SQ_EXCL is set, someone else is processing this syncq - let him
6226 	 * finish the job.
6227 	 */
6228 	if (flags & SQ_EXCL) {
6229 		if (bg_service) {
6230 			ASSERT(sq->sq_servcount != 0);
6231 			sq->sq_servcount--;
6232 		}
6233 		mutex_exit(SQLOCK(sq));
6234 		return;
6235 	}
6236 
6237 	/*
6238 	 * This routine can be called by a background thread if
6239 	 * it was scheduled by a hi-priority thread.  SO, if there are
6240 	 * NOT messages queued, return (remember, we have the SQLOCK,
6241 	 * and it cannot change until we release it). Wakeup any waiters also.
6242 	 */
6243 	if (!(flags & SQ_QUEUED)) {
6244 		if (flags & SQ_WANTWAKEUP) {
6245 			flags &= ~SQ_WANTWAKEUP;
6246 			cv_broadcast(&sq->sq_wait);
6247 		}
6248 		if (flags & SQ_WANTEXWAKEUP) {
6249 			flags &= ~SQ_WANTEXWAKEUP;
6250 			cv_broadcast(&sq->sq_exitwait);
6251 		}
6252 		sq->sq_flags = flags;
6253 		if (bg_service) {
6254 			ASSERT(sq->sq_servcount != 0);
6255 			sq->sq_servcount--;
6256 		}
6257 		mutex_exit(SQLOCK(sq));
6258 		return;
6259 	}
6260 
6261 	/*
6262 	 * If this is not a concurrent put perimiter, we need to
6263 	 * become exclusive to drain.  Also, if not CIPUT, we would
6264 	 * not have acquired a putlock, so we don't need to check
6265 	 * the putcounts.  If not entering with a claim, we test
6266 	 * for sq_count == 0.
6267 	 */
6268 	type = sq->sq_type;
6269 	if (!(type & SQ_CIPUT)) {
6270 		if (sq->sq_count > 1) {
6271 			if (bg_service) {
6272 				ASSERT(sq->sq_servcount != 0);
6273 				sq->sq_servcount--;
6274 			}
6275 			mutex_exit(SQLOCK(sq));
6276 			return;
6277 		}
6278 		sq->sq_flags |= SQ_EXCL;
6279 	}
6280 
6281 	/*
6282 	 * This is where we make a claim to the syncq.
6283 	 * This can either be done by incrementing a putlock, or
6284 	 * the sq_count.  But since we already have the SQLOCK
6285 	 * here, we just bump the sq_count.
6286 	 *
6287 	 * Note that after we make a claim, we need to let the code
6288 	 * fall through to the end of this routine to clean itself
6289 	 * up.  A return in the while loop will put the syncq in a
6290 	 * very bad state.
6291 	 */
6292 	sq->sq_count++;
6293 	ASSERT(sq->sq_count != 0);	/* wraparound */
6294 
6295 	while ((flags = sq->sq_flags) & SQ_QUEUED) {
6296 		/*
6297 		 * If we are told to stayaway or went exclusive,
6298 		 * we are done.
6299 		 */
6300 		if (flags & (SQ_STAYAWAY)) {
6301 			break;
6302 		}
6303 
6304 		/*
6305 		 * If there are events to run, do so.
6306 		 * We have one claim to the syncq, so if there are
6307 		 * more than one, other threads are running.
6308 		 */
6309 		if (sq->sq_evhead != NULL) {
6310 			ASSERT(sq->sq_flags & SQ_EVENTS);
6311 
6312 			count = sq->sq_count;
6313 			SQ_PUTLOCKS_ENTER(sq);
6314 			SUM_SQ_PUTCOUNTS(sq, count);
6315 			if (count > 1) {
6316 				SQ_PUTLOCKS_EXIT(sq);
6317 				/* Can't upgrade - other threads inside */
6318 				break;
6319 			}
6320 			ASSERT((flags & SQ_EXCL) == 0);
6321 			sq->sq_flags = flags | SQ_EXCL;
6322 			SQ_PUTLOCKS_EXIT(sq);
6323 			/*
6324 			 * we have the only claim, run the events,
6325 			 * sq_run_events will clear the SQ_EXCL flag.
6326 			 */
6327 			sq_run_events(sq);
6328 
6329 			/*
6330 			 * If this is a CIPUT perimiter, we need
6331 			 * to drop the SQ_EXCL flag so we can properly
6332 			 * continue draining the syncq.
6333 			 */
6334 			if (type & SQ_CIPUT) {
6335 				ASSERT(sq->sq_flags & SQ_EXCL);
6336 				sq->sq_flags &= ~SQ_EXCL;
6337 			}
6338 
6339 			/*
6340 			 * And go back to the beginning just in case
6341 			 * anything changed while we were away.
6342 			 */
6343 			ASSERT((sq->sq_flags & SQ_EXCL) || (type & SQ_CIPUT));
6344 			continue;
6345 		}
6346 
6347 		ASSERT(sq->sq_evhead == NULL);
6348 		ASSERT(!(sq->sq_flags & SQ_EVENTS));
6349 
6350 		/*
6351 		 * Find the queue that is not draining.
6352 		 *
6353 		 * q_draining is protected by QLOCK which we do not hold.
6354 		 * But if it was set, then a thread was draining, and if it gets
6355 		 * cleared, then it was because the thread has successfully
6356 		 * drained the syncq, or a GOAWAY state occured. For the GOAWAY
6357 		 * state to happen, a thread needs the SQLOCK which we hold, and
6358 		 * if there was such a flag, we whould have already seen it.
6359 		 */
6360 
6361 		for (qp = sq->sq_head;
6362 		    qp != NULL && (qp->q_draining ||
6363 			(qp->q_sqflags & Q_SQDRAINING));
6364 		    qp = qp->q_sqnext)
6365 			;
6366 
6367 		if (qp == NULL)
6368 			break;
6369 
6370 		/*
6371 		 * We have a queue to work on, and we hold the
6372 		 * SQLOCK and one claim, call qdrain_syncq.
6373 		 * This means we need to release the SQLOCK and
6374 		 * aquire the QLOCK (OK since we have a claim).
6375 		 * Note that qdrain_syncq will actually dequeue
6376 		 * this queue from the sq_head list when it is
6377 		 * convinced all the work is done and release
6378 		 * the QLOCK before returning.
6379 		 */
6380 		qp->q_sqflags |= Q_SQDRAINING;
6381 		mutex_exit(SQLOCK(sq));
6382 		mutex_enter(QLOCK(qp));
6383 		qdrain_syncq(sq, qp);
6384 		mutex_enter(SQLOCK(sq));
6385 
6386 		/* The queue is drained */
6387 		ASSERT(qp->q_sqflags & Q_SQDRAINING);
6388 		qp->q_sqflags &= ~Q_SQDRAINING;
6389 		/*
6390 		 * NOTE: After this point qp should not be used since it may be
6391 		 * closed.
6392 		 */
6393 	}
6394 
6395 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
6396 	flags = sq->sq_flags;
6397 
6398 	/*
6399 	 * sq->sq_head cannot change because we hold the
6400 	 * sqlock. However, a thread CAN decide that it is no longer
6401 	 * going to drain that queue.  However, this should be due to
6402 	 * a GOAWAY state, and we should see that here.
6403 	 *
6404 	 * This loop is not very efficient. One solution may be adding a second
6405 	 * pointer to the "draining" queue, but it is difficult to do when
6406 	 * queues are inserted in the middle due to priority ordering. Another
6407 	 * possibility is to yank the queue out of the sq list and put it onto
6408 	 * the "draining list" and then put it back if it can't be drained.
6409 	 */
6410 
6411 	ASSERT((sq->sq_head == NULL) || (flags & SQ_GOAWAY) ||
6412 		(type & SQ_CI) || sq->sq_head->q_draining);
6413 
6414 	/* Drop SQ_EXCL for non-CIPUT perimiters */
6415 	if (!(type & SQ_CIPUT))
6416 		flags &= ~SQ_EXCL;
6417 	ASSERT((flags & SQ_EXCL) == 0);
6418 
6419 	/* Wake up any waiters. */
6420 	if (flags & SQ_WANTWAKEUP) {
6421 		flags &= ~SQ_WANTWAKEUP;
6422 		cv_broadcast(&sq->sq_wait);
6423 	}
6424 	if (flags & SQ_WANTEXWAKEUP) {
6425 		flags &= ~SQ_WANTEXWAKEUP;
6426 		cv_broadcast(&sq->sq_exitwait);
6427 	}
6428 	sq->sq_flags = flags;
6429 
6430 	ASSERT(sq->sq_count != 0);
6431 	/* Release our claim. */
6432 	sq->sq_count--;
6433 
6434 	if (bg_service) {
6435 		ASSERT(sq->sq_servcount != 0);
6436 		sq->sq_servcount--;
6437 	}
6438 
6439 	mutex_exit(SQLOCK(sq));
6440 
6441 	TRACE_1(TR_FAC_STREAMS_FR, TR_DRAIN_SYNCQ_END,
6442 		"drain_syncq end:%p", sq);
6443 }
6444 
6445 
6446 /*
6447  *
6448  * qdrain_syncq can be called (currently) from only one of two places:
6449  *	drain_syncq
6450  * 	putnext  (or some variation of it).
6451  * and eventually
6452  * 	qwait(_sig)
6453  *
6454  * If called from drain_syncq, we found it in the list
6455  * of queue's needing service, so there is work to be done (or it
6456  * wouldn't be on the list).
6457  *
6458  * If called from some putnext variation, it was because the
6459  * perimiter is open, but messages are blocking a putnext and
6460  * there is not a thread working on it.  Now a thread could start
6461  * working on it while we are getting ready to do so ourself, but
6462  * the thread would set the q_draining flag, and we can spin out.
6463  *
6464  * As for qwait(_sig), I think I shall let it continue to call
6465  * drain_syncq directly (after all, it will get here eventually).
6466  *
6467  * qdrain_syncq has to terminate when:
6468  * - one of the SQ_STAYAWAY bits gets set to preserve qwriter(OUTER) ordering
6469  * - SQ_EVENTS gets set to preserve qwriter(INNER) ordering
6470  *
6471  * ASSUMES:
6472  *	One claim
6473  * 	QLOCK held
6474  * 	SQLOCK not held
6475  *	Will release QLOCK before returning
6476  */
6477 void
6478 qdrain_syncq(syncq_t *sq, queue_t *q)
6479 {
6480 	mblk_t		*bp;
6481 	boolean_t	do_clr;
6482 #ifdef DEBUG
6483 	uint16_t	count;
6484 #endif
6485 
6486 	TRACE_1(TR_FAC_STREAMS_FR, TR_DRAIN_SYNCQ_START,
6487 		"drain_syncq start:%p", sq);
6488 	ASSERT(q->q_syncq == sq);
6489 	ASSERT(MUTEX_HELD(QLOCK(q)));
6490 	ASSERT(MUTEX_NOT_HELD(SQLOCK(sq)));
6491 	/*
6492 	 * For non-CIPUT perimiters, we should be called with the
6493 	 * exclusive bit set already.  For non-CIPUT perimiters we
6494 	 * will be doing a concurrent drain, so it better not be set.
6495 	 */
6496 	ASSERT((sq->sq_flags & (SQ_EXCL|SQ_CIPUT)));
6497 	ASSERT(!((sq->sq_type & SQ_CIPUT) && (sq->sq_flags & SQ_EXCL)));
6498 	ASSERT((sq->sq_type & SQ_CIPUT) || (sq->sq_flags & SQ_EXCL));
6499 	/*
6500 	 * All outer pointers are set, or none of them are
6501 	 */
6502 	ASSERT((sq->sq_outer == NULL && sq->sq_onext == NULL &&
6503 		sq->sq_oprev == NULL) ||
6504 		(sq->sq_outer != NULL && sq->sq_onext != NULL &&
6505 		sq->sq_oprev != NULL));
6506 #ifdef DEBUG
6507 	count = sq->sq_count;
6508 	/*
6509 	 * This is OK without the putlocks, because we have one
6510 	 * claim either from the sq_count, or a putcount.  We could
6511 	 * get an erroneous value from other counts, but ours won't
6512 	 * change, so one way or another, we will have at least a
6513 	 * value of one.
6514 	 */
6515 	SUM_SQ_PUTCOUNTS(sq, count);
6516 	ASSERT(count >= 1);
6517 #endif /* DEBUG */
6518 
6519 	/*
6520 	 * The first thing to do here, is find out if a thread is already
6521 	 * draining this queue or the queue is closing. If so, we are done,
6522 	 * just return. Also, if there are no messages, we are done as well.
6523 	 * Note that we check the q_sqhead since there is s window of
6524 	 * opportunity for us to enter here because Q_SQQUEUED was set, but is
6525 	 * not anymore.
6526 	 */
6527 	if (q->q_draining || (q->q_sqhead == NULL)) {
6528 		mutex_exit(QLOCK(q));
6529 		return;
6530 	}
6531 
6532 	/*
6533 	 * If the perimiter is exclusive, there is nothing we can
6534 	 * do right now, go away.
6535 	 * Note that there is nothing to prevent this case from changing
6536 	 * right after this check, but the spin-out will catch it.
6537 	 */
6538 
6539 	/* Tell other threads that we are draining this queue */
6540 	q->q_draining = 1;	/* Protected by QLOCK */
6541 
6542 	for (bp = q->q_sqhead; bp != NULL; bp = q->q_sqhead) {
6543 
6544 		/*
6545 		 * Because we can enter this routine just because
6546 		 * a putnext is blocked, we need to spin out if
6547 		 * the perimiter wants to go exclusive as well
6548 		 * as just blocked. We need to spin out also if
6549 		 * events are queued on the syncq.
6550 		 * Don't check for SQ_EXCL, because non-CIPUT
6551 		 * perimiters would set it, and it can't become
6552 		 * exclusive while we hold a claim.
6553 		 */
6554 		if (sq->sq_flags & (SQ_STAYAWAY | SQ_EVENTS)) {
6555 			break;
6556 		}
6557 
6558 #ifdef DEBUG
6559 		/*
6560 		 * Since we are in qdrain_syncq, we already know the queue,
6561 		 * but for sanity, we want to check this against the qp that
6562 		 * was passed in by bp->b_queue.
6563 		 */
6564 
6565 		ASSERT(bp->b_queue == q);
6566 		ASSERT(bp->b_queue->q_syncq == sq);
6567 		bp->b_queue = NULL;
6568 
6569 		/*
6570 		 * We would have the following check in the DEBUG code:
6571 		 *
6572 		 * if (bp->b_prev != NULL)  {
6573 		 *	ASSERT(bp->b_prev == (void (*)())q->q_qinfo->qi_putp);
6574 		 * }
6575 		 *
6576 		 * This can't be done, however, since IP modifies qinfo
6577 		 * structure at run-time (switching between IPv4 qinfo and IPv6
6578 		 * qinfo), invalidating the check.
6579 		 * So the assignment to func is left here, but the ASSERT itself
6580 		 * is removed until the whole issue is resolved.
6581 		 */
6582 #endif
6583 		ASSERT(q->q_sqhead == bp);
6584 		q->q_sqhead = bp->b_next;
6585 		bp->b_prev = bp->b_next = NULL;
6586 		ASSERT(q->q_syncqmsgs > 0);
6587 		mutex_exit(QLOCK(q));
6588 
6589 		ASSERT(bp->b_datap->db_ref != 0);
6590 
6591 		(void) (*q->q_qinfo->qi_putp)(q, bp);
6592 
6593 		mutex_enter(QLOCK(q));
6594 		/*
6595 		 * We should decrement q_syncqmsgs only after executing the
6596 		 * put procedure to avoid a possible race with putnext().
6597 		 * In putnext() though it sees Q_SQQUEUED is set, there is
6598 		 * an optimization which allows putnext to call the put
6599 		 * procedure directly if (q_syncqmsgs == 0) and thus
6600 		 * a message reodering could otherwise occur.
6601 		 */
6602 		q->q_syncqmsgs--;
6603 
6604 		/*
6605 		 * Clear QFULL in the next service procedure queue if
6606 		 * this is the last message destined to that queue.
6607 		 *
6608 		 * It would make better sense to have some sort of
6609 		 * tunable for the low water mark, but these symantics
6610 		 * are not yet defined.  So, alas, we use a constant.
6611 		 */
6612 		do_clr = (q->q_syncqmsgs == 0);
6613 		mutex_exit(QLOCK(q));
6614 
6615 		if (do_clr)
6616 			clr_qfull(q);
6617 
6618 		mutex_enter(QLOCK(q));
6619 		/*
6620 		 * Always clear SQ_EXCL when CIPUT in order to handle
6621 		 * qwriter(INNER).
6622 		 */
6623 		/*
6624 		 * The putp() can call qwriter and get exclusive access
6625 		 * IFF this is the only claim.  So, we need to test for
6626 		 * this possibility so we can aquire the mutex and clear
6627 		 * the bit.
6628 		 */
6629 		if ((sq->sq_type & SQ_CIPUT) && (sq->sq_flags & SQ_EXCL)) {
6630 			mutex_enter(SQLOCK(sq));
6631 			sq->sq_flags &= ~SQ_EXCL;
6632 			mutex_exit(SQLOCK(sq));
6633 		}
6634 	}
6635 
6636 	/*
6637 	 * We should either have no queues on the syncq, or we were
6638 	 * told to goaway by a waiter (which we will wake up at the
6639 	 * end of this function).
6640 	 */
6641 	ASSERT((q->q_sqhead == NULL) ||
6642 	    (sq->sq_flags & (SQ_STAYAWAY | SQ_EVENTS)));
6643 
6644 	ASSERT(MUTEX_HELD(QLOCK(q)));
6645 	ASSERT(MUTEX_NOT_HELD(SQLOCK(sq)));
6646 
6647 	/*
6648 	 * Remove the q from the syncq list if all the messages are
6649 	 * drained.
6650 	 */
6651 	if (q->q_sqhead == NULL) {
6652 		mutex_enter(SQLOCK(sq));
6653 		if (q->q_sqflags & Q_SQQUEUED)
6654 			SQRM_Q(sq, q);
6655 		mutex_exit(SQLOCK(sq));
6656 		/*
6657 		 * Since the queue is removed from the list, reset its priority.
6658 		 */
6659 		q->q_spri = 0;
6660 	}
6661 
6662 	/*
6663 	 * Remember, the q_draining flag is used to let another
6664 	 * thread know that there is a thread currently draining
6665 	 * the messages for a queue.  Since we are now done with
6666 	 * this queue (even if there may be messages still there),
6667 	 * we need to clear this flag so some thread will work
6668 	 * on it if needed.
6669 	 */
6670 	ASSERT(q->q_draining);
6671 	q->q_draining = 0;
6672 
6673 	/* called with a claim, so OK to drop all locks. */
6674 	mutex_exit(QLOCK(q));
6675 
6676 	TRACE_1(TR_FAC_STREAMS_FR, TR_DRAIN_SYNCQ_END,
6677 		"drain_syncq end:%p", sq);
6678 }
6679 /* END OF QDRAIN_SYNCQ  */
6680 
6681 
6682 /*
6683  * This is the mate to qdrain_syncq, except that it is putting the
6684  * message onto the the queue instead draining.  Since the
6685  * message is destined for the queue that is selected, there is
6686  * no need to identify the function because the message is
6687  * intended for the put routine for the queue.  But this
6688  * routine will do it anyway just in case (but only for debug kernels).
6689  *
6690  * After the message is enqueued on the syncq, it calls putnext_tail()
6691  * which will schedule a background thread to actually process the message.
6692  *
6693  * Assumes that there is a claim on the syncq (sq->sq_count > 0) and
6694  * SQLOCK(sq) and QLOCK(q) are not held.
6695  */
6696 void
6697 qfill_syncq(syncq_t *sq, queue_t *q, mblk_t *mp)
6698 {
6699 	queue_t		*fq = NULL;
6700 
6701 	ASSERT(MUTEX_NOT_HELD(SQLOCK(sq)));
6702 	ASSERT(MUTEX_NOT_HELD(QLOCK(q)));
6703 	ASSERT(sq->sq_count > 0);
6704 	ASSERT(q->q_syncq == sq);
6705 	ASSERT((sq->sq_outer == NULL && sq->sq_onext == NULL &&
6706 		sq->sq_oprev == NULL) ||
6707 		(sq->sq_outer != NULL && sq->sq_onext != NULL &&
6708 		sq->sq_oprev != NULL));
6709 
6710 	mutex_enter(QLOCK(q));
6711 
6712 	/*
6713 	 * Set QFULL in next service procedure queue (that cares) if not
6714 	 * already set and if there are already more messages on the syncq
6715 	 * than sq_max_size.  If sq_max_size is 0, no flow control will be
6716 	 * asserted on any syncq.
6717 	 *
6718 	 * The fq here is the next queue with a service procedure.
6719 	 * This is where we would fail canputnext, so this is where we
6720 	 * need to set QFULL.
6721 	 *
6722 	 * LOCKING HIERARCHY: In the case when fq != q we need to
6723 	 *  a) Take QLOCK(fq) to set QFULL flag and
6724 	 *  b) Take sd_reflock in the case of the hot stream to update
6725 	 *  	sd_refcnt.
6726 	 * We already have QLOCK at this point. To avoid cross-locks with
6727 	 * freezestr() which grabs all QLOCKs and with strlock() which grabs
6728 	 * both SQLOCK and sd_reflock, we need to drop respective locks first.
6729 	 */
6730 	if ((sq_max_size != 0) && (!(q->q_nfsrv->q_flag & QFULL)) &&
6731 	    (q->q_syncqmsgs > sq_max_size)) {
6732 		if ((fq = q->q_nfsrv) == q) {
6733 			fq->q_flag |= QFULL;
6734 		} else {
6735 			mutex_exit(QLOCK(q));
6736 			mutex_enter(QLOCK(fq));
6737 			fq->q_flag |= QFULL;
6738 			mutex_exit(QLOCK(fq));
6739 			mutex_enter(QLOCK(q));
6740 		}
6741 	}
6742 
6743 #ifdef DEBUG
6744 	/*
6745 	 * This is used for debug in the qfill_syncq/qdrain_syncq case
6746 	 * to trace the queue that the message is intended for.  Note
6747 	 * that the original use was to identify the queue and function
6748 	 * to call on the drain.  In the new syncq, we have the context
6749 	 * of the queue that we are draining, so call it's putproc and
6750 	 * don't rely on the saved values.  But for debug this is still
6751 	 * usefull information.
6752 	 */
6753 	mp->b_prev = (mblk_t *)q->q_qinfo->qi_putp;
6754 	mp->b_queue = q;
6755 	mp->b_next = NULL;
6756 #endif
6757 	ASSERT(q->q_syncq == sq);
6758 	/*
6759 	 * Enqueue the message on the list.
6760 	 * SQPUT_MP() accesses q_syncqmsgs.  We are already holding QLOCK to
6761 	 * protect it.  So its ok to acquire SQLOCK after SQPUT_MP().
6762 	 */
6763 	SQPUT_MP(q, mp);
6764 	mutex_enter(SQLOCK(sq));
6765 
6766 	/*
6767 	 * And queue on syncq for scheduling, if not already queued.
6768 	 * Note that we need the SQLOCK for this, and for testing flags
6769 	 * at the end to see if we will drain.  So grab it now, and
6770 	 * release it before we call qdrain_syncq or return.
6771 	 */
6772 	if (!(q->q_sqflags & Q_SQQUEUED)) {
6773 		q->q_spri = curthread->t_pri;
6774 		SQPUT_Q(sq, q);
6775 	}
6776 #ifdef DEBUG
6777 	else {
6778 		/*
6779 		 * All of these conditions MUST be true!
6780 		 */
6781 		ASSERT(sq->sq_tail != NULL);
6782 		if (sq->sq_tail == sq->sq_head) {
6783 			ASSERT((q->q_sqprev == NULL) &&
6784 			    (q->q_sqnext == NULL));
6785 		} else {
6786 			ASSERT((q->q_sqprev != NULL) ||
6787 			    (q->q_sqnext != NULL));
6788 		}
6789 		ASSERT(sq->sq_flags & SQ_QUEUED);
6790 		ASSERT(q->q_syncqmsgs != 0);
6791 		ASSERT(q->q_sqflags & Q_SQQUEUED);
6792 	}
6793 #endif
6794 	mutex_exit(QLOCK(q));
6795 	/*
6796 	 * SQLOCK is still held, so sq_count can be safely decremented.
6797 	 */
6798 	sq->sq_count--;
6799 
6800 	putnext_tail(sq, q, 0);
6801 	/* Should not reference sq or q after this point. */
6802 }
6803 
6804 /*  End of qfill_syncq  */
6805 
6806 /*
6807  * Remove all messages from a syncq (if qp is NULL) or remove all messages
6808  * that would be put into qp by drain_syncq.
6809  * Used when deleting the syncq (qp == NULL) or when detaching
6810  * a queue (qp != NULL).
6811  * Return non-zero if one or more messages were freed.
6812  *
6813  * no need to grab sq_putlocks here. See comment in strsubr.h that explains when
6814  * sq_putlocks are used.
6815  *
6816  * NOTE: This function assumes that it is called from the close() context and
6817  * that all the queues in the syncq are going aay. For this reason it doesn't
6818  * acquire QLOCK for modifying q_sqhead/q_sqtail fields. This assumption is
6819  * currently valid, but it is useful to rethink this function to behave properly
6820  * in other cases.
6821  */
6822 int
6823 flush_syncq(syncq_t *sq, queue_t *qp)
6824 {
6825 	mblk_t		*bp, *mp_head, *mp_next, *mp_prev;
6826 	queue_t		*q;
6827 	int		ret = 0;
6828 
6829 	mutex_enter(SQLOCK(sq));
6830 
6831 	/*
6832 	 * Before we leave, we need to make sure there are no
6833 	 * events listed for this queue.  All events for this queue
6834 	 * will just be freed.
6835 	 */
6836 	if (qp != NULL && sq->sq_evhead != NULL) {
6837 		ASSERT(sq->sq_flags & SQ_EVENTS);
6838 
6839 		mp_prev = NULL;
6840 		for (bp = sq->sq_evhead; bp != NULL; bp = mp_next) {
6841 			mp_next = bp->b_next;
6842 			if (bp->b_queue == qp) {
6843 				/* Delete this message */
6844 				if (mp_prev != NULL) {
6845 					mp_prev->b_next = mp_next;
6846 					/*
6847 					 * Update sq_evtail if the last element
6848 					 * is removed.
6849 					 */
6850 					if (bp == sq->sq_evtail) {
6851 						ASSERT(mp_next == NULL);
6852 						sq->sq_evtail = mp_prev;
6853 					}
6854 				} else
6855 					sq->sq_evhead = mp_next;
6856 				if (sq->sq_evhead == NULL)
6857 					sq->sq_flags &= ~SQ_EVENTS;
6858 				bp->b_prev = bp->b_next = NULL;
6859 				freemsg(bp);
6860 				ret++;
6861 			} else {
6862 				mp_prev = bp;
6863 			}
6864 		}
6865 	}
6866 
6867 	/*
6868 	 * Walk sq_head and:
6869 	 *	- match qp if qp is set, remove it's messages
6870 	 *	- all if qp is not set
6871 	 */
6872 	q = sq->sq_head;
6873 	while (q != NULL) {
6874 		ASSERT(q->q_syncq == sq);
6875 		if ((qp == NULL) || (qp == q)) {
6876 			/*
6877 			 * Yank the messages as a list off the queue
6878 			 */
6879 			mp_head = q->q_sqhead;
6880 			/*
6881 			 * We do not have QLOCK(q) here (which is safe due to
6882 			 * assumptions mentioned above). To obtain the lock we
6883 			 * need to release SQLOCK which may allow lots of things
6884 			 * to change upon us. This place requires more analysis.
6885 			 */
6886 			q->q_sqhead = q->q_sqtail = NULL;
6887 			ASSERT(mp_head->b_queue &&
6888 			    mp_head->b_queue->q_syncq == sq);
6889 
6890 			/*
6891 			 * Free each of the messages.
6892 			 */
6893 			for (bp = mp_head; bp != NULL; bp = mp_next) {
6894 				mp_next = bp->b_next;
6895 				bp->b_prev = bp->b_next = NULL;
6896 				freemsg(bp);
6897 				ret++;
6898 			}
6899 			/*
6900 			 * Now remove the queue from the syncq.
6901 			 */
6902 			ASSERT(q->q_sqflags & Q_SQQUEUED);
6903 			SQRM_Q(sq, q);
6904 			q->q_spri = 0;
6905 			q->q_syncqmsgs = 0;
6906 
6907 			/*
6908 			 * If qp was specified, we are done with it and are
6909 			 * going to drop SQLOCK(sq) and return. We wakeup syncq
6910 			 * waiters while we still have the SQLOCK.
6911 			 */
6912 			if ((qp != NULL) && (sq->sq_flags & SQ_WANTWAKEUP)) {
6913 				sq->sq_flags &= ~SQ_WANTWAKEUP;
6914 				cv_broadcast(&sq->sq_wait);
6915 			}
6916 			/* Drop SQLOCK across clr_qfull */
6917 			mutex_exit(SQLOCK(sq));
6918 
6919 			/*
6920 			 * We avoid doing the test that drain_syncq does and
6921 			 * unconditionally clear qfull for every flushed
6922 			 * message. Since flush_syncq is only called during
6923 			 * close this should not be a problem.
6924 			 */
6925 			clr_qfull(q);
6926 			if (qp != NULL) {
6927 				return (ret);
6928 			} else {
6929 				mutex_enter(SQLOCK(sq));
6930 				/*
6931 				 * The head was removed by SQRM_Q above.
6932 				 * reread the new head and flush it.
6933 				 */
6934 				q = sq->sq_head;
6935 			}
6936 		} else {
6937 			q = q->q_sqnext;
6938 		}
6939 		ASSERT(MUTEX_HELD(SQLOCK(sq)));
6940 	}
6941 
6942 	if (sq->sq_flags & SQ_WANTWAKEUP) {
6943 		sq->sq_flags &= ~SQ_WANTWAKEUP;
6944 		cv_broadcast(&sq->sq_wait);
6945 	}
6946 
6947 	mutex_exit(SQLOCK(sq));
6948 	return (ret);
6949 }
6950 
6951 /*
6952  * Propagate all messages from a syncq to the next syncq that are associated
6953  * with the specified queue. If the queue is attached to a driver or if the
6954  * messages have been added due to a qwriter(PERIM_INNER), free the messages.
6955  *
6956  * Assumes that the stream is strlock()'ed. We don't come here if there
6957  * are no messages to propagate.
6958  *
6959  * NOTE : If the queue is attached to a driver, all the messages are freed
6960  * as there is no point in propagating the messages from the driver syncq
6961  * to the closing stream head which will in turn get freed later.
6962  */
6963 static int
6964 propagate_syncq(queue_t *qp)
6965 {
6966 	mblk_t		*bp, *head, *tail, *prev, *next;
6967 	syncq_t 	*sq;
6968 	queue_t		*nqp;
6969 	syncq_t		*nsq;
6970 	boolean_t	isdriver;
6971 	int 		moved = 0;
6972 	uint16_t	flags;
6973 	pri_t		priority = curthread->t_pri;
6974 #ifdef DEBUG
6975 	void		(*func)();
6976 #endif
6977 
6978 	sq = qp->q_syncq;
6979 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
6980 	/* debug macro */
6981 	SQ_PUTLOCKS_HELD(sq);
6982 	/*
6983 	 * As entersq() does not increment the sq_count for
6984 	 * the write side, check sq_count for non-QPERQ
6985 	 * perimeters alone.
6986 	 */
6987 	ASSERT((qp->q_flag & QPERQ) || (sq->sq_count >= 1));
6988 
6989 	/*
6990 	 * propagate_syncq() can be called because of either messages on the
6991 	 * queue syncq or because on events on the queue syncq. Do actual
6992 	 * message propagations if there are any messages.
6993 	 */
6994 	if (qp->q_syncqmsgs) {
6995 		isdriver = (qp->q_flag & QISDRV);
6996 
6997 		if (!isdriver) {
6998 			nqp = qp->q_next;
6999 			nsq = nqp->q_syncq;
7000 			ASSERT(MUTEX_HELD(SQLOCK(nsq)));
7001 			/* debug macro */
7002 			SQ_PUTLOCKS_HELD(nsq);
7003 #ifdef DEBUG
7004 			func = (void (*)())nqp->q_qinfo->qi_putp;
7005 #endif
7006 		}
7007 
7008 		SQRM_Q(sq, qp);
7009 		priority = MAX(qp->q_spri, priority);
7010 		qp->q_spri = 0;
7011 		head = qp->q_sqhead;
7012 		tail = qp->q_sqtail;
7013 		qp->q_sqhead = qp->q_sqtail = NULL;
7014 		qp->q_syncqmsgs = 0;
7015 
7016 		/*
7017 		 * Walk the list of messages, and free them if this is a driver,
7018 		 * otherwise reset the b_prev and b_queue value to the new putp.
7019 		 * Afterward, we will just add the head to the end of the next
7020 		 * syncq, and point the tail to the end of this one.
7021 		 */
7022 
7023 		for (bp = head; bp != NULL; bp = next) {
7024 			next = bp->b_next;
7025 			if (isdriver) {
7026 				bp->b_prev = bp->b_next = NULL;
7027 				freemsg(bp);
7028 				continue;
7029 			}
7030 			/* Change the q values for this message */
7031 			bp->b_queue = nqp;
7032 #ifdef DEBUG
7033 			bp->b_prev = (mblk_t *)func;
7034 #endif
7035 			moved++;
7036 		}
7037 		/*
7038 		 * Attach list of messages to the end of the new queue (if there
7039 		 * is a list of messages).
7040 		 */
7041 
7042 		if (!isdriver && head != NULL) {
7043 			ASSERT(tail != NULL);
7044 			if (nqp->q_sqhead == NULL) {
7045 				nqp->q_sqhead = head;
7046 			} else {
7047 				ASSERT(nqp->q_sqtail != NULL);
7048 				nqp->q_sqtail->b_next = head;
7049 			}
7050 			nqp->q_sqtail = tail;
7051 			/*
7052 			 * When messages are moved from high priority queue to
7053 			 * another queue, the destination queue priority is
7054 			 * upgraded.
7055 			 */
7056 
7057 			if (priority > nqp->q_spri)
7058 				nqp->q_spri = priority;
7059 
7060 			SQPUT_Q(nsq, nqp);
7061 
7062 			nqp->q_syncqmsgs += moved;
7063 			ASSERT(nqp->q_syncqmsgs != 0);
7064 		}
7065 	}
7066 
7067 	/*
7068 	 * Before we leave, we need to make sure there are no
7069 	 * events listed for this queue.  All events for this queue
7070 	 * will just be freed.
7071 	 */
7072 	if (sq->sq_evhead != NULL) {
7073 		ASSERT(sq->sq_flags & SQ_EVENTS);
7074 		prev = NULL;
7075 		for (bp = sq->sq_evhead; bp != NULL; bp = next) {
7076 			next = bp->b_next;
7077 			if (bp->b_queue == qp) {
7078 				/* Delete this message */
7079 				if (prev != NULL) {
7080 					prev->b_next = next;
7081 					/*
7082 					 * Update sq_evtail if the last element
7083 					 * is removed.
7084 					 */
7085 					if (bp == sq->sq_evtail) {
7086 						ASSERT(next == NULL);
7087 						sq->sq_evtail = prev;
7088 					}
7089 				} else
7090 					sq->sq_evhead = next;
7091 				if (sq->sq_evhead == NULL)
7092 					sq->sq_flags &= ~SQ_EVENTS;
7093 				bp->b_prev = bp->b_next = NULL;
7094 				freemsg(bp);
7095 			} else {
7096 				prev = bp;
7097 			}
7098 		}
7099 	}
7100 
7101 	flags = sq->sq_flags;
7102 
7103 	/* Wake up any waiter before leaving. */
7104 	if (flags & SQ_WANTWAKEUP) {
7105 		flags &= ~SQ_WANTWAKEUP;
7106 		cv_broadcast(&sq->sq_wait);
7107 	}
7108 	sq->sq_flags = flags;
7109 
7110 	return (moved);
7111 }
7112 
7113 /*
7114  * Try and upgrade to exclusive access at the inner perimeter. If this can
7115  * not be done without blocking then request will be queued on the syncq
7116  * and drain_syncq will run it later.
7117  *
7118  * This routine can only be called from put or service procedures plus
7119  * asynchronous callback routines that have properly entered to
7120  * queue (with entersq.) Thus qwriter_inner assumes the caller has one claim
7121  * on the syncq associated with q.
7122  */
7123 void
7124 qwriter_inner(queue_t *q, mblk_t *mp, void (*func)())
7125 {
7126 	syncq_t	*sq = q->q_syncq;
7127 	uint16_t count;
7128 
7129 	mutex_enter(SQLOCK(sq));
7130 	count = sq->sq_count;
7131 	SQ_PUTLOCKS_ENTER(sq);
7132 	SUM_SQ_PUTCOUNTS(sq, count);
7133 	ASSERT(count >= 1);
7134 	ASSERT(sq->sq_type & (SQ_CIPUT|SQ_CISVC));
7135 
7136 	if (count == 1) {
7137 		/*
7138 		 * Can upgrade. This case also handles nested qwriter calls
7139 		 * (when the qwriter callback function calls qwriter). In that
7140 		 * case SQ_EXCL is already set.
7141 		 */
7142 		sq->sq_flags |= SQ_EXCL;
7143 		SQ_PUTLOCKS_EXIT(sq);
7144 		mutex_exit(SQLOCK(sq));
7145 		(*func)(q, mp);
7146 		/*
7147 		 * Assumes that leavesq, putnext, and drain_syncq will reset
7148 		 * SQ_EXCL for SQ_CIPUT/SQ_CISVC queues. We leave SQ_EXCL on
7149 		 * until putnext, leavesq, or drain_syncq drops it.
7150 		 * That way we handle nested qwriter(INNER) without dropping
7151 		 * SQ_EXCL until the outermost qwriter callback routine is
7152 		 * done.
7153 		 */
7154 		return;
7155 	}
7156 	SQ_PUTLOCKS_EXIT(sq);
7157 	sqfill_events(sq, q, mp, func);
7158 }
7159 
7160 /*
7161  * Synchronous callback support functions
7162  */
7163 
7164 /*
7165  * Allocate a callback parameter structure.
7166  * Assumes that caller initializes the flags and the id.
7167  * Acquires SQLOCK(sq) if non-NULL is returned.
7168  */
7169 callbparams_t *
7170 callbparams_alloc(syncq_t *sq, void (*func)(void *), void *arg, int kmflags)
7171 {
7172 	callbparams_t *cbp;
7173 	size_t size = sizeof (callbparams_t);
7174 
7175 	cbp = kmem_alloc(size, kmflags & ~KM_PANIC);
7176 
7177 	/*
7178 	 * Only try tryhard allocation if the caller is ready to panic.
7179 	 * Otherwise just fail.
7180 	 */
7181 	if (cbp == NULL) {
7182 		if (kmflags & KM_PANIC)
7183 			cbp = kmem_alloc_tryhard(sizeof (callbparams_t),
7184 			    &size, kmflags);
7185 		else
7186 			return (NULL);
7187 	}
7188 
7189 	ASSERT(size >= sizeof (callbparams_t));
7190 	cbp->cbp_size = size;
7191 	cbp->cbp_sq = sq;
7192 	cbp->cbp_func = func;
7193 	cbp->cbp_arg = arg;
7194 	mutex_enter(SQLOCK(sq));
7195 	cbp->cbp_next = sq->sq_callbpend;
7196 	sq->sq_callbpend = cbp;
7197 	return (cbp);
7198 }
7199 
7200 void
7201 callbparams_free(syncq_t *sq, callbparams_t *cbp)
7202 {
7203 	callbparams_t **pp, *p;
7204 
7205 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
7206 
7207 	for (pp = &sq->sq_callbpend; (p = *pp) != NULL; pp = &p->cbp_next) {
7208 		if (p == cbp) {
7209 			*pp = p->cbp_next;
7210 			kmem_free(p, p->cbp_size);
7211 			return;
7212 		}
7213 	}
7214 	(void) (STRLOG(0, 0, 0, SL_CONSOLE,
7215 	    "callbparams_free: not found\n"));
7216 }
7217 
7218 void
7219 callbparams_free_id(syncq_t *sq, callbparams_id_t id, int32_t flag)
7220 {
7221 	callbparams_t **pp, *p;
7222 
7223 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
7224 
7225 	for (pp = &sq->sq_callbpend; (p = *pp) != NULL; pp = &p->cbp_next) {
7226 		if (p->cbp_id == id && p->cbp_flags == flag) {
7227 			*pp = p->cbp_next;
7228 			kmem_free(p, p->cbp_size);
7229 			return;
7230 		}
7231 	}
7232 	(void) (STRLOG(0, 0, 0, SL_CONSOLE,
7233 	    "callbparams_free_id: not found\n"));
7234 }
7235 
7236 /*
7237  * Callback wrapper function used by once-only callbacks that can be
7238  * cancelled (qtimeout and qbufcall)
7239  * Contains inline version of entersq(sq, SQ_CALLBACK) that can be
7240  * cancelled by the qun* functions.
7241  */
7242 void
7243 qcallbwrapper(void *arg)
7244 {
7245 	callbparams_t *cbp = arg;
7246 	syncq_t	*sq;
7247 	uint16_t count = 0;
7248 	uint16_t waitflags = SQ_STAYAWAY | SQ_EVENTS | SQ_EXCL;
7249 	uint16_t type;
7250 
7251 	sq = cbp->cbp_sq;
7252 	mutex_enter(SQLOCK(sq));
7253 	type = sq->sq_type;
7254 	if (!(type & SQ_CICB)) {
7255 		count = sq->sq_count;
7256 		SQ_PUTLOCKS_ENTER(sq);
7257 		SQ_PUTCOUNT_CLRFAST_LOCKED(sq);
7258 		SUM_SQ_PUTCOUNTS(sq, count);
7259 		sq->sq_needexcl++;
7260 		ASSERT(sq->sq_needexcl != 0);	/* wraparound */
7261 		waitflags |= SQ_MESSAGES;
7262 	}
7263 	/* Can not handle exlusive entry at outer perimeter */
7264 	ASSERT(type & SQ_COCB);
7265 
7266 	while ((sq->sq_flags & waitflags) || (!(type & SQ_CICB) &&count != 0)) {
7267 		if ((sq->sq_callbflags & cbp->cbp_flags) &&
7268 		    (sq->sq_cancelid == cbp->cbp_id)) {
7269 			/* timeout has been cancelled */
7270 			sq->sq_callbflags |= SQ_CALLB_BYPASSED;
7271 			callbparams_free(sq, cbp);
7272 			if (!(type & SQ_CICB)) {
7273 				ASSERT(sq->sq_needexcl > 0);
7274 				sq->sq_needexcl--;
7275 				if (sq->sq_needexcl == 0) {
7276 					SQ_PUTCOUNT_SETFAST_LOCKED(sq);
7277 				}
7278 				SQ_PUTLOCKS_EXIT(sq);
7279 			}
7280 			mutex_exit(SQLOCK(sq));
7281 			return;
7282 		}
7283 		sq->sq_flags |= SQ_WANTWAKEUP;
7284 		if (!(type & SQ_CICB)) {
7285 			SQ_PUTLOCKS_EXIT(sq);
7286 		}
7287 		cv_wait(&sq->sq_wait, SQLOCK(sq));
7288 		if (!(type & SQ_CICB)) {
7289 			count = sq->sq_count;
7290 			SQ_PUTLOCKS_ENTER(sq);
7291 			SUM_SQ_PUTCOUNTS(sq, count);
7292 		}
7293 	}
7294 
7295 	sq->sq_count++;
7296 	ASSERT(sq->sq_count != 0);	/* Wraparound */
7297 	if (!(type & SQ_CICB)) {
7298 		ASSERT(count == 0);
7299 		sq->sq_flags |= SQ_EXCL;
7300 		ASSERT(sq->sq_needexcl > 0);
7301 		sq->sq_needexcl--;
7302 		if (sq->sq_needexcl == 0) {
7303 			SQ_PUTCOUNT_SETFAST_LOCKED(sq);
7304 		}
7305 		SQ_PUTLOCKS_EXIT(sq);
7306 	}
7307 
7308 	mutex_exit(SQLOCK(sq));
7309 
7310 	cbp->cbp_func(cbp->cbp_arg);
7311 
7312 	/*
7313 	 * We drop the lock only for leavesq to re-acquire it.
7314 	 * Possible optimization is inline of leavesq.
7315 	 */
7316 	mutex_enter(SQLOCK(sq));
7317 	callbparams_free(sq, cbp);
7318 	mutex_exit(SQLOCK(sq));
7319 	leavesq(sq, SQ_CALLBACK);
7320 }
7321 
7322 /*
7323  * no need to grab sq_putlocks here. See comment in strsubr.h that
7324  * explains when sq_putlocks are used.
7325  *
7326  * sq_count (or one of the sq_putcounts) has already been
7327  * decremented by the caller, and if SQ_QUEUED, we need to call
7328  * drain_syncq (the global syncq drain).
7329  * If putnext_tail is called with the SQ_EXCL bit set, we are in
7330  * one of two states, non-CIPUT perimiter, and we need to clear
7331  * it, or we went exclusive in the put procedure.  In any case,
7332  * we want to clear the bit now, and it is probably easier to do
7333  * this at the beginning of this function (remember, we hold
7334  * the SQLOCK).  Lastly, if there are other messages queued
7335  * on the syncq (and not for our destination), enable the syncq
7336  * for background work.
7337  */
7338 
7339 /* ARGSUSED */
7340 void
7341 putnext_tail(syncq_t *sq, queue_t *qp, uint32_t passflags)
7342 {
7343 	uint16_t	flags = sq->sq_flags;
7344 
7345 	ASSERT(MUTEX_HELD(SQLOCK(sq)));
7346 	ASSERT(MUTEX_NOT_HELD(QLOCK(qp)));
7347 
7348 	/* Clear SQ_EXCL if set in passflags */
7349 	if (passflags & SQ_EXCL) {
7350 		flags &= ~SQ_EXCL;
7351 	}
7352 	if (flags & SQ_WANTWAKEUP) {
7353 		flags &= ~SQ_WANTWAKEUP;
7354 		cv_broadcast(&sq->sq_wait);
7355 	}
7356 	if (flags & SQ_WANTEXWAKEUP) {
7357 		flags &= ~SQ_WANTEXWAKEUP;
7358 		cv_broadcast(&sq->sq_exitwait);
7359 	}
7360 	sq->sq_flags = flags;
7361 
7362 	/*
7363 	 * We have cleared SQ_EXCL if we were asked to, and started
7364 	 * the wakeup process for waiters.  If there are no writers
7365 	 * then we need to drain the syncq if we were told to, or
7366 	 * enable the background thread to do it.
7367 	 */
7368 	if (!(flags & (SQ_STAYAWAY|SQ_EXCL))) {
7369 		if ((passflags & SQ_QUEUED) ||
7370 		    (sq->sq_svcflags & SQ_DISABLED)) {
7371 			/* drain_syncq will take care of events in the list */
7372 			drain_syncq(sq);
7373 			return;
7374 		} else if (flags & SQ_QUEUED) {
7375 			sqenable(sq);
7376 		}
7377 	}
7378 	/* Drop the SQLOCK on exit */
7379 	mutex_exit(SQLOCK(sq));
7380 	TRACE_3(TR_FAC_STREAMS_FR, TR_PUTNEXT_END,
7381 		"putnext_end:(%p, %p, %p) done", NULL, qp, sq);
7382 }
7383 
7384 void
7385 set_qend(queue_t *q)
7386 {
7387 	mutex_enter(QLOCK(q));
7388 	if (!O_SAMESTR(q))
7389 		q->q_flag |= QEND;
7390 	else
7391 		q->q_flag &= ~QEND;
7392 	mutex_exit(QLOCK(q));
7393 	q = _OTHERQ(q);
7394 	mutex_enter(QLOCK(q));
7395 	if (!O_SAMESTR(q))
7396 		q->q_flag |= QEND;
7397 	else
7398 		q->q_flag &= ~QEND;
7399 	mutex_exit(QLOCK(q));
7400 }
7401 
7402 
7403 void
7404 clr_qfull(queue_t *q)
7405 {
7406 	queue_t	*oq = q;
7407 
7408 	q = q->q_nfsrv;
7409 	/* Fast check if there is any work to do before getting the lock. */
7410 	if ((q->q_flag & (QFULL|QWANTW)) == 0) {
7411 		return;
7412 	}
7413 
7414 	/*
7415 	 * Do not reset QFULL (and backenable) if the q_count is the reason
7416 	 * for QFULL being set.
7417 	 */
7418 	mutex_enter(QLOCK(q));
7419 	/*
7420 	 * If both q_count and q_mblkcnt are less than the hiwat mark
7421 	 */
7422 	if ((q->q_count < q->q_hiwat) && (q->q_mblkcnt < q->q_hiwat)) {
7423 		q->q_flag &= ~QFULL;
7424 		/*
7425 		 * A little more confusing, how about this way:
7426 		 * if someone wants to write,
7427 		 * AND
7428 		 *    both counts are less than the lowat mark
7429 		 *    OR
7430 		 *    the lowat mark is zero
7431 		 * THEN
7432 		 * backenable
7433 		 */
7434 		if ((q->q_flag & QWANTW) &&
7435 		    (((q->q_count < q->q_lowat) &&
7436 		    (q->q_mblkcnt < q->q_lowat)) || q->q_lowat == 0)) {
7437 			q->q_flag &= ~QWANTW;
7438 			mutex_exit(QLOCK(q));
7439 			backenable(oq, 0);
7440 		} else
7441 			mutex_exit(QLOCK(q));
7442 	} else
7443 		mutex_exit(QLOCK(q));
7444 }
7445 
7446 /*
7447  * Set the forward service procedure pointer.
7448  *
7449  * Called at insert-time to cache a queue's next forward service procedure in
7450  * q_nfsrv; used by canput() and canputnext().  If the queue to be inserted
7451  * has a service procedure then q_nfsrv points to itself.  If the queue to be
7452  * inserted does not have a service procedure, then q_nfsrv points to the next
7453  * queue forward that has a service procedure.  If the queue is at the logical
7454  * end of the stream (driver for write side, stream head for the read side)
7455  * and does not have a service procedure, then q_nfsrv also points to itself.
7456  */
7457 void
7458 set_nfsrv_ptr(
7459 	queue_t  *rnew,		/* read queue pointer to new module */
7460 	queue_t  *wnew,		/* write queue pointer to new module */
7461 	queue_t  *prev_rq,	/* read queue pointer to the module above */
7462 	queue_t  *prev_wq)	/* write queue pointer to the module above */
7463 {
7464 	queue_t *qp;
7465 
7466 	if (prev_wq->q_next == NULL) {
7467 		/*
7468 		 * Insert the driver, initialize the driver and stream head.
7469 		 * In this case, prev_rq/prev_wq should be the stream head.
7470 		 * _I_INSERT does not allow inserting a driver.  Make sure
7471 		 * that it is not an insertion.
7472 		 */
7473 		ASSERT(!(rnew->q_flag & _QINSERTING));
7474 		wnew->q_nfsrv = wnew;
7475 		if (rnew->q_qinfo->qi_srvp)
7476 			rnew->q_nfsrv = rnew;
7477 		else
7478 			rnew->q_nfsrv = prev_rq;
7479 		prev_rq->q_nfsrv = prev_rq;
7480 		prev_wq->q_nfsrv = prev_wq;
7481 	} else {
7482 		/*
7483 		 * set up read side q_nfsrv pointer.  This MUST be done
7484 		 * before setting the write side, because the setting of
7485 		 * the write side for a fifo may depend on it.
7486 		 *
7487 		 * Suppose we have a fifo that only has pipemod pushed.
7488 		 * pipemod has no read or write service procedures, so
7489 		 * nfsrv for both pipemod queues points to prev_rq (the
7490 		 * stream read head).  Now push bufmod (which has only a
7491 		 * read service procedure).  Doing the write side first,
7492 		 * wnew->q_nfsrv is set to pipemod's writeq nfsrv, which
7493 		 * is WRONG; the next queue forward from wnew with a
7494 		 * service procedure will be rnew, not the stream read head.
7495 		 * Since the downstream queue (which in the case of a fifo
7496 		 * is the read queue rnew) can affect upstream queues, it
7497 		 * needs to be done first.  Setting up the read side first
7498 		 * sets nfsrv for both pipemod queues to rnew and then
7499 		 * when the write side is set up, wnew-q_nfsrv will also
7500 		 * point to rnew.
7501 		 */
7502 		if (rnew->q_qinfo->qi_srvp) {
7503 			/*
7504 			 * use _OTHERQ() because, if this is a pipe, next
7505 			 * module may have been pushed from other end and
7506 			 * q_next could be a read queue.
7507 			 */
7508 			qp = _OTHERQ(prev_wq->q_next);
7509 			while (qp && qp->q_nfsrv != qp) {
7510 				qp->q_nfsrv = rnew;
7511 				qp = backq(qp);
7512 			}
7513 			rnew->q_nfsrv = rnew;
7514 		} else
7515 			rnew->q_nfsrv = prev_rq->q_nfsrv;
7516 
7517 		/* set up write side q_nfsrv pointer */
7518 		if (wnew->q_qinfo->qi_srvp) {
7519 			wnew->q_nfsrv = wnew;
7520 
7521 			/*
7522 			 * For insertion, need to update nfsrv of the modules
7523 			 * above which do not have a service routine.
7524 			 */
7525 			if (rnew->q_flag & _QINSERTING) {
7526 				for (qp = prev_wq;
7527 				    qp != NULL && qp->q_nfsrv != qp;
7528 				    qp = backq(qp)) {
7529 					qp->q_nfsrv = wnew->q_nfsrv;
7530 				}
7531 			}
7532 		} else {
7533 			if (prev_wq->q_next == prev_rq)
7534 				/*
7535 				 * Since prev_wq/prev_rq are the middle of a
7536 				 * fifo, wnew/rnew will also be the middle of
7537 				 * a fifo and wnew's nfsrv is same as rnew's.
7538 				 */
7539 				wnew->q_nfsrv = rnew->q_nfsrv;
7540 			else
7541 				wnew->q_nfsrv = prev_wq->q_next->q_nfsrv;
7542 		}
7543 	}
7544 }
7545 
7546 /*
7547  * Reset the forward service procedure pointer; called at remove-time.
7548  */
7549 void
7550 reset_nfsrv_ptr(queue_t *rqp, queue_t *wqp)
7551 {
7552 	queue_t *tmp_qp;
7553 
7554 	/* Reset the write side q_nfsrv pointer for _I_REMOVE */
7555 	if ((rqp->q_flag & _QREMOVING) && (wqp->q_qinfo->qi_srvp != NULL)) {
7556 		for (tmp_qp = backq(wqp);
7557 		    tmp_qp != NULL && tmp_qp->q_nfsrv == wqp;
7558 		    tmp_qp = backq(tmp_qp)) {
7559 			tmp_qp->q_nfsrv = wqp->q_nfsrv;
7560 		}
7561 	}
7562 
7563 	/* reset the read side q_nfsrv pointer */
7564 	if (rqp->q_qinfo->qi_srvp) {
7565 		if (wqp->q_next) {	/* non-driver case */
7566 			tmp_qp = _OTHERQ(wqp->q_next);
7567 			while (tmp_qp && tmp_qp->q_nfsrv == rqp) {
7568 				/* Note that rqp->q_next cannot be NULL */
7569 				ASSERT(rqp->q_next != NULL);
7570 				tmp_qp->q_nfsrv = rqp->q_next->q_nfsrv;
7571 				tmp_qp = backq(tmp_qp);
7572 			}
7573 		}
7574 	}
7575 }
7576 
7577 /*
7578  * This routine should be called after all stream geometry changes to update
7579  * the stream head cached struio() rd/wr queue pointers. Note must be called
7580  * with the streamlock()ed.
7581  *
7582  * Note: only enables Synchronous STREAMS for a side of a Stream which has
7583  *	 an explicit synchronous barrier module queue. That is, a queue that
7584  *	 has specified a struio() type.
7585  */
7586 static void
7587 strsetuio(stdata_t *stp)
7588 {
7589 	queue_t *wrq;
7590 
7591 	if (stp->sd_flag & STPLEX) {
7592 		/*
7593 		 * Not stremahead, but a mux, so no Synchronous STREAMS.
7594 		 */
7595 		stp->sd_struiowrq = NULL;
7596 		stp->sd_struiordq = NULL;
7597 		return;
7598 	}
7599 	/*
7600 	 * Scan the write queue(s) while synchronous
7601 	 * until we find a qinfo uio type specified.
7602 	 */
7603 	wrq = stp->sd_wrq->q_next;
7604 	while (wrq) {
7605 		if (wrq->q_struiot == STRUIOT_NONE) {
7606 			wrq = 0;
7607 			break;
7608 		}
7609 		if (wrq->q_struiot != STRUIOT_DONTCARE)
7610 			break;
7611 		if (! _SAMESTR(wrq)) {
7612 			wrq = 0;
7613 			break;
7614 		}
7615 		wrq = wrq->q_next;
7616 	}
7617 	stp->sd_struiowrq = wrq;
7618 	/*
7619 	 * Scan the read queue(s) while synchronous
7620 	 * until we find a qinfo uio type specified.
7621 	 */
7622 	wrq = stp->sd_wrq->q_next;
7623 	while (wrq) {
7624 		if (_RD(wrq)->q_struiot == STRUIOT_NONE) {
7625 			wrq = 0;
7626 			break;
7627 		}
7628 		if (_RD(wrq)->q_struiot != STRUIOT_DONTCARE)
7629 			break;
7630 		if (! _SAMESTR(wrq)) {
7631 			wrq = 0;
7632 			break;
7633 		}
7634 		wrq = wrq->q_next;
7635 	}
7636 	stp->sd_struiordq = wrq ? _RD(wrq) : 0;
7637 }
7638 
7639 /*
7640  * pass_wput, unblocks the passthru queues, so that
7641  * messages can arrive at muxs lower read queue, before
7642  * I_LINK/I_UNLINK is acked/nacked.
7643  */
7644 static void
7645 pass_wput(queue_t *q, mblk_t *mp)
7646 {
7647 	syncq_t *sq;
7648 
7649 	sq = _RD(q)->q_syncq;
7650 	if (sq->sq_flags & SQ_BLOCKED)
7651 		unblocksq(sq, SQ_BLOCKED, 0);
7652 	putnext(q, mp);
7653 }
7654 
7655 /*
7656  * Set up queues for the link/unlink.
7657  * Create a new queue and block it and then insert it
7658  * below the stream head on the lower stream.
7659  * This prevents any messages from arriving during the setq
7660  * as well as while the mux is processing the LINK/I_UNLINK.
7661  * The blocked passq is unblocked once the LINK/I_UNLINK has
7662  * been acked or nacked or if a message is generated and sent
7663  * down muxs write put procedure.
7664  * see pass_wput().
7665  *
7666  * After the new queue is inserted, all messages coming from below are
7667  * blocked. The call to strlock will ensure that all activity in the stream head
7668  * read queue syncq is stopped (sq_count drops to zero).
7669  */
7670 static queue_t *
7671 link_addpassthru(stdata_t *stpdown)
7672 {
7673 	queue_t *passq;
7674 	sqlist_t sqlist;
7675 
7676 	passq = allocq();
7677 	STREAM(passq) = STREAM(_WR(passq)) = stpdown;
7678 	/* setq might sleep in allocator - avoid holding locks. */
7679 	setq(passq, &passthru_rinit, &passthru_winit, NULL, QPERQ,
7680 	    SQ_CI|SQ_CO, B_FALSE);
7681 	claimq(passq);
7682 	blocksq(passq->q_syncq, SQ_BLOCKED, 1);
7683 	insertq(STREAM(passq), passq);
7684 
7685 	/*
7686 	 * Use strlock() to wait for the stream head sq_count to drop to zero
7687 	 * since we are going to change q_ptr in the stream head.  Note that
7688 	 * insertq() doesn't wait for any syncq counts to drop to zero.
7689 	 */
7690 	sqlist.sqlist_head = NULL;
7691 	sqlist.sqlist_index = 0;
7692 	sqlist.sqlist_size = sizeof (sqlist_t);
7693 	sqlist_insert(&sqlist, _RD(stpdown->sd_wrq)->q_syncq);
7694 	strlock(stpdown, &sqlist);
7695 	strunlock(stpdown, &sqlist);
7696 
7697 	releaseq(passq);
7698 	return (passq);
7699 }
7700 
7701 /*
7702  * Let messages flow up into the mux by removing
7703  * the passq.
7704  */
7705 static void
7706 link_rempassthru(queue_t *passq)
7707 {
7708 	claimq(passq);
7709 	removeq(passq);
7710 	releaseq(passq);
7711 	freeq(passq);
7712 }
7713 
7714 /*
7715  * Wait for the condition variable pointed to by `cvp' to be signaled,
7716  * or for `tim' milliseconds to elapse, whichever comes first.  If `tim'
7717  * is negative, then there is no time limit.  If `nosigs' is non-zero,
7718  * then the wait will be non-interruptible.
7719  *
7720  * Returns >0 if signaled, 0 if interrupted, or -1 upon timeout.
7721  */
7722 clock_t
7723 str_cv_wait(kcondvar_t *cvp, kmutex_t *mp, clock_t tim, int nosigs)
7724 {
7725 	clock_t ret, now, tick;
7726 
7727 	if (tim < 0) {
7728 		if (nosigs) {
7729 			cv_wait(cvp, mp);
7730 			ret = 1;
7731 		} else {
7732 			ret = cv_wait_sig(cvp, mp);
7733 		}
7734 	} else if (tim > 0) {
7735 		/*
7736 		 * convert milliseconds to clock ticks
7737 		 */
7738 		tick = MSEC_TO_TICK_ROUNDUP(tim);
7739 		time_to_wait(&now, tick);
7740 		if (nosigs) {
7741 			ret = cv_timedwait(cvp, mp, now);
7742 		} else {
7743 			ret = cv_timedwait_sig(cvp, mp, now);
7744 		}
7745 	} else {
7746 		ret = -1;
7747 	}
7748 	return (ret);
7749 }
7750 
7751 /*
7752  * Wait until the stream head can determine if it is at the mark but
7753  * don't wait forever to prevent a race condition between the "mark" state
7754  * in the stream head and any mark state in the caller/user of this routine.
7755  *
7756  * This is used by sockets and for a socket it would be incorrect
7757  * to return a failure for SIOCATMARK when there is no data in the receive
7758  * queue and the marked urgent data is traveling up the stream.
7759  *
7760  * This routine waits until the mark is known by waiting for one of these
7761  * three events:
7762  *	The stream head read queue becoming non-empty (including an EOF)
7763  *	The STRATMARK flag being set. (Due to a MSGMARKNEXT message.)
7764  *	The STRNOTATMARK flag being set (which indicates that the transport
7765  *	has sent a MSGNOTMARKNEXT message to indicate that it is not at
7766  *	the mark).
7767  *
7768  * The routine returns 1 if the stream is at the mark; 0 if it can
7769  * be determined that the stream is not at the mark.
7770  * If the wait times out and it can't determine
7771  * whether or not the stream might be at the mark the routine will return -1.
7772  *
7773  * Note: This routine should only be used when a mark is pending i.e.,
7774  * in the socket case the SIGURG has been posted.
7775  * Note2: This can not wakeup just because synchronous streams indicate
7776  * that data is available since it is not possible to use the synchronous
7777  * streams interfaces to determine the b_flag value for the data queued below
7778  * the stream head.
7779  */
7780 int
7781 strwaitmark(vnode_t *vp)
7782 {
7783 	struct stdata *stp = vp->v_stream;
7784 	queue_t *rq = _RD(stp->sd_wrq);
7785 	int mark;
7786 
7787 	mutex_enter(&stp->sd_lock);
7788 	while (rq->q_first == NULL &&
7789 	    !(stp->sd_flag & (STRATMARK|STRNOTATMARK|STREOF))) {
7790 		stp->sd_flag |= RSLEEP;
7791 
7792 		/* Wait for 100 milliseconds for any state change. */
7793 		if (str_cv_wait(&rq->q_wait, &stp->sd_lock, 100, 1) == -1) {
7794 			mutex_exit(&stp->sd_lock);
7795 			return (-1);
7796 		}
7797 	}
7798 	if (stp->sd_flag & STRATMARK)
7799 		mark = 1;
7800 	else if (rq->q_first != NULL && (rq->q_first->b_flag & MSGMARK))
7801 		mark = 1;
7802 	else
7803 		mark = 0;
7804 
7805 	mutex_exit(&stp->sd_lock);
7806 	return (mark);
7807 }
7808 
7809 /*
7810  * Set a read side error. If persist is set change the socket error
7811  * to persistent. If errfunc is set install the function as the exported
7812  * error handler.
7813  */
7814 void
7815 strsetrerror(vnode_t *vp, int error, int persist, errfunc_t errfunc)
7816 {
7817 	struct stdata *stp = vp->v_stream;
7818 
7819 	mutex_enter(&stp->sd_lock);
7820 	stp->sd_rerror = error;
7821 	if (error == 0 && errfunc == NULL)
7822 		stp->sd_flag &= ~STRDERR;
7823 	else
7824 		stp->sd_flag |= STRDERR;
7825 	if (persist) {
7826 		stp->sd_flag &= ~STRDERRNONPERSIST;
7827 	} else {
7828 		stp->sd_flag |= STRDERRNONPERSIST;
7829 	}
7830 	stp->sd_rderrfunc = errfunc;
7831 	if (error != 0 || errfunc != NULL) {
7832 		cv_broadcast(&_RD(stp->sd_wrq)->q_wait);	/* readers */
7833 		cv_broadcast(&stp->sd_wrq->q_wait);		/* writers */
7834 		cv_broadcast(&stp->sd_monitor);			/* ioctllers */
7835 
7836 		mutex_exit(&stp->sd_lock);
7837 		pollwakeup(&stp->sd_pollist, POLLERR);
7838 		mutex_enter(&stp->sd_lock);
7839 
7840 		if (stp->sd_sigflags & S_ERROR)
7841 			strsendsig(stp->sd_siglist, S_ERROR, 0, error);
7842 	}
7843 	mutex_exit(&stp->sd_lock);
7844 }
7845 
7846 /*
7847  * Set a write side error. If persist is set change the socket error
7848  * to persistent.
7849  */
7850 void
7851 strsetwerror(vnode_t *vp, int error, int persist, errfunc_t errfunc)
7852 {
7853 	struct stdata *stp = vp->v_stream;
7854 
7855 	mutex_enter(&stp->sd_lock);
7856 	stp->sd_werror = error;
7857 	if (error == 0 && errfunc == NULL)
7858 		stp->sd_flag &= ~STWRERR;
7859 	else
7860 		stp->sd_flag |= STWRERR;
7861 	if (persist) {
7862 		stp->sd_flag &= ~STWRERRNONPERSIST;
7863 	} else {
7864 		stp->sd_flag |= STWRERRNONPERSIST;
7865 	}
7866 	stp->sd_wrerrfunc = errfunc;
7867 	if (error != 0 || errfunc != NULL) {
7868 		cv_broadcast(&_RD(stp->sd_wrq)->q_wait);	/* readers */
7869 		cv_broadcast(&stp->sd_wrq->q_wait);		/* writers */
7870 		cv_broadcast(&stp->sd_monitor);			/* ioctllers */
7871 
7872 		mutex_exit(&stp->sd_lock);
7873 		pollwakeup(&stp->sd_pollist, POLLERR);
7874 		mutex_enter(&stp->sd_lock);
7875 
7876 		if (stp->sd_sigflags & S_ERROR)
7877 			strsendsig(stp->sd_siglist, S_ERROR, 0, error);
7878 	}
7879 	mutex_exit(&stp->sd_lock);
7880 }
7881 
7882 /*
7883  * Make the stream return 0 (EOF) when all data has been read.
7884  * No effect on write side.
7885  */
7886 void
7887 strseteof(vnode_t *vp, int eof)
7888 {
7889 	struct stdata *stp = vp->v_stream;
7890 
7891 	mutex_enter(&stp->sd_lock);
7892 	if (!eof) {
7893 		stp->sd_flag &= ~STREOF;
7894 		mutex_exit(&stp->sd_lock);
7895 		return;
7896 	}
7897 	stp->sd_flag |= STREOF;
7898 	if (stp->sd_flag & RSLEEP) {
7899 		stp->sd_flag &= ~RSLEEP;
7900 		cv_broadcast(&_RD(stp->sd_wrq)->q_wait);
7901 	}
7902 
7903 	mutex_exit(&stp->sd_lock);
7904 	pollwakeup(&stp->sd_pollist, POLLIN|POLLRDNORM);
7905 	mutex_enter(&stp->sd_lock);
7906 
7907 	if (stp->sd_sigflags & (S_INPUT|S_RDNORM))
7908 		strsendsig(stp->sd_siglist, S_INPUT|S_RDNORM, 0, 0);
7909 	mutex_exit(&stp->sd_lock);
7910 }
7911 
7912 void
7913 strflushrq(vnode_t *vp, int flag)
7914 {
7915 	struct stdata *stp = vp->v_stream;
7916 
7917 	mutex_enter(&stp->sd_lock);
7918 	flushq(_RD(stp->sd_wrq), flag);
7919 	mutex_exit(&stp->sd_lock);
7920 }
7921 
7922 void
7923 strsetrputhooks(vnode_t *vp, uint_t flags,
7924 		msgfunc_t protofunc, msgfunc_t miscfunc)
7925 {
7926 	struct stdata *stp = vp->v_stream;
7927 
7928 	mutex_enter(&stp->sd_lock);
7929 
7930 	if (protofunc == NULL)
7931 		stp->sd_rprotofunc = strrput_proto;
7932 	else
7933 		stp->sd_rprotofunc = protofunc;
7934 
7935 	if (miscfunc == NULL)
7936 		stp->sd_rmiscfunc = strrput_misc;
7937 	else
7938 		stp->sd_rmiscfunc = miscfunc;
7939 
7940 	if (flags & SH_CONSOL_DATA)
7941 		stp->sd_rput_opt |= SR_CONSOL_DATA;
7942 	else
7943 		stp->sd_rput_opt &= ~SR_CONSOL_DATA;
7944 
7945 	if (flags & SH_SIGALLDATA)
7946 		stp->sd_rput_opt |= SR_SIGALLDATA;
7947 	else
7948 		stp->sd_rput_opt &= ~SR_SIGALLDATA;
7949 
7950 	if (flags & SH_IGN_ZEROLEN)
7951 		stp->sd_rput_opt |= SR_IGN_ZEROLEN;
7952 	else
7953 		stp->sd_rput_opt &= ~SR_IGN_ZEROLEN;
7954 
7955 	mutex_exit(&stp->sd_lock);
7956 }
7957 
7958 void
7959 strsetwputhooks(vnode_t *vp, uint_t flags, clock_t closetime)
7960 {
7961 	struct stdata *stp = vp->v_stream;
7962 
7963 	mutex_enter(&stp->sd_lock);
7964 	stp->sd_closetime = closetime;
7965 
7966 	if (flags & SH_SIGPIPE)
7967 		stp->sd_wput_opt |= SW_SIGPIPE;
7968 	else
7969 		stp->sd_wput_opt &= ~SW_SIGPIPE;
7970 	if (flags & SH_RECHECK_ERR)
7971 		stp->sd_wput_opt |= SW_RECHECK_ERR;
7972 	else
7973 		stp->sd_wput_opt &= ~SW_RECHECK_ERR;
7974 
7975 	mutex_exit(&stp->sd_lock);
7976 }
7977 
7978 /* Used within framework when the queue is already locked */
7979 void
7980 qenable_locked(queue_t *q)
7981 {
7982 	stdata_t *stp = STREAM(q);
7983 
7984 	ASSERT(MUTEX_HELD(QLOCK(q)));
7985 
7986 	if (!q->q_qinfo->qi_srvp)
7987 		return;
7988 
7989 	/*
7990 	 * Do not place on run queue if already enabled or closing.
7991 	 */
7992 	if (q->q_flag & (QWCLOSE|QENAB))
7993 		return;
7994 
7995 	/*
7996 	 * mark queue enabled and place on run list if it is not already being
7997 	 * serviced. If it is serviced, the runservice() function will detect
7998 	 * that QENAB is set and call service procedure before clearing
7999 	 * QINSERVICE flag.
8000 	 */
8001 	q->q_flag |= QENAB;
8002 	if (q->q_flag & QINSERVICE)
8003 		return;
8004 
8005 	/* Record the time of qenable */
8006 	q->q_qtstamp = lbolt;
8007 
8008 	/*
8009 	 * Put the queue in the stp list and schedule it for background
8010 	 * processing if it is not already scheduled or if stream head does not
8011 	 * intent to process it in the foreground later by setting
8012 	 * STRS_WILLSERVICE flag.
8013 	 */
8014 	mutex_enter(&stp->sd_qlock);
8015 	/*
8016 	 * If there are already something on the list, stp flags should show
8017 	 * intention to drain it.
8018 	 */
8019 	IMPLY(STREAM_NEEDSERVICE(stp),
8020 	    (stp->sd_svcflags & (STRS_WILLSERVICE | STRS_SCHEDULED)));
8021 
8022 	ENQUEUE(q, stp->sd_qhead, stp->sd_qtail, q_link);
8023 	stp->sd_nqueues++;
8024 
8025 	/*
8026 	 * If no one will drain this stream we are the first producer and
8027 	 * need to schedule it for background thread.
8028 	 */
8029 	if (!(stp->sd_svcflags & (STRS_WILLSERVICE | STRS_SCHEDULED))) {
8030 		/*
8031 		 * No one will service this stream later, so we have to
8032 		 * schedule it now.
8033 		 */
8034 		STRSTAT(stenables);
8035 		stp->sd_svcflags |= STRS_SCHEDULED;
8036 		stp->sd_servid = (void *)taskq_dispatch(streams_taskq,
8037 		    (task_func_t *)stream_service, stp, TQ_NOSLEEP|TQ_NOQUEUE);
8038 
8039 		if (stp->sd_servid == NULL) {
8040 			/*
8041 			 * Task queue failed so fail over to the backup
8042 			 * servicing thread.
8043 			 */
8044 			STRSTAT(taskqfails);
8045 			/*
8046 			 * It is safe to clear STRS_SCHEDULED flag because it
8047 			 * was set by this thread above.
8048 			 */
8049 			stp->sd_svcflags &= ~STRS_SCHEDULED;
8050 
8051 			/*
8052 			 * Failover scheduling is protected by service_queue
8053 			 * lock.
8054 			 */
8055 			mutex_enter(&service_queue);
8056 			ASSERT((stp->sd_qhead == q) && (stp->sd_qtail == q));
8057 			ASSERT(q->q_link == NULL);
8058 			/*
8059 			 * Append the queue to qhead/qtail list.
8060 			 */
8061 			if (qhead == NULL)
8062 				qhead = q;
8063 			else
8064 				qtail->q_link = q;
8065 			qtail = q;
8066 			/*
8067 			 * Clear stp queue list.
8068 			 */
8069 			stp->sd_qhead = stp->sd_qtail = NULL;
8070 			stp->sd_nqueues = 0;
8071 			/*
8072 			 * Wakeup background queue processing thread.
8073 			 */
8074 			cv_signal(&services_to_run);
8075 			mutex_exit(&service_queue);
8076 		}
8077 	}
8078 	mutex_exit(&stp->sd_qlock);
8079 }
8080 
8081 static void
8082 queue_service(queue_t *q)
8083 {
8084 	/*
8085 	 * The queue in the list should have
8086 	 * QENAB flag set and should not have
8087 	 * QINSERVICE flag set. QINSERVICE is
8088 	 * set when the queue is dequeued and
8089 	 * qenable_locked doesn't enqueue a
8090 	 * queue with QINSERVICE set.
8091 	 */
8092 
8093 	ASSERT(!(q->q_flag & QINSERVICE));
8094 	ASSERT((q->q_flag & QENAB));
8095 	mutex_enter(QLOCK(q));
8096 	q->q_flag &= ~QENAB;
8097 	q->q_flag |= QINSERVICE;
8098 	mutex_exit(QLOCK(q));
8099 	runservice(q);
8100 }
8101 
8102 static void
8103 syncq_service(syncq_t *sq)
8104 {
8105 	STRSTAT(syncqservice);
8106 	mutex_enter(SQLOCK(sq));
8107 	ASSERT(!(sq->sq_svcflags & SQ_SERVICE));
8108 	ASSERT(sq->sq_servcount != 0);
8109 	ASSERT(sq->sq_next == NULL);
8110 
8111 	/* if we came here from the background thread, clear the flag */
8112 	if (sq->sq_svcflags & SQ_BGTHREAD)
8113 		sq->sq_svcflags &= ~SQ_BGTHREAD;
8114 
8115 	/* let drain_syncq know that it's being called in the background */
8116 	sq->sq_svcflags |= SQ_SERVICE;
8117 	drain_syncq(sq);
8118 }
8119 
8120 static void
8121 qwriter_outer_service(syncq_t *outer)
8122 {
8123 	/*
8124 	 * Note that SQ_WRITER is used on the outer perimeter
8125 	 * to signal that a qwriter(OUTER) is either investigating
8126 	 * running or that it is actually running a function.
8127 	 */
8128 	outer_enter(outer, SQ_BLOCKED|SQ_WRITER);
8129 
8130 	/*
8131 	 * All inner syncq are empty and have SQ_WRITER set
8132 	 * to block entering the outer perimeter.
8133 	 *
8134 	 * We do not need to explicitly call write_now since
8135 	 * outer_exit does it for us.
8136 	 */
8137 	outer_exit(outer);
8138 }
8139 
8140 static void
8141 mblk_free(mblk_t *mp)
8142 {
8143 	dblk_t *dbp = mp->b_datap;
8144 	frtn_t *frp = dbp->db_frtnp;
8145 
8146 	mp->b_next = NULL;
8147 	if (dbp->db_fthdr != NULL)
8148 		str_ftfree(dbp);
8149 
8150 	ASSERT(dbp->db_fthdr == NULL);
8151 	frp->free_func(frp->free_arg);
8152 	ASSERT(dbp->db_mblk == mp);
8153 
8154 	if (dbp->db_credp != NULL) {
8155 		crfree(dbp->db_credp);
8156 		dbp->db_credp = NULL;
8157 	}
8158 	dbp->db_cpid = -1;
8159 	dbp->db_struioflag = 0;
8160 	dbp->db_struioun.cksum.flags = 0;
8161 
8162 	kmem_cache_free(dbp->db_cache, dbp);
8163 }
8164 
8165 /*
8166  * Background processing of the stream queue list.
8167  */
8168 static void
8169 stream_service(stdata_t *stp)
8170 {
8171 	queue_t *q;
8172 
8173 	mutex_enter(&stp->sd_qlock);
8174 
8175 	STR_SERVICE(stp, q);
8176 
8177 	stp->sd_svcflags &= ~STRS_SCHEDULED;
8178 	stp->sd_servid = NULL;
8179 	cv_signal(&stp->sd_qcv);
8180 	mutex_exit(&stp->sd_qlock);
8181 }
8182 
8183 /*
8184  * Foreground processing of the stream queue list.
8185  */
8186 void
8187 stream_runservice(stdata_t *stp)
8188 {
8189 	queue_t *q;
8190 
8191 	mutex_enter(&stp->sd_qlock);
8192 	STRSTAT(rservice);
8193 	/*
8194 	 * We are going to drain this stream queue list, so qenable_locked will
8195 	 * not schedule it until we finish.
8196 	 */
8197 	stp->sd_svcflags |= STRS_WILLSERVICE;
8198 
8199 	STR_SERVICE(stp, q);
8200 
8201 	stp->sd_svcflags &= ~STRS_WILLSERVICE;
8202 	mutex_exit(&stp->sd_qlock);
8203 	/*
8204 	 * Help backup background thread to drain the qhead/qtail list.
8205 	 */
8206 	while (qhead != NULL) {
8207 		STRSTAT(qhelps);
8208 		mutex_enter(&service_queue);
8209 		DQ(q, qhead, qtail, q_link);
8210 		mutex_exit(&service_queue);
8211 		if (q != NULL)
8212 			queue_service(q);
8213 	}
8214 }
8215 
8216 void
8217 stream_willservice(stdata_t *stp)
8218 {
8219 	mutex_enter(&stp->sd_qlock);
8220 	stp->sd_svcflags |= STRS_WILLSERVICE;
8221 	mutex_exit(&stp->sd_qlock);
8222 }
8223 
8224 /*
8225  * Replace the cred currently in the mblk with a different one.
8226  */
8227 void
8228 mblk_setcred(mblk_t *mp, cred_t *cr)
8229 {
8230 	cred_t *ocr = DB_CRED(mp);
8231 
8232 	ASSERT(cr != NULL);
8233 
8234 	if (cr != ocr) {
8235 		crhold(mp->b_datap->db_credp = cr);
8236 		if (ocr != NULL)
8237 			crfree(ocr);
8238 	}
8239 }
8240 
8241 int
8242 hcksum_assoc(mblk_t *mp,  multidata_t *mmd, pdesc_t *pd,
8243     uint32_t start, uint32_t stuff, uint32_t end, uint32_t value,
8244     uint32_t flags, int km_flags)
8245 {
8246 	int rc = 0;
8247 
8248 	ASSERT(DB_TYPE(mp) == M_DATA || DB_TYPE(mp) == M_MULTIDATA);
8249 	if (mp->b_datap->db_type == M_DATA) {
8250 		/* Associate values for M_DATA type */
8251 		DB_CKSUMSTART(mp) = (intptr_t)start;
8252 		DB_CKSUMSTUFF(mp) = (intptr_t)stuff;
8253 		DB_CKSUMEND(mp) = (intptr_t)end;
8254 		DB_CKSUMFLAGS(mp) = flags;
8255 		DB_CKSUM16(mp) = (uint16_t)value;
8256 
8257 	} else {
8258 		pattrinfo_t pa_info;
8259 
8260 		ASSERT(mmd != NULL);
8261 
8262 		pa_info.type = PATTR_HCKSUM;
8263 		pa_info.len = sizeof (pattr_hcksum_t);
8264 
8265 		if (mmd_addpattr(mmd, pd, &pa_info, B_TRUE, km_flags) != NULL) {
8266 			pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
8267 
8268 			hck->hcksum_start_offset = start;
8269 			hck->hcksum_stuff_offset = stuff;
8270 			hck->hcksum_end_offset = end;
8271 			hck->hcksum_cksum_val.inet_cksum = (uint16_t)value;
8272 			hck->hcksum_flags = flags;
8273 		} else {
8274 			rc = -1;
8275 		}
8276 	}
8277 	return (rc);
8278 }
8279 
8280 void
8281 hcksum_retrieve(mblk_t *mp, multidata_t *mmd, pdesc_t *pd,
8282     uint32_t *start, uint32_t *stuff, uint32_t *end,
8283     uint32_t *value, uint32_t *flags)
8284 {
8285 	ASSERT(DB_TYPE(mp) == M_DATA || DB_TYPE(mp) == M_MULTIDATA);
8286 	if (mp->b_datap->db_type == M_DATA) {
8287 		if (flags != NULL) {
8288 			*flags = DB_CKSUMFLAGS(mp);
8289 			if (*flags & HCK_PARTIALCKSUM) {
8290 				if (start != NULL)
8291 					*start = (uint32_t)DB_CKSUMSTART(mp);
8292 				if (stuff != NULL)
8293 					*stuff = (uint32_t)DB_CKSUMSTUFF(mp);
8294 				if (end != NULL)
8295 					*end = (uint32_t)DB_CKSUMEND(mp);
8296 				if (value != NULL)
8297 					*value = (uint32_t)DB_CKSUM16(mp);
8298 			}
8299 		}
8300 	} else {
8301 		pattrinfo_t hck_attr = {PATTR_HCKSUM};
8302 
8303 		ASSERT(mmd != NULL);
8304 
8305 		/* get hardware checksum attribute */
8306 		if (mmd_getpattr(mmd, pd, &hck_attr) != NULL) {
8307 			pattr_hcksum_t *hck = (pattr_hcksum_t *)hck_attr.buf;
8308 
8309 			ASSERT(hck_attr.len >= sizeof (pattr_hcksum_t));
8310 			if (flags != NULL)
8311 				*flags = hck->hcksum_flags;
8312 			if (start != NULL)
8313 				*start = hck->hcksum_start_offset;
8314 			if (stuff != NULL)
8315 				*stuff = hck->hcksum_stuff_offset;
8316 			if (end != NULL)
8317 				*end = hck->hcksum_end_offset;
8318 			if (value != NULL)
8319 				*value = (uint32_t)
8320 				    hck->hcksum_cksum_val.inet_cksum;
8321 		}
8322 	}
8323 }
8324 
8325 /*
8326  * Checksum buffer *bp for len bytes with psum partial checksum,
8327  * or 0 if none, and return the 16 bit partial checksum.
8328  */
8329 unsigned
8330 bcksum(uchar_t *bp, int len, unsigned int psum)
8331 {
8332 	int odd = len & 1;
8333 	extern unsigned int ip_ocsum();
8334 
8335 	if (((intptr_t)bp & 1) == 0 && !odd) {
8336 		/*
8337 		 * Bp is 16 bit aligned and len is multiple of 16 bit word.
8338 		 */
8339 		return (ip_ocsum((ushort_t *)bp, len >> 1, psum));
8340 	}
8341 	if (((intptr_t)bp & 1) != 0) {
8342 		/*
8343 		 * Bp isn't 16 bit aligned.
8344 		 */
8345 		unsigned int tsum;
8346 
8347 #ifdef _LITTLE_ENDIAN
8348 		psum += *bp;
8349 #else
8350 		psum += *bp << 8;
8351 #endif
8352 		len--;
8353 		bp++;
8354 		tsum = ip_ocsum((ushort_t *)bp, len >> 1, 0);
8355 		psum += (tsum << 8) & 0xffff | (tsum >> 8);
8356 		if (len & 1) {
8357 			bp += len - 1;
8358 #ifdef _LITTLE_ENDIAN
8359 			psum += *bp << 8;
8360 #else
8361 			psum += *bp;
8362 #endif
8363 		}
8364 	} else {
8365 		/*
8366 		 * Bp is 16 bit aligned.
8367 		 */
8368 		psum = ip_ocsum((ushort_t *)bp, len >> 1, psum);
8369 		if (odd) {
8370 			bp += len - 1;
8371 #ifdef _LITTLE_ENDIAN
8372 			psum += *bp;
8373 #else
8374 			psum += *bp << 8;
8375 #endif
8376 		}
8377 	}
8378 	/*
8379 	 * Normalize psum to 16 bits before returning the new partial
8380 	 * checksum. The max psum value before normalization is 0x3FDFE.
8381 	 */
8382 	return ((psum >> 16) + (psum & 0xFFFF));
8383 }
8384 
8385 boolean_t
8386 is_vmloaned_mblk(mblk_t *mp, multidata_t *mmd, pdesc_t *pd)
8387 {
8388 	boolean_t rc;
8389 
8390 	ASSERT(DB_TYPE(mp) == M_DATA || DB_TYPE(mp) == M_MULTIDATA);
8391 	if (DB_TYPE(mp) == M_DATA) {
8392 		rc = (((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0);
8393 	} else {
8394 		pattrinfo_t zcopy_attr = {PATTR_ZCOPY};
8395 
8396 		ASSERT(mmd != NULL);
8397 		rc = (mmd_getpattr(mmd, pd, &zcopy_attr) != NULL);
8398 	}
8399 	return (rc);
8400 }
8401 
8402 void
8403 freemsgchain(mblk_t *mp)
8404 {
8405 	mblk_t	*next;
8406 
8407 	while (mp != NULL) {
8408 		next = mp->b_next;
8409 		mp->b_next = NULL;
8410 
8411 		freemsg(mp);
8412 		mp = next;
8413 	}
8414 }
8415 
8416 mblk_t *
8417 copymsgchain(mblk_t *mp)
8418 {
8419 	mblk_t	*nmp = NULL;
8420 	mblk_t	**nmpp = &nmp;
8421 
8422 	for (; mp != NULL; mp = mp->b_next) {
8423 		if ((*nmpp = copymsg(mp)) == NULL) {
8424 			freemsgchain(nmp);
8425 			return (NULL);
8426 		}
8427 
8428 		nmpp = &((*nmpp)->b_next);
8429 	}
8430 
8431 	return (nmp);
8432 }
8433 
8434 /* NOTE: Do not add code after this point. */
8435 #undef QLOCK
8436 
8437 /*
8438  * replacement for QLOCK macro for those that can't use it.
8439  */
8440 kmutex_t *
8441 QLOCK(queue_t *q)
8442 {
8443 	return (&(q)->q_lock);
8444 }
8445 
8446 /*
8447  * Dummy runqueues/queuerun functions functions for backwards compatibility.
8448  */
8449 #undef runqueues
8450 void
8451 runqueues(void)
8452 {
8453 }
8454 
8455 #undef queuerun
8456 void
8457 queuerun(void)
8458 {
8459 }
8460