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