xref: /titanic_51/usr/src/uts/common/fs/sockfs/socktpi.c (revision 7b840e52d558c34b70cbcde044d8d79852d169d2)
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 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/t_lock.h>
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/cred.h>
36 #include <sys/kmem.h>
37 #include <sys/sysmacros.h>
38 #include <sys/vfs.h>
39 #include <sys/vnode.h>
40 #include <sys/debug.h>
41 #include <sys/errno.h>
42 #include <sys/time.h>
43 #include <sys/file.h>
44 #include <sys/open.h>
45 #include <sys/user.h>
46 #include <sys/termios.h>
47 #include <sys/stream.h>
48 #include <sys/strsubr.h>
49 #include <sys/strsun.h>
50 #include <sys/ddi.h>
51 #include <sys/esunddi.h>
52 #include <sys/flock.h>
53 #include <sys/modctl.h>
54 #include <sys/vtrace.h>
55 #include <sys/cmn_err.h>
56 #include <sys/pathname.h>
57 
58 #include <sys/socket.h>
59 #include <sys/socketvar.h>
60 #include <sys/sockio.h>
61 #include <netinet/in.h>
62 #include <sys/un.h>
63 #include <sys/strsun.h>
64 
65 #include <sys/tiuser.h>
66 #define	_SUN_TPI_VERSION	2
67 #include <sys/tihdr.h>
68 #include <sys/timod.h>		/* TI_GETMYNAME, TI_GETPEERNAME */
69 
70 #include <c2/audit.h>
71 
72 #include <inet/common.h>
73 #include <inet/ip.h>
74 #include <inet/ip6.h>
75 #include <inet/tcp.h>
76 #include <inet/udp_impl.h>
77 
78 #include <sys/zone.h>
79 
80 #include <fs/sockfs/nl7c.h>
81 #include <fs/sockfs/nl7curi.h>
82 
83 #include <inet/kssl/ksslapi.h>
84 
85 /*
86  * Possible failures when memory can't be allocated. The documented behavior:
87  *
88  * 		5.5:			4.X:		XNET:
89  * accept:	ENOMEM/ENOSR/EINTR	- (EINTR)	ENOMEM/ENOBUFS/ENOSR/
90  *							EINTR
91  *	(4.X does not document EINTR but returns it)
92  * bind:	ENOSR			-		ENOBUFS/ENOSR
93  * connect: 	EINTR			EINTR		ENOBUFS/ENOSR/EINTR
94  * getpeername:	ENOMEM/ENOSR		ENOBUFS (-)	ENOBUFS/ENOSR
95  * getsockname:	ENOMEM/ENOSR		ENOBUFS (-)	ENOBUFS/ENOSR
96  *	(4.X getpeername and getsockname do not fail in practice)
97  * getsockopt:	ENOMEM/ENOSR		-		ENOBUFS/ENOSR
98  * listen:	-			-		ENOBUFS
99  * recv:	ENOMEM/ENOSR/EINTR	EINTR		ENOBUFS/ENOMEM/ENOSR/
100  *							EINTR
101  * send:	ENOMEM/ENOSR/EINTR	ENOBUFS/EINTR	ENOBUFS/ENOMEM/ENOSR/
102  *							EINTR
103  * setsockopt:	ENOMEM/ENOSR		-		ENOBUFS/ENOMEM/ENOSR
104  * shutdown:	ENOMEM/ENOSR		-		ENOBUFS/ENOSR
105  * socket:	ENOMEM/ENOSR		ENOBUFS		ENOBUFS/ENOMEM/ENOSR
106  * socketpair:	ENOMEM/ENOSR		-		ENOBUFS/ENOMEM/ENOSR
107  *
108  * Resolution. When allocation fails:
109  *	recv: return EINTR
110  *	send: return EINTR
111  *	connect, accept: EINTR
112  *	bind, listen, shutdown (unbind, unix_close, disconnect): sleep
113  *	socket, socketpair: ENOBUFS
114  *	getpeername, getsockname: sleep
115  *	getsockopt, setsockopt: sleep
116  */
117 
118 #ifdef SOCK_TEST
119 /*
120  * Variables that make sockfs do something other than the standard TPI
121  * for the AF_INET transports.
122  *
123  * solisten_tpi_tcp:
124  *	TCP can handle a O_T_BIND_REQ with an increased backlog even though
125  *	the transport is already bound. This is needed to avoid loosing the
126  *	port number should listen() do a T_UNBIND_REQ followed by a
127  *	O_T_BIND_REQ.
128  *
129  * soconnect_tpi_udp:
130  *	UDP and ICMP can handle a T_CONN_REQ.
131  *	This is needed to make the sequence of connect(), getsockname()
132  *	return the local IP address used to send packets to the connected to
133  *	destination.
134  *
135  * soconnect_tpi_tcp:
136  *	TCP can handle a T_CONN_REQ without seeing a O_T_BIND_REQ.
137  *	Set this to non-zero to send TPI conformant messages to TCP in this
138  *	respect. This is a performance optimization.
139  *
140  * soaccept_tpi_tcp:
141  *	TCP can handle a T_CONN_REQ without the acceptor being bound.
142  *	This is a performance optimization that has been picked up in XTI.
143  *
144  * soaccept_tpi_multioptions:
145  *	When inheriting SOL_SOCKET options from the listener to the accepting
146  *	socket send them as a single message for AF_INET{,6}.
147  */
148 int solisten_tpi_tcp = 0;
149 int soconnect_tpi_udp = 0;
150 int soconnect_tpi_tcp = 0;
151 int soaccept_tpi_tcp = 0;
152 int soaccept_tpi_multioptions = 1;
153 #else /* SOCK_TEST */
154 #define	soconnect_tpi_tcp	0
155 #define	soconnect_tpi_udp	0
156 #define	solisten_tpi_tcp	0
157 #define	soaccept_tpi_tcp	0
158 #define	soaccept_tpi_multioptions	1
159 #endif /* SOCK_TEST */
160 
161 #ifdef SOCK_TEST
162 extern int do_useracc;
163 extern clock_t sock_test_timelimit;
164 #endif /* SOCK_TEST */
165 
166 /*
167  * Some X/Open added checks might have to be backed out to keep SunOS 4.X
168  * applications working. Turn on this flag to disable these checks.
169  */
170 int xnet_skip_checks = 0;
171 int xnet_check_print = 0;
172 int xnet_truncate_print = 0;
173 
174 extern	void sigintr(k_sigset_t *, int);
175 extern	void sigunintr(k_sigset_t *);
176 
177 extern	void *nl7c_lookup_addr(void *, t_uscalar_t);
178 extern	void *nl7c_add_addr(void *, t_uscalar_t);
179 extern	void nl7c_listener_addr(void *, struct sonode *);
180 
181 /* Sockets acting as an in-kernel SSL proxy */
182 extern mblk_t	*strsock_kssl_input(vnode_t *, mblk_t *, strwakeup_t *,
183 		    strsigset_t *, strsigset_t *, strpollset_t *);
184 extern mblk_t	*strsock_kssl_output(vnode_t *, mblk_t *, strwakeup_t *,
185 		    strsigset_t *, strsigset_t *, strpollset_t *);
186 
187 static int	sotpi_unbind(struct sonode *, int);
188 
189 /* TPI sockfs sonode operations */
190 static int	sotpi_accept(struct sonode *, int, struct sonode **);
191 static int	sotpi_bind(struct sonode *, struct sockaddr *, socklen_t,
192 		    int);
193 static int	sotpi_connect(struct sonode *, const struct sockaddr *,
194 		    socklen_t, int, int);
195 static int	sotpi_listen(struct sonode *, int);
196 static int	sotpi_sendmsg(struct sonode *, struct nmsghdr *,
197 		    struct uio *);
198 static int	sotpi_shutdown(struct sonode *, int);
199 static int	sotpi_getsockname(struct sonode *);
200 static int	sosend_dgramcmsg(struct sonode *, struct sockaddr *, socklen_t,
201 		    struct uio *, void *, t_uscalar_t, int);
202 static int	sodgram_direct(struct sonode *, struct sockaddr *,
203 		    socklen_t, struct uio *, int);
204 
205 sonodeops_t sotpi_sonodeops = {
206 	sotpi_accept,		/* sop_accept		*/
207 	sotpi_bind,		/* sop_bind		*/
208 	sotpi_listen,		/* sop_listen		*/
209 	sotpi_connect,		/* sop_connect		*/
210 	sotpi_recvmsg,		/* sop_recvmsg		*/
211 	sotpi_sendmsg,		/* sop_sendmsg		*/
212 	sotpi_getpeername,	/* sop_getpeername	*/
213 	sotpi_getsockname,	/* sop_getsockname	*/
214 	sotpi_shutdown,		/* sop_shutdown		*/
215 	sotpi_getsockopt,	/* sop_getsockopt	*/
216 	sotpi_setsockopt	/* sop_setsockopt	*/
217 };
218 
219 /*
220  * Common create code for socket and accept. If tso is set the values
221  * from that node is used instead of issuing a T_INFO_REQ.
222  *
223  * Assumes that the caller has a VN_HOLD on accessvp.
224  * The VN_RELE will occur either when sotpi_create() fails or when
225  * the returned sonode is freed.
226  */
227 struct sonode *
228 sotpi_create(vnode_t *accessvp, int domain, int type, int protocol, int version,
229     struct sonode *tso, int *errorp)
230 {
231 	struct sonode	*so;
232 	vnode_t		*vp;
233 	int		flags, error;
234 
235 	ASSERT(accessvp != NULL);
236 	vp = makesockvp(accessvp, domain, type, protocol);
237 	ASSERT(vp != NULL);
238 	so = VTOSO(vp);
239 
240 	flags = FREAD|FWRITE;
241 
242 	if ((type == SOCK_STREAM || type == SOCK_DGRAM) &&
243 	    (domain == AF_INET || domain == AF_INET6) &&
244 	    (protocol == IPPROTO_TCP || protocol == IPPROTO_UDP ||
245 	    protocol == IPPROTO_IP)) {
246 		/* Tell tcp or udp that it's talking to sockets */
247 		flags |= SO_SOCKSTR;
248 
249 		/*
250 		 * Here we indicate to socktpi_open() our attempt to
251 		 * make direct calls between sockfs and transport.
252 		 * The final decision is left to socktpi_open().
253 		 */
254 		so->so_state |= SS_DIRECT;
255 
256 		ASSERT(so->so_type != SOCK_DGRAM || tso == NULL);
257 		if (so->so_type == SOCK_STREAM && tso != NULL) {
258 			if (tso->so_state & SS_DIRECT) {
259 				/*
260 				 * Inherit SS_DIRECT from listener and pass
261 				 * SO_ACCEPTOR open flag to tcp, indicating
262 				 * that this is an accept fast-path instance.
263 				 */
264 				flags |= SO_ACCEPTOR;
265 			} else {
266 				/*
267 				 * SS_DIRECT is not set on listener, meaning
268 				 * that the listener has been converted from
269 				 * a socket to a stream.  Ensure that the
270 				 * acceptor inherits these settings.
271 				 */
272 				so->so_state &= ~SS_DIRECT;
273 				flags &= ~SO_SOCKSTR;
274 			}
275 		}
276 	}
277 
278 	/*
279 	 * Tell local transport that it is talking to sockets.
280 	 */
281 	if (so->so_family == AF_UNIX) {
282 		flags |= SO_SOCKSTR;
283 	}
284 
285 	/* Initialize the kernel SSL proxy fields */
286 	so->so_kssl_type = KSSL_NO_PROXY;
287 	so->so_kssl_ent = NULL;
288 	so->so_kssl_ctx = NULL;
289 
290 	if (error = socktpi_open(&vp, flags, CRED())) {
291 		VN_RELE(vp);
292 		*errorp = error;
293 		return (NULL);
294 	}
295 
296 	if (error = so_strinit(so, tso)) {
297 		(void) VOP_CLOSE(vp, 0, 1, 0, CRED());
298 		VN_RELE(vp);
299 		*errorp = error;
300 		return (NULL);
301 	}
302 
303 	if (version == SOV_DEFAULT)
304 		version = so_default_version;
305 
306 	so->so_version = (short)version;
307 
308 	return (so);
309 }
310 
311 /*
312  * Bind the socket to an unspecified address in sockfs only.
313  * Used for TCP/UDP transports where we know that the O_T_BIND_REQ isn't
314  * required in all cases.
315  */
316 static void
317 so_automatic_bind(struct sonode *so)
318 {
319 	ASSERT(so->so_family == AF_INET || so->so_family == AF_INET6);
320 
321 	ASSERT(MUTEX_HELD(&so->so_lock));
322 	ASSERT(!(so->so_state & SS_ISBOUND));
323 	ASSERT(so->so_unbind_mp);
324 
325 	ASSERT(so->so_laddr_len <= so->so_laddr_maxlen);
326 	bzero(so->so_laddr_sa, so->so_laddr_len);
327 	so->so_laddr_sa->sa_family = so->so_family;
328 	so->so_state |= SS_ISBOUND;
329 }
330 
331 
332 /*
333  * bind the socket.
334  *
335  * If the socket is already bound and none of _SOBIND_SOCKBSD or _SOBIND_XPG4_2
336  * are passed in we allow rebinding. Note that for backwards compatibility
337  * even "svr4" sockets pass in _SOBIND_SOCKBSD/SOV_SOCKBSD to sobind/bind.
338  * Thus the rebinding code is currently not executed.
339  *
340  * The constraints for rebinding are:
341  * - it is a SOCK_DGRAM, or
342  * - it is a SOCK_STREAM/SOCK_SEQPACKET that has not been connected
343  *   and no listen() has been done.
344  * This rebinding code was added based on some language in the XNET book
345  * about not returning EINVAL it the protocol allows rebinding. However,
346  * this language is not present in the Posix socket draft. Thus maybe the
347  * rebinding logic should be deleted from the source.
348  *
349  * A null "name" can be used to unbind the socket if:
350  * - it is a SOCK_DGRAM, or
351  * - it is a SOCK_STREAM/SOCK_SEQPACKET that has not been connected
352  *   and no listen() has been done.
353  */
354 static int
355 sotpi_bindlisten(struct sonode *so, struct sockaddr *name,
356     socklen_t namelen, int backlog, int flags)
357 {
358 	struct T_bind_req	bind_req;
359 	struct T_bind_ack	*bind_ack;
360 	int			error = 0;
361 	mblk_t			*mp;
362 	void			*addr;
363 	t_uscalar_t		addrlen;
364 	int			unbind_on_err = 1;
365 	boolean_t		clear_acceptconn_on_err = B_FALSE;
366 	boolean_t		restore_backlog_on_err = B_FALSE;
367 	int			save_so_backlog;
368 	t_scalar_t		PRIM_type = O_T_BIND_REQ;
369 	boolean_t		tcp_udp_xport;
370 	void			*nl7c = NULL;
371 
372 	dprintso(so, 1, ("sotpi_bindlisten(%p, %p, %d, %d, 0x%x) %s\n",
373 		so, name, namelen, backlog, flags,
374 		pr_state(so->so_state, so->so_mode)));
375 
376 	tcp_udp_xport = so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM;
377 
378 	if (!(flags & _SOBIND_LOCK_HELD)) {
379 		mutex_enter(&so->so_lock);
380 		so_lock_single(so);	/* Set SOLOCKED */
381 	} else {
382 		ASSERT(MUTEX_HELD(&so->so_lock));
383 		ASSERT(so->so_flag & SOLOCKED);
384 	}
385 
386 	/*
387 	 * Make sure that there is a preallocated unbind_req message
388 	 * before binding. This message allocated when the socket is
389 	 * created  but it might be have been consumed.
390 	 */
391 	if (so->so_unbind_mp == NULL) {
392 		dprintso(so, 1, ("sobind: allocating unbind_req\n"));
393 		/* NOTE: holding so_lock while sleeping */
394 		so->so_unbind_mp =
395 		    soallocproto(sizeof (struct T_unbind_req), _ALLOC_SLEEP);
396 	}
397 
398 	if (flags & _SOBIND_REBIND) {
399 		/*
400 		 * Called from solisten after doing an sotpi_unbind() or
401 		 * potentially without the unbind (latter for AF_INET{,6}).
402 		 */
403 		ASSERT(name == NULL && namelen == 0);
404 
405 		if (so->so_family == AF_UNIX) {
406 			ASSERT(so->so_ux_bound_vp);
407 			addr = &so->so_ux_laddr;
408 			addrlen = (t_uscalar_t)sizeof (so->so_ux_laddr);
409 			dprintso(so, 1,
410 			("sobind rebind UNIX: addrlen %d, addr 0x%p, vp %p\n",
411 			    addrlen,
412 			    ((struct so_ux_addr *)addr)->soua_vp,
413 			    so->so_ux_bound_vp));
414 		} else {
415 			addr = so->so_laddr_sa;
416 			addrlen = (t_uscalar_t)so->so_laddr_len;
417 		}
418 	} else if (flags & _SOBIND_UNSPEC) {
419 		ASSERT(name == NULL && namelen == 0);
420 
421 		/*
422 		 * The caller checked SS_ISBOUND but not necessarily
423 		 * under so_lock
424 		 */
425 		if (so->so_state & SS_ISBOUND) {
426 			/* No error */
427 			goto done;
428 		}
429 
430 		/* Set an initial local address */
431 		switch (so->so_family) {
432 		case AF_UNIX:
433 			/*
434 			 * Use an address with same size as struct sockaddr
435 			 * just like BSD.
436 			 */
437 			so->so_laddr_len =
438 				(socklen_t)sizeof (struct sockaddr);
439 			ASSERT(so->so_laddr_len <= so->so_laddr_maxlen);
440 			bzero(so->so_laddr_sa, so->so_laddr_len);
441 			so->so_laddr_sa->sa_family = so->so_family;
442 
443 			/*
444 			 * Pass down an address with the implicit bind
445 			 * magic number and the rest all zeros.
446 			 * The transport will return a unique address.
447 			 */
448 			so->so_ux_laddr.soua_vp = NULL;
449 			so->so_ux_laddr.soua_magic = SOU_MAGIC_IMPLICIT;
450 			addr = &so->so_ux_laddr;
451 			addrlen = (t_uscalar_t)sizeof (so->so_ux_laddr);
452 			break;
453 
454 		case AF_INET:
455 		case AF_INET6:
456 			/*
457 			 * An unspecified bind in TPI has a NULL address.
458 			 * Set the address in sockfs to have the sa_family.
459 			 */
460 			so->so_laddr_len = (so->so_family == AF_INET) ?
461 			    (socklen_t)sizeof (sin_t) :
462 			    (socklen_t)sizeof (sin6_t);
463 			ASSERT(so->so_laddr_len <= so->so_laddr_maxlen);
464 			bzero(so->so_laddr_sa, so->so_laddr_len);
465 			so->so_laddr_sa->sa_family = so->so_family;
466 			addr = NULL;
467 			addrlen = 0;
468 			break;
469 
470 		default:
471 			/*
472 			 * An unspecified bind in TPI has a NULL address.
473 			 * Set the address in sockfs to be zero length.
474 			 *
475 			 * Can not assume there is a sa_family for all
476 			 * protocol families. For example, AF_X25 does not
477 			 * have a family field.
478 			 */
479 			bzero(so->so_laddr_sa, so->so_laddr_len);
480 			so->so_laddr_len = 0;	/* XXX correct? */
481 			addr = NULL;
482 			addrlen = 0;
483 			break;
484 		}
485 
486 	} else {
487 		if (so->so_state & SS_ISBOUND) {
488 			/*
489 			 * If it is ok to rebind the socket, first unbind
490 			 * with the transport. A rebind to the NULL address
491 			 * is interpreted as an unbind.
492 			 * Note that a bind to NULL in BSD does unbind the
493 			 * socket but it fails with EINVAL.
494 			 * Note that regular sockets set SOV_SOCKBSD i.e.
495 			 * _SOBIND_SOCKBSD gets set here hence no type of
496 			 * socket does currently allow rebinding.
497 			 *
498 			 * If the name is NULL just do an unbind.
499 			 */
500 			if (flags & (_SOBIND_SOCKBSD|_SOBIND_XPG4_2) &&
501 			    name != NULL) {
502 				error = EINVAL;
503 				unbind_on_err = 0;
504 				eprintsoline(so, error);
505 				goto done;
506 			}
507 			if ((so->so_mode & SM_CONNREQUIRED) &&
508 			    (so->so_state & SS_CANTREBIND)) {
509 				error = EINVAL;
510 				unbind_on_err = 0;
511 				eprintsoline(so, error);
512 				goto done;
513 			}
514 			error = sotpi_unbind(so, 0);
515 			if (error) {
516 				eprintsoline(so, error);
517 				goto done;
518 			}
519 			ASSERT(!(so->so_state & SS_ISBOUND));
520 			if (name == NULL) {
521 				so->so_state &=
522 					~(SS_ISCONNECTED|SS_ISCONNECTING);
523 				goto done;
524 			}
525 		}
526 		/* X/Open requires this check */
527 		if ((so->so_state & SS_CANTSENDMORE) && !xnet_skip_checks) {
528 			if (xnet_check_print) {
529 				printf("sockfs: X/Open bind state check "
530 				    "caused EINVAL\n");
531 			}
532 			error = EINVAL;
533 			goto done;
534 		}
535 
536 		switch (so->so_family) {
537 		case AF_UNIX:
538 			/*
539 			 * All AF_UNIX addresses are nul terminated
540 			 * when copied (copyin_name) in so the minimum
541 			 * length is 3 bytes.
542 			 */
543 			if (name == NULL ||
544 			    (ssize_t)namelen <= sizeof (short) + 1) {
545 				error = EISDIR;
546 				eprintsoline(so, error);
547 				goto done;
548 			}
549 			/*
550 			 * Verify so_family matches the bound family.
551 			 * BSD does not check this for AF_UNIX resulting
552 			 * in funny mknods.
553 			 */
554 			if (name->sa_family != so->so_family) {
555 				error = EAFNOSUPPORT;
556 				goto done;
557 			}
558 			break;
559 		case AF_INET:
560 			if (name == NULL) {
561 				error = EINVAL;
562 				eprintsoline(so, error);
563 				goto done;
564 			}
565 			if ((size_t)namelen != sizeof (sin_t)) {
566 				error = name->sa_family != so->so_family ?
567 				    EAFNOSUPPORT : EINVAL;
568 				eprintsoline(so, error);
569 				goto done;
570 			}
571 			if ((flags & _SOBIND_XPG4_2) &&
572 			    (name->sa_family != so->so_family)) {
573 				/*
574 				 * This check has to be made for X/Open
575 				 * sockets however application failures have
576 				 * been observed when it is applied to
577 				 * all sockets.
578 				 */
579 				error = EAFNOSUPPORT;
580 				eprintsoline(so, error);
581 				goto done;
582 			}
583 			/*
584 			 * Force a zero sa_family to match so_family.
585 			 *
586 			 * Some programs like inetd(1M) don't set the
587 			 * family field. Other programs leave
588 			 * sin_family set to garbage - SunOS 4.X does
589 			 * not check the family field on a bind.
590 			 * We use the family field that
591 			 * was passed in to the socket() call.
592 			 */
593 			name->sa_family = so->so_family;
594 			break;
595 
596 		case AF_INET6: {
597 #ifdef DEBUG
598 			sin6_t *sin6 = (sin6_t *)name;
599 #endif /* DEBUG */
600 
601 			if (name == NULL) {
602 				error = EINVAL;
603 				eprintsoline(so, error);
604 				goto done;
605 			}
606 			if ((size_t)namelen != sizeof (sin6_t)) {
607 				error = name->sa_family != so->so_family ?
608 				    EAFNOSUPPORT : EINVAL;
609 				eprintsoline(so, error);
610 				goto done;
611 			}
612 			if (name->sa_family != so->so_family) {
613 				/*
614 				 * With IPv6 we require the family to match
615 				 * unlike in IPv4.
616 				 */
617 				error = EAFNOSUPPORT;
618 				eprintsoline(so, error);
619 				goto done;
620 			}
621 #ifdef DEBUG
622 			/*
623 			 * Verify that apps don't forget to clear
624 			 * sin6_scope_id etc
625 			 */
626 			if (sin6->sin6_scope_id != 0 &&
627 			    !IN6_IS_ADDR_LINKSCOPE(&sin6->sin6_addr)) {
628 				zcmn_err(getzoneid(), CE_WARN,
629 				    "bind with uninitialized sin6_scope_id "
630 				    "(%d) on socket. Pid = %d\n",
631 				    (int)sin6->sin6_scope_id,
632 				    (int)curproc->p_pid);
633 			}
634 			if (sin6->__sin6_src_id != 0) {
635 				zcmn_err(getzoneid(), CE_WARN,
636 				    "bind with uninitialized __sin6_src_id "
637 				    "(%d) on socket. Pid = %d\n",
638 				    (int)sin6->__sin6_src_id,
639 				    (int)curproc->p_pid);
640 			}
641 #endif /* DEBUG */
642 			break;
643 		}
644 		default:
645 			/*
646 			 * Don't do any length or sa_family check to allow
647 			 * non-sockaddr style addresses.
648 			 */
649 			if (name == NULL) {
650 				error = EINVAL;
651 				eprintsoline(so, error);
652 				goto done;
653 			}
654 			break;
655 		}
656 
657 		if (namelen > (t_uscalar_t)so->so_laddr_maxlen) {
658 			error = ENAMETOOLONG;
659 			eprintsoline(so, error);
660 			goto done;
661 		}
662 		/*
663 		 * Save local address.
664 		 */
665 		so->so_laddr_len = (socklen_t)namelen;
666 		ASSERT(so->so_laddr_len <= so->so_laddr_maxlen);
667 		bcopy(name, so->so_laddr_sa, namelen);
668 
669 		addr = so->so_laddr_sa;
670 		addrlen = (t_uscalar_t)so->so_laddr_len;
671 		switch (so->so_family) {
672 		case AF_INET6:
673 		case AF_INET:
674 			break;
675 		case AF_UNIX: {
676 			struct sockaddr_un *soun =
677 				(struct sockaddr_un *)so->so_laddr_sa;
678 			struct vnode *vp;
679 			struct vattr vattr;
680 
681 			ASSERT(so->so_ux_bound_vp == NULL);
682 			/*
683 			 * Create vnode for the specified path name.
684 			 * Keep vnode held with a reference in so_ux_bound_vp.
685 			 * Use the vnode pointer as the address used in the
686 			 * bind with the transport.
687 			 *
688 			 * Use the same mode as in BSD. In particular this does
689 			 * not observe the umask.
690 			 */
691 			/* MAXPATHLEN + soun_family + nul termination */
692 			if (so->so_laddr_len >
693 			    (socklen_t)(MAXPATHLEN + sizeof (short) + 1)) {
694 				error = ENAMETOOLONG;
695 				eprintsoline(so, error);
696 				goto done;
697 			}
698 			vattr.va_type = VSOCK;
699 			vattr.va_mode = 0777 & ~PTOU(curproc)->u_cmask;
700 			vattr.va_mask = AT_TYPE|AT_MODE;
701 			/* NOTE: holding so_lock */
702 			error = vn_create(soun->sun_path, UIO_SYSSPACE, &vattr,
703 						EXCL, 0, &vp, CRMKNOD, 0, 0);
704 			if (error) {
705 				if (error == EEXIST)
706 					error = EADDRINUSE;
707 				eprintsoline(so, error);
708 				goto done;
709 			}
710 			/*
711 			 * Establish pointer from the underlying filesystem
712 			 * vnode to the socket node.
713 			 * so_ux_bound_vp and v_stream->sd_vnode form the
714 			 * cross-linkage between the underlying filesystem
715 			 * node and the socket node.
716 			 */
717 			ASSERT(SOTOV(so)->v_stream);
718 			mutex_enter(&vp->v_lock);
719 			vp->v_stream = SOTOV(so)->v_stream;
720 			so->so_ux_bound_vp = vp;
721 			mutex_exit(&vp->v_lock);
722 
723 			/*
724 			 * Use the vnode pointer value as a unique address
725 			 * (together with the magic number to avoid conflicts
726 			 * with implicit binds) in the transport provider.
727 			 */
728 			so->so_ux_laddr.soua_vp = (void *)so->so_ux_bound_vp;
729 			so->so_ux_laddr.soua_magic = SOU_MAGIC_EXPLICIT;
730 			addr = &so->so_ux_laddr;
731 			addrlen = (t_uscalar_t)sizeof (so->so_ux_laddr);
732 			dprintso(so, 1, ("sobind UNIX: addrlen %d, addr %p\n",
733 			    addrlen,
734 			    ((struct so_ux_addr *)addr)->soua_vp));
735 			break;
736 		}
737 		} /* end switch (so->so_family) */
738 	}
739 
740 	/*
741 	 * set SS_ACCEPTCONN before sending down O_T_BIND_REQ since
742 	 * the transport can start passing up T_CONN_IND messages
743 	 * as soon as it receives the bind req and strsock_proto()
744 	 * insists that SS_ACCEPTCONN is set when processing T_CONN_INDs.
745 	 */
746 	if (flags & _SOBIND_LISTEN) {
747 		if ((so->so_state & SS_ACCEPTCONN) == 0)
748 			clear_acceptconn_on_err = B_TRUE;
749 		save_so_backlog = so->so_backlog;
750 		restore_backlog_on_err = B_TRUE;
751 		so->so_state |= SS_ACCEPTCONN;
752 		so->so_backlog = backlog;
753 	}
754 
755 	/*
756 	 * If NL7C addr(s) have been configured check for addr/port match,
757 	 * or if an implicit NL7C socket via AF_NCA mark socket as NL7C.
758 	 *
759 	 * NL7C supports the TCP transport only so check AF_INET and AF_INET6
760 	 * family sockets only. If match mark as such.
761 	 */
762 	if (nl7c_enabled && ((addr != NULL &&
763 	    (so->so_family == AF_INET || so->so_family == AF_INET6) &&
764 	    (nl7c = nl7c_lookup_addr(addr, addrlen))) ||
765 	    so->so_nl7c_flags == NL7C_AF_NCA)) {
766 		/*
767 		 * NL7C is not supported in non-global zones,
768 		 * we enforce this restriction here.
769 		 */
770 		if (so->so_zoneid == GLOBAL_ZONEID) {
771 			/* An NL7C socket, mark it */
772 			so->so_nl7c_flags |= NL7C_ENABLED;
773 			if (nl7c == NULL) {
774 				/*
775 				 * Was an AF_NCA bind() so add it to the
776 				 * addr list for reporting purposes.
777 				 */
778 				nl7c = nl7c_add_addr(addr, addrlen);
779 			}
780 		} else
781 			nl7c = NULL;
782 	}
783 	/*
784 	 * We send a T_BIND_REQ for TCP/UDP since we know it supports it,
785 	 * for other transports we will send in a O_T_BIND_REQ.
786 	 */
787 	if (tcp_udp_xport &&
788 	    (so->so_family == AF_INET || so->so_family == AF_INET6))
789 		PRIM_type = T_BIND_REQ;
790 
791 	bind_req.PRIM_type = PRIM_type;
792 	bind_req.ADDR_length = addrlen;
793 	bind_req.ADDR_offset = (t_scalar_t)sizeof (bind_req);
794 	bind_req.CONIND_number = backlog;
795 	/* NOTE: holding so_lock while sleeping */
796 	mp = soallocproto2(&bind_req, sizeof (bind_req),
797 				addr, addrlen, 0, _ALLOC_SLEEP);
798 	so->so_state &= ~SS_LADDR_VALID;
799 
800 	/* Done using so_laddr_sa - can drop the lock */
801 	mutex_exit(&so->so_lock);
802 
803 	/*
804 	 * Intercept the bind_req message here to check if this <address/port>
805 	 * was configured as an SSL proxy server, or if another endpoint was
806 	 * already configured to act as a proxy for us.
807 	 *
808 	 * Note, only if NL7C not enabled for this socket.
809 	 */
810 	if (nl7c == NULL &&
811 	    (so->so_family == AF_INET || so->so_family == AF_INET6) &&
812 	    so->so_type == SOCK_STREAM) {
813 
814 		if (so->so_kssl_ent != NULL) {
815 			kssl_release_ent(so->so_kssl_ent, so, so->so_kssl_type);
816 			so->so_kssl_ent = NULL;
817 		}
818 
819 		so->so_kssl_type = kssl_check_proxy(mp, so, &so->so_kssl_ent);
820 		switch (so->so_kssl_type) {
821 		case KSSL_NO_PROXY:
822 			break;
823 
824 		case KSSL_HAS_PROXY:
825 			mutex_enter(&so->so_lock);
826 			goto skip_transport;
827 
828 		case KSSL_IS_PROXY:
829 			break;
830 		}
831 	}
832 
833 	error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
834 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR, 0);
835 	if (error) {
836 		eprintsoline(so, error);
837 		mutex_enter(&so->so_lock);
838 		goto done;
839 	}
840 
841 	mutex_enter(&so->so_lock);
842 	error = sowaitprim(so, PRIM_type, T_BIND_ACK,
843 	    (t_uscalar_t)sizeof (*bind_ack), &mp, 0);
844 	if (error) {
845 		eprintsoline(so, error);
846 		goto done;
847 	}
848 skip_transport:
849 	ASSERT(mp);
850 	/*
851 	 * Even if some TPI message (e.g. T_DISCON_IND) was received in
852 	 * strsock_proto while the lock was dropped above, the bind
853 	 * is allowed to complete.
854 	 */
855 
856 	/* Mark as bound. This will be undone if we detect errors below. */
857 	if (flags & _SOBIND_NOXLATE) {
858 		ASSERT(so->so_family == AF_UNIX);
859 		so->so_state |= SS_FADDR_NOXLATE;
860 	}
861 	ASSERT(!(so->so_state & SS_ISBOUND) || (flags & _SOBIND_REBIND));
862 	so->so_state |= SS_ISBOUND;
863 	ASSERT(so->so_unbind_mp);
864 
865 	/* note that we've already set SS_ACCEPTCONN above */
866 
867 	/*
868 	 * Recompute addrlen - an unspecied bind sent down an
869 	 * address of length zero but we expect the appropriate length
870 	 * in return.
871 	 */
872 	addrlen = (t_uscalar_t)(so->so_family == AF_UNIX ?
873 	    sizeof (so->so_ux_laddr) : so->so_laddr_len);
874 
875 	bind_ack = (struct T_bind_ack *)mp->b_rptr;
876 	/*
877 	 * The alignment restriction is really too strict but
878 	 * we want enough alignment to inspect the fields of
879 	 * a sockaddr_in.
880 	 */
881 	addr = sogetoff(mp, bind_ack->ADDR_offset,
882 			bind_ack->ADDR_length,
883 			__TPI_ALIGN_SIZE);
884 	if (addr == NULL) {
885 		freemsg(mp);
886 		error = EPROTO;
887 		eprintsoline(so, error);
888 		goto done;
889 	}
890 	if (!(flags & _SOBIND_UNSPEC)) {
891 		/*
892 		 * Verify that the transport didn't return something we
893 		 * did not want e.g. an address other than what we asked for.
894 		 *
895 		 * NOTE: These checks would go away if/when we switch to
896 		 * using the new TPI (in which the transport would fail
897 		 * the request instead of assigning a different address).
898 		 *
899 		 * NOTE2: For protocols that we don't know (i.e. any
900 		 * other than AF_INET6, AF_INET and AF_UNIX), we
901 		 * cannot know if the transport should be expected to
902 		 * return the same address as that requested.
903 		 *
904 		 * NOTE3: For AF_INET and AF_INET6, TCP/UDP, we send
905 		 * down a T_BIND_REQ. We use O_T_BIND_REQ for others.
906 		 *
907 		 * For example, in the case of netatalk it may be
908 		 * inappropriate for the transport to return the
909 		 * requested address (as it may have allocated a local
910 		 * port number in behaviour similar to that of an
911 		 * AF_INET bind request with a port number of zero).
912 		 *
913 		 * Given the definition of O_T_BIND_REQ, where the
914 		 * transport may bind to an address other than the
915 		 * requested address, it's not possible to determine
916 		 * whether a returned address that differs from the
917 		 * requested address is a reason to fail (because the
918 		 * requested address was not available) or succeed
919 		 * (because the transport allocated an appropriate
920 		 * address and/or port).
921 		 *
922 		 * sockfs currently requires that the transport return
923 		 * the requested address in the T_BIND_ACK, unless
924 		 * there is code here to allow for any discrepancy.
925 		 * Such code exists for AF_INET and AF_INET6.
926 		 *
927 		 * Netatalk chooses to return the requested address
928 		 * rather than the (correct) allocated address.  This
929 		 * means that netatalk violates the TPI specification
930 		 * (and would not function correctly if used from a
931 		 * TLI application), but it does mean that it works
932 		 * with sockfs.
933 		 *
934 		 * As noted above, using the newer XTI bind primitive
935 		 * (T_BIND_REQ) in preference to O_T_BIND_REQ would
936 		 * allow sockfs to be more sure about whether or not
937 		 * the bind request had succeeded (as transports are
938 		 * not permitted to bind to a different address than
939 		 * that requested - they must return failure).
940 		 * Unfortunately, support for T_BIND_REQ may not be
941 		 * present in all transport implementations (netatalk,
942 		 * for example, doesn't have it), making the
943 		 * transition difficult.
944 		 */
945 		if (bind_ack->ADDR_length != addrlen) {
946 			/* Assumes that the requested address was in use */
947 			freemsg(mp);
948 			error = EADDRINUSE;
949 			eprintsoline(so, error);
950 			goto done;
951 		}
952 
953 		switch (so->so_family) {
954 		case AF_INET6:
955 		case AF_INET: {
956 			sin_t *rname, *aname;
957 
958 			rname = (sin_t *)addr;
959 			aname = (sin_t *)so->so_laddr_sa;
960 
961 			/*
962 			 * Take advantage of the alignment
963 			 * of sin_port and sin6_port which fall
964 			 * in the same place in their data structures.
965 			 * Just use sin_port for either address family.
966 			 *
967 			 * This may become a problem if (heaven forbid)
968 			 * there's a separate ipv6port_reserved... :-P
969 			 *
970 			 * Binding to port 0 has the semantics of letting
971 			 * the transport bind to any port.
972 			 *
973 			 * If the transport is TCP or UDP since we had sent
974 			 * a T_BIND_REQ we would not get a port other than
975 			 * what we asked for.
976 			 */
977 			if (tcp_udp_xport) {
978 				/*
979 				 * Pick up the new port number if we bound to
980 				 * port 0.
981 				 */
982 				if (aname->sin_port == 0)
983 					aname->sin_port = rname->sin_port;
984 				so->so_state |= SS_LADDR_VALID;
985 				break;
986 			}
987 			if (aname->sin_port != 0 &&
988 			    aname->sin_port != rname->sin_port) {
989 				freemsg(mp);
990 				error = EADDRINUSE;
991 				eprintsoline(so, error);
992 				goto done;
993 			}
994 			/*
995 			 * Pick up the new port number if we bound to port 0.
996 			 */
997 			aname->sin_port = rname->sin_port;
998 
999 			/*
1000 			 * Unfortunately, addresses aren't _quite_ the same.
1001 			 */
1002 			if (so->so_family == AF_INET) {
1003 				if (aname->sin_addr.s_addr !=
1004 				    rname->sin_addr.s_addr) {
1005 					freemsg(mp);
1006 					error = EADDRNOTAVAIL;
1007 					eprintsoline(so, error);
1008 					goto done;
1009 				}
1010 			} else {
1011 				sin6_t *rname6 = (sin6_t *)rname;
1012 				sin6_t *aname6 = (sin6_t *)aname;
1013 
1014 				if (!IN6_ARE_ADDR_EQUAL(&aname6->sin6_addr,
1015 				    &rname6->sin6_addr)) {
1016 					freemsg(mp);
1017 					error = EADDRNOTAVAIL;
1018 					eprintsoline(so, error);
1019 					goto done;
1020 				}
1021 			}
1022 			break;
1023 		}
1024 		case AF_UNIX:
1025 			if (bcmp(addr, &so->so_ux_laddr, addrlen) != 0) {
1026 				freemsg(mp);
1027 				error = EADDRINUSE;
1028 				eprintsoline(so, error);
1029 				eprintso(so,
1030 					("addrlen %d, addr 0x%x, vp %p\n",
1031 					addrlen, *((int *)addr),
1032 					so->so_ux_bound_vp));
1033 				goto done;
1034 			}
1035 			so->so_state |= SS_LADDR_VALID;
1036 			break;
1037 		default:
1038 			/*
1039 			 * NOTE: This assumes that addresses can be
1040 			 * byte-compared for equivalence.
1041 			 */
1042 			if (bcmp(addr, so->so_laddr_sa, addrlen) != 0) {
1043 				freemsg(mp);
1044 				error = EADDRINUSE;
1045 				eprintsoline(so, error);
1046 				goto done;
1047 			}
1048 			/*
1049 			 * Don't mark SS_LADDR_VALID, as we cannot be
1050 			 * sure that the returned address is the real
1051 			 * bound address when talking to an unknown
1052 			 * transport.
1053 			 */
1054 			break;
1055 		}
1056 	} else {
1057 		/*
1058 		 * Save for returned address for getsockname.
1059 		 * Needed for unspecific bind unless transport supports
1060 		 * the TI_GETMYNAME ioctl.
1061 		 * Do this for AF_INET{,6} even though they do, as
1062 		 * caching info here is much better performance than
1063 		 * a TPI/STREAMS trip to the transport for getsockname.
1064 		 * Any which can't for some reason _must_ _not_ set
1065 		 * LADDR_VALID here for the caching version of getsockname
1066 		 * to not break;
1067 		 */
1068 		switch (so->so_family) {
1069 		case AF_UNIX:
1070 			/*
1071 			 * Record the address bound with the transport
1072 			 * for use by socketpair.
1073 			 */
1074 			bcopy(addr, &so->so_ux_laddr, addrlen);
1075 			so->so_state |= SS_LADDR_VALID;
1076 			break;
1077 		case AF_INET:
1078 		case AF_INET6:
1079 			ASSERT(so->so_laddr_len <= so->so_laddr_maxlen);
1080 			bcopy(addr, so->so_laddr_sa, so->so_laddr_len);
1081 			so->so_state |= SS_LADDR_VALID;
1082 			break;
1083 		default:
1084 			/*
1085 			 * Don't mark SS_LADDR_VALID, as we cannot be
1086 			 * sure that the returned address is the real
1087 			 * bound address when talking to an unknown
1088 			 * transport.
1089 			 */
1090 			break;
1091 		}
1092 	}
1093 
1094 	if (nl7c != NULL) {
1095 		/* Register listen()er sonode pointer with NL7C */
1096 		nl7c_listener_addr(nl7c, so);
1097 	}
1098 
1099 	freemsg(mp);
1100 
1101 done:
1102 	if (error) {
1103 		/* reset state & backlog to values held on entry */
1104 		if (clear_acceptconn_on_err == B_TRUE)
1105 			so->so_state &= ~SS_ACCEPTCONN;
1106 		if (restore_backlog_on_err == B_TRUE)
1107 			so->so_backlog = save_so_backlog;
1108 
1109 		if (unbind_on_err && so->so_state & SS_ISBOUND) {
1110 			int err;
1111 
1112 			err = sotpi_unbind(so, 0);
1113 			/* LINTED - statement has no consequent: if */
1114 			if (err) {
1115 				eprintsoline(so, error);
1116 			} else {
1117 				ASSERT(!(so->so_state & SS_ISBOUND));
1118 			}
1119 		}
1120 	}
1121 	if (!(flags & _SOBIND_LOCK_HELD)) {
1122 		so_unlock_single(so, SOLOCKED);
1123 		mutex_exit(&so->so_lock);
1124 	} else {
1125 		/* If the caller held the lock don't release it here */
1126 		ASSERT(MUTEX_HELD(&so->so_lock));
1127 		ASSERT(so->so_flag & SOLOCKED);
1128 	}
1129 	return (error);
1130 }
1131 
1132 /* bind the socket */
1133 static int
1134 sotpi_bind(struct sonode *so, struct sockaddr *name, socklen_t namelen,
1135     int flags)
1136 {
1137 	if ((flags & _SOBIND_SOCKETPAIR) == 0)
1138 		return (sotpi_bindlisten(so, name, namelen, 0, flags));
1139 
1140 	flags &= ~_SOBIND_SOCKETPAIR;
1141 	return (sotpi_bindlisten(so, name, namelen, 1, flags));
1142 }
1143 
1144 /*
1145  * Unbind a socket - used when bind() fails, when bind() specifies a NULL
1146  * address, or when listen needs to unbind and bind.
1147  * If the _SOUNBIND_REBIND flag is specified the addresses are retained
1148  * so that a sobind can pick them up.
1149  */
1150 static int
1151 sotpi_unbind(struct sonode *so, int flags)
1152 {
1153 	struct T_unbind_req	unbind_req;
1154 	int			error = 0;
1155 	mblk_t			*mp;
1156 
1157 	dprintso(so, 1, ("sotpi_unbind(%p, 0x%x) %s\n",
1158 			so, flags, pr_state(so->so_state, so->so_mode)));
1159 
1160 	ASSERT(MUTEX_HELD(&so->so_lock));
1161 	ASSERT(so->so_flag & SOLOCKED);
1162 
1163 	if (!(so->so_state & SS_ISBOUND)) {
1164 		error = EINVAL;
1165 		eprintsoline(so, error);
1166 		goto done;
1167 	}
1168 
1169 	mutex_exit(&so->so_lock);
1170 
1171 	/*
1172 	 * Flush the read and write side (except stream head read queue)
1173 	 * and send down T_UNBIND_REQ.
1174 	 */
1175 	(void) putnextctl1(strvp2wq(SOTOV(so)), M_FLUSH, FLUSHRW);
1176 
1177 	unbind_req.PRIM_type = T_UNBIND_REQ;
1178 	mp = soallocproto1(&unbind_req, sizeof (unbind_req),
1179 	    0, _ALLOC_SLEEP);
1180 	error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
1181 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR, 0);
1182 	mutex_enter(&so->so_lock);
1183 	if (error) {
1184 		eprintsoline(so, error);
1185 		goto done;
1186 	}
1187 
1188 	error = sowaitokack(so, T_UNBIND_REQ);
1189 	if (error) {
1190 		eprintsoline(so, error);
1191 		goto done;
1192 	}
1193 
1194 	/*
1195 	 * Even if some TPI message (e.g. T_DISCON_IND) was received in
1196 	 * strsock_proto while the lock was dropped above, the unbind
1197 	 * is allowed to complete.
1198 	 */
1199 	if (!(flags & _SOUNBIND_REBIND)) {
1200 		/*
1201 		 * Clear out bound address.
1202 		 */
1203 		vnode_t *vp;
1204 
1205 		if ((vp = so->so_ux_bound_vp) != NULL) {
1206 
1207 			/* Undo any SSL proxy setup */
1208 			if ((so->so_family == AF_INET ||
1209 			    so->so_family == AF_INET6) &&
1210 			    (so->so_type == SOCK_STREAM) &&
1211 			    (so->so_kssl_ent != NULL)) {
1212 				kssl_release_ent(so->so_kssl_ent, so,
1213 				    so->so_kssl_type);
1214 				so->so_kssl_ent = NULL;
1215 				so->so_kssl_type = KSSL_NO_PROXY;
1216 			}
1217 
1218 			so->so_ux_bound_vp = NULL;
1219 			vn_rele_stream(vp);
1220 		}
1221 		/* Clear out address */
1222 		so->so_laddr_len = 0;
1223 	}
1224 	so->so_state &= ~(SS_ISBOUND|SS_ACCEPTCONN|SS_LADDR_VALID);
1225 
1226 done:
1227 
1228 	/* If the caller held the lock don't release it here */
1229 	ASSERT(MUTEX_HELD(&so->so_lock));
1230 	ASSERT(so->so_flag & SOLOCKED);
1231 
1232 	return (error);
1233 }
1234 
1235 /*
1236  * listen on the socket.
1237  * For TPI conforming transports this has to first unbind with the transport
1238  * and then bind again using the new backlog.
1239  */
1240 int
1241 sotpi_listen(struct sonode *so, int backlog)
1242 {
1243 	int		error = 0;
1244 
1245 	dprintso(so, 1, ("sotpi_listen(%p, %d) %s\n",
1246 		so, backlog, pr_state(so->so_state, so->so_mode)));
1247 
1248 	if (so->so_serv_type == T_CLTS)
1249 		return (EOPNOTSUPP);
1250 
1251 	/*
1252 	 * If the socket is ready to accept connections already, then
1253 	 * return without doing anything.  This avoids a problem where
1254 	 * a second listen() call fails if a connection is pending and
1255 	 * leaves the socket unbound. Only when we are not unbinding
1256 	 * with the transport can we safely increase the backlog.
1257 	 */
1258 	if (so->so_state & SS_ACCEPTCONN &&
1259 	    !((so->so_family == AF_INET || so->so_family == AF_INET6) &&
1260 		/*CONSTCOND*/
1261 		!solisten_tpi_tcp))
1262 		return (0);
1263 
1264 	if (so->so_state & SS_ISCONNECTED)
1265 		return (EINVAL);
1266 
1267 	mutex_enter(&so->so_lock);
1268 	so_lock_single(so);	/* Set SOLOCKED */
1269 
1270 	if (backlog < 0)
1271 		backlog = 0;
1272 	/*
1273 	 * Use the same qlimit as in BSD. BSD checks the qlimit
1274 	 * before queuing the next connection implying that a
1275 	 * listen(sock, 0) allows one connection to be queued.
1276 	 * BSD also uses 1.5 times the requested backlog.
1277 	 *
1278 	 * XNS Issue 4 required a strict interpretation of the backlog.
1279 	 * This has been waived subsequently for Issue 4 and the change
1280 	 * incorporated in XNS Issue 5. So we aren't required to do
1281 	 * anything special for XPG apps.
1282 	 */
1283 	if (backlog >= (INT_MAX - 1) / 3)
1284 		backlog = INT_MAX;
1285 	else
1286 		backlog = backlog * 3 / 2 + 1;
1287 
1288 	/*
1289 	 * If the listen doesn't change the backlog we do nothing.
1290 	 * This avoids an EPROTO error from the transport.
1291 	 */
1292 	if ((so->so_state & SS_ACCEPTCONN) &&
1293 	    so->so_backlog == backlog)
1294 		goto done;
1295 
1296 	if (!(so->so_state & SS_ISBOUND)) {
1297 		/*
1298 		 * Must have been explicitly bound in the UNIX domain.
1299 		 */
1300 		if (so->so_family == AF_UNIX) {
1301 			error = EINVAL;
1302 			goto done;
1303 		}
1304 		error = sotpi_bindlisten(so, NULL, 0, backlog,
1305 			    _SOBIND_UNSPEC|_SOBIND_LOCK_HELD|_SOBIND_LISTEN);
1306 	} else if (backlog > 0) {
1307 		/*
1308 		 * AF_INET{,6} hack to avoid losing the port.
1309 		 * Assumes that all AF_INET{,6} transports can handle a
1310 		 * O_T_BIND_REQ with a non-zero CONIND_number when the TPI
1311 		 * has already bound thus it is possible to avoid the unbind.
1312 		 */
1313 		if (!((so->so_family == AF_INET || so->so_family == AF_INET6) &&
1314 		    /*CONSTCOND*/
1315 		    !solisten_tpi_tcp)) {
1316 			error = sotpi_unbind(so, _SOUNBIND_REBIND);
1317 			if (error)
1318 				goto done;
1319 		}
1320 		error = sotpi_bindlisten(so, NULL, 0, backlog,
1321 			    _SOBIND_REBIND|_SOBIND_LOCK_HELD|_SOBIND_LISTEN);
1322 	} else {
1323 		so->so_state |= SS_ACCEPTCONN;
1324 		so->so_backlog = backlog;
1325 	}
1326 	if (error)
1327 		goto done;
1328 	ASSERT(so->so_state & SS_ACCEPTCONN);
1329 done:
1330 	so_unlock_single(so, SOLOCKED);
1331 	mutex_exit(&so->so_lock);
1332 	return (error);
1333 }
1334 
1335 /*
1336  * Disconnect either a specified seqno or all (-1).
1337  * The former is used on listening sockets only.
1338  *
1339  * When seqno == -1 sodisconnect could call sotpi_unbind. However,
1340  * the current use of sodisconnect(seqno == -1) is only for shutdown
1341  * so there is no point (and potentially incorrect) to unbind.
1342  */
1343 int
1344 sodisconnect(struct sonode *so, t_scalar_t seqno, int flags)
1345 {
1346 	struct T_discon_req	discon_req;
1347 	int			error = 0;
1348 	mblk_t			*mp;
1349 
1350 	dprintso(so, 1, ("sodisconnect(%p, %d, 0x%x) %s\n",
1351 			so, seqno, flags, pr_state(so->so_state, so->so_mode)));
1352 
1353 	if (!(flags & _SODISCONNECT_LOCK_HELD)) {
1354 		mutex_enter(&so->so_lock);
1355 		so_lock_single(so);	/* Set SOLOCKED */
1356 	} else {
1357 		ASSERT(MUTEX_HELD(&so->so_lock));
1358 		ASSERT(so->so_flag & SOLOCKED);
1359 	}
1360 
1361 	if (!(so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING|SS_ACCEPTCONN))) {
1362 		error = EINVAL;
1363 		eprintsoline(so, error);
1364 		goto done;
1365 	}
1366 
1367 	mutex_exit(&so->so_lock);
1368 	/*
1369 	 * Flush the write side (unless this is a listener)
1370 	 * and then send down a T_DISCON_REQ.
1371 	 * (Don't flush on listener since it could flush {O_}T_CONN_RES
1372 	 * and other messages.)
1373 	 */
1374 	if (!(so->so_state & SS_ACCEPTCONN))
1375 		(void) putnextctl1(strvp2wq(SOTOV(so)), M_FLUSH, FLUSHW);
1376 
1377 	discon_req.PRIM_type = T_DISCON_REQ;
1378 	discon_req.SEQ_number = seqno;
1379 	mp = soallocproto1(&discon_req, sizeof (discon_req),
1380 	    0, _ALLOC_SLEEP);
1381 	error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
1382 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR, 0);
1383 	mutex_enter(&so->so_lock);
1384 	if (error) {
1385 		eprintsoline(so, error);
1386 		goto done;
1387 	}
1388 
1389 	error = sowaitokack(so, T_DISCON_REQ);
1390 	if (error) {
1391 		eprintsoline(so, error);
1392 		goto done;
1393 	}
1394 	/*
1395 	 * Even if some TPI message (e.g. T_DISCON_IND) was received in
1396 	 * strsock_proto while the lock was dropped above, the disconnect
1397 	 * is allowed to complete. However, it is not possible to
1398 	 * assert that SS_ISCONNECTED|SS_ISCONNECTING are set.
1399 	 */
1400 	so->so_state &=
1401 	    ~(SS_ISCONNECTED|SS_ISCONNECTING|SS_LADDR_VALID|SS_FADDR_VALID);
1402 done:
1403 	if (!(flags & _SODISCONNECT_LOCK_HELD)) {
1404 		so_unlock_single(so, SOLOCKED);
1405 		mutex_exit(&so->so_lock);
1406 	} else {
1407 		/* If the caller held the lock don't release it here */
1408 		ASSERT(MUTEX_HELD(&so->so_lock));
1409 		ASSERT(so->so_flag & SOLOCKED);
1410 	}
1411 	return (error);
1412 }
1413 
1414 int
1415 sotpi_accept(struct sonode *so, int fflag, struct sonode **nsop)
1416 {
1417 	struct T_conn_ind	*conn_ind;
1418 	struct T_conn_res	*conn_res;
1419 	int			error = 0;
1420 	mblk_t			*mp, *ctxmp;
1421 	struct sonode		*nso;
1422 	vnode_t			*nvp;
1423 	void			*src;
1424 	t_uscalar_t		srclen;
1425 	void			*opt;
1426 	t_uscalar_t		optlen;
1427 	t_scalar_t		PRIM_type;
1428 	t_scalar_t		SEQ_number;
1429 
1430 	dprintso(so, 1, ("sotpi_accept(%p, 0x%x, %p) %s\n",
1431 		so, fflag, nsop, pr_state(so->so_state, so->so_mode)));
1432 
1433 	/*
1434 	 * Defer single-threading the accepting socket until
1435 	 * the T_CONN_IND has been received and parsed and the
1436 	 * new sonode has been opened.
1437 	 */
1438 
1439 	/* Check that we are not already connected */
1440 	if ((so->so_state & SS_ACCEPTCONN) == 0)
1441 		goto conn_bad;
1442 again:
1443 	if ((error = sowaitconnind(so, fflag, &mp)) != 0)
1444 		goto e_bad;
1445 
1446 	ASSERT(mp);
1447 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
1448 	ctxmp = mp->b_cont;
1449 
1450 	/*
1451 	 * Save SEQ_number for error paths.
1452 	 */
1453 	SEQ_number = conn_ind->SEQ_number;
1454 
1455 	srclen = conn_ind->SRC_length;
1456 	src = sogetoff(mp, conn_ind->SRC_offset, srclen, 1);
1457 	if (src == NULL) {
1458 		error = EPROTO;
1459 		freemsg(mp);
1460 		eprintsoline(so, error);
1461 		goto disconnect_unlocked;
1462 	}
1463 	optlen = conn_ind->OPT_length;
1464 	switch (so->so_family) {
1465 	case AF_INET:
1466 	case AF_INET6:
1467 		if ((optlen == sizeof (intptr_t)) &&
1468 		    ((so->so_state & SS_DIRECT) != 0)) {
1469 			bcopy(mp->b_rptr + conn_ind->OPT_offset,
1470 			    &opt, conn_ind->OPT_length);
1471 		} else {
1472 			/*
1473 			 * The transport (in this case TCP) hasn't sent up
1474 			 * a pointer to an instance for the accept fast-path.
1475 			 * Disable fast-path completely because the call to
1476 			 * sotpi_create() below would otherwise create an
1477 			 * incomplete TCP instance, which would lead to
1478 			 * problems when sockfs sends a normal T_CONN_RES
1479 			 * message down the new stream.
1480 			 */
1481 			if (so->so_state & SS_DIRECT) {
1482 				int rval;
1483 				/*
1484 				 * For consistency we inform tcp to disable
1485 				 * direct interface on the listener, though
1486 				 * we can certainly live without doing this
1487 				 * because no data will ever travel upstream
1488 				 * on the listening socket.
1489 				 */
1490 				so->so_state &= ~SS_DIRECT;
1491 				(void) strioctl(SOTOV(so), _SIOCSOCKFALLBACK,
1492 				    0, 0, K_TO_K, CRED(), &rval);
1493 			}
1494 			opt = NULL;
1495 			optlen = 0;
1496 		}
1497 		break;
1498 	case AF_UNIX:
1499 	default:
1500 		if (optlen != 0) {
1501 			opt = sogetoff(mp, conn_ind->OPT_offset, optlen,
1502 			    __TPI_ALIGN_SIZE);
1503 			if (opt == NULL) {
1504 				error = EPROTO;
1505 				freemsg(mp);
1506 				eprintsoline(so, error);
1507 				goto disconnect_unlocked;
1508 			}
1509 		}
1510 		if (so->so_family == AF_UNIX) {
1511 			if (!(so->so_state & SS_FADDR_NOXLATE)) {
1512 				src = NULL;
1513 				srclen = 0;
1514 			}
1515 			/* Extract src address from options */
1516 			if (optlen != 0)
1517 				so_getopt_srcaddr(opt, optlen, &src, &srclen);
1518 		}
1519 		break;
1520 	}
1521 
1522 	/*
1523 	 * Create the new socket.
1524 	 */
1525 	VN_HOLD(so->so_accessvp);
1526 	nso = sotpi_create(so->so_accessvp, so->so_family, so->so_type,
1527 			so->so_protocol, so->so_version, so, &error);
1528 	if (nso == NULL) {
1529 		ASSERT(error != 0);
1530 		/*
1531 		 * Accept can not fail with ENOBUFS. sotpi_create
1532 		 * sleeps waiting for memory until a signal is caught
1533 		 * so return EINTR.
1534 		 */
1535 		freemsg(mp);
1536 		if (error == ENOBUFS)
1537 			error = EINTR;
1538 		goto e_disc_unl;
1539 	}
1540 	nvp = SOTOV(nso);
1541 
1542 	/*
1543 	 * If the transport sent up an SSL connection context, then attach
1544 	 * it the new socket, and set the (sd_wputdatafunc)() and
1545 	 * (sd_rputdatafunc)() stream head hooks to intercept and process
1546 	 * SSL records.
1547 	 */
1548 	if (ctxmp != NULL) {
1549 		/*
1550 		 * This kssl_ctx_t is already held for us by the transport.
1551 		 * So, we don't need to do a kssl_hold_ctx() here.
1552 		 */
1553 		nso->so_kssl_ctx = *((kssl_ctx_t *)ctxmp->b_rptr);
1554 		freemsg(ctxmp);
1555 		mp->b_cont = NULL;
1556 		strsetrwputdatahooks(nvp, strsock_kssl_input,
1557 		    strsock_kssl_output);
1558 	}
1559 #ifdef DEBUG
1560 	/*
1561 	 * SO_DEBUG is used to trigger the dprint* and eprint* macros thus
1562 	 * it's inherited early to allow debugging of the accept code itself.
1563 	 */
1564 	nso->so_options |= so->so_options & SO_DEBUG;
1565 #endif /* DEBUG */
1566 
1567 	/*
1568 	 * Save the SRC address from the T_CONN_IND
1569 	 * for getpeername to work on AF_UNIX and on transports that do not
1570 	 * support TI_GETPEERNAME.
1571 	 *
1572 	 * NOTE: AF_UNIX NUL termination is ensured by the sender's
1573 	 * copyin_name().
1574 	 */
1575 	if (srclen > (t_uscalar_t)nso->so_faddr_maxlen) {
1576 		error = EINVAL;
1577 		freemsg(mp);
1578 		eprintsoline(so, error);
1579 		goto disconnect_vp_unlocked;
1580 	}
1581 	nso->so_faddr_len = (socklen_t)srclen;
1582 	ASSERT(so->so_faddr_len <= so->so_faddr_maxlen);
1583 	bcopy(src, nso->so_faddr_sa, srclen);
1584 	nso->so_state |= SS_FADDR_VALID;
1585 
1586 	if ((DB_REF(mp) > 1) || MBLKSIZE(mp) <
1587 	    (sizeof (struct T_conn_res) + sizeof (intptr_t))) {
1588 		cred_t *cr;
1589 
1590 		if ((cr = DB_CRED(mp)) != NULL) {
1591 			crhold(cr);
1592 			nso->so_peercred = cr;
1593 			nso->so_cpid = DB_CPID(mp);
1594 		}
1595 		freemsg(mp);
1596 
1597 		mp = soallocproto1(NULL, sizeof (struct T_conn_res) +
1598 		    sizeof (intptr_t), 0, _ALLOC_INTR);
1599 		if (mp == NULL) {
1600 			/*
1601 			 * Accept can not fail with ENOBUFS.
1602 			 * A signal was caught so return EINTR.
1603 			 */
1604 			error = EINTR;
1605 			eprintsoline(so, error);
1606 			goto disconnect_vp_unlocked;
1607 		}
1608 		conn_res = (struct T_conn_res *)mp->b_rptr;
1609 	} else {
1610 		nso->so_peercred = DB_CRED(mp);
1611 		nso->so_cpid = DB_CPID(mp);
1612 		DB_CRED(mp) = NULL;
1613 
1614 		mp->b_rptr = DB_BASE(mp);
1615 		conn_res = (struct T_conn_res *)mp->b_rptr;
1616 		mp->b_wptr = mp->b_rptr + sizeof (struct T_conn_res);
1617 	}
1618 
1619 	/*
1620 	 * New socket must be bound at least in sockfs and, except for AF_INET,
1621 	 * (or AF_INET6) it also has to be bound in the transport provider.
1622 	 * After accepting the connection on nso so_laddr_sa will be set to
1623 	 * contain the same address as the listener's local address
1624 	 * so the address we bind to isn't important.
1625 	 */
1626 	if ((nso->so_family == AF_INET || nso->so_family == AF_INET6) &&
1627 	    /*CONSTCOND*/
1628 	    nso->so_type == SOCK_STREAM && !soaccept_tpi_tcp) {
1629 		/*
1630 		 * Optimization for AF_INET{,6} transports
1631 		 * that can handle a T_CONN_RES without being bound.
1632 		 */
1633 		mutex_enter(&nso->so_lock);
1634 		so_automatic_bind(nso);
1635 		mutex_exit(&nso->so_lock);
1636 	} else {
1637 		/* Perform NULL bind with the transport provider. */
1638 		if ((error = sotpi_bind(nso, NULL, 0, _SOBIND_UNSPEC)) != 0) {
1639 			ASSERT(error != ENOBUFS);
1640 			freemsg(mp);
1641 			eprintsoline(nso, error);
1642 			goto disconnect_vp_unlocked;
1643 		}
1644 	}
1645 
1646 	/*
1647 	 * Inherit SIOCSPGRP, SS_ASYNC before we send the {O_}T_CONN_RES
1648 	 * so that any data arriving on the new socket will cause the
1649 	 * appropriate signals to be delivered for the new socket.
1650 	 *
1651 	 * No other thread (except strsock_proto and strsock_misc)
1652 	 * can access the new socket thus we relax the locking.
1653 	 */
1654 	nso->so_pgrp = so->so_pgrp;
1655 	nso->so_state |= so->so_state & (SS_ASYNC|SS_FADDR_NOXLATE);
1656 
1657 	if (nso->so_pgrp != 0) {
1658 		if ((error = so_set_events(nso, nvp, CRED())) != 0) {
1659 			eprintsoline(nso, error);
1660 			error = 0;
1661 			nso->so_pgrp = 0;
1662 		}
1663 	}
1664 
1665 	/*
1666 	 * Make note of the socket level options. TCP and IP level options
1667 	 * are already inherited. We could do all this after accept is
1668 	 * successful but doing it here simplifies code and no harm done
1669 	 * for error case.
1670 	 */
1671 	nso->so_options = so->so_options & (SO_DEBUG|SO_REUSEADDR|SO_KEEPALIVE|
1672 	    SO_DONTROUTE|SO_BROADCAST|SO_USELOOPBACK|
1673 	    SO_OOBINLINE|SO_DGRAM_ERRIND|SO_LINGER);
1674 	nso->so_sndbuf = so->so_sndbuf;
1675 	nso->so_rcvbuf = so->so_rcvbuf;
1676 	if (nso->so_options & SO_LINGER)
1677 		nso->so_linger = so->so_linger;
1678 
1679 	if ((so->so_state & SS_DIRECT) != 0) {
1680 		mblk_t *ack_mp;
1681 
1682 		ASSERT(opt != NULL);
1683 
1684 		conn_res->OPT_length = optlen;
1685 		conn_res->OPT_offset = MBLKL(mp);
1686 		bcopy(&opt, mp->b_wptr, optlen);
1687 		mp->b_wptr += optlen;
1688 		conn_res->PRIM_type = T_CONN_RES;
1689 		conn_res->ACCEPTOR_id = 0;
1690 		PRIM_type = T_CONN_RES;
1691 
1692 		/* Send down the T_CONN_RES on acceptor STREAM */
1693 		error = kstrputmsg(SOTOV(nso), mp, NULL,
1694 		    0, 0, MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR, 0);
1695 		if (error) {
1696 			mutex_enter(&so->so_lock);
1697 			so_lock_single(so);
1698 			eprintsoline(so, error);
1699 			goto disconnect_vp;
1700 		}
1701 		mutex_enter(&nso->so_lock);
1702 		error = sowaitprim(nso, T_CONN_RES, T_OK_ACK,
1703 		    (t_uscalar_t)sizeof (struct T_ok_ack), &ack_mp, 0);
1704 		if (error) {
1705 			mutex_exit(&nso->so_lock);
1706 			mutex_enter(&so->so_lock);
1707 			so_lock_single(so);
1708 			eprintsoline(so, error);
1709 			goto disconnect_vp;
1710 		}
1711 		if (nso->so_family == AF_INET) {
1712 			sin_t *sin;
1713 
1714 			sin = (sin_t *)(ack_mp->b_rptr +
1715 			    sizeof (struct T_ok_ack));
1716 			bcopy(sin, nso->so_laddr_sa, sizeof (sin_t));
1717 			nso->so_laddr_len = sizeof (sin_t);
1718 		} else {
1719 			sin6_t *sin6;
1720 
1721 			sin6 = (sin6_t *)(ack_mp->b_rptr +
1722 			    sizeof (struct T_ok_ack));
1723 			bcopy(sin6, nso->so_laddr_sa, sizeof (sin6_t));
1724 			nso->so_laddr_len = sizeof (sin6_t);
1725 		}
1726 		freemsg(ack_mp);
1727 
1728 		nso->so_state |= SS_ISCONNECTED | SS_LADDR_VALID;
1729 		nso->so_priv = opt;
1730 
1731 		if (so->so_nl7c_flags & NL7C_ENABLED) {
1732 			/*
1733 			 * A NL7C marked listen()er so the new socket
1734 			 * inherits the listen()er's NL7C state, except
1735 			 * for NL7C_POLLIN.
1736 			 *
1737 			 * Only call NL7C to process the new socket if
1738 			 * the listen socket allows blocking i/o.
1739 			 */
1740 			nso->so_nl7c_flags = so->so_nl7c_flags & (~NL7C_POLLIN);
1741 			if (so->so_state & (SS_NONBLOCK|SS_NDELAY)) {
1742 				/*
1743 				 * Nonblocking accept() just make it
1744 				 * persist to defer processing to the
1745 				 * read-side syscall (e.g. read).
1746 				 */
1747 				nso->so_nl7c_flags |= NL7C_SOPERSIST;
1748 			} else if (nl7c_process(nso, B_FALSE)) {
1749 				/*
1750 				 * NL7C has completed processing on the
1751 				 * socket, close the socket and back to
1752 				 * the top to await the next T_CONN_IND.
1753 				 */
1754 				mutex_exit(&nso->so_lock);
1755 				(void) VOP_CLOSE(nvp, 0, 1, (offset_t)0,
1756 						CRED());
1757 				VN_RELE(nvp);
1758 				goto again;
1759 			}
1760 			/* Pass the new socket out */
1761 		}
1762 
1763 		mutex_exit(&nso->so_lock);
1764 
1765 		/*
1766 		 * It's possible, through the use of autopush for example,
1767 		 * that the acceptor stream may not support SS_DIRECT
1768 		 * semantics. If the new socket does not support SS_DIRECT
1769 		 * we issue a _SIOCSOCKFALLBACK to inform the transport
1770 		 * as we would in the I_PUSH case.
1771 		 */
1772 		if (!(nso->so_state & SS_DIRECT)) {
1773 			int	rval;
1774 
1775 			if ((error = strioctl(SOTOV(nso), _SIOCSOCKFALLBACK,
1776 			    0, 0, K_TO_K, CRED(), &rval)) != 0) {
1777 				mutex_enter(&so->so_lock);
1778 				so_lock_single(so);
1779 				eprintsoline(so, error);
1780 				goto disconnect_vp;
1781 			}
1782 		}
1783 
1784 		/*
1785 		 * Pass out new socket.
1786 		 */
1787 		if (nsop != NULL)
1788 			*nsop = nso;
1789 
1790 		return (0);
1791 	}
1792 
1793 	/*
1794 	 * Copy local address from listener.
1795 	 */
1796 	nso->so_laddr_len = so->so_laddr_len;
1797 	ASSERT(nso->so_laddr_len <= nso->so_laddr_maxlen);
1798 	bcopy(so->so_laddr_sa, nso->so_laddr_sa, nso->so_laddr_len);
1799 	nso->so_state |= SS_LADDR_VALID;
1800 
1801 	/*
1802 	 * This is the non-performance case for sockets (e.g. AF_UNIX sockets)
1803 	 * which don't support the FireEngine accept fast-path. It is also
1804 	 * used when the virtual "sockmod" has been I_POP'd and I_PUSH'd
1805 	 * again. Neither sockfs nor TCP attempt to find out if some other
1806 	 * random module has been inserted in between (in which case we
1807 	 * should follow TLI accept behaviour). We blindly assume the worst
1808 	 * case and revert back to old behaviour i.e. TCP will not send us
1809 	 * any option (eager) and the accept should happen on the listener
1810 	 * queue. Any queued T_conn_ind have already got their options removed
1811 	 * by so_sock2_stream() when "sockmod" was I_POP'd.
1812 	 */
1813 	/*
1814 	 * Fill in the {O_}T_CONN_RES before getting SOLOCKED.
1815 	 */
1816 	if ((nso->so_mode & SM_ACCEPTOR_ID) == 0) {
1817 #ifdef	_ILP32
1818 		queue_t	*q;
1819 
1820 		/*
1821 		 * Find read queue in driver
1822 		 * Can safely do this since we "own" nso/nvp.
1823 		 */
1824 		q = strvp2wq(nvp)->q_next;
1825 		while (SAMESTR(q))
1826 			q = q->q_next;
1827 		q = RD(q);
1828 		conn_res->ACCEPTOR_id = (t_uscalar_t)q;
1829 #else
1830 		conn_res->ACCEPTOR_id = (t_uscalar_t)getminor(nvp->v_rdev);
1831 #endif	/* _ILP32 */
1832 		conn_res->PRIM_type = O_T_CONN_RES;
1833 		PRIM_type = O_T_CONN_RES;
1834 	} else {
1835 		conn_res->ACCEPTOR_id = nso->so_acceptor_id;
1836 		conn_res->PRIM_type = T_CONN_RES;
1837 		PRIM_type = T_CONN_RES;
1838 	}
1839 	conn_res->SEQ_number = SEQ_number;
1840 	conn_res->OPT_length = 0;
1841 	conn_res->OPT_offset = 0;
1842 
1843 	mutex_enter(&so->so_lock);
1844 	so_lock_single(so);	/* Set SOLOCKED */
1845 	mutex_exit(&so->so_lock);
1846 
1847 	error = kstrputmsg(SOTOV(so), mp, NULL,
1848 	    0, 0, MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR, 0);
1849 	mutex_enter(&so->so_lock);
1850 	if (error) {
1851 		eprintsoline(so, error);
1852 		goto disconnect_vp;
1853 	}
1854 	error = sowaitokack(so, PRIM_type);
1855 	if (error) {
1856 		eprintsoline(so, error);
1857 		goto disconnect_vp;
1858 	}
1859 	so_unlock_single(so, SOLOCKED);
1860 	mutex_exit(&so->so_lock);
1861 
1862 	nso->so_state |= SS_ISCONNECTED;
1863 
1864 	/*
1865 	 * Pass out new socket.
1866 	 */
1867 	if (nsop != NULL)
1868 		*nsop = nso;
1869 
1870 	return (0);
1871 
1872 
1873 eproto_disc_unl:
1874 	error = EPROTO;
1875 e_disc_unl:
1876 	eprintsoline(so, error);
1877 	goto disconnect_unlocked;
1878 
1879 pr_disc_vp_unl:
1880 	eprintsoline(so, error);
1881 disconnect_vp_unlocked:
1882 	(void) VOP_CLOSE(nvp, 0, 1, 0, CRED());
1883 	VN_RELE(nvp);
1884 disconnect_unlocked:
1885 	(void) sodisconnect(so, SEQ_number, 0);
1886 	return (error);
1887 
1888 pr_disc_vp:
1889 	eprintsoline(so, error);
1890 disconnect_vp:
1891 	(void) sodisconnect(so, SEQ_number, _SODISCONNECT_LOCK_HELD);
1892 	so_unlock_single(so, SOLOCKED);
1893 	mutex_exit(&so->so_lock);
1894 	(void) VOP_CLOSE(nvp, 0, 1, 0, CRED());
1895 	VN_RELE(nvp);
1896 	return (error);
1897 
1898 conn_bad:	/* Note: SunOS 4/BSD unconditionally returns EINVAL here */
1899 	error = (so->so_type == SOCK_DGRAM || so->so_type == SOCK_RAW)
1900 	    ? EOPNOTSUPP : EINVAL;
1901 e_bad:
1902 	eprintsoline(so, error);
1903 	return (error);
1904 }
1905 
1906 /*
1907  * connect a socket.
1908  *
1909  * Allow SOCK_DGRAM sockets to reconnect (by specifying a new address) and to
1910  * unconnect (by specifying a null address).
1911  */
1912 int
1913 sotpi_connect(struct sonode *so,
1914 	const struct sockaddr *name,
1915 	socklen_t namelen,
1916 	int fflag,
1917 	int flags)
1918 {
1919 	struct T_conn_req	conn_req;
1920 	int			error = 0;
1921 	mblk_t			*mp;
1922 	void			*src;
1923 	socklen_t		srclen;
1924 	void			*addr;
1925 	socklen_t		addrlen;
1926 	boolean_t		need_unlock;
1927 
1928 	dprintso(so, 1, ("sotpi_connect(%p, %p, %d, 0x%x, 0x%x) %s\n",
1929 		so, name, namelen, fflag, flags,
1930 		pr_state(so->so_state, so->so_mode)));
1931 
1932 	/*
1933 	 * Preallocate the T_CONN_REQ mblk before grabbing SOLOCKED to
1934 	 * avoid sleeping for memory with SOLOCKED held.
1935 	 * We know that the T_CONN_REQ can't be larger than 2 * so_faddr_maxlen
1936 	 * + sizeof (struct T_opthdr).
1937 	 * (the AF_UNIX so_ux_addr_xlate() does not make the address
1938 	 * exceed so_faddr_maxlen).
1939 	 */
1940 	mp = soallocproto(sizeof (struct T_conn_req) +
1941 	    2 * so->so_faddr_maxlen + sizeof (struct T_opthdr), _ALLOC_INTR);
1942 	if (mp == NULL) {
1943 		/*
1944 		 * Connect can not fail with ENOBUFS. A signal was
1945 		 * caught so return EINTR.
1946 		 */
1947 		error = EINTR;
1948 		eprintsoline(so, error);
1949 		return (error);
1950 	}
1951 
1952 	mutex_enter(&so->so_lock);
1953 	/*
1954 	 * Make sure that there is a preallocated unbind_req
1955 	 * message before any binding. This message allocated when
1956 	 * the socket is created  but it might be have been
1957 	 * consumed.
1958 	 */
1959 	if (so->so_unbind_mp == NULL) {
1960 		dprintso(so, 1, ("sotpi_connect: allocating unbind_req\n"));
1961 		/* NOTE: holding so_lock while sleeping */
1962 		so->so_unbind_mp =
1963 		    soallocproto(sizeof (struct T_unbind_req), _ALLOC_INTR);
1964 		if (so->so_unbind_mp == NULL) {
1965 			error = EINTR;
1966 			need_unlock = B_FALSE;
1967 			goto done;
1968 		}
1969 	}
1970 
1971 	so_lock_single(so);	/* Set SOLOCKED */
1972 	need_unlock = B_TRUE;
1973 
1974 	/*
1975 	 * Can't have done a listen before connecting.
1976 	 */
1977 	if (so->so_state & SS_ACCEPTCONN) {
1978 		error = EOPNOTSUPP;
1979 		goto done;
1980 	}
1981 
1982 	/*
1983 	 * Must be bound with the transport
1984 	 */
1985 	if (!(so->so_state & SS_ISBOUND)) {
1986 		if ((so->so_family == AF_INET || so->so_family == AF_INET6) &&
1987 		    /*CONSTCOND*/
1988 		    so->so_type == SOCK_STREAM && !soconnect_tpi_tcp) {
1989 			/*
1990 			 * Optimization for AF_INET{,6} transports
1991 			 * that can handle a T_CONN_REQ without being bound.
1992 			 */
1993 			so_automatic_bind(so);
1994 		} else {
1995 			error = sotpi_bind(so, NULL, 0,
1996 			    _SOBIND_UNSPEC|_SOBIND_LOCK_HELD);
1997 			if (error)
1998 				goto done;
1999 		}
2000 		ASSERT(so->so_state & SS_ISBOUND);
2001 		flags |= _SOCONNECT_DID_BIND;
2002 	}
2003 
2004 	/*
2005 	 * Handle a connect to a name parameter of type AF_UNSPEC like a
2006 	 * connect to a null address. This is the portable method to
2007 	 * unconnect a socket.
2008 	 */
2009 	if ((namelen >= sizeof (sa_family_t)) &&
2010 	    (name->sa_family == AF_UNSPEC)) {
2011 		name = NULL;
2012 		namelen = 0;
2013 	}
2014 
2015 	/*
2016 	 * Check that we are not already connected.
2017 	 * A connection-oriented socket cannot be reconnected.
2018 	 * A connected connection-less socket can be
2019 	 * - connected to a different address by a subsequent connect
2020 	 * - "unconnected" by a connect to the NULL address
2021 	 */
2022 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) {
2023 		ASSERT(!(flags & _SOCONNECT_DID_BIND));
2024 		if (so->so_mode & SM_CONNREQUIRED) {
2025 			/* Connection-oriented socket */
2026 			error = so->so_state & SS_ISCONNECTED ?
2027 			    EISCONN : EALREADY;
2028 			goto done;
2029 		}
2030 		/* Connection-less socket */
2031 		if (name == NULL) {
2032 			/*
2033 			 * Remove the connected state and clear SO_DGRAM_ERRIND
2034 			 * since it was set when the socket was connected.
2035 			 * If this is UDP also send down a T_DISCON_REQ.
2036 			 */
2037 			int val;
2038 
2039 			if ((so->so_family == AF_INET ||
2040 				so->so_family == AF_INET6) &&
2041 			    (so->so_type == SOCK_DGRAM ||
2042 				so->so_type == SOCK_RAW) &&
2043 			    /*CONSTCOND*/
2044 			    !soconnect_tpi_udp) {
2045 				/* XXX What about implicitly unbinding here? */
2046 				error = sodisconnect(so, -1,
2047 						_SODISCONNECT_LOCK_HELD);
2048 			} else {
2049 				so->so_state &=
2050 				    ~(SS_ISCONNECTED | SS_ISCONNECTING |
2051 				    SS_FADDR_VALID);
2052 				so->so_faddr_len = 0;
2053 			}
2054 
2055 			so_unlock_single(so, SOLOCKED);
2056 			mutex_exit(&so->so_lock);
2057 
2058 			val = 0;
2059 			(void) sotpi_setsockopt(so, SOL_SOCKET, SO_DGRAM_ERRIND,
2060 					&val, (t_uscalar_t)sizeof (val));
2061 
2062 			mutex_enter(&so->so_lock);
2063 			so_lock_single(so);	/* Set SOLOCKED */
2064 			goto done;
2065 		}
2066 	}
2067 	ASSERT(so->so_state & SS_ISBOUND);
2068 
2069 	if (name == NULL || namelen == 0) {
2070 		error = EINVAL;
2071 		goto done;
2072 	}
2073 	/*
2074 	 * Mark the socket if so_faddr_sa represents the transport level
2075 	 * address.
2076 	 */
2077 	if (flags & _SOCONNECT_NOXLATE) {
2078 		struct sockaddr_ux	*soaddr_ux;
2079 
2080 		ASSERT(so->so_family == AF_UNIX);
2081 		if (namelen != sizeof (struct sockaddr_ux)) {
2082 			error = EINVAL;
2083 			goto done;
2084 		}
2085 		soaddr_ux = (struct sockaddr_ux *)name;
2086 		name = (struct sockaddr *)&soaddr_ux->sou_addr;
2087 		namelen = sizeof (soaddr_ux->sou_addr);
2088 		so->so_state |= SS_FADDR_NOXLATE;
2089 	}
2090 
2091 	/*
2092 	 * Length and family checks.
2093 	 */
2094 	error = so_addr_verify(so, name, namelen);
2095 	if (error)
2096 		goto bad;
2097 
2098 	/*
2099 	 * Save foreign address. Needed for AF_UNIX as well as
2100 	 * transport providers that do not support TI_GETPEERNAME.
2101 	 * Also used for cached foreign address for TCP and UDP.
2102 	 */
2103 	if (namelen > (t_uscalar_t)so->so_faddr_maxlen) {
2104 		error = EINVAL;
2105 		goto done;
2106 	}
2107 	so->so_faddr_len = (socklen_t)namelen;
2108 	ASSERT(so->so_faddr_len <= so->so_faddr_maxlen);
2109 	bcopy(name, so->so_faddr_sa, namelen);
2110 	so->so_state |= SS_FADDR_VALID;
2111 
2112 	if (so->so_family == AF_UNIX) {
2113 		if (so->so_state & SS_FADDR_NOXLATE) {
2114 			/*
2115 			 * Already have a transport internal address. Do not
2116 			 * pass any (transport internal) source address.
2117 			 */
2118 			addr = so->so_faddr_sa;
2119 			addrlen = (t_uscalar_t)so->so_faddr_len;
2120 			src = NULL;
2121 			srclen = 0;
2122 		} else {
2123 			/*
2124 			 * Pass the sockaddr_un source address as an option
2125 			 * and translate the remote address.
2126 			 * Holding so_lock thus so_laddr_sa can not change.
2127 			 */
2128 			src = so->so_laddr_sa;
2129 			srclen = (t_uscalar_t)so->so_laddr_len;
2130 			dprintso(so, 1,
2131 				("sotpi_connect UNIX: srclen %d, src %p\n",
2132 				srclen, src));
2133 			error = so_ux_addr_xlate(so,
2134 				so->so_faddr_sa, (socklen_t)so->so_faddr_len,
2135 				(flags & _SOCONNECT_XPG4_2),
2136 				&addr, &addrlen);
2137 			if (error)
2138 				goto bad;
2139 		}
2140 	} else {
2141 		addr = so->so_faddr_sa;
2142 		addrlen = (t_uscalar_t)so->so_faddr_len;
2143 		src = NULL;
2144 		srclen = 0;
2145 	}
2146 	/*
2147 	 * When connecting a datagram socket we issue the SO_DGRAM_ERRIND
2148 	 * option which asks the transport provider to send T_UDERR_IND
2149 	 * messages. These T_UDERR_IND messages are used to return connected
2150 	 * style errors (e.g. ECONNRESET) for connected datagram sockets.
2151 	 *
2152 	 * In addition, for UDP (and SOCK_RAW AF_INET{,6} sockets)
2153 	 * we send down a T_CONN_REQ. This is needed to let the
2154 	 * transport assign a local address that is consistent with
2155 	 * the remote address. Applications depend on a getsockname()
2156 	 * after a connect() to retrieve the "source" IP address for
2157 	 * the connected socket.  Invalidate the cached local address
2158 	 * to force getsockname() to enquire of the transport.
2159 	 */
2160 	if (!(so->so_mode & SM_CONNREQUIRED)) {
2161 		/*
2162 		 * Datagram socket.
2163 		 */
2164 		int32_t val;
2165 
2166 		so_unlock_single(so, SOLOCKED);
2167 		mutex_exit(&so->so_lock);
2168 
2169 		val = 1;
2170 		(void) sotpi_setsockopt(so, SOL_SOCKET, SO_DGRAM_ERRIND,
2171 					&val, (t_uscalar_t)sizeof (val));
2172 
2173 		mutex_enter(&so->so_lock);
2174 		so_lock_single(so);	/* Set SOLOCKED */
2175 		if ((so->so_family != AF_INET && so->so_family != AF_INET6) ||
2176 		    (so->so_type != SOCK_DGRAM && so->so_type != SOCK_RAW) ||
2177 		    soconnect_tpi_udp) {
2178 			soisconnected(so);
2179 			goto done;
2180 		}
2181 		/*
2182 		 * Send down T_CONN_REQ etc.
2183 		 * Clear fflag to avoid returning EWOULDBLOCK.
2184 		 */
2185 		fflag = 0;
2186 		ASSERT(so->so_family != AF_UNIX);
2187 		so->so_state &= ~SS_LADDR_VALID;
2188 	} else if (so->so_laddr_len != 0) {
2189 		/*
2190 		 * If the local address or port was "any" then it may be
2191 		 * changed by the transport as a result of the
2192 		 * connect.  Invalidate the cached version if we have one.
2193 		 */
2194 		switch (so->so_family) {
2195 		case AF_INET:
2196 			ASSERT(so->so_laddr_len == (socklen_t)sizeof (sin_t));
2197 			if (((sin_t *)so->so_laddr_sa)->sin_addr.s_addr ==
2198 			    INADDR_ANY ||
2199 			    ((sin_t *)so->so_laddr_sa)->sin_port == 0)
2200 				so->so_state &= ~SS_LADDR_VALID;
2201 			break;
2202 
2203 		case AF_INET6:
2204 			ASSERT(so->so_laddr_len == (socklen_t)sizeof (sin6_t));
2205 			if (IN6_IS_ADDR_UNSPECIFIED(
2206 			    &((sin6_t *)so->so_laddr_sa) ->sin6_addr) ||
2207 			    IN6_IS_ADDR_V4MAPPED_ANY(
2208 			    &((sin6_t *)so->so_laddr_sa)->sin6_addr) ||
2209 			    ((sin6_t *)so->so_laddr_sa)->sin6_port == 0)
2210 				    so->so_state &= ~SS_LADDR_VALID;
2211 			break;
2212 
2213 		default:
2214 			break;
2215 		}
2216 	}
2217 
2218 	/*
2219 	 * Check for failure of an earlier call
2220 	 */
2221 	if (so->so_error != 0)
2222 		goto so_bad;
2223 
2224 	/*
2225 	 * Send down T_CONN_REQ. Message was allocated above.
2226 	 */
2227 	conn_req.PRIM_type = T_CONN_REQ;
2228 	conn_req.DEST_length = addrlen;
2229 	conn_req.DEST_offset = (t_scalar_t)sizeof (conn_req);
2230 	if (srclen == 0) {
2231 		conn_req.OPT_length = 0;
2232 		conn_req.OPT_offset = 0;
2233 		soappendmsg(mp, &conn_req, sizeof (conn_req));
2234 		soappendmsg(mp, addr, addrlen);
2235 	} else {
2236 		/*
2237 		 * There is a AF_UNIX sockaddr_un to include as a source
2238 		 * address option.
2239 		 */
2240 		struct T_opthdr toh;
2241 
2242 		toh.level = SOL_SOCKET;
2243 		toh.name = SO_SRCADDR;
2244 		toh.len = (t_uscalar_t)(srclen + sizeof (struct T_opthdr));
2245 		toh.status = 0;
2246 		conn_req.OPT_length =
2247 			(t_scalar_t)(sizeof (toh) + _TPI_ALIGN_TOPT(srclen));
2248 		conn_req.OPT_offset = (t_scalar_t)(sizeof (conn_req) +
2249 			_TPI_ALIGN_TOPT(addrlen));
2250 
2251 		soappendmsg(mp, &conn_req, sizeof (conn_req));
2252 		soappendmsg(mp, addr, addrlen);
2253 		mp->b_wptr += _TPI_ALIGN_TOPT(addrlen) - addrlen;
2254 		soappendmsg(mp, &toh, sizeof (toh));
2255 		soappendmsg(mp, src, srclen);
2256 		mp->b_wptr += _TPI_ALIGN_TOPT(srclen) - srclen;
2257 		ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
2258 	}
2259 	/*
2260 	 * Set SS_ISCONNECTING before sending down the T_CONN_REQ
2261 	 * in order to have the right state when the T_CONN_CON shows up.
2262 	 */
2263 	soisconnecting(so);
2264 	mutex_exit(&so->so_lock);
2265 
2266 #ifdef C2_AUDIT
2267 	if (audit_active)
2268 		audit_sock(T_CONN_REQ, strvp2wq(SOTOV(so)), mp, 0);
2269 #endif /* C2_AUDIT */
2270 
2271 	error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
2272 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR, 0);
2273 	mp = NULL;
2274 	mutex_enter(&so->so_lock);
2275 	if (error != 0)
2276 		goto bad;
2277 
2278 	if ((error = sowaitokack(so, T_CONN_REQ)) != 0)
2279 		goto bad;
2280 
2281 	/* Allow other threads to access the socket */
2282 	so_unlock_single(so, SOLOCKED);
2283 	need_unlock = B_FALSE;
2284 
2285 	/*
2286 	 * Wait until we get a T_CONN_CON or an error
2287 	 */
2288 	if ((error = sowaitconnected(so, fflag, 0)) != 0) {
2289 		so_lock_single(so);	/* Set SOLOCKED */
2290 		need_unlock = B_TRUE;
2291 	}
2292 
2293 done:
2294 	freemsg(mp);
2295 	switch (error) {
2296 	case EINPROGRESS:
2297 	case EALREADY:
2298 	case EISCONN:
2299 	case EINTR:
2300 		/* Non-fatal errors */
2301 		so->so_state &= ~SS_LADDR_VALID;
2302 		/* FALLTHRU */
2303 	case 0:
2304 		break;
2305 
2306 	case EHOSTUNREACH:
2307 		if (flags & _SOCONNECT_XPG4_2) {
2308 			/*
2309 			 * X/Open specification contains a requirement that
2310 			 * ENETUNREACH be returned but does not require
2311 			 * EHOSTUNREACH. In order to keep the test suite
2312 			 * happy we mess with the errno here.
2313 			 */
2314 			error = ENETUNREACH;
2315 		}
2316 		/* FALLTHRU */
2317 
2318 	default:
2319 		ASSERT(need_unlock);
2320 		/*
2321 		 * Fatal errors: clear SS_ISCONNECTING in case it was set,
2322 		 * and invalidate local-address cache
2323 		 */
2324 		so->so_state &= ~(SS_ISCONNECTING | SS_LADDR_VALID);
2325 		/* A discon_ind might have already unbound us */
2326 		if ((flags & _SOCONNECT_DID_BIND) &&
2327 		    (so->so_state & SS_ISBOUND)) {
2328 			int err;
2329 
2330 			err = sotpi_unbind(so, 0);
2331 			/* LINTED - statement has no conseq */
2332 			if (err) {
2333 				eprintsoline(so, err);
2334 			}
2335 		}
2336 		break;
2337 	}
2338 	if (need_unlock)
2339 		so_unlock_single(so, SOLOCKED);
2340 	mutex_exit(&so->so_lock);
2341 	return (error);
2342 
2343 so_bad:	error = sogeterr(so);
2344 bad:	eprintsoline(so, error);
2345 	goto done;
2346 }
2347 
2348 int
2349 sotpi_shutdown(struct sonode *so, int how)
2350 {
2351 	struct T_ordrel_req	ordrel_req;
2352 	mblk_t			*mp;
2353 	uint_t			old_state, state_change;
2354 	int			error = 0;
2355 
2356 	dprintso(so, 1, ("sotpi_shutdown(%p, %d) %s\n",
2357 		so, how, pr_state(so->so_state, so->so_mode)));
2358 
2359 	mutex_enter(&so->so_lock);
2360 	so_lock_single(so);	/* Set SOLOCKED */
2361 
2362 	/*
2363 	 * SunOS 4.X has no check for datagram sockets.
2364 	 * 5.X checks that it is connected (ENOTCONN)
2365 	 * X/Open requires that we check the connected state.
2366 	 */
2367 	if (!(so->so_state & SS_ISCONNECTED)) {
2368 		if (!xnet_skip_checks) {
2369 			error = ENOTCONN;
2370 			if (xnet_check_print) {
2371 				printf("sockfs: X/Open shutdown check "
2372 					"caused ENOTCONN\n");
2373 			}
2374 		}
2375 		goto done;
2376 	}
2377 	/*
2378 	 * Record the current state and then perform any state changes.
2379 	 * Then use the difference between the old and new states to
2380 	 * determine which messages need to be sent.
2381 	 * This prevents e.g. duplicate T_ORDREL_REQ when there are
2382 	 * duplicate calls to shutdown().
2383 	 */
2384 	old_state = so->so_state;
2385 
2386 	switch (how) {
2387 	case 0:
2388 		socantrcvmore(so);
2389 		break;
2390 	case 1:
2391 		socantsendmore(so);
2392 		break;
2393 	case 2:
2394 		socantsendmore(so);
2395 		socantrcvmore(so);
2396 		break;
2397 	default:
2398 		error = EINVAL;
2399 		goto done;
2400 	}
2401 
2402 	/*
2403 	 * Assumes that the SS_CANT* flags are never cleared in the above code.
2404 	 */
2405 	state_change = (so->so_state & (SS_CANTRCVMORE|SS_CANTSENDMORE)) -
2406 		(old_state & (SS_CANTRCVMORE|SS_CANTSENDMORE));
2407 	ASSERT((state_change & ~(SS_CANTRCVMORE|SS_CANTSENDMORE)) == 0);
2408 
2409 	switch (state_change) {
2410 	case 0:
2411 		dprintso(so, 1,
2412 		    ("sotpi_shutdown: nothing to send in state 0x%x\n",
2413 		    so->so_state));
2414 		goto done;
2415 
2416 	case SS_CANTRCVMORE:
2417 		mutex_exit(&so->so_lock);
2418 		strseteof(SOTOV(so), 1);
2419 		/*
2420 		 * strseteof takes care of read side wakeups,
2421 		 * pollwakeups, and signals.
2422 		 */
2423 		/*
2424 		 * Get the read lock before flushing data to avoid problems
2425 		 * with the T_EXDATA_IND MSG_PEEK code in sotpi_recvmsg.
2426 		 */
2427 		mutex_enter(&so->so_lock);
2428 		(void) so_lock_read(so, 0);	/* Set SOREADLOCKED */
2429 		mutex_exit(&so->so_lock);
2430 
2431 		/* Flush read side queue */
2432 		strflushrq(SOTOV(so), FLUSHALL);
2433 
2434 		mutex_enter(&so->so_lock);
2435 		so_unlock_read(so);		/* Clear SOREADLOCKED */
2436 		break;
2437 
2438 	case SS_CANTSENDMORE:
2439 		mutex_exit(&so->so_lock);
2440 		strsetwerror(SOTOV(so), 0, 0, sogetwrerr);
2441 		mutex_enter(&so->so_lock);
2442 		break;
2443 
2444 	case SS_CANTSENDMORE|SS_CANTRCVMORE:
2445 		mutex_exit(&so->so_lock);
2446 		strsetwerror(SOTOV(so), 0, 0, sogetwrerr);
2447 		strseteof(SOTOV(so), 1);
2448 		/*
2449 		 * strseteof takes care of read side wakeups,
2450 		 * pollwakeups, and signals.
2451 		 */
2452 		/*
2453 		 * Get the read lock before flushing data to avoid problems
2454 		 * with the T_EXDATA_IND MSG_PEEK code in sotpi_recvmsg.
2455 		 */
2456 		mutex_enter(&so->so_lock);
2457 		(void) so_lock_read(so, 0);	/* Set SOREADLOCKED */
2458 		mutex_exit(&so->so_lock);
2459 
2460 		/* Flush read side queue */
2461 		strflushrq(SOTOV(so), FLUSHALL);
2462 
2463 		mutex_enter(&so->so_lock);
2464 		so_unlock_read(so);		/* Clear SOREADLOCKED */
2465 		break;
2466 	}
2467 
2468 	ASSERT(MUTEX_HELD(&so->so_lock));
2469 
2470 	/*
2471 	 * If either SS_CANTSENDMORE or SS_CANTRCVMORE or both of them
2472 	 * was set due to this call and the new state has both of them set:
2473 	 *	Send the AF_UNIX close indication
2474 	 *	For T_COTS send a discon_ind
2475 	 *
2476 	 * If cantsend was set due to this call:
2477 	 *	For T_COTSORD send an ordrel_ind
2478 	 *
2479 	 * Note that for T_CLTS there is no message sent here.
2480 	 */
2481 	if ((so->so_state & (SS_CANTRCVMORE|SS_CANTSENDMORE)) ==
2482 	    (SS_CANTRCVMORE|SS_CANTSENDMORE)) {
2483 		/*
2484 		 * For SunOS 4.X compatibility we tell the other end
2485 		 * that we are unable to receive at this point.
2486 		 */
2487 		if (so->so_family == AF_UNIX && so->so_serv_type != T_CLTS)
2488 			so_unix_close(so);
2489 
2490 		if (so->so_serv_type == T_COTS)
2491 			error = sodisconnect(so, -1, _SODISCONNECT_LOCK_HELD);
2492 	}
2493 	if ((state_change & SS_CANTSENDMORE) &&
2494 	    (so->so_serv_type == T_COTS_ORD)) {
2495 		/* Send an orderly release */
2496 		ordrel_req.PRIM_type = T_ORDREL_REQ;
2497 
2498 		mutex_exit(&so->so_lock);
2499 		mp = soallocproto1(&ordrel_req, sizeof (ordrel_req),
2500 		    0, _ALLOC_SLEEP);
2501 		/*
2502 		 * Send down the T_ORDREL_REQ even if there is flow control.
2503 		 * This prevents shutdown from blocking.
2504 		 * Note that there is no T_OK_ACK for ordrel_req.
2505 		 */
2506 		error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
2507 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR|MSG_IGNFLOW, 0);
2508 		mutex_enter(&so->so_lock);
2509 		if (error) {
2510 			eprintsoline(so, error);
2511 			goto done;
2512 		}
2513 	}
2514 
2515 done:
2516 	so_unlock_single(so, SOLOCKED);
2517 	mutex_exit(&so->so_lock);
2518 	return (error);
2519 }
2520 
2521 /*
2522  * For any connected SOCK_STREAM/SOCK_SEQPACKET AF_UNIX socket we send
2523  * a zero-length T_OPTDATA_REQ with the SO_UNIX_CLOSE option to inform the peer
2524  * that we have closed.
2525  * Also, for connected AF_UNIX SOCK_DGRAM sockets we send a zero-length
2526  * T_UNITDATA_REQ containing the same option.
2527  *
2528  * For SOCK_DGRAM half-connections (somebody connected to this end
2529  * but this end is not connect) we don't know where to send any
2530  * SO_UNIX_CLOSE.
2531  *
2532  * We have to ignore stream head errors just in case there has been
2533  * a shutdown(output).
2534  * Ignore any flow control to try to get the message more quickly to the peer.
2535  * While locally ignoring flow control solves the problem when there
2536  * is only the loopback transport on the stream it would not provide
2537  * the correct AF_UNIX socket semantics when one or more modules have
2538  * been pushed.
2539  */
2540 void
2541 so_unix_close(struct sonode *so)
2542 {
2543 	int		error;
2544 	struct T_opthdr	toh;
2545 	mblk_t		*mp;
2546 
2547 	ASSERT(MUTEX_HELD(&so->so_lock));
2548 
2549 	ASSERT(so->so_family == AF_UNIX);
2550 
2551 	if ((so->so_state & (SS_ISCONNECTED|SS_ISBOUND)) !=
2552 	    (SS_ISCONNECTED|SS_ISBOUND))
2553 		return;
2554 
2555 	dprintso(so, 1, ("so_unix_close(%p) %s\n",
2556 		so, pr_state(so->so_state, so->so_mode)));
2557 
2558 	toh.level = SOL_SOCKET;
2559 	toh.name = SO_UNIX_CLOSE;
2560 
2561 	/* zero length + header */
2562 	toh.len = (t_uscalar_t)sizeof (struct T_opthdr);
2563 	toh.status = 0;
2564 
2565 	if (so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET) {
2566 		struct T_optdata_req tdr;
2567 
2568 		tdr.PRIM_type = T_OPTDATA_REQ;
2569 		tdr.DATA_flag = 0;
2570 
2571 		tdr.OPT_length = (t_scalar_t)sizeof (toh);
2572 		tdr.OPT_offset = (t_scalar_t)sizeof (tdr);
2573 
2574 		/* NOTE: holding so_lock while sleeping */
2575 		mp = soallocproto2(&tdr, sizeof (tdr),
2576 		    &toh, sizeof (toh), 0, _ALLOC_SLEEP);
2577 	} else {
2578 		struct T_unitdata_req	tudr;
2579 		void			*addr;
2580 		socklen_t		addrlen;
2581 		void			*src;
2582 		socklen_t		srclen;
2583 		struct T_opthdr		toh2;
2584 		t_scalar_t		size;
2585 
2586 		/* Connecteded DGRAM socket */
2587 
2588 		/*
2589 		 * For AF_UNIX the destination address is translated to
2590 		 * an internal name and the source address is passed as
2591 		 * an option.
2592 		 */
2593 		/*
2594 		 * Length and family checks.
2595 		 */
2596 		error = so_addr_verify(so, so->so_faddr_sa,
2597 					(t_uscalar_t)so->so_faddr_len);
2598 		if (error) {
2599 			eprintsoline(so, error);
2600 			return;
2601 		}
2602 		if (so->so_state & SS_FADDR_NOXLATE) {
2603 			/*
2604 			 * Already have a transport internal address. Do not
2605 			 * pass any (transport internal) source address.
2606 			 */
2607 			addr = so->so_faddr_sa;
2608 			addrlen = (t_uscalar_t)so->so_faddr_len;
2609 			src = NULL;
2610 			srclen = 0;
2611 		} else {
2612 			/*
2613 			 * Pass the sockaddr_un source address as an option
2614 			 * and translate the remote address.
2615 			 * Holding so_lock thus so_laddr_sa can not change.
2616 			 */
2617 			src = so->so_laddr_sa;
2618 			srclen = (socklen_t)so->so_laddr_len;
2619 			dprintso(so, 1,
2620 				("so_ux_close: srclen %d, src %p\n",
2621 				srclen, src));
2622 			error = so_ux_addr_xlate(so,
2623 				so->so_faddr_sa,
2624 				(socklen_t)so->so_faddr_len, 0,
2625 				&addr, &addrlen);
2626 			if (error) {
2627 				eprintsoline(so, error);
2628 				return;
2629 			}
2630 		}
2631 		tudr.PRIM_type = T_UNITDATA_REQ;
2632 		tudr.DEST_length = addrlen;
2633 		tudr.DEST_offset = (t_scalar_t)sizeof (tudr);
2634 		if (srclen == 0) {
2635 			tudr.OPT_length = (t_scalar_t)sizeof (toh);
2636 			tudr.OPT_offset = (t_scalar_t)(sizeof (tudr) +
2637 				_TPI_ALIGN_TOPT(addrlen));
2638 
2639 			size = tudr.OPT_offset + tudr.OPT_length;
2640 			/* NOTE: holding so_lock while sleeping */
2641 			mp = soallocproto2(&tudr, sizeof (tudr),
2642 			    addr, addrlen, size, _ALLOC_SLEEP);
2643 			mp->b_wptr += (_TPI_ALIGN_TOPT(addrlen) - addrlen);
2644 			soappendmsg(mp, &toh, sizeof (toh));
2645 		} else {
2646 			/*
2647 			 * There is a AF_UNIX sockaddr_un to include as a
2648 			 * source address option.
2649 			 */
2650 			tudr.OPT_length = (t_scalar_t)(2 * sizeof (toh) +
2651 			    _TPI_ALIGN_TOPT(srclen));
2652 			tudr.OPT_offset = (t_scalar_t)(sizeof (tudr) +
2653 			    _TPI_ALIGN_TOPT(addrlen));
2654 
2655 			toh2.level = SOL_SOCKET;
2656 			toh2.name = SO_SRCADDR;
2657 			toh2.len = (t_uscalar_t)(srclen +
2658 					sizeof (struct T_opthdr));
2659 			toh2.status = 0;
2660 
2661 			size = tudr.OPT_offset + tudr.OPT_length;
2662 
2663 			/* NOTE: holding so_lock while sleeping */
2664 			mp = soallocproto2(&tudr, sizeof (tudr),
2665 			    addr, addrlen, size, _ALLOC_SLEEP);
2666 			mp->b_wptr += _TPI_ALIGN_TOPT(addrlen) - addrlen;
2667 			soappendmsg(mp, &toh, sizeof (toh));
2668 			soappendmsg(mp, &toh2, sizeof (toh2));
2669 			soappendmsg(mp, src, srclen);
2670 			mp->b_wptr += _TPI_ALIGN_TOPT(srclen) - srclen;
2671 		}
2672 		ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
2673 	}
2674 	mutex_exit(&so->so_lock);
2675 	error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
2676 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR|MSG_IGNFLOW, 0);
2677 	mutex_enter(&so->so_lock);
2678 }
2679 
2680 /*
2681  * Handle recv* calls that set MSG_OOB or MSG_OOB together with MSG_PEEK.
2682  */
2683 int
2684 sorecvoob(struct sonode *so, struct nmsghdr *msg, struct uio *uiop, int flags)
2685 {
2686 	mblk_t		*mp, *nmp;
2687 	int		error;
2688 
2689 	dprintso(so, 1, ("sorecvoob(%p, %p, 0x%x)\n", so, msg, flags));
2690 
2691 	/*
2692 	 * There is never any oob data with addresses or control since
2693 	 * the T_EXDATA_IND does not carry any options.
2694 	 */
2695 	msg->msg_controllen = 0;
2696 	msg->msg_namelen = 0;
2697 
2698 	mutex_enter(&so->so_lock);
2699 	ASSERT(so_verify_oobstate(so));
2700 	if ((so->so_options & SO_OOBINLINE) ||
2701 	    (so->so_state & (SS_OOBPEND|SS_HADOOBDATA)) != SS_OOBPEND) {
2702 		dprintso(so, 1, ("sorecvoob: inline or data consumed\n"));
2703 		mutex_exit(&so->so_lock);
2704 		return (EINVAL);
2705 	}
2706 	if (!(so->so_state & SS_HAVEOOBDATA)) {
2707 		dprintso(so, 1, ("sorecvoob: no data yet\n"));
2708 		mutex_exit(&so->so_lock);
2709 		return (EWOULDBLOCK);
2710 	}
2711 	ASSERT(so->so_oobmsg != NULL);
2712 	mp = so->so_oobmsg;
2713 	if (flags & MSG_PEEK) {
2714 		/*
2715 		 * Since recv* can not return ENOBUFS we can not use dupmsg.
2716 		 * Instead we revert to the consolidation private
2717 		 * allocb_wait plus bcopy.
2718 		 */
2719 		mblk_t *mp1;
2720 
2721 		mp1 = allocb_wait(msgdsize(mp), BPRI_MED, STR_NOSIG, NULL);
2722 		ASSERT(mp1);
2723 
2724 		while (mp != NULL) {
2725 			ssize_t size;
2726 
2727 			size = MBLKL(mp);
2728 			bcopy(mp->b_rptr, mp1->b_wptr, size);
2729 			mp1->b_wptr += size;
2730 			ASSERT(mp1->b_wptr <= mp1->b_datap->db_lim);
2731 			mp = mp->b_cont;
2732 		}
2733 		mp = mp1;
2734 	} else {
2735 		/*
2736 		 * Update the state indicating that the data has been consumed.
2737 		 * Keep SS_OOBPEND set until data is consumed past the mark.
2738 		 */
2739 		so->so_oobmsg = NULL;
2740 		so->so_state ^= SS_HAVEOOBDATA|SS_HADOOBDATA;
2741 	}
2742 	dprintso(so, 1,
2743 		("after recvoob(%p): counts %d/%d state %s\n",
2744 		so, so->so_oobsigcnt,
2745 		so->so_oobcnt, pr_state(so->so_state, so->so_mode)));
2746 	ASSERT(so_verify_oobstate(so));
2747 	mutex_exit(&so->so_lock);
2748 
2749 	error = 0;
2750 	nmp = mp;
2751 	while (nmp != NULL && uiop->uio_resid > 0) {
2752 		ssize_t n = MBLKL(nmp);
2753 
2754 		n = MIN(n, uiop->uio_resid);
2755 		if (n > 0)
2756 			error = uiomove(nmp->b_rptr, n,
2757 					UIO_READ, uiop);
2758 		if (error)
2759 			break;
2760 		nmp = nmp->b_cont;
2761 	}
2762 	freemsg(mp);
2763 	return (error);
2764 }
2765 
2766 /*
2767  * Called by sotpi_recvmsg when reading a non-zero amount of data.
2768  * In addition, the caller typically verifies that there is some
2769  * potential state to clear by checking
2770  *	if (so->so_state & (SS_OOBPEND|SS_HAVEOOBDATA|SS_RCVATMARK))
2771  * before calling this routine.
2772  * Note that such a check can be made without holding so_lock since
2773  * sotpi_recvmsg is single-threaded (using SOREADLOCKED) and only sotpi_recvmsg
2774  * decrements so_oobsigcnt.
2775  *
2776  * When data is read *after* the point that all pending
2777  * oob data has been consumed the oob indication is cleared.
2778  *
2779  * This logic keeps select/poll returning POLLRDBAND and
2780  * SIOCATMARK returning true until we have read past
2781  * the mark.
2782  */
2783 static void
2784 sorecv_update_oobstate(struct sonode *so)
2785 {
2786 	mutex_enter(&so->so_lock);
2787 	ASSERT(so_verify_oobstate(so));
2788 	dprintso(so, 1,
2789 		("sorecv_update_oobstate: counts %d/%d state %s\n",
2790 		so->so_oobsigcnt,
2791 		so->so_oobcnt, pr_state(so->so_state, so->so_mode)));
2792 	if (so->so_oobsigcnt == 0) {
2793 		/* No more pending oob indications */
2794 		so->so_state &= ~(SS_OOBPEND|SS_HAVEOOBDATA|SS_RCVATMARK);
2795 		freemsg(so->so_oobmsg);
2796 		so->so_oobmsg = NULL;
2797 	}
2798 	ASSERT(so_verify_oobstate(so));
2799 	mutex_exit(&so->so_lock);
2800 }
2801 
2802 /*
2803  * Handle recv* calls for an so which has NL7C saved recv mblk_t(s).
2804  */
2805 static int
2806 nl7c_sorecv(struct sonode *so, mblk_t **rmp, uio_t *uiop, rval_t *rp)
2807 {
2808 	int	error = 0;
2809 	mblk_t *tmp = NULL;
2810 	mblk_t *pmp = NULL;
2811 	mblk_t *nmp = so->so_nl7c_rcv_mp;
2812 
2813 	ASSERT(nmp != NULL);
2814 
2815 	while (nmp != NULL && uiop->uio_resid > 0) {
2816 		ssize_t n;
2817 
2818 		if (DB_TYPE(nmp) == M_DATA) {
2819 			/*
2820 			 * We have some data, uiomove up to resid bytes.
2821 			 */
2822 			n = MIN(MBLKL(nmp), uiop->uio_resid);
2823 			if (n > 0)
2824 				error = uiomove(nmp->b_rptr, n, UIO_READ, uiop);
2825 			nmp->b_rptr += n;
2826 			if (nmp->b_rptr == nmp->b_wptr) {
2827 				pmp = nmp;
2828 				nmp = nmp->b_cont;
2829 			}
2830 			if (error)
2831 				break;
2832 		} else {
2833 			/*
2834 			 * We only handle data, save for caller to handle.
2835 			 */
2836 			if (pmp != NULL) {
2837 				pmp->b_cont = nmp->b_cont;
2838 			}
2839 			nmp->b_cont = NULL;
2840 			if (*rmp == NULL) {
2841 				*rmp = nmp;
2842 			} else {
2843 				tmp->b_cont = nmp;
2844 			}
2845 			nmp = nmp->b_cont;
2846 			tmp = nmp;
2847 		}
2848 	}
2849 	if (pmp != NULL) {
2850 		/* Free any mblk_t(s) which we have consumed */
2851 		pmp->b_cont = NULL;
2852 		freemsg(so->so_nl7c_rcv_mp);
2853 	}
2854 	if ((so->so_nl7c_rcv_mp = nmp) == NULL) {
2855 		/* Last mblk_t so return the saved kstrgetmsg() rval/error */
2856 		if (error == 0) {
2857 			rval_t	*p = (rval_t *)&so->so_nl7c_rcv_rval;
2858 
2859 			error = p->r_v.r_v2;
2860 			p->r_v.r_v2 = 0;
2861 		}
2862 		rp->r_vals = so->so_nl7c_rcv_rval;
2863 		so->so_nl7c_rcv_rval = 0;
2864 	} else {
2865 		/* More mblk_t(s) to process so no rval to return */
2866 		rp->r_vals = 0;
2867 	}
2868 	return (error);
2869 }
2870 
2871 /*
2872  * Receive the next message on the queue.
2873  * If msg_controllen is non-zero when called the caller is interested in
2874  * any received control info (options).
2875  * If msg_namelen is non-zero when called the caller is interested in
2876  * any received source address.
2877  * The routine returns with msg_control and msg_name pointing to
2878  * kmem_alloc'ed memory which the caller has to free.
2879  */
2880 int
2881 sotpi_recvmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
2882 {
2883 	union T_primitives	*tpr;
2884 	mblk_t			*mp;
2885 	uchar_t			pri;
2886 	int			pflag, opflag;
2887 	void			*control;
2888 	t_uscalar_t		controllen;
2889 	t_uscalar_t		namelen;
2890 	int			so_state = so->so_state; /* Snapshot */
2891 	ssize_t			saved_resid;
2892 	int			error;
2893 	rval_t			rval;
2894 	int			flags;
2895 	clock_t			timout;
2896 	int			first;
2897 
2898 	flags = msg->msg_flags;
2899 	msg->msg_flags = 0;
2900 
2901 	dprintso(so, 1, ("sotpi_recvmsg(%p, %p, 0x%x) state %s err %d\n",
2902 		so, msg, flags,
2903 		pr_state(so->so_state, so->so_mode), so->so_error));
2904 
2905 	/*
2906 	 * If we are not connected because we have never been connected
2907 	 * we return ENOTCONN. If we have been connected (but are no longer
2908 	 * connected) then SS_CANTRCVMORE is set and we let kstrgetmsg return
2909 	 * the EOF.
2910 	 *
2911 	 * An alternative would be to post an ENOTCONN error in stream head
2912 	 * (read+write) and clear it when we're connected. However, that error
2913 	 * would cause incorrect poll/select behavior!
2914 	 */
2915 	if ((so_state & (SS_ISCONNECTED|SS_CANTRCVMORE)) == 0 &&
2916 	    (so->so_mode & SM_CONNREQUIRED)) {
2917 		return (ENOTCONN);
2918 	}
2919 
2920 	/*
2921 	 * Note: SunOS 4.X checks uio_resid == 0 before going to sleep (but
2922 	 * after checking that the read queue is empty) and returns zero.
2923 	 * This implementation will sleep (in kstrgetmsg) even if uio_resid
2924 	 * is zero.
2925 	 */
2926 
2927 	if (flags & MSG_OOB) {
2928 		/* Check that the transport supports OOB */
2929 		if (!(so->so_mode & SM_EXDATA))
2930 			return (EOPNOTSUPP);
2931 		return (sorecvoob(so, msg, uiop, flags));
2932 	}
2933 
2934 	/*
2935 	 * Set msg_controllen and msg_namelen to zero here to make it
2936 	 * simpler in the cases that no control or name is returned.
2937 	 */
2938 	controllen = msg->msg_controllen;
2939 	namelen = msg->msg_namelen;
2940 	msg->msg_controllen = 0;
2941 	msg->msg_namelen = 0;
2942 
2943 	dprintso(so, 1, ("sotpi_recvmsg: namelen %d controllen %d\n",
2944 		namelen, controllen));
2945 
2946 	mutex_enter(&so->so_lock);
2947 	/*
2948 	 * If an NL7C enabled socket and not waiting for write data.
2949 	 */
2950 	if ((so->so_nl7c_flags & (NL7C_ENABLED | NL7C_WAITWRITE)) ==
2951 	    NL7C_ENABLED) {
2952 		if (so->so_nl7c_uri) {
2953 			/* Close uri processing for a previous request */
2954 			nl7c_close(so);
2955 		}
2956 		if ((so_state & SS_CANTRCVMORE) && so->so_nl7c_rcv_mp == NULL) {
2957 			/* Nothing to process, EOF */
2958 			mutex_exit(&so->so_lock);
2959 			return (0);
2960 		} else if (so->so_nl7c_flags & NL7C_SOPERSIST) {
2961 			/* Persistent NL7C socket, try to process request */
2962 			boolean_t ret;
2963 
2964 			ret = nl7c_process(so,
2965 			    (so->so_state & (SS_NONBLOCK|SS_NDELAY)));
2966 			rval.r_vals = so->so_nl7c_rcv_rval;
2967 			error = rval.r_v.r_v2;
2968 			if (error) {
2969 				/* Error of some sort, return it */
2970 				mutex_exit(&so->so_lock);
2971 				return (error);
2972 			}
2973 			if (so->so_nl7c_flags &&
2974 			    ! (so->so_nl7c_flags & NL7C_WAITWRITE)) {
2975 				/*
2976 				 * Still an NL7C socket and no data
2977 				 * to pass up to the caller.
2978 				 */
2979 				mutex_exit(&so->so_lock);
2980 				if (ret) {
2981 					/* EOF */
2982 					return (0);
2983 				} else {
2984 					/* Need more data */
2985 					return (EAGAIN);
2986 				}
2987 			}
2988 		} else {
2989 			/*
2990 			 * Not persistent so no further NL7C processing.
2991 			 */
2992 			so->so_nl7c_flags = 0;
2993 		}
2994 	}
2995 	/*
2996 	 * Only one reader is allowed at any given time. This is needed
2997 	 * for T_EXDATA handling and, in the future, MSG_WAITALL.
2998 	 *
2999 	 * This is slightly different that BSD behavior in that it fails with
3000 	 * EWOULDBLOCK when using nonblocking io. In BSD the read queue access
3001 	 * is single-threaded using sblock(), which is dropped while waiting
3002 	 * for data to appear. The difference shows up e.g. if one
3003 	 * file descriptor does not have O_NONBLOCK but a dup'ed file descriptor
3004 	 * does use nonblocking io and different threads are reading each
3005 	 * file descriptor. In BSD there would never be an EWOULDBLOCK error
3006 	 * in this case as long as the read queue doesn't get empty.
3007 	 * In this implementation the thread using nonblocking io can
3008 	 * get an EWOULDBLOCK error due to the blocking thread executing
3009 	 * e.g. in the uiomove in kstrgetmsg.
3010 	 * This difference is not believed to be significant.
3011 	 */
3012 	/* Set SOREADLOCKED */
3013 	error = so_lock_read_intr(so,
3014 	    uiop->uio_fmode | ((flags & MSG_DONTWAIT) ? FNONBLOCK : 0));
3015 	mutex_exit(&so->so_lock);
3016 	if (error)
3017 		return (error);
3018 
3019 	/*
3020 	 * Tell kstrgetmsg to not inspect the stream head errors until all
3021 	 * queued data has been consumed.
3022 	 * Use a timeout=-1 to wait forever unless MSG_DONTWAIT is set.
3023 	 * Also, If uio_fmode indicates nonblocking kstrgetmsg will not block.
3024 	 *
3025 	 * MSG_WAITALL only applies to M_DATA and T_DATA_IND messages and
3026 	 * to T_OPTDATA_IND that do not contain any user-visible control msg.
3027 	 * Note that MSG_WAITALL set with MSG_PEEK is a noop.
3028 	 */
3029 	pflag = MSG_ANY | MSG_DELAYERROR;
3030 	if (flags & MSG_PEEK) {
3031 		pflag |= MSG_IPEEK;
3032 		flags &= ~MSG_WAITALL;
3033 	}
3034 	if (so->so_mode & SM_ATOMIC)
3035 		pflag |= MSG_DISCARDTAIL;
3036 
3037 	if (flags & MSG_DONTWAIT)
3038 		timout = 0;
3039 	else
3040 		timout = -1;
3041 	opflag = pflag;
3042 	first = 1;
3043 
3044 retry:
3045 	saved_resid = uiop->uio_resid;
3046 	pri = 0;
3047 	mp = NULL;
3048 	if (so->so_nl7c_rcv_mp != NULL) {
3049 		/* Already kstrgetmsg()ed saved mblk(s) from NL7C */
3050 		error = nl7c_sorecv(so, &mp, uiop, &rval);
3051 	} else {
3052 		error = kstrgetmsg(SOTOV(so), &mp, uiop, &pri, &pflag,
3053 		    timout, &rval);
3054 	}
3055 	if (error) {
3056 		switch (error) {
3057 		case EINTR:
3058 		case EWOULDBLOCK:
3059 			if (!first)
3060 				error = 0;
3061 			break;
3062 		case ETIME:
3063 			/* Returned from kstrgetmsg when timeout expires */
3064 			if (!first)
3065 				error = 0;
3066 			else
3067 				error = EWOULDBLOCK;
3068 			break;
3069 		default:
3070 			eprintsoline(so, error);
3071 			break;
3072 		}
3073 		mutex_enter(&so->so_lock);
3074 		so_unlock_read(so);	/* Clear SOREADLOCKED */
3075 		mutex_exit(&so->so_lock);
3076 		return (error);
3077 	}
3078 	/*
3079 	 * For datagrams the MOREDATA flag is used to set MSG_TRUNC.
3080 	 * For non-datagrams MOREDATA is used to set MSG_EOR.
3081 	 */
3082 	ASSERT(!(rval.r_val1 & MORECTL));
3083 	if ((rval.r_val1 & MOREDATA) && (so->so_mode & SM_ATOMIC))
3084 		msg->msg_flags |= MSG_TRUNC;
3085 
3086 	if (mp == NULL) {
3087 		dprintso(so, 1, ("sotpi_recvmsg: got M_DATA\n"));
3088 		/*
3089 		 * 4.3BSD and 4.4BSD clears the mark when peeking across it.
3090 		 * The draft Posix socket spec states that the mark should
3091 		 * not be cleared when peeking. We follow the latter.
3092 		 */
3093 		if ((so->so_state &
3094 		    (SS_OOBPEND|SS_HAVEOOBDATA|SS_RCVATMARK)) &&
3095 		    (uiop->uio_resid != saved_resid) &&
3096 		    !(flags & MSG_PEEK)) {
3097 			sorecv_update_oobstate(so);
3098 		}
3099 
3100 		mutex_enter(&so->so_lock);
3101 		/* Set MSG_EOR based on MOREDATA */
3102 		if (!(rval.r_val1 & MOREDATA)) {
3103 			if (so->so_state & SS_SAVEDEOR) {
3104 				msg->msg_flags |= MSG_EOR;
3105 				so->so_state &= ~SS_SAVEDEOR;
3106 			}
3107 		}
3108 		/*
3109 		 * If some data was received (i.e. not EOF) and the
3110 		 * read/recv* has not been satisfied wait for some more.
3111 		 */
3112 		if ((flags & MSG_WAITALL) && !(msg->msg_flags & MSG_EOR) &&
3113 		    uiop->uio_resid != saved_resid && uiop->uio_resid > 0) {
3114 			mutex_exit(&so->so_lock);
3115 			first = 0;
3116 			pflag = opflag | MSG_NOMARK;
3117 			goto retry;
3118 		}
3119 		so_unlock_read(so);	/* Clear SOREADLOCKED */
3120 		mutex_exit(&so->so_lock);
3121 		return (0);
3122 	}
3123 
3124 	/* strsock_proto has already verified length and alignment */
3125 	tpr = (union T_primitives *)mp->b_rptr;
3126 	dprintso(so, 1, ("sotpi_recvmsg: type %d\n", tpr->type));
3127 
3128 	switch (tpr->type) {
3129 	case T_DATA_IND: {
3130 		if ((so->so_state &
3131 		    (SS_OOBPEND|SS_HAVEOOBDATA|SS_RCVATMARK)) &&
3132 		    (uiop->uio_resid != saved_resid) &&
3133 		    !(flags & MSG_PEEK)) {
3134 			sorecv_update_oobstate(so);
3135 		}
3136 
3137 		/*
3138 		 * Set msg_flags to MSG_EOR based on
3139 		 * MORE_flag and MOREDATA.
3140 		 */
3141 		mutex_enter(&so->so_lock);
3142 		so->so_state &= ~SS_SAVEDEOR;
3143 		if (!(tpr->data_ind.MORE_flag & 1)) {
3144 			if (!(rval.r_val1 & MOREDATA))
3145 				msg->msg_flags |= MSG_EOR;
3146 			else
3147 				so->so_state |= SS_SAVEDEOR;
3148 		}
3149 		freemsg(mp);
3150 		/*
3151 		 * If some data was received (i.e. not EOF) and the
3152 		 * read/recv* has not been satisfied wait for some more.
3153 		 */
3154 		if ((flags & MSG_WAITALL) && !(msg->msg_flags & MSG_EOR) &&
3155 		    uiop->uio_resid != saved_resid && uiop->uio_resid > 0) {
3156 			mutex_exit(&so->so_lock);
3157 			first = 0;
3158 			pflag = opflag | MSG_NOMARK;
3159 			goto retry;
3160 		}
3161 		so_unlock_read(so);	/* Clear SOREADLOCKED */
3162 		mutex_exit(&so->so_lock);
3163 		return (0);
3164 	}
3165 	case T_UNITDATA_IND: {
3166 		void *addr;
3167 		t_uscalar_t addrlen;
3168 		void *abuf;
3169 		t_uscalar_t optlen;
3170 		void *opt;
3171 
3172 		if ((so->so_state &
3173 		    (SS_OOBPEND|SS_HAVEOOBDATA|SS_RCVATMARK)) &&
3174 		    (uiop->uio_resid != saved_resid) &&
3175 		    !(flags & MSG_PEEK)) {
3176 			sorecv_update_oobstate(so);
3177 		}
3178 
3179 		if (namelen != 0) {
3180 			/* Caller wants source address */
3181 			addrlen = tpr->unitdata_ind.SRC_length;
3182 			addr = sogetoff(mp,
3183 				tpr->unitdata_ind.SRC_offset,
3184 				addrlen, 1);
3185 			if (addr == NULL) {
3186 				freemsg(mp);
3187 				error = EPROTO;
3188 				eprintsoline(so, error);
3189 				goto err;
3190 			}
3191 			if (so->so_family == AF_UNIX) {
3192 				/*
3193 				 * Can not use the transport level address.
3194 				 * If there is a SO_SRCADDR option carrying
3195 				 * the socket level address it will be
3196 				 * extracted below.
3197 				 */
3198 				addr = NULL;
3199 				addrlen = 0;
3200 			}
3201 		}
3202 		optlen = tpr->unitdata_ind.OPT_length;
3203 		if (optlen != 0) {
3204 			t_uscalar_t ncontrollen;
3205 
3206 			/*
3207 			 * Extract any source address option.
3208 			 * Determine how large cmsg buffer is needed.
3209 			 */
3210 			opt = sogetoff(mp,
3211 				tpr->unitdata_ind.OPT_offset,
3212 				optlen, __TPI_ALIGN_SIZE);
3213 
3214 			if (opt == NULL) {
3215 				freemsg(mp);
3216 				error = EPROTO;
3217 				eprintsoline(so, error);
3218 				goto err;
3219 			}
3220 			if (so->so_family == AF_UNIX)
3221 				so_getopt_srcaddr(opt, optlen, &addr, &addrlen);
3222 			ncontrollen = so_cmsglen(mp, opt, optlen,
3223 						!(flags & MSG_XPG4_2));
3224 			if (controllen != 0)
3225 				controllen = ncontrollen;
3226 			else if (ncontrollen != 0)
3227 				msg->msg_flags |= MSG_CTRUNC;
3228 		} else {
3229 			controllen = 0;
3230 		}
3231 
3232 		if (namelen != 0) {
3233 			/*
3234 			 * Return address to caller.
3235 			 * Caller handles truncation if length
3236 			 * exceeds msg_namelen.
3237 			 * NOTE: AF_UNIX NUL termination is ensured by
3238 			 * the sender's copyin_name().
3239 			 */
3240 			abuf = kmem_alloc(addrlen, KM_SLEEP);
3241 
3242 			bcopy(addr, abuf, addrlen);
3243 			msg->msg_name = abuf;
3244 			msg->msg_namelen = addrlen;
3245 		}
3246 
3247 		if (controllen != 0) {
3248 			/*
3249 			 * Return control msg to caller.
3250 			 * Caller handles truncation if length
3251 			 * exceeds msg_controllen.
3252 			 */
3253 			control = kmem_alloc(controllen, KM_SLEEP);
3254 
3255 			error = so_opt2cmsg(mp, opt, optlen,
3256 					!(flags & MSG_XPG4_2),
3257 					control, controllen);
3258 			if (error) {
3259 				freemsg(mp);
3260 				if (msg->msg_namelen != 0)
3261 					kmem_free(msg->msg_name,
3262 						msg->msg_namelen);
3263 				kmem_free(control, controllen);
3264 				eprintsoline(so, error);
3265 				goto err;
3266 			}
3267 			msg->msg_control = control;
3268 			msg->msg_controllen = controllen;
3269 		}
3270 
3271 		freemsg(mp);
3272 		mutex_enter(&so->so_lock);
3273 		so_unlock_read(so);	/* Clear SOREADLOCKED */
3274 		mutex_exit(&so->so_lock);
3275 		return (0);
3276 	}
3277 	case T_OPTDATA_IND: {
3278 		struct T_optdata_req *tdr;
3279 		void *opt;
3280 		t_uscalar_t optlen;
3281 
3282 		if ((so->so_state &
3283 		    (SS_OOBPEND|SS_HAVEOOBDATA|SS_RCVATMARK)) &&
3284 		    (uiop->uio_resid != saved_resid) &&
3285 		    !(flags & MSG_PEEK)) {
3286 			sorecv_update_oobstate(so);
3287 		}
3288 
3289 		tdr = (struct T_optdata_req *)mp->b_rptr;
3290 		optlen = tdr->OPT_length;
3291 		if (optlen != 0) {
3292 			t_uscalar_t ncontrollen;
3293 			/*
3294 			 * Determine how large cmsg buffer is needed.
3295 			 */
3296 			opt = sogetoff(mp,
3297 					tpr->optdata_ind.OPT_offset,
3298 					optlen, __TPI_ALIGN_SIZE);
3299 
3300 			if (opt == NULL) {
3301 				freemsg(mp);
3302 				error = EPROTO;
3303 				eprintsoline(so, error);
3304 				goto err;
3305 			}
3306 
3307 			ncontrollen = so_cmsglen(mp, opt, optlen,
3308 						!(flags & MSG_XPG4_2));
3309 			if (controllen != 0)
3310 				controllen = ncontrollen;
3311 			else if (ncontrollen != 0)
3312 				msg->msg_flags |= MSG_CTRUNC;
3313 		} else {
3314 			controllen = 0;
3315 		}
3316 
3317 		if (controllen != 0) {
3318 			/*
3319 			 * Return control msg to caller.
3320 			 * Caller handles truncation if length
3321 			 * exceeds msg_controllen.
3322 			 */
3323 			control = kmem_alloc(controllen, KM_SLEEP);
3324 
3325 			error = so_opt2cmsg(mp, opt, optlen,
3326 					!(flags & MSG_XPG4_2),
3327 					control, controllen);
3328 			if (error) {
3329 				freemsg(mp);
3330 				kmem_free(control, controllen);
3331 				eprintsoline(so, error);
3332 				goto err;
3333 			}
3334 			msg->msg_control = control;
3335 			msg->msg_controllen = controllen;
3336 		}
3337 
3338 		/*
3339 		 * Set msg_flags to MSG_EOR based on
3340 		 * DATA_flag and MOREDATA.
3341 		 */
3342 		mutex_enter(&so->so_lock);
3343 		so->so_state &= ~SS_SAVEDEOR;
3344 		if (!(tpr->data_ind.MORE_flag & 1)) {
3345 			if (!(rval.r_val1 & MOREDATA))
3346 				msg->msg_flags |= MSG_EOR;
3347 			else
3348 				so->so_state |= SS_SAVEDEOR;
3349 		}
3350 		freemsg(mp);
3351 		/*
3352 		 * If some data was received (i.e. not EOF) and the
3353 		 * read/recv* has not been satisfied wait for some more.
3354 		 * Not possible to wait if control info was received.
3355 		 */
3356 		if ((flags & MSG_WAITALL) && !(msg->msg_flags & MSG_EOR) &&
3357 		    controllen == 0 &&
3358 		    uiop->uio_resid != saved_resid && uiop->uio_resid > 0) {
3359 			mutex_exit(&so->so_lock);
3360 			first = 0;
3361 			pflag = opflag | MSG_NOMARK;
3362 			goto retry;
3363 		}
3364 		so_unlock_read(so);	/* Clear SOREADLOCKED */
3365 		mutex_exit(&so->so_lock);
3366 		return (0);
3367 	}
3368 	case T_EXDATA_IND: {
3369 		dprintso(so, 1,
3370 			("sotpi_recvmsg: EXDATA_IND counts %d/%d consumed %ld "
3371 			"state %s\n",
3372 			so->so_oobsigcnt, so->so_oobcnt,
3373 			saved_resid - uiop->uio_resid,
3374 			pr_state(so->so_state, so->so_mode)));
3375 		/*
3376 		 * kstrgetmsg handles MSGMARK so there is nothing to
3377 		 * inspect in the T_EXDATA_IND.
3378 		 * strsock_proto makes the stream head queue the T_EXDATA_IND
3379 		 * as a separate message with no M_DATA component. Furthermore,
3380 		 * the stream head does not consolidate M_DATA messages onto
3381 		 * an MSGMARK'ed message ensuring that the T_EXDATA_IND
3382 		 * remains a message by itself. This is needed since MSGMARK
3383 		 * marks both the whole message as well as the last byte
3384 		 * of the message.
3385 		 */
3386 		freemsg(mp);
3387 		ASSERT(uiop->uio_resid == saved_resid);	/* No data */
3388 		if (flags & MSG_PEEK) {
3389 			/*
3390 			 * Even though we are peeking we consume the
3391 			 * T_EXDATA_IND thereby moving the mark information
3392 			 * to SS_RCVATMARK. Then the oob code below will
3393 			 * retry the peeking kstrgetmsg.
3394 			 * Note that the stream head read queue is
3395 			 * never flushed without holding SOREADLOCKED
3396 			 * thus the T_EXDATA_IND can not disappear
3397 			 * underneath us.
3398 			 */
3399 			dprintso(so, 1,
3400 				("sotpi_recvmsg: consume EXDATA_IND "
3401 				"counts %d/%d state %s\n",
3402 				so->so_oobsigcnt,
3403 				so->so_oobcnt,
3404 				pr_state(so->so_state, so->so_mode)));
3405 
3406 			pflag = MSG_ANY | MSG_DELAYERROR;
3407 			if (so->so_mode & SM_ATOMIC)
3408 				pflag |= MSG_DISCARDTAIL;
3409 
3410 			pri = 0;
3411 			mp = NULL;
3412 
3413 			error = kstrgetmsg(SOTOV(so), &mp, uiop,
3414 				&pri, &pflag, (clock_t)-1, &rval);
3415 			ASSERT(uiop->uio_resid == saved_resid);
3416 
3417 			if (error) {
3418 #ifdef SOCK_DEBUG
3419 				if (error != EWOULDBLOCK && error != EINTR) {
3420 					eprintsoline(so, error);
3421 				}
3422 #endif /* SOCK_DEBUG */
3423 				mutex_enter(&so->so_lock);
3424 				so_unlock_read(so);	/* Clear SOREADLOCKED */
3425 				mutex_exit(&so->so_lock);
3426 				return (error);
3427 			}
3428 			ASSERT(mp);
3429 			tpr = (union T_primitives *)mp->b_rptr;
3430 			ASSERT(tpr->type == T_EXDATA_IND);
3431 			freemsg(mp);
3432 		} /* end "if (flags & MSG_PEEK)" */
3433 
3434 		/*
3435 		 * Decrement the number of queued and pending oob.
3436 		 *
3437 		 * SS_RCVATMARK is cleared when we read past a mark.
3438 		 * SS_HAVEOOBDATA is cleared when we've read past the
3439 		 * last mark.
3440 		 * SS_OOBPEND is cleared if we've read past the last
3441 		 * mark and no (new) SIGURG has been posted.
3442 		 */
3443 		mutex_enter(&so->so_lock);
3444 		ASSERT(so_verify_oobstate(so));
3445 		ASSERT(so->so_oobsigcnt >= so->so_oobcnt);
3446 		ASSERT(so->so_oobsigcnt > 0);
3447 		so->so_oobsigcnt--;
3448 		ASSERT(so->so_oobcnt > 0);
3449 		so->so_oobcnt--;
3450 		/*
3451 		 * Since the T_EXDATA_IND has been removed from the stream
3452 		 * head, but we have not read data past the mark,
3453 		 * sockfs needs to track that the socket is still at the mark.
3454 		 *
3455 		 * Since no data was received call kstrgetmsg again to wait
3456 		 * for data.
3457 		 */
3458 		so->so_state |= SS_RCVATMARK;
3459 		mutex_exit(&so->so_lock);
3460 		dprintso(so, 1,
3461 		    ("sotpi_recvmsg: retry EXDATA_IND counts %d/%d state %s\n",
3462 		    so->so_oobsigcnt, so->so_oobcnt,
3463 		    pr_state(so->so_state, so->so_mode)));
3464 		pflag = opflag;
3465 		goto retry;
3466 	}
3467 	default:
3468 		ASSERT(0);
3469 		freemsg(mp);
3470 		error = EPROTO;
3471 		eprintsoline(so, error);
3472 		goto err;
3473 	}
3474 	/* NOTREACHED */
3475 err:
3476 	mutex_enter(&so->so_lock);
3477 	so_unlock_read(so);	/* Clear SOREADLOCKED */
3478 	mutex_exit(&so->so_lock);
3479 	return (error);
3480 }
3481 
3482 /*
3483  * Sending data with options on a datagram socket.
3484  * Assumes caller has verified that SS_ISBOUND etc. are set.
3485  */
3486 static int
3487 sosend_dgramcmsg(struct sonode *so, struct sockaddr *name, socklen_t namelen,
3488     struct uio *uiop, void *control, t_uscalar_t controllen, int flags)
3489 {
3490 	struct T_unitdata_req	tudr;
3491 	mblk_t			*mp;
3492 	int			error;
3493 	void			*addr;
3494 	socklen_t		addrlen;
3495 	void			*src;
3496 	socklen_t		srclen;
3497 	ssize_t			len;
3498 	int			size;
3499 	struct T_opthdr		toh;
3500 	struct fdbuf		*fdbuf;
3501 	t_uscalar_t		optlen;
3502 	void			*fds;
3503 	int			fdlen;
3504 
3505 	ASSERT(name && namelen);
3506 	ASSERT(control && controllen);
3507 
3508 	len = uiop->uio_resid;
3509 	if (len > (ssize_t)so->so_tidu_size) {
3510 		return (EMSGSIZE);
3511 	}
3512 
3513 	/*
3514 	 * For AF_UNIX the destination address is translated to an internal
3515 	 * name and the source address is passed as an option.
3516 	 * Also, file descriptors are passed as file pointers in an
3517 	 * option.
3518 	 */
3519 
3520 	/*
3521 	 * Length and family checks.
3522 	 */
3523 	error = so_addr_verify(so, name, namelen);
3524 	if (error) {
3525 		eprintsoline(so, error);
3526 		return (error);
3527 	}
3528 	if (so->so_family == AF_UNIX) {
3529 		if (so->so_state & SS_FADDR_NOXLATE) {
3530 			/*
3531 			 * Already have a transport internal address. Do not
3532 			 * pass any (transport internal) source address.
3533 			 */
3534 			addr = name;
3535 			addrlen = namelen;
3536 			src = NULL;
3537 			srclen = 0;
3538 		} else {
3539 			/*
3540 			 * Pass the sockaddr_un source address as an option
3541 			 * and translate the remote address.
3542 			 *
3543 			 * Note that this code does not prevent so_laddr_sa
3544 			 * from changing while it is being used. Thus
3545 			 * if an unbind+bind occurs concurrently with this
3546 			 * send the peer might see a partially new and a
3547 			 * partially old "from" address.
3548 			 */
3549 			src = so->so_laddr_sa;
3550 			srclen = (t_uscalar_t)so->so_laddr_len;
3551 			dprintso(so, 1,
3552 			    ("sosend_dgramcmsg UNIX: srclen %d, src %p\n",
3553 			    srclen, src));
3554 			error = so_ux_addr_xlate(so, name, namelen,
3555 				(flags & MSG_XPG4_2),
3556 				&addr, &addrlen);
3557 			if (error) {
3558 				eprintsoline(so, error);
3559 				return (error);
3560 			}
3561 		}
3562 	} else {
3563 		addr = name;
3564 		addrlen = namelen;
3565 		src = NULL;
3566 		srclen = 0;
3567 	}
3568 	optlen = so_optlen(control, controllen,
3569 					!(flags & MSG_XPG4_2));
3570 	tudr.PRIM_type = T_UNITDATA_REQ;
3571 	tudr.DEST_length = addrlen;
3572 	tudr.DEST_offset = (t_scalar_t)sizeof (tudr);
3573 	if (srclen != 0)
3574 		tudr.OPT_length = (t_scalar_t)(optlen + sizeof (toh) +
3575 		    _TPI_ALIGN_TOPT(srclen));
3576 	else
3577 		tudr.OPT_length = optlen;
3578 	tudr.OPT_offset = (t_scalar_t)(sizeof (tudr) +
3579 				_TPI_ALIGN_TOPT(addrlen));
3580 
3581 	size = tudr.OPT_offset + tudr.OPT_length;
3582 
3583 	/*
3584 	 * File descriptors only when SM_FDPASSING set.
3585 	 */
3586 	error = so_getfdopt(control, controllen,
3587 			!(flags & MSG_XPG4_2), &fds, &fdlen);
3588 	if (error)
3589 		return (error);
3590 	if (fdlen != -1) {
3591 		if (!(so->so_mode & SM_FDPASSING))
3592 			return (EOPNOTSUPP);
3593 
3594 		error = fdbuf_create(fds, fdlen, &fdbuf);
3595 		if (error)
3596 			return (error);
3597 		mp = fdbuf_allocmsg(size, fdbuf);
3598 	} else {
3599 		mp = soallocproto(size, _ALLOC_INTR);
3600 		if (mp == NULL) {
3601 			/*
3602 			 * Caught a signal waiting for memory.
3603 			 * Let send* return EINTR.
3604 			 */
3605 			return (EINTR);
3606 		}
3607 	}
3608 	soappendmsg(mp, &tudr, sizeof (tudr));
3609 	soappendmsg(mp, addr, addrlen);
3610 	mp->b_wptr += _TPI_ALIGN_TOPT(addrlen) - addrlen;
3611 
3612 	if (fdlen != -1) {
3613 		ASSERT(fdbuf != NULL);
3614 		toh.level = SOL_SOCKET;
3615 		toh.name = SO_FILEP;
3616 		toh.len = fdbuf->fd_size +
3617 				(t_uscalar_t)sizeof (struct T_opthdr);
3618 		toh.status = 0;
3619 		soappendmsg(mp, &toh, sizeof (toh));
3620 		soappendmsg(mp, fdbuf, fdbuf->fd_size);
3621 		ASSERT(__TPI_TOPT_ISALIGNED(mp->b_wptr));
3622 	}
3623 	if (srclen != 0) {
3624 		/*
3625 		 * There is a AF_UNIX sockaddr_un to include as a source
3626 		 * address option.
3627 		 */
3628 		toh.level = SOL_SOCKET;
3629 		toh.name = SO_SRCADDR;
3630 		toh.len = (t_uscalar_t)(srclen + sizeof (struct T_opthdr));
3631 		toh.status = 0;
3632 		soappendmsg(mp, &toh, sizeof (toh));
3633 		soappendmsg(mp, src, srclen);
3634 		mp->b_wptr += _TPI_ALIGN_TOPT(srclen) - srclen;
3635 		ASSERT(__TPI_TOPT_ISALIGNED(mp->b_wptr));
3636 	}
3637 	ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
3638 	so_cmsg2opt(control, controllen, !(flags & MSG_XPG4_2), mp);
3639 	/* At most 3 bytes left in the message */
3640 	ASSERT(MBLKL(mp) > (ssize_t)(size - __TPI_ALIGN_SIZE));
3641 	ASSERT(MBLKL(mp) <= (ssize_t)size);
3642 
3643 	ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
3644 #ifdef C2_AUDIT
3645 	if (audit_active)
3646 		audit_sock(T_UNITDATA_REQ, strvp2wq(SOTOV(so)), mp, 0);
3647 #endif /* C2_AUDIT */
3648 
3649 	error = kstrputmsg(SOTOV(so), mp, uiop, len, 0, MSG_BAND, 0);
3650 #ifdef SOCK_DEBUG
3651 	if (error) {
3652 		eprintsoline(so, error);
3653 	}
3654 #endif /* SOCK_DEBUG */
3655 	return (error);
3656 }
3657 
3658 /*
3659  * Sending data with options on a connected stream socket.
3660  * Assumes caller has verified that SS_ISCONNECTED is set.
3661  */
3662 static int
3663 sosend_svccmsg(struct sonode *so,
3664 		struct uio *uiop,
3665 		int more,
3666 		void *control,
3667 		t_uscalar_t controllen,
3668 		int flags)
3669 {
3670 	struct T_optdata_req	tdr;
3671 	mblk_t			*mp;
3672 	int			error;
3673 	ssize_t			iosize;
3674 	int			first = 1;
3675 	int			size;
3676 	struct fdbuf		*fdbuf;
3677 	t_uscalar_t		optlen;
3678 	void			*fds;
3679 	int			fdlen;
3680 	struct T_opthdr		toh;
3681 
3682 	dprintso(so, 1,
3683 		("sosend_svccmsg: resid %ld bytes\n", uiop->uio_resid));
3684 
3685 	/*
3686 	 * Has to be bound and connected. However, since no locks are
3687 	 * held the state could have changed after sotpi_sendmsg checked it
3688 	 * thus it is not possible to ASSERT on the state.
3689 	 */
3690 
3691 	/* Options on connection-oriented only when SM_OPTDATA set. */
3692 	if (!(so->so_mode & SM_OPTDATA))
3693 		return (EOPNOTSUPP);
3694 
3695 	do {
3696 		/*
3697 		 * Set the MORE flag if uio_resid does not fit in this
3698 		 * message or if the caller passed in "more".
3699 		 * Error for transports with zero tidu_size.
3700 		 */
3701 		tdr.PRIM_type = T_OPTDATA_REQ;
3702 		iosize = so->so_tidu_size;
3703 		if (iosize <= 0)
3704 			return (EMSGSIZE);
3705 		if (uiop->uio_resid > iosize) {
3706 			tdr.DATA_flag = 1;
3707 		} else {
3708 			if (more)
3709 				tdr.DATA_flag = 1;
3710 			else
3711 				tdr.DATA_flag = 0;
3712 			iosize = uiop->uio_resid;
3713 		}
3714 		dprintso(so, 1, ("sosend_svccmsg: sending %d, %ld bytes\n",
3715 			tdr.DATA_flag, iosize));
3716 
3717 		optlen = so_optlen(control, controllen, !(flags & MSG_XPG4_2));
3718 		tdr.OPT_length = optlen;
3719 		tdr.OPT_offset = (t_scalar_t)sizeof (tdr);
3720 
3721 		size = (int)sizeof (tdr) + optlen;
3722 		/*
3723 		 * File descriptors only when SM_FDPASSING set.
3724 		 */
3725 		error = so_getfdopt(control, controllen,
3726 				!(flags & MSG_XPG4_2), &fds, &fdlen);
3727 		if (error)
3728 			return (error);
3729 		if (fdlen != -1) {
3730 			if (!(so->so_mode & SM_FDPASSING))
3731 				return (EOPNOTSUPP);
3732 
3733 			error = fdbuf_create(fds, fdlen, &fdbuf);
3734 			if (error)
3735 				return (error);
3736 			mp = fdbuf_allocmsg(size, fdbuf);
3737 		} else {
3738 			mp = soallocproto(size, _ALLOC_INTR);
3739 			if (mp == NULL) {
3740 				/*
3741 				 * Caught a signal waiting for memory.
3742 				 * Let send* return EINTR.
3743 				 */
3744 				return (first ? EINTR : 0);
3745 			}
3746 		}
3747 		soappendmsg(mp, &tdr, sizeof (tdr));
3748 
3749 		if (fdlen != -1) {
3750 			ASSERT(fdbuf != NULL);
3751 			toh.level = SOL_SOCKET;
3752 			toh.name = SO_FILEP;
3753 			toh.len = fdbuf->fd_size +
3754 				(t_uscalar_t)sizeof (struct T_opthdr);
3755 			toh.status = 0;
3756 			soappendmsg(mp, &toh, sizeof (toh));
3757 			soappendmsg(mp, fdbuf, fdbuf->fd_size);
3758 			ASSERT(__TPI_TOPT_ISALIGNED(mp->b_wptr));
3759 		}
3760 		so_cmsg2opt(control, controllen, !(flags & MSG_XPG4_2), mp);
3761 		/* At most 3 bytes left in the message */
3762 		ASSERT(MBLKL(mp) > (ssize_t)(size - __TPI_ALIGN_SIZE));
3763 		ASSERT(MBLKL(mp) <= (ssize_t)size);
3764 
3765 		ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
3766 
3767 		error = kstrputmsg(SOTOV(so), mp, uiop, iosize,
3768 					0, MSG_BAND, 0);
3769 		if (error) {
3770 			if (!first && error == EWOULDBLOCK)
3771 				return (0);
3772 			eprintsoline(so, error);
3773 			return (error);
3774 		}
3775 		control = NULL;
3776 		first = 0;
3777 		if (uiop->uio_resid > 0) {
3778 			/*
3779 			 * Recheck for fatal errors. Fail write even though
3780 			 * some data have been written. This is consistent
3781 			 * with strwrite semantics and BSD sockets semantics.
3782 			 */
3783 			if (so->so_state & SS_CANTSENDMORE) {
3784 				tsignal(curthread, SIGPIPE);
3785 				eprintsoline(so, error);
3786 				return (EPIPE);
3787 			}
3788 			if (so->so_error != 0) {
3789 				mutex_enter(&so->so_lock);
3790 				error = sogeterr(so);
3791 				mutex_exit(&so->so_lock);
3792 				if (error != 0) {
3793 					eprintsoline(so, error);
3794 					return (error);
3795 				}
3796 			}
3797 		}
3798 	} while (uiop->uio_resid > 0);
3799 	return (0);
3800 }
3801 
3802 /*
3803  * Sending data on a datagram socket.
3804  * Assumes caller has verified that SS_ISBOUND etc. are set.
3805  *
3806  * For AF_UNIX the destination address is translated to an internal
3807  * name and the source address is passed as an option.
3808  */
3809 int
3810 sosend_dgram(struct sonode *so, struct sockaddr	*name, socklen_t namelen,
3811     struct uio *uiop, int flags)
3812 {
3813 	struct T_unitdata_req	tudr;
3814 	mblk_t			*mp;
3815 	int			error;
3816 	void			*addr;
3817 	socklen_t		addrlen;
3818 	void			*src;
3819 	socklen_t		srclen;
3820 	ssize_t			len;
3821 
3822 	ASSERT(name != NULL && namelen != 0);
3823 
3824 	len = uiop->uio_resid;
3825 	if (len > so->so_tidu_size) {
3826 		error = EMSGSIZE;
3827 		goto done;
3828 	}
3829 
3830 	/* Length and family checks */
3831 	error = so_addr_verify(so, name, namelen);
3832 	if (error != 0)
3833 		goto done;
3834 
3835 	if (so->so_state & SS_DIRECT)
3836 		return (sodgram_direct(so, name, namelen, uiop, flags));
3837 
3838 	if (so->so_family == AF_UNIX) {
3839 		if (so->so_state & SS_FADDR_NOXLATE) {
3840 			/*
3841 			 * Already have a transport internal address. Do not
3842 			 * pass any (transport internal) source address.
3843 			 */
3844 			addr = name;
3845 			addrlen = namelen;
3846 			src = NULL;
3847 			srclen = 0;
3848 		} else {
3849 			/*
3850 			 * Pass the sockaddr_un source address as an option
3851 			 * and translate the remote address.
3852 			 *
3853 			 * Note that this code does not prevent so_laddr_sa
3854 			 * from changing while it is being used. Thus
3855 			 * if an unbind+bind occurs concurrently with this
3856 			 * send the peer might see a partially new and a
3857 			 * partially old "from" address.
3858 			 */
3859 			src = so->so_laddr_sa;
3860 			srclen = (socklen_t)so->so_laddr_len;
3861 			dprintso(so, 1,
3862 				("sosend_dgram UNIX: srclen %d, src %p\n",
3863 				srclen, src));
3864 			error = so_ux_addr_xlate(so, name, namelen,
3865 				(flags & MSG_XPG4_2),
3866 				&addr, &addrlen);
3867 			if (error) {
3868 				eprintsoline(so, error);
3869 				goto done;
3870 			}
3871 		}
3872 	} else {
3873 		addr = name;
3874 		addrlen = namelen;
3875 		src = NULL;
3876 		srclen = 0;
3877 	}
3878 	tudr.PRIM_type = T_UNITDATA_REQ;
3879 	tudr.DEST_length = addrlen;
3880 	tudr.DEST_offset = (t_scalar_t)sizeof (tudr);
3881 	if (srclen == 0) {
3882 		tudr.OPT_length = 0;
3883 		tudr.OPT_offset = 0;
3884 
3885 		mp = soallocproto2(&tudr, sizeof (tudr),
3886 		    addr, addrlen, 0, _ALLOC_INTR);
3887 		if (mp == NULL) {
3888 			/*
3889 			 * Caught a signal waiting for memory.
3890 			 * Let send* return EINTR.
3891 			 */
3892 			error = EINTR;
3893 			goto done;
3894 		}
3895 	} else {
3896 		/*
3897 		 * There is a AF_UNIX sockaddr_un to include as a source
3898 		 * address option.
3899 		 */
3900 		struct T_opthdr toh;
3901 		ssize_t size;
3902 
3903 		tudr.OPT_length = (t_scalar_t)(sizeof (toh) +
3904 					_TPI_ALIGN_TOPT(srclen));
3905 		tudr.OPT_offset = (t_scalar_t)(sizeof (tudr) +
3906 					_TPI_ALIGN_TOPT(addrlen));
3907 
3908 		toh.level = SOL_SOCKET;
3909 		toh.name = SO_SRCADDR;
3910 		toh.len = (t_uscalar_t)(srclen + sizeof (struct T_opthdr));
3911 		toh.status = 0;
3912 
3913 		size = tudr.OPT_offset + tudr.OPT_length;
3914 		mp = soallocproto2(&tudr, sizeof (tudr),
3915 		    addr, addrlen, size, _ALLOC_INTR);
3916 		if (mp == NULL) {
3917 			/*
3918 			 * Caught a signal waiting for memory.
3919 			 * Let send* return EINTR.
3920 			 */
3921 			error = EINTR;
3922 			goto done;
3923 		}
3924 		mp->b_wptr += _TPI_ALIGN_TOPT(addrlen) - addrlen;
3925 		soappendmsg(mp, &toh, sizeof (toh));
3926 		soappendmsg(mp, src, srclen);
3927 		mp->b_wptr += _TPI_ALIGN_TOPT(srclen) - srclen;
3928 		ASSERT(mp->b_wptr <= mp->b_datap->db_lim);
3929 	}
3930 
3931 #ifdef C2_AUDIT
3932 	if (audit_active)
3933 		audit_sock(T_UNITDATA_REQ, strvp2wq(SOTOV(so)), mp, 0);
3934 #endif /* C2_AUDIT */
3935 
3936 	error = kstrputmsg(SOTOV(so), mp, uiop, len, 0, MSG_BAND, 0);
3937 done:
3938 #ifdef SOCK_DEBUG
3939 	if (error) {
3940 		eprintsoline(so, error);
3941 	}
3942 #endif /* SOCK_DEBUG */
3943 	return (error);
3944 }
3945 
3946 /*
3947  * Sending data on a connected stream socket.
3948  * Assumes caller has verified that SS_ISCONNECTED is set.
3949  */
3950 int
3951 sosend_svc(struct sonode *so,
3952 	struct uio *uiop,
3953 	t_scalar_t prim,
3954 	int more,
3955 	int sflag)
3956 {
3957 	struct T_data_req	tdr;
3958 	mblk_t			*mp;
3959 	int			error;
3960 	ssize_t			iosize;
3961 	int			first = 1;
3962 
3963 	dprintso(so, 1,
3964 		("sosend_svc: %p, resid %ld bytes, prim %d, sflag 0x%x\n",
3965 		so, uiop->uio_resid, prim, sflag));
3966 
3967 	/*
3968 	 * Has to be bound and connected. However, since no locks are
3969 	 * held the state could have changed after sotpi_sendmsg checked it
3970 	 * thus it is not possible to ASSERT on the state.
3971 	 */
3972 
3973 	do {
3974 		/*
3975 		 * Set the MORE flag if uio_resid does not fit in this
3976 		 * message or if the caller passed in "more".
3977 		 * Error for transports with zero tidu_size.
3978 		 */
3979 		tdr.PRIM_type = prim;
3980 		iosize = so->so_tidu_size;
3981 		if (iosize <= 0)
3982 			return (EMSGSIZE);
3983 		if (uiop->uio_resid > iosize) {
3984 			tdr.MORE_flag = 1;
3985 		} else {
3986 			if (more)
3987 				tdr.MORE_flag = 1;
3988 			else
3989 				tdr.MORE_flag = 0;
3990 			iosize = uiop->uio_resid;
3991 		}
3992 		dprintso(so, 1, ("sosend_svc: sending 0x%x %d, %ld bytes\n",
3993 			prim, tdr.MORE_flag, iosize));
3994 		mp = soallocproto1(&tdr, sizeof (tdr), 0, _ALLOC_INTR);
3995 		if (mp == NULL) {
3996 			/*
3997 			 * Caught a signal waiting for memory.
3998 			 * Let send* return EINTR.
3999 			 */
4000 			if (first)
4001 				return (EINTR);
4002 			else
4003 				return (0);
4004 		}
4005 
4006 		error = kstrputmsg(SOTOV(so), mp, uiop, iosize,
4007 					0, sflag | MSG_BAND, 0);
4008 		if (error) {
4009 			if (!first && error == EWOULDBLOCK)
4010 				return (0);
4011 			eprintsoline(so, error);
4012 			return (error);
4013 		}
4014 		first = 0;
4015 		if (uiop->uio_resid > 0) {
4016 			/*
4017 			 * Recheck for fatal errors. Fail write even though
4018 			 * some data have been written. This is consistent
4019 			 * with strwrite semantics and BSD sockets semantics.
4020 			 */
4021 			if (so->so_state & SS_CANTSENDMORE) {
4022 				tsignal(curthread, SIGPIPE);
4023 				eprintsoline(so, error);
4024 				return (EPIPE);
4025 			}
4026 			if (so->so_error != 0) {
4027 				mutex_enter(&so->so_lock);
4028 				error = sogeterr(so);
4029 				mutex_exit(&so->so_lock);
4030 				if (error != 0) {
4031 					eprintsoline(so, error);
4032 					return (error);
4033 				}
4034 			}
4035 		}
4036 	} while (uiop->uio_resid > 0);
4037 	return (0);
4038 }
4039 
4040 /*
4041  * Check the state for errors and call the appropriate send function.
4042  *
4043  * If MSG_DONTROUTE is set (and SO_DONTROUTE isn't already set)
4044  * this function issues a setsockopt to toggle SO_DONTROUTE before and
4045  * after sending the message.
4046  */
4047 static int
4048 sotpi_sendmsg(struct sonode *so, struct nmsghdr *msg, struct uio *uiop)
4049 {
4050 	int		so_state;
4051 	int		so_mode;
4052 	int		error;
4053 	struct sockaddr *name;
4054 	t_uscalar_t	namelen;
4055 	int		dontroute;
4056 	int		flags;
4057 
4058 	dprintso(so, 1, ("sotpi_sendmsg(%p, %p, 0x%x) state %s, error %d\n",
4059 		so, msg, msg->msg_flags,
4060 		pr_state(so->so_state, so->so_mode), so->so_error));
4061 
4062 	mutex_enter(&so->so_lock);
4063 	so_state = so->so_state;
4064 
4065 	if (so_state & SS_CANTSENDMORE) {
4066 		mutex_exit(&so->so_lock);
4067 		tsignal(curthread, SIGPIPE);
4068 		return (EPIPE);
4069 	}
4070 
4071 	if (so->so_error != 0) {
4072 		error = sogeterr(so);
4073 		if (error != 0) {
4074 			mutex_exit(&so->so_lock);
4075 			return (error);
4076 		}
4077 	}
4078 
4079 	name = (struct sockaddr *)msg->msg_name;
4080 	namelen = msg->msg_namelen;
4081 
4082 	so_mode = so->so_mode;
4083 
4084 	if (name == NULL) {
4085 		if (!(so_state & SS_ISCONNECTED)) {
4086 			mutex_exit(&so->so_lock);
4087 			if (so_mode & SM_CONNREQUIRED)
4088 				return (ENOTCONN);
4089 			else
4090 				return (EDESTADDRREQ);
4091 		}
4092 		if (so_mode & SM_CONNREQUIRED) {
4093 			name = NULL;
4094 			namelen = 0;
4095 		} else {
4096 			/*
4097 			 * Note that this code does not prevent so_faddr_sa
4098 			 * from changing while it is being used. Thus
4099 			 * if an "unconnect"+connect occurs concurrently with
4100 			 * this send the datagram might be delivered to a
4101 			 * garbaled address.
4102 			 */
4103 			ASSERT(so->so_faddr_sa);
4104 			name = so->so_faddr_sa;
4105 			namelen = (t_uscalar_t)so->so_faddr_len;
4106 		}
4107 	} else {
4108 		if (!(so_state & SS_ISCONNECTED) &&
4109 		    (so_mode & SM_CONNREQUIRED)) {
4110 			/* Required but not connected */
4111 			mutex_exit(&so->so_lock);
4112 			return (ENOTCONN);
4113 		}
4114 		/*
4115 		 * Ignore the address on connection-oriented sockets.
4116 		 * Just like BSD this code does not generate an error for
4117 		 * TCP (a CONNREQUIRED socket) when sending to an address
4118 		 * passed in with sendto/sendmsg. Instead the data is
4119 		 * delivered on the connection as if no address had been
4120 		 * supplied.
4121 		 */
4122 		if ((so_state & SS_ISCONNECTED) &&
4123 		    !(so_mode & SM_CONNREQUIRED)) {
4124 			mutex_exit(&so->so_lock);
4125 			return (EISCONN);
4126 		}
4127 		if (!(so_state & SS_ISBOUND)) {
4128 			so_lock_single(so);	/* Set SOLOCKED */
4129 			error = sotpi_bind(so, NULL, 0,
4130 			    _SOBIND_UNSPEC|_SOBIND_LOCK_HELD);
4131 			so_unlock_single(so, SOLOCKED);
4132 			if (error) {
4133 				mutex_exit(&so->so_lock);
4134 				eprintsoline(so, error);
4135 				return (error);
4136 			}
4137 		}
4138 		/*
4139 		 * Handle delayed datagram errors. These are only queued
4140 		 * when the application sets SO_DGRAM_ERRIND.
4141 		 * Return the error if we are sending to the address
4142 		 * that was returned in the last T_UDERROR_IND.
4143 		 * If sending to some other address discard the delayed
4144 		 * error indication.
4145 		 */
4146 		if (so->so_delayed_error) {
4147 			struct T_uderror_ind	*tudi;
4148 			void			*addr;
4149 			t_uscalar_t		addrlen;
4150 			boolean_t		match = B_FALSE;
4151 
4152 			ASSERT(so->so_eaddr_mp);
4153 			error = so->so_delayed_error;
4154 			so->so_delayed_error = 0;
4155 			tudi = (struct T_uderror_ind *)so->so_eaddr_mp->b_rptr;
4156 			addrlen = tudi->DEST_length;
4157 			addr = sogetoff(so->so_eaddr_mp,
4158 					tudi->DEST_offset,
4159 					addrlen, 1);
4160 			ASSERT(addr);	/* Checked by strsock_proto */
4161 			switch (so->so_family) {
4162 			case AF_INET: {
4163 				/* Compare just IP address and port */
4164 				sin_t *sin1 = (sin_t *)name;
4165 				sin_t *sin2 = (sin_t *)addr;
4166 
4167 				if (addrlen == sizeof (sin_t) &&
4168 				    namelen == addrlen &&
4169 				    sin1->sin_port == sin2->sin_port &&
4170 				    sin1->sin_addr.s_addr ==
4171 				    sin2->sin_addr.s_addr)
4172 					match = B_TRUE;
4173 				break;
4174 			}
4175 			case AF_INET6: {
4176 				/* Compare just IP address and port. Not flow */
4177 				sin6_t *sin1 = (sin6_t *)name;
4178 				sin6_t *sin2 = (sin6_t *)addr;
4179 
4180 				if (addrlen == sizeof (sin6_t) &&
4181 				    namelen == addrlen &&
4182 				    sin1->sin6_port == sin2->sin6_port &&
4183 				    IN6_ARE_ADDR_EQUAL(&sin1->sin6_addr,
4184 					&sin2->sin6_addr))
4185 					match = B_TRUE;
4186 				break;
4187 			}
4188 			case AF_UNIX:
4189 			default:
4190 				if (namelen == addrlen &&
4191 				    bcmp(name, addr, namelen) == 0)
4192 					match = B_TRUE;
4193 			}
4194 			if (match) {
4195 				freemsg(so->so_eaddr_mp);
4196 				so->so_eaddr_mp = NULL;
4197 				mutex_exit(&so->so_lock);
4198 #ifdef DEBUG
4199 				dprintso(so, 0,
4200 					("sockfs delayed error %d for %s\n",
4201 					error,
4202 					pr_addr(so->so_family, name, namelen)));
4203 #endif /* DEBUG */
4204 				return (error);
4205 			}
4206 			freemsg(so->so_eaddr_mp);
4207 			so->so_eaddr_mp = NULL;
4208 		}
4209 	}
4210 	mutex_exit(&so->so_lock);
4211 
4212 	flags = msg->msg_flags;
4213 	dontroute = 0;
4214 	if ((flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE)) {
4215 		uint32_t	val;
4216 
4217 		val = 1;
4218 		error = sotpi_setsockopt(so, SOL_SOCKET, SO_DONTROUTE,
4219 					&val, (t_uscalar_t)sizeof (val));
4220 		if (error)
4221 			return (error);
4222 		dontroute = 1;
4223 	}
4224 
4225 	if ((flags & MSG_OOB) && !(so_mode & SM_EXDATA)) {
4226 		error = EOPNOTSUPP;
4227 		goto done;
4228 	}
4229 	if (msg->msg_controllen != 0) {
4230 		if (!(so_mode & SM_CONNREQUIRED)) {
4231 			error = sosend_dgramcmsg(so, name, namelen, uiop,
4232 			    msg->msg_control, msg->msg_controllen, flags);
4233 		} else {
4234 			if (flags & MSG_OOB) {
4235 				/* Can't generate T_EXDATA_REQ with options */
4236 				error = EOPNOTSUPP;
4237 				goto done;
4238 			}
4239 			error = sosend_svccmsg(so, uiop,
4240 				!(flags & MSG_EOR),
4241 				msg->msg_control, msg->msg_controllen,
4242 				flags);
4243 		}
4244 		goto done;
4245 	}
4246 
4247 	if (!(so_mode & SM_CONNREQUIRED)) {
4248 		/*
4249 		 * If there is no SO_DONTROUTE to turn off return immediately
4250 		 * from send_dgram. This can allow tail-call optimizations.
4251 		 */
4252 		if (!dontroute) {
4253 			return (sosend_dgram(so, name, namelen, uiop, flags));
4254 		}
4255 		error = sosend_dgram(so, name, namelen, uiop, flags);
4256 	} else {
4257 		t_scalar_t prim;
4258 		int sflag;
4259 
4260 		/* Ignore msg_name in the connected state */
4261 		if (flags & MSG_OOB) {
4262 			prim = T_EXDATA_REQ;
4263 			/*
4264 			 * Send down T_EXDATA_REQ even if there is flow
4265 			 * control for data.
4266 			 */
4267 			sflag = MSG_IGNFLOW;
4268 		} else {
4269 			if (so_mode & SM_BYTESTREAM) {
4270 				/* Byte stream transport - use write */
4271 
4272 				dprintso(so, 1, ("sotpi_sendmsg: write\n"));
4273 				/*
4274 				 * If there is no SO_DONTROUTE to turn off,
4275 				 * SS_DIRECT is on, and there is no flow
4276 				 * control, we can take the fast path.
4277 				 */
4278 				if (!dontroute &&
4279 				    (so_state & SS_DIRECT) &&
4280 				    canputnext(SOTOV(so)->v_stream->sd_wrq)) {
4281 					return (sostream_direct(so, uiop,
4282 					    NULL, CRED()));
4283 				}
4284 				error = strwrite(SOTOV(so), uiop, CRED());
4285 				goto done;
4286 			}
4287 			prim = T_DATA_REQ;
4288 			sflag = 0;
4289 		}
4290 		/*
4291 		 * If there is no SO_DONTROUTE to turn off return immediately
4292 		 * from sosend_svc. This can allow tail-call optimizations.
4293 		 */
4294 		if (!dontroute)
4295 			return (sosend_svc(so, uiop, prim,
4296 				!(flags & MSG_EOR), sflag));
4297 		error = sosend_svc(so, uiop, prim,
4298 				!(flags & MSG_EOR), sflag);
4299 	}
4300 	ASSERT(dontroute);
4301 done:
4302 	if (dontroute) {
4303 		uint32_t	val;
4304 
4305 		val = 0;
4306 		(void) sotpi_setsockopt(so, SOL_SOCKET, SO_DONTROUTE,
4307 				&val, (t_uscalar_t)sizeof (val));
4308 	}
4309 	return (error);
4310 }
4311 
4312 /*
4313  * Sending data on a datagram socket.
4314  * Assumes caller has verified that SS_ISBOUND etc. are set.
4315  */
4316 /* ARGSUSED */
4317 static int
4318 sodgram_direct(struct sonode *so, struct sockaddr *name,
4319     socklen_t namelen, struct uio *uiop, int flags)
4320 {
4321 	struct T_unitdata_req	tudr;
4322 	mblk_t			*mp;
4323 	int			error = 0;
4324 	void			*addr;
4325 	socklen_t		addrlen;
4326 	ssize_t			len;
4327 	struct stdata		*stp = SOTOV(so)->v_stream;
4328 	int			so_state;
4329 	queue_t			*udp_wq;
4330 
4331 	ASSERT(name != NULL && namelen != 0);
4332 	ASSERT(!(so->so_mode & SM_CONNREQUIRED));
4333 	ASSERT(!(so->so_mode & SM_EXDATA));
4334 	ASSERT(so->so_family == AF_INET || so->so_family == AF_INET6);
4335 	ASSERT(SOTOV(so)->v_type == VSOCK);
4336 
4337 	/* Caller checked for proper length */
4338 	len = uiop->uio_resid;
4339 	ASSERT(len <= so->so_tidu_size);
4340 
4341 	/* Length and family checks have been done by caller */
4342 	ASSERT(name->sa_family == so->so_family);
4343 	ASSERT(so->so_family == AF_INET ||
4344 	    (namelen == (socklen_t)sizeof (struct sockaddr_in6)));
4345 	ASSERT(so->so_family == AF_INET6 ||
4346 	    (namelen == (socklen_t)sizeof (struct sockaddr_in)));
4347 
4348 	addr = name;
4349 	addrlen = namelen;
4350 
4351 	if (stp->sd_sidp != NULL &&
4352 	    (error = straccess(stp, JCWRITE)) != 0)
4353 		goto done;
4354 
4355 	so_state = so->so_state;
4356 
4357 	/*
4358 	 * For UDP we don't break up the copyin into smaller pieces
4359 	 * as in the TCP case.  That means if ENOMEM is returned by
4360 	 * mcopyinuio() then the uio vector has not been modified at
4361 	 * all and we fallback to either strwrite() or kstrputmsg()
4362 	 * below.  Note also that we never generate priority messages
4363 	 * from here.
4364 	 */
4365 	udp_wq = stp->sd_wrq->q_next;
4366 	if (canput(udp_wq) &&
4367 	    (mp = mcopyinuio(stp, uiop, -1, -1, &error)) != NULL) {
4368 		ASSERT(DB_TYPE(mp) == M_DATA);
4369 		ASSERT(uiop->uio_resid == 0);
4370 #ifdef C2_AUDIT
4371 		if (audit_active)
4372 			audit_sock(T_UNITDATA_REQ, strvp2wq(SOTOV(so)), mp, 0);
4373 #endif /* C2_AUDIT */
4374 		udp_wput_data(udp_wq, mp, addr, addrlen);
4375 		return (0);
4376 	}
4377 	if (error != 0 && error != ENOMEM)
4378 		return (error);
4379 
4380 	/*
4381 	 * For connected, let strwrite() handle the blocking case.
4382 	 * Otherwise we fall thru and use kstrputmsg().
4383 	 */
4384 	if (so_state & SS_ISCONNECTED)
4385 		return (strwrite(SOTOV(so), uiop, CRED()));
4386 
4387 	tudr.PRIM_type = T_UNITDATA_REQ;
4388 	tudr.DEST_length = addrlen;
4389 	tudr.DEST_offset = (t_scalar_t)sizeof (tudr);
4390 	tudr.OPT_length = 0;
4391 	tudr.OPT_offset = 0;
4392 
4393 	mp = soallocproto2(&tudr, sizeof (tudr), addr, addrlen, 0, _ALLOC_INTR);
4394 	if (mp == NULL) {
4395 		/*
4396 		 * Caught a signal waiting for memory.
4397 		 * Let send* return EINTR.
4398 		 */
4399 		error = EINTR;
4400 		goto done;
4401 	}
4402 
4403 #ifdef C2_AUDIT
4404 	if (audit_active)
4405 		audit_sock(T_UNITDATA_REQ, strvp2wq(SOTOV(so)), mp, 0);
4406 #endif /* C2_AUDIT */
4407 
4408 	error = kstrputmsg(SOTOV(so), mp, uiop, len, 0, MSG_BAND, 0);
4409 done:
4410 #ifdef SOCK_DEBUG
4411 	if (error != 0) {
4412 		eprintsoline(so, error);
4413 	}
4414 #endif /* SOCK_DEBUG */
4415 	return (error);
4416 }
4417 
4418 int
4419 sostream_direct(struct sonode *so, struct uio *uiop, mblk_t *mp, cred_t *cr)
4420 {
4421 	struct stdata *stp = SOTOV(so)->v_stream;
4422 	ssize_t iosize, rmax, maxblk;
4423 	queue_t *tcp_wq = stp->sd_wrq->q_next;
4424 	mblk_t *newmp;
4425 	int error = 0, wflag = 0;
4426 
4427 	ASSERT(so->so_mode & SM_BYTESTREAM);
4428 	ASSERT(SOTOV(so)->v_type == VSOCK);
4429 
4430 	if (stp->sd_sidp != NULL &&
4431 	    (error = straccess(stp, JCWRITE)) != 0)
4432 		return (error);
4433 
4434 	if (uiop == NULL) {
4435 		/*
4436 		 * kstrwritemp() should have checked sd_flag and
4437 		 * flow-control before coming here.  If we end up
4438 		 * here it means that we can simply pass down the
4439 		 * data to tcp.
4440 		 */
4441 		ASSERT(mp != NULL);
4442 		if (stp->sd_wputdatafunc != NULL) {
4443 			newmp = (stp->sd_wputdatafunc)(SOTOV(so), mp, NULL,
4444 			    NULL, NULL, NULL);
4445 			if (newmp == NULL) {
4446 				/* The caller will free mp */
4447 				return (ECOMM);
4448 			}
4449 			mp = newmp;
4450 		}
4451 		tcp_wput(tcp_wq, mp);
4452 		return (0);
4453 	}
4454 
4455 	/* Fallback to strwrite() to do proper error handling */
4456 	if (stp->sd_flag & (STWRERR|STRHUP|STPLEX|STRDELIM|OLDNDELAY))
4457 		return (strwrite(SOTOV(so), uiop, cr));
4458 
4459 	rmax = stp->sd_qn_maxpsz;
4460 	ASSERT(rmax >= 0 || rmax == INFPSZ);
4461 	if (rmax == 0 || uiop->uio_resid <= 0)
4462 		return (0);
4463 
4464 	if (rmax == INFPSZ)
4465 		rmax = uiop->uio_resid;
4466 
4467 	maxblk = stp->sd_maxblk;
4468 
4469 	for (;;) {
4470 		iosize = MIN(uiop->uio_resid, rmax);
4471 
4472 		mp = mcopyinuio(stp, uiop, iosize, maxblk, &error);
4473 		if (mp == NULL) {
4474 			/*
4475 			 * Fallback to strwrite() for ENOMEM; if this
4476 			 * is our first time in this routine and the uio
4477 			 * vector has not been modified, we will end up
4478 			 * calling strwrite() without any flag set.
4479 			 */
4480 			if (error == ENOMEM)
4481 				goto slow_send;
4482 			else
4483 				return (error);
4484 		}
4485 		ASSERT(uiop->uio_resid >= 0);
4486 		/*
4487 		 * If mp is non-NULL and ENOMEM is set, it means that
4488 		 * mcopyinuio() was able to break down some of the user
4489 		 * data into one or more mblks.  Send the partial data
4490 		 * to tcp and let the rest be handled in strwrite().
4491 		 */
4492 		ASSERT(error == 0 || error == ENOMEM);
4493 		if (stp->sd_wputdatafunc != NULL) {
4494 			newmp = (stp->sd_wputdatafunc)(SOTOV(so), mp, NULL,
4495 			    NULL, NULL, NULL);
4496 			if (newmp == NULL) {
4497 				/* The caller will free mp */
4498 				return (ECOMM);
4499 			}
4500 			mp = newmp;
4501 		}
4502 		tcp_wput(tcp_wq, mp);
4503 
4504 		wflag |= NOINTR;
4505 
4506 		if (uiop->uio_resid == 0) {	/* No more data; we're done */
4507 			ASSERT(error == 0);
4508 			break;
4509 		} else if (error == ENOMEM || !canput(tcp_wq) || (stp->sd_flag &
4510 		    (STWRERR|STRHUP|STPLEX|STRDELIM|OLDNDELAY))) {
4511 slow_send:
4512 			/*
4513 			 * We were able to send down partial data using
4514 			 * the direct call interface, but are now relying
4515 			 * on strwrite() to handle the non-fastpath cases.
4516 			 * If the socket is blocking we will sleep in
4517 			 * strwaitq() until write is permitted, otherwise,
4518 			 * we will need to return the amount of bytes
4519 			 * written so far back to the app.  This is the
4520 			 * reason why we pass NOINTR flag to strwrite()
4521 			 * for non-blocking socket, because we don't want
4522 			 * to return EAGAIN when portion of the user data
4523 			 * has actually been sent down.
4524 			 */
4525 			return (strwrite_common(SOTOV(so), uiop, cr, wflag));
4526 		}
4527 	}
4528 	return (0);
4529 }
4530 
4531 /*
4532  * Update so_faddr by asking the transport (unless AF_UNIX).
4533  */
4534 int
4535 sotpi_getpeername(struct sonode *so)
4536 {
4537 	struct strbuf	strbuf;
4538 	int		error = 0, res;
4539 	void		*addr;
4540 	t_uscalar_t	addrlen;
4541 	k_sigset_t	smask;
4542 
4543 	dprintso(so, 1, ("sotpi_getpeername(%p) %s\n",
4544 		so, pr_state(so->so_state, so->so_mode)));
4545 
4546 	mutex_enter(&so->so_lock);
4547 	so_lock_single(so);	/* Set SOLOCKED */
4548 	if (!(so->so_state & SS_ISCONNECTED)) {
4549 		error = ENOTCONN;
4550 		goto done;
4551 	}
4552 	/* Added this check for X/Open */
4553 	if ((so->so_state & SS_CANTSENDMORE) && !xnet_skip_checks) {
4554 		error = EINVAL;
4555 		if (xnet_check_print) {
4556 			printf("sockfs: X/Open getpeername check => EINVAL\n");
4557 		}
4558 		goto done;
4559 	}
4560 #ifdef DEBUG
4561 	dprintso(so, 1, ("sotpi_getpeername (local): %s\n",
4562 		pr_addr(so->so_family, so->so_faddr_sa,
4563 			(t_uscalar_t)so->so_faddr_len)));
4564 #endif /* DEBUG */
4565 
4566 	if (so->so_family == AF_UNIX) {
4567 		/* Transport has different name space - return local info */
4568 		error = 0;
4569 		goto done;
4570 	}
4571 
4572 	ASSERT(so->so_faddr_sa);
4573 	/* Allocate local buffer to use with ioctl */
4574 	addrlen = (t_uscalar_t)so->so_faddr_maxlen;
4575 	mutex_exit(&so->so_lock);
4576 	addr = kmem_alloc(addrlen, KM_SLEEP);
4577 
4578 	/*
4579 	 * Issue TI_GETPEERNAME with signals masked.
4580 	 * Put the result in so_faddr_sa so that getpeername works after
4581 	 * a shutdown(output).
4582 	 * If the ioctl fails (e.g. due to a ECONNRESET) the error is reposted
4583 	 * back to the socket.
4584 	 */
4585 	strbuf.buf = addr;
4586 	strbuf.maxlen = addrlen;
4587 	strbuf.len = 0;
4588 
4589 	sigintr(&smask, 0);
4590 	res = 0;
4591 	ASSERT(CRED());
4592 	error = strioctl(SOTOV(so), TI_GETPEERNAME, (intptr_t)&strbuf,
4593 			0, K_TO_K, CRED(), &res);
4594 	sigunintr(&smask);
4595 
4596 	mutex_enter(&so->so_lock);
4597 	/*
4598 	 * If there is an error record the error in so_error put don't fail
4599 	 * the getpeername. Instead fallback on the recorded
4600 	 * so->so_faddr_sa.
4601 	 */
4602 	if (error) {
4603 		/*
4604 		 * Various stream head errors can be returned to the ioctl.
4605 		 * However, it is impossible to determine which ones of
4606 		 * these are really socket level errors that were incorrectly
4607 		 * consumed by the ioctl. Thus this code silently ignores the
4608 		 * error - to code explicitly does not reinstate the error
4609 		 * using soseterror().
4610 		 * Experiments have shows that at least this set of
4611 		 * errors are reported and should not be reinstated on the
4612 		 * socket:
4613 		 *	EINVAL	E.g. if an I_LINK was in effect when
4614 		 *		getpeername was called.
4615 		 *	EPIPE	The ioctl error semantics prefer the write
4616 		 *		side error over the read side error.
4617 		 *	ENOTCONN The transport just got disconnected but
4618 		 *		sockfs had not yet seen the T_DISCON_IND
4619 		 *		when issuing the ioctl.
4620 		 */
4621 		error = 0;
4622 	} else if (res == 0 && strbuf.len > 0 &&
4623 	    (so->so_state & SS_ISCONNECTED)) {
4624 		ASSERT(strbuf.len <= (int)so->so_faddr_maxlen);
4625 		so->so_faddr_len = (socklen_t)strbuf.len;
4626 		bcopy(addr, so->so_faddr_sa, so->so_faddr_len);
4627 		so->so_state |= SS_FADDR_VALID;
4628 	}
4629 	kmem_free(addr, addrlen);
4630 #ifdef DEBUG
4631 	dprintso(so, 1, ("sotpi_getpeername (tp): %s\n",
4632 			pr_addr(so->so_family, so->so_faddr_sa,
4633 				(t_uscalar_t)so->so_faddr_len)));
4634 #endif /* DEBUG */
4635 done:
4636 	so_unlock_single(so, SOLOCKED);
4637 	mutex_exit(&so->so_lock);
4638 	return (error);
4639 }
4640 
4641 /*
4642  * Update so_laddr by asking the transport (unless AF_UNIX).
4643  */
4644 int
4645 sotpi_getsockname(struct sonode *so)
4646 {
4647 	struct strbuf	strbuf;
4648 	int		error = 0, res;
4649 	void		*addr;
4650 	t_uscalar_t	addrlen;
4651 	k_sigset_t	smask;
4652 
4653 	dprintso(so, 1, ("sotpi_getsockname(%p) %s\n",
4654 		so, pr_state(so->so_state, so->so_mode)));
4655 
4656 	mutex_enter(&so->so_lock);
4657 	so_lock_single(so);	/* Set SOLOCKED */
4658 	if (!(so->so_state & SS_ISBOUND) && so->so_family != AF_UNIX) {
4659 		/* Return an all zero address except for the family */
4660 		if (so->so_family == AF_INET)
4661 			so->so_laddr_len = (socklen_t)sizeof (sin_t);
4662 		else if (so->so_family == AF_INET6)
4663 			so->so_laddr_len = (socklen_t)sizeof (sin6_t);
4664 		ASSERT(so->so_laddr_len <= so->so_laddr_maxlen);
4665 		bzero(so->so_laddr_sa, so->so_laddr_len);
4666 		/*
4667 		 * Can not assume there is a sa_family for all
4668 		 * protocol families.
4669 		 */
4670 		if (so->so_family == AF_INET || so->so_family == AF_INET6)
4671 			so->so_laddr_sa->sa_family = so->so_family;
4672 	}
4673 #ifdef DEBUG
4674 	dprintso(so, 1, ("sotpi_getsockname (local): %s\n",
4675 		pr_addr(so->so_family, so->so_laddr_sa,
4676 			(t_uscalar_t)so->so_laddr_len)));
4677 #endif /* DEBUG */
4678 	if (so->so_family == AF_UNIX) {
4679 		/* Transport has different name space - return local info */
4680 		error = 0;
4681 		goto done;
4682 	}
4683 	if (!(so->so_state & SS_ISBOUND)) {
4684 		/* If not bound, then nothing to return. */
4685 		error = 0;
4686 		goto done;
4687 	}
4688 	/* Allocate local buffer to use with ioctl */
4689 	addrlen = (t_uscalar_t)so->so_laddr_maxlen;
4690 	mutex_exit(&so->so_lock);
4691 	addr = kmem_alloc(addrlen, KM_SLEEP);
4692 
4693 	/*
4694 	 * Issue TI_GETMYNAME with signals masked.
4695 	 * Put the result in so_laddr_sa so that getsockname works after
4696 	 * a shutdown(output).
4697 	 * If the ioctl fails (e.g. due to a ECONNRESET) the error is reposted
4698 	 * back to the socket.
4699 	 */
4700 	strbuf.buf = addr;
4701 	strbuf.maxlen = addrlen;
4702 	strbuf.len = 0;
4703 
4704 	sigintr(&smask, 0);
4705 	res = 0;
4706 	ASSERT(CRED());
4707 	error = strioctl(SOTOV(so), TI_GETMYNAME, (intptr_t)&strbuf,
4708 			0, K_TO_K, CRED(), &res);
4709 	sigunintr(&smask);
4710 
4711 	mutex_enter(&so->so_lock);
4712 	/*
4713 	 * If there is an error record the error in so_error put don't fail
4714 	 * the getsockname. Instead fallback on the recorded
4715 	 * so->so_laddr_sa.
4716 	 */
4717 	if (error) {
4718 		/*
4719 		 * Various stream head errors can be returned to the ioctl.
4720 		 * However, it is impossible to determine which ones of
4721 		 * these are really socket level errors that were incorrectly
4722 		 * consumed by the ioctl. Thus this code silently ignores the
4723 		 * error - to code explicitly does not reinstate the error
4724 		 * using soseterror().
4725 		 * Experiments have shows that at least this set of
4726 		 * errors are reported and should not be reinstated on the
4727 		 * socket:
4728 		 *	EINVAL	E.g. if an I_LINK was in effect when
4729 		 *		getsockname was called.
4730 		 *	EPIPE	The ioctl error semantics prefer the write
4731 		 *		side error over the read side error.
4732 		 */
4733 		error = 0;
4734 	} else if (res == 0 && strbuf.len > 0 &&
4735 	    (so->so_state & SS_ISBOUND)) {
4736 		ASSERT(strbuf.len <= (int)so->so_laddr_maxlen);
4737 		so->so_laddr_len = (socklen_t)strbuf.len;
4738 		bcopy(addr, so->so_laddr_sa, so->so_laddr_len);
4739 		so->so_state |= SS_LADDR_VALID;
4740 	}
4741 	kmem_free(addr, addrlen);
4742 #ifdef DEBUG
4743 	dprintso(so, 1, ("sotpi_getsockname (tp): %s\n",
4744 			pr_addr(so->so_family, so->so_laddr_sa,
4745 				(t_uscalar_t)so->so_laddr_len)));
4746 #endif /* DEBUG */
4747 done:
4748 	so_unlock_single(so, SOLOCKED);
4749 	mutex_exit(&so->so_lock);
4750 	return (error);
4751 }
4752 
4753 /*
4754  * Get socket options. For SOL_SOCKET options some options are handled
4755  * by the sockfs while others use the value recorded in the sonode as a
4756  * fallback should the T_SVR4_OPTMGMT_REQ fail.
4757  *
4758  * On the return most *optlenp bytes are copied to optval.
4759  */
4760 int
4761 sotpi_getsockopt(struct sonode *so, int level, int option_name,
4762 		void *optval, socklen_t *optlenp, int flags)
4763 {
4764 	struct T_optmgmt_req	optmgmt_req;
4765 	struct T_optmgmt_ack	*optmgmt_ack;
4766 	struct opthdr		oh;
4767 	struct opthdr		*opt_res;
4768 	mblk_t			*mp = NULL;
4769 	int			error = 0;
4770 	void			*option = NULL;	/* Set if fallback value */
4771 	t_uscalar_t		maxlen = *optlenp;
4772 	t_uscalar_t		len;
4773 	uint32_t		value;
4774 
4775 	dprintso(so, 1, ("sotpi_getsockopt(%p, 0x%x, 0x%x, %p, %p) %s\n",
4776 			so, level, option_name, optval, optlenp,
4777 			pr_state(so->so_state, so->so_mode)));
4778 
4779 	mutex_enter(&so->so_lock);
4780 	so_lock_single(so);	/* Set SOLOCKED */
4781 
4782 	/*
4783 	 * Check for SOL_SOCKET options.
4784 	 * Certain SOL_SOCKET options are returned directly whereas
4785 	 * others only provide a default (fallback) value should
4786 	 * the T_SVR4_OPTMGMT_REQ fail.
4787 	 */
4788 	if (level == SOL_SOCKET) {
4789 		/* Check parameters */
4790 		switch (option_name) {
4791 		case SO_TYPE:
4792 		case SO_ERROR:
4793 		case SO_DEBUG:
4794 		case SO_ACCEPTCONN:
4795 		case SO_REUSEADDR:
4796 		case SO_KEEPALIVE:
4797 		case SO_DONTROUTE:
4798 		case SO_BROADCAST:
4799 		case SO_USELOOPBACK:
4800 		case SO_OOBINLINE:
4801 		case SO_SNDBUF:
4802 		case SO_RCVBUF:
4803 #ifdef notyet
4804 		case SO_SNDLOWAT:
4805 		case SO_RCVLOWAT:
4806 		case SO_SNDTIMEO:
4807 		case SO_RCVTIMEO:
4808 #endif /* notyet */
4809 		case SO_DOMAIN:
4810 		case SO_DGRAM_ERRIND:
4811 			if (maxlen < (t_uscalar_t)sizeof (int32_t)) {
4812 				error = EINVAL;
4813 				eprintsoline(so, error);
4814 				goto done2;
4815 			}
4816 			break;
4817 		case SO_LINGER:
4818 			if (maxlen < (t_uscalar_t)sizeof (struct linger)) {
4819 				error = EINVAL;
4820 				eprintsoline(so, error);
4821 				goto done2;
4822 			}
4823 			break;
4824 		}
4825 
4826 		len = (t_uscalar_t)sizeof (uint32_t);	/* Default */
4827 
4828 		switch (option_name) {
4829 		case SO_TYPE:
4830 			value = so->so_type;
4831 			option = &value;
4832 			goto copyout; /* No need to issue T_SVR4_OPTMGMT_REQ */
4833 
4834 		case SO_ERROR:
4835 			value = sogeterr(so);
4836 			option = &value;
4837 			goto copyout; /* No need to issue T_SVR4_OPTMGMT_REQ */
4838 
4839 		case SO_ACCEPTCONN:
4840 			if (so->so_state & SS_ACCEPTCONN)
4841 				value = SO_ACCEPTCONN;
4842 			else
4843 				value = 0;
4844 #ifdef DEBUG
4845 			if (value) {
4846 				dprintso(so, 1,
4847 				    ("sotpi_getsockopt: 0x%x is set\n",
4848 				    option_name));
4849 			} else {
4850 				dprintso(so, 1,
4851 				    ("sotpi_getsockopt: 0x%x not set\n",
4852 				    option_name));
4853 			}
4854 #endif /* DEBUG */
4855 			option = &value;
4856 			goto copyout; /* No need to issue T_SVR4_OPTMGMT_REQ */
4857 
4858 		case SO_DEBUG:
4859 		case SO_REUSEADDR:
4860 		case SO_KEEPALIVE:
4861 		case SO_DONTROUTE:
4862 		case SO_BROADCAST:
4863 		case SO_USELOOPBACK:
4864 		case SO_OOBINLINE:
4865 		case SO_DGRAM_ERRIND:
4866 			value = (so->so_options & option_name);
4867 #ifdef DEBUG
4868 			if (value) {
4869 				dprintso(so, 1,
4870 				    ("sotpi_getsockopt: 0x%x is set\n",
4871 				    option_name));
4872 			} else {
4873 				dprintso(so, 1,
4874 				    ("sotpi_getsockopt: 0x%x not set\n",
4875 				    option_name));
4876 			}
4877 #endif /* DEBUG */
4878 			option = &value;
4879 			goto copyout; /* No need to issue T_SVR4_OPTMGMT_REQ */
4880 
4881 		/*
4882 		 * The following options are only returned by sockfs when the
4883 		 * T_SVR4_OPTMGMT_REQ fails.
4884 		 */
4885 		case SO_LINGER:
4886 			option = &so->so_linger;
4887 			len = (t_uscalar_t)sizeof (struct linger);
4888 			break;
4889 		case SO_SNDBUF: {
4890 			ssize_t lvalue;
4891 
4892 			/*
4893 			 * If the option has not been set then get a default
4894 			 * value from the read queue. This value is
4895 			 * returned if the transport fails
4896 			 * the T_SVR4_OPTMGMT_REQ.
4897 			 */
4898 			lvalue = so->so_sndbuf;
4899 			if (lvalue == 0) {
4900 				mutex_exit(&so->so_lock);
4901 				(void) strqget(strvp2wq(SOTOV(so))->q_next,
4902 						QHIWAT, 0, &lvalue);
4903 				mutex_enter(&so->so_lock);
4904 				dprintso(so, 1,
4905 				    ("got SO_SNDBUF %ld from q\n", lvalue));
4906 			}
4907 			value = (int)lvalue;
4908 			option = &value;
4909 			len = (t_uscalar_t)sizeof (so->so_sndbuf);
4910 			break;
4911 		}
4912 		case SO_RCVBUF: {
4913 			ssize_t lvalue;
4914 
4915 			/*
4916 			 * If the option has not been set then get a default
4917 			 * value from the read queue. This value is
4918 			 * returned if the transport fails
4919 			 * the T_SVR4_OPTMGMT_REQ.
4920 			 *
4921 			 * XXX If SO_RCVBUF has been set and this is an
4922 			 * XPG 4.2 application then do not ask the transport
4923 			 * since the transport might adjust the value and not
4924 			 * return exactly what was set by the application.
4925 			 * For non-XPG 4.2 application we return the value
4926 			 * that the transport is actually using.
4927 			 */
4928 			lvalue = so->so_rcvbuf;
4929 			if (lvalue == 0) {
4930 				mutex_exit(&so->so_lock);
4931 				(void) strqget(RD(strvp2wq(SOTOV(so))),
4932 						QHIWAT, 0, &lvalue);
4933 				mutex_enter(&so->so_lock);
4934 				dprintso(so, 1,
4935 				    ("got SO_RCVBUF %ld from q\n", lvalue));
4936 			} else if (flags & _SOGETSOCKOPT_XPG4_2) {
4937 				value = (int)lvalue;
4938 				option = &value;
4939 				goto copyout;	/* skip asking transport */
4940 			}
4941 			value = (int)lvalue;
4942 			option = &value;
4943 			len = (t_uscalar_t)sizeof (so->so_rcvbuf);
4944 			break;
4945 		}
4946 		case SO_DOMAIN:
4947 			value = so->so_family;
4948 			option = &value;
4949 			goto copyout; /* No need to issue T_SVR4_OPTMGMT_REQ */
4950 
4951 #ifdef notyet
4952 		/*
4953 		 * We do not implement the semantics of these options
4954 		 * thus we shouldn't implement the options either.
4955 		 */
4956 		case SO_SNDLOWAT:
4957 			value = so->so_sndlowat;
4958 			option = &value;
4959 			break;
4960 		case SO_RCVLOWAT:
4961 			value = so->so_rcvlowat;
4962 			option = &value;
4963 			break;
4964 		case SO_SNDTIMEO:
4965 			value = so->so_sndtimeo;
4966 			option = &value;
4967 			break;
4968 		case SO_RCVTIMEO:
4969 			value = so->so_rcvtimeo;
4970 			option = &value;
4971 			break;
4972 #endif /* notyet */
4973 		}
4974 	}
4975 
4976 	mutex_exit(&so->so_lock);
4977 
4978 	/* Send request */
4979 	optmgmt_req.PRIM_type = T_SVR4_OPTMGMT_REQ;
4980 	optmgmt_req.MGMT_flags = T_CHECK;
4981 	optmgmt_req.OPT_length = (t_scalar_t)(sizeof (oh) + maxlen);
4982 	optmgmt_req.OPT_offset = (t_scalar_t)sizeof (optmgmt_req);
4983 
4984 	oh.level = level;
4985 	oh.name = option_name;
4986 	oh.len = maxlen;
4987 
4988 	mp = soallocproto3(&optmgmt_req, sizeof (optmgmt_req),
4989 	    &oh, sizeof (oh), NULL, maxlen, 0, _ALLOC_SLEEP);
4990 	/* Let option management work in the presence of data flow control */
4991 	error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
4992 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR|MSG_IGNFLOW, 0);
4993 	mp = NULL;
4994 	mutex_enter(&so->so_lock);
4995 	if (error) {
4996 		eprintsoline(so, error);
4997 		goto done2;
4998 	}
4999 	error = sowaitprim(so, T_SVR4_OPTMGMT_REQ, T_OPTMGMT_ACK,
5000 	    (t_uscalar_t)(sizeof (*optmgmt_ack) + sizeof (*opt_res)), &mp, 0);
5001 	if (error) {
5002 		if (option != NULL) {
5003 			/* We have a fallback value */
5004 			error = 0;
5005 			goto copyout;
5006 		}
5007 		eprintsoline(so, error);
5008 		goto done2;
5009 	}
5010 	ASSERT(mp);
5011 	optmgmt_ack = (struct T_optmgmt_ack *)mp->b_rptr;
5012 	opt_res = (struct opthdr *)sogetoff(mp, optmgmt_ack->OPT_offset,
5013 			optmgmt_ack->OPT_length, __TPI_ALIGN_SIZE);
5014 	if (opt_res == NULL) {
5015 		if (option != NULL) {
5016 			/* We have a fallback value */
5017 			error = 0;
5018 			goto copyout;
5019 		}
5020 		error = EPROTO;
5021 		eprintsoline(so, error);
5022 		goto done;
5023 	}
5024 	option = &opt_res[1];
5025 
5026 	/* check to ensure that the option is within bounds */
5027 	if (((uintptr_t)option + opt_res->len < (uintptr_t)option) ||
5028 		(uintptr_t)option + opt_res->len > (uintptr_t)mp->b_wptr) {
5029 		if (option != NULL) {
5030 			/* We have a fallback value */
5031 			error = 0;
5032 			goto copyout;
5033 		}
5034 		error = EPROTO;
5035 		eprintsoline(so, error);
5036 		goto done;
5037 	}
5038 
5039 	len = opt_res->len;
5040 
5041 copyout: {
5042 		t_uscalar_t size = MIN(len, maxlen);
5043 		bcopy(option, optval, size);
5044 		bcopy(&size, optlenp, sizeof (size));
5045 	}
5046 done:
5047 	freemsg(mp);
5048 done2:
5049 	so_unlock_single(so, SOLOCKED);
5050 	mutex_exit(&so->so_lock);
5051 	return (error);
5052 }
5053 
5054 /*
5055  * Set socket options. All options are passed down in a T_SVR4_OPTMGMT_REQ.
5056  * SOL_SOCKET options are also recorded in the sonode. A setsockopt for
5057  * SOL_SOCKET options will not fail just because the T_SVR4_OPTMGMT_REQ fails -
5058  * setsockopt has to work even if the transport does not support the option.
5059  */
5060 int
5061 sotpi_setsockopt(struct sonode *so, int level, int option_name,
5062 	const void *optval, t_uscalar_t optlen)
5063 {
5064 	struct T_optmgmt_req	optmgmt_req;
5065 	struct opthdr		oh;
5066 	mblk_t			*mp;
5067 	int			error = 0;
5068 	boolean_t		handled = B_FALSE;
5069 
5070 	dprintso(so, 1, ("sotpi_setsockopt(%p, 0x%x, 0x%x, %p, %d) %s\n",
5071 			so, level, option_name, optval, optlen,
5072 			pr_state(so->so_state, so->so_mode)));
5073 
5074 
5075 	/* X/Open requires this check */
5076 	if ((so->so_state & SS_CANTSENDMORE) && !xnet_skip_checks) {
5077 		if (xnet_check_print)
5078 			printf("sockfs: X/Open setsockopt check => EINVAL\n");
5079 		return (EINVAL);
5080 	}
5081 
5082 	/* Caller allocates aligned optval, or passes null */
5083 	ASSERT(((uintptr_t)optval & (sizeof (t_scalar_t) - 1)) == 0);
5084 	/* If optval is null optlen is 0, and vice-versa */
5085 	ASSERT(optval != NULL || optlen == 0);
5086 	ASSERT(optlen != 0 || optval == NULL);
5087 
5088 	mutex_enter(&so->so_lock);
5089 	so_lock_single(so);	/* Set SOLOCKED */
5090 	mutex_exit(&so->so_lock);
5091 
5092 	/*
5093 	 * For SOCKET or TCP level options, try to set it here itself
5094 	 * provided socket has not been popped and we know the tcp
5095 	 * structure (stored in so_priv).
5096 	 */
5097 	if ((level == SOL_SOCKET || level == IPPROTO_TCP) &&
5098 	    (so->so_family == AF_INET || so->so_family == AF_INET6) &&
5099 	    (so->so_version == SOV_SOCKSTREAM) && (so->so_priv != NULL)) {
5100 		tcp_t		*tcp = so->so_priv;
5101 		boolean_t	onoff;
5102 
5103 #define	intvalue	(*(int32_t *)optval)
5104 
5105 		switch (level) {
5106 		case SOL_SOCKET:
5107 			switch (option_name) {		/* Check length param */
5108 			case SO_DEBUG:
5109 			case SO_REUSEADDR:
5110 			case SO_DONTROUTE:
5111 			case SO_BROADCAST:
5112 			case SO_USELOOPBACK:
5113 			case SO_OOBINLINE:
5114 			case SO_DGRAM_ERRIND:
5115 				if (optlen != (t_uscalar_t)sizeof (int32_t)) {
5116 					error = EINVAL;
5117 					eprintsoline(so, error);
5118 					mutex_enter(&so->so_lock);
5119 					goto done2;
5120 				}
5121 				ASSERT(optval);
5122 				onoff = intvalue != 0;
5123 				handled = B_TRUE;
5124 				break;
5125 			case SO_LINGER:
5126 				if (optlen !=
5127 				    (t_uscalar_t)sizeof (struct linger)) {
5128 					error = EINVAL;
5129 					eprintsoline(so, error);
5130 					mutex_enter(&so->so_lock);
5131 					goto done2;
5132 				}
5133 				ASSERT(optval);
5134 				handled = B_TRUE;
5135 				break;
5136 			}
5137 
5138 			switch (option_name) {			/* Do actions */
5139 			case SO_LINGER: {
5140 				struct linger *lgr = (struct linger *)optval;
5141 
5142 				if (lgr->l_onoff) {
5143 					tcp->tcp_linger = 1;
5144 					tcp->tcp_lingertime = lgr->l_linger;
5145 					so->so_linger.l_onoff = SO_LINGER;
5146 					so->so_options |= SO_LINGER;
5147 				} else {
5148 					tcp->tcp_linger = 0;
5149 					tcp->tcp_lingertime = 0;
5150 					so->so_linger.l_onoff = 0;
5151 					so->so_options &= ~SO_LINGER;
5152 				}
5153 				so->so_linger.l_linger = lgr->l_linger;
5154 				handled = B_TRUE;
5155 				break;
5156 			}
5157 			case SO_DEBUG:
5158 				tcp->tcp_debug = onoff;
5159 #ifdef SOCK_TEST
5160 				if (intvalue & 2)
5161 					sock_test_timelimit = 10 * hz;
5162 				else
5163 					sock_test_timelimit = 0;
5164 
5165 				if (intvalue & 4)
5166 					do_useracc = 0;
5167 				else
5168 					do_useracc = 1;
5169 #endif /* SOCK_TEST */
5170 				break;
5171 			case SO_DONTROUTE:
5172 				/*
5173 				 * SO_DONTROUTE, SO_USELOOPBACK and
5174 				 * SO_BROADCAST are only of interest to IP.
5175 				 * We track them here only so
5176 				 * that we can report their current value.
5177 				 */
5178 				tcp->tcp_dontroute = onoff;
5179 				if (onoff)
5180 					so->so_options |= option_name;
5181 				else
5182 					so->so_options &= ~option_name;
5183 				break;
5184 			case SO_USELOOPBACK:
5185 				tcp->tcp_useloopback = onoff;
5186 				if (onoff)
5187 					so->so_options |= option_name;
5188 				else
5189 					so->so_options &= ~option_name;
5190 				break;
5191 			case SO_BROADCAST:
5192 				tcp->tcp_broadcast = onoff;
5193 				if (onoff)
5194 					so->so_options |= option_name;
5195 				else
5196 					so->so_options &= ~option_name;
5197 				break;
5198 			case SO_REUSEADDR:
5199 				tcp->tcp_reuseaddr = onoff;
5200 				if (onoff)
5201 					so->so_options |= option_name;
5202 				else
5203 					so->so_options &= ~option_name;
5204 				break;
5205 			case SO_OOBINLINE:
5206 				tcp->tcp_oobinline = onoff;
5207 				if (onoff)
5208 					so->so_options |= option_name;
5209 				else
5210 					so->so_options &= ~option_name;
5211 				break;
5212 			case SO_DGRAM_ERRIND:
5213 				tcp->tcp_dgram_errind = onoff;
5214 				if (onoff)
5215 					so->so_options |= option_name;
5216 				else
5217 					so->so_options &= ~option_name;
5218 				break;
5219 			}
5220 			break;
5221 		case IPPROTO_TCP:
5222 			switch (option_name) {
5223 			case TCP_NODELAY:
5224 				if (optlen != (t_uscalar_t)sizeof (int32_t)) {
5225 					error = EINVAL;
5226 					eprintsoline(so, error);
5227 					mutex_enter(&so->so_lock);
5228 					goto done2;
5229 				}
5230 				ASSERT(optval);
5231 				tcp->tcp_naglim = intvalue ? 1 : tcp->tcp_mss;
5232 				handled = B_TRUE;
5233 				break;
5234 			}
5235 			break;
5236 		default:
5237 			handled = B_FALSE;
5238 			break;
5239 		}
5240 	}
5241 
5242 	if (handled) {
5243 		mutex_enter(&so->so_lock);
5244 		goto done2;
5245 	}
5246 
5247 	optmgmt_req.PRIM_type = T_SVR4_OPTMGMT_REQ;
5248 	optmgmt_req.MGMT_flags = T_NEGOTIATE;
5249 	optmgmt_req.OPT_length = (t_scalar_t)sizeof (oh) + optlen;
5250 	optmgmt_req.OPT_offset = (t_scalar_t)sizeof (optmgmt_req);
5251 
5252 	oh.level = level;
5253 	oh.name = option_name;
5254 	oh.len = optlen;
5255 
5256 	mp = soallocproto3(&optmgmt_req, sizeof (optmgmt_req),
5257 	    &oh, sizeof (oh), optval, optlen, 0, _ALLOC_SLEEP);
5258 	/* Let option management work in the presence of data flow control */
5259 	error = kstrputmsg(SOTOV(so), mp, NULL, 0, 0,
5260 			MSG_BAND|MSG_HOLDSIG|MSG_IGNERROR|MSG_IGNFLOW, 0);
5261 	mp = NULL;
5262 	mutex_enter(&so->so_lock);
5263 	if (error) {
5264 		eprintsoline(so, error);
5265 		goto done;
5266 	}
5267 	error = sowaitprim(so, T_SVR4_OPTMGMT_REQ, T_OPTMGMT_ACK,
5268 	    (t_uscalar_t)sizeof (struct T_optmgmt_ack), &mp, 0);
5269 	if (error) {
5270 		eprintsoline(so, error);
5271 		goto done;
5272 	}
5273 	ASSERT(mp);
5274 	/* No need to verify T_optmgmt_ack */
5275 	freemsg(mp);
5276 done:
5277 	/*
5278 	 * Check for SOL_SOCKET options and record their values.
5279 	 * If we know about a SOL_SOCKET parameter and the transport
5280 	 * failed it with TBADOPT or TOUTSTATE (i.e. ENOPROTOOPT or
5281 	 * EPROTO) we let the setsockopt succeed.
5282 	 */
5283 	if (level == SOL_SOCKET) {
5284 		/* Check parameters */
5285 		switch (option_name) {
5286 		case SO_DEBUG:
5287 		case SO_REUSEADDR:
5288 		case SO_KEEPALIVE:
5289 		case SO_DONTROUTE:
5290 		case SO_BROADCAST:
5291 		case SO_USELOOPBACK:
5292 		case SO_OOBINLINE:
5293 		case SO_SNDBUF:
5294 		case SO_RCVBUF:
5295 #ifdef notyet
5296 		case SO_SNDLOWAT:
5297 		case SO_RCVLOWAT:
5298 		case SO_SNDTIMEO:
5299 		case SO_RCVTIMEO:
5300 #endif /* notyet */
5301 		case SO_DGRAM_ERRIND:
5302 			if (optlen != (t_uscalar_t)sizeof (int32_t)) {
5303 				error = EINVAL;
5304 				eprintsoline(so, error);
5305 				goto done2;
5306 			}
5307 			ASSERT(optval);
5308 			handled = B_TRUE;
5309 			break;
5310 		case SO_LINGER:
5311 			if (optlen != (t_uscalar_t)sizeof (struct linger)) {
5312 				error = EINVAL;
5313 				eprintsoline(so, error);
5314 				goto done2;
5315 			}
5316 			ASSERT(optval);
5317 			handled = B_TRUE;
5318 			break;
5319 		}
5320 
5321 #define	intvalue	(*(int32_t *)optval)
5322 
5323 		switch (option_name) {
5324 		case SO_TYPE:
5325 		case SO_ERROR:
5326 		case SO_ACCEPTCONN:
5327 			/* Can't be set */
5328 			error = ENOPROTOOPT;
5329 			goto done2;
5330 		case SO_LINGER: {
5331 			struct linger *l = (struct linger *)optval;
5332 
5333 			so->so_linger.l_linger = l->l_linger;
5334 			if (l->l_onoff) {
5335 				so->so_linger.l_onoff = SO_LINGER;
5336 				so->so_options |= SO_LINGER;
5337 			} else {
5338 				so->so_linger.l_onoff = 0;
5339 				so->so_options &= ~SO_LINGER;
5340 			}
5341 			break;
5342 		}
5343 
5344 		case SO_DEBUG:
5345 #ifdef SOCK_TEST
5346 			if (intvalue & 2)
5347 				sock_test_timelimit = 10 * hz;
5348 			else
5349 				sock_test_timelimit = 0;
5350 
5351 			if (intvalue & 4)
5352 				do_useracc = 0;
5353 			else
5354 				do_useracc = 1;
5355 #endif /* SOCK_TEST */
5356 			/* FALLTHRU */
5357 		case SO_REUSEADDR:
5358 		case SO_KEEPALIVE:
5359 		case SO_DONTROUTE:
5360 		case SO_BROADCAST:
5361 		case SO_USELOOPBACK:
5362 		case SO_OOBINLINE:
5363 		case SO_DGRAM_ERRIND:
5364 			if (intvalue != 0) {
5365 				dprintso(so, 1,
5366 					("sotpi_setsockopt: setting 0x%x\n",
5367 					option_name));
5368 				so->so_options |= option_name;
5369 			} else {
5370 				dprintso(so, 1,
5371 					("sotpi_setsockopt: clearing 0x%x\n",
5372 					option_name));
5373 				so->so_options &= ~option_name;
5374 			}
5375 			break;
5376 		/*
5377 		 * The following options are only returned by us when the
5378 		 * T_SVR4_OPTMGMT_REQ fails.
5379 		 * XXX XPG 4.2 applications retrieve SO_RCVBUF from sockfs
5380 		 * since the transport might adjust the value and not
5381 		 * return exactly what was set by the application.
5382 		 */
5383 		case SO_SNDBUF:
5384 			so->so_sndbuf = intvalue;
5385 			break;
5386 		case SO_RCVBUF:
5387 			so->so_rcvbuf = intvalue;
5388 			break;
5389 #ifdef notyet
5390 		/*
5391 		 * We do not implement the semantics of these options
5392 		 * thus we shouldn't implement the options either.
5393 		 */
5394 		case SO_SNDLOWAT:
5395 			so->so_sndlowat = intvalue;
5396 			break;
5397 		case SO_RCVLOWAT:
5398 			so->so_rcvlowat = intvalue;
5399 			break;
5400 		case SO_SNDTIMEO:
5401 			so->so_sndtimeo = intvalue;
5402 			break;
5403 		case SO_RCVTIMEO:
5404 			so->so_rcvtimeo = intvalue;
5405 			break;
5406 #endif /* notyet */
5407 		}
5408 #undef	intvalue
5409 
5410 		if (error) {
5411 			if ((error == ENOPROTOOPT || error == EPROTO ||
5412 			    error == EINVAL) && handled) {
5413 				dprintso(so, 1,
5414 				    ("setsockopt: ignoring error %d for 0x%x\n",
5415 				    error, option_name));
5416 				error = 0;
5417 			}
5418 		}
5419 	}
5420 done2:
5421 ret:
5422 	so_unlock_single(so, SOLOCKED);
5423 	mutex_exit(&so->so_lock);
5424 	return (error);
5425 }
5426