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