xref: /illumos-gate/usr/src/uts/common/os/streamio.c (revision ca9327a6de44d69ddab3668cc1e143ce781387a3)
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/stat.h>
38 #include <sys/proc.h>
39 #include <sys/cred.h>
40 #include <sys/user.h>
41 #include <sys/vnode.h>
42 #include <sys/file.h>
43 #include <sys/stream.h>
44 #include <sys/strsubr.h>
45 #include <sys/stropts.h>
46 #include <sys/tihdr.h>
47 #include <sys/var.h>
48 #include <sys/poll.h>
49 #include <sys/termio.h>
50 #include <sys/ttold.h>
51 #include <sys/systm.h>
52 #include <sys/uio.h>
53 #include <sys/cmn_err.h>
54 #include <sys/sad.h>
55 #include <sys/netstack.h>
56 #include <sys/priocntl.h>
57 #include <sys/jioctl.h>
58 #include <sys/procset.h>
59 #include <sys/session.h>
60 #include <sys/kmem.h>
61 #include <sys/filio.h>
62 #include <sys/vtrace.h>
63 #include <sys/debug.h>
64 #include <sys/strredir.h>
65 #include <sys/fs/fifonode.h>
66 #include <sys/fs/snode.h>
67 #include <sys/strlog.h>
68 #include <sys/strsun.h>
69 #include <sys/project.h>
70 #include <sys/kbio.h>
71 #include <sys/msio.h>
72 #include <sys/tty.h>
73 #include <sys/ptyvar.h>
74 #include <sys/vuid_event.h>
75 #include <sys/modctl.h>
76 #include <sys/sunddi.h>
77 #include <sys/sunldi_impl.h>
78 #include <sys/autoconf.h>
79 #include <sys/policy.h>
80 #include <sys/dld.h>
81 #include <sys/zone.h>
82 
83 /*
84  * This define helps improve the readability of streams code while
85  * still maintaining a very old streams performance enhancement.  The
86  * performance enhancement basically involved having all callers
87  * of straccess() perform the first check that straccess() will do
88  * locally before actually calling straccess().  (There by reducing
89  * the number of unnecessary calls to straccess().)
90  */
91 #define	i_straccess(x, y)	((stp->sd_sidp == NULL) ? 0 : \
92 				    (stp->sd_vnode->v_type == VFIFO) ? 0 : \
93 				    straccess((x), (y)))
94 
95 /*
96  * what is mblk_pull_len?
97  *
98  * If a streams message consists of many short messages,
99  * a performance degradation occurs from copyout overhead.
100  * To decrease the per mblk overhead, messages that are
101  * likely to consist of many small mblks are pulled up into
102  * one continuous chunk of memory.
103  *
104  * To avoid the processing overhead of examining every
105  * mblk, a quick heuristic is used. If the first mblk in
106  * the message is shorter than mblk_pull_len, it is likely
107  * that the rest of the mblk will be short.
108  *
109  * This heuristic was decided upon after performance tests
110  * indicated that anything more complex slowed down the main
111  * code path.
112  */
113 #define	MBLK_PULL_LEN 64
114 uint32_t mblk_pull_len = MBLK_PULL_LEN;
115 
116 /*
117  * The sgttyb_handling flag controls the handling of the old BSD
118  * TIOCGETP, TIOCSETP, and TIOCSETN ioctls as follows:
119  *
120  * 0 - Emit no warnings at all and retain old, broken behavior.
121  * 1 - Emit no warnings and silently handle new semantics.
122  * 2 - Send cmn_err(CE_NOTE) when either TIOCSETP or TIOCSETN is used
123  *     (once per system invocation).  Handle with new semantics.
124  * 3 - Send SIGSYS when any TIOCGETP, TIOCSETP, or TIOCSETN call is
125  *     made (so that offenders drop core and are easy to debug).
126  *
127  * The "new semantics" are that TIOCGETP returns B38400 for
128  * sg_[io]speed if the corresponding value is over B38400, and that
129  * TIOCSET[PN] accept B38400 in these cases to mean "retain current
130  * bit rate."
131  */
132 int sgttyb_handling = 1;
133 static boolean_t sgttyb_complaint;
134 
135 /* don't push drcompat module by default on Style-2 streams */
136 static int push_drcompat = 0;
137 
138 /*
139  * id value used to distinguish between different ioctl messages
140  */
141 static uint32_t ioc_id;
142 
143 static void putback(struct stdata *, queue_t *, mblk_t *, int);
144 static void strcleanall(struct vnode *);
145 static int strwsrv(queue_t *);
146 static int strdocmd(struct stdata *, struct strcmd *, cred_t *);
147 
148 /*
149  * qinit and module_info structures for stream head read and write queues
150  */
151 struct module_info strm_info = { 0, "strrhead", 0, INFPSZ, STRHIGH, STRLOW };
152 struct module_info stwm_info = { 0, "strwhead", 0, 0, 0, 0 };
153 struct qinit strdata = { strrput, NULL, NULL, NULL, NULL, &strm_info };
154 struct qinit stwdata = { NULL, strwsrv, NULL, NULL, NULL, &stwm_info };
155 struct module_info fiform_info = { 0, "fifostrrhead", 0, PIPE_BUF, FIFOHIWAT,
156     FIFOLOWAT };
157 struct module_info fifowm_info = { 0, "fifostrwhead", 0, 0, 0, 0 };
158 struct qinit fifo_strdata = { strrput, NULL, NULL, NULL, NULL, &fiform_info };
159 struct qinit fifo_stwdata = { NULL, strwsrv, NULL, NULL, NULL, &fifowm_info };
160 
161 extern kmutex_t	strresources;	/* protects global resources */
162 extern kmutex_t muxifier;	/* single-threads multiplexor creation */
163 
164 static boolean_t msghasdata(mblk_t *bp);
165 #define	msgnodata(bp) (!msghasdata(bp))
166 
167 /*
168  * Stream head locking notes:
169  *	There are four monitors associated with the stream head:
170  *	1. v_stream monitor: in stropen() and strclose() v_lock
171  *		is held while the association of vnode and stream
172  *		head is established or tested for.
173  *	2. open/close/push/pop monitor: sd_lock is held while each
174  *		thread bids for exclusive access to this monitor
175  *		for opening or closing a stream.  In addition, this
176  *		monitor is entered during pushes and pops.  This
177  *		guarantees that during plumbing operations there
178  *		is only one thread trying to change the plumbing.
179  *		Any other threads present in the stream are only
180  *		using the plumbing.
181  *	3. read/write monitor: in the case of read, a thread holds
182  *		sd_lock while trying to get data from the stream
183  *		head queue.  if there is none to fulfill a read
184  *		request, it sets RSLEEP and calls cv_wait_sig() down
185  *		in strwaitq() to await the arrival of new data.
186  *		when new data arrives in strrput(), sd_lock is acquired
187  *		before testing for RSLEEP and calling cv_broadcast().
188  *		the behavior of strwrite(), strwsrv(), and WSLEEP
189  *		mirror this.
190  *	4. ioctl monitor: sd_lock is gotten to ensure that only one
191  *		thread is doing an ioctl at a time.
192  */
193 
194 static int
195 push_mod(queue_t *qp, dev_t *devp, struct stdata *stp, const char *name,
196     int anchor, cred_t *crp, uint_t anchor_zoneid)
197 {
198 	int error;
199 	fmodsw_impl_t *fp;
200 
201 	if (stp->sd_flag & (STRHUP|STRDERR|STWRERR)) {
202 		error = (stp->sd_flag & STRHUP) ? ENXIO : EIO;
203 		return (error);
204 	}
205 	if (stp->sd_pushcnt >= nstrpush) {
206 		return (EINVAL);
207 	}
208 
209 	if ((fp = fmodsw_find(name, FMODSW_HOLD | FMODSW_LOAD)) == NULL) {
210 		stp->sd_flag |= STREOPENFAIL;
211 		return (EINVAL);
212 	}
213 
214 	/*
215 	 * push new module and call its open routine via qattach
216 	 */
217 	if ((error = qattach(qp, devp, 0, crp, fp, B_FALSE)) != 0)
218 		return (error);
219 
220 	/*
221 	 * Check to see if caller wants a STREAMS anchor
222 	 * put at this place in the stream, and add if so.
223 	 */
224 	mutex_enter(&stp->sd_lock);
225 	if (anchor == stp->sd_pushcnt) {
226 		stp->sd_anchor = stp->sd_pushcnt;
227 		stp->sd_anchorzone = anchor_zoneid;
228 	}
229 	mutex_exit(&stp->sd_lock);
230 
231 	return (0);
232 }
233 
234 /*
235  * Open a stream device.
236  */
237 int
238 stropen(vnode_t *vp, dev_t *devp, int flag, cred_t *crp)
239 {
240 	struct stdata *stp;
241 	queue_t *qp;
242 	int s;
243 	dev_t dummydev, savedev;
244 	struct autopush *ap;
245 	struct dlautopush dlap;
246 	int error = 0;
247 	ssize_t	rmin, rmax;
248 	int cloneopen;
249 	queue_t *brq;
250 	major_t major;
251 	str_stack_t *ss;
252 	zoneid_t zoneid;
253 	uint_t anchor;
254 
255 	if (audit_active)
256 		audit_stropen(vp, devp, flag, crp);
257 
258 	/*
259 	 * If the stream already exists, wait for any open in progress
260 	 * to complete, then call the open function of each module and
261 	 * driver in the stream.  Otherwise create the stream.
262 	 */
263 	TRACE_1(TR_FAC_STREAMS_FR, TR_STROPEN, "stropen:%p", vp);
264 retry:
265 	mutex_enter(&vp->v_lock);
266 	if ((stp = vp->v_stream) != NULL) {
267 
268 		/*
269 		 * Waiting for stream to be created to device
270 		 * due to another open.
271 		 */
272 		mutex_exit(&vp->v_lock);
273 
274 		if (STRMATED(stp)) {
275 			struct stdata *strmatep = stp->sd_mate;
276 
277 			STRLOCKMATES(stp);
278 			if (strmatep->sd_flag & (STWOPEN|STRCLOSE|STRPLUMB)) {
279 				if (flag & (FNDELAY|FNONBLOCK)) {
280 					error = EAGAIN;
281 					mutex_exit(&strmatep->sd_lock);
282 					goto ckreturn;
283 				}
284 				mutex_exit(&stp->sd_lock);
285 				if (!cv_wait_sig(&strmatep->sd_monitor,
286 				    &strmatep->sd_lock)) {
287 					error = EINTR;
288 					mutex_exit(&strmatep->sd_lock);
289 					mutex_enter(&stp->sd_lock);
290 					goto ckreturn;
291 				}
292 				mutex_exit(&strmatep->sd_lock);
293 				goto retry;
294 			}
295 			if (stp->sd_flag & (STWOPEN|STRCLOSE|STRPLUMB)) {
296 				if (flag & (FNDELAY|FNONBLOCK)) {
297 					error = EAGAIN;
298 					mutex_exit(&strmatep->sd_lock);
299 					goto ckreturn;
300 				}
301 				mutex_exit(&strmatep->sd_lock);
302 				if (!cv_wait_sig(&stp->sd_monitor,
303 				    &stp->sd_lock)) {
304 					error = EINTR;
305 					goto ckreturn;
306 				}
307 				mutex_exit(&stp->sd_lock);
308 				goto retry;
309 			}
310 
311 			if (stp->sd_flag & (STRDERR|STWRERR)) {
312 				error = EIO;
313 				mutex_exit(&strmatep->sd_lock);
314 				goto ckreturn;
315 			}
316 
317 			stp->sd_flag |= STWOPEN;
318 			STRUNLOCKMATES(stp);
319 		} else {
320 			mutex_enter(&stp->sd_lock);
321 			if (stp->sd_flag & (STWOPEN|STRCLOSE|STRPLUMB)) {
322 				if (flag & (FNDELAY|FNONBLOCK)) {
323 					error = EAGAIN;
324 					goto ckreturn;
325 				}
326 				if (!cv_wait_sig(&stp->sd_monitor,
327 				    &stp->sd_lock)) {
328 					error = EINTR;
329 					goto ckreturn;
330 				}
331 				mutex_exit(&stp->sd_lock);
332 				goto retry;  /* could be clone! */
333 			}
334 
335 			if (stp->sd_flag & (STRDERR|STWRERR)) {
336 				error = EIO;
337 				goto ckreturn;
338 			}
339 
340 			stp->sd_flag |= STWOPEN;
341 			mutex_exit(&stp->sd_lock);
342 		}
343 
344 		/*
345 		 * Open all modules and devices down stream to notify
346 		 * that another user is streaming.  For modules, set the
347 		 * last argument to MODOPEN and do not pass any open flags.
348 		 * Ignore dummydev since this is not the first open.
349 		 */
350 		claimstr(stp->sd_wrq);
351 		qp = stp->sd_wrq;
352 		while (_SAMESTR(qp)) {
353 			qp = qp->q_next;
354 			if ((error = qreopen(_RD(qp), devp, flag, crp)) != 0)
355 				break;
356 		}
357 		releasestr(stp->sd_wrq);
358 		mutex_enter(&stp->sd_lock);
359 		stp->sd_flag &= ~(STRHUP|STWOPEN|STRDERR|STWRERR);
360 		stp->sd_rerror = 0;
361 		stp->sd_werror = 0;
362 ckreturn:
363 		cv_broadcast(&stp->sd_monitor);
364 		mutex_exit(&stp->sd_lock);
365 		return (error);
366 	}
367 
368 	/*
369 	 * This vnode isn't streaming.  SPECFS already
370 	 * checked for multiple vnodes pointing to the
371 	 * same stream, so create a stream to the driver.
372 	 */
373 	qp = allocq();
374 	stp = shalloc(qp);
375 
376 	/*
377 	 * Initialize stream head.  shalloc() has given us
378 	 * exclusive access, and we have the vnode locked;
379 	 * we can do whatever we want with stp.
380 	 */
381 	stp->sd_flag = STWOPEN;
382 	stp->sd_siglist = NULL;
383 	stp->sd_pollist.ph_list = NULL;
384 	stp->sd_sigflags = 0;
385 	stp->sd_mark = NULL;
386 	stp->sd_closetime = STRTIMOUT;
387 	stp->sd_sidp = NULL;
388 	stp->sd_pgidp = NULL;
389 	stp->sd_vnode = vp;
390 	stp->sd_rerror = 0;
391 	stp->sd_werror = 0;
392 	stp->sd_wroff = 0;
393 	stp->sd_tail = 0;
394 	stp->sd_iocblk = NULL;
395 	stp->sd_cmdblk = NULL;
396 	stp->sd_pushcnt = 0;
397 	stp->sd_qn_minpsz = 0;
398 	stp->sd_qn_maxpsz = INFPSZ - 1;	/* used to check for initialization */
399 	stp->sd_maxblk = INFPSZ;
400 	qp->q_ptr = _WR(qp)->q_ptr = stp;
401 	STREAM(qp) = STREAM(_WR(qp)) = stp;
402 	vp->v_stream = stp;
403 	mutex_exit(&vp->v_lock);
404 	if (vp->v_type == VFIFO) {
405 		stp->sd_flag |= OLDNDELAY;
406 		/*
407 		 * This means, both for pipes and fifos
408 		 * strwrite will send SIGPIPE if the other
409 		 * end is closed. For putmsg it depends
410 		 * on whether it is a XPG4_2 application
411 		 * or not
412 		 */
413 		stp->sd_wput_opt = SW_SIGPIPE;
414 
415 		/* setq might sleep in kmem_alloc - avoid holding locks. */
416 		setq(qp, &fifo_strdata, &fifo_stwdata, NULL, QMTSAFE,
417 		    SQ_CI|SQ_CO, B_FALSE);
418 
419 		set_qend(qp);
420 		stp->sd_strtab = fifo_getinfo();
421 		_WR(qp)->q_nfsrv = _WR(qp);
422 		qp->q_nfsrv = qp;
423 		/*
424 		 * Wake up others that are waiting for stream to be created.
425 		 */
426 		mutex_enter(&stp->sd_lock);
427 		/*
428 		 * nothing is be pushed on stream yet, so
429 		 * optimized stream head packetsizes are just that
430 		 * of the read queue
431 		 */
432 		stp->sd_qn_minpsz = qp->q_minpsz;
433 		stp->sd_qn_maxpsz = qp->q_maxpsz;
434 		stp->sd_flag &= ~STWOPEN;
435 		goto fifo_opendone;
436 	}
437 	/* setq might sleep in kmem_alloc - avoid holding locks. */
438 	setq(qp, &strdata, &stwdata, NULL, QMTSAFE, SQ_CI|SQ_CO, B_FALSE);
439 
440 	set_qend(qp);
441 
442 	/*
443 	 * Open driver and create stream to it (via qattach).
444 	 */
445 	savedev = *devp;
446 	cloneopen = (getmajor(*devp) == clone_major);
447 	if ((error = qattach(qp, devp, flag, crp, NULL, B_FALSE)) != 0) {
448 		mutex_enter(&vp->v_lock);
449 		vp->v_stream = NULL;
450 		mutex_exit(&vp->v_lock);
451 		mutex_enter(&stp->sd_lock);
452 		cv_broadcast(&stp->sd_monitor);
453 		mutex_exit(&stp->sd_lock);
454 		freeq(_RD(qp));
455 		shfree(stp);
456 		return (error);
457 	}
458 	/*
459 	 * Set sd_strtab after open in order to handle clonable drivers
460 	 */
461 	stp->sd_strtab = STREAMSTAB(getmajor(*devp));
462 
463 	/*
464 	 * Historical note: dummydev used to be be prior to the initial
465 	 * open (via qattach above), which made the value seen
466 	 * inconsistent between an I_PUSH and an autopush of a module.
467 	 */
468 	dummydev = *devp;
469 
470 	/*
471 	 * For clone open of old style (Q not associated) network driver,
472 	 * push DRMODNAME module to handle DL_ATTACH/DL_DETACH
473 	 */
474 	brq = _RD(_WR(qp)->q_next);
475 	major = getmajor(*devp);
476 	if (push_drcompat && cloneopen && NETWORK_DRV(major) &&
477 	    ((brq->q_flag & _QASSOCIATED) == 0)) {
478 		if (push_mod(qp, &dummydev, stp, DRMODNAME, 0, crp, 0) != 0)
479 			cmn_err(CE_WARN, "cannot push " DRMODNAME
480 			    " streams module");
481 	}
482 
483 	if (!NETWORK_DRV(major)) {
484 		savedev = *devp;
485 	} else {
486 		/*
487 		 * For network devices, process differently based on the
488 		 * return value from dld_autopush():
489 		 *
490 		 *   0: the passed-in device points to a GLDv3 datalink with
491 		 *   per-link autopush configuration; use that configuration
492 		 *   and ignore any per-driver autopush configuration.
493 		 *
494 		 *   1: the passed-in device points to a physical GLDv3
495 		 *   datalink without per-link autopush configuration.  The
496 		 *   passed in device was changed to refer to the actual
497 		 *   physical device (if it's not already); we use that new
498 		 *   device to look up any per-driver autopush configuration.
499 		 *
500 		 *   -1: neither of the above cases applied; use the initial
501 		 *   device to look up any per-driver autopush configuration.
502 		 */
503 		switch (dld_autopush(&savedev, &dlap)) {
504 		case 0:
505 			zoneid = crgetzoneid(crp);
506 			for (s = 0; s < dlap.dap_npush; s++) {
507 				error = push_mod(qp, &dummydev, stp,
508 				    dlap.dap_aplist[s], dlap.dap_anchor, crp,
509 				    zoneid);
510 				if (error != 0)
511 					break;
512 			}
513 			goto opendone;
514 		case 1:
515 			break;
516 		case -1:
517 			savedev = *devp;
518 			break;
519 		}
520 	}
521 	/*
522 	 * Find the autopush configuration based on "savedev". Start with the
523 	 * global zone. If not found check in the local zone.
524 	 */
525 	zoneid = GLOBAL_ZONEID;
526 retryap:
527 	ss = netstack_find_by_stackid(zoneid_to_netstackid(zoneid))->
528 	    netstack_str;
529 	if ((ap = sad_ap_find_by_dev(savedev, ss)) == NULL) {
530 		netstack_rele(ss->ss_netstack);
531 		if (zoneid == GLOBAL_ZONEID) {
532 			/*
533 			 * None found. Also look in the zone's autopush table.
534 			 */
535 			zoneid = crgetzoneid(crp);
536 			if (zoneid != GLOBAL_ZONEID)
537 				goto retryap;
538 		}
539 		goto opendone;
540 	}
541 	anchor = ap->ap_anchor;
542 	zoneid = crgetzoneid(crp);
543 	for (s = 0; s < ap->ap_npush; s++) {
544 		error = push_mod(qp, &dummydev, stp, ap->ap_list[s],
545 		    anchor, crp, zoneid);
546 		if (error != 0)
547 			break;
548 	}
549 	sad_ap_rele(ap, ss);
550 	netstack_rele(ss->ss_netstack);
551 
552 opendone:
553 
554 	/*
555 	 * let specfs know that open failed part way through
556 	 */
557 	if (error) {
558 		mutex_enter(&stp->sd_lock);
559 		stp->sd_flag |= STREOPENFAIL;
560 		mutex_exit(&stp->sd_lock);
561 	}
562 
563 	/*
564 	 * Wake up others that are waiting for stream to be created.
565 	 */
566 	mutex_enter(&stp->sd_lock);
567 	stp->sd_flag &= ~STWOPEN;
568 
569 	/*
570 	 * As a performance concern we are caching the values of
571 	 * q_minpsz and q_maxpsz of the module below the stream
572 	 * head in the stream head.
573 	 */
574 	mutex_enter(QLOCK(stp->sd_wrq->q_next));
575 	rmin = stp->sd_wrq->q_next->q_minpsz;
576 	rmax = stp->sd_wrq->q_next->q_maxpsz;
577 	mutex_exit(QLOCK(stp->sd_wrq->q_next));
578 
579 	/* do this processing here as a performance concern */
580 	if (strmsgsz != 0) {
581 		if (rmax == INFPSZ)
582 			rmax = strmsgsz;
583 		else
584 			rmax = MIN(strmsgsz, rmax);
585 	}
586 
587 	mutex_enter(QLOCK(stp->sd_wrq));
588 	stp->sd_qn_minpsz = rmin;
589 	stp->sd_qn_maxpsz = rmax;
590 	mutex_exit(QLOCK(stp->sd_wrq));
591 
592 fifo_opendone:
593 	cv_broadcast(&stp->sd_monitor);
594 	mutex_exit(&stp->sd_lock);
595 	return (error);
596 }
597 
598 static int strsink(queue_t *, mblk_t *);
599 static struct qinit deadrend = {
600 	strsink, NULL, NULL, NULL, NULL, &strm_info, NULL
601 };
602 static struct qinit deadwend = {
603 	NULL, NULL, NULL, NULL, NULL, &stwm_info, NULL
604 };
605 
606 /*
607  * Close a stream.
608  * This is called from closef() on the last close of an open stream.
609  * Strclean() will already have removed the siglist and pollist
610  * information, so all that remains is to remove all multiplexor links
611  * for the stream, pop all the modules (and the driver), and free the
612  * stream structure.
613  */
614 
615 int
616 strclose(struct vnode *vp, int flag, cred_t *crp)
617 {
618 	struct stdata *stp;
619 	queue_t *qp;
620 	int rval;
621 	int freestp = 1;
622 	queue_t *rmq;
623 
624 	if (audit_active)
625 		audit_strclose(vp, flag, crp);
626 
627 	TRACE_1(TR_FAC_STREAMS_FR,
628 	    TR_STRCLOSE, "strclose:%p", vp);
629 	ASSERT(vp->v_stream);
630 
631 	stp = vp->v_stream;
632 	ASSERT(!(stp->sd_flag & STPLEX));
633 	qp = stp->sd_wrq;
634 
635 	/*
636 	 * Needed so that strpoll will return non-zero for this fd.
637 	 * Note that with POLLNOERR STRHUP does still cause POLLHUP.
638 	 */
639 	mutex_enter(&stp->sd_lock);
640 	stp->sd_flag |= STRHUP;
641 	mutex_exit(&stp->sd_lock);
642 
643 	/*
644 	 * If the registered process or process group did not have an
645 	 * open instance of this stream then strclean would not be
646 	 * called. Thus at the time of closing all remaining siglist entries
647 	 * are removed.
648 	 */
649 	if (stp->sd_siglist != NULL)
650 		strcleanall(vp);
651 
652 	ASSERT(stp->sd_siglist == NULL);
653 	ASSERT(stp->sd_sigflags == 0);
654 
655 	if (STRMATED(stp)) {
656 		struct stdata *strmatep = stp->sd_mate;
657 		int waited = 1;
658 
659 		STRLOCKMATES(stp);
660 		while (waited) {
661 			waited = 0;
662 			while (stp->sd_flag & (STWOPEN|STRCLOSE|STRPLUMB)) {
663 				mutex_exit(&strmatep->sd_lock);
664 				cv_wait(&stp->sd_monitor, &stp->sd_lock);
665 				mutex_exit(&stp->sd_lock);
666 				STRLOCKMATES(stp);
667 				waited = 1;
668 			}
669 			while (strmatep->sd_flag &
670 			    (STWOPEN|STRCLOSE|STRPLUMB)) {
671 				mutex_exit(&stp->sd_lock);
672 				cv_wait(&strmatep->sd_monitor,
673 				    &strmatep->sd_lock);
674 				mutex_exit(&strmatep->sd_lock);
675 				STRLOCKMATES(stp);
676 				waited = 1;
677 			}
678 		}
679 		stp->sd_flag |= STRCLOSE;
680 		STRUNLOCKMATES(stp);
681 	} else {
682 		mutex_enter(&stp->sd_lock);
683 		stp->sd_flag |= STRCLOSE;
684 		mutex_exit(&stp->sd_lock);
685 	}
686 
687 	ASSERT(qp->q_first == NULL);	/* No more delayed write */
688 
689 	/* Check if an I_LINK was ever done on this stream */
690 	if (stp->sd_flag & STRHASLINKS) {
691 		netstack_t *ns;
692 		str_stack_t *ss;
693 
694 		ns = netstack_find_by_cred(crp);
695 		ASSERT(ns != NULL);
696 		ss = ns->netstack_str;
697 		ASSERT(ss != NULL);
698 
699 		(void) munlinkall(stp, LINKCLOSE|LINKNORMAL, crp, &rval, ss);
700 		netstack_rele(ss->ss_netstack);
701 	}
702 
703 	while (_SAMESTR(qp)) {
704 		/*
705 		 * Holding sd_lock prevents q_next from changing in
706 		 * this stream.
707 		 */
708 		mutex_enter(&stp->sd_lock);
709 		if (!(flag & (FNDELAY|FNONBLOCK)) && (stp->sd_closetime > 0)) {
710 
711 			/*
712 			 * sleep until awakened by strwsrv() or timeout
713 			 */
714 			for (;;) {
715 				mutex_enter(QLOCK(qp->q_next));
716 				if (!(qp->q_next->q_mblkcnt)) {
717 					mutex_exit(QLOCK(qp->q_next));
718 					break;
719 				}
720 				stp->sd_flag |= WSLEEP;
721 
722 				/* ensure strwsrv gets enabled */
723 				qp->q_next->q_flag |= QWANTW;
724 				mutex_exit(QLOCK(qp->q_next));
725 				/* get out if we timed out or recv'd a signal */
726 				if (str_cv_wait(&qp->q_wait, &stp->sd_lock,
727 				    stp->sd_closetime, 0) <= 0) {
728 					break;
729 				}
730 			}
731 			stp->sd_flag &= ~WSLEEP;
732 		}
733 		mutex_exit(&stp->sd_lock);
734 
735 		rmq = qp->q_next;
736 		if (rmq->q_flag & QISDRV) {
737 			ASSERT(!_SAMESTR(rmq));
738 			wait_sq_svc(_RD(qp)->q_syncq);
739 		}
740 
741 		qdetach(_RD(rmq), 1, flag, crp, B_FALSE);
742 	}
743 
744 	/*
745 	 * Since we call pollwakeup in close() now, the poll list should
746 	 * be empty in most cases. The only exception is the layered devices
747 	 * (e.g. the console drivers with redirection modules pushed on top
748 	 * of it).  We have to do this after calling qdetach() because
749 	 * the redirection module won't have torn down the console
750 	 * redirection until after qdetach() has been invoked.
751 	 */
752 	if (stp->sd_pollist.ph_list != NULL) {
753 		pollwakeup(&stp->sd_pollist, POLLERR);
754 		pollhead_clean(&stp->sd_pollist);
755 	}
756 	ASSERT(stp->sd_pollist.ph_list == NULL);
757 	ASSERT(stp->sd_sidp == NULL);
758 	ASSERT(stp->sd_pgidp == NULL);
759 
760 	/* Prevent qenable from re-enabling the stream head queue */
761 	disable_svc(_RD(qp));
762 
763 	/*
764 	 * Wait until service procedure of each queue is
765 	 * run, if QINSERVICE is set.
766 	 */
767 	wait_svc(_RD(qp));
768 
769 	/*
770 	 * Now, flush both queues.
771 	 */
772 	flushq(_RD(qp), FLUSHALL);
773 	flushq(qp, FLUSHALL);
774 
775 	/*
776 	 * If the write queue of the stream head is pointing to a
777 	 * read queue, we have a twisted stream.  If the read queue
778 	 * is alive, convert the stream head queues into a dead end.
779 	 * If the read queue is dead, free the dead pair.
780 	 */
781 	if (qp->q_next && !_SAMESTR(qp)) {
782 		if (qp->q_next->q_qinfo == &deadrend) {	/* half-closed pipe */
783 			flushq(qp->q_next, FLUSHALL); /* ensure no message */
784 			shfree(qp->q_next->q_stream);
785 			freeq(qp->q_next);
786 			freeq(_RD(qp));
787 		} else if (qp->q_next == _RD(qp)) {	/* fifo */
788 			freeq(_RD(qp));
789 		} else {				/* pipe */
790 			freestp = 0;
791 			/*
792 			 * The q_info pointers are never accessed when
793 			 * SQLOCK is held.
794 			 */
795 			ASSERT(qp->q_syncq == _RD(qp)->q_syncq);
796 			mutex_enter(SQLOCK(qp->q_syncq));
797 			qp->q_qinfo = &deadwend;
798 			_RD(qp)->q_qinfo = &deadrend;
799 			mutex_exit(SQLOCK(qp->q_syncq));
800 		}
801 	} else {
802 		freeq(_RD(qp)); /* free stream head queue pair */
803 	}
804 
805 	mutex_enter(&vp->v_lock);
806 	if (stp->sd_iocblk) {
807 		if (stp->sd_iocblk != (mblk_t *)-1) {
808 			freemsg(stp->sd_iocblk);
809 		}
810 		stp->sd_iocblk = NULL;
811 	}
812 	stp->sd_vnode = NULL;
813 	vp->v_stream = NULL;
814 	mutex_exit(&vp->v_lock);
815 	mutex_enter(&stp->sd_lock);
816 	freemsg(stp->sd_cmdblk);
817 	stp->sd_cmdblk = NULL;
818 	stp->sd_flag &= ~STRCLOSE;
819 	cv_broadcast(&stp->sd_monitor);
820 	mutex_exit(&stp->sd_lock);
821 
822 	if (freestp)
823 		shfree(stp);
824 	return (0);
825 }
826 
827 static int
828 strsink(queue_t *q, mblk_t *bp)
829 {
830 	struct copyresp *resp;
831 
832 	switch (bp->b_datap->db_type) {
833 	case M_FLUSH:
834 		if ((*bp->b_rptr & FLUSHW) && !(bp->b_flag & MSGNOLOOP)) {
835 			*bp->b_rptr &= ~FLUSHR;
836 			bp->b_flag |= MSGNOLOOP;
837 			/*
838 			 * Protect against the driver passing up
839 			 * messages after it has done a qprocsoff.
840 			 */
841 			if (_OTHERQ(q)->q_next == NULL)
842 				freemsg(bp);
843 			else
844 				qreply(q, bp);
845 		} else {
846 			freemsg(bp);
847 		}
848 		break;
849 
850 	case M_COPYIN:
851 	case M_COPYOUT:
852 		if (bp->b_cont) {
853 			freemsg(bp->b_cont);
854 			bp->b_cont = NULL;
855 		}
856 		bp->b_datap->db_type = M_IOCDATA;
857 		bp->b_wptr = bp->b_rptr + sizeof (struct copyresp);
858 		resp = (struct copyresp *)bp->b_rptr;
859 		resp->cp_rval = (caddr_t)1;	/* failure */
860 		/*
861 		 * Protect against the driver passing up
862 		 * messages after it has done a qprocsoff.
863 		 */
864 		if (_OTHERQ(q)->q_next == NULL)
865 			freemsg(bp);
866 		else
867 			qreply(q, bp);
868 		break;
869 
870 	case M_IOCTL:
871 		if (bp->b_cont) {
872 			freemsg(bp->b_cont);
873 			bp->b_cont = NULL;
874 		}
875 		bp->b_datap->db_type = M_IOCNAK;
876 		/*
877 		 * Protect against the driver passing up
878 		 * messages after it has done a qprocsoff.
879 		 */
880 		if (_OTHERQ(q)->q_next == NULL)
881 			freemsg(bp);
882 		else
883 			qreply(q, bp);
884 		break;
885 
886 	default:
887 		freemsg(bp);
888 		break;
889 	}
890 
891 	return (0);
892 }
893 
894 /*
895  * Clean up after a process when it closes a stream.  This is called
896  * from closef for all closes, whereas strclose is called only for the
897  * last close on a stream.  The siglist is scanned for entries for the
898  * current process, and these are removed.
899  */
900 void
901 strclean(struct vnode *vp)
902 {
903 	strsig_t *ssp, *pssp, *tssp;
904 	stdata_t *stp;
905 	int update = 0;
906 
907 	TRACE_1(TR_FAC_STREAMS_FR,
908 	    TR_STRCLEAN, "strclean:%p", vp);
909 	stp = vp->v_stream;
910 	pssp = NULL;
911 	mutex_enter(&stp->sd_lock);
912 	ssp = stp->sd_siglist;
913 	while (ssp) {
914 		if (ssp->ss_pidp == curproc->p_pidp) {
915 			tssp = ssp->ss_next;
916 			if (pssp)
917 				pssp->ss_next = tssp;
918 			else
919 				stp->sd_siglist = tssp;
920 			mutex_enter(&pidlock);
921 			PID_RELE(ssp->ss_pidp);
922 			mutex_exit(&pidlock);
923 			kmem_free(ssp, sizeof (strsig_t));
924 			update = 1;
925 			ssp = tssp;
926 		} else {
927 			pssp = ssp;
928 			ssp = ssp->ss_next;
929 		}
930 	}
931 	if (update) {
932 		stp->sd_sigflags = 0;
933 		for (ssp = stp->sd_siglist; ssp; ssp = ssp->ss_next)
934 			stp->sd_sigflags |= ssp->ss_events;
935 	}
936 	mutex_exit(&stp->sd_lock);
937 }
938 
939 /*
940  * Used on the last close to remove any remaining items on the siglist.
941  * These could be present on the siglist due to I_ESETSIG calls that
942  * use process groups or processed that do not have an open file descriptor
943  * for this stream (Such entries would not be removed by strclean).
944  */
945 static void
946 strcleanall(struct vnode *vp)
947 {
948 	strsig_t *ssp, *nssp;
949 	stdata_t *stp;
950 
951 	stp = vp->v_stream;
952 	mutex_enter(&stp->sd_lock);
953 	ssp = stp->sd_siglist;
954 	stp->sd_siglist = NULL;
955 	while (ssp) {
956 		nssp = ssp->ss_next;
957 		mutex_enter(&pidlock);
958 		PID_RELE(ssp->ss_pidp);
959 		mutex_exit(&pidlock);
960 		kmem_free(ssp, sizeof (strsig_t));
961 		ssp = nssp;
962 	}
963 	stp->sd_sigflags = 0;
964 	mutex_exit(&stp->sd_lock);
965 }
966 
967 /*
968  * Retrieve the next message from the logical stream head read queue
969  * using either rwnext (if sync stream) or getq_noenab.
970  * It is the callers responsibility to call qbackenable after
971  * it is finished with the message. The caller should not call
972  * qbackenable until after any putback calls to avoid spurious backenabling.
973  */
974 mblk_t *
975 strget(struct stdata *stp, queue_t *q, struct uio *uiop, int first,
976     int *errorp)
977 {
978 	mblk_t *bp;
979 	int error;
980 
981 	ASSERT(MUTEX_HELD(&stp->sd_lock));
982 	/* Holding sd_lock prevents the read queue from changing  */
983 
984 	if (uiop != NULL && stp->sd_struiordq != NULL &&
985 	    q->q_first == NULL &&
986 	    (!first || (stp->sd_wakeq & RSLEEP))) {
987 		/*
988 		 * Stream supports rwnext() for the read side.
989 		 * If this is the first time we're called by e.g. strread
990 		 * only do the downcall if there is a deferred wakeup
991 		 * (registered in sd_wakeq).
992 		 */
993 		struiod_t uiod;
994 
995 		if (first)
996 			stp->sd_wakeq &= ~RSLEEP;
997 
998 		(void) uiodup(uiop, &uiod.d_uio, uiod.d_iov,
999 		    sizeof (uiod.d_iov) / sizeof (*uiod.d_iov));
1000 		uiod.d_mp = 0;
1001 		/*
1002 		 * Mark that a thread is in rwnext on the read side
1003 		 * to prevent strrput from nacking ioctls immediately.
1004 		 * When the last concurrent rwnext returns
1005 		 * the ioctls are nack'ed.
1006 		 */
1007 		ASSERT(MUTEX_HELD(&stp->sd_lock));
1008 		stp->sd_struiodnak++;
1009 		/*
1010 		 * Note: rwnext will drop sd_lock.
1011 		 */
1012 		error = rwnext(q, &uiod);
1013 		ASSERT(MUTEX_NOT_HELD(&stp->sd_lock));
1014 		mutex_enter(&stp->sd_lock);
1015 		stp->sd_struiodnak--;
1016 		while (stp->sd_struiodnak == 0 &&
1017 		    ((bp = stp->sd_struionak) != NULL)) {
1018 			stp->sd_struionak = bp->b_next;
1019 			bp->b_next = NULL;
1020 			bp->b_datap->db_type = M_IOCNAK;
1021 			/*
1022 			 * Protect against the driver passing up
1023 			 * messages after it has done a qprocsoff.
1024 			 */
1025 			if (_OTHERQ(q)->q_next == NULL)
1026 				freemsg(bp);
1027 			else {
1028 				mutex_exit(&stp->sd_lock);
1029 				qreply(q, bp);
1030 				mutex_enter(&stp->sd_lock);
1031 			}
1032 		}
1033 		ASSERT(MUTEX_HELD(&stp->sd_lock));
1034 		if (error == 0 || error == EWOULDBLOCK) {
1035 			if ((bp = uiod.d_mp) != NULL) {
1036 				*errorp = 0;
1037 				ASSERT(MUTEX_HELD(&stp->sd_lock));
1038 				return (bp);
1039 			}
1040 			error = 0;
1041 		} else if (error == EINVAL) {
1042 			/*
1043 			 * The stream plumbing must have
1044 			 * changed while we were away, so
1045 			 * just turn off rwnext()s.
1046 			 */
1047 			error = 0;
1048 		} else if (error == EBUSY) {
1049 			/*
1050 			 * The module might have data in transit using putnext
1051 			 * Fall back on waiting + getq.
1052 			 */
1053 			error = 0;
1054 		} else {
1055 			*errorp = error;
1056 			ASSERT(MUTEX_HELD(&stp->sd_lock));
1057 			return (NULL);
1058 		}
1059 		/*
1060 		 * Try a getq in case a rwnext() generated mblk
1061 		 * has bubbled up via strrput().
1062 		 */
1063 	}
1064 	*errorp = 0;
1065 	ASSERT(MUTEX_HELD(&stp->sd_lock));
1066 	return (getq_noenab(q));
1067 }
1068 
1069 /*
1070  * Copy out the message pointed to by `bp' into the uio pointed to by `uiop'.
1071  * If the message does not fit in the uio the remainder of it is returned;
1072  * otherwise NULL is returned.  Any embedded zero-length mblk_t's are
1073  * consumed, even if uio_resid reaches zero.  On error, `*errorp' is set to
1074  * the error code, the message is consumed, and NULL is returned.
1075  */
1076 static mblk_t *
1077 struiocopyout(mblk_t *bp, struct uio *uiop, int *errorp)
1078 {
1079 	int error;
1080 	ptrdiff_t n;
1081 	mblk_t *nbp;
1082 
1083 	ASSERT(bp->b_wptr >= bp->b_rptr);
1084 
1085 	do {
1086 		if ((n = MIN(uiop->uio_resid, MBLKL(bp))) != 0) {
1087 			ASSERT(n > 0);
1088 
1089 			error = uiomove(bp->b_rptr, n, UIO_READ, uiop);
1090 			if (error != 0) {
1091 				freemsg(bp);
1092 				*errorp = error;
1093 				return (NULL);
1094 			}
1095 		}
1096 
1097 		bp->b_rptr += n;
1098 		while (bp != NULL && (bp->b_rptr >= bp->b_wptr)) {
1099 			nbp = bp;
1100 			bp = bp->b_cont;
1101 			freeb(nbp);
1102 		}
1103 	} while (bp != NULL && uiop->uio_resid > 0);
1104 
1105 	*errorp = 0;
1106 	return (bp);
1107 }
1108 
1109 /*
1110  * Read a stream according to the mode flags in sd_flag:
1111  *
1112  * (default mode)		- Byte stream, msg boundaries are ignored
1113  * RD_MSGDIS (msg discard)	- Read on msg boundaries and throw away
1114  *				any data remaining in msg
1115  * RD_MSGNODIS (msg non-discard) - Read on msg boundaries and put back
1116  *				any remaining data on head of read queue
1117  *
1118  * Consume readable messages on the front of the queue until
1119  * ttolwp(curthread)->lwp_count
1120  * is satisfied, the readable messages are exhausted, or a message
1121  * boundary is reached in a message mode.  If no data was read and
1122  * the stream was not opened with the NDELAY flag, block until data arrives.
1123  * Otherwise return the data read and update the count.
1124  *
1125  * In default mode a 0 length message signifies end-of-file and terminates
1126  * a read in progress.  The 0 length message is removed from the queue
1127  * only if it is the only message read (no data is read).
1128  *
1129  * An attempt to read an M_PROTO or M_PCPROTO message results in an
1130  * EBADMSG error return, unless either RD_PROTDAT or RD_PROTDIS are set.
1131  * If RD_PROTDAT is set, M_PROTO and M_PCPROTO messages are read as data.
1132  * If RD_PROTDIS is set, the M_PROTO and M_PCPROTO parts of the message
1133  * are unlinked from and M_DATA blocks in the message, the protos are
1134  * thrown away, and the data is read.
1135  */
1136 /* ARGSUSED */
1137 int
1138 strread(struct vnode *vp, struct uio *uiop, cred_t *crp)
1139 {
1140 	struct stdata *stp;
1141 	mblk_t *bp, *nbp;
1142 	queue_t *q;
1143 	int error = 0;
1144 	uint_t old_sd_flag;
1145 	int first;
1146 	char rflg;
1147 	uint_t mark;		/* Contains MSG*MARK and _LASTMARK */
1148 #define	_LASTMARK	0x8000	/* Distinct from MSG*MARK */
1149 	short delim;
1150 	unsigned char pri = 0;
1151 	char waitflag;
1152 	unsigned char type;
1153 
1154 	TRACE_1(TR_FAC_STREAMS_FR,
1155 	    TR_STRREAD_ENTER, "strread:%p", vp);
1156 	ASSERT(vp->v_stream);
1157 	stp = vp->v_stream;
1158 
1159 	mutex_enter(&stp->sd_lock);
1160 
1161 	if ((error = i_straccess(stp, JCREAD)) != 0) {
1162 		mutex_exit(&stp->sd_lock);
1163 		return (error);
1164 	}
1165 
1166 	if (stp->sd_flag & (STRDERR|STPLEX)) {
1167 		error = strgeterr(stp, STRDERR|STPLEX, 0);
1168 		if (error != 0) {
1169 			mutex_exit(&stp->sd_lock);
1170 			return (error);
1171 		}
1172 	}
1173 
1174 	/*
1175 	 * Loop terminates when uiop->uio_resid == 0.
1176 	 */
1177 	rflg = 0;
1178 	waitflag = READWAIT;
1179 	q = _RD(stp->sd_wrq);
1180 	for (;;) {
1181 		ASSERT(MUTEX_HELD(&stp->sd_lock));
1182 		old_sd_flag = stp->sd_flag;
1183 		mark = 0;
1184 		delim = 0;
1185 		first = 1;
1186 		while ((bp = strget(stp, q, uiop, first, &error)) == NULL) {
1187 			int done = 0;
1188 
1189 			ASSERT(MUTEX_HELD(&stp->sd_lock));
1190 
1191 			if (error != 0)
1192 				goto oops;
1193 
1194 			if (stp->sd_flag & (STRHUP|STREOF)) {
1195 				goto oops;
1196 			}
1197 			if (rflg && !(stp->sd_flag & STRDELIM)) {
1198 				goto oops;
1199 			}
1200 			/*
1201 			 * If a read(fd,buf,0) has been done, there is no
1202 			 * need to sleep. We always have zero bytes to
1203 			 * return.
1204 			 */
1205 			if (uiop->uio_resid == 0) {
1206 				goto oops;
1207 			}
1208 
1209 			qbackenable(q, 0);
1210 
1211 			TRACE_3(TR_FAC_STREAMS_FR, TR_STRREAD_WAIT,
1212 			    "strread calls strwaitq:%p, %p, %p",
1213 			    vp, uiop, crp);
1214 			if ((error = strwaitq(stp, waitflag, uiop->uio_resid,
1215 			    uiop->uio_fmode, -1, &done)) != 0 || done) {
1216 				TRACE_3(TR_FAC_STREAMS_FR, TR_STRREAD_DONE,
1217 				    "strread error or done:%p, %p, %p",
1218 				    vp, uiop, crp);
1219 				if ((uiop->uio_fmode & FNDELAY) &&
1220 				    (stp->sd_flag & OLDNDELAY) &&
1221 				    (error == EAGAIN))
1222 					error = 0;
1223 				goto oops;
1224 			}
1225 			TRACE_3(TR_FAC_STREAMS_FR, TR_STRREAD_AWAKE,
1226 			    "strread awakes:%p, %p, %p", vp, uiop, crp);
1227 			if ((error = i_straccess(stp, JCREAD)) != 0) {
1228 				goto oops;
1229 			}
1230 			first = 0;
1231 		}
1232 		ASSERT(MUTEX_HELD(&stp->sd_lock));
1233 		ASSERT(bp);
1234 		pri = bp->b_band;
1235 		/*
1236 		 * Extract any mark information. If the message is not
1237 		 * completely consumed this information will be put in the mblk
1238 		 * that is putback.
1239 		 * If MSGMARKNEXT is set and the message is completely consumed
1240 		 * the STRATMARK flag will be set below. Likewise, if
1241 		 * MSGNOTMARKNEXT is set and the message is
1242 		 * completely consumed STRNOTATMARK will be set.
1243 		 *
1244 		 * For some unknown reason strread only breaks the read at the
1245 		 * last mark.
1246 		 */
1247 		mark = bp->b_flag & (MSGMARK | MSGMARKNEXT | MSGNOTMARKNEXT);
1248 		ASSERT((mark & (MSGMARKNEXT|MSGNOTMARKNEXT)) !=
1249 		    (MSGMARKNEXT|MSGNOTMARKNEXT));
1250 		if (mark != 0 && bp == stp->sd_mark) {
1251 			if (rflg) {
1252 				putback(stp, q, bp, pri);
1253 				goto oops;
1254 			}
1255 			mark |= _LASTMARK;
1256 			stp->sd_mark = NULL;
1257 		}
1258 		if ((stp->sd_flag & STRDELIM) && (bp->b_flag & MSGDELIM))
1259 			delim = 1;
1260 		mutex_exit(&stp->sd_lock);
1261 
1262 		if (STREAM_NEEDSERVICE(stp))
1263 			stream_runservice(stp);
1264 
1265 		type = bp->b_datap->db_type;
1266 
1267 		switch (type) {
1268 
1269 		case M_DATA:
1270 ismdata:
1271 			if (msgnodata(bp)) {
1272 				if (mark || delim) {
1273 					freemsg(bp);
1274 				} else if (rflg) {
1275 
1276 					/*
1277 					 * If already read data put zero
1278 					 * length message back on queue else
1279 					 * free msg and return 0.
1280 					 */
1281 					bp->b_band = pri;
1282 					mutex_enter(&stp->sd_lock);
1283 					putback(stp, q, bp, pri);
1284 					mutex_exit(&stp->sd_lock);
1285 				} else {
1286 					freemsg(bp);
1287 				}
1288 				error =  0;
1289 				goto oops1;
1290 			}
1291 
1292 			rflg = 1;
1293 			waitflag |= NOINTR;
1294 			bp = struiocopyout(bp, uiop, &error);
1295 			if (error != 0)
1296 				goto oops1;
1297 
1298 			mutex_enter(&stp->sd_lock);
1299 			if (bp) {
1300 				/*
1301 				 * Have remaining data in message.
1302 				 * Free msg if in discard mode.
1303 				 */
1304 				if (stp->sd_read_opt & RD_MSGDIS) {
1305 					freemsg(bp);
1306 				} else {
1307 					bp->b_band = pri;
1308 					if ((mark & _LASTMARK) &&
1309 					    (stp->sd_mark == NULL))
1310 						stp->sd_mark = bp;
1311 					bp->b_flag |= mark & ~_LASTMARK;
1312 					if (delim)
1313 						bp->b_flag |= MSGDELIM;
1314 					if (msgnodata(bp))
1315 						freemsg(bp);
1316 					else
1317 						putback(stp, q, bp, pri);
1318 				}
1319 			} else {
1320 				/*
1321 				 * Consumed the complete message.
1322 				 * Move the MSG*MARKNEXT information
1323 				 * to the stream head just in case
1324 				 * the read queue becomes empty.
1325 				 *
1326 				 * If the stream head was at the mark
1327 				 * (STRATMARK) before we dropped sd_lock above
1328 				 * and some data was consumed then we have
1329 				 * moved past the mark thus STRATMARK is
1330 				 * cleared. However, if a message arrived in
1331 				 * strrput during the copyout above causing
1332 				 * STRATMARK to be set we can not clear that
1333 				 * flag.
1334 				 */
1335 				if (mark &
1336 				    (MSGMARKNEXT|MSGNOTMARKNEXT|MSGMARK)) {
1337 					if (mark & MSGMARKNEXT) {
1338 						stp->sd_flag &= ~STRNOTATMARK;
1339 						stp->sd_flag |= STRATMARK;
1340 					} else if (mark & MSGNOTMARKNEXT) {
1341 						stp->sd_flag &= ~STRATMARK;
1342 						stp->sd_flag |= STRNOTATMARK;
1343 					} else {
1344 						stp->sd_flag &=
1345 						    ~(STRATMARK|STRNOTATMARK);
1346 					}
1347 				} else if (rflg && (old_sd_flag & STRATMARK)) {
1348 					stp->sd_flag &= ~STRATMARK;
1349 				}
1350 			}
1351 
1352 			/*
1353 			 * Check for signal messages at the front of the read
1354 			 * queue and generate the signal(s) if appropriate.
1355 			 * The only signal that can be on queue is M_SIG at
1356 			 * this point.
1357 			 */
1358 			while ((((bp = q->q_first)) != NULL) &&
1359 			    (bp->b_datap->db_type == M_SIG)) {
1360 				bp = getq_noenab(q);
1361 				/*
1362 				 * sd_lock is held so the content of the
1363 				 * read queue can not change.
1364 				 */
1365 				ASSERT(bp != NULL &&
1366 				    bp->b_datap->db_type == M_SIG);
1367 				strsignal_nolock(stp, *bp->b_rptr,
1368 				    (int32_t)bp->b_band);
1369 				mutex_exit(&stp->sd_lock);
1370 				freemsg(bp);
1371 				if (STREAM_NEEDSERVICE(stp))
1372 					stream_runservice(stp);
1373 				mutex_enter(&stp->sd_lock);
1374 			}
1375 
1376 			if ((uiop->uio_resid == 0) || (mark & _LASTMARK) ||
1377 			    delim ||
1378 			    (stp->sd_read_opt & (RD_MSGDIS|RD_MSGNODIS))) {
1379 				goto oops;
1380 			}
1381 			continue;
1382 
1383 		case M_SIG:
1384 			strsignal(stp, *bp->b_rptr, (int32_t)bp->b_band);
1385 			freemsg(bp);
1386 			mutex_enter(&stp->sd_lock);
1387 			continue;
1388 
1389 		case M_PROTO:
1390 		case M_PCPROTO:
1391 			/*
1392 			 * Only data messages are readable.
1393 			 * Any others generate an error, unless
1394 			 * RD_PROTDIS or RD_PROTDAT is set.
1395 			 */
1396 			if (stp->sd_read_opt & RD_PROTDAT) {
1397 				for (nbp = bp; nbp; nbp = nbp->b_next) {
1398 					if ((nbp->b_datap->db_type ==
1399 					    M_PROTO) ||
1400 					    (nbp->b_datap->db_type ==
1401 					    M_PCPROTO)) {
1402 						nbp->b_datap->db_type = M_DATA;
1403 					} else {
1404 						break;
1405 					}
1406 				}
1407 				/*
1408 				 * clear stream head hi pri flag based on
1409 				 * first message
1410 				 */
1411 				if (type == M_PCPROTO) {
1412 					mutex_enter(&stp->sd_lock);
1413 					stp->sd_flag &= ~STRPRI;
1414 					mutex_exit(&stp->sd_lock);
1415 				}
1416 				goto ismdata;
1417 			} else if (stp->sd_read_opt & RD_PROTDIS) {
1418 				/*
1419 				 * discard non-data messages
1420 				 */
1421 				while (bp &&
1422 				    ((bp->b_datap->db_type == M_PROTO) ||
1423 				    (bp->b_datap->db_type == M_PCPROTO))) {
1424 					nbp = unlinkb(bp);
1425 					freeb(bp);
1426 					bp = nbp;
1427 				}
1428 				/*
1429 				 * clear stream head hi pri flag based on
1430 				 * first message
1431 				 */
1432 				if (type == M_PCPROTO) {
1433 					mutex_enter(&stp->sd_lock);
1434 					stp->sd_flag &= ~STRPRI;
1435 					mutex_exit(&stp->sd_lock);
1436 				}
1437 				if (bp) {
1438 					bp->b_band = pri;
1439 					goto ismdata;
1440 				} else {
1441 					break;
1442 				}
1443 			}
1444 			/* FALLTHRU */
1445 		case M_PASSFP:
1446 			if ((bp->b_datap->db_type == M_PASSFP) &&
1447 			    (stp->sd_read_opt & RD_PROTDIS)) {
1448 				freemsg(bp);
1449 				break;
1450 			}
1451 			mutex_enter(&stp->sd_lock);
1452 			putback(stp, q, bp, pri);
1453 			mutex_exit(&stp->sd_lock);
1454 			if (rflg == 0)
1455 				error = EBADMSG;
1456 			goto oops1;
1457 
1458 		default:
1459 			/*
1460 			 * Garbage on stream head read queue.
1461 			 */
1462 			cmn_err(CE_WARN, "bad %x found at stream head\n",
1463 			    bp->b_datap->db_type);
1464 			freemsg(bp);
1465 			goto oops1;
1466 		}
1467 		mutex_enter(&stp->sd_lock);
1468 	}
1469 oops:
1470 	mutex_exit(&stp->sd_lock);
1471 oops1:
1472 	qbackenable(q, pri);
1473 	return (error);
1474 #undef	_LASTMARK
1475 }
1476 
1477 /*
1478  * Default processing of M_PROTO/M_PCPROTO messages.
1479  * Determine which wakeups and signals are needed.
1480  * This can be replaced by a user-specified procedure for kernel users
1481  * of STREAMS.
1482  */
1483 /* ARGSUSED */
1484 mblk_t *
1485 strrput_proto(vnode_t *vp, mblk_t *mp,
1486     strwakeup_t *wakeups, strsigset_t *firstmsgsigs,
1487     strsigset_t *allmsgsigs, strpollset_t *pollwakeups)
1488 {
1489 	*wakeups = RSLEEP;
1490 	*allmsgsigs = 0;
1491 
1492 	switch (mp->b_datap->db_type) {
1493 	case M_PROTO:
1494 		if (mp->b_band == 0) {
1495 			*firstmsgsigs = S_INPUT | S_RDNORM;
1496 			*pollwakeups = POLLIN | POLLRDNORM;
1497 		} else {
1498 			*firstmsgsigs = S_INPUT | S_RDBAND;
1499 			*pollwakeups = POLLIN | POLLRDBAND;
1500 		}
1501 		break;
1502 	case M_PCPROTO:
1503 		*firstmsgsigs = S_HIPRI;
1504 		*pollwakeups = POLLPRI;
1505 		break;
1506 	}
1507 	return (mp);
1508 }
1509 
1510 /*
1511  * Default processing of everything but M_DATA, M_PROTO, M_PCPROTO and
1512  * M_PASSFP messages.
1513  * Determine which wakeups and signals are needed.
1514  * This can be replaced by a user-specified procedure for kernel users
1515  * of STREAMS.
1516  */
1517 /* ARGSUSED */
1518 mblk_t *
1519 strrput_misc(vnode_t *vp, mblk_t *mp,
1520     strwakeup_t *wakeups, strsigset_t *firstmsgsigs,
1521     strsigset_t *allmsgsigs, strpollset_t *pollwakeups)
1522 {
1523 	*wakeups = 0;
1524 	*firstmsgsigs = 0;
1525 	*allmsgsigs = 0;
1526 	*pollwakeups = 0;
1527 	return (mp);
1528 }
1529 
1530 /*
1531  * Stream read put procedure.  Called from downstream driver/module
1532  * with messages for the stream head.  Data, protocol, and in-stream
1533  * signal messages are placed on the queue, others are handled directly.
1534  */
1535 int
1536 strrput(queue_t *q, mblk_t *bp)
1537 {
1538 	struct stdata	*stp;
1539 	ulong_t		rput_opt;
1540 	strwakeup_t	wakeups;
1541 	strsigset_t	firstmsgsigs;	/* Signals if first message on queue */
1542 	strsigset_t	allmsgsigs;	/* Signals for all messages */
1543 	strsigset_t	signals;	/* Signals events to generate */
1544 	strpollset_t	pollwakeups;
1545 	mblk_t		*nextbp;
1546 	uchar_t		band = 0;
1547 	int		hipri_sig;
1548 
1549 	stp = (struct stdata *)q->q_ptr;
1550 	/*
1551 	 * Use rput_opt for optimized access to the SR_ flags except
1552 	 * SR_POLLIN. That flag has to be checked under sd_lock since it
1553 	 * is modified by strpoll().
1554 	 */
1555 	rput_opt = stp->sd_rput_opt;
1556 
1557 	ASSERT(qclaimed(q));
1558 	TRACE_2(TR_FAC_STREAMS_FR, TR_STRRPUT_ENTER,
1559 	    "strrput called with message type:q %p bp %p", q, bp);
1560 
1561 	/*
1562 	 * Perform initial processing and pass to the parameterized functions.
1563 	 */
1564 	ASSERT(bp->b_next == NULL);
1565 
1566 	switch (bp->b_datap->db_type) {
1567 	case M_DATA:
1568 		/*
1569 		 * sockfs is the only consumer of STREOF and when it is set,
1570 		 * it implies that the receiver is not interested in receiving
1571 		 * any more data, hence the mblk is freed to prevent unnecessary
1572 		 * message queueing at the stream head.
1573 		 */
1574 		if (stp->sd_flag == STREOF) {
1575 			freemsg(bp);
1576 			return (0);
1577 		}
1578 		if ((rput_opt & SR_IGN_ZEROLEN) &&
1579 		    bp->b_rptr == bp->b_wptr && msgnodata(bp)) {
1580 			/*
1581 			 * Ignore zero-length M_DATA messages. These might be
1582 			 * generated by some transports.
1583 			 * The zero-length M_DATA messages, even if they
1584 			 * are ignored, should effect the atmark tracking and
1585 			 * should wake up a thread sleeping in strwaitmark.
1586 			 */
1587 			mutex_enter(&stp->sd_lock);
1588 			if (bp->b_flag & MSGMARKNEXT) {
1589 				/*
1590 				 * Record the position of the mark either
1591 				 * in q_last or in STRATMARK.
1592 				 */
1593 				if (q->q_last != NULL) {
1594 					q->q_last->b_flag &= ~MSGNOTMARKNEXT;
1595 					q->q_last->b_flag |= MSGMARKNEXT;
1596 				} else {
1597 					stp->sd_flag &= ~STRNOTATMARK;
1598 					stp->sd_flag |= STRATMARK;
1599 				}
1600 			} else if (bp->b_flag & MSGNOTMARKNEXT) {
1601 				/*
1602 				 * Record that this is not the position of
1603 				 * the mark either in q_last or in
1604 				 * STRNOTATMARK.
1605 				 */
1606 				if (q->q_last != NULL) {
1607 					q->q_last->b_flag &= ~MSGMARKNEXT;
1608 					q->q_last->b_flag |= MSGNOTMARKNEXT;
1609 				} else {
1610 					stp->sd_flag &= ~STRATMARK;
1611 					stp->sd_flag |= STRNOTATMARK;
1612 				}
1613 			}
1614 			if (stp->sd_flag & RSLEEP) {
1615 				stp->sd_flag &= ~RSLEEP;
1616 				cv_broadcast(&q->q_wait);
1617 			}
1618 			mutex_exit(&stp->sd_lock);
1619 			freemsg(bp);
1620 			return (0);
1621 		}
1622 		wakeups = RSLEEP;
1623 		if (bp->b_band == 0) {
1624 			firstmsgsigs = S_INPUT | S_RDNORM;
1625 			pollwakeups = POLLIN | POLLRDNORM;
1626 		} else {
1627 			firstmsgsigs = S_INPUT | S_RDBAND;
1628 			pollwakeups = POLLIN | POLLRDBAND;
1629 		}
1630 		if (rput_opt & SR_SIGALLDATA)
1631 			allmsgsigs = firstmsgsigs;
1632 		else
1633 			allmsgsigs = 0;
1634 
1635 		mutex_enter(&stp->sd_lock);
1636 		if ((rput_opt & SR_CONSOL_DATA) &&
1637 		    (q->q_last != NULL) &&
1638 		    (bp->b_flag & (MSGMARK|MSGDELIM)) == 0) {
1639 			/*
1640 			 * Consolidate an M_DATA message onto an M_DATA,
1641 			 * M_PROTO, or M_PCPROTO by merging it with q_last.
1642 			 * The consolidation does not take place if
1643 			 * the old message is marked with either of the
1644 			 * marks or the delim flag or if the new
1645 			 * message is marked with MSGMARK. The MSGMARK
1646 			 * check is needed to handle the odd semantics of
1647 			 * MSGMARK where essentially the whole message
1648 			 * is to be treated as marked.
1649 			 * Carry any MSGMARKNEXT  and MSGNOTMARKNEXT from the
1650 			 * new message to the front of the b_cont chain.
1651 			 */
1652 			mblk_t *lbp = q->q_last;
1653 			unsigned char db_type = lbp->b_datap->db_type;
1654 
1655 			if ((db_type == M_DATA || db_type == M_PROTO ||
1656 			    db_type == M_PCPROTO) &&
1657 			    !(lbp->b_flag & (MSGDELIM|MSGMARK|MSGMARKNEXT))) {
1658 				rmvq_noenab(q, lbp);
1659 				/*
1660 				 * The first message in the b_cont list
1661 				 * tracks MSGMARKNEXT and MSGNOTMARKNEXT.
1662 				 * We need to handle the case where we
1663 				 * are appending:
1664 				 *
1665 				 * 1) a MSGMARKNEXT to a MSGNOTMARKNEXT.
1666 				 * 2) a MSGMARKNEXT to a plain message.
1667 				 * 3) a MSGNOTMARKNEXT to a plain message
1668 				 * 4) a MSGNOTMARKNEXT to a MSGNOTMARKNEXT
1669 				 *    message.
1670 				 *
1671 				 * Thus we never append a MSGMARKNEXT or
1672 				 * MSGNOTMARKNEXT to a MSGMARKNEXT message.
1673 				 */
1674 				if (bp->b_flag & MSGMARKNEXT) {
1675 					lbp->b_flag |= MSGMARKNEXT;
1676 					lbp->b_flag &= ~MSGNOTMARKNEXT;
1677 					bp->b_flag &= ~MSGMARKNEXT;
1678 				} else if (bp->b_flag & MSGNOTMARKNEXT) {
1679 					lbp->b_flag |= MSGNOTMARKNEXT;
1680 					bp->b_flag &= ~MSGNOTMARKNEXT;
1681 				}
1682 
1683 				linkb(lbp, bp);
1684 				bp = lbp;
1685 				/*
1686 				 * The new message logically isn't the first
1687 				 * even though the q_first check below thinks
1688 				 * it is. Clear the firstmsgsigs to make it
1689 				 * not appear to be first.
1690 				 */
1691 				firstmsgsigs = 0;
1692 			}
1693 		}
1694 		break;
1695 
1696 	case M_PASSFP:
1697 		wakeups = RSLEEP;
1698 		allmsgsigs = 0;
1699 		if (bp->b_band == 0) {
1700 			firstmsgsigs = S_INPUT | S_RDNORM;
1701 			pollwakeups = POLLIN | POLLRDNORM;
1702 		} else {
1703 			firstmsgsigs = S_INPUT | S_RDBAND;
1704 			pollwakeups = POLLIN | POLLRDBAND;
1705 		}
1706 		mutex_enter(&stp->sd_lock);
1707 		break;
1708 
1709 	case M_PROTO:
1710 	case M_PCPROTO:
1711 		ASSERT(stp->sd_rprotofunc != NULL);
1712 		bp = (stp->sd_rprotofunc)(stp->sd_vnode, bp,
1713 		    &wakeups, &firstmsgsigs, &allmsgsigs, &pollwakeups);
1714 #define	ALLSIG	(S_INPUT|S_HIPRI|S_OUTPUT|S_MSG|S_ERROR|S_HANGUP|S_RDNORM|\
1715 		S_WRNORM|S_RDBAND|S_WRBAND|S_BANDURG)
1716 #define	ALLPOLL	(POLLIN|POLLPRI|POLLOUT|POLLRDNORM|POLLWRNORM|POLLRDBAND|\
1717 		POLLWRBAND)
1718 
1719 		ASSERT((wakeups & ~(RSLEEP|WSLEEP)) == 0);
1720 		ASSERT((firstmsgsigs & ~ALLSIG) == 0);
1721 		ASSERT((allmsgsigs & ~ALLSIG) == 0);
1722 		ASSERT((pollwakeups & ~ALLPOLL) == 0);
1723 
1724 		mutex_enter(&stp->sd_lock);
1725 		break;
1726 
1727 	default:
1728 		ASSERT(stp->sd_rmiscfunc != NULL);
1729 		bp = (stp->sd_rmiscfunc)(stp->sd_vnode, bp,
1730 		    &wakeups, &firstmsgsigs, &allmsgsigs, &pollwakeups);
1731 		ASSERT((wakeups & ~(RSLEEP|WSLEEP)) == 0);
1732 		ASSERT((firstmsgsigs & ~ALLSIG) == 0);
1733 		ASSERT((allmsgsigs & ~ALLSIG) == 0);
1734 		ASSERT((pollwakeups & ~ALLPOLL) == 0);
1735 #undef	ALLSIG
1736 #undef	ALLPOLL
1737 		mutex_enter(&stp->sd_lock);
1738 		break;
1739 	}
1740 	ASSERT(MUTEX_HELD(&stp->sd_lock));
1741 
1742 	/* By default generate superset of signals */
1743 	signals = (firstmsgsigs | allmsgsigs);
1744 
1745 	/*
1746 	 * The  proto and misc functions can return multiple messages
1747 	 * as a b_next chain. Such messages are processed separately.
1748 	 */
1749 one_more:
1750 	hipri_sig = 0;
1751 	if (bp == NULL) {
1752 		nextbp = NULL;
1753 	} else {
1754 		nextbp = bp->b_next;
1755 		bp->b_next = NULL;
1756 
1757 		switch (bp->b_datap->db_type) {
1758 		case M_PCPROTO:
1759 			/*
1760 			 * Only one priority protocol message is allowed at the
1761 			 * stream head at a time.
1762 			 */
1763 			if (stp->sd_flag & STRPRI) {
1764 				TRACE_0(TR_FAC_STREAMS_FR, TR_STRRPUT_PROTERR,
1765 				    "M_PCPROTO already at head");
1766 				freemsg(bp);
1767 				mutex_exit(&stp->sd_lock);
1768 				goto done;
1769 			}
1770 			stp->sd_flag |= STRPRI;
1771 			hipri_sig = 1;
1772 			/* FALLTHRU */
1773 		case M_DATA:
1774 		case M_PROTO:
1775 		case M_PASSFP:
1776 			band = bp->b_band;
1777 			/*
1778 			 * Marking doesn't work well when messages
1779 			 * are marked in more than one band.  We only
1780 			 * remember the last message received, even if
1781 			 * it is placed on the queue ahead of other
1782 			 * marked messages.
1783 			 */
1784 			if (bp->b_flag & MSGMARK)
1785 				stp->sd_mark = bp;
1786 			(void) putq(q, bp);
1787 
1788 			/*
1789 			 * If message is a PCPROTO message, always use
1790 			 * firstmsgsigs to determine if a signal should be
1791 			 * sent as strrput is the only place to send
1792 			 * signals for PCPROTO. Other messages are based on
1793 			 * the STRGETINPROG flag. The flag determines if
1794 			 * strrput or (k)strgetmsg will be responsible for
1795 			 * sending the signals, in the firstmsgsigs case.
1796 			 */
1797 			if ((hipri_sig == 1) ||
1798 			    (((stp->sd_flag & STRGETINPROG) == 0) &&
1799 			    (q->q_first == bp)))
1800 				signals = (firstmsgsigs | allmsgsigs);
1801 			else
1802 				signals = allmsgsigs;
1803 			break;
1804 
1805 		default:
1806 			mutex_exit(&stp->sd_lock);
1807 			(void) strrput_nondata(q, bp);
1808 			mutex_enter(&stp->sd_lock);
1809 			break;
1810 		}
1811 	}
1812 	ASSERT(MUTEX_HELD(&stp->sd_lock));
1813 	/*
1814 	 * Wake sleeping read/getmsg and cancel deferred wakeup
1815 	 */
1816 	if (wakeups & RSLEEP)
1817 		stp->sd_wakeq &= ~RSLEEP;
1818 
1819 	wakeups &= stp->sd_flag;
1820 	if (wakeups & RSLEEP) {
1821 		stp->sd_flag &= ~RSLEEP;
1822 		cv_broadcast(&q->q_wait);
1823 	}
1824 	if (wakeups & WSLEEP) {
1825 		stp->sd_flag &= ~WSLEEP;
1826 		cv_broadcast(&_WR(q)->q_wait);
1827 	}
1828 
1829 	if (pollwakeups != 0) {
1830 		if (pollwakeups == (POLLIN | POLLRDNORM)) {
1831 			/*
1832 			 * Can't use rput_opt since it was not
1833 			 * read when sd_lock was held and SR_POLLIN is changed
1834 			 * by strpoll() under sd_lock.
1835 			 */
1836 			if (!(stp->sd_rput_opt & SR_POLLIN))
1837 				goto no_pollwake;
1838 			stp->sd_rput_opt &= ~SR_POLLIN;
1839 		}
1840 		mutex_exit(&stp->sd_lock);
1841 		pollwakeup(&stp->sd_pollist, pollwakeups);
1842 		mutex_enter(&stp->sd_lock);
1843 	}
1844 no_pollwake:
1845 
1846 	/*
1847 	 * strsendsig can handle multiple signals with a
1848 	 * single call.
1849 	 */
1850 	if (stp->sd_sigflags & signals)
1851 		strsendsig(stp->sd_siglist, signals, band, 0);
1852 	mutex_exit(&stp->sd_lock);
1853 
1854 
1855 done:
1856 	if (nextbp == NULL)
1857 		return (0);
1858 
1859 	/*
1860 	 * Any signals were handled the first time.
1861 	 * Wakeups and pollwakeups are redone to avoid any race
1862 	 * conditions - all the messages are not queued until the
1863 	 * last message has been processed by strrput.
1864 	 */
1865 	bp = nextbp;
1866 	signals = firstmsgsigs = allmsgsigs = 0;
1867 	mutex_enter(&stp->sd_lock);
1868 	goto one_more;
1869 }
1870 
1871 static void
1872 log_dupioc(queue_t *rq, mblk_t *bp)
1873 {
1874 	queue_t *wq, *qp;
1875 	char *modnames, *mnp, *dname;
1876 	size_t maxmodstr;
1877 	boolean_t islast;
1878 
1879 	/*
1880 	 * Allocate a buffer large enough to hold the names of nstrpush modules
1881 	 * and one driver, with spaces between and NUL terminator.  If we can't
1882 	 * get memory, then we'll just log the driver name.
1883 	 */
1884 	maxmodstr = nstrpush * (FMNAMESZ + 1);
1885 	mnp = modnames = kmem_alloc(maxmodstr, KM_NOSLEEP);
1886 
1887 	/* march down write side to print log message down to the driver */
1888 	wq = WR(rq);
1889 
1890 	/* make sure q_next doesn't shift around while we're grabbing data */
1891 	claimstr(wq);
1892 	qp = wq->q_next;
1893 	do {
1894 		if ((dname = qp->q_qinfo->qi_minfo->mi_idname) == NULL)
1895 			dname = "?";
1896 		islast = !SAMESTR(qp) || qp->q_next == NULL;
1897 		if (modnames == NULL) {
1898 			/*
1899 			 * If we don't have memory, then get the driver name in
1900 			 * the log where we can see it.  Note that memory
1901 			 * pressure is a possible cause of these sorts of bugs.
1902 			 */
1903 			if (islast) {
1904 				modnames = dname;
1905 				maxmodstr = 0;
1906 			}
1907 		} else {
1908 			mnp += snprintf(mnp, FMNAMESZ + 1, "%s", dname);
1909 			if (!islast)
1910 				*mnp++ = ' ';
1911 		}
1912 		qp = qp->q_next;
1913 	} while (!islast);
1914 	releasestr(wq);
1915 	/* Cannot happen unless stream head is corrupt. */
1916 	ASSERT(modnames != NULL);
1917 	(void) strlog(rq->q_qinfo->qi_minfo->mi_idnum, 0, 1,
1918 	    SL_CONSOLE|SL_TRACE|SL_ERROR,
1919 	    "Warning: stream %p received duplicate %X M_IOC%s; module list: %s",
1920 	    rq->q_ptr, ((struct iocblk *)bp->b_rptr)->ioc_cmd,
1921 	    (DB_TYPE(bp) == M_IOCACK ? "ACK" : "NAK"), modnames);
1922 	if (maxmodstr != 0)
1923 		kmem_free(modnames, maxmodstr);
1924 }
1925 
1926 int
1927 strrput_nondata(queue_t *q, mblk_t *bp)
1928 {
1929 	struct stdata *stp;
1930 	struct iocblk *iocbp;
1931 	struct stroptions *sop;
1932 	struct copyreq *reqp;
1933 	struct copyresp *resp;
1934 	unsigned char bpri;
1935 	unsigned char  flushed_already = 0;
1936 
1937 	stp = (struct stdata *)q->q_ptr;
1938 
1939 	ASSERT(!(stp->sd_flag & STPLEX));
1940 	ASSERT(qclaimed(q));
1941 
1942 	switch (bp->b_datap->db_type) {
1943 	case M_ERROR:
1944 		/*
1945 		 * An error has occurred downstream, the errno is in the first
1946 		 * bytes of the message.
1947 		 */
1948 		if ((bp->b_wptr - bp->b_rptr) == 2) {	/* New flavor */
1949 			unsigned char rw = 0;
1950 
1951 			mutex_enter(&stp->sd_lock);
1952 			if (*bp->b_rptr != NOERROR) {	/* read error */
1953 				if (*bp->b_rptr != 0) {
1954 					if (stp->sd_flag & STRDERR)
1955 						flushed_already |= FLUSHR;
1956 					stp->sd_flag |= STRDERR;
1957 					rw |= FLUSHR;
1958 				} else {
1959 					stp->sd_flag &= ~STRDERR;
1960 				}
1961 				stp->sd_rerror = *bp->b_rptr;
1962 			}
1963 			bp->b_rptr++;
1964 			if (*bp->b_rptr != NOERROR) {	/* write error */
1965 				if (*bp->b_rptr != 0) {
1966 					if (stp->sd_flag & STWRERR)
1967 						flushed_already |= FLUSHW;
1968 					stp->sd_flag |= STWRERR;
1969 					rw |= FLUSHW;
1970 				} else {
1971 					stp->sd_flag &= ~STWRERR;
1972 				}
1973 				stp->sd_werror = *bp->b_rptr;
1974 			}
1975 			if (rw) {
1976 				TRACE_2(TR_FAC_STREAMS_FR, TR_STRRPUT_WAKE,
1977 				    "strrput cv_broadcast:q %p, bp %p",
1978 				    q, bp);
1979 				cv_broadcast(&q->q_wait); /* readers */
1980 				cv_broadcast(&_WR(q)->q_wait); /* writers */
1981 				cv_broadcast(&stp->sd_monitor); /* ioctllers */
1982 
1983 				mutex_exit(&stp->sd_lock);
1984 				pollwakeup(&stp->sd_pollist, POLLERR);
1985 				mutex_enter(&stp->sd_lock);
1986 
1987 				if (stp->sd_sigflags & S_ERROR)
1988 					strsendsig(stp->sd_siglist, S_ERROR, 0,
1989 					    ((rw & FLUSHR) ? stp->sd_rerror :
1990 					    stp->sd_werror));
1991 				mutex_exit(&stp->sd_lock);
1992 				/*
1993 				 * Send the M_FLUSH only
1994 				 * for the first M_ERROR
1995 				 * message on the stream
1996 				 */
1997 				if (flushed_already == rw) {
1998 					freemsg(bp);
1999 					return (0);
2000 				}
2001 
2002 				bp->b_datap->db_type = M_FLUSH;
2003 				*bp->b_rptr = rw;
2004 				bp->b_wptr = bp->b_rptr + 1;
2005 				/*
2006 				 * Protect against the driver
2007 				 * passing up messages after
2008 				 * it has done a qprocsoff
2009 				 */
2010 				if (_OTHERQ(q)->q_next == NULL)
2011 					freemsg(bp);
2012 				else
2013 					qreply(q, bp);
2014 				return (0);
2015 			} else
2016 				mutex_exit(&stp->sd_lock);
2017 		} else if (*bp->b_rptr != 0) {		/* Old flavor */
2018 				if (stp->sd_flag & (STRDERR|STWRERR))
2019 					flushed_already = FLUSHRW;
2020 				mutex_enter(&stp->sd_lock);
2021 				stp->sd_flag |= (STRDERR|STWRERR);
2022 				stp->sd_rerror = *bp->b_rptr;
2023 				stp->sd_werror = *bp->b_rptr;
2024 				TRACE_2(TR_FAC_STREAMS_FR,
2025 				    TR_STRRPUT_WAKE2,
2026 				    "strrput wakeup #2:q %p, bp %p", q, bp);
2027 				cv_broadcast(&q->q_wait); /* the readers */
2028 				cv_broadcast(&_WR(q)->q_wait); /* the writers */
2029 				cv_broadcast(&stp->sd_monitor); /* ioctllers */
2030 
2031 				mutex_exit(&stp->sd_lock);
2032 				pollwakeup(&stp->sd_pollist, POLLERR);
2033 				mutex_enter(&stp->sd_lock);
2034 
2035 				if (stp->sd_sigflags & S_ERROR)
2036 					strsendsig(stp->sd_siglist, S_ERROR, 0,
2037 					    (stp->sd_werror ? stp->sd_werror :
2038 					    stp->sd_rerror));
2039 				mutex_exit(&stp->sd_lock);
2040 
2041 				/*
2042 				 * Send the M_FLUSH only
2043 				 * for the first M_ERROR
2044 				 * message on the stream
2045 				 */
2046 				if (flushed_already != FLUSHRW) {
2047 					bp->b_datap->db_type = M_FLUSH;
2048 					*bp->b_rptr = FLUSHRW;
2049 					/*
2050 					 * Protect against the driver passing up
2051 					 * messages after it has done a
2052 					 * qprocsoff.
2053 					 */
2054 				if (_OTHERQ(q)->q_next == NULL)
2055 					freemsg(bp);
2056 				else
2057 					qreply(q, bp);
2058 				return (0);
2059 				}
2060 		}
2061 		freemsg(bp);
2062 		return (0);
2063 
2064 	case M_HANGUP:
2065 
2066 		freemsg(bp);
2067 		mutex_enter(&stp->sd_lock);
2068 		stp->sd_werror = ENXIO;
2069 		stp->sd_flag |= STRHUP;
2070 		stp->sd_flag &= ~(WSLEEP|RSLEEP);
2071 
2072 		/*
2073 		 * send signal if controlling tty
2074 		 */
2075 
2076 		if (stp->sd_sidp) {
2077 			prsignal(stp->sd_sidp, SIGHUP);
2078 			if (stp->sd_sidp != stp->sd_pgidp)
2079 				pgsignal(stp->sd_pgidp, SIGTSTP);
2080 		}
2081 
2082 		/*
2083 		 * wake up read, write, and exception pollers and
2084 		 * reset wakeup mechanism.
2085 		 */
2086 		cv_broadcast(&q->q_wait);	/* the readers */
2087 		cv_broadcast(&_WR(q)->q_wait);	/* the writers */
2088 		cv_broadcast(&stp->sd_monitor);	/* the ioctllers */
2089 		strhup(stp);
2090 		mutex_exit(&stp->sd_lock);
2091 		return (0);
2092 
2093 	case M_UNHANGUP:
2094 		freemsg(bp);
2095 		mutex_enter(&stp->sd_lock);
2096 		stp->sd_werror = 0;
2097 		stp->sd_flag &= ~STRHUP;
2098 		mutex_exit(&stp->sd_lock);
2099 		return (0);
2100 
2101 	case M_SIG:
2102 		/*
2103 		 * Someone downstream wants to post a signal.  The
2104 		 * signal to post is contained in the first byte of the
2105 		 * message.  If the message would go on the front of
2106 		 * the queue, send a signal to the process group
2107 		 * (if not SIGPOLL) or to the siglist processes
2108 		 * (SIGPOLL).  If something is already on the queue,
2109 		 * OR if we are delivering a delayed suspend (*sigh*
2110 		 * another "tty" hack) and there's no one sleeping already,
2111 		 * just enqueue the message.
2112 		 */
2113 		mutex_enter(&stp->sd_lock);
2114 		if (q->q_first || (*bp->b_rptr == SIGTSTP &&
2115 		    !(stp->sd_flag & RSLEEP))) {
2116 			(void) putq(q, bp);
2117 			mutex_exit(&stp->sd_lock);
2118 			return (0);
2119 		}
2120 		mutex_exit(&stp->sd_lock);
2121 		/* FALLTHRU */
2122 
2123 	case M_PCSIG:
2124 		/*
2125 		 * Don't enqueue, just post the signal.
2126 		 */
2127 		strsignal(stp, *bp->b_rptr, 0L);
2128 		freemsg(bp);
2129 		return (0);
2130 
2131 	case M_CMD:
2132 		if (MBLKL(bp) != sizeof (cmdblk_t)) {
2133 			freemsg(bp);
2134 			return (0);
2135 		}
2136 
2137 		mutex_enter(&stp->sd_lock);
2138 		if (stp->sd_flag & STRCMDWAIT) {
2139 			ASSERT(stp->sd_cmdblk == NULL);
2140 			stp->sd_cmdblk = bp;
2141 			cv_broadcast(&stp->sd_monitor);
2142 			mutex_exit(&stp->sd_lock);
2143 		} else {
2144 			mutex_exit(&stp->sd_lock);
2145 			freemsg(bp);
2146 		}
2147 		return (0);
2148 
2149 	case M_FLUSH:
2150 		/*
2151 		 * Flush queues.  The indication of which queues to flush
2152 		 * is in the first byte of the message.  If the read queue
2153 		 * is specified, then flush it.  If FLUSHBAND is set, just
2154 		 * flush the band specified by the second byte of the message.
2155 		 *
2156 		 * If a module has issued a M_SETOPT to not flush hi
2157 		 * priority messages off of the stream head, then pass this
2158 		 * flag into the flushq code to preserve such messages.
2159 		 */
2160 
2161 		if (*bp->b_rptr & FLUSHR) {
2162 			mutex_enter(&stp->sd_lock);
2163 			if (*bp->b_rptr & FLUSHBAND) {
2164 				ASSERT((bp->b_wptr - bp->b_rptr) >= 2);
2165 				flushband(q, *(bp->b_rptr + 1), FLUSHALL);
2166 			} else
2167 				flushq_common(q, FLUSHALL,
2168 				    stp->sd_read_opt & RFLUSHPCPROT);
2169 			if ((q->q_first == NULL) ||
2170 			    (q->q_first->b_datap->db_type < QPCTL))
2171 				stp->sd_flag &= ~STRPRI;
2172 			else {
2173 				ASSERT(stp->sd_flag & STRPRI);
2174 			}
2175 			mutex_exit(&stp->sd_lock);
2176 		}
2177 		if ((*bp->b_rptr & FLUSHW) && !(bp->b_flag & MSGNOLOOP)) {
2178 			*bp->b_rptr &= ~FLUSHR;
2179 			bp->b_flag |= MSGNOLOOP;
2180 			/*
2181 			 * Protect against the driver passing up
2182 			 * messages after it has done a qprocsoff.
2183 			 */
2184 			if (_OTHERQ(q)->q_next == NULL)
2185 				freemsg(bp);
2186 			else
2187 				qreply(q, bp);
2188 			return (0);
2189 		}
2190 		freemsg(bp);
2191 		return (0);
2192 
2193 	case M_IOCACK:
2194 	case M_IOCNAK:
2195 		iocbp = (struct iocblk *)bp->b_rptr;
2196 		/*
2197 		 * If not waiting for ACK or NAK then just free msg.
2198 		 * If incorrect id sequence number then just free msg.
2199 		 * If already have ACK or NAK for user then this is a
2200 		 *    duplicate, display a warning and free the msg.
2201 		 */
2202 		mutex_enter(&stp->sd_lock);
2203 		if ((stp->sd_flag & IOCWAIT) == 0 || stp->sd_iocblk ||
2204 		    (stp->sd_iocid != iocbp->ioc_id)) {
2205 			/*
2206 			 * If the ACK/NAK is a dup, display a message
2207 			 * Dup is when sd_iocid == ioc_id, and
2208 			 * sd_iocblk == <valid ptr> or -1 (the former
2209 			 * is when an ioctl has been put on the stream
2210 			 * head, but has not yet been consumed, the
2211 			 * later is when it has been consumed).
2212 			 */
2213 			if ((stp->sd_iocid == iocbp->ioc_id) &&
2214 			    (stp->sd_iocblk != NULL)) {
2215 				log_dupioc(q, bp);
2216 			}
2217 			freemsg(bp);
2218 			mutex_exit(&stp->sd_lock);
2219 			return (0);
2220 		}
2221 
2222 		/*
2223 		 * Assign ACK or NAK to user and wake up.
2224 		 */
2225 		stp->sd_iocblk = bp;
2226 		cv_broadcast(&stp->sd_monitor);
2227 		mutex_exit(&stp->sd_lock);
2228 		return (0);
2229 
2230 	case M_COPYIN:
2231 	case M_COPYOUT:
2232 		reqp = (struct copyreq *)bp->b_rptr;
2233 
2234 		/*
2235 		 * If not waiting for ACK or NAK then just fail request.
2236 		 * If already have ACK, NAK, or copy request, then just
2237 		 * fail request.
2238 		 * If incorrect id sequence number then just fail request.
2239 		 */
2240 		mutex_enter(&stp->sd_lock);
2241 		if ((stp->sd_flag & IOCWAIT) == 0 || stp->sd_iocblk ||
2242 		    (stp->sd_iocid != reqp->cq_id)) {
2243 			if (bp->b_cont) {
2244 				freemsg(bp->b_cont);
2245 				bp->b_cont = NULL;
2246 			}
2247 			bp->b_datap->db_type = M_IOCDATA;
2248 			bp->b_wptr = bp->b_rptr + sizeof (struct copyresp);
2249 			resp = (struct copyresp *)bp->b_rptr;
2250 			resp->cp_rval = (caddr_t)1;	/* failure */
2251 			mutex_exit(&stp->sd_lock);
2252 			putnext(stp->sd_wrq, bp);
2253 			return (0);
2254 		}
2255 
2256 		/*
2257 		 * Assign copy request to user and wake up.
2258 		 */
2259 		stp->sd_iocblk = bp;
2260 		cv_broadcast(&stp->sd_monitor);
2261 		mutex_exit(&stp->sd_lock);
2262 		return (0);
2263 
2264 	case M_SETOPTS:
2265 		/*
2266 		 * Set stream head options (read option, write offset,
2267 		 * min/max packet size, and/or high/low water marks for
2268 		 * the read side only).
2269 		 */
2270 
2271 		bpri = 0;
2272 		sop = (struct stroptions *)bp->b_rptr;
2273 		mutex_enter(&stp->sd_lock);
2274 		if (sop->so_flags & SO_READOPT) {
2275 			switch (sop->so_readopt & RMODEMASK) {
2276 			case RNORM:
2277 				stp->sd_read_opt &= ~(RD_MSGDIS | RD_MSGNODIS);
2278 				break;
2279 
2280 			case RMSGD:
2281 				stp->sd_read_opt =
2282 				    ((stp->sd_read_opt & ~RD_MSGNODIS) |
2283 				    RD_MSGDIS);
2284 				break;
2285 
2286 			case RMSGN:
2287 				stp->sd_read_opt =
2288 				    ((stp->sd_read_opt & ~RD_MSGDIS) |
2289 				    RD_MSGNODIS);
2290 				break;
2291 			}
2292 			switch (sop->so_readopt & RPROTMASK) {
2293 			case RPROTNORM:
2294 				stp->sd_read_opt &= ~(RD_PROTDAT | RD_PROTDIS);
2295 				break;
2296 
2297 			case RPROTDAT:
2298 				stp->sd_read_opt =
2299 				    ((stp->sd_read_opt & ~RD_PROTDIS) |
2300 				    RD_PROTDAT);
2301 				break;
2302 
2303 			case RPROTDIS:
2304 				stp->sd_read_opt =
2305 				    ((stp->sd_read_opt & ~RD_PROTDAT) |
2306 				    RD_PROTDIS);
2307 				break;
2308 			}
2309 			switch (sop->so_readopt & RFLUSHMASK) {
2310 			case RFLUSHPCPROT:
2311 				/*
2312 				 * This sets the stream head to NOT flush
2313 				 * M_PCPROTO messages.
2314 				 */
2315 				stp->sd_read_opt |= RFLUSHPCPROT;
2316 				break;
2317 			}
2318 		}
2319 		if (sop->so_flags & SO_ERROPT) {
2320 			switch (sop->so_erropt & RERRMASK) {
2321 			case RERRNORM:
2322 				stp->sd_flag &= ~STRDERRNONPERSIST;
2323 				break;
2324 			case RERRNONPERSIST:
2325 				stp->sd_flag |= STRDERRNONPERSIST;
2326 				break;
2327 			}
2328 			switch (sop->so_erropt & WERRMASK) {
2329 			case WERRNORM:
2330 				stp->sd_flag &= ~STWRERRNONPERSIST;
2331 				break;
2332 			case WERRNONPERSIST:
2333 				stp->sd_flag |= STWRERRNONPERSIST;
2334 				break;
2335 			}
2336 		}
2337 		if (sop->so_flags & SO_COPYOPT) {
2338 			if (sop->so_copyopt & ZCVMSAFE) {
2339 				stp->sd_copyflag |= STZCVMSAFE;
2340 				stp->sd_copyflag &= ~STZCVMUNSAFE;
2341 			} else if (sop->so_copyopt & ZCVMUNSAFE) {
2342 				stp->sd_copyflag |= STZCVMUNSAFE;
2343 				stp->sd_copyflag &= ~STZCVMSAFE;
2344 			}
2345 
2346 			if (sop->so_copyopt & COPYCACHED) {
2347 				stp->sd_copyflag |= STRCOPYCACHED;
2348 			}
2349 		}
2350 		if (sop->so_flags & SO_WROFF)
2351 			stp->sd_wroff = sop->so_wroff;
2352 		if (sop->so_flags & SO_TAIL)
2353 			stp->sd_tail = sop->so_tail;
2354 		if (sop->so_flags & SO_MINPSZ)
2355 			q->q_minpsz = sop->so_minpsz;
2356 		if (sop->so_flags & SO_MAXPSZ)
2357 			q->q_maxpsz = sop->so_maxpsz;
2358 		if (sop->so_flags & SO_MAXBLK)
2359 			stp->sd_maxblk = sop->so_maxblk;
2360 		if (sop->so_flags & SO_HIWAT) {
2361 			if (sop->so_flags & SO_BAND) {
2362 				if (strqset(q, QHIWAT,
2363 				    sop->so_band, sop->so_hiwat)) {
2364 					cmn_err(CE_WARN, "strrput: could not "
2365 					    "allocate qband\n");
2366 				} else {
2367 					bpri = sop->so_band;
2368 				}
2369 			} else {
2370 				q->q_hiwat = sop->so_hiwat;
2371 			}
2372 		}
2373 		if (sop->so_flags & SO_LOWAT) {
2374 			if (sop->so_flags & SO_BAND) {
2375 				if (strqset(q, QLOWAT,
2376 				    sop->so_band, sop->so_lowat)) {
2377 					cmn_err(CE_WARN, "strrput: could not "
2378 					    "allocate qband\n");
2379 				} else {
2380 					bpri = sop->so_band;
2381 				}
2382 			} else {
2383 				q->q_lowat = sop->so_lowat;
2384 			}
2385 		}
2386 		if (sop->so_flags & SO_MREADON)
2387 			stp->sd_flag |= SNDMREAD;
2388 		if (sop->so_flags & SO_MREADOFF)
2389 			stp->sd_flag &= ~SNDMREAD;
2390 		if (sop->so_flags & SO_NDELON)
2391 			stp->sd_flag |= OLDNDELAY;
2392 		if (sop->so_flags & SO_NDELOFF)
2393 			stp->sd_flag &= ~OLDNDELAY;
2394 		if (sop->so_flags & SO_ISTTY)
2395 			stp->sd_flag |= STRISTTY;
2396 		if (sop->so_flags & SO_ISNTTY)
2397 			stp->sd_flag &= ~STRISTTY;
2398 		if (sop->so_flags & SO_TOSTOP)
2399 			stp->sd_flag |= STRTOSTOP;
2400 		if (sop->so_flags & SO_TONSTOP)
2401 			stp->sd_flag &= ~STRTOSTOP;
2402 		if (sop->so_flags & SO_DELIM)
2403 			stp->sd_flag |= STRDELIM;
2404 		if (sop->so_flags & SO_NODELIM)
2405 			stp->sd_flag &= ~STRDELIM;
2406 
2407 		mutex_exit(&stp->sd_lock);
2408 		freemsg(bp);
2409 
2410 		/* Check backenable in case the water marks changed */
2411 		qbackenable(q, bpri);
2412 		return (0);
2413 
2414 	/*
2415 	 * The following set of cases deal with situations where two stream
2416 	 * heads are connected to each other (twisted streams).  These messages
2417 	 * have no meaning at the stream head.
2418 	 */
2419 	case M_BREAK:
2420 	case M_CTL:
2421 	case M_DELAY:
2422 	case M_START:
2423 	case M_STOP:
2424 	case M_IOCDATA:
2425 	case M_STARTI:
2426 	case M_STOPI:
2427 		freemsg(bp);
2428 		return (0);
2429 
2430 	case M_IOCTL:
2431 		/*
2432 		 * Always NAK this condition
2433 		 * (makes no sense)
2434 		 * If there is one or more threads in the read side
2435 		 * rwnext we have to defer the nacking until that thread
2436 		 * returns (in strget).
2437 		 */
2438 		mutex_enter(&stp->sd_lock);
2439 		if (stp->sd_struiodnak != 0) {
2440 			/*
2441 			 * Defer NAK to the streamhead. Queue at the end
2442 			 * the list.
2443 			 */
2444 			mblk_t *mp = stp->sd_struionak;
2445 
2446 			while (mp && mp->b_next)
2447 				mp = mp->b_next;
2448 			if (mp)
2449 				mp->b_next = bp;
2450 			else
2451 				stp->sd_struionak = bp;
2452 			bp->b_next = NULL;
2453 			mutex_exit(&stp->sd_lock);
2454 			return (0);
2455 		}
2456 		mutex_exit(&stp->sd_lock);
2457 
2458 		bp->b_datap->db_type = M_IOCNAK;
2459 		/*
2460 		 * Protect against the driver passing up
2461 		 * messages after it has done a qprocsoff.
2462 		 */
2463 		if (_OTHERQ(q)->q_next == NULL)
2464 			freemsg(bp);
2465 		else
2466 			qreply(q, bp);
2467 		return (0);
2468 
2469 	default:
2470 #ifdef DEBUG
2471 		cmn_err(CE_WARN,
2472 		    "bad message type %x received at stream head\n",
2473 		    bp->b_datap->db_type);
2474 #endif
2475 		freemsg(bp);
2476 		return (0);
2477 	}
2478 
2479 	/* NOTREACHED */
2480 }
2481 
2482 /*
2483  * Check if the stream pointed to by `stp' can be written to, and return an
2484  * error code if not.  If `eiohup' is set, then return EIO if STRHUP is set.
2485  * If `sigpipeok' is set and the SW_SIGPIPE option is enabled on the stream,
2486  * then always return EPIPE and send a SIGPIPE to the invoking thread.
2487  */
2488 static int
2489 strwriteable(struct stdata *stp, boolean_t eiohup, boolean_t sigpipeok)
2490 {
2491 	int error;
2492 
2493 	ASSERT(MUTEX_HELD(&stp->sd_lock));
2494 
2495 	/*
2496 	 * For modem support, POSIX states that on writes, EIO should
2497 	 * be returned if the stream has been hung up.
2498 	 */
2499 	if (eiohup && (stp->sd_flag & (STPLEX|STRHUP)) == STRHUP)
2500 		error = EIO;
2501 	else
2502 		error = strgeterr(stp, STRHUP|STPLEX|STWRERR, 0);
2503 
2504 	if (error != 0) {
2505 		if (!(stp->sd_flag & STPLEX) &&
2506 		    (stp->sd_wput_opt & SW_SIGPIPE) && sigpipeok) {
2507 			tsignal(curthread, SIGPIPE);
2508 			error = EPIPE;
2509 		}
2510 	}
2511 
2512 	return (error);
2513 }
2514 
2515 /*
2516  * Copyin and send data down a stream.
2517  * The caller will allocate and copyin any control part that precedes the
2518  * message and pass than in as mctl.
2519  *
2520  * Caller should *not* hold sd_lock.
2521  * When EWOULDBLOCK is returned the caller has to redo the canputnext
2522  * under sd_lock in order to avoid missing a backenabling wakeup.
2523  *
2524  * Use iosize = -1 to not send any M_DATA. iosize = 0 sends zero-length M_DATA.
2525  *
2526  * Set MSG_IGNFLOW in flags to ignore flow control for hipri messages.
2527  * For sync streams we can only ignore flow control by reverting to using
2528  * putnext.
2529  *
2530  * If sd_maxblk is less than *iosize this routine might return without
2531  * transferring all of *iosize. In all cases, on return *iosize will contain
2532  * the amount of data that was transferred.
2533  */
2534 static int
2535 strput(struct stdata *stp, mblk_t *mctl, struct uio *uiop, ssize_t *iosize,
2536     int b_flag, int pri, int flags)
2537 {
2538 	struiod_t uiod;
2539 	mblk_t *mp;
2540 	queue_t *wqp = stp->sd_wrq;
2541 	int error = 0;
2542 	ssize_t count = *iosize;
2543 	cred_t *cr;
2544 
2545 	ASSERT(MUTEX_NOT_HELD(&stp->sd_lock));
2546 
2547 	if (uiop != NULL && count >= 0)
2548 		flags |= stp->sd_struiowrq ? STRUIO_POSTPONE : 0;
2549 
2550 	if (!(flags & STRUIO_POSTPONE)) {
2551 		/*
2552 		 * Use regular canputnext, strmakedata, putnext sequence.
2553 		 */
2554 		if (pri == 0) {
2555 			if (!canputnext(wqp) && !(flags & MSG_IGNFLOW)) {
2556 				freemsg(mctl);
2557 				return (EWOULDBLOCK);
2558 			}
2559 		} else {
2560 			if (!(flags & MSG_IGNFLOW) && !bcanputnext(wqp, pri)) {
2561 				freemsg(mctl);
2562 				return (EWOULDBLOCK);
2563 			}
2564 		}
2565 
2566 		if ((error = strmakedata(iosize, uiop, stp, flags,
2567 		    &mp)) != 0) {
2568 			freemsg(mctl);
2569 			/*
2570 			 * need to change return code to ENOMEM
2571 			 * so that this is not confused with
2572 			 * flow control, EAGAIN.
2573 			 */
2574 
2575 			if (error == EAGAIN)
2576 				return (ENOMEM);
2577 			else
2578 				return (error);
2579 		}
2580 		if (mctl != NULL) {
2581 			if (mctl->b_cont == NULL)
2582 				mctl->b_cont = mp;
2583 			else if (mp != NULL)
2584 				linkb(mctl, mp);
2585 			mp = mctl;
2586 			/*
2587 			 * Note that for interrupt thread, the CRED() is
2588 			 * NULL. Don't bother with the pid either.
2589 			 */
2590 			if ((cr = CRED()) != NULL) {
2591 				mblk_setcred(mp, cr);
2592 				DB_CPID(mp) = curproc->p_pid;
2593 			}
2594 		} else if (mp == NULL)
2595 			return (0);
2596 
2597 		mp->b_flag |= b_flag;
2598 		mp->b_band = (uchar_t)pri;
2599 
2600 		if (flags & MSG_IGNFLOW) {
2601 			/*
2602 			 * XXX Hack: Don't get stuck running service
2603 			 * procedures. This is needed for sockfs when
2604 			 * sending the unbind message out of the rput
2605 			 * procedure - we don't want a put procedure
2606 			 * to run service procedures.
2607 			 */
2608 			putnext(wqp, mp);
2609 		} else {
2610 			stream_willservice(stp);
2611 			putnext(wqp, mp);
2612 			stream_runservice(stp);
2613 		}
2614 		return (0);
2615 	}
2616 	/*
2617 	 * Stream supports rwnext() for the write side.
2618 	 */
2619 	if ((error = strmakedata(iosize, uiop, stp, flags, &mp)) != 0) {
2620 		freemsg(mctl);
2621 		/*
2622 		 * map EAGAIN to ENOMEM since EAGAIN means "flow controlled".
2623 		 */
2624 		return (error == EAGAIN ? ENOMEM : error);
2625 	}
2626 	if (mctl != NULL) {
2627 		if (mctl->b_cont == NULL)
2628 			mctl->b_cont = mp;
2629 		else if (mp != NULL)
2630 			linkb(mctl, mp);
2631 		mp = mctl;
2632 		/*
2633 		 * Note that for interrupt thread, the CRED() is
2634 		 * NULL.  Don't bother with the pid either.
2635 		 */
2636 		if ((cr = CRED()) != NULL) {
2637 			mblk_setcred(mp, cr);
2638 			DB_CPID(mp) = curproc->p_pid;
2639 		}
2640 	} else if (mp == NULL) {
2641 		return (0);
2642 	}
2643 
2644 	mp->b_flag |= b_flag;
2645 	mp->b_band = (uchar_t)pri;
2646 
2647 	(void) uiodup(uiop, &uiod.d_uio, uiod.d_iov,
2648 	    sizeof (uiod.d_iov) / sizeof (*uiod.d_iov));
2649 	uiod.d_uio.uio_offset = 0;
2650 	uiod.d_mp = mp;
2651 	error = rwnext(wqp, &uiod);
2652 	if (! uiod.d_mp) {
2653 		uioskip(uiop, *iosize);
2654 		return (error);
2655 	}
2656 	ASSERT(mp == uiod.d_mp);
2657 	if (error == EINVAL) {
2658 		/*
2659 		 * The stream plumbing must have changed while
2660 		 * we were away, so just turn off rwnext()s.
2661 		 */
2662 		error = 0;
2663 	} else if (error == EBUSY || error == EWOULDBLOCK) {
2664 		/*
2665 		 * Couldn't enter a perimeter or took a page fault,
2666 		 * so fall-back to putnext().
2667 		 */
2668 		error = 0;
2669 	} else {
2670 		freemsg(mp);
2671 		return (error);
2672 	}
2673 	/* Have to check canput before consuming data from the uio */
2674 	if (pri == 0) {
2675 		if (!canputnext(wqp) && !(flags & MSG_IGNFLOW)) {
2676 			freemsg(mp);
2677 			return (EWOULDBLOCK);
2678 		}
2679 	} else {
2680 		if (!bcanputnext(wqp, pri) && !(flags & MSG_IGNFLOW)) {
2681 			freemsg(mp);
2682 			return (EWOULDBLOCK);
2683 		}
2684 	}
2685 	ASSERT(mp == uiod.d_mp);
2686 	/* Copyin data from the uio */
2687 	if ((error = struioget(wqp, mp, &uiod, 0)) != 0) {
2688 		freemsg(mp);
2689 		return (error);
2690 	}
2691 	uioskip(uiop, *iosize);
2692 	if (flags & MSG_IGNFLOW) {
2693 		/*
2694 		 * XXX Hack: Don't get stuck running service procedures.
2695 		 * This is needed for sockfs when sending the unbind message
2696 		 * out of the rput procedure - we don't want a put procedure
2697 		 * to run service procedures.
2698 		 */
2699 		putnext(wqp, mp);
2700 	} else {
2701 		stream_willservice(stp);
2702 		putnext(wqp, mp);
2703 		stream_runservice(stp);
2704 	}
2705 	return (0);
2706 }
2707 
2708 /*
2709  * Write attempts to break the write request into messages conforming
2710  * with the minimum and maximum packet sizes set downstream.
2711  *
2712  * Write will not block if downstream queue is full and
2713  * O_NDELAY is set, otherwise it will block waiting for the queue to get room.
2714  *
2715  * A write of zero bytes gets packaged into a zero length message and sent
2716  * downstream like any other message.
2717  *
2718  * If buffers of the requested sizes are not available, the write will
2719  * sleep until the buffers become available.
2720  *
2721  * Write (if specified) will supply a write offset in a message if it
2722  * makes sense. This can be specified by downstream modules as part of
2723  * a M_SETOPTS message.  Write will not supply the write offset if it
2724  * cannot supply any data in a buffer.  In other words, write will never
2725  * send down an empty packet due to a write offset.
2726  */
2727 /* ARGSUSED2 */
2728 int
2729 strwrite(struct vnode *vp, struct uio *uiop, cred_t *crp)
2730 {
2731 	return (strwrite_common(vp, uiop, crp, 0));
2732 }
2733 
2734 /* ARGSUSED2 */
2735 int
2736 strwrite_common(struct vnode *vp, struct uio *uiop, cred_t *crp, int wflag)
2737 {
2738 	struct stdata *stp;
2739 	struct queue *wqp;
2740 	ssize_t rmin, rmax;
2741 	ssize_t iosize;
2742 	int waitflag;
2743 	int tempmode;
2744 	int error = 0;
2745 	int b_flag;
2746 
2747 	ASSERT(vp->v_stream);
2748 	stp = vp->v_stream;
2749 
2750 	mutex_enter(&stp->sd_lock);
2751 
2752 	if ((error = i_straccess(stp, JCWRITE)) != 0) {
2753 		mutex_exit(&stp->sd_lock);
2754 		return (error);
2755 	}
2756 
2757 	if (stp->sd_flag & (STWRERR|STRHUP|STPLEX)) {
2758 		error = strwriteable(stp, B_TRUE, B_TRUE);
2759 		if (error != 0) {
2760 			mutex_exit(&stp->sd_lock);
2761 			return (error);
2762 		}
2763 	}
2764 
2765 	mutex_exit(&stp->sd_lock);
2766 
2767 	wqp = stp->sd_wrq;
2768 
2769 	/* get these values from them cached in the stream head */
2770 	rmin = stp->sd_qn_minpsz;
2771 	rmax = stp->sd_qn_maxpsz;
2772 
2773 	/*
2774 	 * Check the min/max packet size constraints.  If min packet size
2775 	 * is non-zero, the write cannot be split into multiple messages
2776 	 * and still guarantee the size constraints.
2777 	 */
2778 	TRACE_1(TR_FAC_STREAMS_FR, TR_STRWRITE_IN, "strwrite in:q %p", wqp);
2779 
2780 	ASSERT((rmax >= 0) || (rmax == INFPSZ));
2781 	if (rmax == 0) {
2782 		return (0);
2783 	}
2784 	if (rmin > 0) {
2785 		if (uiop->uio_resid < rmin) {
2786 			TRACE_3(TR_FAC_STREAMS_FR, TR_STRWRITE_OUT,
2787 			    "strwrite out:q %p out %d error %d",
2788 			    wqp, 0, ERANGE);
2789 			return (ERANGE);
2790 		}
2791 		if ((rmax != INFPSZ) && (uiop->uio_resid > rmax)) {
2792 			TRACE_3(TR_FAC_STREAMS_FR, TR_STRWRITE_OUT,
2793 			    "strwrite out:q %p out %d error %d",
2794 			    wqp, 1, ERANGE);
2795 			return (ERANGE);
2796 		}
2797 	}
2798 
2799 	/*
2800 	 * Do until count satisfied or error.
2801 	 */
2802 	waitflag = WRITEWAIT | wflag;
2803 	if (stp->sd_flag & OLDNDELAY)
2804 		tempmode = uiop->uio_fmode & ~FNDELAY;
2805 	else
2806 		tempmode = uiop->uio_fmode;
2807 
2808 	if (rmax == INFPSZ)
2809 		rmax = uiop->uio_resid;
2810 
2811 	/*
2812 	 * Note that tempmode does not get used in strput/strmakedata
2813 	 * but only in strwaitq. The other routines use uio_fmode
2814 	 * unmodified.
2815 	 */
2816 
2817 	/* LINTED: constant in conditional context */
2818 	while (1) {	/* breaks when uio_resid reaches zero */
2819 		/*
2820 		 * Determine the size of the next message to be
2821 		 * packaged.  May have to break write into several
2822 		 * messages based on max packet size.
2823 		 */
2824 		iosize = MIN(uiop->uio_resid, rmax);
2825 
2826 		/*
2827 		 * Put block downstream when flow control allows it.
2828 		 */
2829 		if ((stp->sd_flag & STRDELIM) && (uiop->uio_resid == iosize))
2830 			b_flag = MSGDELIM;
2831 		else
2832 			b_flag = 0;
2833 
2834 		for (;;) {
2835 			int done = 0;
2836 
2837 			error = strput(stp, NULL, uiop, &iosize, b_flag, 0, 0);
2838 			if (error == 0)
2839 				break;
2840 			if (error != EWOULDBLOCK)
2841 				goto out;
2842 
2843 			mutex_enter(&stp->sd_lock);
2844 			/*
2845 			 * Check for a missed wakeup.
2846 			 * Needed since strput did not hold sd_lock across
2847 			 * the canputnext.
2848 			 */
2849 			if (canputnext(wqp)) {
2850 				/* Try again */
2851 				mutex_exit(&stp->sd_lock);
2852 				continue;
2853 			}
2854 			TRACE_1(TR_FAC_STREAMS_FR, TR_STRWRITE_WAIT,
2855 			    "strwrite wait:q %p wait", wqp);
2856 			if ((error = strwaitq(stp, waitflag, (ssize_t)0,
2857 			    tempmode, -1, &done)) != 0 || done) {
2858 				mutex_exit(&stp->sd_lock);
2859 				if ((vp->v_type == VFIFO) &&
2860 				    (uiop->uio_fmode & FNDELAY) &&
2861 				    (error == EAGAIN))
2862 					error = 0;
2863 				goto out;
2864 			}
2865 			TRACE_1(TR_FAC_STREAMS_FR, TR_STRWRITE_WAKE,
2866 			    "strwrite wake:q %p awakes", wqp);
2867 			if ((error = i_straccess(stp, JCWRITE)) != 0) {
2868 				mutex_exit(&stp->sd_lock);
2869 				goto out;
2870 			}
2871 			mutex_exit(&stp->sd_lock);
2872 		}
2873 		waitflag |= NOINTR;
2874 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRWRITE_RESID,
2875 		    "strwrite resid:q %p uiop %p", wqp, uiop);
2876 		if (uiop->uio_resid) {
2877 			/* Recheck for errors - needed for sockets */
2878 			if ((stp->sd_wput_opt & SW_RECHECK_ERR) &&
2879 			    (stp->sd_flag & (STWRERR|STRHUP|STPLEX))) {
2880 				mutex_enter(&stp->sd_lock);
2881 				error = strwriteable(stp, B_FALSE, B_TRUE);
2882 				mutex_exit(&stp->sd_lock);
2883 				if (error != 0)
2884 					return (error);
2885 			}
2886 			continue;
2887 		}
2888 		break;
2889 	}
2890 out:
2891 	/*
2892 	 * For historical reasons, applications expect EAGAIN when a data
2893 	 * mblk_t cannot be allocated, so change ENOMEM back to EAGAIN.
2894 	 */
2895 	if (error == ENOMEM)
2896 		error = EAGAIN;
2897 	TRACE_3(TR_FAC_STREAMS_FR, TR_STRWRITE_OUT,
2898 	    "strwrite out:q %p out %d error %d", wqp, 2, error);
2899 	return (error);
2900 }
2901 
2902 /*
2903  * Stream head write service routine.
2904  * Its job is to wake up any sleeping writers when a queue
2905  * downstream needs data (part of the flow control in putq and getq).
2906  * It also must wake anyone sleeping on a poll().
2907  * For stream head right below mux module, it must also invoke put procedure
2908  * of next downstream module.
2909  */
2910 int
2911 strwsrv(queue_t *q)
2912 {
2913 	struct stdata *stp;
2914 	queue_t *tq;
2915 	qband_t *qbp;
2916 	int i;
2917 	qband_t *myqbp;
2918 	int isevent;
2919 	unsigned char	qbf[NBAND];	/* band flushing backenable flags */
2920 
2921 	TRACE_1(TR_FAC_STREAMS_FR,
2922 	    TR_STRWSRV, "strwsrv:q %p", q);
2923 	stp = (struct stdata *)q->q_ptr;
2924 	ASSERT(qclaimed(q));
2925 	mutex_enter(&stp->sd_lock);
2926 	ASSERT(!(stp->sd_flag & STPLEX));
2927 
2928 	if (stp->sd_flag & WSLEEP) {
2929 		stp->sd_flag &= ~WSLEEP;
2930 		cv_broadcast(&q->q_wait);
2931 	}
2932 	mutex_exit(&stp->sd_lock);
2933 
2934 	/* The other end of a stream pipe went away. */
2935 	if ((tq = q->q_next) == NULL) {
2936 		return (0);
2937 	}
2938 
2939 	/* Find the next module forward that has a service procedure */
2940 	claimstr(q);
2941 	tq = q->q_nfsrv;
2942 	ASSERT(tq != NULL);
2943 
2944 	if ((q->q_flag & QBACK)) {
2945 		if ((tq->q_flag & QFULL)) {
2946 			mutex_enter(QLOCK(tq));
2947 			if (!(tq->q_flag & QFULL)) {
2948 				mutex_exit(QLOCK(tq));
2949 				goto wakeup;
2950 			}
2951 			/*
2952 			 * The queue must have become full again. Set QWANTW
2953 			 * again so strwsrv will be back enabled when
2954 			 * the queue becomes non-full next time.
2955 			 */
2956 			tq->q_flag |= QWANTW;
2957 			mutex_exit(QLOCK(tq));
2958 		} else {
2959 		wakeup:
2960 			pollwakeup(&stp->sd_pollist, POLLWRNORM);
2961 			mutex_enter(&stp->sd_lock);
2962 			if (stp->sd_sigflags & S_WRNORM)
2963 				strsendsig(stp->sd_siglist, S_WRNORM, 0, 0);
2964 			mutex_exit(&stp->sd_lock);
2965 		}
2966 	}
2967 
2968 	isevent = 0;
2969 	i = 1;
2970 	bzero((caddr_t)qbf, NBAND);
2971 	mutex_enter(QLOCK(tq));
2972 	if ((myqbp = q->q_bandp) != NULL)
2973 		for (qbp = tq->q_bandp; qbp && myqbp; qbp = qbp->qb_next) {
2974 			ASSERT(myqbp);
2975 			if ((myqbp->qb_flag & QB_BACK)) {
2976 				if (qbp->qb_flag & QB_FULL) {
2977 					/*
2978 					 * The band must have become full again.
2979 					 * Set QB_WANTW again so strwsrv will
2980 					 * be back enabled when the band becomes
2981 					 * non-full next time.
2982 					 */
2983 					qbp->qb_flag |= QB_WANTW;
2984 				} else {
2985 					isevent = 1;
2986 					qbf[i] = 1;
2987 				}
2988 			}
2989 			myqbp = myqbp->qb_next;
2990 			i++;
2991 		}
2992 	mutex_exit(QLOCK(tq));
2993 
2994 	if (isevent) {
2995 		for (i = tq->q_nband; i; i--) {
2996 			if (qbf[i]) {
2997 				pollwakeup(&stp->sd_pollist, POLLWRBAND);
2998 				mutex_enter(&stp->sd_lock);
2999 				if (stp->sd_sigflags & S_WRBAND)
3000 					strsendsig(stp->sd_siglist, S_WRBAND,
3001 					    (uchar_t)i, 0);
3002 				mutex_exit(&stp->sd_lock);
3003 			}
3004 		}
3005 	}
3006 
3007 	releasestr(q);
3008 	return (0);
3009 }
3010 
3011 /*
3012  * Special case of strcopyin/strcopyout for copying
3013  * struct strioctl that can deal with both data
3014  * models.
3015  */
3016 
3017 #ifdef	_LP64
3018 
3019 static int
3020 strcopyin_strioctl(void *from, void *to, int flag, int copyflag)
3021 {
3022 	struct	strioctl32 strioc32;
3023 	struct	strioctl *striocp;
3024 
3025 	if (copyflag & U_TO_K) {
3026 		ASSERT((copyflag & K_TO_K) == 0);
3027 
3028 		if ((flag & FMODELS) == DATAMODEL_ILP32) {
3029 			if (copyin(from, &strioc32, sizeof (strioc32)))
3030 				return (EFAULT);
3031 
3032 			striocp = (struct strioctl *)to;
3033 			striocp->ic_cmd	= strioc32.ic_cmd;
3034 			striocp->ic_timout = strioc32.ic_timout;
3035 			striocp->ic_len	= strioc32.ic_len;
3036 			striocp->ic_dp	= (char *)(uintptr_t)strioc32.ic_dp;
3037 
3038 		} else { /* NATIVE data model */
3039 			if (copyin(from, to, sizeof (struct strioctl))) {
3040 				return (EFAULT);
3041 			} else {
3042 				return (0);
3043 			}
3044 		}
3045 	} else {
3046 		ASSERT(copyflag & K_TO_K);
3047 		bcopy(from, to, sizeof (struct strioctl));
3048 	}
3049 	return (0);
3050 }
3051 
3052 static int
3053 strcopyout_strioctl(void *from, void *to, int flag, int copyflag)
3054 {
3055 	struct	strioctl32 strioc32;
3056 	struct	strioctl *striocp;
3057 
3058 	if (copyflag & U_TO_K) {
3059 		ASSERT((copyflag & K_TO_K) == 0);
3060 
3061 		if ((flag & FMODELS) == DATAMODEL_ILP32) {
3062 			striocp = (struct strioctl *)from;
3063 			strioc32.ic_cmd	= striocp->ic_cmd;
3064 			strioc32.ic_timout = striocp->ic_timout;
3065 			strioc32.ic_len	= striocp->ic_len;
3066 			strioc32.ic_dp	= (caddr32_t)(uintptr_t)striocp->ic_dp;
3067 			ASSERT((char *)(uintptr_t)strioc32.ic_dp ==
3068 			    striocp->ic_dp);
3069 
3070 			if (copyout(&strioc32, to, sizeof (strioc32)))
3071 				return (EFAULT);
3072 
3073 		} else { /* NATIVE data model */
3074 			if (copyout(from, to, sizeof (struct strioctl))) {
3075 				return (EFAULT);
3076 			} else {
3077 				return (0);
3078 			}
3079 		}
3080 	} else {
3081 		ASSERT(copyflag & K_TO_K);
3082 		bcopy(from, to, sizeof (struct strioctl));
3083 	}
3084 	return (0);
3085 }
3086 
3087 #else	/* ! _LP64 */
3088 
3089 /* ARGSUSED2 */
3090 static int
3091 strcopyin_strioctl(void *from, void *to, int flag, int copyflag)
3092 {
3093 	return (strcopyin(from, to, sizeof (struct strioctl), copyflag));
3094 }
3095 
3096 /* ARGSUSED2 */
3097 static int
3098 strcopyout_strioctl(void *from, void *to, int flag, int copyflag)
3099 {
3100 	return (strcopyout(from, to, sizeof (struct strioctl), copyflag));
3101 }
3102 
3103 #endif	/* _LP64 */
3104 
3105 /*
3106  * Determine type of job control semantics expected by user.  The
3107  * possibilities are:
3108  *	JCREAD	- Behaves like read() on fd; send SIGTTIN
3109  *	JCWRITE	- Behaves like write() on fd; send SIGTTOU if TOSTOP set
3110  *	JCSETP	- Sets a value in the stream; send SIGTTOU, ignore TOSTOP
3111  *	JCGETP	- Gets a value in the stream; no signals.
3112  * See straccess in strsubr.c for usage of these values.
3113  *
3114  * This routine also returns -1 for I_STR as a special case; the
3115  * caller must call again with the real ioctl number for
3116  * classification.
3117  */
3118 static int
3119 job_control_type(int cmd)
3120 {
3121 	switch (cmd) {
3122 	case I_STR:
3123 		return (-1);
3124 
3125 	case I_RECVFD:
3126 	case I_E_RECVFD:
3127 		return (JCREAD);
3128 
3129 	case I_FDINSERT:
3130 	case I_SENDFD:
3131 		return (JCWRITE);
3132 
3133 	case TCSETA:
3134 	case TCSETAW:
3135 	case TCSETAF:
3136 	case TCSBRK:
3137 	case TCXONC:
3138 	case TCFLSH:
3139 	case TCDSET:	/* Obsolete */
3140 	case TIOCSWINSZ:
3141 	case TCSETS:
3142 	case TCSETSW:
3143 	case TCSETSF:
3144 	case TIOCSETD:
3145 	case TIOCHPCL:
3146 	case TIOCSETP:
3147 	case TIOCSETN:
3148 	case TIOCEXCL:
3149 	case TIOCNXCL:
3150 	case TIOCFLUSH:
3151 	case TIOCSETC:
3152 	case TIOCLBIS:
3153 	case TIOCLBIC:
3154 	case TIOCLSET:
3155 	case TIOCSBRK:
3156 	case TIOCCBRK:
3157 	case TIOCSDTR:
3158 	case TIOCCDTR:
3159 	case TIOCSLTC:
3160 	case TIOCSTOP:
3161 	case TIOCSTART:
3162 	case TIOCSTI:
3163 	case TIOCSPGRP:
3164 	case TIOCMSET:
3165 	case TIOCMBIS:
3166 	case TIOCMBIC:
3167 	case TIOCREMOTE:
3168 	case TIOCSIGNAL:
3169 	case LDSETT:
3170 	case LDSMAP:	/* Obsolete */
3171 	case DIOCSETP:
3172 	case I_FLUSH:
3173 	case I_SRDOPT:
3174 	case I_SETSIG:
3175 	case I_SWROPT:
3176 	case I_FLUSHBAND:
3177 	case I_SETCLTIME:
3178 	case I_SERROPT:
3179 	case I_ESETSIG:
3180 	case FIONBIO:
3181 	case FIOASYNC:
3182 	case FIOSETOWN:
3183 	case JBOOT:	/* Obsolete */
3184 	case JTERM:	/* Obsolete */
3185 	case JTIMOM:	/* Obsolete */
3186 	case JZOMBOOT:	/* Obsolete */
3187 	case JAGENT:	/* Obsolete */
3188 	case JTRUN:	/* Obsolete */
3189 	case JXTPROTO:	/* Obsolete */
3190 	case TIOCSETLD:
3191 		return (JCSETP);
3192 	}
3193 
3194 	return (JCGETP);
3195 }
3196 
3197 /*
3198  * ioctl for streams
3199  */
3200 int
3201 strioctl(struct vnode *vp, int cmd, intptr_t arg, int flag, int copyflag,
3202     cred_t *crp, int *rvalp)
3203 {
3204 	struct stdata *stp;
3205 	struct strcmd *scp;
3206 	struct strioctl strioc;
3207 	struct uio uio;
3208 	struct iovec iov;
3209 	int access;
3210 	mblk_t *mp;
3211 	int error = 0;
3212 	int done = 0;
3213 	ssize_t	rmin, rmax;
3214 	queue_t *wrq;
3215 	queue_t *rdq;
3216 	boolean_t kioctl = B_FALSE;
3217 
3218 	if (flag & FKIOCTL) {
3219 		copyflag = K_TO_K;
3220 		kioctl = B_TRUE;
3221 	}
3222 	ASSERT(vp->v_stream);
3223 	ASSERT(copyflag == U_TO_K || copyflag == K_TO_K);
3224 	stp = vp->v_stream;
3225 
3226 	TRACE_3(TR_FAC_STREAMS_FR, TR_IOCTL_ENTER,
3227 	    "strioctl:stp %p cmd %X arg %lX", stp, cmd, arg);
3228 
3229 	if (audit_active)
3230 		audit_strioctl(vp, cmd, arg, flag, copyflag, crp, rvalp);
3231 
3232 	/*
3233 	 * If the copy is kernel to kernel, make sure that the FNATIVE
3234 	 * flag is set.  After this it would be a serious error to have
3235 	 * no model flag.
3236 	 */
3237 	if (copyflag == K_TO_K)
3238 		flag = (flag & ~FMODELS) | FNATIVE;
3239 
3240 	ASSERT((flag & FMODELS) != 0);
3241 
3242 	wrq = stp->sd_wrq;
3243 	rdq = _RD(wrq);
3244 
3245 	access = job_control_type(cmd);
3246 
3247 	/* We should never see these here, should be handled by iwscn */
3248 	if (cmd == SRIOCSREDIR || cmd == SRIOCISREDIR)
3249 		return (EINVAL);
3250 
3251 	mutex_enter(&stp->sd_lock);
3252 	if ((access != -1) && ((error = i_straccess(stp, access)) != 0)) {
3253 		mutex_exit(&stp->sd_lock);
3254 		return (error);
3255 	}
3256 	mutex_exit(&stp->sd_lock);
3257 
3258 	/*
3259 	 * Check for sgttyb-related ioctls first, and complain as
3260 	 * necessary.
3261 	 */
3262 	switch (cmd) {
3263 	case TIOCGETP:
3264 	case TIOCSETP:
3265 	case TIOCSETN:
3266 		if (sgttyb_handling >= 2 && !sgttyb_complaint) {
3267 			sgttyb_complaint = B_TRUE;
3268 			cmn_err(CE_NOTE,
3269 			    "application used obsolete TIOC[GS]ET");
3270 		}
3271 		if (sgttyb_handling >= 3) {
3272 			tsignal(curthread, SIGSYS);
3273 			return (EIO);
3274 		}
3275 		break;
3276 	}
3277 
3278 	mutex_enter(&stp->sd_lock);
3279 
3280 	switch (cmd) {
3281 	case I_RECVFD:
3282 	case I_E_RECVFD:
3283 	case I_PEEK:
3284 	case I_NREAD:
3285 	case FIONREAD:
3286 	case FIORDCHK:
3287 	case I_ATMARK:
3288 	case FIONBIO:
3289 	case FIOASYNC:
3290 		if (stp->sd_flag & (STRDERR|STPLEX)) {
3291 			error = strgeterr(stp, STRDERR|STPLEX, 0);
3292 			if (error != 0) {
3293 				mutex_exit(&stp->sd_lock);
3294 				return (error);
3295 			}
3296 		}
3297 		break;
3298 
3299 	default:
3300 		if (stp->sd_flag & (STRDERR|STWRERR|STPLEX)) {
3301 			error = strgeterr(stp, STRDERR|STWRERR|STPLEX, 0);
3302 			if (error != 0) {
3303 				mutex_exit(&stp->sd_lock);
3304 				return (error);
3305 			}
3306 		}
3307 	}
3308 
3309 	mutex_exit(&stp->sd_lock);
3310 
3311 	switch (cmd) {
3312 	default:
3313 		/*
3314 		 * The stream head has hardcoded knowledge of a
3315 		 * miscellaneous collection of terminal-, keyboard- and
3316 		 * mouse-related ioctls, enumerated below.  This hardcoded
3317 		 * knowledge allows the stream head to automatically
3318 		 * convert transparent ioctl requests made by userland
3319 		 * programs into I_STR ioctls which many old STREAMS
3320 		 * modules and drivers require.
3321 		 *
3322 		 * No new ioctls should ever be added to this list.
3323 		 * Instead, the STREAMS module or driver should be written
3324 		 * to either handle transparent ioctls or require any
3325 		 * userland programs to use I_STR ioctls (by returning
3326 		 * EINVAL to any transparent ioctl requests).
3327 		 *
3328 		 * More importantly, removing ioctls from this list should
3329 		 * be done with the utmost care, since our STREAMS modules
3330 		 * and drivers *count* on the stream head performing this
3331 		 * conversion, and thus may panic while processing
3332 		 * transparent ioctl request for one of these ioctls (keep
3333 		 * in mind that third party modules and drivers may have
3334 		 * similar problems).
3335 		 */
3336 		if (((cmd & IOCTYPE) == LDIOC) ||
3337 		    ((cmd & IOCTYPE) == tIOC) ||
3338 		    ((cmd & IOCTYPE) == TIOC) ||
3339 		    ((cmd & IOCTYPE) == KIOC) ||
3340 		    ((cmd & IOCTYPE) == MSIOC) ||
3341 		    ((cmd & IOCTYPE) == VUIOC)) {
3342 			/*
3343 			 * The ioctl is a tty ioctl - set up strioc buffer
3344 			 * and call strdoioctl() to do the work.
3345 			 */
3346 			if (stp->sd_flag & STRHUP)
3347 				return (ENXIO);
3348 			strioc.ic_cmd = cmd;
3349 			strioc.ic_timout = INFTIM;
3350 
3351 			switch (cmd) {
3352 
3353 			case TCXONC:
3354 			case TCSBRK:
3355 			case TCFLSH:
3356 			case TCDSET:
3357 				{
3358 				int native_arg = (int)arg;
3359 				strioc.ic_len = sizeof (int);
3360 				strioc.ic_dp = (char *)&native_arg;
3361 				return (strdoioctl(stp, &strioc, flag,
3362 				    K_TO_K, crp, rvalp));
3363 				}
3364 
3365 			case TCSETA:
3366 			case TCSETAW:
3367 			case TCSETAF:
3368 				strioc.ic_len = sizeof (struct termio);
3369 				strioc.ic_dp = (char *)arg;
3370 				return (strdoioctl(stp, &strioc, flag,
3371 				    copyflag, crp, rvalp));
3372 
3373 			case TCSETS:
3374 			case TCSETSW:
3375 			case TCSETSF:
3376 				strioc.ic_len = sizeof (struct termios);
3377 				strioc.ic_dp = (char *)arg;
3378 				return (strdoioctl(stp, &strioc, flag,
3379 				    copyflag, crp, rvalp));
3380 
3381 			case LDSETT:
3382 				strioc.ic_len = sizeof (struct termcb);
3383 				strioc.ic_dp = (char *)arg;
3384 				return (strdoioctl(stp, &strioc, flag,
3385 				    copyflag, crp, rvalp));
3386 
3387 			case TIOCSETP:
3388 				strioc.ic_len = sizeof (struct sgttyb);
3389 				strioc.ic_dp = (char *)arg;
3390 				return (strdoioctl(stp, &strioc, flag,
3391 				    copyflag, crp, rvalp));
3392 
3393 			case TIOCSTI:
3394 				if ((flag & FREAD) == 0 &&
3395 				    secpolicy_sti(crp) != 0) {
3396 					return (EPERM);
3397 				}
3398 				mutex_enter(&stp->sd_lock);
3399 				mutex_enter(&curproc->p_splock);
3400 				if (stp->sd_sidp != curproc->p_sessp->s_sidp &&
3401 				    secpolicy_sti(crp) != 0) {
3402 					mutex_exit(&curproc->p_splock);
3403 					mutex_exit(&stp->sd_lock);
3404 					return (EACCES);
3405 				}
3406 				mutex_exit(&curproc->p_splock);
3407 				mutex_exit(&stp->sd_lock);
3408 
3409 				strioc.ic_len = sizeof (char);
3410 				strioc.ic_dp = (char *)arg;
3411 				return (strdoioctl(stp, &strioc, flag,
3412 				    copyflag, crp, rvalp));
3413 
3414 			case TIOCSWINSZ:
3415 				strioc.ic_len = sizeof (struct winsize);
3416 				strioc.ic_dp = (char *)arg;
3417 				return (strdoioctl(stp, &strioc, flag,
3418 				    copyflag, crp, rvalp));
3419 
3420 			case TIOCSSIZE:
3421 				strioc.ic_len = sizeof (struct ttysize);
3422 				strioc.ic_dp = (char *)arg;
3423 				return (strdoioctl(stp, &strioc, flag,
3424 				    copyflag, crp, rvalp));
3425 
3426 			case TIOCSSOFTCAR:
3427 			case KIOCTRANS:
3428 			case KIOCTRANSABLE:
3429 			case KIOCCMD:
3430 			case KIOCSDIRECT:
3431 			case KIOCSCOMPAT:
3432 			case KIOCSKABORTEN:
3433 			case KIOCSRPTDELAY:
3434 			case KIOCSRPTRATE:
3435 			case VUIDSFORMAT:
3436 			case TIOCSPPS:
3437 				strioc.ic_len = sizeof (int);
3438 				strioc.ic_dp = (char *)arg;
3439 				return (strdoioctl(stp, &strioc, flag,
3440 				    copyflag, crp, rvalp));
3441 
3442 			case KIOCSETKEY:
3443 			case KIOCGETKEY:
3444 				strioc.ic_len = sizeof (struct kiockey);
3445 				strioc.ic_dp = (char *)arg;
3446 				return (strdoioctl(stp, &strioc, flag,
3447 				    copyflag, crp, rvalp));
3448 
3449 			case KIOCSKEY:
3450 			case KIOCGKEY:
3451 				strioc.ic_len = sizeof (struct kiockeymap);
3452 				strioc.ic_dp = (char *)arg;
3453 				return (strdoioctl(stp, &strioc, flag,
3454 				    copyflag, crp, rvalp));
3455 
3456 			case KIOCSLED:
3457 				/* arg is a pointer to char */
3458 				strioc.ic_len = sizeof (char);
3459 				strioc.ic_dp = (char *)arg;
3460 				return (strdoioctl(stp, &strioc, flag,
3461 				    copyflag, crp, rvalp));
3462 
3463 			case MSIOSETPARMS:
3464 				strioc.ic_len = sizeof (Ms_parms);
3465 				strioc.ic_dp = (char *)arg;
3466 				return (strdoioctl(stp, &strioc, flag,
3467 				    copyflag, crp, rvalp));
3468 
3469 			case VUIDSADDR:
3470 			case VUIDGADDR:
3471 				strioc.ic_len = sizeof (struct vuid_addr_probe);
3472 				strioc.ic_dp = (char *)arg;
3473 				return (strdoioctl(stp, &strioc, flag,
3474 				    copyflag, crp, rvalp));
3475 
3476 			/*
3477 			 * These M_IOCTL's don't require any data to be sent
3478 			 * downstream, and the driver will allocate and link
3479 			 * on its own mblk_t upon M_IOCACK -- thus we set
3480 			 * ic_len to zero and set ic_dp to arg so we know
3481 			 * where to copyout to later.
3482 			 */
3483 			case TIOCGSOFTCAR:
3484 			case TIOCGWINSZ:
3485 			case TIOCGSIZE:
3486 			case KIOCGTRANS:
3487 			case KIOCGTRANSABLE:
3488 			case KIOCTYPE:
3489 			case KIOCGDIRECT:
3490 			case KIOCGCOMPAT:
3491 			case KIOCLAYOUT:
3492 			case KIOCGLED:
3493 			case MSIOGETPARMS:
3494 			case MSIOBUTTONS:
3495 			case VUIDGFORMAT:
3496 			case TIOCGPPS:
3497 			case TIOCGPPSEV:
3498 			case TCGETA:
3499 			case TCGETS:
3500 			case LDGETT:
3501 			case TIOCGETP:
3502 			case KIOCGRPTDELAY:
3503 			case KIOCGRPTRATE:
3504 				strioc.ic_len = 0;
3505 				strioc.ic_dp = (char *)arg;
3506 				return (strdoioctl(stp, &strioc, flag,
3507 				    copyflag, crp, rvalp));
3508 			}
3509 		}
3510 
3511 		/*
3512 		 * Unknown cmd - send it down as a transparent ioctl.
3513 		 */
3514 		strioc.ic_cmd = cmd;
3515 		strioc.ic_timout = INFTIM;
3516 		strioc.ic_len = TRANSPARENT;
3517 		strioc.ic_dp = (char *)&arg;
3518 
3519 		return (strdoioctl(stp, &strioc, flag, copyflag, crp, rvalp));
3520 
3521 	case I_STR:
3522 		/*
3523 		 * Stream ioctl.  Read in an strioctl buffer from the user
3524 		 * along with any data specified and send it downstream.
3525 		 * Strdoioctl will wait allow only one ioctl message at
3526 		 * a time, and waits for the acknowledgement.
3527 		 */
3528 
3529 		if (stp->sd_flag & STRHUP)
3530 			return (ENXIO);
3531 
3532 		error = strcopyin_strioctl((void *)arg, &strioc, flag,
3533 		    copyflag);
3534 		if (error != 0)
3535 			return (error);
3536 
3537 		if ((strioc.ic_len < 0) || (strioc.ic_timout < -1))
3538 			return (EINVAL);
3539 
3540 		access = job_control_type(strioc.ic_cmd);
3541 		mutex_enter(&stp->sd_lock);
3542 		if ((access != -1) &&
3543 		    ((error = i_straccess(stp, access)) != 0)) {
3544 			mutex_exit(&stp->sd_lock);
3545 			return (error);
3546 		}
3547 		mutex_exit(&stp->sd_lock);
3548 
3549 		/*
3550 		 * The I_STR facility provides a trap door for malicious
3551 		 * code to send down bogus streamio(7I) ioctl commands to
3552 		 * unsuspecting STREAMS modules and drivers which expect to
3553 		 * only get these messages from the stream head.
3554 		 * Explicitly prohibit any streamio ioctls which can be
3555 		 * passed downstream by the stream head.  Note that we do
3556 		 * not block all streamio ioctls because the ioctl
3557 		 * numberspace is not well managed and thus it's possible
3558 		 * that a module or driver's ioctl numbers may accidentally
3559 		 * collide with them.
3560 		 */
3561 		switch (strioc.ic_cmd) {
3562 		case I_LINK:
3563 		case I_PLINK:
3564 		case I_UNLINK:
3565 		case I_PUNLINK:
3566 		case _I_GETPEERCRED:
3567 		case _I_PLINK_LH:
3568 			return (EINVAL);
3569 		}
3570 
3571 		error = strdoioctl(stp, &strioc, flag, copyflag, crp, rvalp);
3572 		if (error == 0) {
3573 			error = strcopyout_strioctl(&strioc, (void *)arg,
3574 			    flag, copyflag);
3575 		}
3576 		return (error);
3577 
3578 	case _I_CMD:
3579 		/*
3580 		 * Like I_STR, but without using M_IOC* messages and without
3581 		 * copyins/copyouts beyond the passed-in argument.
3582 		 */
3583 		if (stp->sd_flag & STRHUP)
3584 			return (ENXIO);
3585 
3586 		if ((scp = kmem_alloc(sizeof (strcmd_t), KM_NOSLEEP)) == NULL)
3587 			return (ENOMEM);
3588 
3589 		if (copyin((void *)arg, scp, sizeof (strcmd_t))) {
3590 			kmem_free(scp, sizeof (strcmd_t));
3591 			return (EFAULT);
3592 		}
3593 
3594 		access = job_control_type(scp->sc_cmd);
3595 		mutex_enter(&stp->sd_lock);
3596 		if (access != -1 && (error = i_straccess(stp, access)) != 0) {
3597 			mutex_exit(&stp->sd_lock);
3598 			kmem_free(scp, sizeof (strcmd_t));
3599 			return (error);
3600 		}
3601 		mutex_exit(&stp->sd_lock);
3602 
3603 		*rvalp = 0;
3604 		if ((error = strdocmd(stp, scp, crp)) == 0) {
3605 			if (copyout(scp, (void *)arg, sizeof (strcmd_t)))
3606 				error = EFAULT;
3607 		}
3608 		kmem_free(scp, sizeof (strcmd_t));
3609 		return (error);
3610 
3611 	case I_NREAD:
3612 		/*
3613 		 * Return number of bytes of data in first message
3614 		 * in queue in "arg" and return the number of messages
3615 		 * in queue in return value.
3616 		 */
3617 	{
3618 		size_t	size;
3619 		int	retval;
3620 		int	count = 0;
3621 
3622 		mutex_enter(QLOCK(rdq));
3623 
3624 		size = msgdsize(rdq->q_first);
3625 		for (mp = rdq->q_first; mp != NULL; mp = mp->b_next)
3626 			count++;
3627 
3628 		mutex_exit(QLOCK(rdq));
3629 		if (stp->sd_struiordq) {
3630 			infod_t infod;
3631 
3632 			infod.d_cmd = INFOD_COUNT;
3633 			infod.d_count = 0;
3634 			if (count == 0) {
3635 				infod.d_cmd |= INFOD_FIRSTBYTES;
3636 				infod.d_bytes = 0;
3637 			}
3638 			infod.d_res = 0;
3639 			(void) infonext(rdq, &infod);
3640 			count += infod.d_count;
3641 			if (infod.d_res & INFOD_FIRSTBYTES)
3642 				size = infod.d_bytes;
3643 		}
3644 
3645 		/*
3646 		 * Drop down from size_t to the "int" required by the
3647 		 * interface.  Cap at INT_MAX.
3648 		 */
3649 		retval = MIN(size, INT_MAX);
3650 		error = strcopyout(&retval, (void *)arg, sizeof (retval),
3651 		    copyflag);
3652 		if (!error)
3653 			*rvalp = count;
3654 		return (error);
3655 	}
3656 
3657 	case FIONREAD:
3658 		/*
3659 		 * Return number of bytes of data in all data messages
3660 		 * in queue in "arg".
3661 		 */
3662 	{
3663 		size_t	size = 0;
3664 		int	retval;
3665 
3666 		mutex_enter(QLOCK(rdq));
3667 		for (mp = rdq->q_first; mp != NULL; mp = mp->b_next)
3668 			size += msgdsize(mp);
3669 		mutex_exit(QLOCK(rdq));
3670 
3671 		if (stp->sd_struiordq) {
3672 			infod_t infod;
3673 
3674 			infod.d_cmd = INFOD_BYTES;
3675 			infod.d_res = 0;
3676 			infod.d_bytes = 0;
3677 			(void) infonext(rdq, &infod);
3678 			size += infod.d_bytes;
3679 		}
3680 
3681 		/*
3682 		 * Drop down from size_t to the "int" required by the
3683 		 * interface.  Cap at INT_MAX.
3684 		 */
3685 		retval = MIN(size, INT_MAX);
3686 		error = strcopyout(&retval, (void *)arg, sizeof (retval),
3687 		    copyflag);
3688 
3689 		*rvalp = 0;
3690 		return (error);
3691 	}
3692 	case FIORDCHK:
3693 		/*
3694 		 * FIORDCHK does not use arg value (like FIONREAD),
3695 		 * instead a count is returned. I_NREAD value may
3696 		 * not be accurate but safe. The real thing to do is
3697 		 * to add the msgdsizes of all data  messages until
3698 		 * a non-data message.
3699 		 */
3700 	{
3701 		size_t size = 0;
3702 
3703 		mutex_enter(QLOCK(rdq));
3704 		for (mp = rdq->q_first; mp != NULL; mp = mp->b_next)
3705 			size += msgdsize(mp);
3706 		mutex_exit(QLOCK(rdq));
3707 
3708 		if (stp->sd_struiordq) {
3709 			infod_t infod;
3710 
3711 			infod.d_cmd = INFOD_BYTES;
3712 			infod.d_res = 0;
3713 			infod.d_bytes = 0;
3714 			(void) infonext(rdq, &infod);
3715 			size += infod.d_bytes;
3716 		}
3717 
3718 		/*
3719 		 * Since ioctl returns an int, and memory sizes under
3720 		 * LP64 may not fit, we return INT_MAX if the count was
3721 		 * actually greater.
3722 		 */
3723 		*rvalp = MIN(size, INT_MAX);
3724 		return (0);
3725 	}
3726 
3727 	case I_FIND:
3728 		/*
3729 		 * Get module name.
3730 		 */
3731 	{
3732 		char mname[FMNAMESZ + 1];
3733 		queue_t *q;
3734 
3735 		error = (copyflag & U_TO_K ? copyinstr : copystr)((void *)arg,
3736 		    mname, FMNAMESZ + 1, NULL);
3737 		if (error)
3738 			return ((error == ENAMETOOLONG) ? EINVAL : EFAULT);
3739 
3740 		/*
3741 		 * Return EINVAL if we're handed a bogus module name.
3742 		 */
3743 		if (fmodsw_find(mname, FMODSW_LOAD) == NULL) {
3744 			TRACE_0(TR_FAC_STREAMS_FR,
3745 			    TR_I_CANT_FIND, "couldn't I_FIND");
3746 			return (EINVAL);
3747 		}
3748 
3749 		*rvalp = 0;
3750 
3751 		/* Look downstream to see if module is there. */
3752 		claimstr(stp->sd_wrq);
3753 		for (q = stp->sd_wrq->q_next; q; q = q->q_next) {
3754 			if (q->q_flag&QREADR) {
3755 				q = NULL;
3756 				break;
3757 			}
3758 			if (strcmp(mname, q->q_qinfo->qi_minfo->mi_idname) == 0)
3759 				break;
3760 		}
3761 		releasestr(stp->sd_wrq);
3762 
3763 		*rvalp = (q ? 1 : 0);
3764 		return (error);
3765 	}
3766 
3767 	case I_PUSH:
3768 	case __I_PUSH_NOCTTY:
3769 		/*
3770 		 * Push a module.
3771 		 * For the case __I_PUSH_NOCTTY push a module but
3772 		 * do not allocate controlling tty. See bugid 4025044
3773 		 */
3774 
3775 	{
3776 		char mname[FMNAMESZ + 1];
3777 		fmodsw_impl_t *fp;
3778 		dev_t dummydev;
3779 
3780 		if (stp->sd_flag & STRHUP)
3781 			return (ENXIO);
3782 
3783 		/*
3784 		 * Get module name and look up in fmodsw.
3785 		 */
3786 		error = (copyflag & U_TO_K ? copyinstr : copystr)((void *)arg,
3787 		    mname, FMNAMESZ + 1, NULL);
3788 		if (error)
3789 			return ((error == ENAMETOOLONG) ? EINVAL : EFAULT);
3790 
3791 		if ((fp = fmodsw_find(mname, FMODSW_HOLD | FMODSW_LOAD)) ==
3792 		    NULL)
3793 			return (EINVAL);
3794 
3795 		TRACE_2(TR_FAC_STREAMS_FR, TR_I_PUSH,
3796 		    "I_PUSH:fp %p stp %p", fp, stp);
3797 
3798 		if (error = strstartplumb(stp, flag, cmd)) {
3799 			fmodsw_rele(fp);
3800 			return (error);
3801 		}
3802 
3803 		/*
3804 		 * See if any more modules can be pushed on this stream.
3805 		 * Note that this check must be done after strstartplumb()
3806 		 * since otherwise multiple threads issuing I_PUSHes on
3807 		 * the same stream will be able to exceed nstrpush.
3808 		 */
3809 		mutex_enter(&stp->sd_lock);
3810 		if (stp->sd_pushcnt >= nstrpush) {
3811 			fmodsw_rele(fp);
3812 			strendplumb(stp);
3813 			mutex_exit(&stp->sd_lock);
3814 			return (EINVAL);
3815 		}
3816 		mutex_exit(&stp->sd_lock);
3817 
3818 		/*
3819 		 * Push new module and call its open routine
3820 		 * via qattach().  Modules don't change device
3821 		 * numbers, so just ignore dummydev here.
3822 		 */
3823 		dummydev = vp->v_rdev;
3824 		if ((error = qattach(rdq, &dummydev, 0, crp, fp,
3825 		    B_FALSE)) == 0) {
3826 			if (vp->v_type == VCHR && /* sorry, no pipes allowed */
3827 			    (cmd == I_PUSH) && (stp->sd_flag & STRISTTY)) {
3828 				/*
3829 				 * try to allocate it as a controlling terminal
3830 				 */
3831 				(void) strctty(stp);
3832 			}
3833 		}
3834 
3835 		mutex_enter(&stp->sd_lock);
3836 
3837 		/*
3838 		 * As a performance concern we are caching the values of
3839 		 * q_minpsz and q_maxpsz of the module below the stream
3840 		 * head in the stream head.
3841 		 */
3842 		mutex_enter(QLOCK(stp->sd_wrq->q_next));
3843 		rmin = stp->sd_wrq->q_next->q_minpsz;
3844 		rmax = stp->sd_wrq->q_next->q_maxpsz;
3845 		mutex_exit(QLOCK(stp->sd_wrq->q_next));
3846 
3847 		/* Do this processing here as a performance concern */
3848 		if (strmsgsz != 0) {
3849 			if (rmax == INFPSZ)
3850 				rmax = strmsgsz;
3851 			else  {
3852 				if (vp->v_type == VFIFO)
3853 					rmax = MIN(PIPE_BUF, rmax);
3854 				else	rmax = MIN(strmsgsz, rmax);
3855 			}
3856 		}
3857 
3858 		mutex_enter(QLOCK(wrq));
3859 		stp->sd_qn_minpsz = rmin;
3860 		stp->sd_qn_maxpsz = rmax;
3861 		mutex_exit(QLOCK(wrq));
3862 
3863 		strendplumb(stp);
3864 		mutex_exit(&stp->sd_lock);
3865 		return (error);
3866 	}
3867 
3868 	case I_POP:
3869 	{
3870 		queue_t	*q;
3871 
3872 		if (stp->sd_flag & STRHUP)
3873 			return (ENXIO);
3874 		if (!wrq->q_next)	/* for broken pipes */
3875 			return (EINVAL);
3876 
3877 		if (error = strstartplumb(stp, flag, cmd))
3878 			return (error);
3879 
3880 		/*
3881 		 * If there is an anchor on this stream and popping
3882 		 * the current module would attempt to pop through the
3883 		 * anchor, then disallow the pop unless we have sufficient
3884 		 * privileges; take the cheapest (non-locking) check
3885 		 * first.
3886 		 */
3887 		if (secpolicy_ip_config(crp, B_TRUE) != 0 ||
3888 		    (stp->sd_anchorzone != crgetzoneid(crp))) {
3889 			mutex_enter(&stp->sd_lock);
3890 			/*
3891 			 * Anchors only apply if there's at least one
3892 			 * module on the stream (sd_pushcnt > 0).
3893 			 */
3894 			if (stp->sd_pushcnt > 0 &&
3895 			    stp->sd_pushcnt == stp->sd_anchor &&
3896 			    stp->sd_vnode->v_type != VFIFO) {
3897 				strendplumb(stp);
3898 				mutex_exit(&stp->sd_lock);
3899 				if (stp->sd_anchorzone != crgetzoneid(crp))
3900 					return (EINVAL);
3901 				/* Audit and report error */
3902 				return (secpolicy_ip_config(crp, B_FALSE));
3903 			}
3904 			mutex_exit(&stp->sd_lock);
3905 		}
3906 
3907 		q = wrq->q_next;
3908 		TRACE_2(TR_FAC_STREAMS_FR, TR_I_POP,
3909 		    "I_POP:%p from %p", q, stp);
3910 		if (q->q_next == NULL || (q->q_flag & (QREADR|QISDRV))) {
3911 			error = EINVAL;
3912 		} else {
3913 			qdetach(_RD(q), 1, flag, crp, B_FALSE);
3914 			error = 0;
3915 		}
3916 		mutex_enter(&stp->sd_lock);
3917 
3918 		/*
3919 		 * As a performance concern we are caching the values of
3920 		 * q_minpsz and q_maxpsz of the module below the stream
3921 		 * head in the stream head.
3922 		 */
3923 		mutex_enter(QLOCK(wrq->q_next));
3924 		rmin = wrq->q_next->q_minpsz;
3925 		rmax = wrq->q_next->q_maxpsz;
3926 		mutex_exit(QLOCK(wrq->q_next));
3927 
3928 		/* Do this processing here as a performance concern */
3929 		if (strmsgsz != 0) {
3930 			if (rmax == INFPSZ)
3931 				rmax = strmsgsz;
3932 			else  {
3933 				if (vp->v_type == VFIFO)
3934 					rmax = MIN(PIPE_BUF, rmax);
3935 				else	rmax = MIN(strmsgsz, rmax);
3936 			}
3937 		}
3938 
3939 		mutex_enter(QLOCK(wrq));
3940 		stp->sd_qn_minpsz = rmin;
3941 		stp->sd_qn_maxpsz = rmax;
3942 		mutex_exit(QLOCK(wrq));
3943 
3944 		/* If we popped through the anchor, then reset the anchor. */
3945 		if (stp->sd_pushcnt < stp->sd_anchor) {
3946 			stp->sd_anchor = 0;
3947 			stp->sd_anchorzone = 0;
3948 		}
3949 		strendplumb(stp);
3950 		mutex_exit(&stp->sd_lock);
3951 		return (error);
3952 	}
3953 
3954 	case _I_MUXID2FD:
3955 	{
3956 		/*
3957 		 * Create a fd for a I_PLINK'ed lower stream with a given
3958 		 * muxid.  With the fd, application can send down ioctls,
3959 		 * like I_LIST, to the previously I_PLINK'ed stream.  Note
3960 		 * that after getting the fd, the application has to do an
3961 		 * I_PUNLINK on the muxid before it can do any operation
3962 		 * on the lower stream.  This is required by spec1170.
3963 		 *
3964 		 * The fd used to do this ioctl should point to the same
3965 		 * controlling device used to do the I_PLINK.  If it uses
3966 		 * a different stream or an invalid muxid, I_MUXID2FD will
3967 		 * fail.  The error code is set to EINVAL.
3968 		 *
3969 		 * The intended use of this interface is the following.
3970 		 * An application I_PLINK'ed a stream and exits.  The fd
3971 		 * to the lower stream is gone.  Another application
3972 		 * wants to get a fd to the lower stream, it uses I_MUXID2FD.
3973 		 */
3974 		int muxid = (int)arg;
3975 		int fd;
3976 		linkinfo_t *linkp;
3977 		struct file *fp;
3978 		netstack_t *ns;
3979 		str_stack_t *ss;
3980 
3981 		/*
3982 		 * Do not allow the wildcard muxid.  This ioctl is not
3983 		 * intended to find arbitrary link.
3984 		 */
3985 		if (muxid == 0) {
3986 			return (EINVAL);
3987 		}
3988 
3989 		ns = netstack_find_by_cred(crp);
3990 		ASSERT(ns != NULL);
3991 		ss = ns->netstack_str;
3992 		ASSERT(ss != NULL);
3993 
3994 		mutex_enter(&muxifier);
3995 		linkp = findlinks(vp->v_stream, muxid, LINKPERSIST, ss);
3996 		if (linkp == NULL) {
3997 			mutex_exit(&muxifier);
3998 			netstack_rele(ss->ss_netstack);
3999 			return (EINVAL);
4000 		}
4001 
4002 		if ((fd = ufalloc(0)) == -1) {
4003 			mutex_exit(&muxifier);
4004 			netstack_rele(ss->ss_netstack);
4005 			return (EMFILE);
4006 		}
4007 		fp = linkp->li_fpdown;
4008 		mutex_enter(&fp->f_tlock);
4009 		fp->f_count++;
4010 		mutex_exit(&fp->f_tlock);
4011 		mutex_exit(&muxifier);
4012 		setf(fd, fp);
4013 		*rvalp = fd;
4014 		netstack_rele(ss->ss_netstack);
4015 		return (0);
4016 	}
4017 
4018 	case _I_INSERT:
4019 	{
4020 		/*
4021 		 * To insert a module to a given position in a stream.
4022 		 * In the first release, only allow privileged user
4023 		 * to use this ioctl. Furthermore, the insert is only allowed
4024 		 * below an anchor if the zoneid is the same as the zoneid
4025 		 * which created the anchor.
4026 		 *
4027 		 * Note that we do not plan to support this ioctl
4028 		 * on pipes in the first release.  We want to learn more
4029 		 * about the implications of these ioctls before extending
4030 		 * their support.  And we do not think these features are
4031 		 * valuable for pipes.
4032 		 *
4033 		 * Neither do we support O/C hot stream.  Note that only
4034 		 * the upper streams of TCP/IP stack are O/C hot streams.
4035 		 * The lower IP stream is not.
4036 		 * When there is a O/C cold barrier, we only allow inserts
4037 		 * above the barrier.
4038 		 */
4039 		STRUCT_DECL(strmodconf, strmodinsert);
4040 		char mod_name[FMNAMESZ + 1];
4041 		fmodsw_impl_t *fp;
4042 		dev_t dummydev;
4043 		queue_t *tmp_wrq;
4044 		int pos;
4045 		boolean_t is_insert;
4046 
4047 		STRUCT_INIT(strmodinsert, flag);
4048 		if (stp->sd_flag & STRHUP)
4049 			return (ENXIO);
4050 		if (STRMATED(stp))
4051 			return (EINVAL);
4052 		if ((error = secpolicy_net_config(crp, B_FALSE)) != 0)
4053 			return (error);
4054 		if (stp->sd_anchor != 0 &&
4055 		    stp->sd_anchorzone != crgetzoneid(crp))
4056 			return (EINVAL);
4057 
4058 		error = strcopyin((void *)arg, STRUCT_BUF(strmodinsert),
4059 		    STRUCT_SIZE(strmodinsert), copyflag);
4060 		if (error)
4061 			return (error);
4062 
4063 		/*
4064 		 * Get module name and look up in fmodsw.
4065 		 */
4066 		error = (copyflag & U_TO_K ? copyinstr :
4067 		    copystr)(STRUCT_FGETP(strmodinsert, mod_name),
4068 		    mod_name, FMNAMESZ + 1, NULL);
4069 		if (error)
4070 			return ((error == ENAMETOOLONG) ? EINVAL : EFAULT);
4071 
4072 		if ((fp = fmodsw_find(mod_name, FMODSW_HOLD | FMODSW_LOAD)) ==
4073 		    NULL)
4074 			return (EINVAL);
4075 
4076 		if (error = strstartplumb(stp, flag, cmd)) {
4077 			fmodsw_rele(fp);
4078 			return (error);
4079 		}
4080 
4081 		/*
4082 		 * Is this _I_INSERT just like an I_PUSH?  We need to know
4083 		 * this because we do some optimizations if this is a
4084 		 * module being pushed.
4085 		 */
4086 		pos = STRUCT_FGET(strmodinsert, pos);
4087 		is_insert = (pos != 0);
4088 
4089 		/*
4090 		 * Make sure pos is valid.  Even though it is not an I_PUSH,
4091 		 * we impose the same limit on the number of modules in a
4092 		 * stream.
4093 		 */
4094 		mutex_enter(&stp->sd_lock);
4095 		if (stp->sd_pushcnt >= nstrpush || pos < 0 ||
4096 		    pos > stp->sd_pushcnt) {
4097 			fmodsw_rele(fp);
4098 			strendplumb(stp);
4099 			mutex_exit(&stp->sd_lock);
4100 			return (EINVAL);
4101 		}
4102 		if (stp->sd_anchor != 0) {
4103 			/*
4104 			 * Is this insert below the anchor?
4105 			 * Pushcnt hasn't been increased yet hence
4106 			 * we test for greater than here, and greater or
4107 			 * equal after qattach.
4108 			 */
4109 			if (pos > (stp->sd_pushcnt - stp->sd_anchor) &&
4110 			    stp->sd_anchorzone != crgetzoneid(crp)) {
4111 				fmodsw_rele(fp);
4112 				strendplumb(stp);
4113 				mutex_exit(&stp->sd_lock);
4114 				return (EPERM);
4115 			}
4116 		}
4117 
4118 		mutex_exit(&stp->sd_lock);
4119 
4120 		/*
4121 		 * First find the correct position this module to
4122 		 * be inserted.  We don't need to call claimstr()
4123 		 * as the stream should not be changing at this point.
4124 		 *
4125 		 * Insert new module and call its open routine
4126 		 * via qattach().  Modules don't change device
4127 		 * numbers, so just ignore dummydev here.
4128 		 */
4129 		for (tmp_wrq = stp->sd_wrq; pos > 0;
4130 		    tmp_wrq = tmp_wrq->q_next, pos--) {
4131 			ASSERT(SAMESTR(tmp_wrq));
4132 		}
4133 		dummydev = vp->v_rdev;
4134 		if ((error = qattach(_RD(tmp_wrq), &dummydev, 0, crp,
4135 		    fp, is_insert)) != 0) {
4136 			mutex_enter(&stp->sd_lock);
4137 			strendplumb(stp);
4138 			mutex_exit(&stp->sd_lock);
4139 			return (error);
4140 		}
4141 
4142 		mutex_enter(&stp->sd_lock);
4143 
4144 		/*
4145 		 * As a performance concern we are caching the values of
4146 		 * q_minpsz and q_maxpsz of the module below the stream
4147 		 * head in the stream head.
4148 		 */
4149 		if (!is_insert) {
4150 			mutex_enter(QLOCK(stp->sd_wrq->q_next));
4151 			rmin = stp->sd_wrq->q_next->q_minpsz;
4152 			rmax = stp->sd_wrq->q_next->q_maxpsz;
4153 			mutex_exit(QLOCK(stp->sd_wrq->q_next));
4154 
4155 			/* Do this processing here as a performance concern */
4156 			if (strmsgsz != 0) {
4157 				if (rmax == INFPSZ) {
4158 					rmax = strmsgsz;
4159 				} else  {
4160 					rmax = MIN(strmsgsz, rmax);
4161 				}
4162 			}
4163 
4164 			mutex_enter(QLOCK(wrq));
4165 			stp->sd_qn_minpsz = rmin;
4166 			stp->sd_qn_maxpsz = rmax;
4167 			mutex_exit(QLOCK(wrq));
4168 		}
4169 
4170 		/*
4171 		 * Need to update the anchor value if this module is
4172 		 * inserted below the anchor point.
4173 		 */
4174 		if (stp->sd_anchor != 0) {
4175 			pos = STRUCT_FGET(strmodinsert, pos);
4176 			if (pos >= (stp->sd_pushcnt - stp->sd_anchor))
4177 				stp->sd_anchor++;
4178 		}
4179 
4180 		strendplumb(stp);
4181 		mutex_exit(&stp->sd_lock);
4182 		return (0);
4183 	}
4184 
4185 	case _I_REMOVE:
4186 	{
4187 		/*
4188 		 * To remove a module with a given name in a stream.  The
4189 		 * caller of this ioctl needs to provide both the name and
4190 		 * the position of the module to be removed.  This eliminates
4191 		 * the ambiguity of removal if a module is inserted/pushed
4192 		 * multiple times in a stream.  In the first release, only
4193 		 * allow privileged user to use this ioctl.
4194 		 * Furthermore, the remove is only allowed
4195 		 * below an anchor if the zoneid is the same as the zoneid
4196 		 * which created the anchor.
4197 		 *
4198 		 * Note that we do not plan to support this ioctl
4199 		 * on pipes in the first release.  We want to learn more
4200 		 * about the implications of these ioctls before extending
4201 		 * their support.  And we do not think these features are
4202 		 * valuable for pipes.
4203 		 *
4204 		 * Neither do we support O/C hot stream.  Note that only
4205 		 * the upper streams of TCP/IP stack are O/C hot streams.
4206 		 * The lower IP stream is not.
4207 		 * When there is a O/C cold barrier we do not allow removal
4208 		 * below the barrier.
4209 		 *
4210 		 * Also note that _I_REMOVE cannot be used to remove a
4211 		 * driver or the stream head.
4212 		 */
4213 		STRUCT_DECL(strmodconf, strmodremove);
4214 		queue_t	*q;
4215 		int pos;
4216 		char mod_name[FMNAMESZ + 1];
4217 		boolean_t is_remove;
4218 
4219 		STRUCT_INIT(strmodremove, flag);
4220 		if (stp->sd_flag & STRHUP)
4221 			return (ENXIO);
4222 		if (STRMATED(stp))
4223 			return (EINVAL);
4224 		if ((error = secpolicy_net_config(crp, B_FALSE)) != 0)
4225 			return (error);
4226 		if (stp->sd_anchor != 0 &&
4227 		    stp->sd_anchorzone != crgetzoneid(crp))
4228 			return (EINVAL);
4229 
4230 		error = strcopyin((void *)arg, STRUCT_BUF(strmodremove),
4231 		    STRUCT_SIZE(strmodremove), copyflag);
4232 		if (error)
4233 			return (error);
4234 
4235 		error = (copyflag & U_TO_K ? copyinstr :
4236 		    copystr)(STRUCT_FGETP(strmodremove, mod_name),
4237 		    mod_name, FMNAMESZ + 1, NULL);
4238 		if (error)
4239 			return ((error == ENAMETOOLONG) ? EINVAL : EFAULT);
4240 
4241 		if ((error = strstartplumb(stp, flag, cmd)) != 0)
4242 			return (error);
4243 
4244 		/*
4245 		 * Match the name of given module to the name of module at
4246 		 * the given position.
4247 		 */
4248 		pos = STRUCT_FGET(strmodremove, pos);
4249 
4250 		is_remove = (pos != 0);
4251 		for (q = stp->sd_wrq->q_next; SAMESTR(q) && pos > 0;
4252 		    q = q->q_next, pos--)
4253 			;
4254 		if (pos > 0 || ! SAMESTR(q) ||
4255 		    strncmp(q->q_qinfo->qi_minfo->mi_idname, mod_name,
4256 		    strlen(q->q_qinfo->qi_minfo->mi_idname)) != 0) {
4257 			mutex_enter(&stp->sd_lock);
4258 			strendplumb(stp);
4259 			mutex_exit(&stp->sd_lock);
4260 			return (EINVAL);
4261 		}
4262 
4263 		/*
4264 		 * If the position is at or below an anchor, then the zoneid
4265 		 * must match the zoneid that created the anchor.
4266 		 */
4267 		if (stp->sd_anchor != 0) {
4268 			pos = STRUCT_FGET(strmodremove, pos);
4269 			if (pos >= (stp->sd_pushcnt - stp->sd_anchor) &&
4270 			    stp->sd_anchorzone != crgetzoneid(crp)) {
4271 				mutex_enter(&stp->sd_lock);
4272 				strendplumb(stp);
4273 				mutex_exit(&stp->sd_lock);
4274 				return (EPERM);
4275 			}
4276 		}
4277 
4278 
4279 		ASSERT(!(q->q_flag & QREADR));
4280 		qdetach(_RD(q), 1, flag, crp, is_remove);
4281 
4282 		mutex_enter(&stp->sd_lock);
4283 
4284 		/*
4285 		 * As a performance concern we are caching the values of
4286 		 * q_minpsz and q_maxpsz of the module below the stream
4287 		 * head in the stream head.
4288 		 */
4289 		if (!is_remove) {
4290 			mutex_enter(QLOCK(wrq->q_next));
4291 			rmin = wrq->q_next->q_minpsz;
4292 			rmax = wrq->q_next->q_maxpsz;
4293 			mutex_exit(QLOCK(wrq->q_next));
4294 
4295 			/* Do this processing here as a performance concern */
4296 			if (strmsgsz != 0) {
4297 				if (rmax == INFPSZ)
4298 					rmax = strmsgsz;
4299 				else  {
4300 					if (vp->v_type == VFIFO)
4301 						rmax = MIN(PIPE_BUF, rmax);
4302 					else	rmax = MIN(strmsgsz, rmax);
4303 				}
4304 			}
4305 
4306 			mutex_enter(QLOCK(wrq));
4307 			stp->sd_qn_minpsz = rmin;
4308 			stp->sd_qn_maxpsz = rmax;
4309 			mutex_exit(QLOCK(wrq));
4310 		}
4311 
4312 		/*
4313 		 * Need to update the anchor value if this module is removed
4314 		 * at or below the anchor point.  If the removed module is at
4315 		 * the anchor point, remove the anchor for this stream if
4316 		 * there is no module above the anchor point.  Otherwise, if
4317 		 * the removed module is below the anchor point, decrement the
4318 		 * anchor point by 1.
4319 		 */
4320 		if (stp->sd_anchor != 0) {
4321 			pos = STRUCT_FGET(strmodremove, pos);
4322 			if (pos == stp->sd_pushcnt - stp->sd_anchor + 1)
4323 				stp->sd_anchor = 0;
4324 			else if (pos > (stp->sd_pushcnt - stp->sd_anchor + 1))
4325 				stp->sd_anchor--;
4326 		}
4327 
4328 		strendplumb(stp);
4329 		mutex_exit(&stp->sd_lock);
4330 		return (0);
4331 	}
4332 
4333 	case I_ANCHOR:
4334 		/*
4335 		 * Set the anchor position on the stream to reside at
4336 		 * the top module (in other words, the top module
4337 		 * cannot be popped).  Anchors with a FIFO make no
4338 		 * obvious sense, so they're not allowed.
4339 		 */
4340 		mutex_enter(&stp->sd_lock);
4341 
4342 		if (stp->sd_vnode->v_type == VFIFO) {
4343 			mutex_exit(&stp->sd_lock);
4344 			return (EINVAL);
4345 		}
4346 		/* Only allow the same zoneid to update the anchor */
4347 		if (stp->sd_anchor != 0 &&
4348 		    stp->sd_anchorzone != crgetzoneid(crp)) {
4349 			mutex_exit(&stp->sd_lock);
4350 			return (EINVAL);
4351 		}
4352 		stp->sd_anchor = stp->sd_pushcnt;
4353 		stp->sd_anchorzone = crgetzoneid(crp);
4354 		mutex_exit(&stp->sd_lock);
4355 		return (0);
4356 
4357 	case I_LOOK:
4358 		/*
4359 		 * Get name of first module downstream.
4360 		 * If no module, return an error.
4361 		 */
4362 	{
4363 		claimstr(wrq);
4364 		if (_SAMESTR(wrq) && wrq->q_next->q_next) {
4365 			char *name = wrq->q_next->q_qinfo->qi_minfo->mi_idname;
4366 			error = strcopyout(name, (void *)arg, strlen(name) + 1,
4367 			    copyflag);
4368 			releasestr(wrq);
4369 			return (error);
4370 		}
4371 		releasestr(wrq);
4372 		return (EINVAL);
4373 	}
4374 
4375 	case I_LINK:
4376 	case I_PLINK:
4377 		/*
4378 		 * Link a multiplexor.
4379 		 */
4380 		error = mlink(vp, cmd, (int)arg, crp, rvalp, 0);
4381 		return (error);
4382 
4383 	case _I_PLINK_LH:
4384 		/*
4385 		 * Link a multiplexor: Call must originate from kernel.
4386 		 */
4387 		if (kioctl)
4388 			return (ldi_mlink_lh(vp, cmd, arg, crp, rvalp));
4389 
4390 		return (EINVAL);
4391 	case I_UNLINK:
4392 	case I_PUNLINK:
4393 		/*
4394 		 * Unlink a multiplexor.
4395 		 * If arg is -1, unlink all links for which this is the
4396 		 * controlling stream.  Otherwise, arg is an index number
4397 		 * for a link to be removed.
4398 		 */
4399 	{
4400 		struct linkinfo *linkp;
4401 		int native_arg = (int)arg;
4402 		int type;
4403 		netstack_t *ns;
4404 		str_stack_t *ss;
4405 
4406 		TRACE_1(TR_FAC_STREAMS_FR,
4407 		    TR_I_UNLINK, "I_UNLINK/I_PUNLINK:%p", stp);
4408 		if (vp->v_type == VFIFO) {
4409 			return (EINVAL);
4410 		}
4411 		if (cmd == I_UNLINK)
4412 			type = LINKNORMAL;
4413 		else	/* I_PUNLINK */
4414 			type = LINKPERSIST;
4415 		if (native_arg == 0) {
4416 			return (EINVAL);
4417 		}
4418 		ns = netstack_find_by_cred(crp);
4419 		ASSERT(ns != NULL);
4420 		ss = ns->netstack_str;
4421 		ASSERT(ss != NULL);
4422 
4423 		if (native_arg == MUXID_ALL)
4424 			error = munlinkall(stp, type, crp, rvalp, ss);
4425 		else {
4426 			mutex_enter(&muxifier);
4427 			if (!(linkp = findlinks(stp, (int)arg, type, ss))) {
4428 				/* invalid user supplied index number */
4429 				mutex_exit(&muxifier);
4430 				netstack_rele(ss->ss_netstack);
4431 				return (EINVAL);
4432 			}
4433 			/* munlink drops the muxifier lock */
4434 			error = munlink(stp, linkp, type, crp, rvalp, ss);
4435 		}
4436 		netstack_rele(ss->ss_netstack);
4437 		return (error);
4438 	}
4439 
4440 	case I_FLUSH:
4441 		/*
4442 		 * send a flush message downstream
4443 		 * flush message can indicate
4444 		 * FLUSHR - flush read queue
4445 		 * FLUSHW - flush write queue
4446 		 * FLUSHRW - flush read/write queue
4447 		 */
4448 		if (stp->sd_flag & STRHUP)
4449 			return (ENXIO);
4450 		if (arg & ~FLUSHRW)
4451 			return (EINVAL);
4452 
4453 		for (;;) {
4454 			if (putnextctl1(stp->sd_wrq, M_FLUSH, (int)arg)) {
4455 				break;
4456 			}
4457 			if (error = strwaitbuf(1, BPRI_HI)) {
4458 				return (error);
4459 			}
4460 		}
4461 
4462 		/*
4463 		 * Send down an unsupported ioctl and wait for the nack
4464 		 * in order to allow the M_FLUSH to propagate back
4465 		 * up to the stream head.
4466 		 * Replaces if (qready()) runqueues();
4467 		 */
4468 		strioc.ic_cmd = -1;	/* The unsupported ioctl */
4469 		strioc.ic_timout = 0;
4470 		strioc.ic_len = 0;
4471 		strioc.ic_dp = NULL;
4472 		(void) strdoioctl(stp, &strioc, flag, K_TO_K, crp, rvalp);
4473 		*rvalp = 0;
4474 		return (0);
4475 
4476 	case I_FLUSHBAND:
4477 	{
4478 		struct bandinfo binfo;
4479 
4480 		error = strcopyin((void *)arg, &binfo, sizeof (binfo),
4481 		    copyflag);
4482 		if (error)
4483 			return (error);
4484 		if (stp->sd_flag & STRHUP)
4485 			return (ENXIO);
4486 		if (binfo.bi_flag & ~FLUSHRW)
4487 			return (EINVAL);
4488 		while (!(mp = allocb(2, BPRI_HI))) {
4489 			if (error = strwaitbuf(2, BPRI_HI))
4490 				return (error);
4491 		}
4492 		mp->b_datap->db_type = M_FLUSH;
4493 		*mp->b_wptr++ = binfo.bi_flag | FLUSHBAND;
4494 		*mp->b_wptr++ = binfo.bi_pri;
4495 		putnext(stp->sd_wrq, mp);
4496 		/*
4497 		 * Send down an unsupported ioctl and wait for the nack
4498 		 * in order to allow the M_FLUSH to propagate back
4499 		 * up to the stream head.
4500 		 * Replaces if (qready()) runqueues();
4501 		 */
4502 		strioc.ic_cmd = -1;	/* The unsupported ioctl */
4503 		strioc.ic_timout = 0;
4504 		strioc.ic_len = 0;
4505 		strioc.ic_dp = NULL;
4506 		(void) strdoioctl(stp, &strioc, flag, K_TO_K, crp, rvalp);
4507 		*rvalp = 0;
4508 		return (0);
4509 	}
4510 
4511 	case I_SRDOPT:
4512 		/*
4513 		 * Set read options
4514 		 *
4515 		 * RNORM - default stream mode
4516 		 * RMSGN - message no discard
4517 		 * RMSGD - message discard
4518 		 * RPROTNORM - fail read with EBADMSG for M_[PC]PROTOs
4519 		 * RPROTDAT - convert M_[PC]PROTOs to M_DATAs
4520 		 * RPROTDIS - discard M_[PC]PROTOs and retain M_DATAs
4521 		 */
4522 		if (arg & ~(RMODEMASK | RPROTMASK))
4523 			return (EINVAL);
4524 
4525 		if ((arg & (RMSGD|RMSGN)) == (RMSGD|RMSGN))
4526 			return (EINVAL);
4527 
4528 		mutex_enter(&stp->sd_lock);
4529 		switch (arg & RMODEMASK) {
4530 		case RNORM:
4531 			stp->sd_read_opt &= ~(RD_MSGDIS | RD_MSGNODIS);
4532 			break;
4533 		case RMSGD:
4534 			stp->sd_read_opt = (stp->sd_read_opt & ~RD_MSGNODIS) |
4535 			    RD_MSGDIS;
4536 			break;
4537 		case RMSGN:
4538 			stp->sd_read_opt = (stp->sd_read_opt & ~RD_MSGDIS) |
4539 			    RD_MSGNODIS;
4540 			break;
4541 		}
4542 
4543 		switch (arg & RPROTMASK) {
4544 		case RPROTNORM:
4545 			stp->sd_read_opt &= ~(RD_PROTDAT | RD_PROTDIS);
4546 			break;
4547 
4548 		case RPROTDAT:
4549 			stp->sd_read_opt = ((stp->sd_read_opt & ~RD_PROTDIS) |
4550 			    RD_PROTDAT);
4551 			break;
4552 
4553 		case RPROTDIS:
4554 			stp->sd_read_opt = ((stp->sd_read_opt & ~RD_PROTDAT) |
4555 			    RD_PROTDIS);
4556 			break;
4557 		}
4558 		mutex_exit(&stp->sd_lock);
4559 		return (0);
4560 
4561 	case I_GRDOPT:
4562 		/*
4563 		 * Get read option and return the value
4564 		 * to spot pointed to by arg
4565 		 */
4566 	{
4567 		int rdopt;
4568 
4569 		rdopt = ((stp->sd_read_opt & RD_MSGDIS) ? RMSGD :
4570 		    ((stp->sd_read_opt & RD_MSGNODIS) ? RMSGN : RNORM));
4571 		rdopt |= ((stp->sd_read_opt & RD_PROTDAT) ? RPROTDAT :
4572 		    ((stp->sd_read_opt & RD_PROTDIS) ? RPROTDIS : RPROTNORM));
4573 
4574 		return (strcopyout(&rdopt, (void *)arg, sizeof (int),
4575 		    copyflag));
4576 	}
4577 
4578 	case I_SERROPT:
4579 		/*
4580 		 * Set error options
4581 		 *
4582 		 * RERRNORM - persistent read errors
4583 		 * RERRNONPERSIST - non-persistent read errors
4584 		 * WERRNORM - persistent write errors
4585 		 * WERRNONPERSIST - non-persistent write errors
4586 		 */
4587 		if (arg & ~(RERRMASK | WERRMASK))
4588 			return (EINVAL);
4589 
4590 		mutex_enter(&stp->sd_lock);
4591 		switch (arg & RERRMASK) {
4592 		case RERRNORM:
4593 			stp->sd_flag &= ~STRDERRNONPERSIST;
4594 			break;
4595 		case RERRNONPERSIST:
4596 			stp->sd_flag |= STRDERRNONPERSIST;
4597 			break;
4598 		}
4599 		switch (arg & WERRMASK) {
4600 		case WERRNORM:
4601 			stp->sd_flag &= ~STWRERRNONPERSIST;
4602 			break;
4603 		case WERRNONPERSIST:
4604 			stp->sd_flag |= STWRERRNONPERSIST;
4605 			break;
4606 		}
4607 		mutex_exit(&stp->sd_lock);
4608 		return (0);
4609 
4610 	case I_GERROPT:
4611 		/*
4612 		 * Get error option and return the value
4613 		 * to spot pointed to by arg
4614 		 */
4615 	{
4616 		int erropt = 0;
4617 
4618 		erropt |= (stp->sd_flag & STRDERRNONPERSIST) ? RERRNONPERSIST :
4619 		    RERRNORM;
4620 		erropt |= (stp->sd_flag & STWRERRNONPERSIST) ? WERRNONPERSIST :
4621 		    WERRNORM;
4622 		return (strcopyout(&erropt, (void *)arg, sizeof (int),
4623 		    copyflag));
4624 	}
4625 
4626 	case I_SETSIG:
4627 		/*
4628 		 * Register the calling proc to receive the SIGPOLL
4629 		 * signal based on the events given in arg.  If
4630 		 * arg is zero, remove the proc from register list.
4631 		 */
4632 	{
4633 		strsig_t *ssp, *pssp;
4634 		struct pid *pidp;
4635 
4636 		pssp = NULL;
4637 		pidp = curproc->p_pidp;
4638 		/*
4639 		 * Hold sd_lock to prevent traversal of sd_siglist while
4640 		 * it is modified.
4641 		 */
4642 		mutex_enter(&stp->sd_lock);
4643 		for (ssp = stp->sd_siglist; ssp && (ssp->ss_pidp != pidp);
4644 		    pssp = ssp, ssp = ssp->ss_next)
4645 			;
4646 
4647 		if (arg) {
4648 			if (arg & ~(S_INPUT|S_HIPRI|S_MSG|S_HANGUP|S_ERROR|
4649 			    S_RDNORM|S_WRNORM|S_RDBAND|S_WRBAND|S_BANDURG)) {
4650 				mutex_exit(&stp->sd_lock);
4651 				return (EINVAL);
4652 			}
4653 			if ((arg & S_BANDURG) && !(arg & S_RDBAND)) {
4654 				mutex_exit(&stp->sd_lock);
4655 				return (EINVAL);
4656 			}
4657 
4658 			/*
4659 			 * If proc not already registered, add it
4660 			 * to list.
4661 			 */
4662 			if (!ssp) {
4663 				ssp = kmem_alloc(sizeof (strsig_t), KM_SLEEP);
4664 				ssp->ss_pidp = pidp;
4665 				ssp->ss_pid = pidp->pid_id;
4666 				ssp->ss_next = NULL;
4667 				if (pssp)
4668 					pssp->ss_next = ssp;
4669 				else
4670 					stp->sd_siglist = ssp;
4671 				mutex_enter(&pidlock);
4672 				PID_HOLD(pidp);
4673 				mutex_exit(&pidlock);
4674 			}
4675 
4676 			/*
4677 			 * Set events.
4678 			 */
4679 			ssp->ss_events = (int)arg;
4680 		} else {
4681 			/*
4682 			 * Remove proc from register list.
4683 			 */
4684 			if (ssp) {
4685 				mutex_enter(&pidlock);
4686 				PID_RELE(pidp);
4687 				mutex_exit(&pidlock);
4688 				if (pssp)
4689 					pssp->ss_next = ssp->ss_next;
4690 				else
4691 					stp->sd_siglist = ssp->ss_next;
4692 				kmem_free(ssp, sizeof (strsig_t));
4693 			} else {
4694 				mutex_exit(&stp->sd_lock);
4695 				return (EINVAL);
4696 			}
4697 		}
4698 
4699 		/*
4700 		 * Recalculate OR of sig events.
4701 		 */
4702 		stp->sd_sigflags = 0;
4703 		for (ssp = stp->sd_siglist; ssp; ssp = ssp->ss_next)
4704 			stp->sd_sigflags |= ssp->ss_events;
4705 		mutex_exit(&stp->sd_lock);
4706 		return (0);
4707 	}
4708 
4709 	case I_GETSIG:
4710 		/*
4711 		 * Return (in arg) the current registration of events
4712 		 * for which the calling proc is to be signaled.
4713 		 */
4714 	{
4715 		struct strsig *ssp;
4716 		struct pid  *pidp;
4717 
4718 		pidp = curproc->p_pidp;
4719 		mutex_enter(&stp->sd_lock);
4720 		for (ssp = stp->sd_siglist; ssp; ssp = ssp->ss_next)
4721 			if (ssp->ss_pidp == pidp) {
4722 				error = strcopyout(&ssp->ss_events, (void *)arg,
4723 				    sizeof (int), copyflag);
4724 				mutex_exit(&stp->sd_lock);
4725 				return (error);
4726 			}
4727 		mutex_exit(&stp->sd_lock);
4728 		return (EINVAL);
4729 	}
4730 
4731 	case I_ESETSIG:
4732 		/*
4733 		 * Register the ss_pid to receive the SIGPOLL
4734 		 * signal based on the events is ss_events arg.  If
4735 		 * ss_events is zero, remove the proc from register list.
4736 		 */
4737 	{
4738 		struct strsig *ssp, *pssp;
4739 		struct proc *proc;
4740 		struct pid  *pidp;
4741 		pid_t pid;
4742 		struct strsigset ss;
4743 
4744 		error = strcopyin((void *)arg, &ss, sizeof (ss), copyflag);
4745 		if (error)
4746 			return (error);
4747 
4748 		pid = ss.ss_pid;
4749 
4750 		if (ss.ss_events != 0) {
4751 			/*
4752 			 * Permissions check by sending signal 0.
4753 			 * Note that when kill fails it does a set_errno
4754 			 * causing the system call to fail.
4755 			 */
4756 			error = kill(pid, 0);
4757 			if (error) {
4758 				return (error);
4759 			}
4760 		}
4761 		mutex_enter(&pidlock);
4762 		if (pid == 0)
4763 			proc = curproc;
4764 		else if (pid < 0)
4765 			proc = pgfind(-pid);
4766 		else
4767 			proc = prfind(pid);
4768 		if (proc == NULL) {
4769 			mutex_exit(&pidlock);
4770 			return (ESRCH);
4771 		}
4772 		if (pid < 0)
4773 			pidp = proc->p_pgidp;
4774 		else
4775 			pidp = proc->p_pidp;
4776 		ASSERT(pidp);
4777 		/*
4778 		 * Get a hold on the pid structure while referencing it.
4779 		 * There is a separate PID_HOLD should it be inserted
4780 		 * in the list below.
4781 		 */
4782 		PID_HOLD(pidp);
4783 		mutex_exit(&pidlock);
4784 
4785 		pssp = NULL;
4786 		/*
4787 		 * Hold sd_lock to prevent traversal of sd_siglist while
4788 		 * it is modified.
4789 		 */
4790 		mutex_enter(&stp->sd_lock);
4791 		for (ssp = stp->sd_siglist; ssp && (ssp->ss_pid != pid);
4792 		    pssp = ssp, ssp = ssp->ss_next)
4793 			;
4794 
4795 		if (ss.ss_events) {
4796 			if (ss.ss_events &
4797 			    ~(S_INPUT|S_HIPRI|S_MSG|S_HANGUP|S_ERROR|
4798 			    S_RDNORM|S_WRNORM|S_RDBAND|S_WRBAND|S_BANDURG)) {
4799 				mutex_exit(&stp->sd_lock);
4800 				mutex_enter(&pidlock);
4801 				PID_RELE(pidp);
4802 				mutex_exit(&pidlock);
4803 				return (EINVAL);
4804 			}
4805 			if ((ss.ss_events & S_BANDURG) &&
4806 			    !(ss.ss_events & S_RDBAND)) {
4807 				mutex_exit(&stp->sd_lock);
4808 				mutex_enter(&pidlock);
4809 				PID_RELE(pidp);
4810 				mutex_exit(&pidlock);
4811 				return (EINVAL);
4812 			}
4813 
4814 			/*
4815 			 * If proc not already registered, add it
4816 			 * to list.
4817 			 */
4818 			if (!ssp) {
4819 				ssp = kmem_alloc(sizeof (strsig_t), KM_SLEEP);
4820 				ssp->ss_pidp = pidp;
4821 				ssp->ss_pid = pid;
4822 				ssp->ss_next = NULL;
4823 				if (pssp)
4824 					pssp->ss_next = ssp;
4825 				else
4826 					stp->sd_siglist = ssp;
4827 				mutex_enter(&pidlock);
4828 				PID_HOLD(pidp);
4829 				mutex_exit(&pidlock);
4830 			}
4831 
4832 			/*
4833 			 * Set events.
4834 			 */
4835 			ssp->ss_events = ss.ss_events;
4836 		} else {
4837 			/*
4838 			 * Remove proc from register list.
4839 			 */
4840 			if (ssp) {
4841 				mutex_enter(&pidlock);
4842 				PID_RELE(pidp);
4843 				mutex_exit(&pidlock);
4844 				if (pssp)
4845 					pssp->ss_next = ssp->ss_next;
4846 				else
4847 					stp->sd_siglist = ssp->ss_next;
4848 				kmem_free(ssp, sizeof (strsig_t));
4849 			} else {
4850 				mutex_exit(&stp->sd_lock);
4851 				mutex_enter(&pidlock);
4852 				PID_RELE(pidp);
4853 				mutex_exit(&pidlock);
4854 				return (EINVAL);
4855 			}
4856 		}
4857 
4858 		/*
4859 		 * Recalculate OR of sig events.
4860 		 */
4861 		stp->sd_sigflags = 0;
4862 		for (ssp = stp->sd_siglist; ssp; ssp = ssp->ss_next)
4863 			stp->sd_sigflags |= ssp->ss_events;
4864 		mutex_exit(&stp->sd_lock);
4865 		mutex_enter(&pidlock);
4866 		PID_RELE(pidp);
4867 		mutex_exit(&pidlock);
4868 		return (0);
4869 	}
4870 
4871 	case I_EGETSIG:
4872 		/*
4873 		 * Return (in arg) the current registration of events
4874 		 * for which the calling proc is to be signaled.
4875 		 */
4876 	{
4877 		struct strsig *ssp;
4878 		struct proc *proc;
4879 		pid_t pid;
4880 		struct pid  *pidp;
4881 		struct strsigset ss;
4882 
4883 		error = strcopyin((void *)arg, &ss, sizeof (ss), copyflag);
4884 		if (error)
4885 			return (error);
4886 
4887 		pid = ss.ss_pid;
4888 		mutex_enter(&pidlock);
4889 		if (pid == 0)
4890 			proc = curproc;
4891 		else if (pid < 0)
4892 			proc = pgfind(-pid);
4893 		else
4894 			proc = prfind(pid);
4895 		if (proc == NULL) {
4896 			mutex_exit(&pidlock);
4897 			return (ESRCH);
4898 		}
4899 		if (pid < 0)
4900 			pidp = proc->p_pgidp;
4901 		else
4902 			pidp = proc->p_pidp;
4903 
4904 		/* Prevent the pidp from being reassigned */
4905 		PID_HOLD(pidp);
4906 		mutex_exit(&pidlock);
4907 
4908 		mutex_enter(&stp->sd_lock);
4909 		for (ssp = stp->sd_siglist; ssp; ssp = ssp->ss_next)
4910 			if (ssp->ss_pid == pid) {
4911 				ss.ss_pid = ssp->ss_pid;
4912 				ss.ss_events = ssp->ss_events;
4913 				error = strcopyout(&ss, (void *)arg,
4914 				    sizeof (struct strsigset), copyflag);
4915 				mutex_exit(&stp->sd_lock);
4916 				mutex_enter(&pidlock);
4917 				PID_RELE(pidp);
4918 				mutex_exit(&pidlock);
4919 				return (error);
4920 			}
4921 		mutex_exit(&stp->sd_lock);
4922 		mutex_enter(&pidlock);
4923 		PID_RELE(pidp);
4924 		mutex_exit(&pidlock);
4925 		return (EINVAL);
4926 	}
4927 
4928 	case I_PEEK:
4929 	{
4930 		STRUCT_DECL(strpeek, strpeek);
4931 		size_t n;
4932 		mblk_t *fmp, *tmp_mp = NULL;
4933 
4934 		STRUCT_INIT(strpeek, flag);
4935 
4936 		error = strcopyin((void *)arg, STRUCT_BUF(strpeek),
4937 		    STRUCT_SIZE(strpeek), copyflag);
4938 		if (error)
4939 			return (error);
4940 
4941 		mutex_enter(QLOCK(rdq));
4942 		/*
4943 		 * Skip the invalid messages
4944 		 */
4945 		for (mp = rdq->q_first; mp != NULL; mp = mp->b_next)
4946 			if (mp->b_datap->db_type != M_SIG)
4947 				break;
4948 
4949 		/*
4950 		 * If user has requested to peek at a high priority message
4951 		 * and first message is not, return 0
4952 		 */
4953 		if (mp != NULL) {
4954 			if ((STRUCT_FGET(strpeek, flags) & RS_HIPRI) &&
4955 			    queclass(mp) == QNORM) {
4956 				*rvalp = 0;
4957 				mutex_exit(QLOCK(rdq));
4958 				return (0);
4959 			}
4960 		} else if (stp->sd_struiordq == NULL ||
4961 		    (STRUCT_FGET(strpeek, flags) & RS_HIPRI)) {
4962 			/*
4963 			 * No mblks to look at at the streamhead and
4964 			 * 1). This isn't a synch stream or
4965 			 * 2). This is a synch stream but caller wants high
4966 			 *	priority messages which is not supported by
4967 			 *	the synch stream. (it only supports QNORM)
4968 			 */
4969 			*rvalp = 0;
4970 			mutex_exit(QLOCK(rdq));
4971 			return (0);
4972 		}
4973 
4974 		fmp = mp;
4975 
4976 		if (mp && mp->b_datap->db_type == M_PASSFP) {
4977 			mutex_exit(QLOCK(rdq));
4978 			return (EBADMSG);
4979 		}
4980 
4981 		ASSERT(mp == NULL || mp->b_datap->db_type == M_PCPROTO ||
4982 		    mp->b_datap->db_type == M_PROTO ||
4983 		    mp->b_datap->db_type == M_DATA);
4984 
4985 		if (mp && mp->b_datap->db_type == M_PCPROTO) {
4986 			STRUCT_FSET(strpeek, flags, RS_HIPRI);
4987 		} else {
4988 			STRUCT_FSET(strpeek, flags, 0);
4989 		}
4990 
4991 
4992 		if (mp && ((tmp_mp = dupmsg(mp)) == NULL)) {
4993 			mutex_exit(QLOCK(rdq));
4994 			return (ENOSR);
4995 		}
4996 		mutex_exit(QLOCK(rdq));
4997 
4998 		/*
4999 		 * set mp = tmp_mp, so that I_PEEK processing can continue.
5000 		 * tmp_mp is used to free the dup'd message.
5001 		 */
5002 		mp = tmp_mp;
5003 
5004 		uio.uio_fmode = 0;
5005 		uio.uio_extflg = UIO_COPY_CACHED;
5006 		uio.uio_segflg = (copyflag == U_TO_K) ? UIO_USERSPACE :
5007 		    UIO_SYSSPACE;
5008 		uio.uio_limit = 0;
5009 		/*
5010 		 * First process PROTO blocks, if any.
5011 		 * If user doesn't want to get ctl info by setting maxlen <= 0,
5012 		 * then set len to -1/0 and skip control blocks part.
5013 		 */
5014 		if (STRUCT_FGET(strpeek, ctlbuf.maxlen) < 0)
5015 			STRUCT_FSET(strpeek, ctlbuf.len, -1);
5016 		else if (STRUCT_FGET(strpeek, ctlbuf.maxlen) == 0)
5017 			STRUCT_FSET(strpeek, ctlbuf.len, 0);
5018 		else {
5019 			int	ctl_part = 0;
5020 
5021 			iov.iov_base = STRUCT_FGETP(strpeek, ctlbuf.buf);
5022 			iov.iov_len = STRUCT_FGET(strpeek, ctlbuf.maxlen);
5023 			uio.uio_iov = &iov;
5024 			uio.uio_resid = iov.iov_len;
5025 			uio.uio_loffset = 0;
5026 			uio.uio_iovcnt = 1;
5027 			while (mp && mp->b_datap->db_type != M_DATA &&
5028 			    uio.uio_resid >= 0) {
5029 				ASSERT(STRUCT_FGET(strpeek, flags) == 0 ?
5030 				    mp->b_datap->db_type == M_PROTO :
5031 				    mp->b_datap->db_type == M_PCPROTO);
5032 
5033 				if ((n = MIN(uio.uio_resid,
5034 				    mp->b_wptr - mp->b_rptr)) != 0 &&
5035 				    (error = uiomove((char *)mp->b_rptr, n,
5036 				    UIO_READ, &uio)) != 0) {
5037 					freemsg(tmp_mp);
5038 					return (error);
5039 				}
5040 				ctl_part = 1;
5041 				mp = mp->b_cont;
5042 			}
5043 			/* No ctl message */
5044 			if (ctl_part == 0)
5045 				STRUCT_FSET(strpeek, ctlbuf.len, -1);
5046 			else
5047 				STRUCT_FSET(strpeek, ctlbuf.len,
5048 				    STRUCT_FGET(strpeek, ctlbuf.maxlen) -
5049 				    uio.uio_resid);
5050 		}
5051 
5052 		/*
5053 		 * Now process DATA blocks, if any.
5054 		 * If user doesn't want to get data info by setting maxlen <= 0,
5055 		 * then set len to -1/0 and skip data blocks part.
5056 		 */
5057 		if (STRUCT_FGET(strpeek, databuf.maxlen) < 0)
5058 			STRUCT_FSET(strpeek, databuf.len, -1);
5059 		else if (STRUCT_FGET(strpeek, databuf.maxlen) == 0)
5060 			STRUCT_FSET(strpeek, databuf.len, 0);
5061 		else {
5062 			int	data_part = 0;
5063 
5064 			iov.iov_base = STRUCT_FGETP(strpeek, databuf.buf);
5065 			iov.iov_len = STRUCT_FGET(strpeek, databuf.maxlen);
5066 			uio.uio_iov = &iov;
5067 			uio.uio_resid = iov.iov_len;
5068 			uio.uio_loffset = 0;
5069 			uio.uio_iovcnt = 1;
5070 			while (mp && uio.uio_resid) {
5071 				if (mp->b_datap->db_type == M_DATA) {
5072 					if ((n = MIN(uio.uio_resid,
5073 					    mp->b_wptr - mp->b_rptr)) != 0 &&
5074 					    (error = uiomove((char *)mp->b_rptr,
5075 					    n, UIO_READ, &uio)) != 0) {
5076 						freemsg(tmp_mp);
5077 						return (error);
5078 					}
5079 					data_part = 1;
5080 				}
5081 				ASSERT(data_part == 0 ||
5082 				    mp->b_datap->db_type == M_DATA);
5083 				mp = mp->b_cont;
5084 			}
5085 			/* No data message */
5086 			if (data_part == 0)
5087 				STRUCT_FSET(strpeek, databuf.len, -1);
5088 			else
5089 				STRUCT_FSET(strpeek, databuf.len,
5090 				    STRUCT_FGET(strpeek, databuf.maxlen) -
5091 				    uio.uio_resid);
5092 		}
5093 		freemsg(tmp_mp);
5094 
5095 		/*
5096 		 * It is a synch stream and user wants to get
5097 		 * data (maxlen > 0).
5098 		 * uio setup is done by the codes that process DATA
5099 		 * blocks above.
5100 		 */
5101 		if ((fmp == NULL) && STRUCT_FGET(strpeek, databuf.maxlen) > 0) {
5102 			infod_t infod;
5103 
5104 			infod.d_cmd = INFOD_COPYOUT;
5105 			infod.d_res = 0;
5106 			infod.d_uiop = &uio;
5107 			error = infonext(rdq, &infod);
5108 			if (error == EINVAL || error == EBUSY)
5109 				error = 0;
5110 			if (error)
5111 				return (error);
5112 			STRUCT_FSET(strpeek, databuf.len, STRUCT_FGET(strpeek,
5113 			    databuf.maxlen) - uio.uio_resid);
5114 			if (STRUCT_FGET(strpeek, databuf.len) == 0) {
5115 				/*
5116 				 * No data found by the infonext().
5117 				 */
5118 				STRUCT_FSET(strpeek, databuf.len, -1);
5119 			}
5120 		}
5121 		error = strcopyout(STRUCT_BUF(strpeek), (void *)arg,
5122 		    STRUCT_SIZE(strpeek), copyflag);
5123 		if (error) {
5124 			return (error);
5125 		}
5126 		/*
5127 		 * If there is no message retrieved, set return code to 0
5128 		 * otherwise, set it to 1.
5129 		 */
5130 		if (STRUCT_FGET(strpeek, ctlbuf.len) == -1 &&
5131 		    STRUCT_FGET(strpeek, databuf.len) == -1)
5132 			*rvalp = 0;
5133 		else
5134 			*rvalp = 1;
5135 		return (0);
5136 	}
5137 
5138 	case I_FDINSERT:
5139 	{
5140 		STRUCT_DECL(strfdinsert, strfdinsert);
5141 		struct file *resftp;
5142 		struct stdata *resstp;
5143 		t_uscalar_t	ival;
5144 		ssize_t msgsize;
5145 		struct strbuf mctl;
5146 
5147 		STRUCT_INIT(strfdinsert, flag);
5148 		if (stp->sd_flag & STRHUP)
5149 			return (ENXIO);
5150 		/*
5151 		 * STRDERR, STWRERR and STPLEX tested above.
5152 		 */
5153 		error = strcopyin((void *)arg, STRUCT_BUF(strfdinsert),
5154 		    STRUCT_SIZE(strfdinsert), copyflag);
5155 		if (error)
5156 			return (error);
5157 
5158 		if (STRUCT_FGET(strfdinsert, offset) < 0 ||
5159 		    (STRUCT_FGET(strfdinsert, offset) %
5160 		    sizeof (t_uscalar_t)) != 0)
5161 			return (EINVAL);
5162 		if ((resftp = getf(STRUCT_FGET(strfdinsert, fildes))) != NULL) {
5163 			if ((resstp = resftp->f_vnode->v_stream) == NULL) {
5164 				releasef(STRUCT_FGET(strfdinsert, fildes));
5165 				return (EINVAL);
5166 			}
5167 		} else
5168 			return (EINVAL);
5169 
5170 		mutex_enter(&resstp->sd_lock);
5171 		if (resstp->sd_flag & (STRDERR|STWRERR|STRHUP|STPLEX)) {
5172 			error = strgeterr(resstp,
5173 			    STRDERR|STWRERR|STRHUP|STPLEX, 0);
5174 			if (error != 0) {
5175 				mutex_exit(&resstp->sd_lock);
5176 				releasef(STRUCT_FGET(strfdinsert, fildes));
5177 				return (error);
5178 			}
5179 		}
5180 		mutex_exit(&resstp->sd_lock);
5181 
5182 #ifdef	_ILP32
5183 		{
5184 			queue_t	*q;
5185 			queue_t	*mate = NULL;
5186 
5187 			/* get read queue of stream terminus */
5188 			claimstr(resstp->sd_wrq);
5189 			for (q = resstp->sd_wrq->q_next; q->q_next != NULL;
5190 			    q = q->q_next)
5191 				if (!STRMATED(resstp) && STREAM(q) != resstp &&
5192 				    mate == NULL) {
5193 					ASSERT(q->q_qinfo->qi_srvp);
5194 					ASSERT(_OTHERQ(q)->q_qinfo->qi_srvp);
5195 					claimstr(q);
5196 					mate = q;
5197 				}
5198 			q = _RD(q);
5199 			if (mate)
5200 				releasestr(mate);
5201 			releasestr(resstp->sd_wrq);
5202 			ival = (t_uscalar_t)q;
5203 		}
5204 #else
5205 		ival = (t_uscalar_t)getminor(resftp->f_vnode->v_rdev);
5206 #endif	/* _ILP32 */
5207 
5208 		if (STRUCT_FGET(strfdinsert, ctlbuf.len) <
5209 		    STRUCT_FGET(strfdinsert, offset) + sizeof (t_uscalar_t)) {
5210 			releasef(STRUCT_FGET(strfdinsert, fildes));
5211 			return (EINVAL);
5212 		}
5213 
5214 		/*
5215 		 * Check for legal flag value.
5216 		 */
5217 		if (STRUCT_FGET(strfdinsert, flags) & ~RS_HIPRI) {
5218 			releasef(STRUCT_FGET(strfdinsert, fildes));
5219 			return (EINVAL);
5220 		}
5221 
5222 		/* get these values from those cached in the stream head */
5223 		mutex_enter(QLOCK(stp->sd_wrq));
5224 		rmin = stp->sd_qn_minpsz;
5225 		rmax = stp->sd_qn_maxpsz;
5226 		mutex_exit(QLOCK(stp->sd_wrq));
5227 
5228 		/*
5229 		 * Make sure ctl and data sizes together fall within
5230 		 * the limits of the max and min receive packet sizes
5231 		 * and do not exceed system limit.  A negative data
5232 		 * length means that no data part is to be sent.
5233 		 */
5234 		ASSERT((rmax >= 0) || (rmax == INFPSZ));
5235 		if (rmax == 0) {
5236 			releasef(STRUCT_FGET(strfdinsert, fildes));
5237 			return (ERANGE);
5238 		}
5239 		if ((msgsize = STRUCT_FGET(strfdinsert, databuf.len)) < 0)
5240 			msgsize = 0;
5241 		if ((msgsize < rmin) ||
5242 		    ((msgsize > rmax) && (rmax != INFPSZ)) ||
5243 		    (STRUCT_FGET(strfdinsert, ctlbuf.len) > strctlsz)) {
5244 			releasef(STRUCT_FGET(strfdinsert, fildes));
5245 			return (ERANGE);
5246 		}
5247 
5248 		mutex_enter(&stp->sd_lock);
5249 		while (!(STRUCT_FGET(strfdinsert, flags) & RS_HIPRI) &&
5250 		    !canputnext(stp->sd_wrq)) {
5251 			if ((error = strwaitq(stp, WRITEWAIT, (ssize_t)0,
5252 			    flag, -1, &done)) != 0 || done) {
5253 				mutex_exit(&stp->sd_lock);
5254 				releasef(STRUCT_FGET(strfdinsert, fildes));
5255 				return (error);
5256 			}
5257 			if ((error = i_straccess(stp, access)) != 0) {
5258 				mutex_exit(&stp->sd_lock);
5259 				releasef(
5260 				    STRUCT_FGET(strfdinsert, fildes));
5261 				return (error);
5262 			}
5263 		}
5264 		mutex_exit(&stp->sd_lock);
5265 
5266 		/*
5267 		 * Copy strfdinsert.ctlbuf into native form of
5268 		 * ctlbuf to pass down into strmakemsg().
5269 		 */
5270 		mctl.maxlen = STRUCT_FGET(strfdinsert, ctlbuf.maxlen);
5271 		mctl.len = STRUCT_FGET(strfdinsert, ctlbuf.len);
5272 		mctl.buf = STRUCT_FGETP(strfdinsert, ctlbuf.buf);
5273 
5274 		iov.iov_base = STRUCT_FGETP(strfdinsert, databuf.buf);
5275 		iov.iov_len = STRUCT_FGET(strfdinsert, databuf.len);
5276 		uio.uio_iov = &iov;
5277 		uio.uio_iovcnt = 1;
5278 		uio.uio_loffset = 0;
5279 		uio.uio_segflg = (copyflag == U_TO_K) ? UIO_USERSPACE :
5280 		    UIO_SYSSPACE;
5281 		uio.uio_fmode = 0;
5282 		uio.uio_extflg = UIO_COPY_CACHED;
5283 		uio.uio_resid = iov.iov_len;
5284 		if ((error = strmakemsg(&mctl,
5285 		    &msgsize, &uio, stp,
5286 		    STRUCT_FGET(strfdinsert, flags), &mp)) != 0 || !mp) {
5287 			STRUCT_FSET(strfdinsert, databuf.len, msgsize);
5288 			releasef(STRUCT_FGET(strfdinsert, fildes));
5289 			return (error);
5290 		}
5291 
5292 		STRUCT_FSET(strfdinsert, databuf.len, msgsize);
5293 
5294 		/*
5295 		 * Place the possibly reencoded queue pointer 'offset' bytes
5296 		 * from the start of the control portion of the message.
5297 		 */
5298 		*((t_uscalar_t *)(mp->b_rptr +
5299 		    STRUCT_FGET(strfdinsert, offset))) = ival;
5300 
5301 		/*
5302 		 * Put message downstream.
5303 		 */
5304 		stream_willservice(stp);
5305 		putnext(stp->sd_wrq, mp);
5306 		stream_runservice(stp);
5307 		releasef(STRUCT_FGET(strfdinsert, fildes));
5308 		return (error);
5309 	}
5310 
5311 	case I_SENDFD:
5312 	{
5313 		struct file *fp;
5314 
5315 		if ((fp = getf((int)arg)) == NULL)
5316 			return (EBADF);
5317 		error = do_sendfp(stp, fp, crp);
5318 		if (audit_active) {
5319 			audit_fdsend((int)arg, fp, error);
5320 		}
5321 		releasef((int)arg);
5322 		return (error);
5323 	}
5324 
5325 	case I_RECVFD:
5326 	case I_E_RECVFD:
5327 	{
5328 		struct k_strrecvfd *srf;
5329 		int i, fd;
5330 
5331 		mutex_enter(&stp->sd_lock);
5332 		while (!(mp = getq(rdq))) {
5333 			if (stp->sd_flag & (STRHUP|STREOF)) {
5334 				mutex_exit(&stp->sd_lock);
5335 				return (ENXIO);
5336 			}
5337 			if ((error = strwaitq(stp, GETWAIT, (ssize_t)0,
5338 			    flag, -1, &done)) != 0 || done) {
5339 				mutex_exit(&stp->sd_lock);
5340 				return (error);
5341 			}
5342 			if ((error = i_straccess(stp, access)) != 0) {
5343 				mutex_exit(&stp->sd_lock);
5344 				return (error);
5345 			}
5346 		}
5347 		if (mp->b_datap->db_type != M_PASSFP) {
5348 			putback(stp, rdq, mp, mp->b_band);
5349 			mutex_exit(&stp->sd_lock);
5350 			return (EBADMSG);
5351 		}
5352 		mutex_exit(&stp->sd_lock);
5353 
5354 		srf = (struct k_strrecvfd *)mp->b_rptr;
5355 		if ((fd = ufalloc(0)) == -1) {
5356 			mutex_enter(&stp->sd_lock);
5357 			putback(stp, rdq, mp, mp->b_band);
5358 			mutex_exit(&stp->sd_lock);
5359 			return (EMFILE);
5360 		}
5361 		if (cmd == I_RECVFD) {
5362 			struct o_strrecvfd	ostrfd;
5363 
5364 			/* check to see if uid/gid values are too large. */
5365 
5366 			if (srf->uid > (o_uid_t)USHRT_MAX ||
5367 			    srf->gid > (o_gid_t)USHRT_MAX) {
5368 				mutex_enter(&stp->sd_lock);
5369 				putback(stp, rdq, mp, mp->b_band);
5370 				mutex_exit(&stp->sd_lock);
5371 				setf(fd, NULL);	/* release fd entry */
5372 				return (EOVERFLOW);
5373 			}
5374 
5375 			ostrfd.fd = fd;
5376 			ostrfd.uid = (o_uid_t)srf->uid;
5377 			ostrfd.gid = (o_gid_t)srf->gid;
5378 
5379 			/* Null the filler bits */
5380 			for (i = 0; i < 8; i++)
5381 				ostrfd.fill[i] = 0;
5382 
5383 			error = strcopyout(&ostrfd, (void *)arg,
5384 			    sizeof (struct o_strrecvfd), copyflag);
5385 		} else {		/* I_E_RECVFD */
5386 			struct strrecvfd	strfd;
5387 
5388 			strfd.fd = fd;
5389 			strfd.uid = srf->uid;
5390 			strfd.gid = srf->gid;
5391 
5392 			/* null the filler bits */
5393 			for (i = 0; i < 8; i++)
5394 				strfd.fill[i] = 0;
5395 
5396 			error = strcopyout(&strfd, (void *)arg,
5397 			    sizeof (struct strrecvfd), copyflag);
5398 		}
5399 
5400 		if (error) {
5401 			setf(fd, NULL);	/* release fd entry */
5402 			mutex_enter(&stp->sd_lock);
5403 			putback(stp, rdq, mp, mp->b_band);
5404 			mutex_exit(&stp->sd_lock);
5405 			return (error);
5406 		}
5407 		if (audit_active) {
5408 			audit_fdrecv(fd, srf->fp);
5409 		}
5410 
5411 		/*
5412 		 * Always increment f_count since the freemsg() below will
5413 		 * always call free_passfp() which performs a closef().
5414 		 */
5415 		mutex_enter(&srf->fp->f_tlock);
5416 		srf->fp->f_count++;
5417 		mutex_exit(&srf->fp->f_tlock);
5418 		setf(fd, srf->fp);
5419 		freemsg(mp);
5420 		return (0);
5421 	}
5422 
5423 	case I_SWROPT:
5424 		/*
5425 		 * Set/clear the write options. arg is a bit
5426 		 * mask with any of the following bits set...
5427 		 * 	SNDZERO - send zero length message
5428 		 *	SNDPIPE - send sigpipe to process if
5429 		 *		sd_werror is set and process is
5430 		 *		doing a write or putmsg.
5431 		 * The new stream head write options should reflect
5432 		 * what is in arg.
5433 		 */
5434 		if (arg & ~(SNDZERO|SNDPIPE))
5435 			return (EINVAL);
5436 
5437 		mutex_enter(&stp->sd_lock);
5438 		stp->sd_wput_opt &= ~(SW_SIGPIPE|SW_SNDZERO);
5439 		if (arg & SNDZERO)
5440 			stp->sd_wput_opt |= SW_SNDZERO;
5441 		if (arg & SNDPIPE)
5442 			stp->sd_wput_opt |= SW_SIGPIPE;
5443 		mutex_exit(&stp->sd_lock);
5444 		return (0);
5445 
5446 	case I_GWROPT:
5447 	{
5448 		int wropt = 0;
5449 
5450 		if (stp->sd_wput_opt & SW_SNDZERO)
5451 			wropt |= SNDZERO;
5452 		if (stp->sd_wput_opt & SW_SIGPIPE)
5453 			wropt |= SNDPIPE;
5454 		return (strcopyout(&wropt, (void *)arg, sizeof (wropt),
5455 		    copyflag));
5456 	}
5457 
5458 	case I_LIST:
5459 		/*
5460 		 * Returns all the modules found on this stream,
5461 		 * upto the driver. If argument is NULL, return the
5462 		 * number of modules (including driver). If argument
5463 		 * is not NULL, copy the names into the structure
5464 		 * provided.
5465 		 */
5466 
5467 	{
5468 		queue_t *q;
5469 		int num_modules, space_allocated;
5470 		STRUCT_DECL(str_list, strlist);
5471 		struct str_mlist *mlist_ptr;
5472 
5473 		if (arg == NULL) { /* Return number of modules plus driver */
5474 			q = stp->sd_wrq;
5475 			if (stp->sd_vnode->v_type == VFIFO) {
5476 				*rvalp = stp->sd_pushcnt;
5477 			} else {
5478 				*rvalp = stp->sd_pushcnt + 1;
5479 			}
5480 		} else {
5481 			STRUCT_INIT(strlist, flag);
5482 
5483 			error = strcopyin((void *)arg, STRUCT_BUF(strlist),
5484 			    STRUCT_SIZE(strlist), copyflag);
5485 			if (error)
5486 				return (error);
5487 
5488 			space_allocated = STRUCT_FGET(strlist, sl_nmods);
5489 			if ((space_allocated) <= 0)
5490 				return (EINVAL);
5491 			claimstr(stp->sd_wrq);
5492 			q = stp->sd_wrq;
5493 			num_modules = 0;
5494 			while (_SAMESTR(q) && (space_allocated != 0)) {
5495 				char *name =
5496 				    q->q_next->q_qinfo->qi_minfo->mi_idname;
5497 
5498 				mlist_ptr = STRUCT_FGETP(strlist, sl_modlist);
5499 
5500 				error = strcopyout(name, mlist_ptr,
5501 				    strlen(name) + 1, copyflag);
5502 
5503 				if (error) {
5504 					releasestr(stp->sd_wrq);
5505 					return (error);
5506 				}
5507 				q = q->q_next;
5508 				space_allocated--;
5509 				num_modules++;
5510 				mlist_ptr =
5511 				    (struct str_mlist *)((uintptr_t)mlist_ptr +
5512 				    sizeof (struct str_mlist));
5513 				STRUCT_FSETP(strlist, sl_modlist, mlist_ptr);
5514 			}
5515 			releasestr(stp->sd_wrq);
5516 			error = strcopyout(&num_modules, (void *)arg,
5517 			    sizeof (int), copyflag);
5518 		}
5519 		return (error);
5520 	}
5521 
5522 	case I_CKBAND:
5523 	{
5524 		queue_t *q;
5525 		qband_t *qbp;
5526 
5527 		if ((arg < 0) || (arg >= NBAND))
5528 			return (EINVAL);
5529 		q = _RD(stp->sd_wrq);
5530 		mutex_enter(QLOCK(q));
5531 		if (arg > (int)q->q_nband) {
5532 			*rvalp = 0;
5533 		} else {
5534 			if (arg == 0) {
5535 				if (q->q_first)
5536 					*rvalp = 1;
5537 				else
5538 					*rvalp = 0;
5539 			} else {
5540 				qbp = q->q_bandp;
5541 				while (--arg > 0)
5542 					qbp = qbp->qb_next;
5543 				if (qbp->qb_first)
5544 					*rvalp = 1;
5545 				else
5546 					*rvalp = 0;
5547 			}
5548 		}
5549 		mutex_exit(QLOCK(q));
5550 		return (0);
5551 	}
5552 
5553 	case I_GETBAND:
5554 	{
5555 		int intpri;
5556 		queue_t *q;
5557 
5558 		q = _RD(stp->sd_wrq);
5559 		mutex_enter(QLOCK(q));
5560 		mp = q->q_first;
5561 		if (!mp) {
5562 			mutex_exit(QLOCK(q));
5563 			return (ENODATA);
5564 		}
5565 		intpri = (int)mp->b_band;
5566 		error = strcopyout(&intpri, (void *)arg, sizeof (int),
5567 		    copyflag);
5568 		mutex_exit(QLOCK(q));
5569 		return (error);
5570 	}
5571 
5572 	case I_ATMARK:
5573 	{
5574 		queue_t *q;
5575 
5576 		if (arg & ~(ANYMARK|LASTMARK))
5577 			return (EINVAL);
5578 		q = _RD(stp->sd_wrq);
5579 		mutex_enter(&stp->sd_lock);
5580 		if ((stp->sd_flag & STRATMARK) && (arg == ANYMARK)) {
5581 			*rvalp = 1;
5582 		} else {
5583 			mutex_enter(QLOCK(q));
5584 			mp = q->q_first;
5585 
5586 			if (mp == NULL)
5587 				*rvalp = 0;
5588 			else if ((arg == ANYMARK) && (mp->b_flag & MSGMARK))
5589 				*rvalp = 1;
5590 			else if ((arg == LASTMARK) && (mp == stp->sd_mark))
5591 				*rvalp = 1;
5592 			else
5593 				*rvalp = 0;
5594 			mutex_exit(QLOCK(q));
5595 		}
5596 		mutex_exit(&stp->sd_lock);
5597 		return (0);
5598 	}
5599 
5600 	case I_CANPUT:
5601 	{
5602 		char band;
5603 
5604 		if ((arg < 0) || (arg >= NBAND))
5605 			return (EINVAL);
5606 		band = (char)arg;
5607 		*rvalp = bcanputnext(stp->sd_wrq, band);
5608 		return (0);
5609 	}
5610 
5611 	case I_SETCLTIME:
5612 	{
5613 		int closetime;
5614 
5615 		error = strcopyin((void *)arg, &closetime, sizeof (int),
5616 		    copyflag);
5617 		if (error)
5618 			return (error);
5619 		if (closetime < 0)
5620 			return (EINVAL);
5621 
5622 		stp->sd_closetime = closetime;
5623 		return (0);
5624 	}
5625 
5626 	case I_GETCLTIME:
5627 	{
5628 		int closetime;
5629 
5630 		closetime = stp->sd_closetime;
5631 		return (strcopyout(&closetime, (void *)arg, sizeof (int),
5632 		    copyflag));
5633 	}
5634 
5635 	case TIOCGSID:
5636 	{
5637 		pid_t sid;
5638 
5639 		mutex_enter(&stp->sd_lock);
5640 		if (stp->sd_sidp == NULL) {
5641 			mutex_exit(&stp->sd_lock);
5642 			return (ENOTTY);
5643 		}
5644 		sid = stp->sd_sidp->pid_id;
5645 		mutex_exit(&stp->sd_lock);
5646 		return (strcopyout(&sid, (void *)arg, sizeof (pid_t),
5647 		    copyflag));
5648 	}
5649 
5650 	case TIOCSPGRP:
5651 	{
5652 		pid_t pgrp;
5653 		proc_t *q;
5654 		pid_t	sid, fg_pgid, bg_pgid;
5655 
5656 		if (error = strcopyin((void *)arg, &pgrp, sizeof (pid_t),
5657 		    copyflag))
5658 			return (error);
5659 		mutex_enter(&stp->sd_lock);
5660 		mutex_enter(&pidlock);
5661 		if (stp->sd_sidp != ttoproc(curthread)->p_sessp->s_sidp) {
5662 			mutex_exit(&pidlock);
5663 			mutex_exit(&stp->sd_lock);
5664 			return (ENOTTY);
5665 		}
5666 		if (pgrp == stp->sd_pgidp->pid_id) {
5667 			mutex_exit(&pidlock);
5668 			mutex_exit(&stp->sd_lock);
5669 			return (0);
5670 		}
5671 		if (pgrp <= 0 || pgrp >= maxpid) {
5672 			mutex_exit(&pidlock);
5673 			mutex_exit(&stp->sd_lock);
5674 			return (EINVAL);
5675 		}
5676 		if ((q = pgfind(pgrp)) == NULL ||
5677 		    q->p_sessp != ttoproc(curthread)->p_sessp) {
5678 			mutex_exit(&pidlock);
5679 			mutex_exit(&stp->sd_lock);
5680 			return (EPERM);
5681 		}
5682 		sid = stp->sd_sidp->pid_id;
5683 		fg_pgid = q->p_pgrp;
5684 		bg_pgid = stp->sd_pgidp->pid_id;
5685 		CL_SET_PROCESS_GROUP(curthread, sid, bg_pgid, fg_pgid);
5686 		PID_RELE(stp->sd_pgidp);
5687 		ctty_clear_sighuped();
5688 		stp->sd_pgidp = q->p_pgidp;
5689 		PID_HOLD(stp->sd_pgidp);
5690 		mutex_exit(&pidlock);
5691 		mutex_exit(&stp->sd_lock);
5692 		return (0);
5693 	}
5694 
5695 	case TIOCGPGRP:
5696 	{
5697 		pid_t pgrp;
5698 
5699 		mutex_enter(&stp->sd_lock);
5700 		if (stp->sd_sidp == NULL) {
5701 			mutex_exit(&stp->sd_lock);
5702 			return (ENOTTY);
5703 		}
5704 		pgrp = stp->sd_pgidp->pid_id;
5705 		mutex_exit(&stp->sd_lock);
5706 		return (strcopyout(&pgrp, (void *)arg, sizeof (pid_t),
5707 		    copyflag));
5708 	}
5709 
5710 	case TIOCSCTTY:
5711 	{
5712 		return (strctty(stp));
5713 	}
5714 
5715 	case TIOCNOTTY:
5716 	{
5717 		/* freectty() always assumes curproc. */
5718 		if (freectty(B_FALSE) != 0)
5719 			return (0);
5720 		return (ENOTTY);
5721 	}
5722 
5723 	case FIONBIO:
5724 	case FIOASYNC:
5725 		return (0);	/* handled by the upper layer */
5726 	}
5727 }
5728 
5729 /*
5730  * Custom free routine used for M_PASSFP messages.
5731  */
5732 static void
5733 free_passfp(struct k_strrecvfd *srf)
5734 {
5735 	(void) closef(srf->fp);
5736 	kmem_free(srf, sizeof (struct k_strrecvfd) + sizeof (frtn_t));
5737 }
5738 
5739 /* ARGSUSED */
5740 int
5741 do_sendfp(struct stdata *stp, struct file *fp, struct cred *cr)
5742 {
5743 	queue_t *qp, *nextqp;
5744 	struct k_strrecvfd *srf;
5745 	mblk_t *mp;
5746 	frtn_t *frtnp;
5747 	size_t bufsize;
5748 	queue_t	*mate = NULL;
5749 	syncq_t	*sq = NULL;
5750 	int retval = 0;
5751 
5752 	if (stp->sd_flag & STRHUP)
5753 		return (ENXIO);
5754 
5755 	claimstr(stp->sd_wrq);
5756 
5757 	/* Fastpath, we have a pipe, and we are already mated, use it. */
5758 	if (STRMATED(stp)) {
5759 		qp = _RD(stp->sd_mate->sd_wrq);
5760 		claimstr(qp);
5761 		mate = qp;
5762 	} else { /* Not already mated. */
5763 
5764 		/*
5765 		 * Walk the stream to the end of this one.
5766 		 * assumes that the claimstr() will prevent
5767 		 * plumbing between the stream head and the
5768 		 * driver from changing
5769 		 */
5770 		qp = stp->sd_wrq;
5771 
5772 		/*
5773 		 * Loop until we reach the end of this stream.
5774 		 * On completion, qp points to the write queue
5775 		 * at the end of the stream, or the read queue
5776 		 * at the stream head if this is a fifo.
5777 		 */
5778 		while (((qp = qp->q_next) != NULL) && _SAMESTR(qp))
5779 			;
5780 
5781 		/*
5782 		 * Just in case we get a q_next which is NULL, but
5783 		 * not at the end of the stream.  This is actually
5784 		 * broken, so we set an assert to catch it in
5785 		 * debug, and set an error and return if not debug.
5786 		 */
5787 		ASSERT(qp);
5788 		if (qp == NULL) {
5789 			releasestr(stp->sd_wrq);
5790 			return (EINVAL);
5791 		}
5792 
5793 		/*
5794 		 * Enter the syncq for the driver, so (hopefully)
5795 		 * the queue values will not change on us.
5796 		 * XXXX - This will only prevent the race IFF only
5797 		 *   the write side modifies the q_next member, and
5798 		 *   the put procedure is protected by at least
5799 		 *   MT_PERQ.
5800 		 */
5801 		if ((sq = qp->q_syncq) != NULL)
5802 			entersq(sq, SQ_PUT);
5803 
5804 		/* Now get the q_next value from this qp. */
5805 		nextqp = qp->q_next;
5806 
5807 		/*
5808 		 * If nextqp exists and the other stream is different
5809 		 * from this one claim the stream, set the mate, and
5810 		 * get the read queue at the stream head of the other
5811 		 * stream.  Assumes that nextqp was at least valid when
5812 		 * we got it.  Hopefully the entersq of the driver
5813 		 * will prevent it from changing on us.
5814 		 */
5815 		if ((nextqp != NULL) && (STREAM(nextqp) != stp)) {
5816 			ASSERT(qp->q_qinfo->qi_srvp);
5817 			ASSERT(_OTHERQ(qp)->q_qinfo->qi_srvp);
5818 			ASSERT(_OTHERQ(qp->q_next)->q_qinfo->qi_srvp);
5819 			claimstr(nextqp);
5820 
5821 			/* Make sure we still have a q_next */
5822 			if (nextqp != qp->q_next) {
5823 				releasestr(stp->sd_wrq);
5824 				releasestr(nextqp);
5825 				return (EINVAL);
5826 			}
5827 
5828 			qp = _RD(STREAM(nextqp)->sd_wrq);
5829 			mate = qp;
5830 		}
5831 		/* If we entered the synq above, leave it. */
5832 		if (sq != NULL)
5833 			leavesq(sq, SQ_PUT);
5834 	} /*  STRMATED(STP)  */
5835 
5836 	/* XXX prevents substitution of the ops vector */
5837 	if (qp->q_qinfo != &strdata && qp->q_qinfo != &fifo_strdata) {
5838 		retval = EINVAL;
5839 		goto out;
5840 	}
5841 
5842 	if (qp->q_flag & QFULL) {
5843 		retval = EAGAIN;
5844 		goto out;
5845 	}
5846 
5847 	/*
5848 	 * Since M_PASSFP messages include a file descriptor, we use
5849 	 * esballoc() and specify a custom free routine (free_passfp()) that
5850 	 * will close the descriptor as part of freeing the message.  For
5851 	 * convenience, we stash the frtn_t right after the data block.
5852 	 */
5853 	bufsize = sizeof (struct k_strrecvfd) + sizeof (frtn_t);
5854 	srf = kmem_alloc(bufsize, KM_NOSLEEP);
5855 	if (srf == NULL) {
5856 		retval = EAGAIN;
5857 		goto out;
5858 	}
5859 
5860 	frtnp = (frtn_t *)(srf + 1);
5861 	frtnp->free_arg = (caddr_t)srf;
5862 	frtnp->free_func = free_passfp;
5863 
5864 	mp = esballoc((uchar_t *)srf, bufsize, BPRI_MED, frtnp);
5865 	if (mp == NULL) {
5866 		kmem_free(srf, bufsize);
5867 		retval = EAGAIN;
5868 		goto out;
5869 	}
5870 	mp->b_wptr += sizeof (struct k_strrecvfd);
5871 	mp->b_datap->db_type = M_PASSFP;
5872 
5873 	srf->fp = fp;
5874 	srf->uid = crgetuid(curthread->t_cred);
5875 	srf->gid = crgetgid(curthread->t_cred);
5876 	mutex_enter(&fp->f_tlock);
5877 	fp->f_count++;
5878 	mutex_exit(&fp->f_tlock);
5879 
5880 	put(qp, mp);
5881 out:
5882 	releasestr(stp->sd_wrq);
5883 	if (mate)
5884 		releasestr(mate);
5885 	return (retval);
5886 }
5887 
5888 /*
5889  * Send an ioctl message downstream and wait for acknowledgement.
5890  * flags may be set to either U_TO_K or K_TO_K and a combination
5891  * of STR_NOERROR or STR_NOSIG
5892  * STR_NOSIG: Signals are essentially ignored or held and have
5893  *	no effect for the duration of the call.
5894  * STR_NOERROR: Ignores stream head read, write and hup errors.
5895  *	Additionally, if an existing ioctl times out, it is assumed
5896  *	lost and and this ioctl will continue as if the previous ioctl had
5897  *	finished.  ETIME may be returned if this ioctl times out (i.e.
5898  *	ic_timout is not INFTIM).  Non-stream head errors may be returned if
5899  *	the ioc_error indicates that the driver/module had problems,
5900  *	an EFAULT was found when accessing user data, a lack of
5901  * 	resources, etc.
5902  */
5903 int
5904 strdoioctl(
5905 	struct stdata *stp,
5906 	struct strioctl *strioc,
5907 	int fflags,		/* file flags with model info */
5908 	int flag,
5909 	cred_t *crp,
5910 	int *rvalp)
5911 {
5912 	mblk_t *bp;
5913 	struct iocblk *iocbp;
5914 	struct copyreq *reqp;
5915 	struct copyresp *resp;
5916 	int id;
5917 	int transparent = 0;
5918 	int error = 0;
5919 	int len = 0;
5920 	caddr_t taddr;
5921 	int copyflag = (flag & (U_TO_K | K_TO_K));
5922 	int sigflag = (flag & STR_NOSIG);
5923 	int errs;
5924 	uint_t waitflags;
5925 
5926 	ASSERT(copyflag == U_TO_K || copyflag == K_TO_K);
5927 	ASSERT((fflags & FMODELS) != 0);
5928 
5929 	TRACE_2(TR_FAC_STREAMS_FR,
5930 	    TR_STRDOIOCTL,
5931 	    "strdoioctl:stp %p strioc %p", stp, strioc);
5932 	if (strioc->ic_len == TRANSPARENT) {	/* send arg in M_DATA block */
5933 		transparent = 1;
5934 		strioc->ic_len = sizeof (intptr_t);
5935 	}
5936 
5937 	if (strioc->ic_len < 0 || (strmsgsz > 0 && strioc->ic_len > strmsgsz))
5938 		return (EINVAL);
5939 
5940 	if ((bp = allocb_cred_wait(sizeof (union ioctypes), sigflag, &error,
5941 	    crp)) == NULL)
5942 			return (error);
5943 
5944 	bzero(bp->b_wptr, sizeof (union ioctypes));
5945 
5946 	iocbp = (struct iocblk *)bp->b_wptr;
5947 	iocbp->ioc_count = strioc->ic_len;
5948 	iocbp->ioc_cmd = strioc->ic_cmd;
5949 	iocbp->ioc_flag = (fflags & FMODELS);
5950 
5951 	crhold(crp);
5952 	iocbp->ioc_cr = crp;
5953 	DB_TYPE(bp) = M_IOCTL;
5954 	DB_CPID(bp) = curproc->p_pid;
5955 	bp->b_wptr += sizeof (struct iocblk);
5956 
5957 	if (flag & STR_NOERROR)
5958 		errs = STPLEX;
5959 	else
5960 		errs = STRHUP|STRDERR|STWRERR|STPLEX;
5961 
5962 	/*
5963 	 * If there is data to copy into ioctl block, do so.
5964 	 */
5965 	if (iocbp->ioc_count > 0) {
5966 		if (transparent)
5967 			/*
5968 			 * Note: STR_NOERROR does not have an effect
5969 			 * in putiocd()
5970 			 */
5971 			id = K_TO_K | sigflag;
5972 		else
5973 			id = flag;
5974 		if ((error = putiocd(bp, strioc->ic_dp, id, crp)) != 0) {
5975 			freemsg(bp);
5976 			crfree(crp);
5977 			return (error);
5978 		}
5979 
5980 		/*
5981 		 * We could have slept copying in user pages.
5982 		 * Recheck the stream head state (the other end
5983 		 * of a pipe could have gone away).
5984 		 */
5985 		if (stp->sd_flag & errs) {
5986 			mutex_enter(&stp->sd_lock);
5987 			error = strgeterr(stp, errs, 0);
5988 			mutex_exit(&stp->sd_lock);
5989 			if (error != 0) {
5990 				freemsg(bp);
5991 				crfree(crp);
5992 				return (error);
5993 			}
5994 		}
5995 	}
5996 	if (transparent)
5997 		iocbp->ioc_count = TRANSPARENT;
5998 
5999 	/*
6000 	 * Block for up to STRTIMOUT milliseconds if there is an outstanding
6001 	 * ioctl for this stream already running.  All processes
6002 	 * sleeping here will be awakened as a result of an ACK
6003 	 * or NAK being received for the outstanding ioctl, or
6004 	 * as a result of the timer expiring on the outstanding
6005 	 * ioctl (a failure), or as a result of any waiting
6006 	 * process's timer expiring (also a failure).
6007 	 */
6008 
6009 	error = 0;
6010 	mutex_enter(&stp->sd_lock);
6011 	while (stp->sd_flag & (IOCWAIT | IOCWAITNE)) {
6012 		clock_t cv_rval;
6013 
6014 		TRACE_0(TR_FAC_STREAMS_FR,
6015 		    TR_STRDOIOCTL_WAIT,
6016 		    "strdoioctl sleeps - IOCWAIT");
6017 		cv_rval = str_cv_wait(&stp->sd_iocmonitor, &stp->sd_lock,
6018 		    STRTIMOUT, sigflag);
6019 		if (cv_rval <= 0) {
6020 			if (cv_rval == 0) {
6021 				error = EINTR;
6022 			} else {
6023 				if (flag & STR_NOERROR) {
6024 					/*
6025 					 * Terminating current ioctl in
6026 					 * progress -- assume it got lost and
6027 					 * wake up the other thread so that the
6028 					 * operation completes.
6029 					 */
6030 					if (!(stp->sd_flag & IOCWAITNE)) {
6031 						stp->sd_flag |= IOCWAITNE;
6032 						cv_broadcast(&stp->sd_monitor);
6033 					}
6034 					/*
6035 					 * Otherwise, there's a running
6036 					 * STR_NOERROR -- we have no choice
6037 					 * here but to wait forever (or until
6038 					 * interrupted).
6039 					 */
6040 				} else {
6041 					/*
6042 					 * pending ioctl has caused
6043 					 * us to time out
6044 					 */
6045 					error = ETIME;
6046 				}
6047 			}
6048 		} else if ((stp->sd_flag & errs)) {
6049 			error = strgeterr(stp, errs, 0);
6050 		}
6051 		if (error) {
6052 			mutex_exit(&stp->sd_lock);
6053 			freemsg(bp);
6054 			crfree(crp);
6055 			return (error);
6056 		}
6057 	}
6058 
6059 	/*
6060 	 * Have control of ioctl mechanism.
6061 	 * Send down ioctl packet and wait for response.
6062 	 */
6063 	if (stp->sd_iocblk != (mblk_t *)-1) {
6064 		freemsg(stp->sd_iocblk);
6065 	}
6066 	stp->sd_iocblk = NULL;
6067 
6068 	/*
6069 	 * If this is marked with 'noerror' (internal; mostly
6070 	 * I_{P,}{UN,}LINK), then make sure nobody else is able to get
6071 	 * in here by setting IOCWAITNE.
6072 	 */
6073 	waitflags = IOCWAIT;
6074 	if (flag & STR_NOERROR)
6075 		waitflags |= IOCWAITNE;
6076 
6077 	stp->sd_flag |= waitflags;
6078 
6079 	/*
6080 	 * Assign sequence number.
6081 	 */
6082 	iocbp->ioc_id = stp->sd_iocid = getiocseqno();
6083 
6084 	mutex_exit(&stp->sd_lock);
6085 
6086 	TRACE_1(TR_FAC_STREAMS_FR,
6087 	    TR_STRDOIOCTL_PUT, "strdoioctl put: stp %p", stp);
6088 	stream_willservice(stp);
6089 	putnext(stp->sd_wrq, bp);
6090 	stream_runservice(stp);
6091 
6092 	/*
6093 	 * Timed wait for acknowledgment.  The wait time is limited by the
6094 	 * timeout value, which must be a positive integer (number of
6095 	 * milliseconds) to wait, or 0 (use default value of STRTIMOUT
6096 	 * milliseconds), or -1 (wait forever).  This will be awakened
6097 	 * either by an ACK/NAK message arriving, the timer expiring, or
6098 	 * the timer expiring on another ioctl waiting for control of the
6099 	 * mechanism.
6100 	 */
6101 waitioc:
6102 	mutex_enter(&stp->sd_lock);
6103 
6104 
6105 	/*
6106 	 * If the reply has already arrived, don't sleep.  If awakened from
6107 	 * the sleep, fail only if the reply has not arrived by then.
6108 	 * Otherwise, process the reply.
6109 	 */
6110 	while (!stp->sd_iocblk) {
6111 		clock_t cv_rval;
6112 
6113 		if (stp->sd_flag & errs) {
6114 			error = strgeterr(stp, errs, 0);
6115 			if (error != 0) {
6116 				stp->sd_flag &= ~waitflags;
6117 				cv_broadcast(&stp->sd_iocmonitor);
6118 				mutex_exit(&stp->sd_lock);
6119 				crfree(crp);
6120 				return (error);
6121 			}
6122 		}
6123 
6124 		TRACE_0(TR_FAC_STREAMS_FR,
6125 		    TR_STRDOIOCTL_WAIT2,
6126 		    "strdoioctl sleeps awaiting reply");
6127 		ASSERT(error == 0);
6128 
6129 		cv_rval = str_cv_wait(&stp->sd_monitor, &stp->sd_lock,
6130 		    (strioc->ic_timout ?
6131 		    strioc->ic_timout * 1000 : STRTIMOUT), sigflag);
6132 
6133 		/*
6134 		 * There are four possible cases here: interrupt, timeout,
6135 		 * wakeup by IOCWAITNE (above), or wakeup by strrput_nondata (a
6136 		 * valid M_IOCTL reply).
6137 		 *
6138 		 * If we've been awakened by a STR_NOERROR ioctl on some other
6139 		 * thread, then sd_iocblk will still be NULL, and IOCWAITNE
6140 		 * will be set.  Pretend as if we just timed out.  Note that
6141 		 * this other thread waited at least STRTIMOUT before trying to
6142 		 * awaken our thread, so this is indistinguishable (even for
6143 		 * INFTIM) from the case where we failed with ETIME waiting on
6144 		 * IOCWAIT in the prior loop.
6145 		 */
6146 		if (cv_rval > 0 && !(flag & STR_NOERROR) &&
6147 		    stp->sd_iocblk == NULL && (stp->sd_flag & IOCWAITNE)) {
6148 			cv_rval = -1;
6149 		}
6150 
6151 		/*
6152 		 * note: STR_NOERROR does not protect
6153 		 * us here.. use ic_timout < 0
6154 		 */
6155 		if (cv_rval <= 0) {
6156 			if (cv_rval == 0) {
6157 				error = EINTR;
6158 			} else {
6159 				error =  ETIME;
6160 			}
6161 			/*
6162 			 * A message could have come in after we were scheduled
6163 			 * but before we were actually run.
6164 			 */
6165 			bp = stp->sd_iocblk;
6166 			stp->sd_iocblk = NULL;
6167 			if (bp != NULL) {
6168 				if ((bp->b_datap->db_type == M_COPYIN) ||
6169 				    (bp->b_datap->db_type == M_COPYOUT)) {
6170 					mutex_exit(&stp->sd_lock);
6171 					if (bp->b_cont) {
6172 						freemsg(bp->b_cont);
6173 						bp->b_cont = NULL;
6174 					}
6175 					bp->b_datap->db_type = M_IOCDATA;
6176 					bp->b_wptr = bp->b_rptr +
6177 					    sizeof (struct copyresp);
6178 					resp = (struct copyresp *)bp->b_rptr;
6179 					resp->cp_rval =
6180 					    (caddr_t)1; /* failure */
6181 					stream_willservice(stp);
6182 					putnext(stp->sd_wrq, bp);
6183 					stream_runservice(stp);
6184 					mutex_enter(&stp->sd_lock);
6185 				} else {
6186 					freemsg(bp);
6187 				}
6188 			}
6189 			stp->sd_flag &= ~waitflags;
6190 			cv_broadcast(&stp->sd_iocmonitor);
6191 			mutex_exit(&stp->sd_lock);
6192 			crfree(crp);
6193 			return (error);
6194 		}
6195 	}
6196 	bp = stp->sd_iocblk;
6197 	/*
6198 	 * Note: it is strictly impossible to get here with sd_iocblk set to
6199 	 * -1.  This is because the initial loop above doesn't allow any new
6200 	 * ioctls into the fray until all others have passed this point.
6201 	 */
6202 	ASSERT(bp != NULL && bp != (mblk_t *)-1);
6203 	TRACE_1(TR_FAC_STREAMS_FR,
6204 	    TR_STRDOIOCTL_ACK, "strdoioctl got reply: bp %p", bp);
6205 	if ((bp->b_datap->db_type == M_IOCACK) ||
6206 	    (bp->b_datap->db_type == M_IOCNAK)) {
6207 		/* for detection of duplicate ioctl replies */
6208 		stp->sd_iocblk = (mblk_t *)-1;
6209 		stp->sd_flag &= ~waitflags;
6210 		cv_broadcast(&stp->sd_iocmonitor);
6211 		mutex_exit(&stp->sd_lock);
6212 	} else {
6213 		/*
6214 		 * flags not cleared here because we're still doing
6215 		 * copy in/out for ioctl.
6216 		 */
6217 		stp->sd_iocblk = NULL;
6218 		mutex_exit(&stp->sd_lock);
6219 	}
6220 
6221 
6222 	/*
6223 	 * Have received acknowledgment.
6224 	 */
6225 
6226 	switch (bp->b_datap->db_type) {
6227 	case M_IOCACK:
6228 		/*
6229 		 * Positive ack.
6230 		 */
6231 		iocbp = (struct iocblk *)bp->b_rptr;
6232 
6233 		/*
6234 		 * Set error if indicated.
6235 		 */
6236 		if (iocbp->ioc_error) {
6237 			error = iocbp->ioc_error;
6238 			break;
6239 		}
6240 
6241 		/*
6242 		 * Set return value.
6243 		 */
6244 		*rvalp = iocbp->ioc_rval;
6245 
6246 		/*
6247 		 * Data may have been returned in ACK message (ioc_count > 0).
6248 		 * If so, copy it out to the user's buffer.
6249 		 */
6250 		if (iocbp->ioc_count && !transparent) {
6251 			if (error = getiocd(bp, strioc->ic_dp, copyflag))
6252 				break;
6253 		}
6254 		if (!transparent) {
6255 			if (len)	/* an M_COPYOUT was used with I_STR */
6256 				strioc->ic_len = len;
6257 			else
6258 				strioc->ic_len = (int)iocbp->ioc_count;
6259 		}
6260 		break;
6261 
6262 	case M_IOCNAK:
6263 		/*
6264 		 * Negative ack.
6265 		 *
6266 		 * The only thing to do is set error as specified
6267 		 * in neg ack packet.
6268 		 */
6269 		iocbp = (struct iocblk *)bp->b_rptr;
6270 
6271 		error = (iocbp->ioc_error ? iocbp->ioc_error : EINVAL);
6272 		break;
6273 
6274 	case M_COPYIN:
6275 		/*
6276 		 * Driver or module has requested user ioctl data.
6277 		 */
6278 		reqp = (struct copyreq *)bp->b_rptr;
6279 
6280 		/*
6281 		 * M_COPYIN should *never* have a message attached, though
6282 		 * it's harmless if it does -- thus, panic on a DEBUG
6283 		 * kernel and just free it on a non-DEBUG build.
6284 		 */
6285 		ASSERT(bp->b_cont == NULL);
6286 		if (bp->b_cont != NULL) {
6287 			freemsg(bp->b_cont);
6288 			bp->b_cont = NULL;
6289 		}
6290 
6291 		error = putiocd(bp, reqp->cq_addr, flag, crp);
6292 		if (error && bp->b_cont) {
6293 			freemsg(bp->b_cont);
6294 			bp->b_cont = NULL;
6295 		}
6296 
6297 		bp->b_wptr = bp->b_rptr + sizeof (struct copyresp);
6298 		bp->b_datap->db_type = M_IOCDATA;
6299 
6300 		mblk_setcred(bp, crp);
6301 		DB_CPID(bp) = curproc->p_pid;
6302 		resp = (struct copyresp *)bp->b_rptr;
6303 		resp->cp_rval = (caddr_t)(uintptr_t)error;
6304 		resp->cp_flag = (fflags & FMODELS);
6305 
6306 		stream_willservice(stp);
6307 		putnext(stp->sd_wrq, bp);
6308 		stream_runservice(stp);
6309 
6310 		if (error) {
6311 			mutex_enter(&stp->sd_lock);
6312 			stp->sd_flag &= ~waitflags;
6313 			cv_broadcast(&stp->sd_iocmonitor);
6314 			mutex_exit(&stp->sd_lock);
6315 			crfree(crp);
6316 			return (error);
6317 		}
6318 
6319 		goto waitioc;
6320 
6321 	case M_COPYOUT:
6322 		/*
6323 		 * Driver or module has ioctl data for a user.
6324 		 */
6325 		reqp = (struct copyreq *)bp->b_rptr;
6326 		ASSERT(bp->b_cont != NULL);
6327 
6328 		/*
6329 		 * Always (transparent or non-transparent )
6330 		 * use the address specified in the request
6331 		 */
6332 		taddr = reqp->cq_addr;
6333 		if (!transparent)
6334 			len = (int)reqp->cq_size;
6335 
6336 		/* copyout data to the provided address */
6337 		error = getiocd(bp, taddr, copyflag);
6338 
6339 		freemsg(bp->b_cont);
6340 		bp->b_cont = NULL;
6341 
6342 		bp->b_wptr = bp->b_rptr + sizeof (struct copyresp);
6343 		bp->b_datap->db_type = M_IOCDATA;
6344 
6345 		mblk_setcred(bp, crp);
6346 		DB_CPID(bp) = curproc->p_pid;
6347 		resp = (struct copyresp *)bp->b_rptr;
6348 		resp->cp_rval = (caddr_t)(uintptr_t)error;
6349 		resp->cp_flag = (fflags & FMODELS);
6350 
6351 		stream_willservice(stp);
6352 		putnext(stp->sd_wrq, bp);
6353 		stream_runservice(stp);
6354 
6355 		if (error) {
6356 			mutex_enter(&stp->sd_lock);
6357 			stp->sd_flag &= ~waitflags;
6358 			cv_broadcast(&stp->sd_iocmonitor);
6359 			mutex_exit(&stp->sd_lock);
6360 			crfree(crp);
6361 			return (error);
6362 		}
6363 		goto waitioc;
6364 
6365 	default:
6366 		ASSERT(0);
6367 		mutex_enter(&stp->sd_lock);
6368 		stp->sd_flag &= ~waitflags;
6369 		cv_broadcast(&stp->sd_iocmonitor);
6370 		mutex_exit(&stp->sd_lock);
6371 		break;
6372 	}
6373 
6374 	freemsg(bp);
6375 	crfree(crp);
6376 	return (error);
6377 }
6378 
6379 /*
6380  * Send an M_CMD message downstream and wait for a reply.  This is a ptools
6381  * special used to retrieve information from modules/drivers a stream without
6382  * being subjected to flow control or interfering with pending messages on the
6383  * stream (e.g. an ioctl in flight).
6384  */
6385 int
6386 strdocmd(struct stdata *stp, struct strcmd *scp, cred_t *crp)
6387 {
6388 	mblk_t *mp;
6389 	struct cmdblk *cmdp;
6390 	int error = 0;
6391 	int errs = STRHUP|STRDERR|STWRERR|STPLEX;
6392 	clock_t rval, timeout = STRTIMOUT;
6393 
6394 	if (scp->sc_len < 0 || scp->sc_len > sizeof (scp->sc_buf) ||
6395 	    scp->sc_timeout < -1)
6396 		return (EINVAL);
6397 
6398 	if (scp->sc_timeout > 0)
6399 		timeout = scp->sc_timeout * MILLISEC;
6400 
6401 	if ((mp = allocb_cred(sizeof (struct cmdblk), crp)) == NULL)
6402 		return (ENOMEM);
6403 
6404 	crhold(crp);
6405 
6406 	cmdp = (struct cmdblk *)mp->b_wptr;
6407 	cmdp->cb_cr = crp;
6408 	cmdp->cb_cmd = scp->sc_cmd;
6409 	cmdp->cb_len = scp->sc_len;
6410 	cmdp->cb_error = 0;
6411 	mp->b_wptr += sizeof (struct cmdblk);
6412 
6413 	DB_TYPE(mp) = M_CMD;
6414 	DB_CPID(mp) = curproc->p_pid;
6415 
6416 	/*
6417 	 * Copy in the payload.
6418 	 */
6419 	if (cmdp->cb_len > 0) {
6420 		mp->b_cont = allocb_cred(sizeof (scp->sc_buf), crp);
6421 		if (mp->b_cont == NULL) {
6422 			error = ENOMEM;
6423 			goto out;
6424 		}
6425 
6426 		/* cb_len comes from sc_len, which has already been checked */
6427 		ASSERT(cmdp->cb_len <= sizeof (scp->sc_buf));
6428 		(void) bcopy(scp->sc_buf, mp->b_cont->b_wptr, cmdp->cb_len);
6429 		mp->b_cont->b_wptr += cmdp->cb_len;
6430 		DB_CPID(mp->b_cont) = curproc->p_pid;
6431 	}
6432 
6433 	/*
6434 	 * Since this mechanism is strictly for ptools, and since only one
6435 	 * process can be grabbed at a time, we simply fail if there's
6436 	 * currently an operation pending.
6437 	 */
6438 	mutex_enter(&stp->sd_lock);
6439 	if (stp->sd_flag & STRCMDWAIT) {
6440 		mutex_exit(&stp->sd_lock);
6441 		error = EBUSY;
6442 		goto out;
6443 	}
6444 	stp->sd_flag |= STRCMDWAIT;
6445 	ASSERT(stp->sd_cmdblk == NULL);
6446 	mutex_exit(&stp->sd_lock);
6447 
6448 	putnext(stp->sd_wrq, mp);
6449 	mp = NULL;
6450 
6451 	/*
6452 	 * Timed wait for acknowledgment.  If the reply has already arrived,
6453 	 * don't sleep.  If awakened from the sleep, fail only if the reply
6454 	 * has not arrived by then.  Otherwise, process the reply.
6455 	 */
6456 	mutex_enter(&stp->sd_lock);
6457 	while (stp->sd_cmdblk == NULL) {
6458 		if (stp->sd_flag & errs) {
6459 			if ((error = strgeterr(stp, errs, 0)) != 0)
6460 				goto waitout;
6461 		}
6462 
6463 		rval = str_cv_wait(&stp->sd_monitor, &stp->sd_lock, timeout, 0);
6464 		if (stp->sd_cmdblk != NULL)
6465 			break;
6466 
6467 		if (rval <= 0) {
6468 			error = (rval == 0) ? EINTR : ETIME;
6469 			goto waitout;
6470 		}
6471 	}
6472 
6473 	/*
6474 	 * We received a reply.
6475 	 */
6476 	mp = stp->sd_cmdblk;
6477 	stp->sd_cmdblk = NULL;
6478 	ASSERT(mp != NULL && DB_TYPE(mp) == M_CMD);
6479 	ASSERT(stp->sd_flag & STRCMDWAIT);
6480 	stp->sd_flag &= ~STRCMDWAIT;
6481 	mutex_exit(&stp->sd_lock);
6482 
6483 	cmdp = (struct cmdblk *)mp->b_rptr;
6484 	if ((error = cmdp->cb_error) != 0)
6485 		goto out;
6486 
6487 	/*
6488 	 * Data may have been returned in the reply (cb_len > 0).
6489 	 * If so, copy it out to the user's buffer.
6490 	 */
6491 	if (cmdp->cb_len > 0) {
6492 		if (mp->b_cont == NULL || MBLKL(mp->b_cont) < cmdp->cb_len) {
6493 			error = EPROTO;
6494 			goto out;
6495 		}
6496 
6497 		cmdp->cb_len = MIN(cmdp->cb_len, sizeof (scp->sc_buf));
6498 		(void) bcopy(mp->b_cont->b_rptr, scp->sc_buf, cmdp->cb_len);
6499 	}
6500 	scp->sc_len = cmdp->cb_len;
6501 out:
6502 	freemsg(mp);
6503 	crfree(crp);
6504 	return (error);
6505 waitout:
6506 	ASSERT(stp->sd_cmdblk == NULL);
6507 	stp->sd_flag &= ~STRCMDWAIT;
6508 	mutex_exit(&stp->sd_lock);
6509 	crfree(crp);
6510 	return (error);
6511 }
6512 
6513 /*
6514  * For the SunOS keyboard driver.
6515  * Return the next available "ioctl" sequence number.
6516  * Exported, so that streams modules can send "ioctl" messages
6517  * downstream from their open routine.
6518  */
6519 int
6520 getiocseqno(void)
6521 {
6522 	int	i;
6523 
6524 	mutex_enter(&strresources);
6525 	i = ++ioc_id;
6526 	mutex_exit(&strresources);
6527 	return (i);
6528 }
6529 
6530 /*
6531  * Get the next message from the read queue.  If the message is
6532  * priority, STRPRI will have been set by strrput().  This flag
6533  * should be reset only when the entire message at the front of the
6534  * queue as been consumed.
6535  *
6536  * NOTE: strgetmsg and kstrgetmsg have much of the logic in common.
6537  */
6538 int
6539 strgetmsg(
6540 	struct vnode *vp,
6541 	struct strbuf *mctl,
6542 	struct strbuf *mdata,
6543 	unsigned char *prip,
6544 	int *flagsp,
6545 	int fmode,
6546 	rval_t *rvp)
6547 {
6548 	struct stdata *stp;
6549 	mblk_t *bp, *nbp;
6550 	mblk_t *savemp = NULL;
6551 	mblk_t *savemptail = NULL;
6552 	uint_t old_sd_flag;
6553 	int flg;
6554 	int more = 0;
6555 	int error = 0;
6556 	char first = 1;
6557 	uint_t mark;		/* Contains MSG*MARK and _LASTMARK */
6558 #define	_LASTMARK	0x8000	/* Distinct from MSG*MARK */
6559 	unsigned char pri = 0;
6560 	queue_t *q;
6561 	int	pr = 0;			/* Partial read successful */
6562 	struct uio uios;
6563 	struct uio *uiop = &uios;
6564 	struct iovec iovs;
6565 	unsigned char type;
6566 
6567 	TRACE_1(TR_FAC_STREAMS_FR, TR_STRGETMSG_ENTER,
6568 	    "strgetmsg:%p", vp);
6569 
6570 	ASSERT(vp->v_stream);
6571 	stp = vp->v_stream;
6572 	rvp->r_val1 = 0;
6573 
6574 	mutex_enter(&stp->sd_lock);
6575 
6576 	if ((error = i_straccess(stp, JCREAD)) != 0) {
6577 		mutex_exit(&stp->sd_lock);
6578 		return (error);
6579 	}
6580 
6581 	if (stp->sd_flag & (STRDERR|STPLEX)) {
6582 		error = strgeterr(stp, STRDERR|STPLEX, 0);
6583 		if (error != 0) {
6584 			mutex_exit(&stp->sd_lock);
6585 			return (error);
6586 		}
6587 	}
6588 	mutex_exit(&stp->sd_lock);
6589 
6590 	switch (*flagsp) {
6591 	case MSG_HIPRI:
6592 		if (*prip != 0)
6593 			return (EINVAL);
6594 		break;
6595 
6596 	case MSG_ANY:
6597 	case MSG_BAND:
6598 		break;
6599 
6600 	default:
6601 		return (EINVAL);
6602 	}
6603 	/*
6604 	 * Setup uio and iov for data part
6605 	 */
6606 	iovs.iov_base = mdata->buf;
6607 	iovs.iov_len = mdata->maxlen;
6608 	uios.uio_iov = &iovs;
6609 	uios.uio_iovcnt = 1;
6610 	uios.uio_loffset = 0;
6611 	uios.uio_segflg = UIO_USERSPACE;
6612 	uios.uio_fmode = 0;
6613 	uios.uio_extflg = UIO_COPY_CACHED;
6614 	uios.uio_resid = mdata->maxlen;
6615 	uios.uio_offset = 0;
6616 
6617 	q = _RD(stp->sd_wrq);
6618 	mutex_enter(&stp->sd_lock);
6619 	old_sd_flag = stp->sd_flag;
6620 	mark = 0;
6621 	for (;;) {
6622 		int done = 0;
6623 		mblk_t *q_first = q->q_first;
6624 
6625 		/*
6626 		 * Get the next message of appropriate priority
6627 		 * from the stream head.  If the caller is interested
6628 		 * in band or hipri messages, then they should already
6629 		 * be enqueued at the stream head.  On the other hand
6630 		 * if the caller wants normal (band 0) messages, they
6631 		 * might be deferred in a synchronous stream and they
6632 		 * will need to be pulled up.
6633 		 *
6634 		 * After we have dequeued a message, we might find that
6635 		 * it was a deferred M_SIG that was enqueued at the
6636 		 * stream head.  It must now be posted as part of the
6637 		 * read by calling strsignal_nolock().
6638 		 *
6639 		 * Also note that strrput does not enqueue an M_PCSIG,
6640 		 * and there cannot be more than one hipri message,
6641 		 * so there was no need to have the M_PCSIG case.
6642 		 *
6643 		 * At some time it might be nice to try and wrap the
6644 		 * functionality of kstrgetmsg() and strgetmsg() into
6645 		 * a common routine so to reduce the amount of replicated
6646 		 * code (since they are extremely similar).
6647 		 */
6648 		if (!(*flagsp & (MSG_HIPRI|MSG_BAND))) {
6649 			/* Asking for normal, band0 data */
6650 			bp = strget(stp, q, uiop, first, &error);
6651 			ASSERT(MUTEX_HELD(&stp->sd_lock));
6652 			if (bp != NULL) {
6653 				if (bp->b_datap->db_type == M_SIG) {
6654 					strsignal_nolock(stp, *bp->b_rptr,
6655 					    (int32_t)bp->b_band);
6656 					continue;
6657 				} else {
6658 					break;
6659 				}
6660 			}
6661 			if (error != 0) {
6662 				goto getmout;
6663 			}
6664 
6665 		/*
6666 		 * We can't depend on the value of STRPRI here because
6667 		 * the stream head may be in transit. Therefore, we
6668 		 * must look at the type of the first message to
6669 		 * determine if a high priority messages is waiting
6670 		 */
6671 		} else if ((*flagsp & MSG_HIPRI) && q_first != NULL &&
6672 		    q_first->b_datap->db_type >= QPCTL &&
6673 		    (bp = getq_noenab(q)) != NULL) {
6674 			/* Asked for HIPRI and got one */
6675 			ASSERT(bp->b_datap->db_type >= QPCTL);
6676 			break;
6677 		} else if ((*flagsp & MSG_BAND) && q_first != NULL &&
6678 		    ((q_first->b_band >= *prip) ||
6679 		    q_first->b_datap->db_type >= QPCTL) &&
6680 		    (bp = getq_noenab(q)) != NULL) {
6681 			/*
6682 			 * Asked for at least band "prip" and got either at
6683 			 * least that band or a hipri message.
6684 			 */
6685 			ASSERT(bp->b_band >= *prip ||
6686 			    bp->b_datap->db_type >= QPCTL);
6687 			if (bp->b_datap->db_type == M_SIG) {
6688 				strsignal_nolock(stp, *bp->b_rptr,
6689 				    (int32_t)bp->b_band);
6690 				continue;
6691 			} else {
6692 				break;
6693 			}
6694 		}
6695 
6696 		/* No data. Time to sleep? */
6697 		qbackenable(q, 0);
6698 
6699 		/*
6700 		 * If STRHUP or STREOF, return 0 length control and data.
6701 		 * If resid is 0, then a read(fd,buf,0) was done. Do not
6702 		 * sleep to satisfy this request because by default we have
6703 		 * zero bytes to return.
6704 		 */
6705 		if ((stp->sd_flag & (STRHUP|STREOF)) || (mctl->maxlen == 0 &&
6706 		    mdata->maxlen == 0)) {
6707 			mctl->len = mdata->len = 0;
6708 			*flagsp = 0;
6709 			mutex_exit(&stp->sd_lock);
6710 			return (0);
6711 		}
6712 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRGETMSG_WAIT,
6713 		    "strgetmsg calls strwaitq:%p, %p",
6714 		    vp, uiop);
6715 		if (((error = strwaitq(stp, GETWAIT, (ssize_t)0, fmode, -1,
6716 		    &done)) != 0) || done) {
6717 			TRACE_2(TR_FAC_STREAMS_FR, TR_STRGETMSG_DONE,
6718 			    "strgetmsg error or done:%p, %p",
6719 			    vp, uiop);
6720 			mutex_exit(&stp->sd_lock);
6721 			return (error);
6722 		}
6723 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRGETMSG_AWAKE,
6724 		    "strgetmsg awakes:%p, %p", vp, uiop);
6725 		if ((error = i_straccess(stp, JCREAD)) != 0) {
6726 			mutex_exit(&stp->sd_lock);
6727 			return (error);
6728 		}
6729 		first = 0;
6730 	}
6731 	ASSERT(bp != NULL);
6732 	/*
6733 	 * Extract any mark information. If the message is not completely
6734 	 * consumed this information will be put in the mblk
6735 	 * that is putback.
6736 	 * If MSGMARKNEXT is set and the message is completely consumed
6737 	 * the STRATMARK flag will be set below. Likewise, if
6738 	 * MSGNOTMARKNEXT is set and the message is
6739 	 * completely consumed STRNOTATMARK will be set.
6740 	 */
6741 	mark = bp->b_flag & (MSGMARK | MSGMARKNEXT | MSGNOTMARKNEXT);
6742 	ASSERT((mark & (MSGMARKNEXT|MSGNOTMARKNEXT)) !=
6743 	    (MSGMARKNEXT|MSGNOTMARKNEXT));
6744 	if (mark != 0 && bp == stp->sd_mark) {
6745 		mark |= _LASTMARK;
6746 		stp->sd_mark = NULL;
6747 	}
6748 	/*
6749 	 * keep track of the original message type and priority
6750 	 */
6751 	pri = bp->b_band;
6752 	type = bp->b_datap->db_type;
6753 	if (type == M_PASSFP) {
6754 		if ((mark & _LASTMARK) && (stp->sd_mark == NULL))
6755 			stp->sd_mark = bp;
6756 		bp->b_flag |= mark & ~_LASTMARK;
6757 		putback(stp, q, bp, pri);
6758 		qbackenable(q, pri);
6759 		mutex_exit(&stp->sd_lock);
6760 		return (EBADMSG);
6761 	}
6762 	ASSERT(type != M_SIG);
6763 
6764 	/*
6765 	 * Set this flag so strrput will not generate signals. Need to
6766 	 * make sure this flag is cleared before leaving this routine
6767 	 * else signals will stop being sent.
6768 	 */
6769 	stp->sd_flag |= STRGETINPROG;
6770 	mutex_exit(&stp->sd_lock);
6771 
6772 	if (STREAM_NEEDSERVICE(stp))
6773 		stream_runservice(stp);
6774 
6775 	/*
6776 	 * Set HIPRI flag if message is priority.
6777 	 */
6778 	if (type >= QPCTL)
6779 		flg = MSG_HIPRI;
6780 	else
6781 		flg = MSG_BAND;
6782 
6783 	/*
6784 	 * First process PROTO or PCPROTO blocks, if any.
6785 	 */
6786 	if (mctl->maxlen >= 0 && type != M_DATA) {
6787 		size_t	n, bcnt;
6788 		char	*ubuf;
6789 
6790 		bcnt = mctl->maxlen;
6791 		ubuf = mctl->buf;
6792 		while (bp != NULL && bp->b_datap->db_type != M_DATA) {
6793 			if ((n = MIN(bcnt, bp->b_wptr - bp->b_rptr)) != 0 &&
6794 			    copyout(bp->b_rptr, ubuf, n)) {
6795 				error = EFAULT;
6796 				mutex_enter(&stp->sd_lock);
6797 				/*
6798 				 * clear stream head pri flag based on
6799 				 * first message type
6800 				 */
6801 				if (type >= QPCTL) {
6802 					ASSERT(type == M_PCPROTO);
6803 					stp->sd_flag &= ~STRPRI;
6804 				}
6805 				more = 0;
6806 				freemsg(bp);
6807 				goto getmout;
6808 			}
6809 			ubuf += n;
6810 			bp->b_rptr += n;
6811 			if (bp->b_rptr >= bp->b_wptr) {
6812 				nbp = bp;
6813 				bp = bp->b_cont;
6814 				freeb(nbp);
6815 			}
6816 			ASSERT(n <= bcnt);
6817 			bcnt -= n;
6818 			if (bcnt == 0)
6819 				break;
6820 		}
6821 		mctl->len = mctl->maxlen - bcnt;
6822 	} else
6823 		mctl->len = -1;
6824 
6825 	if (bp && bp->b_datap->db_type != M_DATA) {
6826 		/*
6827 		 * More PROTO blocks in msg.
6828 		 */
6829 		more |= MORECTL;
6830 		savemp = bp;
6831 		while (bp && bp->b_datap->db_type != M_DATA) {
6832 			savemptail = bp;
6833 			bp = bp->b_cont;
6834 		}
6835 		savemptail->b_cont = NULL;
6836 	}
6837 
6838 	/*
6839 	 * Now process DATA blocks, if any.
6840 	 */
6841 	if (mdata->maxlen >= 0 && bp) {
6842 		/*
6843 		 * struiocopyout will consume a potential zero-length
6844 		 * M_DATA even if uio_resid is zero.
6845 		 */
6846 		size_t oldresid = uiop->uio_resid;
6847 
6848 		bp = struiocopyout(bp, uiop, &error);
6849 		if (error != 0) {
6850 			mutex_enter(&stp->sd_lock);
6851 			/*
6852 			 * clear stream head hi pri flag based on
6853 			 * first message
6854 			 */
6855 			if (type >= QPCTL) {
6856 				ASSERT(type == M_PCPROTO);
6857 				stp->sd_flag &= ~STRPRI;
6858 			}
6859 			more = 0;
6860 			freemsg(savemp);
6861 			goto getmout;
6862 		}
6863 		/*
6864 		 * (pr == 1) indicates a partial read.
6865 		 */
6866 		if (oldresid > uiop->uio_resid)
6867 			pr = 1;
6868 		mdata->len = mdata->maxlen - uiop->uio_resid;
6869 	} else
6870 		mdata->len = -1;
6871 
6872 	if (bp) {			/* more data blocks in msg */
6873 		more |= MOREDATA;
6874 		if (savemp)
6875 			savemptail->b_cont = bp;
6876 		else
6877 			savemp = bp;
6878 	}
6879 
6880 	mutex_enter(&stp->sd_lock);
6881 	if (savemp) {
6882 		if (pr && (savemp->b_datap->db_type == M_DATA) &&
6883 		    msgnodata(savemp)) {
6884 			/*
6885 			 * Avoid queuing a zero-length tail part of
6886 			 * a message. pr=1 indicates that we read some of
6887 			 * the message.
6888 			 */
6889 			freemsg(savemp);
6890 			more &= ~MOREDATA;
6891 			/*
6892 			 * clear stream head hi pri flag based on
6893 			 * first message
6894 			 */
6895 			if (type >= QPCTL) {
6896 				ASSERT(type == M_PCPROTO);
6897 				stp->sd_flag &= ~STRPRI;
6898 			}
6899 		} else {
6900 			savemp->b_band = pri;
6901 			/*
6902 			 * If the first message was HIPRI and the one we're
6903 			 * putting back isn't, then clear STRPRI, otherwise
6904 			 * set STRPRI again.  Note that we must set STRPRI
6905 			 * again since the flush logic in strrput_nondata()
6906 			 * may have cleared it while we had sd_lock dropped.
6907 			 */
6908 			if (type >= QPCTL) {
6909 				ASSERT(type == M_PCPROTO);
6910 				if (queclass(savemp) < QPCTL)
6911 					stp->sd_flag &= ~STRPRI;
6912 				else
6913 					stp->sd_flag |= STRPRI;
6914 			} else if (queclass(savemp) >= QPCTL) {
6915 				/*
6916 				 * The first message was not a HIPRI message,
6917 				 * but the one we are about to putback is.
6918 				 * For simplicitly, we do not allow for HIPRI
6919 				 * messages to be embedded in the message
6920 				 * body, so just force it to same type as
6921 				 * first message.
6922 				 */
6923 				ASSERT(type == M_DATA || type == M_PROTO);
6924 				ASSERT(savemp->b_datap->db_type == M_PCPROTO);
6925 				savemp->b_datap->db_type = type;
6926 			}
6927 			if (mark != 0) {
6928 				savemp->b_flag |= mark & ~_LASTMARK;
6929 				if ((mark & _LASTMARK) &&
6930 				    (stp->sd_mark == NULL)) {
6931 					/*
6932 					 * If another marked message arrived
6933 					 * while sd_lock was not held sd_mark
6934 					 * would be non-NULL.
6935 					 */
6936 					stp->sd_mark = savemp;
6937 				}
6938 			}
6939 			putback(stp, q, savemp, pri);
6940 		}
6941 	} else {
6942 		/*
6943 		 * The complete message was consumed.
6944 		 *
6945 		 * If another M_PCPROTO arrived while sd_lock was not held
6946 		 * it would have been discarded since STRPRI was still set.
6947 		 *
6948 		 * Move the MSG*MARKNEXT information
6949 		 * to the stream head just in case
6950 		 * the read queue becomes empty.
6951 		 * clear stream head hi pri flag based on
6952 		 * first message
6953 		 *
6954 		 * If the stream head was at the mark
6955 		 * (STRATMARK) before we dropped sd_lock above
6956 		 * and some data was consumed then we have
6957 		 * moved past the mark thus STRATMARK is
6958 		 * cleared. However, if a message arrived in
6959 		 * strrput during the copyout above causing
6960 		 * STRATMARK to be set we can not clear that
6961 		 * flag.
6962 		 */
6963 		if (type >= QPCTL) {
6964 			ASSERT(type == M_PCPROTO);
6965 			stp->sd_flag &= ~STRPRI;
6966 		}
6967 		if (mark & (MSGMARKNEXT|MSGNOTMARKNEXT|MSGMARK)) {
6968 			if (mark & MSGMARKNEXT) {
6969 				stp->sd_flag &= ~STRNOTATMARK;
6970 				stp->sd_flag |= STRATMARK;
6971 			} else if (mark & MSGNOTMARKNEXT) {
6972 				stp->sd_flag &= ~STRATMARK;
6973 				stp->sd_flag |= STRNOTATMARK;
6974 			} else {
6975 				stp->sd_flag &= ~(STRATMARK|STRNOTATMARK);
6976 			}
6977 		} else if (pr && (old_sd_flag & STRATMARK)) {
6978 			stp->sd_flag &= ~STRATMARK;
6979 		}
6980 	}
6981 
6982 	*flagsp = flg;
6983 	*prip = pri;
6984 
6985 	/*
6986 	 * Getmsg cleanup processing - if the state of the queue has changed
6987 	 * some signals may need to be sent and/or poll awakened.
6988 	 */
6989 getmout:
6990 	qbackenable(q, pri);
6991 
6992 	/*
6993 	 * We dropped the stream head lock above. Send all M_SIG messages
6994 	 * before processing stream head for SIGPOLL messages.
6995 	 */
6996 	ASSERT(MUTEX_HELD(&stp->sd_lock));
6997 	while ((bp = q->q_first) != NULL &&
6998 	    (bp->b_datap->db_type == M_SIG)) {
6999 		/*
7000 		 * sd_lock is held so the content of the read queue can not
7001 		 * change.
7002 		 */
7003 		bp = getq(q);
7004 		ASSERT(bp != NULL && bp->b_datap->db_type == M_SIG);
7005 
7006 		strsignal_nolock(stp, *bp->b_rptr, (int32_t)bp->b_band);
7007 		mutex_exit(&stp->sd_lock);
7008 		freemsg(bp);
7009 		if (STREAM_NEEDSERVICE(stp))
7010 			stream_runservice(stp);
7011 		mutex_enter(&stp->sd_lock);
7012 	}
7013 
7014 	/*
7015 	 * stream head cannot change while we make the determination
7016 	 * whether or not to send a signal. Drop the flag to allow strrput
7017 	 * to send firstmsgsigs again.
7018 	 */
7019 	stp->sd_flag &= ~STRGETINPROG;
7020 
7021 	/*
7022 	 * If the type of message at the front of the queue changed
7023 	 * due to the receive the appropriate signals and pollwakeup events
7024 	 * are generated. The type of changes are:
7025 	 *	Processed a hipri message, q_first is not hipri.
7026 	 *	Processed a band X message, and q_first is band Y.
7027 	 * The generated signals and pollwakeups are identical to what
7028 	 * strrput() generates should the message that is now on q_first
7029 	 * arrive to an empty read queue.
7030 	 *
7031 	 * Note: only strrput will send a signal for a hipri message.
7032 	 */
7033 	if ((bp = q->q_first) != NULL && !(stp->sd_flag & STRPRI)) {
7034 		strsigset_t signals = 0;
7035 		strpollset_t pollwakeups = 0;
7036 
7037 		if (flg & MSG_HIPRI) {
7038 			/*
7039 			 * Removed a hipri message. Regular data at
7040 			 * the front of  the queue.
7041 			 */
7042 			if (bp->b_band == 0) {
7043 				signals = S_INPUT | S_RDNORM;
7044 				pollwakeups = POLLIN | POLLRDNORM;
7045 			} else {
7046 				signals = S_INPUT | S_RDBAND;
7047 				pollwakeups = POLLIN | POLLRDBAND;
7048 			}
7049 		} else if (pri != bp->b_band) {
7050 			/*
7051 			 * The band is different for the new q_first.
7052 			 */
7053 			if (bp->b_band == 0) {
7054 				signals = S_RDNORM;
7055 				pollwakeups = POLLIN | POLLRDNORM;
7056 			} else {
7057 				signals = S_RDBAND;
7058 				pollwakeups = POLLIN | POLLRDBAND;
7059 			}
7060 		}
7061 
7062 		if (pollwakeups != 0) {
7063 			if (pollwakeups == (POLLIN | POLLRDNORM)) {
7064 				if (!(stp->sd_rput_opt & SR_POLLIN))
7065 					goto no_pollwake;
7066 				stp->sd_rput_opt &= ~SR_POLLIN;
7067 			}
7068 			mutex_exit(&stp->sd_lock);
7069 			pollwakeup(&stp->sd_pollist, pollwakeups);
7070 			mutex_enter(&stp->sd_lock);
7071 		}
7072 no_pollwake:
7073 
7074 		if (stp->sd_sigflags & signals)
7075 			strsendsig(stp->sd_siglist, signals, bp->b_band, 0);
7076 	}
7077 	mutex_exit(&stp->sd_lock);
7078 
7079 	rvp->r_val1 = more;
7080 	return (error);
7081 #undef	_LASTMARK
7082 }
7083 
7084 /*
7085  * Get the next message from the read queue.  If the message is
7086  * priority, STRPRI will have been set by strrput().  This flag
7087  * should be reset only when the entire message at the front of the
7088  * queue as been consumed.
7089  *
7090  * If uiop is NULL all data is returned in mctlp.
7091  * Note that a NULL uiop implies that FNDELAY and FNONBLOCK are assumed
7092  * not enabled.
7093  * The timeout parameter is in milliseconds; -1 for infinity.
7094  * This routine handles the consolidation private flags:
7095  *	MSG_IGNERROR	Ignore any stream head error except STPLEX.
7096  *	MSG_DELAYERROR	Defer the error check until the queue is empty.
7097  *	MSG_HOLDSIG	Hold signals while waiting for data.
7098  *	MSG_IPEEK	Only peek at messages.
7099  *	MSG_DISCARDTAIL	Discard the tail M_DATA part of the message
7100  *			that doesn't fit.
7101  *	MSG_NOMARK	If the message is marked leave it on the queue.
7102  *
7103  * NOTE: strgetmsg and kstrgetmsg have much of the logic in common.
7104  */
7105 int
7106 kstrgetmsg(
7107 	struct vnode *vp,
7108 	mblk_t **mctlp,
7109 	struct uio *uiop,
7110 	unsigned char *prip,
7111 	int *flagsp,
7112 	clock_t timout,
7113 	rval_t *rvp)
7114 {
7115 	struct stdata *stp;
7116 	mblk_t *bp, *nbp;
7117 	mblk_t *savemp = NULL;
7118 	mblk_t *savemptail = NULL;
7119 	int flags;
7120 	uint_t old_sd_flag;
7121 	int flg;
7122 	int more = 0;
7123 	int error = 0;
7124 	char first = 1;
7125 	uint_t mark;		/* Contains MSG*MARK and _LASTMARK */
7126 #define	_LASTMARK	0x8000	/* Distinct from MSG*MARK */
7127 	unsigned char pri = 0;
7128 	queue_t *q;
7129 	int	pr = 0;			/* Partial read successful */
7130 	unsigned char type;
7131 
7132 	TRACE_1(TR_FAC_STREAMS_FR, TR_KSTRGETMSG_ENTER,
7133 	    "kstrgetmsg:%p", vp);
7134 
7135 	ASSERT(vp->v_stream);
7136 	stp = vp->v_stream;
7137 	rvp->r_val1 = 0;
7138 
7139 	mutex_enter(&stp->sd_lock);
7140 
7141 	if ((error = i_straccess(stp, JCREAD)) != 0) {
7142 		mutex_exit(&stp->sd_lock);
7143 		return (error);
7144 	}
7145 
7146 	flags = *flagsp;
7147 	if (stp->sd_flag & (STRDERR|STPLEX)) {
7148 		if ((stp->sd_flag & STPLEX) ||
7149 		    (flags & (MSG_IGNERROR|MSG_DELAYERROR)) == 0) {
7150 			error = strgeterr(stp, STRDERR|STPLEX,
7151 			    (flags & MSG_IPEEK));
7152 			if (error != 0) {
7153 				mutex_exit(&stp->sd_lock);
7154 				return (error);
7155 			}
7156 		}
7157 	}
7158 	mutex_exit(&stp->sd_lock);
7159 
7160 	switch (flags & (MSG_HIPRI|MSG_ANY|MSG_BAND)) {
7161 	case MSG_HIPRI:
7162 		if (*prip != 0)
7163 			return (EINVAL);
7164 		break;
7165 
7166 	case MSG_ANY:
7167 	case MSG_BAND:
7168 		break;
7169 
7170 	default:
7171 		return (EINVAL);
7172 	}
7173 
7174 retry:
7175 	q = _RD(stp->sd_wrq);
7176 	mutex_enter(&stp->sd_lock);
7177 	old_sd_flag = stp->sd_flag;
7178 	mark = 0;
7179 	for (;;) {
7180 		int done = 0;
7181 		int waitflag;
7182 		int fmode;
7183 		mblk_t *q_first = q->q_first;
7184 
7185 		/*
7186 		 * This section of the code operates just like the code
7187 		 * in strgetmsg().  There is a comment there about what
7188 		 * is going on here.
7189 		 */
7190 		if (!(flags & (MSG_HIPRI|MSG_BAND))) {
7191 			/* Asking for normal, band0 data */
7192 			bp = strget(stp, q, uiop, first, &error);
7193 			ASSERT(MUTEX_HELD(&stp->sd_lock));
7194 			if (bp != NULL) {
7195 				if (bp->b_datap->db_type == M_SIG) {
7196 					strsignal_nolock(stp, *bp->b_rptr,
7197 					    (int32_t)bp->b_band);
7198 					continue;
7199 				} else {
7200 					break;
7201 				}
7202 			}
7203 			if (error != 0) {
7204 				goto getmout;
7205 			}
7206 		/*
7207 		 * We can't depend on the value of STRPRI here because
7208 		 * the stream head may be in transit. Therefore, we
7209 		 * must look at the type of the first message to
7210 		 * determine if a high priority messages is waiting
7211 		 */
7212 		} else if ((flags & MSG_HIPRI) && q_first != NULL &&
7213 		    q_first->b_datap->db_type >= QPCTL &&
7214 		    (bp = getq_noenab(q)) != NULL) {
7215 			ASSERT(bp->b_datap->db_type >= QPCTL);
7216 			break;
7217 		} else if ((flags & MSG_BAND) && q_first != NULL &&
7218 		    ((q_first->b_band >= *prip) ||
7219 		    q_first->b_datap->db_type >= QPCTL) &&
7220 		    (bp = getq_noenab(q)) != NULL) {
7221 			/*
7222 			 * Asked for at least band "prip" and got either at
7223 			 * least that band or a hipri message.
7224 			 */
7225 			ASSERT(bp->b_band >= *prip ||
7226 			    bp->b_datap->db_type >= QPCTL);
7227 			if (bp->b_datap->db_type == M_SIG) {
7228 				strsignal_nolock(stp, *bp->b_rptr,
7229 				    (int32_t)bp->b_band);
7230 				continue;
7231 			} else {
7232 				break;
7233 			}
7234 		}
7235 
7236 		/* No data. Time to sleep? */
7237 		qbackenable(q, 0);
7238 
7239 		/*
7240 		 * Delayed error notification?
7241 		 */
7242 		if ((stp->sd_flag & (STRDERR|STPLEX)) &&
7243 		    (flags & (MSG_IGNERROR|MSG_DELAYERROR)) == MSG_DELAYERROR) {
7244 			error = strgeterr(stp, STRDERR|STPLEX,
7245 			    (flags & MSG_IPEEK));
7246 			if (error != 0) {
7247 				mutex_exit(&stp->sd_lock);
7248 				return (error);
7249 			}
7250 		}
7251 
7252 		/*
7253 		 * If STRHUP or STREOF, return 0 length control and data.
7254 		 * If a read(fd,buf,0) has been done, do not sleep, just
7255 		 * return.
7256 		 *
7257 		 * If mctlp == NULL and uiop == NULL, then the code will
7258 		 * do the strwaitq. This is an understood way of saying
7259 		 * sleep "polling" until a message is received.
7260 		 */
7261 		if ((stp->sd_flag & (STRHUP|STREOF)) ||
7262 		    (uiop != NULL && uiop->uio_resid == 0)) {
7263 			if (mctlp != NULL)
7264 				*mctlp = NULL;
7265 			*flagsp = 0;
7266 			mutex_exit(&stp->sd_lock);
7267 			return (0);
7268 		}
7269 
7270 		waitflag = GETWAIT;
7271 		if (flags &
7272 		    (MSG_HOLDSIG|MSG_IGNERROR|MSG_IPEEK|MSG_DELAYERROR)) {
7273 			if (flags & MSG_HOLDSIG)
7274 				waitflag |= STR_NOSIG;
7275 			if (flags & MSG_IGNERROR)
7276 				waitflag |= STR_NOERROR;
7277 			if (flags & MSG_IPEEK)
7278 				waitflag |= STR_PEEK;
7279 			if (flags & MSG_DELAYERROR)
7280 				waitflag |= STR_DELAYERR;
7281 		}
7282 		if (uiop != NULL)
7283 			fmode = uiop->uio_fmode;
7284 		else
7285 			fmode = 0;
7286 
7287 		TRACE_2(TR_FAC_STREAMS_FR, TR_KSTRGETMSG_WAIT,
7288 		    "kstrgetmsg calls strwaitq:%p, %p",
7289 		    vp, uiop);
7290 		if (((error = strwaitq(stp, waitflag, (ssize_t)0,
7291 		    fmode, timout, &done)) != 0) || done) {
7292 			TRACE_2(TR_FAC_STREAMS_FR, TR_KSTRGETMSG_DONE,
7293 			    "kstrgetmsg error or done:%p, %p",
7294 			    vp, uiop);
7295 			mutex_exit(&stp->sd_lock);
7296 			return (error);
7297 		}
7298 		TRACE_2(TR_FAC_STREAMS_FR, TR_KSTRGETMSG_AWAKE,
7299 		    "kstrgetmsg awakes:%p, %p", vp, uiop);
7300 		if ((error = i_straccess(stp, JCREAD)) != 0) {
7301 			mutex_exit(&stp->sd_lock);
7302 			return (error);
7303 		}
7304 		first = 0;
7305 	}
7306 	ASSERT(bp != NULL);
7307 	/*
7308 	 * Extract any mark information. If the message is not completely
7309 	 * consumed this information will be put in the mblk
7310 	 * that is putback.
7311 	 * If MSGMARKNEXT is set and the message is completely consumed
7312 	 * the STRATMARK flag will be set below. Likewise, if
7313 	 * MSGNOTMARKNEXT is set and the message is
7314 	 * completely consumed STRNOTATMARK will be set.
7315 	 */
7316 	mark = bp->b_flag & (MSGMARK | MSGMARKNEXT | MSGNOTMARKNEXT);
7317 	ASSERT((mark & (MSGMARKNEXT|MSGNOTMARKNEXT)) !=
7318 	    (MSGMARKNEXT|MSGNOTMARKNEXT));
7319 	pri = bp->b_band;
7320 	if (mark != 0) {
7321 		/*
7322 		 * If the caller doesn't want the mark return.
7323 		 * Used to implement MSG_WAITALL in sockets.
7324 		 */
7325 		if (flags & MSG_NOMARK) {
7326 			putback(stp, q, bp, pri);
7327 			qbackenable(q, pri);
7328 			mutex_exit(&stp->sd_lock);
7329 			return (EWOULDBLOCK);
7330 		}
7331 		if (bp == stp->sd_mark) {
7332 			mark |= _LASTMARK;
7333 			stp->sd_mark = NULL;
7334 		}
7335 	}
7336 
7337 	/*
7338 	 * keep track of the first message type
7339 	 */
7340 	type = bp->b_datap->db_type;
7341 
7342 	if (bp->b_datap->db_type == M_PASSFP) {
7343 		if ((mark & _LASTMARK) && (stp->sd_mark == NULL))
7344 			stp->sd_mark = bp;
7345 		bp->b_flag |= mark & ~_LASTMARK;
7346 		putback(stp, q, bp, pri);
7347 		qbackenable(q, pri);
7348 		mutex_exit(&stp->sd_lock);
7349 		return (EBADMSG);
7350 	}
7351 	ASSERT(type != M_SIG);
7352 
7353 	if (flags & MSG_IPEEK) {
7354 		/*
7355 		 * Clear any struioflag - we do the uiomove over again
7356 		 * when peeking since it simplifies the code.
7357 		 *
7358 		 * Dup the message and put the original back on the queue.
7359 		 * If dupmsg() fails, try again with copymsg() to see if
7360 		 * there is indeed a shortage of memory.  dupmsg() may fail
7361 		 * if db_ref in any of the messages reaches its limit.
7362 		 */
7363 		if ((nbp = dupmsg(bp)) == NULL && (nbp = copymsg(bp)) == NULL) {
7364 			/*
7365 			 * Restore the state of the stream head since we
7366 			 * need to drop sd_lock (strwaitbuf is sleeping).
7367 			 */
7368 			size_t size = msgdsize(bp);
7369 
7370 			if ((mark & _LASTMARK) && (stp->sd_mark == NULL))
7371 				stp->sd_mark = bp;
7372 			bp->b_flag |= mark & ~_LASTMARK;
7373 			putback(stp, q, bp, pri);
7374 			mutex_exit(&stp->sd_lock);
7375 			error = strwaitbuf(size, BPRI_HI);
7376 			if (error) {
7377 				/*
7378 				 * There is no net change to the queue thus
7379 				 * no need to qbackenable.
7380 				 */
7381 				return (error);
7382 			}
7383 			goto retry;
7384 		}
7385 
7386 		if ((mark & _LASTMARK) && (stp->sd_mark == NULL))
7387 			stp->sd_mark = bp;
7388 		bp->b_flag |= mark & ~_LASTMARK;
7389 		putback(stp, q, bp, pri);
7390 		bp = nbp;
7391 	}
7392 
7393 	/*
7394 	 * Set this flag so strrput will not generate signals. Need to
7395 	 * make sure this flag is cleared before leaving this routine
7396 	 * else signals will stop being sent.
7397 	 */
7398 	stp->sd_flag |= STRGETINPROG;
7399 	mutex_exit(&stp->sd_lock);
7400 
7401 	if ((stp->sd_rputdatafunc != NULL) && (DB_TYPE(bp) == M_DATA)) {
7402 		mblk_t *tmp, *prevmp;
7403 
7404 		/*
7405 		 * Put first non-data mblk back to stream head and
7406 		 * cut the mblk chain so sd_rputdatafunc only sees
7407 		 * M_DATA mblks. We can skip the first mblk since it
7408 		 * is M_DATA according to the condition above.
7409 		 */
7410 		for (prevmp = bp, tmp = bp->b_cont; tmp != NULL;
7411 		    prevmp = tmp, tmp = tmp->b_cont) {
7412 			if (DB_TYPE(tmp) != M_DATA) {
7413 				prevmp->b_cont = NULL;
7414 				mutex_enter(&stp->sd_lock);
7415 				putback(stp, q, tmp, tmp->b_band);
7416 				mutex_exit(&stp->sd_lock);
7417 				break;
7418 			}
7419 		}
7420 
7421 		bp = (stp->sd_rputdatafunc)(stp->sd_vnode, bp,
7422 		    NULL, NULL, NULL, NULL);
7423 
7424 		if (bp == NULL)
7425 			goto retry;
7426 	}
7427 
7428 	if (STREAM_NEEDSERVICE(stp))
7429 		stream_runservice(stp);
7430 
7431 	/*
7432 	 * Set HIPRI flag if message is priority.
7433 	 */
7434 	if (type >= QPCTL)
7435 		flg = MSG_HIPRI;
7436 	else
7437 		flg = MSG_BAND;
7438 
7439 	/*
7440 	 * First process PROTO or PCPROTO blocks, if any.
7441 	 */
7442 	if (mctlp != NULL && type != M_DATA) {
7443 		mblk_t *nbp;
7444 
7445 		*mctlp = bp;
7446 		while (bp->b_cont && bp->b_cont->b_datap->db_type != M_DATA)
7447 			bp = bp->b_cont;
7448 		nbp = bp->b_cont;
7449 		bp->b_cont = NULL;
7450 		bp = nbp;
7451 	}
7452 
7453 	if (bp && bp->b_datap->db_type != M_DATA) {
7454 		/*
7455 		 * More PROTO blocks in msg. Will only happen if mctlp is NULL.
7456 		 */
7457 		more |= MORECTL;
7458 		savemp = bp;
7459 		while (bp && bp->b_datap->db_type != M_DATA) {
7460 			savemptail = bp;
7461 			bp = bp->b_cont;
7462 		}
7463 		savemptail->b_cont = NULL;
7464 	}
7465 
7466 	/*
7467 	 * Now process DATA blocks, if any.
7468 	 */
7469 	if (uiop == NULL) {
7470 		/* Append data to tail of mctlp */
7471 		if (mctlp != NULL) {
7472 			mblk_t **mpp = mctlp;
7473 
7474 			while (*mpp != NULL)
7475 				mpp = &((*mpp)->b_cont);
7476 			*mpp = bp;
7477 			bp = NULL;
7478 		}
7479 	} else if (uiop->uio_resid >= 0 && bp) {
7480 		size_t oldresid = uiop->uio_resid;
7481 
7482 		/*
7483 		 * If a streams message is likely to consist
7484 		 * of many small mblks, it is pulled up into
7485 		 * one continuous chunk of memory.
7486 		 * see longer comment at top of page
7487 		 * by mblk_pull_len declaration.
7488 		 */
7489 
7490 		if (MBLKL(bp) < mblk_pull_len) {
7491 			(void) pullupmsg(bp, -1);
7492 		}
7493 
7494 		bp = struiocopyout(bp, uiop, &error);
7495 		if (error != 0) {
7496 			if (mctlp != NULL) {
7497 				freemsg(*mctlp);
7498 				*mctlp = NULL;
7499 			} else
7500 				freemsg(savemp);
7501 			mutex_enter(&stp->sd_lock);
7502 			/*
7503 			 * clear stream head hi pri flag based on
7504 			 * first message
7505 			 */
7506 			if (!(flags & MSG_IPEEK) && (type >= QPCTL)) {
7507 				ASSERT(type == M_PCPROTO);
7508 				stp->sd_flag &= ~STRPRI;
7509 			}
7510 			more = 0;
7511 			goto getmout;
7512 		}
7513 		/*
7514 		 * (pr == 1) indicates a partial read.
7515 		 */
7516 		if (oldresid > uiop->uio_resid)
7517 			pr = 1;
7518 	}
7519 
7520 	if (bp) {			/* more data blocks in msg */
7521 		more |= MOREDATA;
7522 		if (savemp)
7523 			savemptail->b_cont = bp;
7524 		else
7525 			savemp = bp;
7526 	}
7527 
7528 	mutex_enter(&stp->sd_lock);
7529 	if (savemp) {
7530 		if (flags & (MSG_IPEEK|MSG_DISCARDTAIL)) {
7531 			/*
7532 			 * When MSG_DISCARDTAIL is set or
7533 			 * when peeking discard any tail. When peeking this
7534 			 * is the tail of the dup that was copied out - the
7535 			 * message has already been putback on the queue.
7536 			 * Return MOREDATA to the caller even though the data
7537 			 * is discarded. This is used by sockets (to
7538 			 * set MSG_TRUNC).
7539 			 */
7540 			freemsg(savemp);
7541 			if (!(flags & MSG_IPEEK) && (type >= QPCTL)) {
7542 				ASSERT(type == M_PCPROTO);
7543 				stp->sd_flag &= ~STRPRI;
7544 			}
7545 		} else if (pr && (savemp->b_datap->db_type == M_DATA) &&
7546 		    msgnodata(savemp)) {
7547 			/*
7548 			 * Avoid queuing a zero-length tail part of
7549 			 * a message. pr=1 indicates that we read some of
7550 			 * the message.
7551 			 */
7552 			freemsg(savemp);
7553 			more &= ~MOREDATA;
7554 			if (type >= QPCTL) {
7555 				ASSERT(type == M_PCPROTO);
7556 				stp->sd_flag &= ~STRPRI;
7557 			}
7558 		} else {
7559 			savemp->b_band = pri;
7560 			/*
7561 			 * If the first message was HIPRI and the one we're
7562 			 * putting back isn't, then clear STRPRI, otherwise
7563 			 * set STRPRI again.  Note that we must set STRPRI
7564 			 * again since the flush logic in strrput_nondata()
7565 			 * may have cleared it while we had sd_lock dropped.
7566 			 */
7567 			if (type >= QPCTL) {
7568 				ASSERT(type == M_PCPROTO);
7569 				if (queclass(savemp) < QPCTL)
7570 					stp->sd_flag &= ~STRPRI;
7571 				else
7572 					stp->sd_flag |= STRPRI;
7573 			} else if (queclass(savemp) >= QPCTL) {
7574 				/*
7575 				 * The first message was not a HIPRI message,
7576 				 * but the one we are about to putback is.
7577 				 * For simplicitly, we do not allow for HIPRI
7578 				 * messages to be embedded in the message
7579 				 * body, so just force it to same type as
7580 				 * first message.
7581 				 */
7582 				ASSERT(type == M_DATA || type == M_PROTO);
7583 				ASSERT(savemp->b_datap->db_type == M_PCPROTO);
7584 				savemp->b_datap->db_type = type;
7585 			}
7586 			if (mark != 0) {
7587 				if ((mark & _LASTMARK) &&
7588 				    (stp->sd_mark == NULL)) {
7589 					/*
7590 					 * If another marked message arrived
7591 					 * while sd_lock was not held sd_mark
7592 					 * would be non-NULL.
7593 					 */
7594 					stp->sd_mark = savemp;
7595 				}
7596 				savemp->b_flag |= mark & ~_LASTMARK;
7597 			}
7598 			putback(stp, q, savemp, pri);
7599 		}
7600 	} else if (!(flags & MSG_IPEEK)) {
7601 		/*
7602 		 * The complete message was consumed.
7603 		 *
7604 		 * If another M_PCPROTO arrived while sd_lock was not held
7605 		 * it would have been discarded since STRPRI was still set.
7606 		 *
7607 		 * Move the MSG*MARKNEXT information
7608 		 * to the stream head just in case
7609 		 * the read queue becomes empty.
7610 		 * clear stream head hi pri flag based on
7611 		 * first message
7612 		 *
7613 		 * If the stream head was at the mark
7614 		 * (STRATMARK) before we dropped sd_lock above
7615 		 * and some data was consumed then we have
7616 		 * moved past the mark thus STRATMARK is
7617 		 * cleared. However, if a message arrived in
7618 		 * strrput during the copyout above causing
7619 		 * STRATMARK to be set we can not clear that
7620 		 * flag.
7621 		 * XXX A "perimeter" would help by single-threading strrput,
7622 		 * strread, strgetmsg and kstrgetmsg.
7623 		 */
7624 		if (type >= QPCTL) {
7625 			ASSERT(type == M_PCPROTO);
7626 			stp->sd_flag &= ~STRPRI;
7627 		}
7628 		if (mark & (MSGMARKNEXT|MSGNOTMARKNEXT|MSGMARK)) {
7629 			if (mark & MSGMARKNEXT) {
7630 				stp->sd_flag &= ~STRNOTATMARK;
7631 				stp->sd_flag |= STRATMARK;
7632 			} else if (mark & MSGNOTMARKNEXT) {
7633 				stp->sd_flag &= ~STRATMARK;
7634 				stp->sd_flag |= STRNOTATMARK;
7635 			} else {
7636 				stp->sd_flag &= ~(STRATMARK|STRNOTATMARK);
7637 			}
7638 		} else if (pr && (old_sd_flag & STRATMARK)) {
7639 			stp->sd_flag &= ~STRATMARK;
7640 		}
7641 	}
7642 
7643 	*flagsp = flg;
7644 	*prip = pri;
7645 
7646 	/*
7647 	 * Getmsg cleanup processing - if the state of the queue has changed
7648 	 * some signals may need to be sent and/or poll awakened.
7649 	 */
7650 getmout:
7651 	qbackenable(q, pri);
7652 
7653 	/*
7654 	 * We dropped the stream head lock above. Send all M_SIG messages
7655 	 * before processing stream head for SIGPOLL messages.
7656 	 */
7657 	ASSERT(MUTEX_HELD(&stp->sd_lock));
7658 	while ((bp = q->q_first) != NULL &&
7659 	    (bp->b_datap->db_type == M_SIG)) {
7660 		/*
7661 		 * sd_lock is held so the content of the read queue can not
7662 		 * change.
7663 		 */
7664 		bp = getq(q);
7665 		ASSERT(bp != NULL && bp->b_datap->db_type == M_SIG);
7666 
7667 		strsignal_nolock(stp, *bp->b_rptr, (int32_t)bp->b_band);
7668 		mutex_exit(&stp->sd_lock);
7669 		freemsg(bp);
7670 		if (STREAM_NEEDSERVICE(stp))
7671 			stream_runservice(stp);
7672 		mutex_enter(&stp->sd_lock);
7673 	}
7674 
7675 	/*
7676 	 * stream head cannot change while we make the determination
7677 	 * whether or not to send a signal. Drop the flag to allow strrput
7678 	 * to send firstmsgsigs again.
7679 	 */
7680 	stp->sd_flag &= ~STRGETINPROG;
7681 
7682 	/*
7683 	 * If the type of message at the front of the queue changed
7684 	 * due to the receive the appropriate signals and pollwakeup events
7685 	 * are generated. The type of changes are:
7686 	 *	Processed a hipri message, q_first is not hipri.
7687 	 *	Processed a band X message, and q_first is band Y.
7688 	 * The generated signals and pollwakeups are identical to what
7689 	 * strrput() generates should the message that is now on q_first
7690 	 * arrive to an empty read queue.
7691 	 *
7692 	 * Note: only strrput will send a signal for a hipri message.
7693 	 */
7694 	if ((bp = q->q_first) != NULL && !(stp->sd_flag & STRPRI)) {
7695 		strsigset_t signals = 0;
7696 		strpollset_t pollwakeups = 0;
7697 
7698 		if (flg & MSG_HIPRI) {
7699 			/*
7700 			 * Removed a hipri message. Regular data at
7701 			 * the front of  the queue.
7702 			 */
7703 			if (bp->b_band == 0) {
7704 				signals = S_INPUT | S_RDNORM;
7705 				pollwakeups = POLLIN | POLLRDNORM;
7706 			} else {
7707 				signals = S_INPUT | S_RDBAND;
7708 				pollwakeups = POLLIN | POLLRDBAND;
7709 			}
7710 		} else if (pri != bp->b_band) {
7711 			/*
7712 			 * The band is different for the new q_first.
7713 			 */
7714 			if (bp->b_band == 0) {
7715 				signals = S_RDNORM;
7716 				pollwakeups = POLLIN | POLLRDNORM;
7717 			} else {
7718 				signals = S_RDBAND;
7719 				pollwakeups = POLLIN | POLLRDBAND;
7720 			}
7721 		}
7722 
7723 		if (pollwakeups != 0) {
7724 			if (pollwakeups == (POLLIN | POLLRDNORM)) {
7725 				if (!(stp->sd_rput_opt & SR_POLLIN))
7726 					goto no_pollwake;
7727 				stp->sd_rput_opt &= ~SR_POLLIN;
7728 			}
7729 			mutex_exit(&stp->sd_lock);
7730 			pollwakeup(&stp->sd_pollist, pollwakeups);
7731 			mutex_enter(&stp->sd_lock);
7732 		}
7733 no_pollwake:
7734 
7735 		if (stp->sd_sigflags & signals)
7736 			strsendsig(stp->sd_siglist, signals, bp->b_band, 0);
7737 	}
7738 	mutex_exit(&stp->sd_lock);
7739 
7740 	rvp->r_val1 = more;
7741 	return (error);
7742 #undef	_LASTMARK
7743 }
7744 
7745 /*
7746  * Put a message downstream.
7747  *
7748  * NOTE: strputmsg and kstrputmsg have much of the logic in common.
7749  */
7750 int
7751 strputmsg(
7752 	struct vnode *vp,
7753 	struct strbuf *mctl,
7754 	struct strbuf *mdata,
7755 	unsigned char pri,
7756 	int flag,
7757 	int fmode)
7758 {
7759 	struct stdata *stp;
7760 	queue_t *wqp;
7761 	mblk_t *mp;
7762 	ssize_t msgsize;
7763 	ssize_t rmin, rmax;
7764 	int error;
7765 	struct uio uios;
7766 	struct uio *uiop = &uios;
7767 	struct iovec iovs;
7768 	int xpg4 = 0;
7769 
7770 	ASSERT(vp->v_stream);
7771 	stp = vp->v_stream;
7772 	wqp = stp->sd_wrq;
7773 
7774 	/*
7775 	 * If it is an XPG4 application, we need to send
7776 	 * SIGPIPE below
7777 	 */
7778 
7779 	xpg4 = (flag & MSG_XPG4) ? 1 : 0;
7780 	flag &= ~MSG_XPG4;
7781 
7782 	if (audit_active)
7783 		audit_strputmsg(vp, mctl, mdata, pri, flag, fmode);
7784 
7785 	mutex_enter(&stp->sd_lock);
7786 
7787 	if ((error = i_straccess(stp, JCWRITE)) != 0) {
7788 		mutex_exit(&stp->sd_lock);
7789 		return (error);
7790 	}
7791 
7792 	if (stp->sd_flag & (STWRERR|STRHUP|STPLEX)) {
7793 		error = strwriteable(stp, B_FALSE, xpg4);
7794 		if (error != 0) {
7795 			mutex_exit(&stp->sd_lock);
7796 			return (error);
7797 		}
7798 	}
7799 
7800 	mutex_exit(&stp->sd_lock);
7801 
7802 	/*
7803 	 * Check for legal flag value.
7804 	 */
7805 	switch (flag) {
7806 	case MSG_HIPRI:
7807 		if ((mctl->len < 0) || (pri != 0))
7808 			return (EINVAL);
7809 		break;
7810 	case MSG_BAND:
7811 		break;
7812 
7813 	default:
7814 		return (EINVAL);
7815 	}
7816 
7817 	TRACE_1(TR_FAC_STREAMS_FR, TR_STRPUTMSG_IN,
7818 	    "strputmsg in:stp %p", stp);
7819 
7820 	/* get these values from those cached in the stream head */
7821 	rmin = stp->sd_qn_minpsz;
7822 	rmax = stp->sd_qn_maxpsz;
7823 
7824 	/*
7825 	 * Make sure ctl and data sizes together fall within the
7826 	 * limits of the max and min receive packet sizes and do
7827 	 * not exceed system limit.
7828 	 */
7829 	ASSERT((rmax >= 0) || (rmax == INFPSZ));
7830 	if (rmax == 0) {
7831 		return (ERANGE);
7832 	}
7833 	/*
7834 	 * Use the MAXIMUM of sd_maxblk and q_maxpsz.
7835 	 * Needed to prevent partial failures in the strmakedata loop.
7836 	 */
7837 	if (stp->sd_maxblk != INFPSZ && rmax != INFPSZ && rmax < stp->sd_maxblk)
7838 		rmax = stp->sd_maxblk;
7839 
7840 	if ((msgsize = mdata->len) < 0) {
7841 		msgsize = 0;
7842 		rmin = 0;	/* no range check for NULL data part */
7843 	}
7844 	if ((msgsize < rmin) ||
7845 	    ((msgsize > rmax) && (rmax != INFPSZ)) ||
7846 	    (mctl->len > strctlsz)) {
7847 		return (ERANGE);
7848 	}
7849 
7850 	/*
7851 	 * Setup uio and iov for data part
7852 	 */
7853 	iovs.iov_base = mdata->buf;
7854 	iovs.iov_len = msgsize;
7855 	uios.uio_iov = &iovs;
7856 	uios.uio_iovcnt = 1;
7857 	uios.uio_loffset = 0;
7858 	uios.uio_segflg = UIO_USERSPACE;
7859 	uios.uio_fmode = fmode;
7860 	uios.uio_extflg = UIO_COPY_DEFAULT;
7861 	uios.uio_resid = msgsize;
7862 	uios.uio_offset = 0;
7863 
7864 	/* Ignore flow control in strput for HIPRI */
7865 	if (flag & MSG_HIPRI)
7866 		flag |= MSG_IGNFLOW;
7867 
7868 	for (;;) {
7869 		int done = 0;
7870 
7871 		/*
7872 		 * strput will always free the ctl mblk - even when strput
7873 		 * fails.
7874 		 */
7875 		if ((error = strmakectl(mctl, flag, fmode, &mp)) != 0) {
7876 			TRACE_3(TR_FAC_STREAMS_FR, TR_STRPUTMSG_OUT,
7877 			    "strputmsg out:stp %p out %d error %d",
7878 			    stp, 1, error);
7879 			return (error);
7880 		}
7881 		/*
7882 		 * Verify that the whole message can be transferred by
7883 		 * strput.
7884 		 */
7885 		ASSERT(stp->sd_maxblk == INFPSZ ||
7886 		    stp->sd_maxblk >= mdata->len);
7887 
7888 		msgsize = mdata->len;
7889 		error = strput(stp, mp, uiop, &msgsize, 0, pri, flag);
7890 		mdata->len = msgsize;
7891 
7892 		if (error == 0)
7893 			break;
7894 
7895 		if (error != EWOULDBLOCK)
7896 			goto out;
7897 
7898 		mutex_enter(&stp->sd_lock);
7899 		/*
7900 		 * Check for a missed wakeup.
7901 		 * Needed since strput did not hold sd_lock across
7902 		 * the canputnext.
7903 		 */
7904 		if (bcanputnext(wqp, pri)) {
7905 			/* Try again */
7906 			mutex_exit(&stp->sd_lock);
7907 			continue;
7908 		}
7909 		TRACE_2(TR_FAC_STREAMS_FR, TR_STRPUTMSG_WAIT,
7910 		    "strputmsg wait:stp %p waits pri %d", stp, pri);
7911 		if (((error = strwaitq(stp, WRITEWAIT, (ssize_t)0, fmode, -1,
7912 		    &done)) != 0) || done) {
7913 			mutex_exit(&stp->sd_lock);
7914 			TRACE_3(TR_FAC_STREAMS_FR, TR_STRPUTMSG_OUT,
7915 			    "strputmsg out:q %p out %d error %d",
7916 			    stp, 0, error);
7917 			return (error);
7918 		}
7919 		TRACE_1(TR_FAC_STREAMS_FR, TR_STRPUTMSG_WAKE,
7920 		    "strputmsg wake:stp %p wakes", stp);
7921 		if ((error = i_straccess(stp, JCWRITE)) != 0) {
7922 			mutex_exit(&stp->sd_lock);
7923 			return (error);
7924 		}
7925 		mutex_exit(&stp->sd_lock);
7926 	}
7927 out:
7928 	/*
7929 	 * For historic reasons, applications expect EAGAIN
7930 	 * when data mblk could not be allocated. so change
7931 	 * ENOMEM back to EAGAIN
7932 	 */
7933 	if (error == ENOMEM)
7934 		error = EAGAIN;
7935 	TRACE_3(TR_FAC_STREAMS_FR, TR_STRPUTMSG_OUT,
7936 	    "strputmsg out:stp %p out %d error %d", stp, 2, error);
7937 	return (error);
7938 }
7939 
7940 /*
7941  * Put a message downstream.
7942  * Can send only an M_PROTO/M_PCPROTO by passing in a NULL uiop.
7943  * The fmode flag (NDELAY, NONBLOCK) is the or of the flags in the uio
7944  * and the fmode parameter.
7945  *
7946  * This routine handles the consolidation private flags:
7947  *	MSG_IGNERROR	Ignore any stream head error except STPLEX.
7948  *	MSG_HOLDSIG	Hold signals while waiting for data.
7949  *	MSG_IGNFLOW	Don't check streams flow control.
7950  *
7951  * NOTE: strputmsg and kstrputmsg have much of the logic in common.
7952  */
7953 int
7954 kstrputmsg(
7955 	struct vnode *vp,
7956 	mblk_t *mctl,
7957 	struct uio *uiop,
7958 	ssize_t msgsize,
7959 	unsigned char pri,
7960 	int flag,
7961 	int fmode)
7962 {
7963 	struct stdata *stp;
7964 	queue_t *wqp;
7965 	ssize_t rmin, rmax;
7966 	int error;
7967 
7968 	ASSERT(vp->v_stream);
7969 	stp = vp->v_stream;
7970 	wqp = stp->sd_wrq;
7971 	if (audit_active)
7972 		audit_strputmsg(vp, NULL, NULL, pri, flag, fmode);
7973 	if (mctl == NULL)
7974 		return (EINVAL);
7975 
7976 	mutex_enter(&stp->sd_lock);
7977 
7978 	if ((error = i_straccess(stp, JCWRITE)) != 0) {
7979 		mutex_exit(&stp->sd_lock);
7980 		freemsg(mctl);
7981 		return (error);
7982 	}
7983 
7984 	if ((stp->sd_flag & STPLEX) || !(flag & MSG_IGNERROR)) {
7985 		if (stp->sd_flag & (STWRERR|STRHUP|STPLEX)) {
7986 			error = strwriteable(stp, B_FALSE, B_TRUE);
7987 			if (error != 0) {
7988 				mutex_exit(&stp->sd_lock);
7989 				freemsg(mctl);
7990 				return (error);
7991 			}
7992 		}
7993 	}
7994 
7995 	mutex_exit(&stp->sd_lock);
7996 
7997 	/*
7998 	 * Check for legal flag value.
7999 	 */
8000 	switch (flag & (MSG_HIPRI|MSG_BAND|MSG_ANY)) {
8001 	case MSG_HIPRI:
8002 		if (pri != 0) {
8003 			freemsg(mctl);
8004 			return (EINVAL);
8005 		}
8006 		break;
8007 	case MSG_BAND:
8008 		break;
8009 	default:
8010 		freemsg(mctl);
8011 		return (EINVAL);
8012 	}
8013 
8014 	TRACE_1(TR_FAC_STREAMS_FR, TR_KSTRPUTMSG_IN,
8015 	    "kstrputmsg in:stp %p", stp);
8016 
8017 	/* get these values from those cached in the stream head */
8018 	rmin = stp->sd_qn_minpsz;
8019 	rmax = stp->sd_qn_maxpsz;
8020 
8021 	/*
8022 	 * Make sure ctl and data sizes together fall within the
8023 	 * limits of the max and min receive packet sizes and do
8024 	 * not exceed system limit.
8025 	 */
8026 	ASSERT((rmax >= 0) || (rmax == INFPSZ));
8027 	if (rmax == 0) {
8028 		freemsg(mctl);
8029 		return (ERANGE);
8030 	}
8031 	/*
8032 	 * Use the MAXIMUM of sd_maxblk and q_maxpsz.
8033 	 * Needed to prevent partial failures in the strmakedata loop.
8034 	 */
8035 	if (stp->sd_maxblk != INFPSZ && rmax != INFPSZ && rmax < stp->sd_maxblk)
8036 		rmax = stp->sd_maxblk;
8037 
8038 	if (uiop == NULL) {
8039 		msgsize = -1;
8040 		rmin = -1;	/* no range check for NULL data part */
8041 	} else {
8042 		/* Use uio flags as well as the fmode parameter flags */
8043 		fmode |= uiop->uio_fmode;
8044 
8045 		if ((msgsize < rmin) ||
8046 		    ((msgsize > rmax) && (rmax != INFPSZ))) {
8047 			freemsg(mctl);
8048 			return (ERANGE);
8049 		}
8050 	}
8051 
8052 	/* Ignore flow control in strput for HIPRI */
8053 	if (flag & MSG_HIPRI)
8054 		flag |= MSG_IGNFLOW;
8055 
8056 	for (;;) {
8057 		int done = 0;
8058 		int waitflag;
8059 		mblk_t *mp;
8060 
8061 		/*
8062 		 * strput will always free the ctl mblk - even when strput
8063 		 * fails. If MSG_IGNFLOW is set then any error returned
8064 		 * will cause us to break the loop, so we don't need a copy
8065 		 * of the message. If MSG_IGNFLOW is not set, then we can
8066 		 * get hit by flow control and be forced to try again. In
8067 		 * this case we need to have a copy of the message. We
8068 		 * do this using copymsg since the message may get modified
8069 		 * by something below us.
8070 		 *
8071 		 * We've observed that many TPI providers do not check db_ref
8072 		 * on the control messages but blindly reuse them for the
8073 		 * T_OK_ACK/T_ERROR_ACK. Thus using copymsg is more
8074 		 * friendly to such providers than using dupmsg. Also, note
8075 		 * that sockfs uses MSG_IGNFLOW for all TPI control messages.
8076 		 * Only data messages are subject to flow control, hence
8077 		 * subject to this copymsg.
8078 		 */
8079 		if (flag & MSG_IGNFLOW) {
8080 			mp = mctl;
8081 			mctl = NULL;
8082 		} else {
8083 			do {
8084 				/*
8085 				 * If a message has a free pointer, the message
8086 				 * must be dupmsg to maintain this pointer.
8087 				 * Code using this facility must be sure
8088 				 * that modules below will not change the
8089 				 * contents of the dblk without checking db_ref
8090 				 * first. If db_ref is > 1, then the module
8091 				 * needs to do a copymsg first. Otherwise,
8092 				 * the contents of the dblk may become
8093 				 * inconsistent because the freesmg/freeb below
8094 				 * may end up calling atomic_add_32_nv.
8095 				 * The atomic_add_32_nv in freeb (accessing
8096 				 * all of db_ref, db_type, db_flags, and
8097 				 * db_struioflag) does not prevent other threads
8098 				 * from concurrently trying to modify e.g.
8099 				 * db_type.
8100 				 */
8101 				if (mctl->b_datap->db_frtnp != NULL)
8102 					mp = dupmsg(mctl);
8103 				else
8104 					mp = copymsg(mctl);
8105 
8106 				if (mp != NULL)
8107 					break;
8108 
8109 				error = strwaitbuf(msgdsize(mctl), BPRI_MED);
8110 				if (error) {
8111 					freemsg(mctl);
8112 					return (error);
8113 				}
8114 			} while (mp == NULL);
8115 		}
8116 		/*
8117 		 * Verify that all of msgsize can be transferred by
8118 		 * strput.
8119 		 */
8120 		ASSERT(stp->sd_maxblk == INFPSZ || stp->sd_maxblk >= msgsize);
8121 		error = strput(stp, mp, uiop, &msgsize, 0, pri, flag);
8122 		if (error == 0)
8123 			break;
8124 
8125 		if (error != EWOULDBLOCK)
8126 			goto out;
8127 
8128 		/*
8129 		 * IF MSG_IGNFLOW is set we should have broken out of loop
8130 		 * above.
8131 		 */
8132 		ASSERT(!(flag & MSG_IGNFLOW));
8133 		mutex_enter(&stp->sd_lock);
8134 		/*
8135 		 * Check for a missed wakeup.
8136 		 * Needed since strput did not hold sd_lock across
8137 		 * the canputnext.
8138 		 */
8139 		if (bcanputnext(wqp, pri)) {
8140 			/* Try again */
8141 			mutex_exit(&stp->sd_lock);
8142 			continue;
8143 		}
8144 		TRACE_2(TR_FAC_STREAMS_FR, TR_KSTRPUTMSG_WAIT,
8145 		    "kstrputmsg wait:stp %p waits pri %d", stp, pri);
8146 
8147 		waitflag = WRITEWAIT;
8148 		if (flag & (MSG_HOLDSIG|MSG_IGNERROR)) {
8149 			if (flag & MSG_HOLDSIG)
8150 				waitflag |= STR_NOSIG;
8151 			if (flag & MSG_IGNERROR)
8152 				waitflag |= STR_NOERROR;
8153 		}
8154 		if (((error = strwaitq(stp, waitflag,
8155 		    (ssize_t)0, fmode, -1, &done)) != 0) || done) {
8156 			mutex_exit(&stp->sd_lock);
8157 			TRACE_3(TR_FAC_STREAMS_FR, TR_KSTRPUTMSG_OUT,
8158 			    "kstrputmsg out:stp %p out %d error %d",
8159 			    stp, 0, error);
8160 			freemsg(mctl);
8161 			return (error);
8162 		}
8163 		TRACE_1(TR_FAC_STREAMS_FR, TR_KSTRPUTMSG_WAKE,
8164 		    "kstrputmsg wake:stp %p wakes", stp);
8165 		if ((error = i_straccess(stp, JCWRITE)) != 0) {
8166 			mutex_exit(&stp->sd_lock);
8167 			freemsg(mctl);
8168 			return (error);
8169 		}
8170 		mutex_exit(&stp->sd_lock);
8171 	}
8172 out:
8173 	freemsg(mctl);
8174 	/*
8175 	 * For historic reasons, applications expect EAGAIN
8176 	 * when data mblk could not be allocated. so change
8177 	 * ENOMEM back to EAGAIN
8178 	 */
8179 	if (error == ENOMEM)
8180 		error = EAGAIN;
8181 	TRACE_3(TR_FAC_STREAMS_FR, TR_KSTRPUTMSG_OUT,
8182 	    "kstrputmsg out:stp %p out %d error %d", stp, 2, error);
8183 	return (error);
8184 }
8185 
8186 /*
8187  * Determines whether the necessary conditions are set on a stream
8188  * for it to be readable, writeable, or have exceptions.
8189  *
8190  * strpoll handles the consolidation private events:
8191  *	POLLNOERR	Do not return POLLERR even if there are stream
8192  *			head errors.
8193  *			Used by sockfs.
8194  *	POLLRDDATA	Do not return POLLIN unless at least one message on
8195  *			the queue contains one or more M_DATA mblks. Thus
8196  *			when this flag is set a queue with only
8197  *			M_PROTO/M_PCPROTO mblks does not return POLLIN.
8198  *			Used by sockfs to ignore T_EXDATA_IND messages.
8199  *
8200  * Note: POLLRDDATA assumes that synch streams only return messages with
8201  * an M_DATA attached (i.e. not messages consisting of only
8202  * an M_PROTO/M_PCPROTO part).
8203  */
8204 int
8205 strpoll(
8206 	struct stdata *stp,
8207 	short events_arg,
8208 	int anyyet,
8209 	short *reventsp,
8210 	struct pollhead **phpp)
8211 {
8212 	int events = (ushort_t)events_arg;
8213 	int retevents = 0;
8214 	mblk_t *mp;
8215 	qband_t *qbp;
8216 	long sd_flags = stp->sd_flag;
8217 	int headlocked = 0;
8218 
8219 	/*
8220 	 * For performance, a single 'if' tests for most possible edge
8221 	 * conditions in one shot
8222 	 */
8223 	if (sd_flags & (STPLEX | STRDERR | STWRERR)) {
8224 		if (sd_flags & STPLEX) {
8225 			*reventsp = POLLNVAL;
8226 			return (EINVAL);
8227 		}
8228 		if (((events & (POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) &&
8229 		    (sd_flags & STRDERR)) ||
8230 		    ((events & (POLLOUT | POLLWRNORM | POLLWRBAND)) &&
8231 		    (sd_flags & STWRERR))) {
8232 			if (!(events & POLLNOERR)) {
8233 				*reventsp = POLLERR;
8234 				return (0);
8235 			}
8236 		}
8237 	}
8238 	if (sd_flags & STRHUP) {
8239 		retevents |= POLLHUP;
8240 	} else if (events & (POLLWRNORM | POLLWRBAND)) {
8241 		queue_t *tq;
8242 		queue_t	*qp = stp->sd_wrq;
8243 
8244 		claimstr(qp);
8245 		/* Find next module forward that has a service procedure */
8246 		tq = qp->q_next->q_nfsrv;
8247 		ASSERT(tq != NULL);
8248 
8249 		polllock(&stp->sd_pollist, QLOCK(tq));
8250 		if (events & POLLWRNORM) {
8251 			queue_t *sqp;
8252 
8253 			if (tq->q_flag & QFULL)
8254 				/* ensure backq svc procedure runs */
8255 				tq->q_flag |= QWANTW;
8256 			else if ((sqp = stp->sd_struiowrq) != NULL) {
8257 				/* Check sync stream barrier write q */
8258 				mutex_exit(QLOCK(tq));
8259 				polllock(&stp->sd_pollist, QLOCK(sqp));
8260 				if (sqp->q_flag & QFULL)
8261 					/* ensure pollwakeup() is done */
8262 					sqp->q_flag |= QWANTWSYNC;
8263 				else
8264 					retevents |= POLLOUT;
8265 				/* More write events to process ??? */
8266 				if (! (events & POLLWRBAND)) {
8267 					mutex_exit(QLOCK(sqp));
8268 					releasestr(qp);
8269 					goto chkrd;
8270 				}
8271 				mutex_exit(QLOCK(sqp));
8272 				polllock(&stp->sd_pollist, QLOCK(tq));
8273 			} else
8274 				retevents |= POLLOUT;
8275 		}
8276 		if (events & POLLWRBAND) {
8277 			qbp = tq->q_bandp;
8278 			if (qbp) {
8279 				while (qbp) {
8280 					if (qbp->qb_flag & QB_FULL)
8281 						qbp->qb_flag |= QB_WANTW;
8282 					else
8283 						retevents |= POLLWRBAND;
8284 					qbp = qbp->qb_next;
8285 				}
8286 			} else {
8287 				retevents |= POLLWRBAND;
8288 			}
8289 		}
8290 		mutex_exit(QLOCK(tq));
8291 		releasestr(qp);
8292 	}
8293 chkrd:
8294 	if (sd_flags & STRPRI) {
8295 		retevents |= (events & POLLPRI);
8296 	} else if (events & (POLLRDNORM | POLLRDBAND | POLLIN)) {
8297 		queue_t	*qp = _RD(stp->sd_wrq);
8298 		int normevents = (events & (POLLIN | POLLRDNORM));
8299 
8300 		/*
8301 		 * Note: Need to do polllock() here since ps_lock may be
8302 		 * held. See bug 4191544.
8303 		 */
8304 		polllock(&stp->sd_pollist, &stp->sd_lock);
8305 		headlocked = 1;
8306 		mp = qp->q_first;
8307 		while (mp) {
8308 			/*
8309 			 * For POLLRDDATA we scan b_cont and b_next until we
8310 			 * find an M_DATA.
8311 			 */
8312 			if ((events & POLLRDDATA) &&
8313 			    mp->b_datap->db_type != M_DATA) {
8314 				mblk_t *nmp = mp->b_cont;
8315 
8316 				while (nmp != NULL &&
8317 				    nmp->b_datap->db_type != M_DATA)
8318 					nmp = nmp->b_cont;
8319 				if (nmp == NULL) {
8320 					mp = mp->b_next;
8321 					continue;
8322 				}
8323 			}
8324 			if (mp->b_band == 0)
8325 				retevents |= normevents;
8326 			else
8327 				retevents |= (events & (POLLIN | POLLRDBAND));
8328 			break;
8329 		}
8330 		if (! (retevents & normevents) &&
8331 		    (stp->sd_wakeq & RSLEEP)) {
8332 			/*
8333 			 * Sync stream barrier read queue has data.
8334 			 */
8335 			retevents |= normevents;
8336 		}
8337 		/* Treat eof as normal data */
8338 		if (sd_flags & STREOF)
8339 			retevents |= normevents;
8340 	}
8341 
8342 	*reventsp = (short)retevents;
8343 	if (retevents) {
8344 		if (headlocked)
8345 			mutex_exit(&stp->sd_lock);
8346 		return (0);
8347 	}
8348 
8349 	/*
8350 	 * If poll() has not found any events yet, set up event cell
8351 	 * to wake up the poll if a requested event occurs on this
8352 	 * stream.  Check for collisions with outstanding poll requests.
8353 	 */
8354 	if (!anyyet) {
8355 		*phpp = &stp->sd_pollist;
8356 		if (headlocked == 0) {
8357 			polllock(&stp->sd_pollist, &stp->sd_lock);
8358 			headlocked = 1;
8359 		}
8360 		stp->sd_rput_opt |= SR_POLLIN;
8361 	}
8362 	if (headlocked)
8363 		mutex_exit(&stp->sd_lock);
8364 	return (0);
8365 }
8366 
8367 /*
8368  * The purpose of putback() is to assure sleeping polls/reads
8369  * are awakened when there are no new messages arriving at the,
8370  * stream head, and a message is placed back on the read queue.
8371  *
8372  * sd_lock must be held when messages are placed back on stream
8373  * head.  (getq() holds sd_lock when it removes messages from
8374  * the queue)
8375  */
8376 
8377 static void
8378 putback(struct stdata *stp, queue_t *q, mblk_t *bp, int band)
8379 {
8380 	mblk_t	*qfirst = q->q_first;
8381 	ASSERT(MUTEX_HELD(&stp->sd_lock));
8382 
8383 	if ((stp->sd_rput_opt & SR_CONSOL_DATA) &&
8384 	    (qfirst != NULL) &&
8385 	    (qfirst->b_datap->db_type == M_DATA) &&
8386 	    ((qfirst->b_flag & (MSGMARK|MSGDELIM)) == 0)) {
8387 		/*
8388 		 * We use the same logic as defined in strrput()
8389 		 * but in reverse as we are putting back onto the
8390 		 * queue and want to retain byte ordering.
8391 		 * Consolidate an M_DATA message onto an M_DATA,
8392 		 * M_PROTO, or M_PCPROTO by merging it with q_first.
8393 		 * The consolidation does not take place if the message
8394 		 * we are returning to the queue is marked with either
8395 		 * of the marks or the delim flag or if q_first
8396 		 * is marked with MSGMARK. The MSGMARK check is needed to
8397 		 * handle the odd semantics of MSGMARK where essentially
8398 		 * the whole message is to be treated as marked.
8399 		 * Carry any MSGMARKNEXT and MSGNOTMARKNEXT from q_first
8400 		 * to the front of the b_cont chain.
8401 		 */
8402 		unsigned char db_type = bp->b_datap->db_type;
8403 
8404 		if ((db_type == M_DATA || db_type == M_PROTO ||
8405 		    db_type == M_PCPROTO) &&
8406 		    !(bp->b_flag & (MSGMARK|MSGDELIM|MSGMARKNEXT))) {
8407 			rmvq_noenab(q, qfirst);
8408 			/*
8409 			 * The first message in the b_cont list
8410 			 * tracks MSGMARKNEXT and MSGNOTMARKNEXT.
8411 			 * We need to handle the case where we
8412 			 * are appending:
8413 			 *
8414 			 * 1) a MSGMARKNEXT to a MSGNOTMARKNEXT.
8415 			 * 2) a MSGMARKNEXT to a plain message.
8416 			 * 3) a MSGNOTMARKNEXT to a plain message
8417 			 * 4) a MSGNOTMARKNEXT to a MSGNOTMARKNEXT
8418 			 *    message.
8419 			 *
8420 			 * Thus we never append a MSGMARKNEXT or
8421 			 * MSGNOTMARKNEXT to a MSGMARKNEXT message.
8422 			 */
8423 			if (qfirst->b_flag & MSGMARKNEXT) {
8424 				bp->b_flag |= MSGMARKNEXT;
8425 				bp->b_flag &= ~MSGNOTMARKNEXT;
8426 				qfirst->b_flag &= ~MSGMARKNEXT;
8427 			} else if (qfirst->b_flag & MSGNOTMARKNEXT) {
8428 				bp->b_flag |= MSGNOTMARKNEXT;
8429 				qfirst->b_flag &= ~MSGNOTMARKNEXT;
8430 			}
8431 
8432 			linkb(bp, qfirst);
8433 		}
8434 	}
8435 	(void) putbq(q, bp);
8436 
8437 	/*
8438 	 * A message may have come in when the sd_lock was dropped in the
8439 	 * calling routine. If this is the case and STR*ATMARK info was
8440 	 * received, need to move that from the stream head to the q_last
8441 	 * so that SIOCATMARK can return the proper value.
8442 	 */
8443 	if (stp->sd_flag & (STRATMARK | STRNOTATMARK)) {
8444 		unsigned short *flagp = &q->q_last->b_flag;
8445 		uint_t b_flag = (uint_t)*flagp;
8446 
8447 		if (stp->sd_flag & STRATMARK) {
8448 			b_flag &= ~MSGNOTMARKNEXT;
8449 			b_flag |= MSGMARKNEXT;
8450 			stp->sd_flag &= ~STRATMARK;
8451 		} else {
8452 			b_flag &= ~MSGMARKNEXT;
8453 			b_flag |= MSGNOTMARKNEXT;
8454 			stp->sd_flag &= ~STRNOTATMARK;
8455 		}
8456 		*flagp = (unsigned short) b_flag;
8457 	}
8458 
8459 #ifdef	DEBUG
8460 	/*
8461 	 * Make sure that the flags are not messed up.
8462 	 */
8463 	{
8464 		mblk_t *mp;
8465 		mp = q->q_last;
8466 		while (mp != NULL) {
8467 			ASSERT((mp->b_flag & (MSGMARKNEXT|MSGNOTMARKNEXT)) !=
8468 			    (MSGMARKNEXT|MSGNOTMARKNEXT));
8469 			mp = mp->b_cont;
8470 		}
8471 	}
8472 #endif
8473 	if (q->q_first == bp) {
8474 		short pollevents;
8475 
8476 		if (stp->sd_flag & RSLEEP) {
8477 			stp->sd_flag &= ~RSLEEP;
8478 			cv_broadcast(&q->q_wait);
8479 		}
8480 		if (stp->sd_flag & STRPRI) {
8481 			pollevents = POLLPRI;
8482 		} else {
8483 			if (band == 0) {
8484 				if (!(stp->sd_rput_opt & SR_POLLIN))
8485 					return;
8486 				stp->sd_rput_opt &= ~SR_POLLIN;
8487 				pollevents = POLLIN | POLLRDNORM;
8488 			} else {
8489 				pollevents = POLLIN | POLLRDBAND;
8490 			}
8491 		}
8492 		mutex_exit(&stp->sd_lock);
8493 		pollwakeup(&stp->sd_pollist, pollevents);
8494 		mutex_enter(&stp->sd_lock);
8495 	}
8496 }
8497 
8498 /*
8499  * Return the held vnode attached to the stream head of a
8500  * given queue
8501  * It is the responsibility of the calling routine to ensure
8502  * that the queue does not go away (e.g. pop).
8503  */
8504 vnode_t *
8505 strq2vp(queue_t *qp)
8506 {
8507 	vnode_t *vp;
8508 	vp = STREAM(qp)->sd_vnode;
8509 	ASSERT(vp != NULL);
8510 	VN_HOLD(vp);
8511 	return (vp);
8512 }
8513 
8514 /*
8515  * return the stream head write queue for the given vp
8516  * It is the responsibility of the calling routine to ensure
8517  * that the stream or vnode do not close.
8518  */
8519 queue_t *
8520 strvp2wq(vnode_t *vp)
8521 {
8522 	ASSERT(vp->v_stream != NULL);
8523 	return (vp->v_stream->sd_wrq);
8524 }
8525 
8526 /*
8527  * pollwakeup stream head
8528  * It is the responsibility of the calling routine to ensure
8529  * that the stream or vnode do not close.
8530  */
8531 void
8532 strpollwakeup(vnode_t *vp, short event)
8533 {
8534 	ASSERT(vp->v_stream);
8535 	pollwakeup(&vp->v_stream->sd_pollist, event);
8536 }
8537 
8538 /*
8539  * Mate the stream heads of two vnodes together. If the two vnodes are the
8540  * same, we just make the write-side point at the read-side -- otherwise,
8541  * we do a full mate.  Only works on vnodes associated with streams that are
8542  * still being built and thus have only a stream head.
8543  */
8544 void
8545 strmate(vnode_t *vp1, vnode_t *vp2)
8546 {
8547 	queue_t *wrq1 = strvp2wq(vp1);
8548 	queue_t *wrq2 = strvp2wq(vp2);
8549 
8550 	/*
8551 	 * Verify that there are no modules on the stream yet.  We also
8552 	 * rely on the stream head always having a service procedure to
8553 	 * avoid tweaking q_nfsrv.
8554 	 */
8555 	ASSERT(wrq1->q_next == NULL && wrq2->q_next == NULL);
8556 	ASSERT(wrq1->q_qinfo->qi_srvp != NULL);
8557 	ASSERT(wrq2->q_qinfo->qi_srvp != NULL);
8558 
8559 	/*
8560 	 * If the queues are the same, just twist; otherwise do a full mate.
8561 	 */
8562 	if (wrq1 == wrq2) {
8563 		wrq1->q_next = _RD(wrq1);
8564 	} else {
8565 		wrq1->q_next = _RD(wrq2);
8566 		wrq2->q_next = _RD(wrq1);
8567 		STREAM(wrq1)->sd_mate = STREAM(wrq2);
8568 		STREAM(wrq1)->sd_flag |= STRMATE;
8569 		STREAM(wrq2)->sd_mate = STREAM(wrq1);
8570 		STREAM(wrq2)->sd_flag |= STRMATE;
8571 	}
8572 }
8573 
8574 /*
8575  * XXX will go away when console is correctly fixed.
8576  * Clean up the console PIDS, from previous I_SETSIG,
8577  * called only for cnopen which never calls strclean().
8578  */
8579 void
8580 str_cn_clean(struct vnode *vp)
8581 {
8582 	strsig_t *ssp, *pssp, *tssp;
8583 	struct stdata *stp;
8584 	struct pid  *pidp;
8585 	int update = 0;
8586 
8587 	ASSERT(vp->v_stream);
8588 	stp = vp->v_stream;
8589 	pssp = NULL;
8590 	mutex_enter(&stp->sd_lock);
8591 	ssp = stp->sd_siglist;
8592 	while (ssp) {
8593 		mutex_enter(&pidlock);
8594 		pidp = ssp->ss_pidp;
8595 		/*
8596 		 * Get rid of PID if the proc is gone.
8597 		 */
8598 		if (pidp->pid_prinactive) {
8599 			tssp = ssp->ss_next;
8600 			if (pssp)
8601 				pssp->ss_next = tssp;
8602 			else
8603 				stp->sd_siglist = tssp;
8604 			ASSERT(pidp->pid_ref <= 1);
8605 			PID_RELE(ssp->ss_pidp);
8606 			mutex_exit(&pidlock);
8607 			kmem_free(ssp, sizeof (strsig_t));
8608 			update = 1;
8609 			ssp = tssp;
8610 			continue;
8611 		} else
8612 			mutex_exit(&pidlock);
8613 		pssp = ssp;
8614 		ssp = ssp->ss_next;
8615 	}
8616 	if (update) {
8617 		stp->sd_sigflags = 0;
8618 		for (ssp = stp->sd_siglist; ssp; ssp = ssp->ss_next)
8619 			stp->sd_sigflags |= ssp->ss_events;
8620 	}
8621 	mutex_exit(&stp->sd_lock);
8622 }
8623 
8624 /*
8625  * Return B_TRUE if there is data in the message, B_FALSE otherwise.
8626  */
8627 static boolean_t
8628 msghasdata(mblk_t *bp)
8629 {
8630 	for (; bp; bp = bp->b_cont)
8631 		if (bp->b_datap->db_type == M_DATA) {
8632 			ASSERT(bp->b_wptr >= bp->b_rptr);
8633 			if (bp->b_wptr > bp->b_rptr)
8634 				return (B_TRUE);
8635 		}
8636 	return (B_FALSE);
8637 }
8638