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