xref: /titanic_51/usr/src/uts/common/inet/udp/udp.c (revision c64027834c5ffc60c557c2b12555e0cd4d30320c)
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  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 const char udp_version[] = "%Z%%M%	%I%	%E% SMI";
30 
31 #include <sys/types.h>
32 #include <sys/stream.h>
33 #include <sys/dlpi.h>
34 #include <sys/pattr.h>
35 #include <sys/stropts.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/time.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/timod.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/strsubr.h>
45 #include <sys/suntpi.h>
46 #include <sys/xti_inet.h>
47 #include <sys/cmn_err.h>
48 #include <sys/kmem.h>
49 #include <sys/policy.h>
50 #include <sys/ucred.h>
51 #include <sys/zone.h>
52 
53 #include <sys/socket.h>
54 #include <sys/sockio.h>
55 #include <sys/vtrace.h>
56 #include <sys/debug.h>
57 #include <sys/isa_defs.h>
58 #include <sys/random.h>
59 #include <netinet/in.h>
60 #include <netinet/ip6.h>
61 #include <netinet/icmp6.h>
62 #include <netinet/udp.h>
63 #include <net/if.h>
64 #include <net/route.h>
65 
66 #include <inet/common.h>
67 #include <inet/ip.h>
68 #include <inet/ip_impl.h>
69 #include <inet/ip6.h>
70 #include <inet/ip_ire.h>
71 #include <inet/ip_if.h>
72 #include <inet/ip_multi.h>
73 #include <inet/ip_ndp.h>
74 #include <inet/mi.h>
75 #include <inet/mib2.h>
76 #include <inet/nd.h>
77 #include <inet/optcom.h>
78 #include <inet/snmpcom.h>
79 #include <inet/kstatcom.h>
80 #include <inet/udp_impl.h>
81 #include <inet/ipclassifier.h>
82 #include <inet/ipsec_impl.h>
83 #include <inet/ipp_common.h>
84 
85 /*
86  * The ipsec_info.h header file is here since it has the definition for the
87  * M_CTL message types used by IP to convey information to the ULP. The
88  * ipsec_info.h needs the pfkeyv2.h, hence the latter's presence.
89  */
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 
93 #include <sys/tsol/label.h>
94 #include <sys/tsol/tnet.h>
95 #include <rpc/pmap_prot.h>
96 
97 /*
98  * Synchronization notes:
99  *
100  * UDP uses a combination of its internal perimeter, a global lock and
101  * a set of bind hash locks to protect its data structures.  Please see
102  * the note above udp_mode_assertions for details about the internal
103  * perimeter.
104  *
105  * When a UDP endpoint is bound to a local port, it is inserted into
106  * a bind hash list.  The list consists of an array of udp_fanout_t buckets.
107  * The size of the array is controlled by the udp_bind_fanout_size variable.
108  * This variable can be changed in /etc/system if the default value is
109  * not large enough.  Each bind hash bucket is protected by a per bucket
110  * lock.  It protects the udp_bind_hash and udp_ptpbhn fields in the udp_t
111  * structure.  An UDP endpoint is removed from the bind hash list only
112  * when it is being unbound or being closed.  The per bucket lock also
113  * protects a UDP endpoint's state changes.
114  *
115  * Plumbing notes:
116  *
117  * Both udp and ip are merged, but the streams plumbing is kept unchanged
118  * in that udp is always pushed atop /dev/ip.  This is done to preserve
119  * backwards compatibility for certain applications which rely on such
120  * plumbing geometry to do things such as issuing I_POP on the stream
121  * in order to obtain direct access to /dev/ip, etc.
122  *
123  * All UDP processings happen in the /dev/ip instance; the udp module
124  * instance does not possess any state about the endpoint, and merely
125  * acts as a dummy module whose presence is to keep the streams plumbing
126  * appearance unchanged.  At open time /dev/ip allocates a conn_t that
127  * happens to embed a udp_t.  This stays dormant until the time udp is
128  * pushed, which indicates to /dev/ip that it must convert itself from
129  * an IP to a UDP endpoint.
130  *
131  * We only allow for the following plumbing cases:
132  *
133  * Normal:
134  *	/dev/ip is first opened and later udp is pushed directly on top.
135  *	This is the default action that happens when a udp socket or
136  *	/dev/udp is opened.  The conn_t created by /dev/ip instance is
137  *	now shared and is marked with IPCL_UDP.
138  *
139  * SNMP-only:
140  *	udp is pushed on top of a module other than /dev/ip.  When this
141  *	happens it will support only SNMP semantics.  A new conn_t is
142  *	allocated and marked with IPCL_UDPMOD.
143  *
144  * The above cases imply that we don't support any intermediate module to
145  * reside in between /dev/ip and udp -- in fact, we never supported such
146  * scenario in the past as the inter-layer communication semantics have
147  * always been private.  Also note that the normal case allows for SNMP
148  * requests to be processed in addition to the rest of UDP operations.
149  *
150  * The normal case plumbing is depicted by the following diagram:
151  *
152  *	+---------------+---------------+
153  *	|		|		| udp
154  *	|     udp_wq	|    udp_rq	|
155  *	|		|    UDP_RD	|
156  *	|		|		|
157  *	+---------------+---------------+
158  *		|		^
159  *		v		|
160  *	+---------------+---------------+
161  *	|		|		| /dev/ip
162  *	|     ip_wq	|     ip_rq	| conn_t
163  *	|     UDP_WR	|		|
164  *	|		|		|
165  *	+---------------+---------------+
166  *
167  * Messages arriving at udp_wq from above will end up in ip_wq before
168  * it gets processed, i.e. udp write entry points will advance udp_wq
169  * and use its q_next value as ip_wq in order to use the conn_t that
170  * is stored in its q_ptr.  Likewise, messages generated by ip to the
171  * module above udp will appear as if they are originated from udp_rq,
172  * i.e. putnext() calls to the module above udp is done using the
173  * udp_rq instead of ip_rq in order to avoid udp_rput() which does
174  * nothing more than calling putnext().
175  *
176  * The above implies the following rule of thumb:
177  *
178  *   1. udp_t is obtained from conn_t, which is created by the /dev/ip
179  *	instance and is stored in q_ptr of both ip_wq and ip_rq.  There
180  *	is no direct reference to conn_t from either udp_wq or udp_rq.
181  *
182  *   2. Write-side entry points of udp can obtain the conn_t via the
183  *	Q_TO_CONN() macro, using the queue value obtain from UDP_WR().
184  *
185  *   3. While in /dev/ip context, putnext() to the module above udp can
186  *	be done by supplying the queue value obtained from UDP_RD().
187  *
188  */
189 
190 static queue_t *UDP_WR(queue_t *);
191 static queue_t *UDP_RD(queue_t *);
192 
193 udp_stat_t udp_statistics = {
194 	{ "udp_ip_send",		KSTAT_DATA_UINT64 },
195 	{ "udp_ip_ire_send",		KSTAT_DATA_UINT64 },
196 	{ "udp_ire_null",		KSTAT_DATA_UINT64 },
197 	{ "udp_drain",			KSTAT_DATA_UINT64 },
198 	{ "udp_sock_fallback",		KSTAT_DATA_UINT64 },
199 	{ "udp_rrw_busy",		KSTAT_DATA_UINT64 },
200 	{ "udp_rrw_msgcnt",		KSTAT_DATA_UINT64 },
201 	{ "udp_out_sw_cksum",		KSTAT_DATA_UINT64 },
202 	{ "udp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
203 	{ "udp_out_opt",		KSTAT_DATA_UINT64 },
204 	{ "udp_out_err_notconn",	KSTAT_DATA_UINT64 },
205 	{ "udp_out_err_output",		KSTAT_DATA_UINT64 },
206 	{ "udp_out_err_tudr",		KSTAT_DATA_UINT64 },
207 	{ "udp_in_pktinfo",		KSTAT_DATA_UINT64 },
208 	{ "udp_in_recvdstaddr",		KSTAT_DATA_UINT64 },
209 	{ "udp_in_recvopts",		KSTAT_DATA_UINT64 },
210 	{ "udp_in_recvif",		KSTAT_DATA_UINT64 },
211 	{ "udp_in_recvslla",		KSTAT_DATA_UINT64 },
212 	{ "udp_in_recvucred",		KSTAT_DATA_UINT64 },
213 	{ "udp_in_recvttl",		KSTAT_DATA_UINT64 },
214 	{ "udp_in_recvhopopts",		KSTAT_DATA_UINT64 },
215 	{ "udp_in_recvhoplimit",	KSTAT_DATA_UINT64 },
216 	{ "udp_in_recvdstopts",		KSTAT_DATA_UINT64 },
217 	{ "udp_in_recvrtdstopts",	KSTAT_DATA_UINT64 },
218 	{ "udp_in_recvrthdr",		KSTAT_DATA_UINT64 },
219 	{ "udp_in_recvpktinfo",		KSTAT_DATA_UINT64 },
220 	{ "udp_in_recvtclass",		KSTAT_DATA_UINT64 },
221 	{ "udp_in_timestamp",		KSTAT_DATA_UINT64 },
222 #ifdef DEBUG
223 	{ "udp_data_conn",		KSTAT_DATA_UINT64 },
224 	{ "udp_data_notconn",		KSTAT_DATA_UINT64 },
225 #endif
226 };
227 
228 static kstat_t *udp_ksp;
229 struct kmem_cache *udp_cache;
230 
231 /*
232  * Bind hash list size and hash function.  It has to be a power of 2 for
233  * hashing.
234  */
235 #define	UDP_BIND_FANOUT_SIZE	512
236 #define	UDP_BIND_HASH(lport) \
237 	((ntohs((uint16_t)lport)) & (udp_bind_fanout_size - 1))
238 
239 /* UDP bind fanout hash structure. */
240 typedef struct udp_fanout_s {
241 	udp_t *uf_udp;
242 	kmutex_t uf_lock;
243 #if defined(_LP64) || defined(_I32LPx)
244 	char	uf_pad[48];
245 #else
246 	char	uf_pad[56];
247 #endif
248 } udp_fanout_t;
249 
250 uint_t udp_bind_fanout_size = UDP_BIND_FANOUT_SIZE;
251 /* udp_fanout_t *udp_bind_fanout. */
252 static udp_fanout_t *udp_bind_fanout;
253 
254 /*
255  * This controls the rate some ndd info report functions can be used
256  * by non-privileged users.  It stores the last time such info is
257  * requested.  When those report functions are called again, this
258  * is checked with the current time and compare with the ndd param
259  * udp_ndd_get_info_interval.
260  */
261 static clock_t udp_last_ndd_get_info_time;
262 #define	NDD_TOO_QUICK_MSG \
263 	"ndd get info rate too high for non-privileged users, try again " \
264 	"later.\n"
265 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
266 
267 /* Option processing attrs */
268 typedef struct udpattrs_s {
269 	ip6_pkt_t	*udpattr_ipp;
270 	mblk_t		*udpattr_mb;
271 	boolean_t	udpattr_credset;
272 } udpattrs_t;
273 
274 static void	udp_addr_req(queue_t *q, mblk_t *mp);
275 static void	udp_bind(queue_t *q, mblk_t *mp);
276 static void	udp_bind_hash_insert(udp_fanout_t *uf, udp_t *udp);
277 static void	udp_bind_hash_remove(udp_t *udp, boolean_t caller_holds_lock);
278 static int	udp_build_hdrs(queue_t *q, udp_t *udp);
279 static void	udp_capability_req(queue_t *q, mblk_t *mp);
280 static int	udp_close(queue_t *q);
281 static void	udp_connect(queue_t *q, mblk_t *mp);
282 static void	udp_disconnect(queue_t *q, mblk_t *mp);
283 static void	udp_err_ack(queue_t *q, mblk_t *mp, t_scalar_t t_error,
284 		    int sys_error);
285 static void	udp_err_ack_prim(queue_t *q, mblk_t *mp, int primitive,
286 		    t_scalar_t tlierr, int unixerr);
287 static int	udp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
288 		    cred_t *cr);
289 static int	udp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
290 		    char *value, caddr_t cp, cred_t *cr);
291 static int	udp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
292 		    char *value, caddr_t cp, cred_t *cr);
293 static void	udp_icmp_error(queue_t *q, mblk_t *mp);
294 static void	udp_icmp_error_ipv6(queue_t *q, mblk_t *mp);
295 static void	udp_info_req(queue_t *q, mblk_t *mp);
296 static mblk_t	*udp_ip_bind_mp(udp_t *udp, t_scalar_t bind_prim,
297 		    t_scalar_t addr_length);
298 static int	udp_open(queue_t *q, dev_t *devp, int flag, int sflag,
299 		    cred_t *credp);
300 static  int	udp_unitdata_opt_process(queue_t *q, mblk_t *mp,
301 		    int *errorp, udpattrs_t *udpattrs);
302 static boolean_t udp_opt_allow_udr_set(t_scalar_t level, t_scalar_t name);
303 static int	udp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
304 static boolean_t udp_param_register(udpparam_t *udppa, int cnt);
305 static int	udp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
306 		    cred_t *cr);
307 static void	udp_report_item(mblk_t *mp, udp_t *udp);
308 static void	udp_rput(queue_t *q, mblk_t *mp);
309 static void	udp_rput_other(queue_t *, mblk_t *);
310 static int	udp_rinfop(queue_t *q, infod_t *dp);
311 static int	udp_rrw(queue_t *q, struiod_t *dp);
312 static	void	udp_rput_bind_ack(queue_t *q, mblk_t *mp);
313 static int	udp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
314 		    cred_t *cr);
315 static void	udp_send_data(udp_t *udp, queue_t *q, mblk_t *mp, ipha_t *ipha);
316 static void	udp_ud_err(queue_t *q, mblk_t *mp, uchar_t *destaddr,
317 		    t_scalar_t destlen, t_scalar_t err);
318 static void	udp_unbind(queue_t *q, mblk_t *mp);
319 static in_port_t udp_update_next_port(udp_t *udp, in_port_t port,
320     boolean_t random);
321 static void	udp_wput(queue_t *q, mblk_t *mp);
322 static mblk_t	*udp_output_v4(conn_t *, mblk_t *mp, ipaddr_t v4dst,
323 		    uint16_t port, uint_t srcid, int *error);
324 static mblk_t	*udp_output_v6(conn_t *connp, mblk_t *mp, sin6_t *sin6,
325 		    int *error);
326 static void	udp_wput_other(queue_t *q, mblk_t *mp);
327 static void	udp_wput_iocdata(queue_t *q, mblk_t *mp);
328 static void	udp_output(conn_t *connp, mblk_t *mp, struct sockaddr *addr,
329 		    socklen_t addrlen);
330 static size_t	udp_set_rcv_hiwat(udp_t *udp, size_t size);
331 
332 static void	udp_kstat_init(void);
333 static void	udp_kstat_fini(void);
334 static int	udp_kstat_update(kstat_t *kp, int rw);
335 static void	udp_input_wrapper(void *arg, mblk_t *mp, void *arg2);
336 static void	udp_rput_other_wrapper(void *arg, mblk_t *mp, void *arg2);
337 static void	udp_wput_other_wrapper(void *arg, mblk_t *mp, void *arg2);
338 static void	udp_resume_bind_cb(void *arg, mblk_t *mp, void *arg2);
339 
340 static void	udp_rcv_enqueue(queue_t *q, udp_t *udp, mblk_t *mp,
341 		    uint_t pkt_len);
342 static void	udp_rcv_drain(queue_t *q, udp_t *udp, boolean_t closing);
343 static void	udp_enter(conn_t *, mblk_t *, sqproc_t, uint8_t);
344 static void	udp_exit(conn_t *);
345 static void	udp_become_writer(conn_t *, mblk_t *, sqproc_t, uint8_t);
346 #ifdef DEBUG
347 static void	udp_mode_assertions(udp_t *, int);
348 #endif /* DEBUG */
349 
350 major_t UDP6_MAJ;
351 #define	UDP6 "udp6"
352 
353 #define	UDP_RECV_HIWATER	(56 * 1024)
354 #define	UDP_RECV_LOWATER	128
355 #define	UDP_XMIT_HIWATER	(56 * 1024)
356 #define	UDP_XMIT_LOWATER	1024
357 
358 static struct module_info udp_info =  {
359 	UDP_MOD_ID, UDP_MOD_NAME, 1, INFPSZ, UDP_RECV_HIWATER, UDP_RECV_LOWATER
360 };
361 
362 static struct qinit udp_rinit = {
363 	(pfi_t)udp_rput, NULL, udp_open, udp_close, NULL,
364 	&udp_info, NULL, udp_rrw, udp_rinfop, STRUIOT_STANDARD
365 };
366 
367 static struct qinit udp_winit = {
368 	(pfi_t)udp_wput, NULL, NULL, NULL, NULL,
369 	&udp_info, NULL, NULL, NULL, STRUIOT_NONE
370 };
371 
372 static struct qinit winit = {
373 	(pfi_t)putnext, NULL, NULL, NULL, NULL,
374 	&udp_info, NULL, NULL, NULL, STRUIOT_NONE
375 };
376 
377 /* Support for just SNMP if UDP is not pushed directly over device IP */
378 struct qinit udp_snmp_rinit = {
379 	(pfi_t)putnext, NULL, udp_open, ip_snmpmod_close, NULL,
380 	&udp_info, NULL, NULL, NULL, STRUIOT_NONE
381 };
382 
383 struct qinit udp_snmp_winit = {
384 	(pfi_t)ip_snmpmod_wput, NULL, udp_open, ip_snmpmod_close, NULL,
385 	&udp_info, NULL, NULL, NULL, STRUIOT_NONE
386 };
387 
388 struct streamtab udpinfo = {
389 	&udp_rinit, &winit
390 };
391 
392 static	sin_t	sin_null;	/* Zero address for quick clears */
393 static	sin6_t	sin6_null;	/* Zero address for quick clears */
394 
395 /* Hint not protected by any lock */
396 static in_port_t	udp_g_next_port_to_try;
397 
398 /*
399  * Extra privileged ports. In host byte order.
400  */
401 #define	UDP_NUM_EPRIV_PORTS	64
402 static int	udp_g_num_epriv_ports = UDP_NUM_EPRIV_PORTS;
403 static in_port_t udp_g_epriv_ports[UDP_NUM_EPRIV_PORTS] = { 2049, 4045 };
404 
405 /* Only modified during _init and _fini thus no locking is needed. */
406 static IDP	udp_g_nd;	/* Points to table of UDP ND variables. */
407 
408 /* MIB-2 stuff for SNMP */
409 static mib2_udp_t	udp_mib;	/* SNMP fixed size info */
410 static kstat_t		*udp_mibkp;	/* kstat exporting udp_mib data */
411 
412 #define	UDP_MAXPACKET_IPV4 (IP_MAXPACKET - UDPH_SIZE - IP_SIMPLE_HDR_LENGTH)
413 
414 /* Default structure copied into T_INFO_ACK messages */
415 static struct T_info_ack udp_g_t_info_ack_ipv4 = {
416 	T_INFO_ACK,
417 	UDP_MAXPACKET_IPV4,	/* TSDU_size. Excl. headers */
418 	T_INVALID,	/* ETSU_size.  udp does not support expedited data. */
419 	T_INVALID,	/* CDATA_size. udp does not support connect data. */
420 	T_INVALID,	/* DDATA_size. udp does not support disconnect data. */
421 	sizeof (sin_t),	/* ADDR_size. */
422 	0,		/* OPT_size - not initialized here */
423 	UDP_MAXPACKET_IPV4,	/* TIDU_size.  Excl. headers */
424 	T_CLTS,		/* SERV_type.  udp supports connection-less. */
425 	TS_UNBND,	/* CURRENT_state.  This is set from udp_state. */
426 	(XPG4_1|SENDZERO) /* PROVIDER_flag */
427 };
428 
429 #define	UDP_MAXPACKET_IPV6 (IP_MAXPACKET - UDPH_SIZE - IPV6_HDR_LEN)
430 
431 static	struct T_info_ack udp_g_t_info_ack_ipv6 = {
432 	T_INFO_ACK,
433 	UDP_MAXPACKET_IPV6,	/* TSDU_size.  Excl. headers */
434 	T_INVALID,	/* ETSU_size.  udp does not support expedited data. */
435 	T_INVALID,	/* CDATA_size. udp does not support connect data. */
436 	T_INVALID,	/* DDATA_size. udp does not support disconnect data. */
437 	sizeof (sin6_t), /* ADDR_size. */
438 	0,		/* OPT_size - not initialized here */
439 	UDP_MAXPACKET_IPV6,	/* TIDU_size. Excl. headers */
440 	T_CLTS,		/* SERV_type.  udp supports connection-less. */
441 	TS_UNBND,	/* CURRENT_state.  This is set from udp_state. */
442 	(XPG4_1|SENDZERO) /* PROVIDER_flag */
443 };
444 
445 /* largest UDP port number */
446 #define	UDP_MAX_PORT	65535
447 
448 /*
449  * Table of ND variables supported by udp.  These are loaded into udp_g_nd
450  * in udp_open.
451  * All of these are alterable, within the min/max values given, at run time.
452  */
453 /* BEGIN CSTYLED */
454 udpparam_t udp_param_arr[] = {
455  /*min		max		value		name */
456  { 0L,		256,		32,		"udp_wroff_extra" },
457  { 1L,		255,		255,		"udp_ipv4_ttl" },
458  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS, "udp_ipv6_hoplimit"},
459  { 1024,	(32 * 1024),	1024,		"udp_smallest_nonpriv_port" },
460  { 0,		1,		1,		"udp_do_checksum" },
461  { 1024,	UDP_MAX_PORT,	(32 * 1024),	"udp_smallest_anon_port" },
462  { 1024,	UDP_MAX_PORT,	UDP_MAX_PORT,	"udp_largest_anon_port" },
463  { UDP_XMIT_LOWATER, (1<<30), UDP_XMIT_HIWATER,	"udp_xmit_hiwat"},
464  { 0,		     (1<<30), UDP_XMIT_LOWATER, "udp_xmit_lowat"},
465  { UDP_RECV_LOWATER, (1<<30), UDP_RECV_HIWATER,	"udp_recv_hiwat"},
466  { 65536,	(1<<30),	2*1024*1024,	"udp_max_buf"},
467  { 100,		60000,		1000,		"udp_ndd_get_info_interval"},
468 };
469 /* END CSTYLED */
470 
471 /*
472  * The smallest anonymous port in the privileged port range which UDP
473  * looks for free port.  Use in the option UDP_ANONPRIVBIND.
474  */
475 static in_port_t udp_min_anonpriv_port = 512;
476 
477 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
478 uint32_t udp_random_anon_port = 1;
479 
480 /*
481  * Hook functions to enable cluster networking.
482  * On non-clustered systems these vectors must always be NULL
483  */
484 
485 void (*cl_inet_bind)(uchar_t protocol, sa_family_t addr_family,
486     uint8_t *laddrp, in_port_t lport) = NULL;
487 void (*cl_inet_unbind)(uint8_t protocol, sa_family_t addr_family,
488     uint8_t *laddrp, in_port_t lport) = NULL;
489 
490 typedef union T_primitives *t_primp_t;
491 
492 #define	UDP_ENQUEUE_MP(udp, mp, proc, tag) {			\
493 	ASSERT((mp)->b_prev == NULL && (mp)->b_queue == NULL);	\
494 	ASSERT(MUTEX_HELD(&(udp)->udp_connp->conn_lock));	\
495 	(mp)->b_queue = (queue_t *)((uintptr_t)tag);		\
496 	(mp)->b_prev = (mblk_t *)proc;				\
497 	if ((udp)->udp_mphead == NULL)				\
498 		(udp)->udp_mphead = (mp);			\
499 	else							\
500 		(udp)->udp_mptail->b_next = (mp);		\
501 	(udp)->udp_mptail = (mp);				\
502 	(udp)->udp_mpcount++;					\
503 }
504 
505 #define	UDP_READERS_INCREF(udp) {				\
506 	ASSERT(MUTEX_HELD(&(udp)->udp_connp->conn_lock));	\
507 	(udp)->udp_reader_count++;				\
508 }
509 
510 #define	UDP_READERS_DECREF(udp) {				\
511 	ASSERT(MUTEX_HELD(&(udp)->udp_connp->conn_lock));	\
512 	(udp)->udp_reader_count--;				\
513 	if ((udp)->udp_reader_count == 0)			\
514 		cv_broadcast(&(udp)->udp_connp->conn_cv);	\
515 }
516 
517 #define	UDP_SQUEUE_DECREF(udp) {				\
518 	ASSERT(MUTEX_HELD(&(udp)->udp_connp->conn_lock));	\
519 	(udp)->udp_squeue_count--;				\
520 	if ((udp)->udp_squeue_count == 0)			\
521 		cv_broadcast(&(udp)->udp_connp->conn_cv);	\
522 }
523 
524 /*
525  * Notes on UDP endpoint synchronization:
526  *
527  * UDP needs exclusive operation on a per endpoint basis, when executing
528  * functions that modify the endpoint state.  udp_rput_other() deals with
529  * packets with IP options, and processing these packets end up having
530  * to update the endpoint's option related state.  udp_wput_other() deals
531  * with control operations from the top, e.g. connect() that needs to
532  * update the endpoint state.  These could be synchronized using locks,
533  * but the current version uses squeues for this purpose.  squeues may
534  * give performance improvement for certain cases such as connected UDP
535  * sockets; thus the framework allows for using squeues.
536  *
537  * The perimeter routines are described as follows:
538  *
539  * udp_enter():
540  *	Enter the UDP endpoint perimeter.
541  *
542  * udp_become_writer():
543  *	Become exclusive on the UDP endpoint.  Specifies a function
544  *	that will be called exclusively either immediately or later
545  *	when the perimeter is available exclusively.
546  *
547  * udp_exit():
548  *	Exit the UDP perimeter.
549  *
550  * Entering UDP from the top or from the bottom must be done using
551  * udp_enter().  No lock must be held while attempting to enter the UDP
552  * perimeter.  When finished, udp_exit() must be called to get out of
553  * the perimeter.
554  *
555  * UDP operates in either MT_HOT mode or in SQUEUE mode.  In MT_HOT mode,
556  * multiple threads may enter a UDP endpoint concurrently.  This is used
557  * for sending and/or receiving normal data.  Control operations and other
558  * special cases call udp_become_writer() to become exclusive on a per
559  * endpoint basis and this results in transitioning to SQUEUE mode.  squeue
560  * by definition serializes access to the conn_t.  When there are no more
561  * pending messages on the squeue for the UDP connection, the endpoint
562  * reverts to MT_HOT mode.  During the interregnum when not all MT threads
563  * of an endpoint have finished, messages are queued in the UDP endpoint
564  * and the UDP is in UDP_MT_QUEUED mode or UDP_QUEUED_SQUEUE mode.
565  *
566  * These modes have the following analogs:
567  *
568  *	UDP_MT_HOT/udp_reader_count==0		none
569  *	UDP_MT_HOT/udp_reader_count>0		RW_READ_LOCK
570  *	UDP_MT_QUEUED				RW_WRITE_WANTED
571  *	UDP_SQUEUE or UDP_QUEUED_SQUEUE		RW_WRITE_LOCKED
572  *
573  * Stable modes:	UDP_MT_HOT, UDP_SQUEUE
574  * Transient modes:	UDP_MT_QUEUED, UDP_QUEUED_SQUEUE
575  *
576  * While in stable modes, UDP keeps track of the number of threads
577  * operating on the endpoint.  The udp_reader_count variable represents
578  * the number of threads entering the endpoint as readers while it is
579  * in UDP_MT_HOT mode.  Transitioning to UDP_SQUEUE happens when there
580  * is only a single reader, i.e. when this counter drops to 1.  Likewise,
581  * udp_squeue_count represents the number of threads operating on the
582  * endpoint's squeue while it is in UDP_SQUEUE mode.  The mode transition
583  * to UDP_MT_HOT happens after the last thread exits the endpoint, i.e.
584  * when this counter drops to 0.
585  *
586  * The default mode is set to UDP_MT_HOT and UDP alternates between
587  * UDP_MT_HOT and UDP_SQUEUE as shown in the state transition below.
588  *
589  * Mode transition:
590  * ----------------------------------------------------------------
591  * old mode		Event				New mode
592  * ----------------------------------------------------------------
593  * UDP_MT_HOT		Call to udp_become_writer()	UDP_SQUEUE
594  *			and udp_reader_count == 1
595  *
596  * UDP_MT_HOT		Call to udp_become_writer()	UDP_MT_QUEUED
597  *			and udp_reader_count > 1
598  *
599  * UDP_MT_QUEUED	udp_reader_count drops to zero	UDP_QUEUED_SQUEUE
600  *
601  * UDP_QUEUED_SQUEUE	All messages enqueued on the	UDP_SQUEUE
602  *			internal UDP queue successfully
603  *			moved to squeue AND udp_squeue_count != 0
604  *
605  * UDP_QUEUED_SQUEUE	All messages enqueued on the	UDP_MT_HOT
606  *			internal UDP queue successfully
607  *			moved to squeue AND udp_squeue_count
608  *			drops to zero
609  *
610  * UDP_SQUEUE		udp_squeue_count drops to zero	UDP_MT_HOT
611  * ----------------------------------------------------------------
612  */
613 
614 static queue_t *
615 UDP_WR(queue_t *q)
616 {
617 	ASSERT(q->q_ptr == NULL && _OTHERQ(q)->q_ptr == NULL);
618 	ASSERT(WR(q)->q_next != NULL && WR(q)->q_next->q_ptr != NULL);
619 	ASSERT(IPCL_IS_UDP(Q_TO_CONN(WR(q)->q_next)));
620 
621 	return (_WR(q)->q_next);
622 }
623 
624 static queue_t *
625 UDP_RD(queue_t *q)
626 {
627 	ASSERT(q->q_ptr != NULL && _OTHERQ(q)->q_ptr != NULL);
628 	ASSERT(IPCL_IS_UDP(Q_TO_CONN(q)));
629 	ASSERT(RD(q)->q_next != NULL && RD(q)->q_next->q_ptr == NULL);
630 
631 	return (_RD(q)->q_next);
632 }
633 
634 #ifdef DEBUG
635 #define	UDP_MODE_ASSERTIONS(udp, caller) udp_mode_assertions(udp, caller)
636 #else
637 #define	UDP_MODE_ASSERTIONS(udp, caller)
638 #endif
639 
640 /* Invariants */
641 #ifdef DEBUG
642 
643 uint32_t udp_count[4];
644 
645 /* Context of udp_mode_assertions */
646 #define	UDP_ENTER		1
647 #define	UDP_BECOME_WRITER	2
648 #define	UDP_EXIT		3
649 
650 static void
651 udp_mode_assertions(udp_t *udp, int caller)
652 {
653 	ASSERT(MUTEX_HELD(&udp->udp_connp->conn_lock));
654 
655 	switch (udp->udp_mode) {
656 	case UDP_MT_HOT:
657 		/*
658 		 * Messages have not yet been enqueued on the internal queue,
659 		 * otherwise we would have switched to UDP_MT_QUEUED. Likewise
660 		 * by definition, there can't be any messages enqueued on the
661 		 * squeue. The UDP could be quiescent, so udp_reader_count
662 		 * could be zero at entry.
663 		 */
664 		ASSERT(udp->udp_mphead == NULL && udp->udp_mpcount == 0 &&
665 		    udp->udp_squeue_count == 0);
666 		ASSERT(caller == UDP_ENTER || udp->udp_reader_count != 0);
667 		udp_count[0]++;
668 		break;
669 
670 	case UDP_MT_QUEUED:
671 		/*
672 		 * The last MT thread to exit the udp perimeter empties the
673 		 * internal queue and then switches the UDP to
674 		 * UDP_QUEUED_SQUEUE mode. Since we are still in UDP_MT_QUEUED
675 		 * mode, it means there must be at least 1 MT thread still in
676 		 * the perimeter and at least 1 message on the internal queue.
677 		 */
678 		ASSERT(udp->udp_reader_count >= 1 && udp->udp_mphead != NULL &&
679 		    udp->udp_mpcount != 0 && udp->udp_squeue_count == 0);
680 		udp_count[1]++;
681 		break;
682 
683 	case UDP_QUEUED_SQUEUE:
684 		/*
685 		 * The switch has happened from MT to SQUEUE. So there can't
686 		 * any MT threads. Messages could still pile up on the internal
687 		 * queue until the transition is complete and we move to
688 		 * UDP_SQUEUE mode. We can't assert on nonzero udp_squeue_count
689 		 * since the squeue could drain any time.
690 		 */
691 		ASSERT(udp->udp_reader_count == 0);
692 		udp_count[2]++;
693 		break;
694 
695 	case UDP_SQUEUE:
696 		/*
697 		 * The transition is complete. Thre can't be any messages on
698 		 * the internal queue. The udp could be quiescent or the squeue
699 		 * could drain any time, so we can't assert on nonzero
700 		 * udp_squeue_count during entry. Nor can we assert that
701 		 * udp_reader_count is zero, since, a reader thread could have
702 		 * directly become writer in line by calling udp_become_writer
703 		 * without going through the queued states.
704 		 */
705 		ASSERT(udp->udp_mphead == NULL && udp->udp_mpcount == 0);
706 		ASSERT(caller == UDP_ENTER || udp->udp_squeue_count != 0);
707 		udp_count[3]++;
708 		break;
709 	}
710 }
711 #endif
712 
713 #define	_UDP_ENTER(connp, mp, proc, tag) {				\
714 	udp_t *_udp = (connp)->conn_udp;				\
715 									\
716 	mutex_enter(&(connp)->conn_lock);				\
717 	if ((connp)->conn_state_flags & CONN_CLOSING) {			\
718 		mutex_exit(&(connp)->conn_lock);			\
719 		freemsg(mp);						\
720 	} else {							\
721 		UDP_MODE_ASSERTIONS(_udp, UDP_ENTER);			\
722 									\
723 		switch (_udp->udp_mode) {				\
724 		case UDP_MT_HOT:					\
725 			/* We can execute as reader right away. */	\
726 			UDP_READERS_INCREF(_udp);			\
727 			mutex_exit(&(connp)->conn_lock);		\
728 			(*(proc))(connp, mp, (connp)->conn_sqp);	\
729 			break;						\
730 									\
731 		case UDP_SQUEUE:					\
732 			/*						\
733 			 * We are in squeue mode, send the		\
734 			 * packet to the squeue				\
735 			 */						\
736 			_udp->udp_squeue_count++;			\
737 			CONN_INC_REF_LOCKED(connp);			\
738 			mutex_exit(&(connp)->conn_lock);		\
739 			squeue_enter((connp)->conn_sqp, mp, proc,	\
740 			    connp, tag);				\
741 			break;						\
742 									\
743 		case UDP_MT_QUEUED:					\
744 		case UDP_QUEUED_SQUEUE:					\
745 			/*						\
746 			 * Some messages may have been enqueued		\
747 			 * ahead of us.  Enqueue the new message	\
748 			 * at the tail of the internal queue to		\
749 			 * preserve message ordering.			\
750 			 */						\
751 			UDP_ENQUEUE_MP(_udp, mp, proc, tag);		\
752 			mutex_exit(&(connp)->conn_lock);		\
753 			break;						\
754 		}							\
755 	}								\
756 }
757 
758 static void
759 udp_enter(conn_t *connp, mblk_t *mp, sqproc_t proc, uint8_t tag)
760 {
761 	_UDP_ENTER(connp, mp, proc, tag);
762 }
763 
764 static void
765 udp_become_writer(conn_t *connp, mblk_t *mp, sqproc_t proc, uint8_t tag)
766 {
767 	udp_t	*udp;
768 
769 	udp = connp->conn_udp;
770 
771 	mutex_enter(&connp->conn_lock);
772 
773 	UDP_MODE_ASSERTIONS(udp, UDP_BECOME_WRITER);
774 
775 	switch (udp->udp_mode) {
776 	case UDP_MT_HOT:
777 		if (udp->udp_reader_count == 1) {
778 			/*
779 			 * We are the only MT thread. Switch to squeue mode
780 			 * immediately.
781 			 */
782 			udp->udp_mode = UDP_SQUEUE;
783 			udp->udp_squeue_count = 1;
784 			CONN_INC_REF_LOCKED(connp);
785 			mutex_exit(&connp->conn_lock);
786 			squeue_enter(connp->conn_sqp, mp, proc, connp, tag);
787 			return;
788 		}
789 		/* FALLTHRU */
790 
791 	case UDP_MT_QUEUED:
792 		/* Enqueue the packet internally in UDP */
793 		udp->udp_mode = UDP_MT_QUEUED;
794 		UDP_ENQUEUE_MP(udp, mp, proc, tag);
795 		mutex_exit(&connp->conn_lock);
796 		return;
797 
798 	case UDP_SQUEUE:
799 	case UDP_QUEUED_SQUEUE:
800 		/*
801 		 * We are already exclusive. i.e. we are already
802 		 * writer. Simply call the desired function.
803 		 */
804 		udp->udp_squeue_count++;
805 		mutex_exit(&connp->conn_lock);
806 		(*proc)(connp, mp, connp->conn_sqp);
807 		return;
808 	}
809 }
810 
811 /*
812  * Transition from MT mode to SQUEUE mode, when the last MT thread
813  * is exiting the UDP perimeter. Move all messages from the internal
814  * udp queue to the squeue. A better way would be to move all the
815  * messages in one shot, this needs more support from the squeue framework
816  */
817 static void
818 udp_switch_to_squeue(udp_t *udp)
819 {
820 	mblk_t *mp;
821 	mblk_t	*mp_next;
822 	sqproc_t proc;
823 	uint8_t	tag;
824 	conn_t	*connp = udp->udp_connp;
825 
826 	ASSERT(MUTEX_HELD(&connp->conn_lock));
827 	ASSERT(udp->udp_mode == UDP_MT_QUEUED);
828 	while (udp->udp_mphead != NULL) {
829 		mp = udp->udp_mphead;
830 		udp->udp_mphead = NULL;
831 		udp->udp_mptail = NULL;
832 		udp->udp_mpcount = 0;
833 		udp->udp_mode = UDP_QUEUED_SQUEUE;
834 		mutex_exit(&connp->conn_lock);
835 		/*
836 		 * It is best not to hold any locks across the calls
837 		 * to squeue functions. Since we drop the lock we
838 		 * need to go back and check the udp_mphead once again
839 		 * after the squeue_fill and hence the while loop at
840 		 * the top of this function
841 		 */
842 		for (; mp != NULL; mp = mp_next) {
843 			mp_next = mp->b_next;
844 			proc = (sqproc_t)mp->b_prev;
845 			tag = (uint8_t)((uintptr_t)mp->b_queue);
846 			mp->b_next = NULL;
847 			mp->b_prev = NULL;
848 			mp->b_queue = NULL;
849 			CONN_INC_REF(connp);
850 			udp->udp_squeue_count++;
851 			squeue_fill(connp->conn_sqp, mp, proc, connp,
852 			    tag);
853 		}
854 		mutex_enter(&connp->conn_lock);
855 	}
856 	/*
857 	 * udp_squeue_count of zero implies that the squeue has drained
858 	 * even before we arrived here (i.e. after the squeue_fill above)
859 	 */
860 	udp->udp_mode = (udp->udp_squeue_count != 0) ?
861 	    UDP_SQUEUE : UDP_MT_HOT;
862 }
863 
864 #define	_UDP_EXIT(connp) {						\
865 	udp_t *_udp = (connp)->conn_udp;				\
866 									\
867 	mutex_enter(&(connp)->conn_lock);				\
868 	UDP_MODE_ASSERTIONS(_udp, UDP_EXIT);				\
869 									\
870 	switch (_udp->udp_mode) {					\
871 	case UDP_MT_HOT:						\
872 		UDP_READERS_DECREF(_udp);				\
873 		mutex_exit(&(connp)->conn_lock);			\
874 		break;							\
875 									\
876 	case UDP_SQUEUE:						\
877 		UDP_SQUEUE_DECREF(_udp);				\
878 		if (_udp->udp_squeue_count == 0)			\
879 		    _udp->udp_mode = UDP_MT_HOT;			\
880 		mutex_exit(&(connp)->conn_lock);			\
881 		break;							\
882 									\
883 	case UDP_MT_QUEUED:						\
884 		/*							\
885 		 * If this is the last MT thread, we need to		\
886 		 * switch to squeue mode				\
887 		 */							\
888 		UDP_READERS_DECREF(_udp);				\
889 		if (_udp->udp_reader_count == 0)			\
890 			udp_switch_to_squeue(_udp);			\
891 		mutex_exit(&(connp)->conn_lock);			\
892 		break;							\
893 									\
894 	case UDP_QUEUED_SQUEUE:						\
895 		UDP_SQUEUE_DECREF(_udp);				\
896 		/*							\
897 		 * Even if the udp_squeue_count drops to zero, we	\
898 		 * don't want to change udp_mode to UDP_MT_HOT here.	\
899 		 * The thread in udp_switch_to_squeue will take care	\
900 		 * of the transition to UDP_MT_HOT, after emptying	\
901 		 * any more new messages that have been enqueued in	\
902 		 * udp_mphead.						\
903 		 */							\
904 		mutex_exit(&(connp)->conn_lock);			\
905 		break;							\
906 	}								\
907 }
908 
909 static void
910 udp_exit(conn_t *connp)
911 {
912 	_UDP_EXIT(connp);
913 }
914 
915 /*
916  * Return the next anonymous port in the privileged port range for
917  * bind checking.
918  *
919  * Trusted Extension (TX) notes: TX allows administrator to mark or
920  * reserve ports as Multilevel ports (MLP). MLP has special function
921  * on TX systems. Once a port is made MLP, it's not available as
922  * ordinary port. This creates "holes" in the port name space. It
923  * may be necessary to skip the "holes" find a suitable anon port.
924  */
925 static in_port_t
926 udp_get_next_priv_port(udp_t *udp)
927 {
928 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
929 	in_port_t nextport;
930 	boolean_t restart = B_FALSE;
931 
932 retry:
933 	if (next_priv_port < udp_min_anonpriv_port ||
934 	    next_priv_port >= IPPORT_RESERVED) {
935 		next_priv_port = IPPORT_RESERVED - 1;
936 		if (restart)
937 			return (0);
938 		restart = B_TRUE;
939 	}
940 
941 	if (is_system_labeled() &&
942 	    (nextport = tsol_next_port(crgetzone(udp->udp_connp->conn_cred),
943 	    next_priv_port, IPPROTO_UDP, B_FALSE)) != 0) {
944 		next_priv_port = nextport;
945 		goto retry;
946 	}
947 
948 	return (next_priv_port--);
949 }
950 
951 /* UDP bind hash report triggered via the Named Dispatch mechanism. */
952 /* ARGSUSED */
953 static int
954 udp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
955 {
956 	udp_fanout_t	*udpf;
957 	int		i;
958 	zoneid_t	zoneid;
959 	conn_t		*connp;
960 	udp_t		*udp;
961 
962 	connp = Q_TO_CONN(q);
963 	udp = connp->conn_udp;
964 
965 	/* Refer to comments in udp_status_report(). */
966 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
967 		if (ddi_get_lbolt() - udp_last_ndd_get_info_time <
968 		    drv_usectohz(udp_ndd_get_info_interval * 1000)) {
969 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
970 			return (0);
971 		}
972 	}
973 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
974 		/* The following may work even if we cannot get a large buf. */
975 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
976 		return (0);
977 	}
978 
979 	(void) mi_mpprintf(mp,
980 	    "UDP     " MI_COL_HDRPAD_STR
981 	/*   12345678[89ABCDEF] */
982 	    " zone lport src addr        dest addr       port  state");
983 	/*    1234 12345 xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx 12345 UNBOUND */
984 
985 	zoneid = connp->conn_zoneid;
986 
987 	for (i = 0; i < udp_bind_fanout_size; i++) {
988 		udpf = &udp_bind_fanout[i];
989 		mutex_enter(&udpf->uf_lock);
990 
991 		/* Print the hash index. */
992 		udp = udpf->uf_udp;
993 		if (zoneid != GLOBAL_ZONEID) {
994 			/* skip to first entry in this zone; might be none */
995 			while (udp != NULL &&
996 			    udp->udp_connp->conn_zoneid != zoneid)
997 				udp = udp->udp_bind_hash;
998 		}
999 		if (udp != NULL) {
1000 			uint_t print_len, buf_len;
1001 
1002 			buf_len = mp->b_cont->b_datap->db_lim -
1003 			    mp->b_cont->b_wptr;
1004 			print_len = snprintf((char *)mp->b_cont->b_wptr,
1005 			    buf_len, "%d\n", i);
1006 			if (print_len < buf_len) {
1007 				mp->b_cont->b_wptr += print_len;
1008 			} else {
1009 				mp->b_cont->b_wptr += buf_len;
1010 			}
1011 			for (; udp != NULL; udp = udp->udp_bind_hash) {
1012 				if (zoneid == GLOBAL_ZONEID ||
1013 				    zoneid == udp->udp_connp->conn_zoneid)
1014 					udp_report_item(mp->b_cont, udp);
1015 			}
1016 		}
1017 		mutex_exit(&udpf->uf_lock);
1018 	}
1019 	udp_last_ndd_get_info_time = ddi_get_lbolt();
1020 	return (0);
1021 }
1022 
1023 /*
1024  * Hash list removal routine for udp_t structures.
1025  */
1026 static void
1027 udp_bind_hash_remove(udp_t *udp, boolean_t caller_holds_lock)
1028 {
1029 	udp_t	*udpnext;
1030 	kmutex_t *lockp;
1031 
1032 	if (udp->udp_ptpbhn == NULL)
1033 		return;
1034 
1035 	/*
1036 	 * Extract the lock pointer in case there are concurrent
1037 	 * hash_remove's for this instance.
1038 	 */
1039 	ASSERT(udp->udp_port != 0);
1040 	if (!caller_holds_lock) {
1041 		lockp = &udp_bind_fanout[UDP_BIND_HASH(udp->udp_port)].uf_lock;
1042 		ASSERT(lockp != NULL);
1043 		mutex_enter(lockp);
1044 	}
1045 	if (udp->udp_ptpbhn != NULL) {
1046 		udpnext = udp->udp_bind_hash;
1047 		if (udpnext != NULL) {
1048 			udpnext->udp_ptpbhn = udp->udp_ptpbhn;
1049 			udp->udp_bind_hash = NULL;
1050 		}
1051 		*udp->udp_ptpbhn = udpnext;
1052 		udp->udp_ptpbhn = NULL;
1053 	}
1054 	if (!caller_holds_lock) {
1055 		mutex_exit(lockp);
1056 	}
1057 }
1058 
1059 static void
1060 udp_bind_hash_insert(udp_fanout_t *uf, udp_t *udp)
1061 {
1062 	udp_t	**udpp;
1063 	udp_t	*udpnext;
1064 
1065 	ASSERT(MUTEX_HELD(&uf->uf_lock));
1066 	if (udp->udp_ptpbhn != NULL) {
1067 		udp_bind_hash_remove(udp, B_TRUE);
1068 	}
1069 	udpp = &uf->uf_udp;
1070 	udpnext = udpp[0];
1071 	if (udpnext != NULL) {
1072 		/*
1073 		 * If the new udp bound to the INADDR_ANY address
1074 		 * and the first one in the list is not bound to
1075 		 * INADDR_ANY we skip all entries until we find the
1076 		 * first one bound to INADDR_ANY.
1077 		 * This makes sure that applications binding to a
1078 		 * specific address get preference over those binding to
1079 		 * INADDR_ANY.
1080 		 */
1081 		if (V6_OR_V4_INADDR_ANY(udp->udp_bound_v6src) &&
1082 		    !V6_OR_V4_INADDR_ANY(udpnext->udp_bound_v6src)) {
1083 			while ((udpnext = udpp[0]) != NULL &&
1084 			    !V6_OR_V4_INADDR_ANY(
1085 			    udpnext->udp_bound_v6src)) {
1086 				udpp = &(udpnext->udp_bind_hash);
1087 			}
1088 			if (udpnext != NULL)
1089 				udpnext->udp_ptpbhn = &udp->udp_bind_hash;
1090 		} else {
1091 			udpnext->udp_ptpbhn = &udp->udp_bind_hash;
1092 		}
1093 	}
1094 	udp->udp_bind_hash = udpnext;
1095 	udp->udp_ptpbhn = udpp;
1096 	udpp[0] = udp;
1097 }
1098 
1099 /*
1100  * This routine is called to handle each O_T_BIND_REQ/T_BIND_REQ message
1101  * passed to udp_wput.
1102  * It associates a port number and local address with the stream.
1103  * The O_T_BIND_REQ/T_BIND_REQ is passed downstream to ip with the UDP
1104  * protocol type (IPPROTO_UDP) placed in the message following the address.
1105  * A T_BIND_ACK message is passed upstream when ip acknowledges the request.
1106  * (Called as writer.)
1107  *
1108  * Note that UDP over IPv4 and IPv6 sockets can use the same port number
1109  * without setting SO_REUSEADDR. This is needed so that they
1110  * can be viewed as two independent transport protocols.
1111  * However, anonymouns ports are allocated from the same range to avoid
1112  * duplicating the udp_g_next_port_to_try.
1113  */
1114 static void
1115 udp_bind(queue_t *q, mblk_t *mp)
1116 {
1117 	sin_t		*sin;
1118 	sin6_t		*sin6;
1119 	mblk_t		*mp1;
1120 	in_port_t	port;		/* Host byte order */
1121 	in_port_t	requested_port;	/* Host byte order */
1122 	struct T_bind_req *tbr;
1123 	int		count;
1124 	in6_addr_t	v6src;
1125 	boolean_t	bind_to_req_port_only;
1126 	int		loopmax;
1127 	udp_fanout_t	*udpf;
1128 	in_port_t	lport;		/* Network byte order */
1129 	zoneid_t	zoneid;
1130 	conn_t		*connp;
1131 	udp_t		*udp;
1132 	boolean_t	is_inaddr_any;
1133 	mlp_type_t	addrtype, mlptype;
1134 
1135 	connp = Q_TO_CONN(q);
1136 	udp = connp->conn_udp;
1137 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
1138 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
1139 		    "udp_bind: bad req, len %u",
1140 		    (uint_t)(mp->b_wptr - mp->b_rptr));
1141 		udp_err_ack(q, mp, TPROTO, 0);
1142 		return;
1143 	}
1144 
1145 	if (udp->udp_state != TS_UNBND) {
1146 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
1147 		    "udp_bind: bad state, %u", udp->udp_state);
1148 		udp_err_ack(q, mp, TOUTSTATE, 0);
1149 		return;
1150 	}
1151 	/*
1152 	 * Reallocate the message to make sure we have enough room for an
1153 	 * address and the protocol type.
1154 	 */
1155 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
1156 	if (!mp1) {
1157 		udp_err_ack(q, mp, TSYSERR, ENOMEM);
1158 		return;
1159 	}
1160 
1161 	mp = mp1;
1162 	tbr = (struct T_bind_req *)mp->b_rptr;
1163 	switch (tbr->ADDR_length) {
1164 	case 0:			/* Request for a generic port */
1165 		tbr->ADDR_offset = sizeof (struct T_bind_req);
1166 		if (udp->udp_family == AF_INET) {
1167 			tbr->ADDR_length = sizeof (sin_t);
1168 			sin = (sin_t *)&tbr[1];
1169 			*sin = sin_null;
1170 			sin->sin_family = AF_INET;
1171 			mp->b_wptr = (uchar_t *)&sin[1];
1172 		} else {
1173 			ASSERT(udp->udp_family == AF_INET6);
1174 			tbr->ADDR_length = sizeof (sin6_t);
1175 			sin6 = (sin6_t *)&tbr[1];
1176 			*sin6 = sin6_null;
1177 			sin6->sin6_family = AF_INET6;
1178 			mp->b_wptr = (uchar_t *)&sin6[1];
1179 		}
1180 		port = 0;
1181 		break;
1182 
1183 	case sizeof (sin_t):	/* Complete IPv4 address */
1184 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
1185 		    sizeof (sin_t));
1186 		if (sin == NULL || !OK_32PTR((char *)sin)) {
1187 			udp_err_ack(q, mp, TSYSERR, EINVAL);
1188 			return;
1189 		}
1190 		if (udp->udp_family != AF_INET ||
1191 		    sin->sin_family != AF_INET) {
1192 			udp_err_ack(q, mp, TSYSERR, EAFNOSUPPORT);
1193 			return;
1194 		}
1195 		port = ntohs(sin->sin_port);
1196 		break;
1197 
1198 	case sizeof (sin6_t):	/* complete IPv6 address */
1199 		sin6 = (sin6_t *)mi_offset_param(mp, tbr->ADDR_offset,
1200 		    sizeof (sin6_t));
1201 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
1202 			udp_err_ack(q, mp, TSYSERR, EINVAL);
1203 			return;
1204 		}
1205 		if (udp->udp_family != AF_INET6 ||
1206 		    sin6->sin6_family != AF_INET6) {
1207 			udp_err_ack(q, mp, TSYSERR, EAFNOSUPPORT);
1208 			return;
1209 		}
1210 		port = ntohs(sin6->sin6_port);
1211 		break;
1212 
1213 	default:		/* Invalid request */
1214 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
1215 		    "udp_bind: bad ADDR_length length %u", tbr->ADDR_length);
1216 		udp_err_ack(q, mp, TBADADDR, 0);
1217 		return;
1218 	}
1219 
1220 	requested_port = port;
1221 
1222 	if (requested_port == 0 || tbr->PRIM_type == O_T_BIND_REQ)
1223 		bind_to_req_port_only = B_FALSE;
1224 	else			/* T_BIND_REQ and requested_port != 0 */
1225 		bind_to_req_port_only = B_TRUE;
1226 
1227 	if (requested_port == 0) {
1228 		/*
1229 		 * If the application passed in zero for the port number, it
1230 		 * doesn't care which port number we bind to. Get one in the
1231 		 * valid range.
1232 		 */
1233 		if (udp->udp_anon_priv_bind) {
1234 			port = udp_get_next_priv_port(udp);
1235 		} else {
1236 			port = udp_update_next_port(udp,
1237 			    udp_g_next_port_to_try, B_TRUE);
1238 		}
1239 	} else {
1240 		/*
1241 		 * If the port is in the well-known privileged range,
1242 		 * make sure the caller was privileged.
1243 		 */
1244 		int i;
1245 		boolean_t priv = B_FALSE;
1246 
1247 		if (port < udp_smallest_nonpriv_port) {
1248 			priv = B_TRUE;
1249 		} else {
1250 			for (i = 0; i < udp_g_num_epriv_ports; i++) {
1251 				if (port == udp_g_epriv_ports[i]) {
1252 					priv = B_TRUE;
1253 					break;
1254 				}
1255 			}
1256 		}
1257 
1258 		if (priv) {
1259 			cred_t *cr = DB_CREDDEF(mp, connp->conn_cred);
1260 
1261 			if (secpolicy_net_privaddr(cr, port) != 0) {
1262 				udp_err_ack(q, mp, TACCES, 0);
1263 				return;
1264 			}
1265 		}
1266 	}
1267 
1268 	if (port == 0) {
1269 		udp_err_ack(q, mp, TNOADDR, 0);
1270 		return;
1271 	}
1272 
1273 	/*
1274 	 * Copy the source address into our udp structure. This address
1275 	 * may still be zero; if so, IP will fill in the correct address
1276 	 * each time an outbound packet is passed to it.
1277 	 */
1278 	if (udp->udp_family == AF_INET) {
1279 		ASSERT(sin != NULL);
1280 		ASSERT(udp->udp_ipversion == IPV4_VERSION);
1281 		udp->udp_max_hdr_len = IP_SIMPLE_HDR_LENGTH + UDPH_SIZE +
1282 		    udp->udp_ip_snd_options_len;
1283 		IN6_IPADDR_TO_V4MAPPED(sin->sin_addr.s_addr, &v6src);
1284 	} else {
1285 		ASSERT(sin6 != NULL);
1286 		v6src = sin6->sin6_addr;
1287 		if (IN6_IS_ADDR_V4MAPPED(&v6src)) {
1288 			udp->udp_ipversion = IPV4_VERSION;
1289 			udp->udp_max_hdr_len = IP_SIMPLE_HDR_LENGTH +
1290 			    UDPH_SIZE + udp->udp_ip_snd_options_len;
1291 		} else {
1292 			udp->udp_ipversion = IPV6_VERSION;
1293 			udp->udp_max_hdr_len = udp->udp_sticky_hdrs_len;
1294 		}
1295 	}
1296 
1297 	/*
1298 	 * If udp_reuseaddr is not set, then we have to make sure that
1299 	 * the IP address and port number the application requested
1300 	 * (or we selected for the application) is not being used by
1301 	 * another stream.  If another stream is already using the
1302 	 * requested IP address and port, the behavior depends on
1303 	 * "bind_to_req_port_only". If set the bind fails; otherwise we
1304 	 * search for any an unused port to bind to the the stream.
1305 	 *
1306 	 * As per the BSD semantics, as modified by the Deering multicast
1307 	 * changes, if udp_reuseaddr is set, then we allow multiple binds
1308 	 * to the same port independent of the local IP address.
1309 	 *
1310 	 * This is slightly different than in SunOS 4.X which did not
1311 	 * support IP multicast. Note that the change implemented by the
1312 	 * Deering multicast code effects all binds - not only binding
1313 	 * to IP multicast addresses.
1314 	 *
1315 	 * Note that when binding to port zero we ignore SO_REUSEADDR in
1316 	 * order to guarantee a unique port.
1317 	 */
1318 
1319 	count = 0;
1320 	if (udp->udp_anon_priv_bind) {
1321 		/* loopmax = (IPPORT_RESERVED-1) - udp_min_anonpriv_port + 1 */
1322 		loopmax = IPPORT_RESERVED - udp_min_anonpriv_port;
1323 	} else {
1324 		loopmax = udp_largest_anon_port - udp_smallest_anon_port + 1;
1325 	}
1326 
1327 	is_inaddr_any = V6_OR_V4_INADDR_ANY(v6src);
1328 	zoneid = connp->conn_zoneid;
1329 
1330 	for (;;) {
1331 		udp_t		*udp1;
1332 		boolean_t	found_exclbind = B_FALSE;
1333 
1334 		/*
1335 		 * Walk through the list of udp streams bound to
1336 		 * requested port with the same IP address.
1337 		 */
1338 		lport = htons(port);
1339 		udpf = &udp_bind_fanout[UDP_BIND_HASH(lport)];
1340 		mutex_enter(&udpf->uf_lock);
1341 		for (udp1 = udpf->uf_udp; udp1 != NULL;
1342 		    udp1 = udp1->udp_bind_hash) {
1343 			if (lport != udp1->udp_port)
1344 				continue;
1345 
1346 			/*
1347 			 * On a labeled system, we must treat bindings to ports
1348 			 * on shared IP addresses by sockets with MAC exemption
1349 			 * privilege as being in all zones, as there's
1350 			 * otherwise no way to identify the right receiver.
1351 			 */
1352 			if (zoneid != udp1->udp_connp->conn_zoneid &&
1353 			    !udp->udp_mac_exempt && !udp1->udp_mac_exempt)
1354 				continue;
1355 
1356 			/*
1357 			 * If UDP_EXCLBIND is set for either the bound or
1358 			 * binding endpoint, the semantics of bind
1359 			 * is changed according to the following chart.
1360 			 *
1361 			 * spec = specified address (v4 or v6)
1362 			 * unspec = unspecified address (v4 or v6)
1363 			 * A = specified addresses are different for endpoints
1364 			 *
1365 			 * bound	bind to		allowed?
1366 			 * -------------------------------------
1367 			 * unspec	unspec		no
1368 			 * unspec	spec		no
1369 			 * spec		unspec		no
1370 			 * spec		spec		yes if A
1371 			 *
1372 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
1373 			 * as UDP_EXCLBIND, except that zoneid is ignored.
1374 			 */
1375 			if (udp1->udp_exclbind || udp->udp_exclbind ||
1376 			    udp1->udp_mac_exempt || udp->udp_mac_exempt) {
1377 				if (V6_OR_V4_INADDR_ANY(
1378 				    udp1->udp_bound_v6src) ||
1379 				    is_inaddr_any ||
1380 				    IN6_ARE_ADDR_EQUAL(&udp1->udp_bound_v6src,
1381 				    &v6src)) {
1382 					found_exclbind = B_TRUE;
1383 					break;
1384 				}
1385 				continue;
1386 			}
1387 
1388 			/*
1389 			 * Check ipversion to allow IPv4 and IPv6 sockets to
1390 			 * have disjoint port number spaces.
1391 			 */
1392 			if (udp->udp_ipversion != udp1->udp_ipversion) {
1393 
1394 				/*
1395 				 * On the first time through the loop, if the
1396 				 * the user intentionally specified a
1397 				 * particular port number, then ignore any
1398 				 * bindings of the other protocol that may
1399 				 * conflict. This allows the user to bind IPv6
1400 				 * alone and get both v4 and v6, or bind both
1401 				 * both and get each seperately. On subsequent
1402 				 * times through the loop, we're checking a
1403 				 * port that we chose (not the user) and thus
1404 				 * we do not allow casual duplicate bindings.
1405 				 */
1406 				if (count == 0 && requested_port != 0)
1407 					continue;
1408 			}
1409 
1410 			/*
1411 			 * No difference depending on SO_REUSEADDR.
1412 			 *
1413 			 * If existing port is bound to a
1414 			 * non-wildcard IP address and
1415 			 * the requesting stream is bound to
1416 			 * a distinct different IP addresses
1417 			 * (non-wildcard, also), keep going.
1418 			 */
1419 			if (!is_inaddr_any &&
1420 			    !V6_OR_V4_INADDR_ANY(udp1->udp_bound_v6src) &&
1421 			    !IN6_ARE_ADDR_EQUAL(&udp1->udp_bound_v6src,
1422 			    &v6src)) {
1423 				continue;
1424 			}
1425 			break;
1426 		}
1427 
1428 		if (!found_exclbind &&
1429 		    (udp->udp_reuseaddr && requested_port != 0)) {
1430 			break;
1431 		}
1432 
1433 		if (udp1 == NULL) {
1434 			/*
1435 			 * No other stream has this IP address
1436 			 * and port number. We can use it.
1437 			 */
1438 			break;
1439 		}
1440 		mutex_exit(&udpf->uf_lock);
1441 		if (bind_to_req_port_only) {
1442 			/*
1443 			 * We get here only when requested port
1444 			 * is bound (and only first  of the for()
1445 			 * loop iteration).
1446 			 *
1447 			 * The semantics of this bind request
1448 			 * require it to fail so we return from
1449 			 * the routine (and exit the loop).
1450 			 *
1451 			 */
1452 			udp_err_ack(q, mp, TADDRBUSY, 0);
1453 			return;
1454 		}
1455 
1456 		if (udp->udp_anon_priv_bind) {
1457 			port = udp_get_next_priv_port(udp);
1458 		} else {
1459 			if ((count == 0) && (requested_port != 0)) {
1460 				/*
1461 				 * If the application wants us to find
1462 				 * a port, get one to start with. Set
1463 				 * requested_port to 0, so that we will
1464 				 * update udp_g_next_port_to_try below.
1465 				 */
1466 				port = udp_update_next_port(udp,
1467 				    udp_g_next_port_to_try, B_TRUE);
1468 				requested_port = 0;
1469 			} else {
1470 				port = udp_update_next_port(udp, port + 1,
1471 				    B_FALSE);
1472 			}
1473 		}
1474 
1475 		if (port == 0 || ++count >= loopmax) {
1476 			/*
1477 			 * We've tried every possible port number and
1478 			 * there are none available, so send an error
1479 			 * to the user.
1480 			 */
1481 			udp_err_ack(q, mp, TNOADDR, 0);
1482 			return;
1483 		}
1484 	}
1485 
1486 	/*
1487 	 * Copy the source address into our udp structure.  This address
1488 	 * may still be zero; if so, ip will fill in the correct address
1489 	 * each time an outbound packet is passed to it.
1490 	 * If we are binding to a broadcast or multicast address udp_rput
1491 	 * will clear the source address when it receives the T_BIND_ACK.
1492 	 */
1493 	udp->udp_v6src = udp->udp_bound_v6src = v6src;
1494 	udp->udp_port = lport;
1495 	/*
1496 	 * Now reset the the next anonymous port if the application requested
1497 	 * an anonymous port, or we handed out the next anonymous port.
1498 	 */
1499 	if ((requested_port == 0) && (!udp->udp_anon_priv_bind)) {
1500 		udp_g_next_port_to_try = port + 1;
1501 	}
1502 
1503 	/* Initialize the O_T_BIND_REQ/T_BIND_REQ for ip. */
1504 	if (udp->udp_family == AF_INET) {
1505 		sin->sin_port = udp->udp_port;
1506 	} else {
1507 		int error;
1508 
1509 		sin6->sin6_port = udp->udp_port;
1510 		/* Rebuild the header template */
1511 		error = udp_build_hdrs(q, udp);
1512 		if (error != 0) {
1513 			mutex_exit(&udpf->uf_lock);
1514 			udp_err_ack(q, mp, TSYSERR, error);
1515 			return;
1516 		}
1517 	}
1518 	udp->udp_state = TS_IDLE;
1519 	udp_bind_hash_insert(udpf, udp);
1520 	mutex_exit(&udpf->uf_lock);
1521 
1522 	if (cl_inet_bind) {
1523 		/*
1524 		 * Running in cluster mode - register bind information
1525 		 */
1526 		if (udp->udp_ipversion == IPV4_VERSION) {
1527 			(*cl_inet_bind)(IPPROTO_UDP, AF_INET,
1528 			    (uint8_t *)(&V4_PART_OF_V6(udp->udp_v6src)),
1529 			    (in_port_t)udp->udp_port);
1530 		} else {
1531 			(*cl_inet_bind)(IPPROTO_UDP, AF_INET6,
1532 			    (uint8_t *)&(udp->udp_v6src),
1533 			    (in_port_t)udp->udp_port);
1534 		}
1535 
1536 	}
1537 
1538 	connp->conn_anon_port = (is_system_labeled() && requested_port == 0);
1539 	if (is_system_labeled() && (!connp->conn_anon_port ||
1540 	    connp->conn_anon_mlp)) {
1541 		uint16_t mlpport;
1542 		cred_t *cr = connp->conn_cred;
1543 		zone_t *zone;
1544 
1545 		connp->conn_mlp_type = udp->udp_recvucred ? mlptBoth :
1546 		    mlptSingle;
1547 		addrtype = tsol_mlp_addr_type(zoneid, IPV6_VERSION, &v6src);
1548 		if (addrtype == mlptSingle) {
1549 			udp_err_ack(q, mp, TNOADDR, 0);
1550 			connp->conn_anon_port = B_FALSE;
1551 			connp->conn_mlp_type = mlptSingle;
1552 			return;
1553 		}
1554 		mlpport = connp->conn_anon_port ? PMAPPORT : port;
1555 		zone = crgetzone(cr);
1556 		mlptype = tsol_mlp_port_type(zone, IPPROTO_UDP, mlpport,
1557 		    addrtype);
1558 		if (mlptype != mlptSingle &&
1559 		    (connp->conn_mlp_type == mlptSingle ||
1560 		    secpolicy_net_bindmlp(cr) != 0)) {
1561 			if (udp->udp_debug) {
1562 				(void) strlog(UDP_MOD_ID, 0, 1,
1563 				    SL_ERROR|SL_TRACE,
1564 				    "udp_bind: no priv for multilevel port %d",
1565 				    mlpport);
1566 			}
1567 			udp_err_ack(q, mp, TACCES, 0);
1568 			connp->conn_anon_port = B_FALSE;
1569 			connp->conn_mlp_type = mlptSingle;
1570 			return;
1571 		}
1572 
1573 		/*
1574 		 * If we're specifically binding a shared IP address and the
1575 		 * port is MLP on shared addresses, then check to see if this
1576 		 * zone actually owns the MLP.  Reject if not.
1577 		 */
1578 		if (mlptype == mlptShared && addrtype == mlptShared) {
1579 			zoneid_t mlpzone;
1580 
1581 			mlpzone = tsol_mlp_findzone(IPPROTO_UDP,
1582 			    htons(mlpport));
1583 			if (connp->conn_zoneid != mlpzone) {
1584 				if (udp->udp_debug) {
1585 					(void) strlog(UDP_MOD_ID, 0, 1,
1586 					    SL_ERROR|SL_TRACE,
1587 					    "udp_bind: attempt to bind port "
1588 					    "%d on shared addr in zone %d "
1589 					    "(should be %d)",
1590 					    mlpport, connp->conn_zoneid,
1591 					    mlpzone);
1592 				}
1593 				udp_err_ack(q, mp, TACCES, 0);
1594 				connp->conn_anon_port = B_FALSE;
1595 				connp->conn_mlp_type = mlptSingle;
1596 				return;
1597 			}
1598 		}
1599 		if (connp->conn_anon_port) {
1600 			int error;
1601 
1602 			error = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
1603 			    port, B_TRUE);
1604 			if (error != 0) {
1605 				if (udp->udp_debug) {
1606 					(void) strlog(UDP_MOD_ID, 0, 1,
1607 					    SL_ERROR|SL_TRACE,
1608 					    "udp_bind: cannot establish anon "
1609 					    "MLP for port %d", port);
1610 				}
1611 				udp_err_ack(q, mp, TACCES, 0);
1612 				connp->conn_anon_port = B_FALSE;
1613 				connp->conn_mlp_type = mlptSingle;
1614 				return;
1615 			}
1616 		}
1617 		connp->conn_mlp_type = mlptype;
1618 	}
1619 
1620 	/* Pass the protocol number in the message following the address. */
1621 	*mp->b_wptr++ = IPPROTO_UDP;
1622 	if (!V6_OR_V4_INADDR_ANY(udp->udp_v6src)) {
1623 		/*
1624 		 * Append a request for an IRE if udp_v6src not
1625 		 * zero (IPv4 - INADDR_ANY, or IPv6 - all-zeroes address).
1626 		 */
1627 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
1628 		if (!mp->b_cont) {
1629 			udp_err_ack(q, mp, TSYSERR, ENOMEM);
1630 			return;
1631 		}
1632 		mp->b_cont->b_wptr += sizeof (ire_t);
1633 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
1634 	}
1635 	if (udp->udp_family == AF_INET6)
1636 		mp = ip_bind_v6(q, mp, connp, NULL);
1637 	else
1638 		mp = ip_bind_v4(q, mp, connp);
1639 
1640 	if (mp != NULL)
1641 		udp_rput_other(_RD(q), mp);
1642 	else
1643 		CONN_INC_REF(connp);
1644 }
1645 
1646 
1647 void
1648 udp_resume_bind(conn_t *connp, mblk_t *mp)
1649 {
1650 	udp_enter(connp, mp, udp_resume_bind_cb, SQTAG_BIND_RETRY);
1651 }
1652 
1653 /*
1654  * This is called from ip_wput_nondata to resume a deferred UDP bind.
1655  */
1656 /* ARGSUSED */
1657 static void
1658 udp_resume_bind_cb(void *arg, mblk_t *mp, void *arg2)
1659 {
1660 	conn_t *connp = arg;
1661 
1662 	ASSERT(connp != NULL && IPCL_IS_UDP(connp));
1663 
1664 	udp_rput_other(connp->conn_rq, mp);
1665 
1666 	CONN_OPER_PENDING_DONE(connp);
1667 	udp_exit(connp);
1668 }
1669 
1670 /*
1671  * This routine handles each T_CONN_REQ message passed to udp.  It
1672  * associates a default destination address with the stream.
1673  *
1674  * This routine sends down a T_BIND_REQ to IP with the following mblks:
1675  *	T_BIND_REQ	- specifying local and remote address/port
1676  *	IRE_DB_REQ_TYPE	- to get an IRE back containing ire_type and src
1677  *	T_OK_ACK	- for the T_CONN_REQ
1678  *	T_CONN_CON	- to keep the TPI user happy
1679  *
1680  * The connect completes in udp_rput.
1681  * When a T_BIND_ACK is received information is extracted from the IRE
1682  * and the two appended messages are sent to the TPI user.
1683  * Should udp_rput receive T_ERROR_ACK for the T_BIND_REQ it will convert
1684  * it to an error ack for the appropriate primitive.
1685  */
1686 static void
1687 udp_connect(queue_t *q, mblk_t *mp)
1688 {
1689 	sin6_t	*sin6;
1690 	sin_t	*sin;
1691 	struct T_conn_req	*tcr;
1692 	in6_addr_t v6dst;
1693 	ipaddr_t v4dst;
1694 	uint16_t dstport;
1695 	uint32_t flowinfo;
1696 	mblk_t	*mp1, *mp2;
1697 	udp_fanout_t	*udpf;
1698 	udp_t	*udp, *udp1;
1699 
1700 	udp = Q_TO_UDP(q);
1701 
1702 	tcr = (struct T_conn_req *)mp->b_rptr;
1703 
1704 	/* A bit of sanity checking */
1705 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_req)) {
1706 		udp_err_ack(q, mp, TPROTO, 0);
1707 		return;
1708 	}
1709 	/*
1710 	 * This UDP must have bound to a port already before doing
1711 	 * a connect.
1712 	 */
1713 	if (udp->udp_state == TS_UNBND) {
1714 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
1715 		    "udp_connect: bad state, %u", udp->udp_state);
1716 		udp_err_ack(q, mp, TOUTSTATE, 0);
1717 		return;
1718 	}
1719 	ASSERT(udp->udp_port != 0 && udp->udp_ptpbhn != NULL);
1720 
1721 	udpf = &udp_bind_fanout[UDP_BIND_HASH(udp->udp_port)];
1722 
1723 	if (udp->udp_state == TS_DATA_XFER) {
1724 		/* Already connected - clear out state */
1725 		mutex_enter(&udpf->uf_lock);
1726 		udp->udp_v6src = udp->udp_bound_v6src;
1727 		udp->udp_state = TS_IDLE;
1728 		mutex_exit(&udpf->uf_lock);
1729 	}
1730 
1731 	if (tcr->OPT_length != 0) {
1732 		udp_err_ack(q, mp, TBADOPT, 0);
1733 		return;
1734 	}
1735 
1736 	/*
1737 	 * Determine packet type based on type of address passed in
1738 	 * the request should contain an IPv4 or IPv6 address.
1739 	 * Make sure that address family matches the type of
1740 	 * family of the the address passed down
1741 	 */
1742 	switch (tcr->DEST_length) {
1743 	default:
1744 		udp_err_ack(q, mp, TBADADDR, 0);
1745 		return;
1746 
1747 	case sizeof (sin_t):
1748 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
1749 		    sizeof (sin_t));
1750 		if (sin == NULL || !OK_32PTR((char *)sin)) {
1751 			udp_err_ack(q, mp, TSYSERR, EINVAL);
1752 			return;
1753 		}
1754 		if (udp->udp_family != AF_INET ||
1755 		    sin->sin_family != AF_INET) {
1756 			udp_err_ack(q, mp, TSYSERR, EAFNOSUPPORT);
1757 			return;
1758 		}
1759 		v4dst = sin->sin_addr.s_addr;
1760 		dstport = sin->sin_port;
1761 		IN6_IPADDR_TO_V4MAPPED(v4dst, &v6dst);
1762 		ASSERT(udp->udp_ipversion == IPV4_VERSION);
1763 		udp->udp_max_hdr_len = IP_SIMPLE_HDR_LENGTH + UDPH_SIZE +
1764 		    udp->udp_ip_snd_options_len;
1765 		break;
1766 
1767 	case sizeof (sin6_t):
1768 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
1769 		    sizeof (sin6_t));
1770 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
1771 			udp_err_ack(q, mp, TSYSERR, EINVAL);
1772 			return;
1773 		}
1774 		if (udp->udp_family != AF_INET6 ||
1775 		    sin6->sin6_family != AF_INET6) {
1776 			udp_err_ack(q, mp, TSYSERR, EAFNOSUPPORT);
1777 			return;
1778 		}
1779 		v6dst = sin6->sin6_addr;
1780 		if (IN6_IS_ADDR_V4MAPPED(&v6dst)) {
1781 			IN6_V4MAPPED_TO_IPADDR(&v6dst, v4dst);
1782 			udp->udp_ipversion = IPV4_VERSION;
1783 			udp->udp_max_hdr_len = IP_SIMPLE_HDR_LENGTH +
1784 			    UDPH_SIZE + udp->udp_ip_snd_options_len;
1785 			flowinfo = 0;
1786 		} else {
1787 			udp->udp_ipversion = IPV6_VERSION;
1788 			udp->udp_max_hdr_len = udp->udp_sticky_hdrs_len;
1789 			flowinfo = sin6->sin6_flowinfo;
1790 		}
1791 		dstport = sin6->sin6_port;
1792 		break;
1793 	}
1794 	if (dstport == 0) {
1795 		udp_err_ack(q, mp, TBADADDR, 0);
1796 		return;
1797 	}
1798 
1799 	/*
1800 	 * Create a default IP header with no IP options.
1801 	 */
1802 	udp->udp_dstport = dstport;
1803 	if (udp->udp_ipversion == IPV4_VERSION) {
1804 		/*
1805 		 * Interpret a zero destination to mean loopback.
1806 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
1807 		 * generate the T_CONN_CON.
1808 		 */
1809 		if (v4dst == INADDR_ANY) {
1810 			v4dst = htonl(INADDR_LOOPBACK);
1811 			IN6_IPADDR_TO_V4MAPPED(v4dst, &v6dst);
1812 			if (udp->udp_family == AF_INET) {
1813 				sin->sin_addr.s_addr = v4dst;
1814 			} else {
1815 				sin6->sin6_addr = v6dst;
1816 			}
1817 		}
1818 		udp->udp_v6dst = v6dst;
1819 		udp->udp_flowinfo = 0;
1820 
1821 		/*
1822 		 * If the destination address is multicast and
1823 		 * an outgoing multicast interface has been set,
1824 		 * use the address of that interface as our
1825 		 * source address if no source address has been set.
1826 		 */
1827 		if (V4_PART_OF_V6(udp->udp_v6src) == INADDR_ANY &&
1828 		    CLASSD(v4dst) &&
1829 		    udp->udp_multicast_if_addr != INADDR_ANY) {
1830 			IN6_IPADDR_TO_V4MAPPED(udp->udp_multicast_if_addr,
1831 			    &udp->udp_v6src);
1832 		}
1833 	} else {
1834 		ASSERT(udp->udp_ipversion == IPV6_VERSION);
1835 		/*
1836 		 * Interpret a zero destination to mean loopback.
1837 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
1838 		 * generate the T_CONN_CON.
1839 		 */
1840 		if (IN6_IS_ADDR_UNSPECIFIED(&v6dst)) {
1841 			v6dst = ipv6_loopback;
1842 			sin6->sin6_addr = v6dst;
1843 		}
1844 		udp->udp_v6dst = v6dst;
1845 		udp->udp_flowinfo = flowinfo;
1846 		/*
1847 		 * If the destination address is multicast and
1848 		 * an outgoing multicast interface has been set,
1849 		 * then the ip bind logic will pick the correct source
1850 		 * address (i.e. matching the outgoing multicast interface).
1851 		 */
1852 	}
1853 
1854 	/*
1855 	 * Verify that the src/port/dst/port is unique for all
1856 	 * connections in TS_DATA_XFER
1857 	 */
1858 	mutex_enter(&udpf->uf_lock);
1859 	for (udp1 = udpf->uf_udp; udp1 != NULL; udp1 = udp1->udp_bind_hash) {
1860 		if (udp1->udp_state != TS_DATA_XFER)
1861 			continue;
1862 		if (udp->udp_port != udp1->udp_port ||
1863 		    udp->udp_ipversion != udp1->udp_ipversion ||
1864 		    dstport != udp1->udp_dstport ||
1865 		    !IN6_ARE_ADDR_EQUAL(&udp->udp_v6src, &udp1->udp_v6src) ||
1866 		    !IN6_ARE_ADDR_EQUAL(&v6dst, &udp1->udp_v6dst))
1867 			continue;
1868 		mutex_exit(&udpf->uf_lock);
1869 		udp_err_ack(q, mp, TBADADDR, 0);
1870 		return;
1871 	}
1872 	udp->udp_state = TS_DATA_XFER;
1873 	mutex_exit(&udpf->uf_lock);
1874 
1875 	/*
1876 	 * Send down bind to IP to verify that there is a route
1877 	 * and to determine the source address.
1878 	 * This will come back as T_BIND_ACK with an IRE_DB_TYPE in rput.
1879 	 */
1880 	if (udp->udp_family == AF_INET)
1881 		mp1 = udp_ip_bind_mp(udp, O_T_BIND_REQ, sizeof (ipa_conn_t));
1882 	else
1883 		mp1 = udp_ip_bind_mp(udp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
1884 	if (mp1 == NULL) {
1885 		udp_err_ack(q, mp, TSYSERR, ENOMEM);
1886 bind_failed:
1887 		mutex_enter(&udpf->uf_lock);
1888 		udp->udp_state = TS_IDLE;
1889 		mutex_exit(&udpf->uf_lock);
1890 		return;
1891 	}
1892 
1893 	/*
1894 	 * We also have to send a connection confirmation to
1895 	 * keep TLI happy. Prepare it for udp_rput.
1896 	 */
1897 	if (udp->udp_family == AF_INET)
1898 		mp2 = mi_tpi_conn_con(NULL, (char *)sin,
1899 		    sizeof (*sin), NULL, 0);
1900 	else
1901 		mp2 = mi_tpi_conn_con(NULL, (char *)sin6,
1902 		    sizeof (*sin6), NULL, 0);
1903 	if (mp2 == NULL) {
1904 		freemsg(mp1);
1905 		udp_err_ack(q, mp, TSYSERR, ENOMEM);
1906 		goto bind_failed;
1907 	}
1908 
1909 	mp = mi_tpi_ok_ack_alloc(mp);
1910 	if (mp == NULL) {
1911 		/* Unable to reuse the T_CONN_REQ for the ack. */
1912 		freemsg(mp2);
1913 		udp_err_ack_prim(q, mp1, T_CONN_REQ, TSYSERR, ENOMEM);
1914 		goto bind_failed;
1915 	}
1916 
1917 	/* Hang onto the T_OK_ACK and T_CONN_CON for later. */
1918 	linkb(mp1, mp);
1919 	linkb(mp1, mp2);
1920 
1921 	mblk_setcred(mp1, udp->udp_connp->conn_cred);
1922 	if (udp->udp_family == AF_INET)
1923 		mp1 = ip_bind_v4(q, mp1, udp->udp_connp);
1924 	else
1925 		mp1 = ip_bind_v6(q, mp1, udp->udp_connp, NULL);
1926 
1927 	if (mp1 != NULL)
1928 		udp_rput_other(_RD(q), mp1);
1929 	else
1930 		CONN_INC_REF(udp->udp_connp);
1931 }
1932 
1933 static int
1934 udp_close(queue_t *q)
1935 {
1936 	conn_t	*connp = Q_TO_CONN(UDP_WR(q));
1937 	udp_t	*udp;
1938 	queue_t	*ip_rq = RD(UDP_WR(q));
1939 
1940 	ASSERT(connp != NULL && IPCL_IS_UDP(connp));
1941 	udp = connp->conn_udp;
1942 
1943 	ip_quiesce_conn(connp);
1944 	/*
1945 	 * Disable read-side synchronous stream
1946 	 * interface and drain any queued data.
1947 	 */
1948 	udp_rcv_drain(q, udp, B_TRUE);
1949 	ASSERT(!udp->udp_direct_sockfs);
1950 
1951 	qprocsoff(q);
1952 
1953 	/* restore IP module's high and low water marks to default values */
1954 	ip_rq->q_hiwat = ip_rq->q_qinfo->qi_minfo->mi_hiwat;
1955 	WR(ip_rq)->q_hiwat = WR(ip_rq)->q_qinfo->qi_minfo->mi_hiwat;
1956 	WR(ip_rq)->q_lowat = WR(ip_rq)->q_qinfo->qi_minfo->mi_lowat;
1957 
1958 	ASSERT(udp->udp_rcv_cnt == 0);
1959 	ASSERT(udp->udp_rcv_msgcnt == 0);
1960 	ASSERT(udp->udp_rcv_list_head == NULL);
1961 	ASSERT(udp->udp_rcv_list_tail == NULL);
1962 
1963 	/* connp is now single threaded. */
1964 	udp_close_free(connp);
1965 	/*
1966 	 * Restore connp as an IP endpoint.  We don't need
1967 	 * any locks since we are now single threaded
1968 	 */
1969 	connp->conn_flags &= ~IPCL_UDP;
1970 	connp->conn_state_flags &=
1971 	    ~(CONN_CLOSING | CONN_CONDEMNED | CONN_QUIESCED);
1972 	connp->conn_ulp_labeled = B_FALSE;
1973 	return (0);
1974 }
1975 
1976 /*
1977  * Called in the close path from IP (ip_quiesce_conn) to quiesce the conn
1978  */
1979 void
1980 udp_quiesce_conn(conn_t *connp)
1981 {
1982 	udp_t	*udp = connp->conn_udp;
1983 
1984 	if (cl_inet_unbind != NULL && udp->udp_state == TS_IDLE) {
1985 		/*
1986 		 * Running in cluster mode - register unbind information
1987 		 */
1988 		if (udp->udp_ipversion == IPV4_VERSION) {
1989 			(*cl_inet_unbind)(IPPROTO_UDP, AF_INET,
1990 			    (uint8_t *)(&(V4_PART_OF_V6(udp->udp_v6src))),
1991 			    (in_port_t)udp->udp_port);
1992 		} else {
1993 			(*cl_inet_unbind)(IPPROTO_UDP, AF_INET6,
1994 			    (uint8_t *)(&(udp->udp_v6src)),
1995 			    (in_port_t)udp->udp_port);
1996 		}
1997 	}
1998 
1999 	udp_bind_hash_remove(udp, B_FALSE);
2000 
2001 	mutex_enter(&connp->conn_lock);
2002 	while (udp->udp_reader_count != 0 || udp->udp_squeue_count != 0 ||
2003 	    udp->udp_mode != UDP_MT_HOT) {
2004 		cv_wait(&connp->conn_cv, &connp->conn_lock);
2005 	}
2006 	mutex_exit(&connp->conn_lock);
2007 }
2008 
2009 void
2010 udp_close_free(conn_t *connp)
2011 {
2012 	udp_t *udp = connp->conn_udp;
2013 
2014 	/* If there are any options associated with the stream, free them. */
2015 	if (udp->udp_ip_snd_options) {
2016 		mi_free((char *)udp->udp_ip_snd_options);
2017 		udp->udp_ip_snd_options = NULL;
2018 	}
2019 
2020 	if (udp->udp_ip_rcv_options) {
2021 		mi_free((char *)udp->udp_ip_rcv_options);
2022 		udp->udp_ip_rcv_options = NULL;
2023 	}
2024 
2025 	/* Free memory associated with sticky options */
2026 	if (udp->udp_sticky_hdrs_len != 0) {
2027 		kmem_free(udp->udp_sticky_hdrs,
2028 		    udp->udp_sticky_hdrs_len);
2029 		udp->udp_sticky_hdrs = NULL;
2030 		udp->udp_sticky_hdrs_len = 0;
2031 	}
2032 
2033 	ip6_pkt_free(&udp->udp_sticky_ipp);
2034 
2035 	udp->udp_connp = NULL;
2036 	connp->conn_udp = NULL;
2037 	kmem_cache_free(udp_cache, udp);
2038 }
2039 
2040 /*
2041  * This routine handles each T_DISCON_REQ message passed to udp
2042  * as an indicating that UDP is no longer connected. This results
2043  * in sending a T_BIND_REQ to IP to restore the binding to just
2044  * the local address/port.
2045  *
2046  * This routine sends down a T_BIND_REQ to IP with the following mblks:
2047  *	T_BIND_REQ	- specifying just the local address/port
2048  *	T_OK_ACK	- for the T_DISCON_REQ
2049  *
2050  * The disconnect completes in udp_rput.
2051  * When a T_BIND_ACK is received the appended T_OK_ACK is sent to the TPI user.
2052  * Should udp_rput receive T_ERROR_ACK for the T_BIND_REQ it will convert
2053  * it to an error ack for the appropriate primitive.
2054  */
2055 static void
2056 udp_disconnect(queue_t *q, mblk_t *mp)
2057 {
2058 	udp_t	*udp = Q_TO_UDP(q);
2059 	mblk_t	*mp1;
2060 	udp_fanout_t *udpf;
2061 
2062 	if (udp->udp_state != TS_DATA_XFER) {
2063 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
2064 		    "udp_disconnect: bad state, %u", udp->udp_state);
2065 		udp_err_ack(q, mp, TOUTSTATE, 0);
2066 		return;
2067 	}
2068 	udpf = &udp_bind_fanout[UDP_BIND_HASH(udp->udp_port)];
2069 	mutex_enter(&udpf->uf_lock);
2070 	udp->udp_v6src = udp->udp_bound_v6src;
2071 	udp->udp_state = TS_IDLE;
2072 	mutex_exit(&udpf->uf_lock);
2073 
2074 	/*
2075 	 * Send down bind to IP to remove the full binding and revert
2076 	 * to the local address binding.
2077 	 */
2078 	if (udp->udp_family == AF_INET)
2079 		mp1 = udp_ip_bind_mp(udp, O_T_BIND_REQ, sizeof (sin_t));
2080 	else
2081 		mp1 = udp_ip_bind_mp(udp, O_T_BIND_REQ, sizeof (sin6_t));
2082 	if (mp1 == NULL) {
2083 		udp_err_ack(q, mp, TSYSERR, ENOMEM);
2084 		return;
2085 	}
2086 	mp = mi_tpi_ok_ack_alloc(mp);
2087 	if (mp == NULL) {
2088 		/* Unable to reuse the T_DISCON_REQ for the ack. */
2089 		udp_err_ack_prim(q, mp1, T_DISCON_REQ, TSYSERR, ENOMEM);
2090 		return;
2091 	}
2092 
2093 	if (udp->udp_family == AF_INET6) {
2094 		int error;
2095 
2096 		/* Rebuild the header template */
2097 		error = udp_build_hdrs(q, udp);
2098 		if (error != 0) {
2099 			udp_err_ack_prim(q, mp, T_DISCON_REQ, TSYSERR, error);
2100 			freemsg(mp1);
2101 			return;
2102 		}
2103 	}
2104 	mutex_enter(&udpf->uf_lock);
2105 	udp->udp_discon_pending = 1;
2106 	mutex_exit(&udpf->uf_lock);
2107 
2108 	/* Append the T_OK_ACK to the T_BIND_REQ for udp_rput */
2109 	linkb(mp1, mp);
2110 
2111 	if (udp->udp_family == AF_INET6)
2112 		mp1 = ip_bind_v6(q, mp1, udp->udp_connp, NULL);
2113 	else
2114 		mp1 = ip_bind_v4(q, mp1, udp->udp_connp);
2115 
2116 	if (mp1 != NULL)
2117 		udp_rput_other(_RD(q), mp1);
2118 	else
2119 		CONN_INC_REF(udp->udp_connp);
2120 }
2121 
2122 /* This routine creates a T_ERROR_ACK message and passes it upstream. */
2123 static void
2124 udp_err_ack(queue_t *q, mblk_t *mp, t_scalar_t t_error, int sys_error)
2125 {
2126 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
2127 		putnext(UDP_RD(q), mp);
2128 }
2129 
2130 /* Shorthand to generate and send TPI error acks to our client */
2131 static void
2132 udp_err_ack_prim(queue_t *q, mblk_t *mp, int primitive, t_scalar_t t_error,
2133     int sys_error)
2134 {
2135 	struct T_error_ack	*teackp;
2136 
2137 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
2138 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
2139 		teackp = (struct T_error_ack *)mp->b_rptr;
2140 		teackp->ERROR_prim = primitive;
2141 		teackp->TLI_error = t_error;
2142 		teackp->UNIX_error = sys_error;
2143 		putnext(UDP_RD(q), mp);
2144 	}
2145 }
2146 
2147 /*ARGSUSED*/
2148 static int
2149 udp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
2150 {
2151 	int i;
2152 
2153 	for (i = 0; i < udp_g_num_epriv_ports; i++) {
2154 		if (udp_g_epriv_ports[i] != 0)
2155 			(void) mi_mpprintf(mp, "%d ", udp_g_epriv_ports[i]);
2156 	}
2157 	return (0);
2158 }
2159 
2160 /* ARGSUSED */
2161 static int
2162 udp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
2163     cred_t *cr)
2164 {
2165 	long	new_value;
2166 	int	i;
2167 
2168 	/*
2169 	 * Fail the request if the new value does not lie within the
2170 	 * port number limits.
2171 	 */
2172 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
2173 	    new_value <= 0 || new_value >= 65536) {
2174 		return (EINVAL);
2175 	}
2176 
2177 	/* Check if the value is already in the list */
2178 	for (i = 0; i < udp_g_num_epriv_ports; i++) {
2179 		if (new_value == udp_g_epriv_ports[i]) {
2180 			return (EEXIST);
2181 		}
2182 	}
2183 	/* Find an empty slot */
2184 	for (i = 0; i < udp_g_num_epriv_ports; i++) {
2185 		if (udp_g_epriv_ports[i] == 0)
2186 			break;
2187 	}
2188 	if (i == udp_g_num_epriv_ports) {
2189 		return (EOVERFLOW);
2190 	}
2191 
2192 	/* Set the new value */
2193 	udp_g_epriv_ports[i] = (in_port_t)new_value;
2194 	return (0);
2195 }
2196 
2197 /* ARGSUSED */
2198 static int
2199 udp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
2200     cred_t *cr)
2201 {
2202 	long	new_value;
2203 	int	i;
2204 
2205 	/*
2206 	 * Fail the request if the new value does not lie within the
2207 	 * port number limits.
2208 	 */
2209 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
2210 	    new_value <= 0 || new_value >= 65536) {
2211 		return (EINVAL);
2212 	}
2213 
2214 	/* Check that the value is already in the list */
2215 	for (i = 0; i < udp_g_num_epriv_ports; i++) {
2216 		if (udp_g_epriv_ports[i] == new_value)
2217 			break;
2218 	}
2219 	if (i == udp_g_num_epriv_ports) {
2220 		return (ESRCH);
2221 	}
2222 
2223 	/* Clear the value */
2224 	udp_g_epriv_ports[i] = 0;
2225 	return (0);
2226 }
2227 
2228 /* At minimum we need 4 bytes of UDP header */
2229 #define	ICMP_MIN_UDP_HDR	4
2230 
2231 /*
2232  * udp_icmp_error is called by udp_rput to process ICMP msgs. passed up by IP.
2233  * Generates the appropriate T_UDERROR_IND for permanent (non-transient) errors.
2234  * Assumes that IP has pulled up everything up to and including the ICMP header.
2235  * An M_CTL could potentially come here from some other module (i.e. if UDP
2236  * is pushed on some module other than IP). Thus, if we find that the M_CTL
2237  * does not have enough ICMP information , following STREAMS conventions,
2238  * we send it upstream assuming it is an M_CTL we don't understand.
2239  */
2240 static void
2241 udp_icmp_error(queue_t *q, mblk_t *mp)
2242 {
2243 	icmph_t *icmph;
2244 	ipha_t	*ipha;
2245 	int	iph_hdr_length;
2246 	udpha_t	*udpha;
2247 	sin_t	sin;
2248 	sin6_t	sin6;
2249 	mblk_t	*mp1;
2250 	int	error = 0;
2251 	size_t	mp_size = MBLKL(mp);
2252 	udp_t	*udp = Q_TO_UDP(q);
2253 
2254 	/*
2255 	 * Assume IP provides aligned packets - otherwise toss
2256 	 */
2257 	if (!OK_32PTR(mp->b_rptr)) {
2258 		freemsg(mp);
2259 		return;
2260 	}
2261 
2262 	/*
2263 	 * Verify that we have a complete IP header and the application has
2264 	 * asked for errors. If not, send it upstream.
2265 	 */
2266 	if (!udp->udp_dgram_errind || mp_size < sizeof (ipha_t)) {
2267 noticmpv4:
2268 		putnext(UDP_RD(q), mp);
2269 		return;
2270 	}
2271 
2272 	ipha = (ipha_t *)mp->b_rptr;
2273 	/*
2274 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
2275 	 * upstream. ICMPv6  is handled in udp_icmp_error_ipv6.
2276 	 */
2277 	switch (IPH_HDR_VERSION(ipha)) {
2278 	case IPV6_VERSION:
2279 		udp_icmp_error_ipv6(q, mp);
2280 		return;
2281 	case IPV4_VERSION:
2282 		break;
2283 	default:
2284 		goto noticmpv4;
2285 	}
2286 
2287 	/* Skip past the outer IP and ICMP headers */
2288 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2289 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2290 	/*
2291 	 * If we don't have the correct outer IP header length or if the ULP
2292 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
2293 	 * send the packet upstream.
2294 	 */
2295 	if (iph_hdr_length < sizeof (ipha_t) ||
2296 	    ipha->ipha_protocol != IPPROTO_ICMP ||
2297 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
2298 		goto noticmpv4;
2299 	}
2300 	ipha = (ipha_t *)&icmph[1];
2301 
2302 	/* Skip past the inner IP and find the ULP header */
2303 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
2304 	udpha = (udpha_t *)((char *)ipha + iph_hdr_length);
2305 	/*
2306 	 * If we don't have the correct inner IP header length or if the ULP
2307 	 * is not IPPROTO_UDP or if we don't have at least ICMP_MIN_UDP_HDR
2308 	 * bytes of UDP header, send it upstream.
2309 	 */
2310 	if (iph_hdr_length < sizeof (ipha_t) ||
2311 	    ipha->ipha_protocol != IPPROTO_UDP ||
2312 	    (uchar_t *)udpha + ICMP_MIN_UDP_HDR > mp->b_wptr) {
2313 		goto noticmpv4;
2314 	}
2315 
2316 	switch (icmph->icmph_type) {
2317 	case ICMP_DEST_UNREACHABLE:
2318 		switch (icmph->icmph_code) {
2319 		case ICMP_FRAGMENTATION_NEEDED:
2320 			/*
2321 			 * IP has already adjusted the path MTU.
2322 			 * XXX Somehow pass MTU indication to application?
2323 			 */
2324 			break;
2325 		case ICMP_PORT_UNREACHABLE:
2326 		case ICMP_PROTOCOL_UNREACHABLE:
2327 			error = ECONNREFUSED;
2328 			break;
2329 		default:
2330 			/* Transient errors */
2331 			break;
2332 		}
2333 		break;
2334 	default:
2335 		/* Transient errors */
2336 		break;
2337 	}
2338 	if (error == 0) {
2339 		freemsg(mp);
2340 		return;
2341 	}
2342 
2343 	switch (udp->udp_family) {
2344 	case AF_INET:
2345 		sin = sin_null;
2346 		sin.sin_family = AF_INET;
2347 		sin.sin_addr.s_addr = ipha->ipha_dst;
2348 		sin.sin_port = udpha->uha_dst_port;
2349 		mp1 = mi_tpi_uderror_ind((char *)&sin, sizeof (sin_t), NULL, 0,
2350 		    error);
2351 		break;
2352 	case AF_INET6:
2353 		sin6 = sin6_null;
2354 		sin6.sin6_family = AF_INET6;
2355 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &sin6.sin6_addr);
2356 		sin6.sin6_port = udpha->uha_dst_port;
2357 
2358 		mp1 = mi_tpi_uderror_ind((char *)&sin6, sizeof (sin6_t),
2359 		    NULL, 0, error);
2360 		break;
2361 	}
2362 	if (mp1)
2363 		putnext(UDP_RD(q), mp1);
2364 	freemsg(mp);
2365 }
2366 
2367 /*
2368  * udp_icmp_error_ipv6 is called by udp_icmp_error to process ICMP for IPv6.
2369  * Generates the appropriate T_UDERROR_IND for permanent (non-transient) errors.
2370  * Assumes that IP has pulled up all the extension headers as well as the
2371  * ICMPv6 header.
2372  * An M_CTL could potentially come here from some other module (i.e. if UDP
2373  * is pushed on some module other than IP). Thus, if we find that the M_CTL
2374  * does not have enough ICMP information , following STREAMS conventions,
2375  * we send it upstream assuming it is an M_CTL we don't understand. The reason
2376  * it might get here is if the non-ICMP M_CTL accidently has 6 in the version
2377  * field (when cast to ipha_t in udp_icmp_error).
2378  */
2379 static void
2380 udp_icmp_error_ipv6(queue_t *q, mblk_t *mp)
2381 {
2382 	icmp6_t		*icmp6;
2383 	ip6_t		*ip6h, *outer_ip6h;
2384 	uint16_t	hdr_length;
2385 	uint8_t		*nexthdrp;
2386 	udpha_t		*udpha;
2387 	sin6_t		sin6;
2388 	mblk_t		*mp1;
2389 	int		error = 0;
2390 	size_t		mp_size = MBLKL(mp);
2391 	udp_t		*udp = Q_TO_UDP(q);
2392 
2393 	/*
2394 	 * Verify that we have a complete IP header. If not, send it upstream.
2395 	 */
2396 	if (mp_size < sizeof (ip6_t)) {
2397 noticmpv6:
2398 		putnext(UDP_RD(q), mp);
2399 		return;
2400 	}
2401 
2402 	outer_ip6h = (ip6_t *)mp->b_rptr;
2403 	/*
2404 	 * Verify this is an ICMPV6 packet, else send it upstream
2405 	 */
2406 	if (outer_ip6h->ip6_nxt == IPPROTO_ICMPV6) {
2407 		hdr_length = IPV6_HDR_LEN;
2408 	} else if (!ip_hdr_length_nexthdr_v6(mp, outer_ip6h, &hdr_length,
2409 	    &nexthdrp) ||
2410 	    *nexthdrp != IPPROTO_ICMPV6) {
2411 		goto noticmpv6;
2412 	}
2413 	icmp6 = (icmp6_t *)&mp->b_rptr[hdr_length];
2414 	ip6h = (ip6_t *)&icmp6[1];
2415 	/*
2416 	 * Verify we have a complete ICMP and inner IP header.
2417 	 */
2418 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
2419 		goto noticmpv6;
2420 
2421 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &hdr_length, &nexthdrp))
2422 		goto noticmpv6;
2423 	udpha = (udpha_t *)((char *)ip6h + hdr_length);
2424 	/*
2425 	 * Validate inner header. If the ULP is not IPPROTO_UDP or if we don't
2426 	 * have at least ICMP_MIN_UDP_HDR bytes of  UDP header send the
2427 	 * packet upstream.
2428 	 */
2429 	if ((*nexthdrp != IPPROTO_UDP) ||
2430 	    ((uchar_t *)udpha + ICMP_MIN_UDP_HDR) > mp->b_wptr) {
2431 		goto noticmpv6;
2432 	}
2433 
2434 	switch (icmp6->icmp6_type) {
2435 	case ICMP6_DST_UNREACH:
2436 		switch (icmp6->icmp6_code) {
2437 		case ICMP6_DST_UNREACH_NOPORT:
2438 			error = ECONNREFUSED;
2439 			break;
2440 		case ICMP6_DST_UNREACH_ADMIN:
2441 		case ICMP6_DST_UNREACH_NOROUTE:
2442 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
2443 		case ICMP6_DST_UNREACH_ADDR:
2444 			/* Transient errors */
2445 			break;
2446 		default:
2447 			break;
2448 		}
2449 		break;
2450 	case ICMP6_PACKET_TOO_BIG: {
2451 		struct T_unitdata_ind	*tudi;
2452 		struct T_opthdr		*toh;
2453 		size_t			udi_size;
2454 		mblk_t			*newmp;
2455 		t_scalar_t		opt_length = sizeof (struct T_opthdr) +
2456 		    sizeof (struct ip6_mtuinfo);
2457 		sin6_t			*sin6;
2458 		struct ip6_mtuinfo	*mtuinfo;
2459 
2460 		/*
2461 		 * If the application has requested to receive path mtu
2462 		 * information, send up an empty message containing an
2463 		 * IPV6_PATHMTU ancillary data item.
2464 		 */
2465 		if (!udp->udp_ipv6_recvpathmtu)
2466 			break;
2467 
2468 		udi_size = sizeof (struct T_unitdata_ind) + sizeof (sin6_t) +
2469 		    opt_length;
2470 		if ((newmp = allocb(udi_size, BPRI_MED)) == NULL) {
2471 			BUMP_MIB(&udp_mib, udpInErrors);
2472 			break;
2473 		}
2474 
2475 		/*
2476 		 * newmp->b_cont is left to NULL on purpose.  This is an
2477 		 * empty message containing only ancillary data.
2478 		 */
2479 		newmp->b_datap->db_type = M_PROTO;
2480 		tudi = (struct T_unitdata_ind *)newmp->b_rptr;
2481 		newmp->b_wptr = (uchar_t *)tudi + udi_size;
2482 		tudi->PRIM_type = T_UNITDATA_IND;
2483 		tudi->SRC_length = sizeof (sin6_t);
2484 		tudi->SRC_offset = sizeof (struct T_unitdata_ind);
2485 		tudi->OPT_offset = tudi->SRC_offset + sizeof (sin6_t);
2486 		tudi->OPT_length = opt_length;
2487 
2488 		sin6 = (sin6_t *)&tudi[1];
2489 		bzero(sin6, sizeof (sin6_t));
2490 		sin6->sin6_family = AF_INET6;
2491 		sin6->sin6_addr = udp->udp_v6dst;
2492 
2493 		toh = (struct T_opthdr *)&sin6[1];
2494 		toh->level = IPPROTO_IPV6;
2495 		toh->name = IPV6_PATHMTU;
2496 		toh->len = opt_length;
2497 		toh->status = 0;
2498 
2499 		mtuinfo = (struct ip6_mtuinfo *)&toh[1];
2500 		bzero(mtuinfo, sizeof (struct ip6_mtuinfo));
2501 		mtuinfo->ip6m_addr.sin6_family = AF_INET6;
2502 		mtuinfo->ip6m_addr.sin6_addr = ip6h->ip6_dst;
2503 		mtuinfo->ip6m_mtu = icmp6->icmp6_mtu;
2504 		/*
2505 		 * We've consumed everything we need from the original
2506 		 * message.  Free it, then send our empty message.
2507 		 */
2508 		freemsg(mp);
2509 		putnext(UDP_RD(q), newmp);
2510 		return;
2511 	}
2512 	case ICMP6_TIME_EXCEEDED:
2513 		/* Transient errors */
2514 		break;
2515 	case ICMP6_PARAM_PROB:
2516 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
2517 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
2518 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
2519 		    (uchar_t *)nexthdrp) {
2520 			error = ECONNREFUSED;
2521 			break;
2522 		}
2523 		break;
2524 	}
2525 	if (error == 0) {
2526 		freemsg(mp);
2527 		return;
2528 	}
2529 
2530 	sin6 = sin6_null;
2531 	sin6.sin6_family = AF_INET6;
2532 	sin6.sin6_addr = ip6h->ip6_dst;
2533 	sin6.sin6_port = udpha->uha_dst_port;
2534 	sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
2535 
2536 	mp1 = mi_tpi_uderror_ind((char *)&sin6, sizeof (sin6_t), NULL, 0,
2537 	    error);
2538 	if (mp1)
2539 		putnext(UDP_RD(q), mp1);
2540 	freemsg(mp);
2541 }
2542 
2543 /*
2544  * This routine responds to T_ADDR_REQ messages.  It is called by udp_wput.
2545  * The local address is filled in if endpoint is bound. The remote address
2546  * is filled in if remote address has been precified ("connected endpoint")
2547  * (The concept of connected CLTS sockets is alien to published TPI
2548  *  but we support it anyway).
2549  */
2550 static void
2551 udp_addr_req(queue_t *q, mblk_t *mp)
2552 {
2553 	sin_t	*sin;
2554 	sin6_t	*sin6;
2555 	mblk_t	*ackmp;
2556 	struct T_addr_ack *taa;
2557 	udp_t	*udp = Q_TO_UDP(q);
2558 
2559 	/* Make it large enough for worst case */
2560 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
2561 	    2 * sizeof (sin6_t), 1);
2562 	if (ackmp == NULL) {
2563 		udp_err_ack(q, mp, TSYSERR, ENOMEM);
2564 		return;
2565 	}
2566 	taa = (struct T_addr_ack *)ackmp->b_rptr;
2567 
2568 	bzero(taa, sizeof (struct T_addr_ack));
2569 	ackmp->b_wptr = (uchar_t *)&taa[1];
2570 
2571 	taa->PRIM_type = T_ADDR_ACK;
2572 	ackmp->b_datap->db_type = M_PCPROTO;
2573 	/*
2574 	 * Note: Following code assumes 32 bit alignment of basic
2575 	 * data structures like sin_t and struct T_addr_ack.
2576 	 */
2577 	if (udp->udp_state != TS_UNBND) {
2578 		/*
2579 		 * Fill in local address first
2580 		 */
2581 		taa->LOCADDR_offset = sizeof (*taa);
2582 		if (udp->udp_family == AF_INET) {
2583 			taa->LOCADDR_length = sizeof (sin_t);
2584 			sin = (sin_t *)&taa[1];
2585 			/* Fill zeroes and then initialize non-zero fields */
2586 			*sin = sin_null;
2587 			sin->sin_family = AF_INET;
2588 			if (!IN6_IS_ADDR_V4MAPPED_ANY(&udp->udp_v6src) &&
2589 			    !IN6_IS_ADDR_UNSPECIFIED(&udp->udp_v6src)) {
2590 				IN6_V4MAPPED_TO_IPADDR(&udp->udp_v6src,
2591 				    sin->sin_addr.s_addr);
2592 			} else {
2593 				/*
2594 				 * INADDR_ANY
2595 				 * udp_v6src is not set, we might be bound to
2596 				 * broadcast/multicast. Use udp_bound_v6src as
2597 				 * local address instead (that could
2598 				 * also still be INADDR_ANY)
2599 				 */
2600 				IN6_V4MAPPED_TO_IPADDR(&udp->udp_bound_v6src,
2601 				    sin->sin_addr.s_addr);
2602 			}
2603 			sin->sin_port = udp->udp_port;
2604 			ackmp->b_wptr = (uchar_t *)&sin[1];
2605 			if (udp->udp_state == TS_DATA_XFER) {
2606 				/*
2607 				 * connected, fill remote address too
2608 				 */
2609 				taa->REMADDR_length = sizeof (sin_t);
2610 				/* assumed 32-bit alignment */
2611 				taa->REMADDR_offset = taa->LOCADDR_offset +
2612 				    taa->LOCADDR_length;
2613 
2614 				sin = (sin_t *)(ackmp->b_rptr +
2615 				    taa->REMADDR_offset);
2616 				/* initialize */
2617 				*sin = sin_null;
2618 				sin->sin_family = AF_INET;
2619 				sin->sin_addr.s_addr =
2620 				    V4_PART_OF_V6(udp->udp_v6dst);
2621 				sin->sin_port = udp->udp_dstport;
2622 				ackmp->b_wptr = (uchar_t *)&sin[1];
2623 			}
2624 		} else {
2625 			taa->LOCADDR_length = sizeof (sin6_t);
2626 			sin6 = (sin6_t *)&taa[1];
2627 			/* Fill zeroes and then initialize non-zero fields */
2628 			*sin6 = sin6_null;
2629 			sin6->sin6_family = AF_INET6;
2630 			if (!IN6_IS_ADDR_UNSPECIFIED(&udp->udp_v6src)) {
2631 				sin6->sin6_addr = udp->udp_v6src;
2632 			} else {
2633 				/*
2634 				 * UNSPECIFIED
2635 				 * udp_v6src is not set, we might be bound to
2636 				 * broadcast/multicast. Use udp_bound_v6src as
2637 				 * local address instead (that could
2638 				 * also still be UNSPECIFIED)
2639 				 */
2640 				sin6->sin6_addr =
2641 				    udp->udp_bound_v6src;
2642 			}
2643 			sin6->sin6_port = udp->udp_port;
2644 			ackmp->b_wptr = (uchar_t *)&sin6[1];
2645 			if (udp->udp_state == TS_DATA_XFER) {
2646 				/*
2647 				 * connected, fill remote address too
2648 				 */
2649 				taa->REMADDR_length = sizeof (sin6_t);
2650 				/* assumed 32-bit alignment */
2651 				taa->REMADDR_offset = taa->LOCADDR_offset +
2652 				    taa->LOCADDR_length;
2653 
2654 				sin6 = (sin6_t *)(ackmp->b_rptr +
2655 				    taa->REMADDR_offset);
2656 				/* initialize */
2657 				*sin6 = sin6_null;
2658 				sin6->sin6_family = AF_INET6;
2659 				sin6->sin6_addr = udp->udp_v6dst;
2660 				sin6->sin6_port =  udp->udp_dstport;
2661 				ackmp->b_wptr = (uchar_t *)&sin6[1];
2662 			}
2663 			ackmp->b_wptr = (uchar_t *)&sin6[1];
2664 		}
2665 	}
2666 	ASSERT(ackmp->b_wptr <= ackmp->b_datap->db_lim);
2667 	putnext(UDP_RD(q), ackmp);
2668 }
2669 
2670 static void
2671 udp_copy_info(struct T_info_ack *tap, udp_t *udp)
2672 {
2673 	if (udp->udp_family == AF_INET) {
2674 		*tap = udp_g_t_info_ack_ipv4;
2675 	} else {
2676 		*tap = udp_g_t_info_ack_ipv6;
2677 	}
2678 	tap->CURRENT_state = udp->udp_state;
2679 	tap->OPT_size = udp_max_optsize;
2680 }
2681 
2682 /*
2683  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
2684  * udp_wput.  Much of the T_CAPABILITY_ACK information is copied from
2685  * udp_g_t_info_ack.  The current state of the stream is copied from
2686  * udp_state.
2687  */
2688 static void
2689 udp_capability_req(queue_t *q, mblk_t *mp)
2690 {
2691 	t_uscalar_t		cap_bits1;
2692 	struct T_capability_ack	*tcap;
2693 	udp_t	*udp = Q_TO_UDP(q);
2694 
2695 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
2696 
2697 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
2698 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
2699 	if (!mp)
2700 		return;
2701 
2702 	tcap = (struct T_capability_ack *)mp->b_rptr;
2703 	tcap->CAP_bits1 = 0;
2704 
2705 	if (cap_bits1 & TC1_INFO) {
2706 		udp_copy_info(&tcap->INFO_ack, udp);
2707 		tcap->CAP_bits1 |= TC1_INFO;
2708 	}
2709 
2710 	putnext(UDP_RD(q), mp);
2711 }
2712 
2713 /*
2714  * This routine responds to T_INFO_REQ messages.  It is called by udp_wput.
2715  * Most of the T_INFO_ACK information is copied from udp_g_t_info_ack.
2716  * The current state of the stream is copied from udp_state.
2717  */
2718 static void
2719 udp_info_req(queue_t *q, mblk_t *mp)
2720 {
2721 	udp_t *udp = Q_TO_UDP(q);
2722 
2723 	/* Create a T_INFO_ACK message. */
2724 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
2725 	    T_INFO_ACK);
2726 	if (!mp)
2727 		return;
2728 	udp_copy_info((struct T_info_ack *)mp->b_rptr, udp);
2729 	putnext(UDP_RD(q), mp);
2730 }
2731 
2732 /*
2733  * IP recognizes seven kinds of bind requests:
2734  *
2735  * - A zero-length address binds only to the protocol number.
2736  *
2737  * - A 4-byte address is treated as a request to
2738  * validate that the address is a valid local IPv4
2739  * address, appropriate for an application to bind to.
2740  * IP does the verification, but does not make any note
2741  * of the address at this time.
2742  *
2743  * - A 16-byte address contains is treated as a request
2744  * to validate a local IPv6 address, as the 4-byte
2745  * address case above.
2746  *
2747  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
2748  * use it for the inbound fanout of packets.
2749  *
2750  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
2751  * use it for the inbound fanout of packets.
2752  *
2753  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
2754  * information consisting of local and remote addresses
2755  * and ports.  In this case, the addresses are both
2756  * validated as appropriate for this operation, and, if
2757  * so, the information is retained for use in the
2758  * inbound fanout.
2759  *
2760  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
2761  * fanout information, like the 12-byte case above.
2762  *
2763  * IP will also fill in the IRE request mblk with information
2764  * regarding our peer.  In all cases, we notify IP of our protocol
2765  * type by appending a single protocol byte to the bind request.
2766  */
2767 static mblk_t *
2768 udp_ip_bind_mp(udp_t *udp, t_scalar_t bind_prim, t_scalar_t addr_length)
2769 {
2770 	char	*cp;
2771 	mblk_t	*mp;
2772 	struct T_bind_req *tbr;
2773 	ipa_conn_t	*ac;
2774 	ipa6_conn_t	*ac6;
2775 	sin_t		*sin;
2776 	sin6_t		*sin6;
2777 
2778 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
2779 
2780 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
2781 	if (!mp)
2782 		return (mp);
2783 	mp->b_datap->db_type = M_PROTO;
2784 	tbr = (struct T_bind_req *)mp->b_rptr;
2785 	tbr->PRIM_type = bind_prim;
2786 	tbr->ADDR_offset = sizeof (*tbr);
2787 	tbr->CONIND_number = 0;
2788 	tbr->ADDR_length = addr_length;
2789 	cp = (char *)&tbr[1];
2790 	switch (addr_length) {
2791 	case sizeof (ipa_conn_t):
2792 		ASSERT(udp->udp_family == AF_INET);
2793 		/* Append a request for an IRE */
2794 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
2795 		if (!mp->b_cont) {
2796 			freemsg(mp);
2797 			return (NULL);
2798 		}
2799 		mp->b_cont->b_wptr += sizeof (ire_t);
2800 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
2801 
2802 		/* cp known to be 32 bit aligned */
2803 		ac = (ipa_conn_t *)cp;
2804 		ac->ac_laddr = V4_PART_OF_V6(udp->udp_v6src);
2805 		ac->ac_faddr = V4_PART_OF_V6(udp->udp_v6dst);
2806 		ac->ac_fport = udp->udp_dstport;
2807 		ac->ac_lport = udp->udp_port;
2808 		break;
2809 
2810 	case sizeof (ipa6_conn_t):
2811 		ASSERT(udp->udp_family == AF_INET6);
2812 		/* Append a request for an IRE */
2813 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
2814 		if (!mp->b_cont) {
2815 			freemsg(mp);
2816 			return (NULL);
2817 		}
2818 		mp->b_cont->b_wptr += sizeof (ire_t);
2819 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
2820 
2821 		/* cp known to be 32 bit aligned */
2822 		ac6 = (ipa6_conn_t *)cp;
2823 		ac6->ac6_laddr = udp->udp_v6src;
2824 		ac6->ac6_faddr = udp->udp_v6dst;
2825 		ac6->ac6_fport = udp->udp_dstport;
2826 		ac6->ac6_lport = udp->udp_port;
2827 		break;
2828 
2829 	case sizeof (sin_t):
2830 		ASSERT(udp->udp_family == AF_INET);
2831 		/* Append a request for an IRE */
2832 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
2833 		if (!mp->b_cont) {
2834 			freemsg(mp);
2835 			return (NULL);
2836 		}
2837 		mp->b_cont->b_wptr += sizeof (ire_t);
2838 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
2839 
2840 		sin = (sin_t *)cp;
2841 		*sin = sin_null;
2842 		sin->sin_family = AF_INET;
2843 		sin->sin_addr.s_addr = V4_PART_OF_V6(udp->udp_bound_v6src);
2844 		sin->sin_port = udp->udp_port;
2845 		break;
2846 
2847 	case sizeof (sin6_t):
2848 		ASSERT(udp->udp_family == AF_INET6);
2849 		/* Append a request for an IRE */
2850 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
2851 		if (!mp->b_cont) {
2852 			freemsg(mp);
2853 			return (NULL);
2854 		}
2855 		mp->b_cont->b_wptr += sizeof (ire_t);
2856 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
2857 
2858 		sin6 = (sin6_t *)cp;
2859 		*sin6 = sin6_null;
2860 		sin6->sin6_family = AF_INET6;
2861 		sin6->sin6_addr = udp->udp_bound_v6src;
2862 		sin6->sin6_port = udp->udp_port;
2863 		break;
2864 	}
2865 	/* Add protocol number to end */
2866 	cp[addr_length] = (char)IPPROTO_UDP;
2867 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
2868 	return (mp);
2869 }
2870 
2871 /*
2872  * This is the open routine for udp.  It allocates a udp_t structure for
2873  * the stream and, on the first open of the module, creates an ND table.
2874  */
2875 /* ARGSUSED */
2876 static int
2877 udp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
2878 {
2879 	int	err;
2880 	udp_t	*udp;
2881 	conn_t *connp;
2882 	zoneid_t zoneid = getzoneid();
2883 	queue_t	*ip_wq;
2884 	char	*name;
2885 
2886 	TRACE_1(TR_FAC_UDP, TR_UDP_OPEN, "udp_open: q %p", q);
2887 
2888 	/* If the stream is already open, return immediately. */
2889 	if (q->q_ptr != NULL)
2890 		return (0);
2891 
2892 	/* If this is not a push of udp as a module, fail. */
2893 	if (sflag != MODOPEN)
2894 		return (EINVAL);
2895 
2896 	q->q_hiwat = udp_recv_hiwat;
2897 	WR(q)->q_hiwat = udp_xmit_hiwat;
2898 	WR(q)->q_lowat = udp_xmit_lowat;
2899 
2900 	/* Insert ourselves in the stream since we're about to walk q_next */
2901 	qprocson(q);
2902 
2903 	udp = kmem_cache_alloc(udp_cache, KM_SLEEP);
2904 	bzero(udp, sizeof (*udp));
2905 
2906 	/*
2907 	 * UDP is supported only as a module and it has to be pushed directly
2908 	 * above the device instance of IP. If UDP is pushed anywhere else
2909 	 * on a stream, it will support just T_SVR4_OPTMGMT_REQ for the
2910 	 * sake of MIB browsers and fail everything else.
2911 	 */
2912 	ip_wq = WR(q)->q_next;
2913 	if (ip_wq->q_next != NULL ||
2914 	    (name = ip_wq->q_qinfo->qi_minfo->mi_idname) == NULL ||
2915 	    strcmp(name, IP_MOD_NAME) != 0 ||
2916 	    ip_wq->q_qinfo->qi_minfo->mi_idnum != IP_MOD_ID) {
2917 		/* Support just SNMP for MIB browsers */
2918 		connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
2919 		connp->conn_rq = q;
2920 		connp->conn_wq = WR(q);
2921 		connp->conn_flags |= IPCL_UDPMOD;
2922 		connp->conn_cred = credp;
2923 		connp->conn_zoneid = zoneid;
2924 		connp->conn_udp = udp;
2925 		udp->udp_connp = connp;
2926 		q->q_ptr = WR(q)->q_ptr = connp;
2927 		crhold(credp);
2928 		q->q_qinfo = &udp_snmp_rinit;
2929 		WR(q)->q_qinfo = &udp_snmp_winit;
2930 		return (0);
2931 	}
2932 
2933 	/*
2934 	 * Initialize the udp_t structure for this stream.
2935 	 */
2936 	q = RD(ip_wq);
2937 	connp = Q_TO_CONN(q);
2938 	mutex_enter(&connp->conn_lock);
2939 	connp->conn_proto = IPPROTO_UDP;
2940 	connp->conn_flags |= IPCL_UDP;
2941 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
2942 	connp->conn_udp = udp;
2943 
2944 	/* Set the initial state of the stream and the privilege status. */
2945 	udp->udp_connp = connp;
2946 	udp->udp_state = TS_UNBND;
2947 	udp->udp_mode = UDP_MT_HOT;
2948 	if (getmajor(*devp) == (major_t)UDP6_MAJ) {
2949 		udp->udp_family = AF_INET6;
2950 		udp->udp_ipversion = IPV6_VERSION;
2951 		udp->udp_max_hdr_len = IPV6_HDR_LEN + UDPH_SIZE;
2952 		udp->udp_ttl = udp_ipv6_hoplimit;
2953 		connp->conn_af_isv6 = B_TRUE;
2954 		connp->conn_flags |= IPCL_ISV6;
2955 	} else {
2956 		udp->udp_family = AF_INET;
2957 		udp->udp_ipversion = IPV4_VERSION;
2958 		udp->udp_max_hdr_len = IP_SIMPLE_HDR_LENGTH + UDPH_SIZE;
2959 		udp->udp_ttl = udp_ipv4_ttl;
2960 		connp->conn_af_isv6 = B_FALSE;
2961 		connp->conn_flags &= ~IPCL_ISV6;
2962 	}
2963 
2964 	udp->udp_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2965 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
2966 	connp->conn_zoneid = zoneid;
2967 
2968 	/*
2969 	 * If the caller has the process-wide flag set, then default to MAC
2970 	 * exempt mode.  This allows read-down to unlabeled hosts.
2971 	 */
2972 	if (getpflags(NET_MAC_AWARE, credp) != 0)
2973 		udp->udp_mac_exempt = B_TRUE;
2974 
2975 	if (connp->conn_flags & IPCL_SOCKET) {
2976 		udp->udp_issocket = B_TRUE;
2977 		udp->udp_direct_sockfs = B_TRUE;
2978 	}
2979 
2980 	connp->conn_ulp_labeled = is_system_labeled();
2981 
2982 	mutex_exit(&connp->conn_lock);
2983 
2984 	/*
2985 	 * The transmit hiwat/lowat is only looked at on IP's queue.
2986 	 * Store in q_hiwat in order to return on SO_SNDBUF/SO_RCVBUF
2987 	 * getsockopts.
2988 	 */
2989 	q->q_hiwat = udp_recv_hiwat;
2990 	WR(q)->q_hiwat = udp_xmit_hiwat;
2991 	WR(q)->q_lowat = udp_xmit_lowat;
2992 
2993 	if (udp->udp_family == AF_INET6) {
2994 		/* Build initial header template for transmit */
2995 		if ((err = udp_build_hdrs(q, udp)) != 0) {
2996 error:
2997 			qprocsoff(UDP_RD(q));
2998 			udp->udp_connp = NULL;
2999 			connp->conn_udp = NULL;
3000 			kmem_cache_free(udp_cache, udp);
3001 			return (err);
3002 		}
3003 	}
3004 
3005 	/* Set the Stream head write offset and high watermark. */
3006 	(void) mi_set_sth_wroff(UDP_RD(q),
3007 	    udp->udp_max_hdr_len + udp_wroff_extra);
3008 	(void) mi_set_sth_hiwat(UDP_RD(q), udp_set_rcv_hiwat(udp, q->q_hiwat));
3009 
3010 	WR(UDP_RD(q))->q_qinfo = &udp_winit;
3011 
3012 	return (0);
3013 }
3014 
3015 /*
3016  * Which UDP options OK to set through T_UNITDATA_REQ...
3017  */
3018 /* ARGSUSED */
3019 static boolean_t
3020 udp_opt_allow_udr_set(t_scalar_t level, t_scalar_t name)
3021 {
3022 	return (B_TRUE);
3023 }
3024 
3025 /*
3026  * This routine gets default values of certain options whose default
3027  * values are maintained by protcol specific code
3028  */
3029 /* ARGSUSED */
3030 int
3031 udp_opt_default(queue_t	*q, t_scalar_t level, t_scalar_t name, uchar_t *ptr)
3032 {
3033 	int *i1 = (int *)ptr;
3034 
3035 	switch (level) {
3036 	case IPPROTO_IP:
3037 		switch (name) {
3038 		case IP_MULTICAST_TTL:
3039 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
3040 			return (sizeof (uchar_t));
3041 		case IP_MULTICAST_LOOP:
3042 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
3043 			return (sizeof (uchar_t));
3044 		}
3045 		break;
3046 	case IPPROTO_IPV6:
3047 		switch (name) {
3048 		case IPV6_MULTICAST_HOPS:
3049 			*i1 = IP_DEFAULT_MULTICAST_TTL;
3050 			return (sizeof (int));
3051 		case IPV6_MULTICAST_LOOP:
3052 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
3053 			return (sizeof (int));
3054 		case IPV6_UNICAST_HOPS:
3055 			*i1 = udp_ipv6_hoplimit;
3056 			return (sizeof (int));
3057 		}
3058 		break;
3059 	}
3060 	return (-1);
3061 }
3062 
3063 /*
3064  * This routine retrieves the current status of socket options
3065  * and expects the caller to pass in the queue pointer of the
3066  * upper instance.  It returns the size of the option retrieved.
3067  */
3068 int
3069 udp_opt_get(queue_t *q, t_scalar_t level, t_scalar_t name, uchar_t *ptr)
3070 {
3071 	int	*i1 = (int *)ptr;
3072 	conn_t	*connp;
3073 	udp_t	*udp;
3074 	ip6_pkt_t *ipp;
3075 	int	len;
3076 
3077 	q = UDP_WR(q);
3078 	connp = Q_TO_CONN(q);
3079 	udp = connp->conn_udp;
3080 	ipp = &udp->udp_sticky_ipp;
3081 
3082 	switch (level) {
3083 	case SOL_SOCKET:
3084 		switch (name) {
3085 		case SO_DEBUG:
3086 			*i1 = udp->udp_debug;
3087 			break;	/* goto sizeof (int) option return */
3088 		case SO_REUSEADDR:
3089 			*i1 = udp->udp_reuseaddr;
3090 			break;	/* goto sizeof (int) option return */
3091 		case SO_TYPE:
3092 			*i1 = SOCK_DGRAM;
3093 			break;	/* goto sizeof (int) option return */
3094 
3095 		/*
3096 		 * The following three items are available here,
3097 		 * but are only meaningful to IP.
3098 		 */
3099 		case SO_DONTROUTE:
3100 			*i1 = udp->udp_dontroute;
3101 			break;	/* goto sizeof (int) option return */
3102 		case SO_USELOOPBACK:
3103 			*i1 = udp->udp_useloopback;
3104 			break;	/* goto sizeof (int) option return */
3105 		case SO_BROADCAST:
3106 			*i1 = udp->udp_broadcast;
3107 			break;	/* goto sizeof (int) option return */
3108 
3109 		case SO_SNDBUF:
3110 			*i1 = q->q_hiwat;
3111 			break;	/* goto sizeof (int) option return */
3112 		case SO_RCVBUF:
3113 			*i1 = RD(q)->q_hiwat;
3114 			break;	/* goto sizeof (int) option return */
3115 		case SO_DGRAM_ERRIND:
3116 			*i1 = udp->udp_dgram_errind;
3117 			break;	/* goto sizeof (int) option return */
3118 		case SO_RECVUCRED:
3119 			*i1 = udp->udp_recvucred;
3120 			break;	/* goto sizeof (int) option return */
3121 		case SO_TIMESTAMP:
3122 			*i1 = udp->udp_timestamp;
3123 			break;	/* goto sizeof (int) option return */
3124 		case SO_ANON_MLP:
3125 			*i1 = udp->udp_anon_mlp;
3126 			break;	/* goto sizeof (int) option return */
3127 		case SO_MAC_EXEMPT:
3128 			*i1 = udp->udp_mac_exempt;
3129 			break;	/* goto sizeof (int) option return */
3130 		case SO_ALLZONES:
3131 			*i1 = connp->conn_allzones;
3132 			break;	/* goto sizeof (int) option return */
3133 		case SO_EXCLBIND:
3134 			*i1 = udp->udp_exclbind ? SO_EXCLBIND : 0;
3135 			break;
3136 		default:
3137 			return (-1);
3138 		}
3139 		break;
3140 	case IPPROTO_IP:
3141 		if (udp->udp_family != AF_INET)
3142 			return (-1);
3143 		switch (name) {
3144 		case IP_OPTIONS:
3145 		case T_IP_OPTIONS:
3146 			len = udp->udp_ip_rcv_options_len - udp->udp_label_len;
3147 			if (len > 0) {
3148 				bcopy(udp->udp_ip_rcv_options +
3149 				    udp->udp_label_len, ptr, len);
3150 			}
3151 			return (len);
3152 		case IP_TOS:
3153 		case T_IP_TOS:
3154 			*i1 = (int)udp->udp_type_of_service;
3155 			break;	/* goto sizeof (int) option return */
3156 		case IP_TTL:
3157 			*i1 = (int)udp->udp_ttl;
3158 			break;	/* goto sizeof (int) option return */
3159 		case IP_NEXTHOP:
3160 			/* Handled at IP level */
3161 			return (-EINVAL);
3162 		case IP_MULTICAST_IF:
3163 			/* 0 address if not set */
3164 			*(ipaddr_t *)ptr = udp->udp_multicast_if_addr;
3165 			return (sizeof (ipaddr_t));
3166 		case IP_MULTICAST_TTL:
3167 			*(uchar_t *)ptr = udp->udp_multicast_ttl;
3168 			return (sizeof (uchar_t));
3169 		case IP_MULTICAST_LOOP:
3170 			*ptr = connp->conn_multicast_loop;
3171 			return (sizeof (uint8_t));
3172 		case IP_RECVOPTS:
3173 			*i1 = udp->udp_recvopts;
3174 			break;	/* goto sizeof (int) option return */
3175 		case IP_RECVDSTADDR:
3176 			*i1 = udp->udp_recvdstaddr;
3177 			break;	/* goto sizeof (int) option return */
3178 		case IP_RECVIF:
3179 			*i1 = udp->udp_recvif;
3180 			break;	/* goto sizeof (int) option return */
3181 		case IP_RECVSLLA:
3182 			*i1 = udp->udp_recvslla;
3183 			break;	/* goto sizeof (int) option return */
3184 		case IP_RECVTTL:
3185 			*i1 = udp->udp_recvttl;
3186 			break;	/* goto sizeof (int) option return */
3187 		case IP_ADD_MEMBERSHIP:
3188 		case IP_DROP_MEMBERSHIP:
3189 		case IP_BLOCK_SOURCE:
3190 		case IP_UNBLOCK_SOURCE:
3191 		case IP_ADD_SOURCE_MEMBERSHIP:
3192 		case IP_DROP_SOURCE_MEMBERSHIP:
3193 		case MCAST_JOIN_GROUP:
3194 		case MCAST_LEAVE_GROUP:
3195 		case MCAST_BLOCK_SOURCE:
3196 		case MCAST_UNBLOCK_SOURCE:
3197 		case MCAST_JOIN_SOURCE_GROUP:
3198 		case MCAST_LEAVE_SOURCE_GROUP:
3199 		case IP_DONTFAILOVER_IF:
3200 			/* cannot "get" the value for these */
3201 			return (-1);
3202 		case IP_BOUND_IF:
3203 			/* Zero if not set */
3204 			*i1 = udp->udp_bound_if;
3205 			break;	/* goto sizeof (int) option return */
3206 		case IP_UNSPEC_SRC:
3207 			*i1 = udp->udp_unspec_source;
3208 			break;	/* goto sizeof (int) option return */
3209 		case IP_XMIT_IF:
3210 			*i1 = udp->udp_xmit_if;
3211 			break; /* goto sizeof (int) option return */
3212 		default:
3213 			return (-1);
3214 		}
3215 		break;
3216 	case IPPROTO_IPV6:
3217 		if (udp->udp_family != AF_INET6)
3218 			return (-1);
3219 		switch (name) {
3220 		case IPV6_UNICAST_HOPS:
3221 			*i1 = (unsigned int)udp->udp_ttl;
3222 			break;	/* goto sizeof (int) option return */
3223 		case IPV6_MULTICAST_IF:
3224 			/* 0 index if not set */
3225 			*i1 = udp->udp_multicast_if_index;
3226 			break;	/* goto sizeof (int) option return */
3227 		case IPV6_MULTICAST_HOPS:
3228 			*i1 = udp->udp_multicast_ttl;
3229 			break;	/* goto sizeof (int) option return */
3230 		case IPV6_MULTICAST_LOOP:
3231 			*i1 = connp->conn_multicast_loop;
3232 			break;	/* goto sizeof (int) option return */
3233 		case IPV6_JOIN_GROUP:
3234 		case IPV6_LEAVE_GROUP:
3235 		case MCAST_JOIN_GROUP:
3236 		case MCAST_LEAVE_GROUP:
3237 		case MCAST_BLOCK_SOURCE:
3238 		case MCAST_UNBLOCK_SOURCE:
3239 		case MCAST_JOIN_SOURCE_GROUP:
3240 		case MCAST_LEAVE_SOURCE_GROUP:
3241 			/* cannot "get" the value for these */
3242 			return (-1);
3243 		case IPV6_BOUND_IF:
3244 			/* Zero if not set */
3245 			*i1 = udp->udp_bound_if;
3246 			break;	/* goto sizeof (int) option return */
3247 		case IPV6_UNSPEC_SRC:
3248 			*i1 = udp->udp_unspec_source;
3249 			break;	/* goto sizeof (int) option return */
3250 		case IPV6_RECVPKTINFO:
3251 			*i1 = udp->udp_ipv6_recvpktinfo;
3252 			break;	/* goto sizeof (int) option return */
3253 		case IPV6_RECVTCLASS:
3254 			*i1 = udp->udp_ipv6_recvtclass;
3255 			break;	/* goto sizeof (int) option return */
3256 		case IPV6_RECVPATHMTU:
3257 			*i1 = udp->udp_ipv6_recvpathmtu;
3258 			break;	/* goto sizeof (int) option return */
3259 		case IPV6_RECVHOPLIMIT:
3260 			*i1 = udp->udp_ipv6_recvhoplimit;
3261 			break;	/* goto sizeof (int) option return */
3262 		case IPV6_RECVHOPOPTS:
3263 			*i1 = udp->udp_ipv6_recvhopopts;
3264 			break;	/* goto sizeof (int) option return */
3265 		case IPV6_RECVDSTOPTS:
3266 			*i1 = udp->udp_ipv6_recvdstopts;
3267 			break;	/* goto sizeof (int) option return */
3268 		case _OLD_IPV6_RECVDSTOPTS:
3269 			*i1 = udp->udp_old_ipv6_recvdstopts;
3270 			break;	/* goto sizeof (int) option return */
3271 		case IPV6_RECVRTHDRDSTOPTS:
3272 			*i1 = udp->udp_ipv6_recvrthdrdstopts;
3273 			break;	/* goto sizeof (int) option return */
3274 		case IPV6_RECVRTHDR:
3275 			*i1 = udp->udp_ipv6_recvrthdr;
3276 			break;	/* goto sizeof (int) option return */
3277 		case IPV6_PKTINFO: {
3278 			/* XXX assumes that caller has room for max size! */
3279 			struct in6_pktinfo *pkti;
3280 
3281 			pkti = (struct in6_pktinfo *)ptr;
3282 			if (ipp->ipp_fields & IPPF_IFINDEX)
3283 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
3284 			else
3285 				pkti->ipi6_ifindex = 0;
3286 			if (ipp->ipp_fields & IPPF_ADDR)
3287 				pkti->ipi6_addr = ipp->ipp_addr;
3288 			else
3289 				pkti->ipi6_addr = ipv6_all_zeros;
3290 			return (sizeof (struct in6_pktinfo));
3291 		}
3292 		case IPV6_TCLASS:
3293 			if (ipp->ipp_fields & IPPF_TCLASS)
3294 				*i1 = ipp->ipp_tclass;
3295 			else
3296 				*i1 = IPV6_FLOW_TCLASS(
3297 				    IPV6_DEFAULT_VERS_AND_FLOW);
3298 			break;	/* goto sizeof (int) option return */
3299 		case IPV6_NEXTHOP: {
3300 			sin6_t *sin6 = (sin6_t *)ptr;
3301 
3302 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
3303 				return (0);
3304 			*sin6 = sin6_null;
3305 			sin6->sin6_family = AF_INET6;
3306 			sin6->sin6_addr = ipp->ipp_nexthop;
3307 			return (sizeof (sin6_t));
3308 		}
3309 		case IPV6_HOPOPTS:
3310 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
3311 				return (0);
3312 			if (ipp->ipp_hopoptslen <= udp->udp_label_len_v6)
3313 				return (0);
3314 			/*
3315 			 * The cipso/label option is added by kernel.
3316 			 * User is not usually aware of this option.
3317 			 * We copy out the hbh opt after the label option.
3318 			 */
3319 			bcopy((char *)ipp->ipp_hopopts + udp->udp_label_len_v6,
3320 			    ptr, ipp->ipp_hopoptslen - udp->udp_label_len_v6);
3321 			if (udp->udp_label_len_v6 > 0) {
3322 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
3323 				ptr[1] = (ipp->ipp_hopoptslen -
3324 				    udp->udp_label_len_v6 + 7) / 8 - 1;
3325 			}
3326 			return (ipp->ipp_hopoptslen - udp->udp_label_len_v6);
3327 		case IPV6_RTHDRDSTOPTS:
3328 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
3329 				return (0);
3330 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
3331 			return (ipp->ipp_rtdstoptslen);
3332 		case IPV6_RTHDR:
3333 			if (!(ipp->ipp_fields & IPPF_RTHDR))
3334 				return (0);
3335 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
3336 			return (ipp->ipp_rthdrlen);
3337 		case IPV6_DSTOPTS:
3338 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
3339 				return (0);
3340 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
3341 			return (ipp->ipp_dstoptslen);
3342 		case IPV6_PATHMTU:
3343 			return (ip_fill_mtuinfo(&udp->udp_v6dst,
3344 				udp->udp_dstport, (struct ip6_mtuinfo *)ptr));
3345 		default:
3346 			return (-1);
3347 		}
3348 		break;
3349 	case IPPROTO_UDP:
3350 		switch (name) {
3351 		case UDP_ANONPRIVBIND:
3352 			*i1 = udp->udp_anon_priv_bind;
3353 			break;
3354 		case UDP_EXCLBIND:
3355 			*i1 = udp->udp_exclbind ? UDP_EXCLBIND : 0;
3356 			break;
3357 		case UDP_RCVHDR:
3358 			*i1 = udp->udp_rcvhdr ? 1 : 0;
3359 			break;
3360 		default:
3361 			return (-1);
3362 		}
3363 		break;
3364 	default:
3365 		return (-1);
3366 	}
3367 	return (sizeof (int));
3368 }
3369 
3370 /*
3371  * This routine sets socket options; it expects the caller
3372  * to pass in the queue pointer of the upper instance.
3373  */
3374 /* ARGSUSED */
3375 int
3376 udp_opt_set(queue_t *q, uint_t optset_context, int level,
3377     int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
3378     uchar_t *outvalp, void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
3379 {
3380 	udpattrs_t *attrs = thisdg_attrs;
3381 	int	*i1 = (int *)invalp;
3382 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
3383 	boolean_t checkonly;
3384 	int	error;
3385 	conn_t	*connp;
3386 	udp_t	*udp;
3387 	uint_t	newlen;
3388 
3389 	q = UDP_WR(q);
3390 	connp = Q_TO_CONN(q);
3391 	udp = connp->conn_udp;
3392 
3393 	switch (optset_context) {
3394 	case SETFN_OPTCOM_CHECKONLY:
3395 		checkonly = B_TRUE;
3396 		/*
3397 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
3398 		 * inlen != 0 implies value supplied and
3399 		 * 	we have to "pretend" to set it.
3400 		 * inlen == 0 implies that there is no
3401 		 * 	value part in T_CHECK request and just validation
3402 		 * done elsewhere should be enough, we just return here.
3403 		 */
3404 		if (inlen == 0) {
3405 			*outlenp = 0;
3406 			return (0);
3407 		}
3408 		break;
3409 	case SETFN_OPTCOM_NEGOTIATE:
3410 		checkonly = B_FALSE;
3411 		break;
3412 	case SETFN_UD_NEGOTIATE:
3413 	case SETFN_CONN_NEGOTIATE:
3414 		checkonly = B_FALSE;
3415 		/*
3416 		 * Negotiating local and "association-related" options
3417 		 * through T_UNITDATA_REQ.
3418 		 *
3419 		 * Following routine can filter out ones we do not
3420 		 * want to be "set" this way.
3421 		 */
3422 		if (!udp_opt_allow_udr_set(level, name)) {
3423 			*outlenp = 0;
3424 			return (EINVAL);
3425 		}
3426 		break;
3427 	default:
3428 		/*
3429 		 * We should never get here
3430 		 */
3431 		*outlenp = 0;
3432 		return (EINVAL);
3433 	}
3434 
3435 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
3436 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
3437 
3438 	/*
3439 	 * For fixed length options, no sanity check
3440 	 * of passed in length is done. It is assumed *_optcom_req()
3441 	 * routines do the right thing.
3442 	 */
3443 
3444 	switch (level) {
3445 	case SOL_SOCKET:
3446 		switch (name) {
3447 		case SO_REUSEADDR:
3448 			if (!checkonly)
3449 				udp->udp_reuseaddr = onoff;
3450 			break;
3451 		case SO_DEBUG:
3452 			if (!checkonly)
3453 				udp->udp_debug = onoff;
3454 			break;
3455 		/*
3456 		 * The following three items are available here,
3457 		 * but are only meaningful to IP.
3458 		 */
3459 		case SO_DONTROUTE:
3460 			if (!checkonly)
3461 				udp->udp_dontroute = onoff;
3462 			break;
3463 		case SO_USELOOPBACK:
3464 			if (!checkonly)
3465 				udp->udp_useloopback = onoff;
3466 			break;
3467 		case SO_BROADCAST:
3468 			if (!checkonly)
3469 				udp->udp_broadcast = onoff;
3470 			break;
3471 
3472 		case SO_SNDBUF:
3473 			if (*i1 > udp_max_buf) {
3474 				*outlenp = 0;
3475 				return (ENOBUFS);
3476 			}
3477 			if (!checkonly) {
3478 				q->q_hiwat = *i1;
3479 				WR(UDP_RD(q))->q_hiwat = *i1;
3480 			}
3481 			break;
3482 		case SO_RCVBUF:
3483 			if (*i1 > udp_max_buf) {
3484 				*outlenp = 0;
3485 				return (ENOBUFS);
3486 			}
3487 			if (!checkonly) {
3488 				RD(q)->q_hiwat = *i1;
3489 				UDP_RD(q)->q_hiwat = *i1;
3490 				(void) mi_set_sth_hiwat(UDP_RD(q),
3491 				    udp_set_rcv_hiwat(udp, *i1));
3492 			}
3493 			break;
3494 		case SO_DGRAM_ERRIND:
3495 			if (!checkonly)
3496 				udp->udp_dgram_errind = onoff;
3497 			break;
3498 		case SO_RECVUCRED:
3499 			if (!checkonly)
3500 				udp->udp_recvucred = onoff;
3501 			break;
3502 		case SO_ALLZONES:
3503 			/*
3504 			 * "soft" error (negative)
3505 			 * option not handled at this level
3506 			 * Do not modify *outlenp.
3507 			 */
3508 			return (-EINVAL);
3509 		case SO_TIMESTAMP:
3510 			if (!checkonly)
3511 				udp->udp_timestamp = onoff;
3512 			break;
3513 		case SO_ANON_MLP:
3514 			if (!checkonly)
3515 				udp->udp_anon_mlp = onoff;
3516 			break;
3517 		case SO_MAC_EXEMPT:
3518 			if (secpolicy_net_mac_aware(cr) != 0 ||
3519 			    udp->udp_state != TS_UNBND)
3520 				return (EACCES);
3521 			if (!checkonly)
3522 				udp->udp_mac_exempt = onoff;
3523 			break;
3524 		case SCM_UCRED: {
3525 			struct ucred_s *ucr;
3526 			cred_t *cr, *newcr;
3527 			ts_label_t *tsl;
3528 
3529 			/*
3530 			 * Only sockets that have proper privileges and are
3531 			 * bound to MLPs will have any other value here, so
3532 			 * this implicitly tests for privilege to set label.
3533 			 */
3534 			if (connp->conn_mlp_type == mlptSingle)
3535 				break;
3536 			ucr = (struct ucred_s *)invalp;
3537 			if (inlen != ucredsize ||
3538 			    ucr->uc_labeloff < sizeof (*ucr) ||
3539 			    ucr->uc_labeloff + sizeof (bslabel_t) > inlen)
3540 				return (EINVAL);
3541 			if (!checkonly) {
3542 				mblk_t *mb;
3543 
3544 				if (attrs == NULL ||
3545 				    (mb = attrs->udpattr_mb) == NULL)
3546 					return (EINVAL);
3547 				if ((cr = DB_CRED(mb)) == NULL)
3548 					cr = udp->udp_connp->conn_cred;
3549 				ASSERT(cr != NULL);
3550 				if ((tsl = crgetlabel(cr)) == NULL)
3551 					return (EINVAL);
3552 				newcr = copycred_from_bslabel(cr, UCLABEL(ucr),
3553 				    tsl->tsl_doi, KM_NOSLEEP);
3554 				if (newcr == NULL)
3555 					return (ENOSR);
3556 				mblk_setcred(mb, newcr);
3557 				attrs->udpattr_credset = B_TRUE;
3558 				crfree(newcr);
3559 			}
3560 			break;
3561 		}
3562 		case SO_EXCLBIND:
3563 			if (!checkonly)
3564 				udp->udp_exclbind = onoff;
3565 			break;
3566 		default:
3567 			*outlenp = 0;
3568 			return (EINVAL);
3569 		}
3570 		break;
3571 	case IPPROTO_IP:
3572 		if (udp->udp_family != AF_INET) {
3573 			*outlenp = 0;
3574 			return (ENOPROTOOPT);
3575 		}
3576 		switch (name) {
3577 		case IP_OPTIONS:
3578 		case T_IP_OPTIONS:
3579 			/* Save options for use by IP. */
3580 			newlen = inlen + udp->udp_label_len;
3581 			if ((inlen & 0x3) || newlen > IP_MAX_OPT_LENGTH) {
3582 				*outlenp = 0;
3583 				return (EINVAL);
3584 			}
3585 			if (checkonly)
3586 				break;
3587 
3588 			if (!tsol_option_set(&udp->udp_ip_snd_options,
3589 			    &udp->udp_ip_snd_options_len,
3590 			    udp->udp_label_len, invalp, inlen)) {
3591 				*outlenp = 0;
3592 				return (ENOMEM);
3593 			}
3594 
3595 			udp->udp_max_hdr_len = IP_SIMPLE_HDR_LENGTH +
3596 			    UDPH_SIZE + udp->udp_ip_snd_options_len;
3597 			(void) mi_set_sth_wroff(RD(q), udp->udp_max_hdr_len +
3598 			    udp_wroff_extra);
3599 			break;
3600 
3601 		case IP_TTL:
3602 			if (!checkonly) {
3603 				udp->udp_ttl = (uchar_t)*i1;
3604 			}
3605 			break;
3606 		case IP_TOS:
3607 		case T_IP_TOS:
3608 			if (!checkonly) {
3609 				udp->udp_type_of_service = (uchar_t)*i1;
3610 			}
3611 			break;
3612 		case IP_MULTICAST_IF: {
3613 			/*
3614 			 * TODO should check OPTMGMT reply and undo this if
3615 			 * there is an error.
3616 			 */
3617 			struct in_addr *inap = (struct in_addr *)invalp;
3618 			if (!checkonly) {
3619 				udp->udp_multicast_if_addr =
3620 				    inap->s_addr;
3621 			}
3622 			break;
3623 		}
3624 		case IP_MULTICAST_TTL:
3625 			if (!checkonly)
3626 				udp->udp_multicast_ttl = *invalp;
3627 			break;
3628 		case IP_MULTICAST_LOOP:
3629 			if (!checkonly)
3630 				connp->conn_multicast_loop = *invalp;
3631 			break;
3632 		case IP_RECVOPTS:
3633 			if (!checkonly)
3634 				udp->udp_recvopts = onoff;
3635 			break;
3636 		case IP_RECVDSTADDR:
3637 			if (!checkonly)
3638 				udp->udp_recvdstaddr = onoff;
3639 			break;
3640 		case IP_RECVIF:
3641 			if (!checkonly)
3642 				udp->udp_recvif = onoff;
3643 			break;
3644 		case IP_RECVSLLA:
3645 			if (!checkonly)
3646 				udp->udp_recvslla = onoff;
3647 			break;
3648 		case IP_RECVTTL:
3649 			if (!checkonly)
3650 				udp->udp_recvttl = onoff;
3651 			break;
3652 		case IP_ADD_MEMBERSHIP:
3653 		case IP_DROP_MEMBERSHIP:
3654 		case IP_BLOCK_SOURCE:
3655 		case IP_UNBLOCK_SOURCE:
3656 		case IP_ADD_SOURCE_MEMBERSHIP:
3657 		case IP_DROP_SOURCE_MEMBERSHIP:
3658 		case MCAST_JOIN_GROUP:
3659 		case MCAST_LEAVE_GROUP:
3660 		case MCAST_BLOCK_SOURCE:
3661 		case MCAST_UNBLOCK_SOURCE:
3662 		case MCAST_JOIN_SOURCE_GROUP:
3663 		case MCAST_LEAVE_SOURCE_GROUP:
3664 		case IP_SEC_OPT:
3665 		case IP_NEXTHOP:
3666 			/*
3667 			 * "soft" error (negative)
3668 			 * option not handled at this level
3669 			 * Do not modify *outlenp.
3670 			 */
3671 			return (-EINVAL);
3672 		case IP_BOUND_IF:
3673 			if (!checkonly)
3674 				udp->udp_bound_if = *i1;
3675 			break;
3676 		case IP_UNSPEC_SRC:
3677 			if (!checkonly)
3678 				udp->udp_unspec_source = onoff;
3679 			break;
3680 		case IP_XMIT_IF:
3681 			if (!checkonly)
3682 				udp->udp_xmit_if = *i1;
3683 			break;
3684 		default:
3685 			*outlenp = 0;
3686 			return (EINVAL);
3687 		}
3688 		break;
3689 	case IPPROTO_IPV6: {
3690 		ip6_pkt_t		*ipp;
3691 		boolean_t		sticky;
3692 
3693 		if (udp->udp_family != AF_INET6) {
3694 			*outlenp = 0;
3695 			return (ENOPROTOOPT);
3696 		}
3697 		/*
3698 		 * Deal with both sticky options and ancillary data
3699 		 */
3700 		sticky = B_FALSE;
3701 		if (attrs == NULL || (ipp = attrs->udpattr_ipp) == NULL) {
3702 			/* sticky options, or none */
3703 			ipp = &udp->udp_sticky_ipp;
3704 			sticky = B_TRUE;
3705 		}
3706 
3707 		switch (name) {
3708 		case IPV6_MULTICAST_IF:
3709 			if (!checkonly)
3710 				udp->udp_multicast_if_index = *i1;
3711 			break;
3712 		case IPV6_UNICAST_HOPS:
3713 			/* -1 means use default */
3714 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
3715 				*outlenp = 0;
3716 				return (EINVAL);
3717 			}
3718 			if (!checkonly) {
3719 				if (*i1 == -1) {
3720 					udp->udp_ttl = ipp->ipp_unicast_hops =
3721 					    udp_ipv6_hoplimit;
3722 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
3723 					/* Pass modified value to IP. */
3724 					*i1 = udp->udp_ttl;
3725 				} else {
3726 					udp->udp_ttl = ipp->ipp_unicast_hops =
3727 					    (uint8_t)*i1;
3728 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
3729 				}
3730 				/* Rebuild the header template */
3731 				error = udp_build_hdrs(q, udp);
3732 				if (error != 0) {
3733 					*outlenp = 0;
3734 					return (error);
3735 				}
3736 			}
3737 			break;
3738 		case IPV6_MULTICAST_HOPS:
3739 			/* -1 means use default */
3740 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
3741 				*outlenp = 0;
3742 				return (EINVAL);
3743 			}
3744 			if (!checkonly) {
3745 				if (*i1 == -1) {
3746 					udp->udp_multicast_ttl =
3747 					    ipp->ipp_multicast_hops =
3748 					    IP_DEFAULT_MULTICAST_TTL;
3749 					ipp->ipp_fields &= ~IPPF_MULTICAST_HOPS;
3750 					/* Pass modified value to IP. */
3751 					*i1 = udp->udp_multicast_ttl;
3752 				} else {
3753 					udp->udp_multicast_ttl =
3754 					    ipp->ipp_multicast_hops =
3755 					    (uint8_t)*i1;
3756 					ipp->ipp_fields |= IPPF_MULTICAST_HOPS;
3757 				}
3758 			}
3759 			break;
3760 		case IPV6_MULTICAST_LOOP:
3761 			if (*i1 != 0 && *i1 != 1) {
3762 				*outlenp = 0;
3763 				return (EINVAL);
3764 			}
3765 			if (!checkonly)
3766 				connp->conn_multicast_loop = *i1;
3767 			break;
3768 		case IPV6_JOIN_GROUP:
3769 		case IPV6_LEAVE_GROUP:
3770 		case MCAST_JOIN_GROUP:
3771 		case MCAST_LEAVE_GROUP:
3772 		case MCAST_BLOCK_SOURCE:
3773 		case MCAST_UNBLOCK_SOURCE:
3774 		case MCAST_JOIN_SOURCE_GROUP:
3775 		case MCAST_LEAVE_SOURCE_GROUP:
3776 			/*
3777 			 * "soft" error (negative)
3778 			 * option not handled at this level
3779 			 * Note: Do not modify *outlenp
3780 			 */
3781 			return (-EINVAL);
3782 		case IPV6_BOUND_IF:
3783 			if (!checkonly)
3784 				udp->udp_bound_if = *i1;
3785 			break;
3786 		case IPV6_UNSPEC_SRC:
3787 			if (!checkonly)
3788 				udp->udp_unspec_source = onoff;
3789 			break;
3790 		/*
3791 		 * Set boolean switches for ancillary data delivery
3792 		 */
3793 		case IPV6_RECVPKTINFO:
3794 			if (!checkonly)
3795 				udp->udp_ipv6_recvpktinfo = onoff;
3796 			break;
3797 		case IPV6_RECVTCLASS:
3798 			if (!checkonly) {
3799 				udp->udp_ipv6_recvtclass = onoff;
3800 			}
3801 			break;
3802 		case IPV6_RECVPATHMTU:
3803 			if (!checkonly) {
3804 				udp->udp_ipv6_recvpathmtu = onoff;
3805 			}
3806 			break;
3807 		case IPV6_RECVHOPLIMIT:
3808 			if (!checkonly)
3809 				udp->udp_ipv6_recvhoplimit = onoff;
3810 			break;
3811 		case IPV6_RECVHOPOPTS:
3812 			if (!checkonly)
3813 				udp->udp_ipv6_recvhopopts = onoff;
3814 			break;
3815 		case IPV6_RECVDSTOPTS:
3816 			if (!checkonly)
3817 				udp->udp_ipv6_recvdstopts = onoff;
3818 			break;
3819 		case _OLD_IPV6_RECVDSTOPTS:
3820 			if (!checkonly)
3821 				udp->udp_old_ipv6_recvdstopts = onoff;
3822 			break;
3823 		case IPV6_RECVRTHDRDSTOPTS:
3824 			if (!checkonly)
3825 				udp->udp_ipv6_recvrthdrdstopts = onoff;
3826 			break;
3827 		case IPV6_RECVRTHDR:
3828 			if (!checkonly)
3829 				udp->udp_ipv6_recvrthdr = onoff;
3830 			break;
3831 		/*
3832 		 * Set sticky options or ancillary data.
3833 		 * If sticky options, (re)build any extension headers
3834 		 * that might be needed as a result.
3835 		 */
3836 		case IPV6_PKTINFO:
3837 			/*
3838 			 * The source address and ifindex are verified
3839 			 * in ip_opt_set(). For ancillary data the
3840 			 * source address is checked in ip_wput_v6.
3841 			 */
3842 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
3843 				return (EINVAL);
3844 			if (checkonly)
3845 				break;
3846 
3847 			if (inlen == 0) {
3848 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
3849 				ipp->ipp_sticky_ignored |=
3850 				    (IPPF_IFINDEX|IPPF_ADDR);
3851 			} else {
3852 				struct in6_pktinfo *pkti;
3853 
3854 				pkti = (struct in6_pktinfo *)invalp;
3855 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
3856 				ipp->ipp_addr = pkti->ipi6_addr;
3857 				if (ipp->ipp_ifindex != 0)
3858 					ipp->ipp_fields |= IPPF_IFINDEX;
3859 				else
3860 					ipp->ipp_fields &= ~IPPF_IFINDEX;
3861 				if (!IN6_IS_ADDR_UNSPECIFIED(
3862 				    &ipp->ipp_addr))
3863 					ipp->ipp_fields |= IPPF_ADDR;
3864 				else
3865 					ipp->ipp_fields &= ~IPPF_ADDR;
3866 			}
3867 			if (sticky) {
3868 				error = udp_build_hdrs(q, udp);
3869 				if (error != 0)
3870 					return (error);
3871 			}
3872 			break;
3873 		case IPV6_HOPLIMIT:
3874 			if (sticky)
3875 				return (EINVAL);
3876 			if (inlen != 0 && inlen != sizeof (int))
3877 				return (EINVAL);
3878 			if (checkonly)
3879 				break;
3880 
3881 			if (inlen == 0) {
3882 				ipp->ipp_fields &= ~IPPF_HOPLIMIT;
3883 				ipp->ipp_sticky_ignored |= IPPF_HOPLIMIT;
3884 			} else {
3885 				if (*i1 > 255 || *i1 < -1)
3886 					return (EINVAL);
3887 				if (*i1 == -1)
3888 					ipp->ipp_hoplimit = udp_ipv6_hoplimit;
3889 				else
3890 					ipp->ipp_hoplimit = *i1;
3891 				ipp->ipp_fields |= IPPF_HOPLIMIT;
3892 			}
3893 			break;
3894 		case IPV6_TCLASS:
3895 			if (inlen != 0 && inlen != sizeof (int))
3896 				return (EINVAL);
3897 			if (checkonly)
3898 				break;
3899 
3900 			if (inlen == 0) {
3901 				ipp->ipp_fields &= ~IPPF_TCLASS;
3902 				ipp->ipp_sticky_ignored |= IPPF_TCLASS;
3903 			} else {
3904 				if (*i1 > 255 || *i1 < -1)
3905 					return (EINVAL);
3906 				if (*i1 == -1)
3907 					ipp->ipp_tclass = 0;
3908 				else
3909 					ipp->ipp_tclass = *i1;
3910 				ipp->ipp_fields |= IPPF_TCLASS;
3911 			}
3912 			if (sticky) {
3913 				error = udp_build_hdrs(q, udp);
3914 				if (error != 0)
3915 					return (error);
3916 			}
3917 			break;
3918 		case IPV6_NEXTHOP:
3919 			/*
3920 			 * IP will verify that the nexthop is reachable
3921 			 * and fail for sticky options.
3922 			 */
3923 			if (inlen != 0 && inlen != sizeof (sin6_t))
3924 				return (EINVAL);
3925 			if (checkonly)
3926 				break;
3927 
3928 			if (inlen == 0) {
3929 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
3930 				ipp->ipp_sticky_ignored |= IPPF_NEXTHOP;
3931 			} else {
3932 				sin6_t *sin6 = (sin6_t *)invalp;
3933 
3934 				if (sin6->sin6_family != AF_INET6)
3935 					return (EAFNOSUPPORT);
3936 				if (IN6_IS_ADDR_V4MAPPED(
3937 				    &sin6->sin6_addr))
3938 					return (EADDRNOTAVAIL);
3939 				ipp->ipp_nexthop = sin6->sin6_addr;
3940 				if (!IN6_IS_ADDR_UNSPECIFIED(
3941 				    &ipp->ipp_nexthop))
3942 					ipp->ipp_fields |= IPPF_NEXTHOP;
3943 				else
3944 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
3945 			}
3946 			if (sticky) {
3947 				error = udp_build_hdrs(q, udp);
3948 				if (error != 0)
3949 					return (error);
3950 			}
3951 			break;
3952 		case IPV6_HOPOPTS: {
3953 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
3954 			/*
3955 			 * Sanity checks - minimum size, size a multiple of
3956 			 * eight bytes, and matching size passed in.
3957 			 */
3958 			if (inlen != 0 &&
3959 			    inlen != (8 * (hopts->ip6h_len + 1)))
3960 				return (EINVAL);
3961 
3962 			if (checkonly)
3963 				break;
3964 
3965 			error = optcom_pkt_set(invalp, inlen, sticky,
3966 			    (uchar_t **)&ipp->ipp_hopopts,
3967 			    &ipp->ipp_hopoptslen,
3968 			    sticky ? udp->udp_label_len_v6 : 0);
3969 			if (error != 0)
3970 				return (error);
3971 			if (ipp->ipp_hopoptslen == 0) {
3972 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
3973 				ipp->ipp_sticky_ignored |= IPPF_HOPOPTS;
3974 			} else {
3975 				ipp->ipp_fields |= IPPF_HOPOPTS;
3976 			}
3977 			if (sticky) {
3978 				error = udp_build_hdrs(q, udp);
3979 				if (error != 0)
3980 					return (error);
3981 			}
3982 			break;
3983 		}
3984 		case IPV6_RTHDRDSTOPTS: {
3985 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
3986 
3987 			/*
3988 			 * Sanity checks - minimum size, size a multiple of
3989 			 * eight bytes, and matching size passed in.
3990 			 */
3991 			if (inlen != 0 &&
3992 			    inlen != (8 * (dopts->ip6d_len + 1)))
3993 				return (EINVAL);
3994 
3995 			if (checkonly)
3996 				break;
3997 
3998 			if (inlen == 0) {
3999 				if (sticky &&
4000 				    (ipp->ipp_fields & IPPF_RTDSTOPTS) != 0) {
4001 					kmem_free(ipp->ipp_rtdstopts,
4002 					    ipp->ipp_rtdstoptslen);
4003 					ipp->ipp_rtdstopts = NULL;
4004 					ipp->ipp_rtdstoptslen = 0;
4005 				}
4006 
4007 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
4008 				ipp->ipp_sticky_ignored |= IPPF_RTDSTOPTS;
4009 			} else {
4010 				error = optcom_pkt_set(invalp, inlen, sticky,
4011 				    (uchar_t **)&ipp->ipp_rtdstopts,
4012 				    &ipp->ipp_rtdstoptslen, 0);
4013 				if (error != 0)
4014 					return (error);
4015 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
4016 			}
4017 			if (sticky) {
4018 				error = udp_build_hdrs(q, udp);
4019 				if (error != 0)
4020 					return (error);
4021 			}
4022 			break;
4023 		}
4024 		case IPV6_DSTOPTS: {
4025 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
4026 
4027 			/*
4028 			 * Sanity checks - minimum size, size a multiple of
4029 			 * eight bytes, and matching size passed in.
4030 			 */
4031 			if (inlen != 0 &&
4032 			    inlen != (8 * (dopts->ip6d_len + 1)))
4033 				return (EINVAL);
4034 
4035 			if (checkonly)
4036 				break;
4037 
4038 			if (inlen == 0) {
4039 				if (sticky &&
4040 				    (ipp->ipp_fields & IPPF_DSTOPTS) != 0) {
4041 					kmem_free(ipp->ipp_dstopts,
4042 					    ipp->ipp_dstoptslen);
4043 					ipp->ipp_dstopts = NULL;
4044 					ipp->ipp_dstoptslen = 0;
4045 				}
4046 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
4047 				ipp->ipp_sticky_ignored |= IPPF_DSTOPTS;
4048 			} else {
4049 				error = optcom_pkt_set(invalp, inlen, sticky,
4050 				    (uchar_t **)&ipp->ipp_dstopts,
4051 				    &ipp->ipp_dstoptslen, 0);
4052 				if (error != 0)
4053 					return (error);
4054 				ipp->ipp_fields |= IPPF_DSTOPTS;
4055 			}
4056 			if (sticky) {
4057 				error = udp_build_hdrs(q, udp);
4058 				if (error != 0)
4059 					return (error);
4060 			}
4061 			break;
4062 		}
4063 		case IPV6_RTHDR: {
4064 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
4065 
4066 			/*
4067 			 * Sanity checks - minimum size, size a multiple of
4068 			 * eight bytes, and matching size passed in.
4069 			 */
4070 			if (inlen != 0 &&
4071 			    inlen != (8 * (rt->ip6r_len + 1)))
4072 				return (EINVAL);
4073 
4074 			if (checkonly)
4075 				break;
4076 
4077 			if (inlen == 0) {
4078 				if (sticky &&
4079 				    (ipp->ipp_fields & IPPF_RTHDR) != 0) {
4080 					kmem_free(ipp->ipp_rthdr,
4081 					    ipp->ipp_rthdrlen);
4082 					ipp->ipp_rthdr = NULL;
4083 					ipp->ipp_rthdrlen = 0;
4084 				}
4085 				ipp->ipp_fields &= ~IPPF_RTHDR;
4086 				ipp->ipp_sticky_ignored |= IPPF_RTHDR;
4087 			} else {
4088 				error = optcom_pkt_set(invalp, inlen, sticky,
4089 				    (uchar_t **)&ipp->ipp_rthdr,
4090 				    &ipp->ipp_rthdrlen, 0);
4091 				if (error != 0)
4092 					return (error);
4093 				ipp->ipp_fields |= IPPF_RTHDR;
4094 			}
4095 			if (sticky) {
4096 				error = udp_build_hdrs(q, udp);
4097 				if (error != 0)
4098 					return (error);
4099 			}
4100 			break;
4101 		}
4102 
4103 		case IPV6_DONTFRAG:
4104 			if (checkonly)
4105 				break;
4106 
4107 			if (onoff) {
4108 				ipp->ipp_fields |= IPPF_DONTFRAG;
4109 			} else {
4110 				ipp->ipp_fields &= ~IPPF_DONTFRAG;
4111 			}
4112 			break;
4113 
4114 		case IPV6_USE_MIN_MTU:
4115 			if (inlen != sizeof (int))
4116 				return (EINVAL);
4117 
4118 			if (*i1 < -1 || *i1 > 1)
4119 				return (EINVAL);
4120 
4121 			if (checkonly)
4122 				break;
4123 
4124 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
4125 			ipp->ipp_use_min_mtu = *i1;
4126 			break;
4127 
4128 		case IPV6_BOUND_PIF:
4129 		case IPV6_SEC_OPT:
4130 		case IPV6_DONTFAILOVER_IF:
4131 		case IPV6_SRC_PREFERENCES:
4132 		case IPV6_V6ONLY:
4133 			/* Handled at the IP level */
4134 			return (-EINVAL);
4135 		default:
4136 			*outlenp = 0;
4137 			return (EINVAL);
4138 		}
4139 		break;
4140 		}		/* end IPPROTO_IPV6 */
4141 	case IPPROTO_UDP:
4142 		switch (name) {
4143 		case UDP_ANONPRIVBIND:
4144 			if ((error = secpolicy_net_privaddr(cr, 0)) != 0) {
4145 				*outlenp = 0;
4146 				return (error);
4147 			}
4148 			if (!checkonly) {
4149 				udp->udp_anon_priv_bind = onoff;
4150 			}
4151 			break;
4152 		case UDP_EXCLBIND:
4153 			if (!checkonly)
4154 				udp->udp_exclbind = onoff;
4155 			break;
4156 		case UDP_RCVHDR:
4157 			if (!checkonly)
4158 				udp->udp_rcvhdr = onoff;
4159 			break;
4160 		default:
4161 			*outlenp = 0;
4162 			return (EINVAL);
4163 		}
4164 		break;
4165 	default:
4166 		*outlenp = 0;
4167 		return (EINVAL);
4168 	}
4169 	/*
4170 	 * Common case of OK return with outval same as inval.
4171 	 */
4172 	if (invalp != outvalp) {
4173 		/* don't trust bcopy for identical src/dst */
4174 		(void) bcopy(invalp, outvalp, inlen);
4175 	}
4176 	*outlenp = inlen;
4177 	return (0);
4178 }
4179 
4180 /*
4181  * Update udp_sticky_hdrs based on udp_sticky_ipp, udp_v6src, and udp_ttl.
4182  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
4183  * headers, and the udp header.
4184  * Returns failure if can't allocate memory.
4185  */
4186 static int
4187 udp_build_hdrs(queue_t *q, udp_t *udp)
4188 {
4189 	uchar_t	*hdrs;
4190 	uint_t	hdrs_len;
4191 	ip6_t	*ip6h;
4192 	ip6i_t	*ip6i;
4193 	udpha_t	*udpha;
4194 	ip6_pkt_t *ipp = &udp->udp_sticky_ipp;
4195 
4196 	hdrs_len = ip_total_hdrs_len_v6(ipp) + UDPH_SIZE;
4197 	ASSERT(hdrs_len != 0);
4198 	if (hdrs_len != udp->udp_sticky_hdrs_len) {
4199 		/* Need to reallocate */
4200 		hdrs = kmem_alloc(hdrs_len, KM_NOSLEEP);
4201 		if (hdrs == NULL)
4202 			return (ENOMEM);
4203 
4204 		if (udp->udp_sticky_hdrs_len != 0) {
4205 			kmem_free(udp->udp_sticky_hdrs,
4206 			    udp->udp_sticky_hdrs_len);
4207 		}
4208 		udp->udp_sticky_hdrs = hdrs;
4209 		udp->udp_sticky_hdrs_len = hdrs_len;
4210 	}
4211 	ip_build_hdrs_v6(udp->udp_sticky_hdrs,
4212 	    udp->udp_sticky_hdrs_len - UDPH_SIZE, ipp, IPPROTO_UDP);
4213 
4214 	/* Set header fields not in ipp */
4215 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
4216 		ip6i = (ip6i_t *)udp->udp_sticky_hdrs;
4217 		ip6h = (ip6_t *)&ip6i[1];
4218 	} else {
4219 		ip6h = (ip6_t *)udp->udp_sticky_hdrs;
4220 	}
4221 
4222 	if (!(ipp->ipp_fields & IPPF_ADDR))
4223 		ip6h->ip6_src = udp->udp_v6src;
4224 
4225 	udpha = (udpha_t *)(udp->udp_sticky_hdrs + hdrs_len - UDPH_SIZE);
4226 	udpha->uha_src_port = udp->udp_port;
4227 
4228 	/* Try to get everything in a single mblk */
4229 	if (hdrs_len > udp->udp_max_hdr_len) {
4230 		udp->udp_max_hdr_len = hdrs_len;
4231 		(void) mi_set_sth_wroff(RD(q), udp->udp_max_hdr_len +
4232 		    udp_wroff_extra);
4233 	}
4234 	return (0);
4235 }
4236 
4237 /*
4238  * This routine retrieves the value of an ND variable in a udpparam_t
4239  * structure.  It is called through nd_getset when a user reads the
4240  * variable.
4241  */
4242 /* ARGSUSED */
4243 static int
4244 udp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
4245 {
4246 	udpparam_t *udppa = (udpparam_t *)cp;
4247 
4248 	(void) mi_mpprintf(mp, "%d", udppa->udp_param_value);
4249 	return (0);
4250 }
4251 
4252 /*
4253  * Walk through the param array specified registering each element with the
4254  * named dispatch (ND) handler.
4255  */
4256 static boolean_t
4257 udp_param_register(udpparam_t *udppa, int cnt)
4258 {
4259 	for (; cnt-- > 0; udppa++) {
4260 		if (udppa->udp_param_name && udppa->udp_param_name[0]) {
4261 			if (!nd_load(&udp_g_nd, udppa->udp_param_name,
4262 			    udp_param_get, udp_param_set,
4263 			    (caddr_t)udppa)) {
4264 				nd_free(&udp_g_nd);
4265 				return (B_FALSE);
4266 			}
4267 		}
4268 	}
4269 	if (!nd_load(&udp_g_nd, "udp_extra_priv_ports",
4270 	    udp_extra_priv_ports_get, NULL, NULL)) {
4271 		nd_free(&udp_g_nd);
4272 		return (B_FALSE);
4273 	}
4274 	if (!nd_load(&udp_g_nd, "udp_extra_priv_ports_add",
4275 	    NULL, udp_extra_priv_ports_add, NULL)) {
4276 		nd_free(&udp_g_nd);
4277 		return (B_FALSE);
4278 	}
4279 	if (!nd_load(&udp_g_nd, "udp_extra_priv_ports_del",
4280 	    NULL, udp_extra_priv_ports_del, NULL)) {
4281 		nd_free(&udp_g_nd);
4282 		return (B_FALSE);
4283 	}
4284 	if (!nd_load(&udp_g_nd, "udp_status", udp_status_report, NULL,
4285 	    NULL)) {
4286 		nd_free(&udp_g_nd);
4287 		return (B_FALSE);
4288 	}
4289 	if (!nd_load(&udp_g_nd, "udp_bind_hash", udp_bind_hash_report, NULL,
4290 	    NULL)) {
4291 		nd_free(&udp_g_nd);
4292 		return (B_FALSE);
4293 	}
4294 	return (B_TRUE);
4295 }
4296 
4297 /* This routine sets an ND variable in a udpparam_t structure. */
4298 /* ARGSUSED */
4299 static int
4300 udp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
4301 {
4302 	long		new_value;
4303 	udpparam_t	*udppa = (udpparam_t *)cp;
4304 
4305 	/*
4306 	 * Fail the request if the new value does not lie within the
4307 	 * required bounds.
4308 	 */
4309 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
4310 	    new_value < udppa->udp_param_min ||
4311 	    new_value > udppa->udp_param_max) {
4312 		return (EINVAL);
4313 	}
4314 
4315 	/* Set the new value */
4316 	udppa->udp_param_value = new_value;
4317 	return (0);
4318 }
4319 
4320 /*
4321  * Copy hop-by-hop option from ipp->ipp_hopopts to the buffer provided (with
4322  * T_opthdr) and return the number of bytes copied.  'dbuf' may be NULL to
4323  * just count the length needed for allocation.  If 'dbuf' is non-NULL,
4324  * then it's assumed to be allocated to be large enough.
4325  *
4326  * Returns zero if trimming of the security option causes all options to go
4327  * away.
4328  */
4329 static size_t
4330 copy_hop_opts(const ip6_pkt_t *ipp, uchar_t *dbuf)
4331 {
4332 	struct T_opthdr *toh;
4333 	size_t hol = ipp->ipp_hopoptslen;
4334 	ip6_hbh_t *dstopt = NULL;
4335 	const ip6_hbh_t *srcopt = ipp->ipp_hopopts;
4336 	size_t tlen, olen, plen;
4337 	boolean_t deleting;
4338 	const struct ip6_opt *sopt, *lastpad;
4339 	struct ip6_opt *dopt;
4340 
4341 	if ((toh = (struct T_opthdr *)dbuf) != NULL) {
4342 		toh->level = IPPROTO_IPV6;
4343 		toh->name = IPV6_HOPOPTS;
4344 		toh->status = 0;
4345 		dstopt = (ip6_hbh_t *)(toh + 1);
4346 	}
4347 
4348 	/*
4349 	 * If labeling is enabled, then skip the label option
4350 	 * but get other options if there are any.
4351 	 */
4352 	if (is_system_labeled()) {
4353 		dopt = NULL;
4354 		if (dstopt != NULL) {
4355 			/* will fill in ip6h_len later */
4356 			dstopt->ip6h_nxt = srcopt->ip6h_nxt;
4357 			dopt = (struct ip6_opt *)(dstopt + 1);
4358 		}
4359 		sopt = (const struct ip6_opt *)(srcopt + 1);
4360 		hol -= sizeof (*srcopt);
4361 		tlen = sizeof (*dstopt);
4362 		lastpad = NULL;
4363 		deleting = B_FALSE;
4364 		/*
4365 		 * This loop finds the first (lastpad pointer) of any number of
4366 		 * pads that preceeds the security option, then treats the
4367 		 * security option as though it were a pad, and then finds the
4368 		 * next non-pad option (or end of list).
4369 		 *
4370 		 * It then treats the entire block as one big pad.  To preserve
4371 		 * alignment of any options that follow, or just the end of the
4372 		 * list, it computes a minimal new padding size that keeps the
4373 		 * same alignment for the next option.
4374 		 *
4375 		 * If it encounters just a sequence of pads with no security
4376 		 * option, those are copied as-is rather than collapsed.
4377 		 *
4378 		 * Note that to handle the end of list case, the code makes one
4379 		 * loop with 'hol' set to zero.
4380 		 */
4381 		for (;;) {
4382 			if (hol > 0) {
4383 				if (sopt->ip6o_type == IP6OPT_PAD1) {
4384 					if (lastpad == NULL)
4385 						lastpad = sopt;
4386 					sopt = (const struct ip6_opt *)
4387 					    &sopt->ip6o_len;
4388 					hol--;
4389 					continue;
4390 				}
4391 				olen = sopt->ip6o_len + sizeof (*sopt);
4392 				if (olen > hol)
4393 					olen = hol;
4394 				if (sopt->ip6o_type == IP6OPT_PADN ||
4395 				    sopt->ip6o_type == ip6opt_ls) {
4396 					if (sopt->ip6o_type == ip6opt_ls)
4397 						deleting = B_TRUE;
4398 					if (lastpad == NULL)
4399 						lastpad = sopt;
4400 					sopt = (const struct ip6_opt *)
4401 					    ((const char *)sopt + olen);
4402 					hol -= olen;
4403 					continue;
4404 				}
4405 			} else {
4406 				/* if nothing was copied at all, then delete */
4407 				if (tlen == sizeof (*dstopt))
4408 					return (0);
4409 				/* last pass; pick up any trailing padding */
4410 				olen = 0;
4411 			}
4412 			if (deleting) {
4413 				/*
4414 				 * compute aligning effect of deleted material
4415 				 * to reproduce with pad.
4416 				 */
4417 				plen = ((const char *)sopt -
4418 				    (const char *)lastpad) & 7;
4419 				tlen += plen;
4420 				if (dopt != NULL) {
4421 					if (plen == 1) {
4422 						dopt->ip6o_type = IP6OPT_PAD1;
4423 					} else if (plen > 1) {
4424 						plen -= sizeof (*dopt);
4425 						dopt->ip6o_type = IP6OPT_PADN;
4426 						dopt->ip6o_len = plen;
4427 						if (plen > 0)
4428 							bzero(dopt + 1, plen);
4429 					}
4430 					dopt = (struct ip6_opt *)
4431 					    ((char *)dopt + plen);
4432 				}
4433 				deleting = B_FALSE;
4434 				lastpad = NULL;
4435 			}
4436 			/* if there's uncopied padding, then copy that now */
4437 			if (lastpad != NULL) {
4438 				olen += (const char *)sopt -
4439 				    (const char *)lastpad;
4440 				sopt = lastpad;
4441 				lastpad = NULL;
4442 			}
4443 			if (dopt != NULL && olen > 0) {
4444 				bcopy(sopt, dopt, olen);
4445 				dopt = (struct ip6_opt *)((char *)dopt + olen);
4446 			}
4447 			if (hol == 0)
4448 				break;
4449 			tlen += olen;
4450 			sopt = (const struct ip6_opt *)
4451 			    ((const char *)sopt + olen);
4452 			hol -= olen;
4453 		}
4454 		/* go back and patch up the length value, rounded upward */
4455 		if (dstopt != NULL)
4456 			dstopt->ip6h_len = (tlen - 1) >> 3;
4457 	} else {
4458 		tlen = hol;
4459 		if (dstopt != NULL)
4460 			bcopy(srcopt, dstopt, hol);
4461 	}
4462 
4463 	tlen += sizeof (*toh);
4464 	if (toh != NULL)
4465 		toh->len = tlen;
4466 
4467 	return (tlen);
4468 }
4469 
4470 static void
4471 udp_input(conn_t *connp, mblk_t *mp)
4472 {
4473 	struct T_unitdata_ind	*tudi;
4474 	uchar_t			*rptr;		/* Pointer to IP header */
4475 	int			hdr_length;	/* Length of IP+UDP headers */
4476 	int			udi_size;	/* Size of T_unitdata_ind */
4477 	int			mp_len;
4478 	udp_t			*udp;
4479 	udpha_t			*udpha;
4480 	int			ipversion;
4481 	ip6_pkt_t		ipp;
4482 	ip6_t			*ip6h;
4483 	ip6i_t			*ip6i;
4484 	mblk_t			*mp1;
4485 	mblk_t			*options_mp = NULL;
4486 	in_pktinfo_t		*pinfo = NULL;
4487 	cred_t			*cr = NULL;
4488 	queue_t			*q = connp->conn_rq;
4489 	pid_t			cpid;
4490 	cred_t			*rcr = connp->conn_cred;
4491 
4492 	TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_START,
4493 	    "udp_rput_start: q %p mp %p", q, mp);
4494 
4495 	udp = connp->conn_udp;
4496 	rptr = mp->b_rptr;
4497 	ASSERT(DB_TYPE(mp) == M_DATA || DB_TYPE(mp) == M_CTL);
4498 	ASSERT(OK_32PTR(rptr));
4499 
4500 	/*
4501 	 * IP should have prepended the options data in an M_CTL
4502 	 * Check M_CTL "type" to make sure are not here bcos of
4503 	 * a valid ICMP message
4504 	 */
4505 	if (DB_TYPE(mp) == M_CTL) {
4506 		if (MBLKL(mp) == sizeof (in_pktinfo_t) &&
4507 		    ((in_pktinfo_t *)mp->b_rptr)->in_pkt_ulp_type ==
4508 		    IN_PKTINFO) {
4509 			/*
4510 			 * IP_RECVIF or IP_RECVSLLA information has been
4511 			 * appended to the packet by IP. We need to
4512 			 * extract the mblk and adjust the rptr
4513 			 */
4514 			pinfo = (in_pktinfo_t *)mp->b_rptr;
4515 			options_mp = mp;
4516 			mp = mp->b_cont;
4517 			rptr = mp->b_rptr;
4518 			UDP_STAT(udp_in_pktinfo);
4519 		} else {
4520 			/*
4521 			 * ICMP messages.
4522 			 */
4523 			udp_icmp_error(q, mp);
4524 			TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
4525 				"udp_rput_end: q %p (%S)", q, "m_ctl");
4526 			return;
4527 		}
4528 	}
4529 
4530 	mp_len = msgdsize(mp);
4531 	/*
4532 	 * This is the inbound data path.
4533 	 * First, we check to make sure the IP version number is correct,
4534 	 * and then pull the IP and UDP headers into the first mblk.
4535 	 * Assume IP provides aligned packets - otherwise toss.
4536 	 * Also, check if we have a complete IP header.
4537 	 */
4538 
4539 	/* Initialize regardless if ipversion is IPv4 or IPv6 */
4540 	ipp.ipp_fields = 0;
4541 
4542 	ipversion = IPH_HDR_VERSION(rptr);
4543 	switch (ipversion) {
4544 	case IPV4_VERSION:
4545 		ASSERT(MBLKL(mp) >= sizeof (ipha_t));
4546 		ASSERT(((ipha_t *)rptr)->ipha_protocol == IPPROTO_UDP);
4547 		hdr_length = IPH_HDR_LENGTH(rptr) + UDPH_SIZE;
4548 		if ((hdr_length > IP_SIMPLE_HDR_LENGTH + UDPH_SIZE) ||
4549 		    (udp->udp_ip_rcv_options_len)) {
4550 			/*
4551 			 * Handle IPv4 packets with options outside of the
4552 			 * main data path. Not needed for AF_INET6 sockets
4553 			 * since they don't support a getsockopt of IP_OPTIONS.
4554 			 */
4555 			if (udp->udp_family == AF_INET6)
4556 				break;
4557 			/*
4558 			 * UDP length check performed for IPv4 packets with
4559 			 * options to check whether UDP length specified in
4560 			 * the header is the same as the physical length of
4561 			 * the packet.
4562 			 */
4563 			udpha = (udpha_t *)(rptr + (hdr_length - UDPH_SIZE));
4564 			if (mp_len != (ntohs(udpha->uha_length) +
4565 			    hdr_length - UDPH_SIZE)) {
4566 				goto tossit;
4567 			}
4568 			/*
4569 			 * Handle the case where the packet has IP options
4570 			 * and the IP_RECVSLLA & IP_RECVIF are set
4571 			 */
4572 			if (pinfo != NULL)
4573 				mp = options_mp;
4574 			udp_become_writer(connp, mp, udp_rput_other_wrapper,
4575 			    SQTAG_UDP_INPUT);
4576 			TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
4577 				"udp_rput_end: q %p (%S)", q, "end");
4578 			return;
4579 		}
4580 
4581 		/* Handle IPV6_RECVHOPLIMIT. */
4582 		if ((udp->udp_family == AF_INET6) && (pinfo != NULL) &&
4583 		    udp->udp_ipv6_recvpktinfo) {
4584 			if (pinfo->in_pkt_flags & IPF_RECVIF) {
4585 				ipp.ipp_fields |= IPPF_IFINDEX;
4586 				ipp.ipp_ifindex = pinfo->in_pkt_ifindex;
4587 			}
4588 		}
4589 		break;
4590 	case IPV6_VERSION:
4591 		/*
4592 		 * IPv6 packets can only be received by applications
4593 		 * that are prepared to receive IPv6 addresses.
4594 		 * The IP fanout must ensure this.
4595 		 */
4596 		ASSERT(udp->udp_family == AF_INET6);
4597 
4598 		ip6h = (ip6_t *)rptr;
4599 		ASSERT((uchar_t *)&ip6h[1] <= mp->b_wptr);
4600 
4601 		if (ip6h->ip6_nxt != IPPROTO_UDP) {
4602 			uint8_t nexthdrp;
4603 			/* Look for ifindex information */
4604 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
4605 				ip6i = (ip6i_t *)ip6h;
4606 				if ((uchar_t *)&ip6i[1] > mp->b_wptr)
4607 					goto tossit;
4608 
4609 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
4610 					ASSERT(ip6i->ip6i_ifindex != 0);
4611 					ipp.ipp_fields |= IPPF_IFINDEX;
4612 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
4613 				}
4614 				rptr = (uchar_t *)&ip6i[1];
4615 				mp->b_rptr = rptr;
4616 				if (rptr == mp->b_wptr) {
4617 					mp1 = mp->b_cont;
4618 					freeb(mp);
4619 					mp = mp1;
4620 					rptr = mp->b_rptr;
4621 				}
4622 				if (MBLKL(mp) < (IPV6_HDR_LEN + UDPH_SIZE))
4623 					goto tossit;
4624 				ip6h = (ip6_t *)rptr;
4625 				mp_len = msgdsize(mp);
4626 			}
4627 			/*
4628 			 * Find any potentially interesting extension headers
4629 			 * as well as the length of the IPv6 + extension
4630 			 * headers.
4631 			 */
4632 			hdr_length = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp) +
4633 			    UDPH_SIZE;
4634 			ASSERT(nexthdrp == IPPROTO_UDP);
4635 		} else {
4636 			hdr_length = IPV6_HDR_LEN + UDPH_SIZE;
4637 			ip6i = NULL;
4638 		}
4639 		break;
4640 	default:
4641 		ASSERT(0);
4642 	}
4643 
4644 	/*
4645 	 * IP inspected the UDP header thus all of it must be in the mblk.
4646 	 * UDP length check is performed for IPv6 packets and IPv4 packets
4647 	 * without options to check if the size of the packet as specified
4648 	 * by the header is the same as the physical size of the packet.
4649 	 */
4650 	udpha = (udpha_t *)(rptr + (hdr_length - UDPH_SIZE));
4651 	if ((MBLKL(mp) < hdr_length) ||
4652 	    (mp_len != (ntohs(udpha->uha_length) + hdr_length - UDPH_SIZE))) {
4653 		goto tossit;
4654 	}
4655 
4656 	/* Walk past the headers. */
4657 	if (!udp->udp_rcvhdr) {
4658 		mp->b_rptr = rptr + hdr_length;
4659 		mp_len -= hdr_length;
4660 	}
4661 
4662 	/*
4663 	 * This is the inbound data path.  Packets are passed upstream as
4664 	 * T_UNITDATA_IND messages with full IP headers still attached.
4665 	 */
4666 	if (udp->udp_family == AF_INET) {
4667 		sin_t *sin;
4668 
4669 		ASSERT(IPH_HDR_VERSION((ipha_t *)rptr) == IPV4_VERSION);
4670 
4671 		/*
4672 		 * Normally only send up the address.
4673 		 * If IP_RECVDSTADDR is set we include the destination IP
4674 		 * address as an option. With IP_RECVOPTS we include all
4675 		 * the IP options. Only ip_rput_other() handles packets
4676 		 * that contain IP options.
4677 		 */
4678 		udi_size = sizeof (struct T_unitdata_ind) + sizeof (sin_t);
4679 		if (udp->udp_recvdstaddr) {
4680 			udi_size += sizeof (struct T_opthdr) +
4681 			    sizeof (struct in_addr);
4682 			UDP_STAT(udp_in_recvdstaddr);
4683 		}
4684 
4685 		/*
4686 		 * If the IP_RECVSLLA or the IP_RECVIF is set then allocate
4687 		 * space accordingly
4688 		 */
4689 		if (udp->udp_recvif && (pinfo != NULL) &&
4690 		    (pinfo->in_pkt_flags & IPF_RECVIF)) {
4691 			udi_size += sizeof (struct T_opthdr) + sizeof (uint_t);
4692 			UDP_STAT(udp_in_recvif);
4693 		}
4694 
4695 		if (udp->udp_recvslla && (pinfo != NULL) &&
4696 		    (pinfo->in_pkt_flags & IPF_RECVSLLA)) {
4697 			udi_size += sizeof (struct T_opthdr) +
4698 			    sizeof (struct sockaddr_dl);
4699 			UDP_STAT(udp_in_recvslla);
4700 		}
4701 
4702 		if (udp->udp_recvucred && (cr = DB_CRED(mp)) != NULL) {
4703 			udi_size += sizeof (struct T_opthdr) + ucredsize;
4704 			cpid = DB_CPID(mp);
4705 			UDP_STAT(udp_in_recvucred);
4706 		}
4707 
4708 		/*
4709 		 * If SO_TIMESTAMP is set allocate the appropriate sized
4710 		 * buffer. Since gethrestime() expects a pointer aligned
4711 		 * argument, we allocate space necessary for extra
4712 		 * alignment (even though it might not be used).
4713 		 */
4714 		if (udp->udp_timestamp) {
4715 			udi_size += sizeof (struct T_opthdr) +
4716 			    sizeof (timestruc_t) + _POINTER_ALIGNMENT;
4717 			UDP_STAT(udp_in_timestamp);
4718 		}
4719 
4720 		/*
4721 		 * If IP_RECVTTL is set allocate the appropriate sized buffer
4722 		 */
4723 		if (udp->udp_recvttl) {
4724 			udi_size += sizeof (struct T_opthdr) + sizeof (uint8_t);
4725 			UDP_STAT(udp_in_recvttl);
4726 		}
4727 		ASSERT(IPH_HDR_LENGTH((ipha_t *)rptr) == IP_SIMPLE_HDR_LENGTH);
4728 
4729 		/* Allocate a message block for the T_UNITDATA_IND structure. */
4730 		mp1 = allocb(udi_size, BPRI_MED);
4731 		if (mp1 == NULL) {
4732 			freemsg(mp);
4733 			if (options_mp != NULL)
4734 				freeb(options_mp);
4735 			TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
4736 				"udp_rput_end: q %p (%S)", q, "allocbfail");
4737 			BUMP_MIB(&udp_mib, udpInErrors);
4738 			return;
4739 		}
4740 		mp1->b_cont = mp;
4741 		mp = mp1;
4742 		mp->b_datap->db_type = M_PROTO;
4743 		tudi = (struct T_unitdata_ind *)mp->b_rptr;
4744 		mp->b_wptr = (uchar_t *)tudi + udi_size;
4745 		tudi->PRIM_type = T_UNITDATA_IND;
4746 		tudi->SRC_length = sizeof (sin_t);
4747 		tudi->SRC_offset = sizeof (struct T_unitdata_ind);
4748 		tudi->OPT_offset = sizeof (struct T_unitdata_ind) +
4749 		    sizeof (sin_t);
4750 		udi_size -= (sizeof (struct T_unitdata_ind) + sizeof (sin_t));
4751 		tudi->OPT_length = udi_size;
4752 		sin = (sin_t *)&tudi[1];
4753 		sin->sin_addr.s_addr = ((ipha_t *)rptr)->ipha_src;
4754 		sin->sin_port =	udpha->uha_src_port;
4755 		sin->sin_family = udp->udp_family;
4756 		*(uint32_t *)&sin->sin_zero[0] = 0;
4757 		*(uint32_t *)&sin->sin_zero[4] = 0;
4758 
4759 		/*
4760 		 * Add options if IP_RECVDSTADDR, IP_RECVIF, IP_RECVSLLA or
4761 		 * IP_RECVTTL has been set.
4762 		 */
4763 		if (udi_size != 0) {
4764 			/*
4765 			 * Copy in destination address before options to avoid
4766 			 * any padding issues.
4767 			 */
4768 			char *dstopt;
4769 
4770 			dstopt = (char *)&sin[1];
4771 			if (udp->udp_recvdstaddr) {
4772 				struct T_opthdr *toh;
4773 				ipaddr_t *dstptr;
4774 
4775 				toh = (struct T_opthdr *)dstopt;
4776 				toh->level = IPPROTO_IP;
4777 				toh->name = IP_RECVDSTADDR;
4778 				toh->len = sizeof (struct T_opthdr) +
4779 				    sizeof (ipaddr_t);
4780 				toh->status = 0;
4781 				dstopt += sizeof (struct T_opthdr);
4782 				dstptr = (ipaddr_t *)dstopt;
4783 				*dstptr = ((ipha_t *)rptr)->ipha_dst;
4784 				dstopt = (char *)toh + toh->len;
4785 				udi_size -= toh->len;
4786 			}
4787 
4788 			if (udp->udp_recvslla && (pinfo != NULL) &&
4789 			    (pinfo->in_pkt_flags & IPF_RECVSLLA)) {
4790 
4791 				struct T_opthdr *toh;
4792 				struct sockaddr_dl	*dstptr;
4793 
4794 				toh = (struct T_opthdr *)dstopt;
4795 				toh->level = IPPROTO_IP;
4796 				toh->name = IP_RECVSLLA;
4797 				toh->len = sizeof (struct T_opthdr) +
4798 					sizeof (struct sockaddr_dl);
4799 				toh->status = 0;
4800 				dstopt += sizeof (struct T_opthdr);
4801 				dstptr = (struct sockaddr_dl *)dstopt;
4802 				bcopy(&pinfo->in_pkt_slla, dstptr,
4803 				    sizeof (struct sockaddr_dl));
4804 				dstopt = (char *)toh + toh->len;
4805 				udi_size -= toh->len;
4806 			}
4807 
4808 			if (udp->udp_recvif && (pinfo != NULL) &&
4809 			    (pinfo->in_pkt_flags & IPF_RECVIF)) {
4810 
4811 				struct T_opthdr *toh;
4812 				uint_t		*dstptr;
4813 
4814 				toh = (struct T_opthdr *)dstopt;
4815 				toh->level = IPPROTO_IP;
4816 				toh->name = IP_RECVIF;
4817 				toh->len = sizeof (struct T_opthdr) +
4818 					sizeof (uint_t);
4819 				toh->status = 0;
4820 				dstopt += sizeof (struct T_opthdr);
4821 				dstptr = (uint_t *)dstopt;
4822 				*dstptr = pinfo->in_pkt_ifindex;
4823 				dstopt = (char *)toh + toh->len;
4824 				udi_size -= toh->len;
4825 			}
4826 
4827 			if (cr != NULL) {
4828 				struct T_opthdr *toh;
4829 
4830 				toh = (struct T_opthdr *)dstopt;
4831 				toh->level = SOL_SOCKET;
4832 				toh->name = SCM_UCRED;
4833 				toh->len = sizeof (struct T_opthdr) + ucredsize;
4834 				toh->status = 0;
4835 				(void) cred2ucred(cr, cpid, &toh[1], rcr);
4836 				dstopt = (char *)toh + toh->len;
4837 				udi_size -= toh->len;
4838 			}
4839 
4840 			if (udp->udp_timestamp) {
4841 				struct	T_opthdr *toh;
4842 
4843 				toh = (struct T_opthdr *)dstopt;
4844 				toh->level = SOL_SOCKET;
4845 				toh->name = SCM_TIMESTAMP;
4846 				toh->len = sizeof (struct T_opthdr) +
4847 				    sizeof (timestruc_t) + _POINTER_ALIGNMENT;
4848 				toh->status = 0;
4849 				dstopt += sizeof (struct T_opthdr);
4850 				/* Align for gethrestime() */
4851 				dstopt = (char *)P2ROUNDUP((intptr_t)dstopt,
4852 				    sizeof (intptr_t));
4853 				gethrestime((timestruc_t *)dstopt);
4854 				dstopt = (char *)toh + toh->len;
4855 				udi_size -= toh->len;
4856 			}
4857 
4858 			/*
4859 			 * CAUTION:
4860 			 * Due to aligment issues
4861 			 * Processing of IP_RECVTTL option
4862 			 * should always be the last. Adding
4863 			 * any option processing after this will
4864 			 * cause alignment panic.
4865 			 */
4866 			if (udp->udp_recvttl) {
4867 				struct	T_opthdr *toh;
4868 				uint8_t	*dstptr;
4869 
4870 				toh = (struct T_opthdr *)dstopt;
4871 				toh->level = IPPROTO_IP;
4872 				toh->name = IP_RECVTTL;
4873 				toh->len = sizeof (struct T_opthdr) +
4874 				    sizeof (uint8_t);
4875 				toh->status = 0;
4876 				dstopt += sizeof (struct T_opthdr);
4877 				dstptr = (uint8_t *)dstopt;
4878 				*dstptr = ((ipha_t *)rptr)->ipha_ttl;
4879 				dstopt = (char *)toh + toh->len;
4880 				udi_size -= toh->len;
4881 			}
4882 
4883 			/* Consumed all of allocated space */
4884 			ASSERT(udi_size == 0);
4885 		}
4886 	} else {
4887 		sin6_t *sin6;
4888 
4889 		/*
4890 		 * Handle both IPv4 and IPv6 packets for IPv6 sockets.
4891 		 *
4892 		 * Normally we only send up the address. If receiving of any
4893 		 * optional receive side information is enabled, we also send
4894 		 * that up as options.
4895 		 * [ Only udp_rput_other() handles packets that contain IP
4896 		 * options so code to account for does not appear immediately
4897 		 * below but elsewhere ]
4898 		 */
4899 		udi_size = sizeof (struct T_unitdata_ind) + sizeof (sin6_t);
4900 
4901 		if (ipp.ipp_fields & (IPPF_HOPOPTS|IPPF_DSTOPTS|IPPF_RTDSTOPTS|
4902 		    IPPF_RTHDR|IPPF_IFINDEX)) {
4903 			if (udp->udp_ipv6_recvhopopts &&
4904 			    (ipp.ipp_fields & IPPF_HOPOPTS)) {
4905 				size_t hlen;
4906 
4907 				UDP_STAT(udp_in_recvhopopts);
4908 				hlen = copy_hop_opts(&ipp, NULL);
4909 				if (hlen == 0)
4910 					ipp.ipp_fields &= ~IPPF_HOPOPTS;
4911 				udi_size += hlen;
4912 			}
4913 			if ((udp->udp_ipv6_recvdstopts ||
4914 				udp->udp_old_ipv6_recvdstopts) &&
4915 			    (ipp.ipp_fields & IPPF_DSTOPTS)) {
4916 				udi_size += sizeof (struct T_opthdr) +
4917 				    ipp.ipp_dstoptslen;
4918 				UDP_STAT(udp_in_recvdstopts);
4919 			}
4920 			if (((udp->udp_ipv6_recvdstopts &&
4921 			    udp->udp_ipv6_recvrthdr &&
4922 			    (ipp.ipp_fields & IPPF_RTHDR)) ||
4923 			    udp->udp_ipv6_recvrthdrdstopts) &&
4924 			    (ipp.ipp_fields & IPPF_RTDSTOPTS)) {
4925 				udi_size += sizeof (struct T_opthdr) +
4926 				    ipp.ipp_rtdstoptslen;
4927 				UDP_STAT(udp_in_recvrtdstopts);
4928 			}
4929 			if (udp->udp_ipv6_recvrthdr &&
4930 			    (ipp.ipp_fields & IPPF_RTHDR)) {
4931 				udi_size += sizeof (struct T_opthdr) +
4932 				    ipp.ipp_rthdrlen;
4933 				UDP_STAT(udp_in_recvrthdr);
4934 			}
4935 			if (udp->udp_ipv6_recvpktinfo &&
4936 			    (ipp.ipp_fields & IPPF_IFINDEX)) {
4937 				udi_size += sizeof (struct T_opthdr) +
4938 				    sizeof (struct in6_pktinfo);
4939 				UDP_STAT(udp_in_recvpktinfo);
4940 			}
4941 
4942 		}
4943 		if (udp->udp_recvucred && (cr = DB_CRED(mp)) != NULL) {
4944 			udi_size += sizeof (struct T_opthdr) + ucredsize;
4945 			cpid = DB_CPID(mp);
4946 			UDP_STAT(udp_in_recvucred);
4947 		}
4948 
4949 		if (udp->udp_ipv6_recvhoplimit) {
4950 			udi_size += sizeof (struct T_opthdr) + sizeof (int);
4951 			UDP_STAT(udp_in_recvhoplimit);
4952 		}
4953 
4954 		if (udp->udp_ipv6_recvtclass) {
4955 			udi_size += sizeof (struct T_opthdr) + sizeof (int);
4956 			UDP_STAT(udp_in_recvtclass);
4957 		}
4958 
4959 		mp1 = allocb(udi_size, BPRI_MED);
4960 		if (mp1 == NULL) {
4961 			freemsg(mp);
4962 			if (options_mp != NULL)
4963 				freeb(options_mp);
4964 			TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
4965 				"udp_rput_end: q %p (%S)", q, "allocbfail");
4966 			BUMP_MIB(&udp_mib, udpInErrors);
4967 			return;
4968 		}
4969 		mp1->b_cont = mp;
4970 		mp = mp1;
4971 		mp->b_datap->db_type = M_PROTO;
4972 		tudi = (struct T_unitdata_ind *)mp->b_rptr;
4973 		mp->b_wptr = (uchar_t *)tudi + udi_size;
4974 		tudi->PRIM_type = T_UNITDATA_IND;
4975 		tudi->SRC_length = sizeof (sin6_t);
4976 		tudi->SRC_offset = sizeof (struct T_unitdata_ind);
4977 		tudi->OPT_offset = sizeof (struct T_unitdata_ind) +
4978 		    sizeof (sin6_t);
4979 		udi_size -= (sizeof (struct T_unitdata_ind) + sizeof (sin6_t));
4980 		tudi->OPT_length = udi_size;
4981 		sin6 = (sin6_t *)&tudi[1];
4982 		if (ipversion == IPV4_VERSION) {
4983 			in6_addr_t v6dst;
4984 
4985 			IN6_IPADDR_TO_V4MAPPED(((ipha_t *)rptr)->ipha_src,
4986 			    &sin6->sin6_addr);
4987 			IN6_IPADDR_TO_V4MAPPED(((ipha_t *)rptr)->ipha_dst,
4988 			    &v6dst);
4989 			sin6->sin6_flowinfo = 0;
4990 			sin6->sin6_scope_id = 0;
4991 			sin6->__sin6_src_id = ip_srcid_find_addr(&v6dst,
4992 			    connp->conn_zoneid);
4993 		} else {
4994 			sin6->sin6_addr = ip6h->ip6_src;
4995 			/* No sin6_flowinfo per API */
4996 			sin6->sin6_flowinfo = 0;
4997 			/* For link-scope source pass up scope id */
4998 			if ((ipp.ipp_fields & IPPF_IFINDEX) &&
4999 			    IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
5000 				sin6->sin6_scope_id = ipp.ipp_ifindex;
5001 			else
5002 				sin6->sin6_scope_id = 0;
5003 			sin6->__sin6_src_id = ip_srcid_find_addr(
5004 			    &ip6h->ip6_dst, connp->conn_zoneid);
5005 		}
5006 		sin6->sin6_port = udpha->uha_src_port;
5007 		sin6->sin6_family = udp->udp_family;
5008 
5009 		if (udi_size != 0) {
5010 			uchar_t *dstopt;
5011 
5012 			dstopt = (uchar_t *)&sin6[1];
5013 			if (udp->udp_ipv6_recvpktinfo &&
5014 			    (ipp.ipp_fields & IPPF_IFINDEX)) {
5015 				struct T_opthdr *toh;
5016 				struct in6_pktinfo *pkti;
5017 
5018 				toh = (struct T_opthdr *)dstopt;
5019 				toh->level = IPPROTO_IPV6;
5020 				toh->name = IPV6_PKTINFO;
5021 				toh->len = sizeof (struct T_opthdr) +
5022 				    sizeof (*pkti);
5023 				toh->status = 0;
5024 				dstopt += sizeof (struct T_opthdr);
5025 				pkti = (struct in6_pktinfo *)dstopt;
5026 				if (ipversion == IPV6_VERSION)
5027 					pkti->ipi6_addr = ip6h->ip6_dst;
5028 				else
5029 					IN6_IPADDR_TO_V4MAPPED(
5030 						((ipha_t *)rptr)->ipha_dst,
5031 						    &pkti->ipi6_addr);
5032 				pkti->ipi6_ifindex = ipp.ipp_ifindex;
5033 				dstopt += sizeof (*pkti);
5034 				udi_size -= toh->len;
5035 			}
5036 			if (udp->udp_ipv6_recvhoplimit) {
5037 				struct T_opthdr *toh;
5038 
5039 				toh = (struct T_opthdr *)dstopt;
5040 				toh->level = IPPROTO_IPV6;
5041 				toh->name = IPV6_HOPLIMIT;
5042 				toh->len = sizeof (struct T_opthdr) +
5043 				    sizeof (uint_t);
5044 				toh->status = 0;
5045 				dstopt += sizeof (struct T_opthdr);
5046 				if (ipversion == IPV6_VERSION)
5047 					*(uint_t *)dstopt = ip6h->ip6_hops;
5048 				else
5049 					*(uint_t *)dstopt =
5050 					    ((ipha_t *)rptr)->ipha_ttl;
5051 				dstopt += sizeof (uint_t);
5052 				udi_size -= toh->len;
5053 			}
5054 			if (udp->udp_ipv6_recvtclass) {
5055 				struct T_opthdr *toh;
5056 
5057 				toh = (struct T_opthdr *)dstopt;
5058 				toh->level = IPPROTO_IPV6;
5059 				toh->name = IPV6_TCLASS;
5060 				toh->len = sizeof (struct T_opthdr) +
5061 				    sizeof (uint_t);
5062 				toh->status = 0;
5063 				dstopt += sizeof (struct T_opthdr);
5064 				if (ipversion == IPV6_VERSION) {
5065 					*(uint_t *)dstopt =
5066 					IPV6_FLOW_TCLASS(ip6h->ip6_flow);
5067 				} else {
5068 					ipha_t *ipha = (ipha_t *)rptr;
5069 					*(uint_t *)dstopt =
5070 					    ipha->ipha_type_of_service;
5071 				}
5072 				dstopt += sizeof (uint_t);
5073 				udi_size -= toh->len;
5074 			}
5075 			if (udp->udp_ipv6_recvhopopts &&
5076 			    (ipp.ipp_fields & IPPF_HOPOPTS)) {
5077 				size_t hlen;
5078 
5079 				hlen = copy_hop_opts(&ipp, dstopt);
5080 				dstopt += hlen;
5081 				udi_size -= hlen;
5082 			}
5083 			if (udp->udp_ipv6_recvdstopts &&
5084 			    udp->udp_ipv6_recvrthdr &&
5085 			    (ipp.ipp_fields & IPPF_RTHDR) &&
5086 			    (ipp.ipp_fields & IPPF_RTDSTOPTS)) {
5087 				struct T_opthdr *toh;
5088 
5089 				toh = (struct T_opthdr *)dstopt;
5090 				toh->level = IPPROTO_IPV6;
5091 				toh->name = IPV6_DSTOPTS;
5092 				toh->len = sizeof (struct T_opthdr) +
5093 				    ipp.ipp_rtdstoptslen;
5094 				toh->status = 0;
5095 				dstopt += sizeof (struct T_opthdr);
5096 				bcopy(ipp.ipp_rtdstopts, dstopt,
5097 				    ipp.ipp_rtdstoptslen);
5098 				dstopt += ipp.ipp_rtdstoptslen;
5099 				udi_size -= toh->len;
5100 			}
5101 			if (udp->udp_ipv6_recvrthdr &&
5102 			    (ipp.ipp_fields & IPPF_RTHDR)) {
5103 				struct T_opthdr *toh;
5104 
5105 				toh = (struct T_opthdr *)dstopt;
5106 				toh->level = IPPROTO_IPV6;
5107 				toh->name = IPV6_RTHDR;
5108 				toh->len = sizeof (struct T_opthdr) +
5109 				    ipp.ipp_rthdrlen;
5110 				toh->status = 0;
5111 				dstopt += sizeof (struct T_opthdr);
5112 				bcopy(ipp.ipp_rthdr, dstopt, ipp.ipp_rthdrlen);
5113 				dstopt += ipp.ipp_rthdrlen;
5114 				udi_size -= toh->len;
5115 			}
5116 			if (udp->udp_ipv6_recvdstopts &&
5117 			    (ipp.ipp_fields & IPPF_DSTOPTS)) {
5118 				struct T_opthdr *toh;
5119 
5120 				toh = (struct T_opthdr *)dstopt;
5121 				toh->level = IPPROTO_IPV6;
5122 				toh->name = IPV6_DSTOPTS;
5123 				toh->len = sizeof (struct T_opthdr) +
5124 				    ipp.ipp_dstoptslen;
5125 				toh->status = 0;
5126 				dstopt += sizeof (struct T_opthdr);
5127 				bcopy(ipp.ipp_dstopts, dstopt,
5128 				    ipp.ipp_dstoptslen);
5129 				dstopt += ipp.ipp_dstoptslen;
5130 				udi_size -= toh->len;
5131 			}
5132 
5133 			if (cr != NULL) {
5134 				struct T_opthdr *toh;
5135 
5136 				toh = (struct T_opthdr *)dstopt;
5137 				toh->level = SOL_SOCKET;
5138 				toh->name = SCM_UCRED;
5139 				toh->len = sizeof (struct T_opthdr) + ucredsize;
5140 				toh->status = 0;
5141 				(void) cred2ucred(cr, cpid, &toh[1], rcr);
5142 				dstopt += toh->len;
5143 				udi_size -= toh->len;
5144 			}
5145 			/* Consumed all of allocated space */
5146 			ASSERT(udi_size == 0);
5147 		}
5148 #undef	sin6
5149 		/* No IP_RECVDSTADDR for IPv6. */
5150 	}
5151 
5152 	BUMP_MIB(&udp_mib, udpInDatagrams);
5153 	TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
5154 		"udp_rput_end: q %p (%S)", q, "end");
5155 	if (options_mp != NULL)
5156 		freeb(options_mp);
5157 
5158 	if (udp->udp_direct_sockfs) {
5159 		/*
5160 		 * There is nothing above us except for the stream head;
5161 		 * use the read-side synchronous stream interface in
5162 		 * order to reduce the time spent in interrupt thread.
5163 		 */
5164 		ASSERT(udp->udp_issocket);
5165 		udp_rcv_enqueue(UDP_RD(q), udp, mp, mp_len);
5166 	} else {
5167 		/*
5168 		 * Use regular STREAMS interface to pass data upstream
5169 		 * if this is not a socket endpoint, or if we have
5170 		 * switched over to the slow mode due to sockmod being
5171 		 * popped or a module being pushed on top of us.
5172 		 */
5173 		putnext(UDP_RD(q), mp);
5174 	}
5175 	return;
5176 
5177 tossit:
5178 	freemsg(mp);
5179 	if (options_mp != NULL)
5180 		freeb(options_mp);
5181 	BUMP_MIB(&udp_mib, udpInErrors);
5182 }
5183 
5184 void
5185 udp_conn_recv(conn_t *connp, mblk_t *mp)
5186 {
5187 	_UDP_ENTER(connp, mp, udp_input_wrapper, SQTAG_UDP_FANOUT);
5188 }
5189 
5190 /* ARGSUSED */
5191 static void
5192 udp_input_wrapper(void *arg, mblk_t *mp, void *arg2)
5193 {
5194 	udp_input((conn_t *)arg, mp);
5195 	_UDP_EXIT((conn_t *)arg);
5196 }
5197 
5198 /*
5199  * Process non-M_DATA messages as well as M_DATA messages that requires
5200  * modifications to udp_ip_rcv_options i.e. IPv4 packets with IP options.
5201  */
5202 static void
5203 udp_rput_other(queue_t *q, mblk_t *mp)
5204 {
5205 	struct T_unitdata_ind	*tudi;
5206 	mblk_t			*mp1;
5207 	uchar_t			*rptr;
5208 	uchar_t			*new_rptr;
5209 	int			hdr_length;
5210 	int			udi_size;	/* Size of T_unitdata_ind */
5211 	int			opt_len;	/* Length of IP options */
5212 	sin_t			*sin;
5213 	struct T_error_ack	*tea;
5214 	mblk_t			*options_mp = NULL;
5215 	in_pktinfo_t		*pinfo;
5216 	boolean_t		recv_on = B_FALSE;
5217 	cred_t			*cr = NULL;
5218 	udp_t			*udp = Q_TO_UDP(q);
5219 	pid_t			cpid;
5220 	cred_t			*rcr = udp->udp_connp->conn_cred;
5221 
5222 	TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_START,
5223 	    "udp_rput_other: q %p mp %p", q, mp);
5224 
5225 	ASSERT(OK_32PTR(mp->b_rptr));
5226 	rptr = mp->b_rptr;
5227 
5228 	switch (mp->b_datap->db_type) {
5229 	case M_CTL:
5230 		/*
5231 		 * We are here only if IP_RECVSLLA and/or IP_RECVIF are set
5232 		 */
5233 		recv_on = B_TRUE;
5234 		options_mp = mp;
5235 		pinfo = (in_pktinfo_t *)options_mp->b_rptr;
5236 
5237 		/*
5238 		 * The actual data is in mp->b_cont
5239 		 */
5240 		mp = mp->b_cont;
5241 		ASSERT(OK_32PTR(mp->b_rptr));
5242 		rptr = mp->b_rptr;
5243 		break;
5244 	case M_DATA:
5245 		/*
5246 		 * M_DATA messages contain IPv4 datagrams.  They are handled
5247 		 * after this switch.
5248 		 */
5249 		break;
5250 	case M_PROTO:
5251 	case M_PCPROTO:
5252 		/* M_PROTO messages contain some type of TPI message. */
5253 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
5254 		if (mp->b_wptr - rptr < sizeof (t_scalar_t)) {
5255 			freemsg(mp);
5256 			TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
5257 			    "udp_rput_other_end: q %p (%S)", q, "protoshort");
5258 			return;
5259 		}
5260 		tea = (struct T_error_ack *)rptr;
5261 
5262 		switch (tea->PRIM_type) {
5263 		case T_ERROR_ACK:
5264 			switch (tea->ERROR_prim) {
5265 			case O_T_BIND_REQ:
5266 			case T_BIND_REQ: {
5267 				/*
5268 				 * If our O_T_BIND_REQ/T_BIND_REQ fails,
5269 				 * clear out the associated port and source
5270 				 * address before passing the message
5271 				 * upstream. If this was caused by a T_CONN_REQ
5272 				 * revert back to bound state.
5273 				 */
5274 				udp_fanout_t	*udpf;
5275 
5276 				udpf = &udp_bind_fanout[
5277 				    UDP_BIND_HASH(udp->udp_port)];
5278 				mutex_enter(&udpf->uf_lock);
5279 				if (udp->udp_state == TS_DATA_XFER) {
5280 					/* Connect failed */
5281 					tea->ERROR_prim = T_CONN_REQ;
5282 					/* Revert back to the bound source */
5283 					udp->udp_v6src = udp->udp_bound_v6src;
5284 					udp->udp_state = TS_IDLE;
5285 					mutex_exit(&udpf->uf_lock);
5286 					if (udp->udp_family == AF_INET6)
5287 						(void) udp_build_hdrs(q, udp);
5288 					break;
5289 				}
5290 
5291 				if (udp->udp_discon_pending) {
5292 					tea->ERROR_prim = T_DISCON_REQ;
5293 					udp->udp_discon_pending = 0;
5294 				}
5295 				V6_SET_ZERO(udp->udp_v6src);
5296 				V6_SET_ZERO(udp->udp_bound_v6src);
5297 				udp->udp_state = TS_UNBND;
5298 				udp_bind_hash_remove(udp, B_TRUE);
5299 				udp->udp_port = 0;
5300 				mutex_exit(&udpf->uf_lock);
5301 				if (udp->udp_family == AF_INET6)
5302 					(void) udp_build_hdrs(q, udp);
5303 				break;
5304 			}
5305 			default:
5306 				break;
5307 			}
5308 			break;
5309 		case T_BIND_ACK:
5310 			udp_rput_bind_ack(q, mp);
5311 			return;
5312 
5313 		case T_OPTMGMT_ACK:
5314 		case T_OK_ACK:
5315 			break;
5316 		default:
5317 			freemsg(mp);
5318 			return;
5319 		}
5320 		putnext(UDP_RD(q), mp);
5321 		return;
5322 	}
5323 
5324 	/*
5325 	 * This is the inbound data path.
5326 	 * First, we make sure the data contains both IP and UDP headers.
5327 	 *
5328 	 * This handle IPv4 packets for only AF_INET sockets.
5329 	 * AF_INET6 sockets can never access udp_ip_rcv_options thus there
5330 	 * is no need saving the options.
5331 	 */
5332 	ASSERT(IPH_HDR_VERSION((ipha_t *)rptr) == IPV4_VERSION);
5333 	hdr_length = IPH_HDR_LENGTH(rptr) + UDPH_SIZE;
5334 	if (mp->b_wptr - rptr < hdr_length) {
5335 		if (!pullupmsg(mp, hdr_length)) {
5336 			freemsg(mp);
5337 			if (options_mp != NULL)
5338 				freeb(options_mp);
5339 			BUMP_MIB(&udp_mib, udpInErrors);
5340 			TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
5341 			    "udp_rput_other_end: q %p (%S)", q, "hdrshort");
5342 			BUMP_MIB(&udp_mib, udpInErrors);
5343 			return;
5344 		}
5345 		rptr = mp->b_rptr;
5346 	}
5347 	/* Walk past the headers. */
5348 	new_rptr = rptr + hdr_length;
5349 	if (!udp->udp_rcvhdr)
5350 		mp->b_rptr = new_rptr;
5351 
5352 	/* Save the options if any */
5353 	opt_len = hdr_length - (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE);
5354 	if (opt_len > 0) {
5355 		if (opt_len > udp->udp_ip_rcv_options_len) {
5356 			if (udp->udp_ip_rcv_options_len)
5357 				mi_free((char *)udp->udp_ip_rcv_options);
5358 			udp->udp_ip_rcv_options_len = 0;
5359 			udp->udp_ip_rcv_options =
5360 			    (uchar_t *)mi_alloc(opt_len, BPRI_HI);
5361 			if (udp->udp_ip_rcv_options)
5362 				udp->udp_ip_rcv_options_len = opt_len;
5363 		}
5364 		if (udp->udp_ip_rcv_options_len) {
5365 			bcopy(rptr + IP_SIMPLE_HDR_LENGTH,
5366 			    udp->udp_ip_rcv_options, opt_len);
5367 			/* Adjust length if we are resusing the space */
5368 			udp->udp_ip_rcv_options_len = opt_len;
5369 		}
5370 	} else if (udp->udp_ip_rcv_options_len) {
5371 		mi_free((char *)udp->udp_ip_rcv_options);
5372 		udp->udp_ip_rcv_options = NULL;
5373 		udp->udp_ip_rcv_options_len = 0;
5374 	}
5375 
5376 	/*
5377 	 * Normally only send up the address.
5378 	 * If IP_RECVDSTADDR is set we include the destination IP
5379 	 * address as an option. With IP_RECVOPTS we include all
5380 	 * the IP options.
5381 	 */
5382 	udi_size = sizeof (struct T_unitdata_ind) + sizeof (sin_t);
5383 	if (udp->udp_recvdstaddr) {
5384 		udi_size += sizeof (struct T_opthdr) + sizeof (struct in_addr);
5385 		UDP_STAT(udp_in_recvdstaddr);
5386 	}
5387 	if (udp->udp_recvopts && opt_len > 0) {
5388 		udi_size += sizeof (struct T_opthdr) + opt_len;
5389 		UDP_STAT(udp_in_recvopts);
5390 	}
5391 
5392 	/*
5393 	 * If the IP_RECVSLLA or the IP_RECVIF is set then allocate
5394 	 * space accordingly
5395 	 */
5396 	if (udp->udp_recvif && recv_on &&
5397 	    (pinfo->in_pkt_flags & IPF_RECVIF)) {
5398 		udi_size += sizeof (struct T_opthdr) + sizeof (uint_t);
5399 		UDP_STAT(udp_in_recvif);
5400 	}
5401 
5402 	if (udp->udp_recvslla && recv_on &&
5403 	    (pinfo->in_pkt_flags & IPF_RECVSLLA)) {
5404 		udi_size += sizeof (struct T_opthdr) +
5405 		    sizeof (struct sockaddr_dl);
5406 		UDP_STAT(udp_in_recvslla);
5407 	}
5408 
5409 	if (udp->udp_recvucred && (cr = DB_CRED(mp)) != NULL) {
5410 		udi_size += sizeof (struct T_opthdr) + ucredsize;
5411 		cpid = DB_CPID(mp);
5412 		UDP_STAT(udp_in_recvucred);
5413 	}
5414 	/*
5415 	 * If IP_RECVTTL is set allocate the appropriate sized buffer
5416 	 */
5417 	if (udp->udp_recvttl) {
5418 		udi_size += sizeof (struct T_opthdr) + sizeof (uint8_t);
5419 		UDP_STAT(udp_in_recvttl);
5420 	}
5421 
5422 	/* Allocate a message block for the T_UNITDATA_IND structure. */
5423 	mp1 = allocb(udi_size, BPRI_MED);
5424 	if (mp1 == NULL) {
5425 		freemsg(mp);
5426 		if (options_mp != NULL)
5427 			freeb(options_mp);
5428 		TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
5429 			"udp_rput_other_end: q %p (%S)", q, "allocbfail");
5430 		BUMP_MIB(&udp_mib, udpInErrors);
5431 		return;
5432 	}
5433 	mp1->b_cont = mp;
5434 	mp = mp1;
5435 	mp->b_datap->db_type = M_PROTO;
5436 	tudi = (struct T_unitdata_ind *)mp->b_rptr;
5437 	mp->b_wptr = (uchar_t *)tudi + udi_size;
5438 	tudi->PRIM_type = T_UNITDATA_IND;
5439 	tudi->SRC_length = sizeof (sin_t);
5440 	tudi->SRC_offset = sizeof (struct T_unitdata_ind);
5441 	tudi->OPT_offset = sizeof (struct T_unitdata_ind) + sizeof (sin_t);
5442 	udi_size -= (sizeof (struct T_unitdata_ind) + sizeof (sin_t));
5443 	tudi->OPT_length = udi_size;
5444 
5445 	sin = (sin_t *)&tudi[1];
5446 	sin->sin_addr.s_addr = ((ipha_t *)rptr)->ipha_src;
5447 	sin->sin_port =	((in_port_t *)
5448 	    new_rptr)[-(UDPH_SIZE/sizeof (in_port_t))];
5449 	sin->sin_family = AF_INET;
5450 	*(uint32_t *)&sin->sin_zero[0] = 0;
5451 	*(uint32_t *)&sin->sin_zero[4] = 0;
5452 
5453 	/*
5454 	 * Add options if IP_RECVDSTADDR, IP_RECVIF, IP_RECVSLLA or
5455 	 * IP_RECVTTL has been set.
5456 	 */
5457 	if (udi_size != 0) {
5458 		/*
5459 		 * Copy in destination address before options to avoid any
5460 		 * padding issues.
5461 		 */
5462 		char *dstopt;
5463 
5464 		dstopt = (char *)&sin[1];
5465 		if (udp->udp_recvdstaddr) {
5466 			struct T_opthdr *toh;
5467 			ipaddr_t *dstptr;
5468 
5469 			toh = (struct T_opthdr *)dstopt;
5470 			toh->level = IPPROTO_IP;
5471 			toh->name = IP_RECVDSTADDR;
5472 			toh->len = sizeof (struct T_opthdr) + sizeof (ipaddr_t);
5473 			toh->status = 0;
5474 			dstopt += sizeof (struct T_opthdr);
5475 			dstptr = (ipaddr_t *)dstopt;
5476 			*dstptr = (((ipaddr_t *)rptr)[4]);
5477 			dstopt += sizeof (ipaddr_t);
5478 			udi_size -= toh->len;
5479 		}
5480 		if (udp->udp_recvopts && udi_size != 0) {
5481 			struct T_opthdr *toh;
5482 
5483 			toh = (struct T_opthdr *)dstopt;
5484 			toh->level = IPPROTO_IP;
5485 			toh->name = IP_RECVOPTS;
5486 			toh->len = sizeof (struct T_opthdr) + opt_len;
5487 			toh->status = 0;
5488 			dstopt += sizeof (struct T_opthdr);
5489 			bcopy(rptr + IP_SIMPLE_HDR_LENGTH, dstopt, opt_len);
5490 			dstopt += opt_len;
5491 			udi_size -= toh->len;
5492 		}
5493 
5494 		if (udp->udp_recvslla && recv_on &&
5495 		    (pinfo->in_pkt_flags & IPF_RECVSLLA)) {
5496 
5497 			struct T_opthdr *toh;
5498 			struct sockaddr_dl	*dstptr;
5499 
5500 			toh = (struct T_opthdr *)dstopt;
5501 			toh->level = IPPROTO_IP;
5502 			toh->name = IP_RECVSLLA;
5503 			toh->len = sizeof (struct T_opthdr) +
5504 			    sizeof (struct sockaddr_dl);
5505 			toh->status = 0;
5506 			dstopt += sizeof (struct T_opthdr);
5507 			dstptr = (struct sockaddr_dl *)dstopt;
5508 			bcopy(&pinfo->in_pkt_slla, dstptr,
5509 			    sizeof (struct sockaddr_dl));
5510 			dstopt += sizeof (struct sockaddr_dl);
5511 			udi_size -= toh->len;
5512 		}
5513 
5514 		if (udp->udp_recvif && recv_on &&
5515 		    (pinfo->in_pkt_flags & IPF_RECVIF)) {
5516 
5517 			struct T_opthdr *toh;
5518 			uint_t		*dstptr;
5519 
5520 			toh = (struct T_opthdr *)dstopt;
5521 			toh->level = IPPROTO_IP;
5522 			toh->name = IP_RECVIF;
5523 			toh->len = sizeof (struct T_opthdr) +
5524 			    sizeof (uint_t);
5525 			toh->status = 0;
5526 			dstopt += sizeof (struct T_opthdr);
5527 			dstptr = (uint_t *)dstopt;
5528 			*dstptr = pinfo->in_pkt_ifindex;
5529 			dstopt += sizeof (uint_t);
5530 			udi_size -= toh->len;
5531 		}
5532 
5533 		if (cr != NULL) {
5534 			struct T_opthdr *toh;
5535 
5536 			toh = (struct T_opthdr *)dstopt;
5537 			toh->level = SOL_SOCKET;
5538 			toh->name = SCM_UCRED;
5539 			toh->len = sizeof (struct T_opthdr) + ucredsize;
5540 			toh->status = 0;
5541 			(void) cred2ucred(cr, cpid, &toh[1], rcr);
5542 			dstopt += toh->len;
5543 			udi_size -= toh->len;
5544 		}
5545 
5546 		if (udp->udp_recvttl) {
5547 			struct	T_opthdr *toh;
5548 			uint8_t	*dstptr;
5549 
5550 			toh = (struct T_opthdr *)dstopt;
5551 			toh->level = IPPROTO_IP;
5552 			toh->name = IP_RECVTTL;
5553 			toh->len = sizeof (struct T_opthdr) +
5554 			    sizeof (uint8_t);
5555 			toh->status = 0;
5556 			dstopt += sizeof (struct T_opthdr);
5557 			dstptr = (uint8_t *)dstopt;
5558 			*dstptr = ((ipha_t *)rptr)->ipha_ttl;
5559 			dstopt += sizeof (uint8_t);
5560 			udi_size -= toh->len;
5561 		}
5562 
5563 		ASSERT(udi_size == 0);	/* "Consumed" all of allocated space */
5564 	}
5565 	BUMP_MIB(&udp_mib, udpInDatagrams);
5566 	TRACE_2(TR_FAC_UDP, TR_UDP_RPUT_END,
5567 	    "udp_rput_other_end: q %p (%S)", q, "end");
5568 	if (options_mp != NULL)
5569 		freeb(options_mp);
5570 
5571 	if (udp->udp_direct_sockfs) {
5572 		/*
5573 		 * There is nothing above us except for the stream head;
5574 		 * use the read-side synchronous stream interface in
5575 		 * order to reduce the time spent in interrupt thread.
5576 		 */
5577 		ASSERT(udp->udp_issocket);
5578 		udp_rcv_enqueue(UDP_RD(q), udp, mp, msgdsize(mp));
5579 	} else {
5580 		/*
5581 		 * Use regular STREAMS interface to pass data upstream
5582 		 * if this is not a socket endpoint, or if we have
5583 		 * switched over to the slow mode due to sockmod being
5584 		 * popped or a module being pushed on top of us.
5585 		 */
5586 		putnext(UDP_RD(q), mp);
5587 	}
5588 }
5589 
5590 /* ARGSUSED */
5591 static void
5592 udp_rput_other_wrapper(void *arg, mblk_t *mp, void *arg2)
5593 {
5594 	conn_t *connp = arg;
5595 
5596 	udp_rput_other(connp->conn_rq, mp);
5597 	udp_exit(connp);
5598 }
5599 
5600 /*
5601  * Process a T_BIND_ACK
5602  */
5603 static void
5604 udp_rput_bind_ack(queue_t *q, mblk_t *mp)
5605 {
5606 	udp_t	*udp = Q_TO_UDP(q);
5607 	mblk_t	*mp1;
5608 	ire_t	*ire;
5609 	struct T_bind_ack *tba;
5610 	uchar_t *addrp;
5611 	ipa_conn_t	*ac;
5612 	ipa6_conn_t	*ac6;
5613 
5614 	if (udp->udp_discon_pending)
5615 		udp->udp_discon_pending = 0;
5616 
5617 	/*
5618 	 * If a broadcast/multicast address was bound set
5619 	 * the source address to 0.
5620 	 * This ensures no datagrams with broadcast address
5621 	 * as source address are emitted (which would violate
5622 	 * RFC1122 - Hosts requirements)
5623 	 *
5624 	 * Note that when connecting the returned IRE is
5625 	 * for the destination address and we only perform
5626 	 * the broadcast check for the source address (it
5627 	 * is OK to connect to a broadcast/multicast address.)
5628 	 */
5629 	mp1 = mp->b_cont;
5630 	if (mp1 != NULL && mp1->b_datap->db_type == IRE_DB_TYPE) {
5631 		ire = (ire_t *)mp1->b_rptr;
5632 
5633 		/*
5634 		 * Note: we get IRE_BROADCAST for IPv6 to "mark" a multicast
5635 		 * local address.
5636 		 */
5637 		if (ire->ire_type == IRE_BROADCAST &&
5638 		    udp->udp_state != TS_DATA_XFER) {
5639 			/* This was just a local bind to a broadcast addr */
5640 			V6_SET_ZERO(udp->udp_v6src);
5641 			if (udp->udp_family == AF_INET6)
5642 				(void) udp_build_hdrs(q, udp);
5643 		} else if (V6_OR_V4_INADDR_ANY(udp->udp_v6src)) {
5644 			/*
5645 			 * Local address not yet set - pick it from the
5646 			 * T_bind_ack
5647 			 */
5648 			tba = (struct T_bind_ack *)mp->b_rptr;
5649 			addrp = &mp->b_rptr[tba->ADDR_offset];
5650 			switch (udp->udp_family) {
5651 			case AF_INET:
5652 				if (tba->ADDR_length == sizeof (ipa_conn_t)) {
5653 					ac = (ipa_conn_t *)addrp;
5654 				} else {
5655 					ASSERT(tba->ADDR_length ==
5656 					    sizeof (ipa_conn_x_t));
5657 					ac = &((ipa_conn_x_t *)addrp)->acx_conn;
5658 				}
5659 				IN6_IPADDR_TO_V4MAPPED(ac->ac_laddr,
5660 				    &udp->udp_v6src);
5661 				break;
5662 			case AF_INET6:
5663 				if (tba->ADDR_length == sizeof (ipa6_conn_t)) {
5664 					ac6 = (ipa6_conn_t *)addrp;
5665 				} else {
5666 					ASSERT(tba->ADDR_length ==
5667 					    sizeof (ipa6_conn_x_t));
5668 					ac6 = &((ipa6_conn_x_t *)
5669 					    addrp)->ac6x_conn;
5670 				}
5671 				udp->udp_v6src = ac6->ac6_laddr;
5672 				(void) udp_build_hdrs(q, udp);
5673 				break;
5674 			}
5675 		}
5676 		mp1 = mp1->b_cont;
5677 	}
5678 	/*
5679 	 * Look for one or more appended ACK message added by
5680 	 * udp_connect or udp_disconnect.
5681 	 * If none found just send up the T_BIND_ACK.
5682 	 * udp_connect has appended a T_OK_ACK and a T_CONN_CON.
5683 	 * udp_disconnect has appended a T_OK_ACK.
5684 	 */
5685 	if (mp1 != NULL) {
5686 		if (mp->b_cont == mp1)
5687 			mp->b_cont = NULL;
5688 		else {
5689 			ASSERT(mp->b_cont->b_cont == mp1);
5690 			mp->b_cont->b_cont = NULL;
5691 		}
5692 		freemsg(mp);
5693 		mp = mp1;
5694 		while (mp != NULL) {
5695 			mp1 = mp->b_cont;
5696 			mp->b_cont = NULL;
5697 			putnext(UDP_RD(q), mp);
5698 			mp = mp1;
5699 		}
5700 		return;
5701 	}
5702 	freemsg(mp->b_cont);
5703 	mp->b_cont = NULL;
5704 	putnext(UDP_RD(q), mp);
5705 }
5706 
5707 /*
5708  * return SNMP stuff in buffer in mpdata
5709  */
5710 int
5711 udp_snmp_get(queue_t *q, mblk_t *mpctl)
5712 {
5713 	mblk_t			*mpdata;
5714 	mblk_t			*mp_conn_ctl;
5715 	mblk_t			*mp_attr_ctl;
5716 	mblk_t			*mp6_conn_ctl;
5717 	mblk_t			*mp6_attr_ctl;
5718 	mblk_t			*mp_conn_tail;
5719 	mblk_t			*mp_attr_tail;
5720 	mblk_t			*mp6_conn_tail;
5721 	mblk_t			*mp6_attr_tail;
5722 	struct opthdr		*optp;
5723 	mib2_udpEntry_t		ude;
5724 	mib2_udp6Entry_t	ude6;
5725 	mib2_transportMLPEntry_t mlp;
5726 	int			state;
5727 	zoneid_t		zoneid;
5728 	int			i;
5729 	connf_t			*connfp;
5730 	conn_t			*connp = Q_TO_CONN(q);
5731 	udp_t			*udp = connp->conn_udp;
5732 	int			v4_conn_idx;
5733 	int			v6_conn_idx;
5734 	boolean_t		needattr;
5735 
5736 	mp_conn_ctl = mp_attr_ctl = mp6_conn_ctl = NULL;
5737 	if (mpctl == NULL ||
5738 	    (mpdata = mpctl->b_cont) == NULL ||
5739 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
5740 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
5741 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
5742 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
5743 		freemsg(mp_conn_ctl);
5744 		freemsg(mp_attr_ctl);
5745 		freemsg(mp6_conn_ctl);
5746 		return (0);
5747 	}
5748 
5749 	zoneid = connp->conn_zoneid;
5750 
5751 	/* fixed length structure for IPv4 and IPv6 counters */
5752 	SET_MIB(udp_mib.udpEntrySize, sizeof (mib2_udpEntry_t));
5753 	SET_MIB(udp_mib.udp6EntrySize, sizeof (mib2_udp6Entry_t));
5754 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
5755 	optp->level = MIB2_UDP;
5756 	optp->name = 0;
5757 	(void) snmp_append_data(mpdata, (char *)&udp_mib, sizeof (udp_mib));
5758 	optp->len = msgdsize(mpdata);
5759 	qreply(q, mpctl);
5760 
5761 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
5762 	v4_conn_idx = v6_conn_idx = 0;
5763 
5764 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
5765 		connfp = &ipcl_globalhash_fanout[i];
5766 		connp = NULL;
5767 
5768 		while ((connp = ipcl_get_next_conn(connfp, connp,
5769 		    IPCL_UDP))) {
5770 			udp = connp->conn_udp;
5771 			if (zoneid != connp->conn_zoneid)
5772 				continue;
5773 
5774 			/*
5775 			 * Note that the port numbers are sent in
5776 			 * host byte order
5777 			 */
5778 
5779 			if (udp->udp_state == TS_UNBND)
5780 				state = MIB2_UDP_unbound;
5781 			else if (udp->udp_state == TS_IDLE)
5782 				state = MIB2_UDP_idle;
5783 			else if (udp->udp_state == TS_DATA_XFER)
5784 				state = MIB2_UDP_connected;
5785 			else
5786 				state = MIB2_UDP_unknown;
5787 
5788 			needattr = B_FALSE;
5789 			bzero(&mlp, sizeof (mlp));
5790 			if (connp->conn_mlp_type != mlptSingle) {
5791 				if (connp->conn_mlp_type == mlptShared ||
5792 				    connp->conn_mlp_type == mlptBoth)
5793 					mlp.tme_flags |= MIB2_TMEF_SHARED;
5794 				if (connp->conn_mlp_type == mlptPrivate ||
5795 				    connp->conn_mlp_type == mlptBoth)
5796 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
5797 				needattr = B_TRUE;
5798 			}
5799 
5800 			/*
5801 			 * Create an IPv4 table entry for IPv4 entries and also
5802 			 * any IPv6 entries which are bound to in6addr_any
5803 			 * (i.e. anything a IPv4 peer could connect/send to).
5804 			 */
5805 			if (udp->udp_ipversion == IPV4_VERSION ||
5806 			    (udp->udp_state <= TS_IDLE &&
5807 			    IN6_IS_ADDR_UNSPECIFIED(&udp->udp_v6src))) {
5808 				ude.udpEntryInfo.ue_state = state;
5809 				/*
5810 				 * If in6addr_any this will set it to
5811 				 * INADDR_ANY
5812 				 */
5813 				ude.udpLocalAddress =
5814 				    V4_PART_OF_V6(udp->udp_v6src);
5815 				ude.udpLocalPort = ntohs(udp->udp_port);
5816 				if (udp->udp_state == TS_DATA_XFER) {
5817 					/*
5818 					 * Can potentially get here for
5819 					 * v6 socket if another process
5820 					 * (say, ping) has just done a
5821 					 * sendto(), changing the state
5822 					 * from the TS_IDLE above to
5823 					 * TS_DATA_XFER by the time we hit
5824 					 * this part of the code.
5825 					 */
5826 					ude.udpEntryInfo.ue_RemoteAddress =
5827 					    V4_PART_OF_V6(udp->udp_v6dst);
5828 					ude.udpEntryInfo.ue_RemotePort =
5829 					    ntohs(udp->udp_dstport);
5830 				} else {
5831 					ude.udpEntryInfo.ue_RemoteAddress = 0;
5832 					ude.udpEntryInfo.ue_RemotePort = 0;
5833 				}
5834 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
5835 				    &mp_conn_tail, (char *)&ude, sizeof (ude));
5836 				mlp.tme_connidx = v4_conn_idx++;
5837 				if (needattr)
5838 					(void) snmp_append_data2(
5839 					    mp_attr_ctl->b_cont, &mp_attr_tail,
5840 					    (char *)&mlp, sizeof (mlp));
5841 			}
5842 			if (udp->udp_ipversion == IPV6_VERSION) {
5843 				ude6.udp6EntryInfo.ue_state  = state;
5844 				ude6.udp6LocalAddress = udp->udp_v6src;
5845 				ude6.udp6LocalPort = ntohs(udp->udp_port);
5846 				ude6.udp6IfIndex = udp->udp_bound_if;
5847 				if (udp->udp_state == TS_DATA_XFER) {
5848 					ude6.udp6EntryInfo.ue_RemoteAddress =
5849 					    udp->udp_v6dst;
5850 					ude6.udp6EntryInfo.ue_RemotePort =
5851 					    ntohs(udp->udp_dstport);
5852 				} else {
5853 					ude6.udp6EntryInfo.ue_RemoteAddress =
5854 					    sin6_null.sin6_addr;
5855 					ude6.udp6EntryInfo.ue_RemotePort = 0;
5856 				}
5857 				(void) snmp_append_data2(mp6_conn_ctl->b_cont,
5858 				    &mp6_conn_tail, (char *)&ude6,
5859 				    sizeof (ude6));
5860 				mlp.tme_connidx = v6_conn_idx++;
5861 				if (needattr)
5862 					(void) snmp_append_data2(
5863 					    mp6_attr_ctl->b_cont,
5864 					    &mp6_attr_tail, (char *)&mlp,
5865 					    sizeof (mlp));
5866 			}
5867 		}
5868 	}
5869 
5870 	/* IPv4 UDP endpoints */
5871 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
5872 	    sizeof (struct T_optmgmt_ack)];
5873 	optp->level = MIB2_UDP;
5874 	optp->name = MIB2_UDP_ENTRY;
5875 	optp->len = msgdsize(mp_conn_ctl->b_cont);
5876 	qreply(q, mp_conn_ctl);
5877 
5878 	/* table of MLP attributes... */
5879 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
5880 	    sizeof (struct T_optmgmt_ack)];
5881 	optp->level = MIB2_UDP;
5882 	optp->name = EXPER_XPORT_MLP;
5883 	optp->len = msgdsize(mp_attr_ctl->b_cont);
5884 	if (optp->len == 0)
5885 		freemsg(mp_attr_ctl);
5886 	else
5887 		qreply(q, mp_attr_ctl);
5888 
5889 	/* IPv6 UDP endpoints */
5890 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
5891 	    sizeof (struct T_optmgmt_ack)];
5892 	optp->level = MIB2_UDP6;
5893 	optp->name = MIB2_UDP6_ENTRY;
5894 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
5895 	qreply(q, mp6_conn_ctl);
5896 
5897 	/* table of MLP attributes... */
5898 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
5899 	    sizeof (struct T_optmgmt_ack)];
5900 	optp->level = MIB2_UDP6;
5901 	optp->name = EXPER_XPORT_MLP;
5902 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
5903 	if (optp->len == 0)
5904 		freemsg(mp6_attr_ctl);
5905 	else
5906 		qreply(q, mp6_attr_ctl);
5907 
5908 	return (1);
5909 }
5910 
5911 /*
5912  * Return 0 if invalid set request, 1 otherwise, including non-udp requests.
5913  * NOTE: Per MIB-II, UDP has no writable data.
5914  * TODO:  If this ever actually tries to set anything, it needs to be
5915  * to do the appropriate locking.
5916  */
5917 /* ARGSUSED */
5918 int
5919 udp_snmp_set(queue_t *q, t_scalar_t level, t_scalar_t name,
5920     uchar_t *ptr, int len)
5921 {
5922 	switch (level) {
5923 	case MIB2_UDP:
5924 		return (0);
5925 	default:
5926 		return (1);
5927 	}
5928 }
5929 
5930 static void
5931 udp_report_item(mblk_t *mp, udp_t *udp)
5932 {
5933 	char *state;
5934 	char addrbuf1[INET6_ADDRSTRLEN];
5935 	char addrbuf2[INET6_ADDRSTRLEN];
5936 	uint_t print_len, buf_len;
5937 
5938 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
5939 	ASSERT(buf_len >= 0);
5940 	if (buf_len == 0)
5941 		return;
5942 
5943 	if (udp->udp_state == TS_UNBND)
5944 		state = "UNBOUND";
5945 	else if (udp->udp_state == TS_IDLE)
5946 		state = "IDLE";
5947 	else if (udp->udp_state == TS_DATA_XFER)
5948 		state = "CONNECTED";
5949 	else
5950 		state = "UnkState";
5951 	print_len = snprintf((char *)mp->b_wptr, buf_len,
5952 	    MI_COL_PTRFMT_STR "%4d %5u %s %s %5u %s\n",
5953 	    (void *)udp, udp->udp_connp->conn_zoneid, ntohs(udp->udp_port),
5954 	    inet_ntop(AF_INET6, &udp->udp_v6src,
5955 		addrbuf1, sizeof (addrbuf1)),
5956 	    inet_ntop(AF_INET6, &udp->udp_v6dst,
5957 		addrbuf2, sizeof (addrbuf2)),
5958 	    ntohs(udp->udp_dstport), state);
5959 	if (print_len < buf_len) {
5960 		mp->b_wptr += print_len;
5961 	} else {
5962 		mp->b_wptr += buf_len;
5963 	}
5964 }
5965 
5966 /* Report for ndd "udp_status" */
5967 /* ARGSUSED */
5968 static int
5969 udp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
5970 {
5971 	zoneid_t zoneid;
5972 	connf_t	*connfp;
5973 	conn_t	*connp = Q_TO_CONN(q);
5974 	udp_t	*udp = connp->conn_udp;
5975 	int	i;
5976 
5977 	/*
5978 	 * Because of the ndd constraint, at most we can have 64K buffer
5979 	 * to put in all UDP info.  So to be more efficient, just
5980 	 * allocate a 64K buffer here, assuming we need that large buffer.
5981 	 * This may be a problem as any user can read udp_status.  Therefore
5982 	 * we limit the rate of doing this using udp_ndd_get_info_interval.
5983 	 * This should be OK as normal users should not do this too often.
5984 	 */
5985 	if (cr == NULL || secpolicy_net_config(cr, B_TRUE) != 0) {
5986 		if (ddi_get_lbolt() - udp_last_ndd_get_info_time <
5987 		    drv_usectohz(udp_ndd_get_info_interval * 1000)) {
5988 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
5989 			return (0);
5990 		}
5991 	}
5992 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
5993 		/* The following may work even if we cannot get a large buf. */
5994 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
5995 		return (0);
5996 	}
5997 	(void) mi_mpprintf(mp,
5998 	    "UDP     " MI_COL_HDRPAD_STR
5999 	/*   12345678[89ABCDEF] */
6000 	    " zone lport src addr        dest addr       port  state");
6001 	/*    1234 12345 xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx 12345 UNBOUND */
6002 
6003 	zoneid = connp->conn_zoneid;
6004 
6005 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
6006 		connfp = &ipcl_globalhash_fanout[i];
6007 		connp = NULL;
6008 
6009 		while ((connp = ipcl_get_next_conn(connfp, connp,
6010 		    IPCL_UDP))) {
6011 			udp = connp->conn_udp;
6012 			if (zoneid != GLOBAL_ZONEID &&
6013 			    zoneid != connp->conn_zoneid)
6014 				continue;
6015 
6016 			udp_report_item(mp->b_cont, udp);
6017 		}
6018 	}
6019 	udp_last_ndd_get_info_time = ddi_get_lbolt();
6020 	return (0);
6021 }
6022 
6023 /*
6024  * This routine creates a T_UDERROR_IND message and passes it upstream.
6025  * The address and options are copied from the T_UNITDATA_REQ message
6026  * passed in mp.  This message is freed.
6027  */
6028 static void
6029 udp_ud_err(queue_t *q, mblk_t *mp, uchar_t *destaddr, t_scalar_t destlen,
6030     t_scalar_t err)
6031 {
6032 	struct T_unitdata_req *tudr;
6033 	mblk_t	*mp1;
6034 	uchar_t	*optaddr;
6035 	t_scalar_t optlen;
6036 
6037 	if (DB_TYPE(mp) == M_DATA) {
6038 		ASSERT(destaddr != NULL && destlen != 0);
6039 		optaddr = NULL;
6040 		optlen = 0;
6041 	} else {
6042 		if ((mp->b_wptr < mp->b_rptr) ||
6043 		    (MBLKL(mp)) < sizeof (struct T_unitdata_req)) {
6044 			goto done;
6045 		}
6046 		tudr = (struct T_unitdata_req *)mp->b_rptr;
6047 		destaddr = mp->b_rptr + tudr->DEST_offset;
6048 		if (destaddr < mp->b_rptr || destaddr >= mp->b_wptr ||
6049 		    destaddr + tudr->DEST_length < mp->b_rptr ||
6050 		    destaddr + tudr->DEST_length > mp->b_wptr) {
6051 			goto done;
6052 		}
6053 		optaddr = mp->b_rptr + tudr->OPT_offset;
6054 		if (optaddr < mp->b_rptr || optaddr >= mp->b_wptr ||
6055 		    optaddr + tudr->OPT_length < mp->b_rptr ||
6056 		    optaddr + tudr->OPT_length > mp->b_wptr) {
6057 			goto done;
6058 		}
6059 		destlen = tudr->DEST_length;
6060 		optlen = tudr->OPT_length;
6061 	}
6062 
6063 	mp1 = mi_tpi_uderror_ind((char *)destaddr, destlen,
6064 	    (char *)optaddr, optlen, err);
6065 	if (mp1 != NULL)
6066 		putnext(UDP_RD(q), mp1);
6067 
6068 done:
6069 	freemsg(mp);
6070 }
6071 
6072 /*
6073  * This routine removes a port number association from a stream.  It
6074  * is called by udp_wput to handle T_UNBIND_REQ messages.
6075  */
6076 static void
6077 udp_unbind(queue_t *q, mblk_t *mp)
6078 {
6079 	udp_t *udp = Q_TO_UDP(q);
6080 
6081 	/* If a bind has not been done, we can't unbind. */
6082 	if (udp->udp_state == TS_UNBND) {
6083 		udp_err_ack(q, mp, TOUTSTATE, 0);
6084 		return;
6085 	}
6086 	if (cl_inet_unbind != NULL) {
6087 		/*
6088 		 * Running in cluster mode - register unbind information
6089 		 */
6090 		if (udp->udp_ipversion == IPV4_VERSION) {
6091 			(*cl_inet_unbind)(IPPROTO_UDP, AF_INET,
6092 			    (uint8_t *)(&V4_PART_OF_V6(udp->udp_v6src)),
6093 			    (in_port_t)udp->udp_port);
6094 		} else {
6095 			(*cl_inet_unbind)(IPPROTO_UDP, AF_INET6,
6096 			    (uint8_t *)&(udp->udp_v6src),
6097 			    (in_port_t)udp->udp_port);
6098 		}
6099 	}
6100 
6101 	udp_bind_hash_remove(udp, B_FALSE);
6102 	V6_SET_ZERO(udp->udp_v6src);
6103 	V6_SET_ZERO(udp->udp_bound_v6src);
6104 	udp->udp_port = 0;
6105 	udp->udp_state = TS_UNBND;
6106 
6107 	if (udp->udp_family == AF_INET6) {
6108 		int error;
6109 
6110 		/* Rebuild the header template */
6111 		error = udp_build_hdrs(q, udp);
6112 		if (error != 0) {
6113 			udp_err_ack(q, mp, TSYSERR, error);
6114 			return;
6115 		}
6116 	}
6117 	/*
6118 	 * Pass the unbind to IP; T_UNBIND_REQ is larger than T_OK_ACK
6119 	 * and therefore ip_unbind must never return NULL.
6120 	 */
6121 	mp = ip_unbind(q, mp);
6122 	ASSERT(mp != NULL);
6123 	putnext(UDP_RD(q), mp);
6124 }
6125 
6126 /*
6127  * Don't let port fall into the privileged range.
6128  * Since the extra privileged ports can be arbitrary we also
6129  * ensure that we exclude those from consideration.
6130  * udp_g_epriv_ports is not sorted thus we loop over it until
6131  * there are no changes.
6132  */
6133 static in_port_t
6134 udp_update_next_port(udp_t *udp, in_port_t port, boolean_t random)
6135 {
6136 	int i;
6137 	in_port_t nextport;
6138 	boolean_t restart = B_FALSE;
6139 
6140 	if (random && udp_random_anon_port != 0) {
6141 		(void) random_get_pseudo_bytes((uint8_t *)&port,
6142 		    sizeof (in_port_t));
6143 		/*
6144 		 * Unless changed by a sys admin, the smallest anon port
6145 		 * is 32768 and the largest anon port is 65535.  It is
6146 		 * very likely (50%) for the random port to be smaller
6147 		 * than the smallest anon port.  When that happens,
6148 		 * add port % (anon port range) to the smallest anon
6149 		 * port to get the random port.  It should fall into the
6150 		 * valid anon port range.
6151 		 */
6152 		if (port < udp_smallest_anon_port) {
6153 			port = udp_smallest_anon_port +
6154 			    port % (udp_largest_anon_port -
6155 			    udp_smallest_anon_port);
6156 		}
6157 	}
6158 
6159 retry:
6160 	if (port < udp_smallest_anon_port)
6161 		port = udp_smallest_anon_port;
6162 
6163 	if (port > udp_largest_anon_port) {
6164 		port = udp_smallest_anon_port;
6165 		if (restart)
6166 			return (0);
6167 		restart = B_TRUE;
6168 	}
6169 
6170 	if (port < udp_smallest_nonpriv_port)
6171 		port = udp_smallest_nonpriv_port;
6172 
6173 	for (i = 0; i < udp_g_num_epriv_ports; i++) {
6174 		if (port == udp_g_epriv_ports[i]) {
6175 			port++;
6176 			/*
6177 			 * Make sure that the port is in the
6178 			 * valid range.
6179 			 */
6180 			goto retry;
6181 		}
6182 	}
6183 
6184 	if (is_system_labeled() &&
6185 	    (nextport = tsol_next_port(crgetzone(udp->udp_connp->conn_cred),
6186 	    port, IPPROTO_UDP, B_TRUE)) != 0) {
6187 		port = nextport;
6188 		goto retry;
6189 	}
6190 
6191 	return (port);
6192 }
6193 
6194 static int
6195 udp_update_label(queue_t *wq, mblk_t *mp, ipaddr_t dst)
6196 {
6197 	int err;
6198 	uchar_t opt_storage[IP_MAX_OPT_LENGTH];
6199 	udp_t *udp = Q_TO_UDP(wq);
6200 
6201 	err = tsol_compute_label(DB_CREDDEF(mp, udp->udp_connp->conn_cred), dst,
6202 	    opt_storage, udp->udp_mac_exempt);
6203 	if (err == 0) {
6204 		err = tsol_update_options(&udp->udp_ip_snd_options,
6205 		    &udp->udp_ip_snd_options_len, &udp->udp_label_len,
6206 		    opt_storage);
6207 	}
6208 	if (err != 0) {
6209 		DTRACE_PROBE4(
6210 		    tx__ip__log__info__updatelabel__udp,
6211 		    char *, "queue(1) failed to update options(2) on mp(3)",
6212 		    queue_t *, wq, char *, opt_storage, mblk_t *, mp);
6213 	} else {
6214 		IN6_IPADDR_TO_V4MAPPED(dst, &udp->udp_v6lastdst);
6215 	}
6216 	return (err);
6217 }
6218 
6219 static mblk_t *
6220 udp_output_v4(conn_t *connp, mblk_t *mp, ipaddr_t v4dst, uint16_t port,
6221     uint_t srcid, int *error)
6222 {
6223 	udp_t	*udp = connp->conn_udp;
6224 	queue_t	*q = connp->conn_wq;
6225 	mblk_t	*mp1 = mp;
6226 	mblk_t	*mp2;
6227 	ipha_t	*ipha;
6228 	int	ip_hdr_length;
6229 	uint32_t ip_len;
6230 	udpha_t	*udpha;
6231 	udpattrs_t	attrs;
6232 	uchar_t	ip_snd_opt[IP_MAX_OPT_LENGTH];
6233 	uint32_t	ip_snd_opt_len = 0;
6234 
6235 	*error = 0;
6236 
6237 	if (v4dst == INADDR_ANY)
6238 		v4dst = htonl(INADDR_LOOPBACK);
6239 
6240 	/*
6241 	 * If options passed in, feed it for verification and handling
6242 	 */
6243 	attrs.udpattr_credset = B_FALSE;
6244 	if (DB_TYPE(mp) != M_DATA) {
6245 		mp1 = mp->b_cont;
6246 		if (((struct T_unitdata_req *)mp->b_rptr)->OPT_length != 0) {
6247 			attrs.udpattr_ipp = NULL;
6248 			attrs.udpattr_mb = mp;
6249 			if (udp_unitdata_opt_process(q, mp, error, &attrs) < 0)
6250 				goto done;
6251 			/*
6252 			 * Note: success in processing options.
6253 			 * mp option buffer represented by
6254 			 * OPT_length/offset now potentially modified
6255 			 * and contain option setting results
6256 			 */
6257 			ASSERT(*error == 0);
6258 		}
6259 	}
6260 
6261 	/* mp1 points to the M_DATA mblk carrying the packet */
6262 	ASSERT(mp1 != NULL && DB_TYPE(mp1) == M_DATA);
6263 
6264 	/*
6265 	 * Check if our saved options are valid; update if not
6266 	 * TSOL Note: Since we are not in WRITER mode, UDP packets
6267 	 * to different destination may require different labels.
6268 	 * We use conn_lock to ensure that lastdst, ip_snd_options,
6269 	 * and ip_snd_options_len are consistent for the current
6270 	 * destination and are updated atomically.
6271 	 */
6272 	mutex_enter(&connp->conn_lock);
6273 	if (is_system_labeled()) {
6274 		/* Using UDP MLP requires SCM_UCRED from user */
6275 		if (connp->conn_mlp_type != mlptSingle &&
6276 		    !attrs.udpattr_credset) {
6277 			mutex_exit(&connp->conn_lock);
6278 			DTRACE_PROBE4(
6279 			    tx__ip__log__info__output__udp,
6280 			    char *, "MLP mp(1) lacks SCM_UCRED attr(2) on q(3)",
6281 			    mblk_t *, mp1, udpattrs_t *, &attrs, queue_t *, q);
6282 			*error = ECONNREFUSED;
6283 			goto done;
6284 		}
6285 		if ((!IN6_IS_ADDR_V4MAPPED(&udp->udp_v6lastdst) ||
6286 		    V4_PART_OF_V6(udp->udp_v6lastdst) != v4dst) &&
6287 		    (*error = udp_update_label(q, mp, v4dst)) != 0) {
6288 			mutex_exit(&connp->conn_lock);
6289 			goto done;
6290 		}
6291 	}
6292 	if (udp->udp_ip_snd_options_len > 0) {
6293 		ip_snd_opt_len = udp->udp_ip_snd_options_len;
6294 		bcopy(udp->udp_ip_snd_options, ip_snd_opt, ip_snd_opt_len);
6295 	}
6296 	mutex_exit(&connp->conn_lock);
6297 
6298 	/* Add an IP header */
6299 	ip_hdr_length = IP_SIMPLE_HDR_LENGTH + UDPH_SIZE + ip_snd_opt_len;
6300 	ipha = (ipha_t *)&mp1->b_rptr[-ip_hdr_length];
6301 	if (DB_REF(mp1) != 1 || (uchar_t *)ipha < DB_BASE(mp1) ||
6302 	    !OK_32PTR(ipha)) {
6303 		mp2 = allocb(ip_hdr_length + udp_wroff_extra, BPRI_LO);
6304 		if (mp2 == NULL) {
6305 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6306 			    "udp_wput_end: q %p (%S)", q, "allocbfail2");
6307 			*error = ENOMEM;
6308 			goto done;
6309 		}
6310 		mp2->b_wptr = DB_LIM(mp2);
6311 		mp2->b_cont = mp1;
6312 		mp1 = mp2;
6313 		if (DB_TYPE(mp) != M_DATA)
6314 			mp->b_cont = mp1;
6315 		else
6316 			mp = mp1;
6317 
6318 		ipha = (ipha_t *)(mp1->b_wptr - ip_hdr_length);
6319 	}
6320 	ip_hdr_length -= UDPH_SIZE;
6321 #ifdef	_BIG_ENDIAN
6322 	/* Set version, header length, and tos */
6323 	*(uint16_t *)&ipha->ipha_version_and_hdr_length =
6324 	    ((((IP_VERSION << 4) | (ip_hdr_length>>2)) << 8) |
6325 		udp->udp_type_of_service);
6326 	/* Set ttl and protocol */
6327 	*(uint16_t *)&ipha->ipha_ttl = (udp->udp_ttl << 8) | IPPROTO_UDP;
6328 #else
6329 	/* Set version, header length, and tos */
6330 	*(uint16_t *)&ipha->ipha_version_and_hdr_length =
6331 		((udp->udp_type_of_service << 8) |
6332 		    ((IP_VERSION << 4) | (ip_hdr_length>>2)));
6333 	/* Set ttl and protocol */
6334 	*(uint16_t *)&ipha->ipha_ttl = (IPPROTO_UDP << 8) | udp->udp_ttl;
6335 #endif
6336 	/*
6337 	 * Copy our address into the packet.  If this is zero,
6338 	 * first look at __sin6_src_id for a hint. If we leave the source
6339 	 * as INADDR_ANY then ip will fill in the real source address.
6340 	 */
6341 	IN6_V4MAPPED_TO_IPADDR(&udp->udp_v6src, ipha->ipha_src);
6342 	if (srcid != 0 && ipha->ipha_src == INADDR_ANY) {
6343 		in6_addr_t v6src;
6344 
6345 		ip_srcid_find_id(srcid, &v6src, connp->conn_zoneid);
6346 		IN6_V4MAPPED_TO_IPADDR(&v6src, ipha->ipha_src);
6347 	}
6348 
6349 	ipha->ipha_fragment_offset_and_flags = 0;
6350 	ipha->ipha_ident = 0;
6351 
6352 	mp1->b_rptr = (uchar_t *)ipha;
6353 
6354 	ASSERT((uintptr_t)(mp1->b_wptr - (uchar_t *)ipha) <=
6355 	    (uintptr_t)UINT_MAX);
6356 
6357 	/* Determine length of packet */
6358 	ip_len = (uint32_t)(mp1->b_wptr - (uchar_t *)ipha);
6359 	if ((mp2 = mp1->b_cont) != NULL) {
6360 		do {
6361 			ASSERT((uintptr_t)MBLKL(mp2) <= (uintptr_t)UINT_MAX);
6362 			ip_len += (uint32_t)MBLKL(mp2);
6363 		} while ((mp2 = mp2->b_cont) != NULL);
6364 	}
6365 	/*
6366 	 * If the size of the packet is greater than the maximum allowed by
6367 	 * ip, return an error. Passing this down could cause panics because
6368 	 * the size will have wrapped and be inconsistent with the msg size.
6369 	 */
6370 	if (ip_len > IP_MAXPACKET) {
6371 		TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6372 		    "udp_wput_end: q %p (%S)", q, "IP length exceeded");
6373 		*error = EMSGSIZE;
6374 		goto done;
6375 	}
6376 	ipha->ipha_length = htons((uint16_t)ip_len);
6377 	ip_len -= ip_hdr_length;
6378 	ip_len = htons((uint16_t)ip_len);
6379 	udpha = (udpha_t *)(((uchar_t *)ipha) + ip_hdr_length);
6380 
6381 	/*
6382 	 * Copy in the destination address
6383 	 */
6384 	ipha->ipha_dst = v4dst;
6385 
6386 	/*
6387 	 * Set ttl based on IP_MULTICAST_TTL to match IPv6 logic.
6388 	 */
6389 	if (CLASSD(v4dst))
6390 		ipha->ipha_ttl = udp->udp_multicast_ttl;
6391 
6392 	udpha->uha_dst_port = port;
6393 	udpha->uha_src_port = udp->udp_port;
6394 
6395 	if (ip_hdr_length > IP_SIMPLE_HDR_LENGTH) {
6396 		uint32_t	cksum;
6397 
6398 		bcopy(ip_snd_opt, &ipha[1], ip_snd_opt_len);
6399 		/*
6400 		 * Massage source route putting first source route in ipha_dst.
6401 		 * Ignore the destination in T_unitdata_req.
6402 		 * Create a checksum adjustment for a source route, if any.
6403 		 */
6404 		cksum = ip_massage_options(ipha);
6405 		cksum = (cksum & 0xFFFF) + (cksum >> 16);
6406 		cksum -= ((ipha->ipha_dst >> 16) & 0xFFFF) +
6407 		    (ipha->ipha_dst & 0xFFFF);
6408 		if ((int)cksum < 0)
6409 			cksum--;
6410 		cksum = (cksum & 0xFFFF) + (cksum >> 16);
6411 		/*
6412 		 * IP does the checksum if uha_checksum is non-zero,
6413 		 * We make it easy for IP to include our pseudo header
6414 		 * by putting our length in uha_checksum.
6415 		 */
6416 		cksum += ip_len;
6417 		cksum = (cksum & 0xFFFF) + (cksum >> 16);
6418 		/* There might be a carry. */
6419 		cksum = (cksum & 0xFFFF) + (cksum >> 16);
6420 #ifdef _LITTLE_ENDIAN
6421 		if (udp_do_checksum)
6422 			ip_len = (cksum << 16) | ip_len;
6423 #else
6424 		if (udp_do_checksum)
6425 			ip_len = (ip_len << 16) | cksum;
6426 		else
6427 			ip_len <<= 16;
6428 #endif
6429 	} else {
6430 		/*
6431 		 * IP does the checksum if uha_checksum is non-zero,
6432 		 * We make it easy for IP to include our pseudo header
6433 		 * by putting our length in uha_checksum.
6434 		 */
6435 		if (udp_do_checksum)
6436 			ip_len |= (ip_len << 16);
6437 #ifndef _LITTLE_ENDIAN
6438 		else
6439 			ip_len <<= 16;
6440 #endif
6441 	}
6442 	/* Set UDP length and checksum */
6443 	*((uint32_t *)&udpha->uha_length) = ip_len;
6444 	if (DB_CRED(mp) != NULL)
6445 		mblk_setcred(mp1, DB_CRED(mp));
6446 
6447 	if (DB_TYPE(mp) != M_DATA) {
6448 		ASSERT(mp != mp1);
6449 		freeb(mp);
6450 	}
6451 
6452 	/* mp has been consumed and we'll return success */
6453 	ASSERT(*error == 0);
6454 	mp = NULL;
6455 
6456 	/* We're done.  Pass the packet to ip. */
6457 	BUMP_MIB(&udp_mib, udpOutDatagrams);
6458 	TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6459 		"udp_wput_end: q %p (%S)", q, "end");
6460 
6461 	if ((connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
6462 	    CONN_OUTBOUND_POLICY_PRESENT(connp) ||
6463 	    connp->conn_dontroute || connp->conn_xmit_if_ill != NULL ||
6464 	    connp->conn_nofailover_ill != NULL ||
6465 	    connp->conn_outgoing_ill != NULL ||
6466 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
6467 	    IPP_ENABLED(IPP_LOCAL_OUT) || ip_g_mrouter != NULL) {
6468 		UDP_STAT(udp_ip_send);
6469 		ip_output(connp, mp1, connp->conn_wq, IP_WPUT);
6470 	} else {
6471 		udp_send_data(udp, connp->conn_wq, mp1, ipha);
6472 	}
6473 
6474 done:
6475 	if (*error != 0) {
6476 		ASSERT(mp != NULL);
6477 		BUMP_MIB(&udp_mib, udpOutErrors);
6478 	}
6479 	return (mp);
6480 }
6481 
6482 static void
6483 udp_send_data(udp_t *udp, queue_t *q, mblk_t *mp, ipha_t *ipha)
6484 {
6485 	conn_t	*connp = udp->udp_connp;
6486 	ipaddr_t src, dst;
6487 	ill_t	*ill;
6488 	ire_t	*ire;
6489 	ipif_t	*ipif = NULL;
6490 	mblk_t	*ire_fp_mp;
6491 	uint_t	ire_fp_mp_len;
6492 	uint16_t *up;
6493 	uint32_t cksum, hcksum_txflags;
6494 	queue_t	*dev_q;
6495 	boolean_t retry_caching;
6496 
6497 	dst = ipha->ipha_dst;
6498 	src = ipha->ipha_src;
6499 	ASSERT(ipha->ipha_ident == 0);
6500 
6501 	if (CLASSD(dst)) {
6502 		int err;
6503 
6504 		ipif = conn_get_held_ipif(connp,
6505 		    &connp->conn_multicast_ipif, &err);
6506 
6507 		if (ipif == NULL || ipif->ipif_isv6 ||
6508 		    (ipif->ipif_ill->ill_phyint->phyint_flags &
6509 		    PHYI_LOOPBACK)) {
6510 			if (ipif != NULL)
6511 				ipif_refrele(ipif);
6512 			UDP_STAT(udp_ip_send);
6513 			ip_output(connp, mp, q, IP_WPUT);
6514 			return;
6515 		}
6516 	}
6517 
6518 	retry_caching = B_FALSE;
6519 	mutex_enter(&connp->conn_lock);
6520 	ire = connp->conn_ire_cache;
6521 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
6522 
6523 	if (ire == NULL || ire->ire_addr != dst ||
6524 	    (ire->ire_marks & IRE_MARK_CONDEMNED)) {
6525 		retry_caching = B_TRUE;
6526 	} else if (CLASSD(dst) && (ire->ire_type & IRE_CACHE)) {
6527 		ill_t *stq_ill = (ill_t *)ire->ire_stq->q_ptr;
6528 
6529 		ASSERT(ipif != NULL);
6530 		if (stq_ill != ipif->ipif_ill && (stq_ill->ill_group == NULL ||
6531 		    stq_ill->ill_group != ipif->ipif_ill->ill_group))
6532 			retry_caching = B_TRUE;
6533 	}
6534 
6535 	if (!retry_caching) {
6536 		ASSERT(ire != NULL);
6537 		IRE_REFHOLD(ire);
6538 		mutex_exit(&connp->conn_lock);
6539 	} else {
6540 		boolean_t cached = B_FALSE;
6541 
6542 		connp->conn_ire_cache = NULL;
6543 		mutex_exit(&connp->conn_lock);
6544 
6545 		/* Release the old ire */
6546 		if (ire != NULL) {
6547 			IRE_REFRELE_NOTR(ire);
6548 			ire = NULL;
6549 		}
6550 
6551 		if (CLASSD(dst)) {
6552 			ASSERT(ipif != NULL);
6553 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
6554 			    connp->conn_zoneid, MBLK_GETLABEL(mp),
6555 			    MATCH_IRE_ILL_GROUP);
6556 		} else {
6557 			ASSERT(ipif == NULL);
6558 			ire = ire_cache_lookup(dst, connp->conn_zoneid,
6559 			    MBLK_GETLABEL(mp));
6560 		}
6561 
6562 		if (ire == NULL) {
6563 			if (ipif != NULL)
6564 				ipif_refrele(ipif);
6565 			UDP_STAT(udp_ire_null);
6566 			ip_output(connp, mp, q, IP_WPUT);
6567 			return;
6568 		}
6569 		IRE_REFHOLD_NOTR(ire);
6570 
6571 		mutex_enter(&connp->conn_lock);
6572 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
6573 		    connp->conn_ire_cache == NULL) {
6574 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
6575 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
6576 				connp->conn_ire_cache = ire;
6577 				cached = B_TRUE;
6578 			}
6579 			rw_exit(&ire->ire_bucket->irb_lock);
6580 		}
6581 		mutex_exit(&connp->conn_lock);
6582 
6583 		/*
6584 		 * We can continue to use the ire but since it was not
6585 		 * cached, we should drop the extra reference.
6586 		 */
6587 		if (!cached)
6588 			IRE_REFRELE_NOTR(ire);
6589 	}
6590 	ASSERT(ire != NULL && ire->ire_ipversion == IPV4_VERSION);
6591 	ASSERT(!CLASSD(dst) || ipif != NULL);
6592 
6593 	/*
6594 	 * Check if we can take the fast-path.
6595 	 * Note that "incomplete" ire's (where the link-layer for next hop
6596 	 * is not resolved, or where the fast-path header in nce_fp_mp is not
6597 	 * available yet) are sent down the legacy (slow) path
6598 	 */
6599 	if ((ire->ire_type & (IRE_BROADCAST|IRE_LOCAL|IRE_LOOPBACK)) ||
6600 	    (ire->ire_flags & RTF_MULTIRT) || ire->ire_stq == NULL ||
6601 	    ire->ire_max_frag < ntohs(ipha->ipha_length) ||
6602 	    (ire->ire_nce != NULL &&
6603 	    (ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
6604 	    (connp->conn_nexthop_set) ||
6605 	    (ire_fp_mp_len = MBLKL(ire_fp_mp)) > MBLKHEAD(mp)) {
6606 		if (ipif != NULL)
6607 			ipif_refrele(ipif);
6608 		UDP_STAT(udp_ip_ire_send);
6609 		IRE_REFRELE(ire);
6610 		ip_output(connp, mp, q, IP_WPUT);
6611 		return;
6612 	}
6613 
6614 	BUMP_MIB(&ip_mib, ipOutRequests);
6615 
6616 	ill = ire_to_ill(ire);
6617 	ASSERT(ill != NULL);
6618 
6619 	dev_q = ire->ire_stq->q_next;
6620 	ASSERT(dev_q != NULL);
6621 	/*
6622 	 * If the service thread is already running, or if the driver
6623 	 * queue is currently flow-controlled, queue this packet.
6624 	 */
6625 	if ((q->q_first != NULL || connp->conn_draining) ||
6626 	    ((dev_q->q_next || dev_q->q_first) && !canput(dev_q))) {
6627 		if (ip_output_queue) {
6628 			(void) putq(q, mp);
6629 		} else {
6630 			BUMP_MIB(&ip_mib, ipOutDiscards);
6631 			freemsg(mp);
6632 		}
6633 		if (ipif != NULL)
6634 			ipif_refrele(ipif);
6635 		IRE_REFRELE(ire);
6636 		return;
6637 	}
6638 
6639 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
6640 #ifndef _BIG_ENDIAN
6641 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
6642 #endif
6643 
6644 	if (src == INADDR_ANY && !connp->conn_unspec_src) {
6645 		if (CLASSD(dst) && !(ire->ire_flags & RTF_SETSRC))
6646 			src = ipha->ipha_src = ipif->ipif_src_addr;
6647 		else
6648 			src = ipha->ipha_src = ire->ire_src_addr;
6649 	}
6650 
6651 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
6652 		ASSERT(ill->ill_hcksum_capab != NULL);
6653 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
6654 	} else {
6655 		hcksum_txflags = 0;
6656 	}
6657 
6658 	/* pseudo-header checksum (do it in parts for IP header checksum) */
6659 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
6660 
6661 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
6662 	up = IPH_UDPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
6663 	if (*up != 0) {
6664 		IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags,
6665 		    mp, ipha, up, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
6666 		    ntohs(ipha->ipha_length), cksum);
6667 
6668 		/* Software checksum? */
6669 		if (DB_CKSUMFLAGS(mp) == 0) {
6670 			UDP_STAT(udp_out_sw_cksum);
6671 			UDP_STAT_UPDATE(udp_out_sw_cksum_bytes,
6672 			    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
6673 		}
6674 	}
6675 
6676 	ipha->ipha_fragment_offset_and_flags |=
6677 	    (uint32_t)htons(ire->ire_frag_flag);
6678 
6679 	/* Calculate IP header checksum if hardware isn't capable */
6680 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
6681 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
6682 		    ((uint16_t *)ipha)[4]);
6683 	}
6684 
6685 	if (CLASSD(dst)) {
6686 		ilm_t *ilm;
6687 
6688 		ILM_WALKER_HOLD(ill);
6689 		ilm = ilm_lookup_ill(ill, dst, ALL_ZONES);
6690 		ILM_WALKER_RELE(ill);
6691 		if (ilm != NULL) {
6692 			ip_multicast_loopback(q, ill, mp,
6693 			    connp->conn_multicast_loop ? 0 :
6694 			    IP_FF_NO_MCAST_LOOP, connp->conn_zoneid);
6695 		}
6696 
6697 		/* If multicast TTL is 0 then we are done */
6698 		if (ipha->ipha_ttl == 0) {
6699 			if (ipif != NULL)
6700 				ipif_refrele(ipif);
6701 			freemsg(mp);
6702 			IRE_REFRELE(ire);
6703 			return;
6704 		}
6705 	}
6706 
6707 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
6708 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
6709 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
6710 
6711 	UPDATE_OB_PKT_COUNT(ire);
6712 	ire->ire_last_used_time = lbolt;
6713 
6714 	if (ILL_DLS_CAPABLE(ill)) {
6715 		/*
6716 		 * Send the packet directly to DLD, where it may be queued
6717 		 * depending on the availability of transmit resources at
6718 		 * the media layer.
6719 		 */
6720 		IP_DLS_ILL_TX(ill, mp);
6721 	} else {
6722 		putnext(ire->ire_stq, mp);
6723 	}
6724 
6725 	if (ipif != NULL)
6726 		ipif_refrele(ipif);
6727 	IRE_REFRELE(ire);
6728 }
6729 
6730 static boolean_t
6731 udp_update_label_v6(queue_t *wq, mblk_t *mp, in6_addr_t *dst)
6732 {
6733 	udp_t *udp = Q_TO_UDP(wq);
6734 	int err;
6735 	uchar_t opt_storage[TSOL_MAX_IPV6_OPTION];
6736 
6737 	err = tsol_compute_label_v6(DB_CREDDEF(mp, udp->udp_connp->conn_cred),
6738 	    dst, opt_storage, udp->udp_mac_exempt);
6739 	if (err == 0) {
6740 		err = tsol_update_sticky(&udp->udp_sticky_ipp,
6741 		    &udp->udp_label_len_v6, opt_storage);
6742 	}
6743 	if (err != 0) {
6744 		DTRACE_PROBE4(
6745 		    tx__ip__log__drop__updatelabel__udp6,
6746 		    char *, "queue(1) failed to update options(2) on mp(3)",
6747 		    queue_t *, wq, char *, opt_storage, mblk_t *, mp);
6748 	} else {
6749 		udp->udp_v6lastdst = *dst;
6750 	}
6751 	return (err);
6752 }
6753 
6754 /*
6755  * This routine handles all messages passed downstream.  It either
6756  * consumes the message or passes it downstream; it never queues a
6757  * a message.
6758  */
6759 static void
6760 udp_output(conn_t *connp, mblk_t *mp, struct sockaddr *addr, socklen_t addrlen)
6761 {
6762 	sin6_t		*sin6;
6763 	sin_t		*sin;
6764 	ipaddr_t	v4dst;
6765 	uint16_t	port;
6766 	uint_t		srcid;
6767 	queue_t		*q = connp->conn_wq;
6768 	udp_t		*udp = connp->conn_udp;
6769 	int		error = 0;
6770 	struct sockaddr_storage ss;
6771 
6772 	TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_START,
6773 	    "udp_wput_start: connp %p mp %p", connp, mp);
6774 
6775 	/*
6776 	 * We directly handle several cases here: T_UNITDATA_REQ message
6777 	 * coming down as M_PROTO/M_PCPROTO and M_DATA messages for both
6778 	 * connected and non-connected socket.  The latter carries the
6779 	 * address structure along when this routine gets called.
6780 	 */
6781 	switch (DB_TYPE(mp)) {
6782 	case M_DATA:
6783 		if (!udp->udp_direct_sockfs || udp->udp_state != TS_DATA_XFER) {
6784 			if (!udp->udp_direct_sockfs ||
6785 			    addr == NULL || addrlen == 0) {
6786 				/* Not connected; address is required */
6787 				BUMP_MIB(&udp_mib, udpOutErrors);
6788 				UDP_STAT(udp_out_err_notconn);
6789 				freemsg(mp);
6790 				TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6791 				    "udp_wput_end: connp %p (%S)", connp,
6792 				    "not-connected; address required");
6793 				return;
6794 			}
6795 			ASSERT(udp->udp_issocket);
6796 			UDP_DBGSTAT(udp_data_notconn);
6797 			/* Not connected; do some more checks below */
6798 			break;
6799 		}
6800 		/* M_DATA for connected socket */
6801 		UDP_DBGSTAT(udp_data_conn);
6802 		IN6_V4MAPPED_TO_IPADDR(&udp->udp_v6dst, v4dst);
6803 
6804 		/* Initialize addr and addrlen as if they're passed in */
6805 		if (udp->udp_family == AF_INET) {
6806 			sin = (sin_t *)&ss;
6807 			sin->sin_family = AF_INET;
6808 			sin->sin_port = udp->udp_dstport;
6809 			sin->sin_addr.s_addr = v4dst;
6810 			addr = (struct sockaddr *)sin;
6811 			addrlen = sizeof (*sin);
6812 		} else {
6813 			sin6 = (sin6_t *)&ss;
6814 			sin6->sin6_family = AF_INET6;
6815 			sin6->sin6_port = udp->udp_dstport;
6816 			sin6->sin6_flowinfo = udp->udp_flowinfo;
6817 			sin6->sin6_addr = udp->udp_v6dst;
6818 			sin6->sin6_scope_id = 0;
6819 			sin6->__sin6_src_id = 0;
6820 			addr = (struct sockaddr *)sin6;
6821 			addrlen = sizeof (*sin6);
6822 		}
6823 
6824 		if (udp->udp_family == AF_INET ||
6825 		    IN6_IS_ADDR_V4MAPPED(&udp->udp_v6dst)) {
6826 			/*
6827 			 * Handle both AF_INET and AF_INET6; the latter
6828 			 * for IPV4 mapped destination addresses.  Note
6829 			 * here that both addr and addrlen point to the
6830 			 * corresponding struct depending on the address
6831 			 * family of the socket.
6832 			 */
6833 			mp = udp_output_v4(connp, mp, v4dst,
6834 			    udp->udp_dstport, 0, &error);
6835 		} else {
6836 			mp = udp_output_v6(connp, mp, sin6, &error);
6837 		}
6838 		if (error != 0) {
6839 			ASSERT(addr != NULL && addrlen != 0);
6840 			goto ud_error;
6841 		}
6842 		return;
6843 	case M_PROTO:
6844 	case M_PCPROTO: {
6845 		struct T_unitdata_req *tudr;
6846 
6847 		ASSERT((uintptr_t)MBLKL(mp) <= (uintptr_t)INT_MAX);
6848 		tudr = (struct T_unitdata_req *)mp->b_rptr;
6849 
6850 		/* Handle valid T_UNITDATA_REQ here */
6851 		if (MBLKL(mp) >= sizeof (*tudr) &&
6852 		    ((t_primp_t)mp->b_rptr)->type == T_UNITDATA_REQ) {
6853 			if (mp->b_cont == NULL) {
6854 				TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6855 				    "udp_wput_end: q %p (%S)", q, "badaddr");
6856 				error = EPROTO;
6857 				goto ud_error;
6858 			}
6859 
6860 			if (!MBLKIN(mp, 0, tudr->DEST_offset +
6861 			    tudr->DEST_length)) {
6862 				TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6863 				    "udp_wput_end: q %p (%S)", q, "badaddr");
6864 				error = EADDRNOTAVAIL;
6865 				goto ud_error;
6866 			}
6867 			/*
6868 			 * If a port has not been bound to the stream, fail.
6869 			 * This is not a problem when sockfs is directly
6870 			 * above us, because it will ensure that the socket
6871 			 * is first bound before allowing data to be sent.
6872 			 */
6873 			if (udp->udp_state == TS_UNBND) {
6874 				TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6875 				    "udp_wput_end: q %p (%S)", q, "outstate");
6876 				error = EPROTO;
6877 				goto ud_error;
6878 			}
6879 			addr = (struct sockaddr *)
6880 			    &mp->b_rptr[tudr->DEST_offset];
6881 			addrlen = tudr->DEST_length;
6882 			if (tudr->OPT_length != 0)
6883 				UDP_STAT(udp_out_opt);
6884 			break;
6885 		}
6886 		/* FALLTHRU */
6887 	}
6888 	default:
6889 		udp_become_writer(connp, mp, udp_wput_other_wrapper,
6890 		    SQTAG_UDP_OUTPUT);
6891 		return;
6892 	}
6893 	ASSERT(addr != NULL);
6894 
6895 	switch (udp->udp_family) {
6896 	case AF_INET6:
6897 		sin6 = (sin6_t *)addr;
6898 		if (!OK_32PTR((char *)sin6) || addrlen != sizeof (sin6_t) ||
6899 		    sin6->sin6_family != AF_INET6) {
6900 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6901 			    "udp_wput_end: q %p (%S)", q, "badaddr");
6902 			error = EADDRNOTAVAIL;
6903 			goto ud_error;
6904 		}
6905 
6906 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6907 			/*
6908 			 * Destination is a non-IPv4-compatible IPv6 address.
6909 			 * Send out an IPv6 format packet.
6910 			 */
6911 			mp = udp_output_v6(connp, mp, sin6, &error);
6912 			if (error != 0)
6913 				goto ud_error;
6914 
6915 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6916 			    "udp_wput_end: q %p (%S)", q, "udp_output_v6");
6917 			return;
6918 		}
6919 		/*
6920 		 * If the local address is not zero or a mapped address
6921 		 * return an error.  It would be possible to send an IPv4
6922 		 * packet but the response would never make it back to the
6923 		 * application since it is bound to a non-mapped address.
6924 		 */
6925 		if (!IN6_IS_ADDR_V4MAPPED(&udp->udp_v6src) &&
6926 		    !IN6_IS_ADDR_UNSPECIFIED(&udp->udp_v6src)) {
6927 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6928 			    "udp_wput_end: q %p (%S)", q, "badaddr");
6929 			error = EADDRNOTAVAIL;
6930 			goto ud_error;
6931 		}
6932 		/* Send IPv4 packet without modifying udp_ipversion */
6933 		/* Extract port and ipaddr */
6934 		port = sin6->sin6_port;
6935 		IN6_V4MAPPED_TO_IPADDR(&sin6->sin6_addr, v4dst);
6936 		srcid = sin6->__sin6_src_id;
6937 		break;
6938 
6939 	case AF_INET:
6940 		sin = (sin_t *)addr;
6941 		if (!OK_32PTR((char *)sin) || addrlen != sizeof (sin_t) ||
6942 		    sin->sin_family != AF_INET) {
6943 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_END,
6944 			    "udp_wput_end: q %p (%S)", q, "badaddr");
6945 			error = EADDRNOTAVAIL;
6946 			goto ud_error;
6947 		}
6948 		/* Extract port and ipaddr */
6949 		port = sin->sin_port;
6950 		v4dst = sin->sin_addr.s_addr;
6951 		srcid = 0;
6952 		break;
6953 	}
6954 
6955 	mp = udp_output_v4(connp, mp, v4dst, port, srcid, &error);
6956 	if (error != 0) {
6957 ud_error:
6958 		UDP_STAT(udp_out_err_output);
6959 		ASSERT(mp != NULL);
6960 		/* mp is freed by the following routine */
6961 		udp_ud_err(q, mp, (uchar_t *)addr, (t_scalar_t)addrlen,
6962 		    (t_scalar_t)error);
6963 	}
6964 }
6965 
6966 /* ARGSUSED */
6967 static void
6968 udp_output_wrapper(void *arg, mblk_t *mp, void *arg2)
6969 {
6970 	udp_output((conn_t *)arg, mp, NULL, 0);
6971 	_UDP_EXIT((conn_t *)arg);
6972 }
6973 
6974 static void
6975 udp_wput(queue_t *q, mblk_t *mp)
6976 {
6977 	_UDP_ENTER(Q_TO_CONN(UDP_WR(q)), mp, udp_output_wrapper,
6978 	    SQTAG_UDP_WPUT);
6979 }
6980 
6981 /*
6982  * Allocate and prepare a T_UNITDATA_REQ message.
6983  */
6984 static mblk_t *
6985 udp_tudr_alloc(struct sockaddr *addr, socklen_t addrlen)
6986 {
6987 	struct T_unitdata_req *tudr;
6988 	mblk_t *mp;
6989 
6990 	mp = allocb(sizeof (*tudr) + addrlen, BPRI_MED);
6991 	if (mp != NULL) {
6992 		mp->b_wptr += sizeof (*tudr) + addrlen;
6993 		DB_TYPE(mp) = M_PROTO;
6994 
6995 		tudr = (struct T_unitdata_req *)mp->b_rptr;
6996 		tudr->PRIM_type = T_UNITDATA_REQ;
6997 		tudr->DEST_length = addrlen;
6998 		tudr->DEST_offset = (t_scalar_t)sizeof (*tudr);
6999 		tudr->OPT_length = 0;
7000 		tudr->OPT_offset = 0;
7001 		bcopy(addr, tudr+1, addrlen);
7002 	}
7003 	return (mp);
7004 }
7005 
7006 /*
7007  * Entry point for sockfs when udp is in "direct sockfs" mode.  This mode
7008  * is valid when we are directly beneath the stream head, and thus sockfs
7009  * is able to bypass STREAMS and directly call us, passing along the sockaddr
7010  * structure without the cumbersome T_UNITDATA_REQ interface.  Note that
7011  * this is done for both connected and non-connected endpoint.
7012  */
7013 void
7014 udp_wput_data(queue_t *q, mblk_t *mp, struct sockaddr *addr, socklen_t addrlen)
7015 {
7016 	conn_t	*connp;
7017 	udp_t	*udp;
7018 
7019 	q = UDP_WR(q);
7020 	connp = Q_TO_CONN(q);
7021 	udp = connp->conn_udp;
7022 
7023 	/* udpsockfs should only send down M_DATA for this entry point */
7024 	ASSERT(DB_TYPE(mp) == M_DATA);
7025 
7026 	mutex_enter(&connp->conn_lock);
7027 	UDP_MODE_ASSERTIONS(udp, UDP_ENTER);
7028 
7029 	if (udp->udp_mode != UDP_MT_HOT) {
7030 		/*
7031 		 * We can't enter this conn right away because another
7032 		 * thread is currently executing as writer; therefore we
7033 		 * need to deposit the message into the squeue to be
7034 		 * drained later.  If a socket address is present, we
7035 		 * need to create a T_UNITDATA_REQ message as placeholder.
7036 		 */
7037 		if (addr != NULL && addrlen != 0) {
7038 			mblk_t *tudr_mp = udp_tudr_alloc(addr, addrlen);
7039 
7040 			if (tudr_mp == NULL) {
7041 				mutex_exit(&connp->conn_lock);
7042 				BUMP_MIB(&udp_mib, udpOutErrors);
7043 				UDP_STAT(udp_out_err_tudr);
7044 				freemsg(mp);
7045 				return;
7046 			}
7047 			/* Tag the packet with T_UNITDATA_REQ */
7048 			tudr_mp->b_cont = mp;
7049 			mp = tudr_mp;
7050 		}
7051 		mutex_exit(&connp->conn_lock);
7052 		udp_enter(connp, mp, udp_output_wrapper, SQTAG_UDP_WPUT);
7053 		return;
7054 	}
7055 
7056 	/* We can execute as reader right away. */
7057 	UDP_READERS_INCREF(udp);
7058 	mutex_exit(&connp->conn_lock);
7059 
7060 	udp_output(connp, mp, addr, addrlen);
7061 
7062 	udp_exit(connp);
7063 }
7064 
7065 /*
7066  * udp_output_v6():
7067  * Assumes that udp_wput did some sanity checking on the destination
7068  * address.
7069  */
7070 static mblk_t *
7071 udp_output_v6(conn_t *connp, mblk_t *mp, sin6_t *sin6, int *error)
7072 {
7073 	ip6_t		*ip6h;
7074 	ip6i_t		*ip6i;	/* mp1->b_rptr even if no ip6i_t */
7075 	mblk_t		*mp1 = mp;
7076 	mblk_t		*mp2;
7077 	int		udp_ip_hdr_len = IPV6_HDR_LEN + UDPH_SIZE;
7078 	size_t		ip_len;
7079 	udpha_t		*udph;
7080 	udp_t		*udp = connp->conn_udp;
7081 	queue_t		*q = connp->conn_wq;
7082 	ip6_pkt_t	ipp_s;	/* For ancillary data options */
7083 	ip6_pkt_t	*ipp = &ipp_s;
7084 	ip6_pkt_t	*tipp;	/* temporary ipp */
7085 	uint32_t	csum = 0;
7086 	uint_t		ignore = 0;
7087 	uint_t		option_exists = 0, is_sticky = 0;
7088 	uint8_t		*cp;
7089 	uint8_t		*nxthdr_ptr;
7090 	in6_addr_t	ip6_dst;
7091 	udpattrs_t	attrs;
7092 	boolean_t	opt_present;
7093 	ip6_hbh_t	*hopoptsptr = NULL;
7094 	uint_t		hopoptslen = 0;
7095 	boolean_t	is_ancillary = B_FALSE;
7096 
7097 	*error = 0;
7098 
7099 	/*
7100 	 * If the local address is a mapped address return
7101 	 * an error.
7102 	 * It would be possible to send an IPv6 packet but the
7103 	 * response would never make it back to the application
7104 	 * since it is bound to a mapped address.
7105 	 */
7106 	if (IN6_IS_ADDR_V4MAPPED(&udp->udp_v6src)) {
7107 		*error = EADDRNOTAVAIL;
7108 		goto done;
7109 	}
7110 
7111 	ipp->ipp_fields = 0;
7112 	ipp->ipp_sticky_ignored = 0;
7113 
7114 	/*
7115 	 * If TPI options passed in, feed it for verification and handling
7116 	 */
7117 	attrs.udpattr_credset = B_FALSE;
7118 	opt_present = B_FALSE;
7119 	if (DB_TYPE(mp) != M_DATA) {
7120 		mp1 = mp->b_cont;
7121 		if (((struct T_unitdata_req *)mp->b_rptr)->OPT_length != 0) {
7122 			attrs.udpattr_ipp = ipp;
7123 			attrs.udpattr_mb = mp;
7124 			if (udp_unitdata_opt_process(q, mp, error, &attrs) < 0)
7125 				goto done;
7126 			ASSERT(*error == 0);
7127 			opt_present = B_TRUE;
7128 		}
7129 	}
7130 	ignore = ipp->ipp_sticky_ignored;
7131 
7132 	/* mp1 points to the M_DATA mblk carrying the packet */
7133 	ASSERT(mp1 != NULL && DB_TYPE(mp1) == M_DATA);
7134 
7135 	if (sin6->sin6_scope_id != 0 &&
7136 	    IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
7137 		/*
7138 		 * IPPF_SCOPE_ID is special.  It's neither a sticky
7139 		 * option nor ancillary data.  It needs to be
7140 		 * explicitly set in options_exists.
7141 		 */
7142 		option_exists |= IPPF_SCOPE_ID;
7143 	}
7144 
7145 	/*
7146 	 * Compute the destination address
7147 	 */
7148 	ip6_dst = sin6->sin6_addr;
7149 	if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
7150 		ip6_dst = ipv6_loopback;
7151 
7152 	/*
7153 	 * If we're not going to the same destination as last time, then
7154 	 * recompute the label required.  This is done in a separate routine to
7155 	 * avoid blowing up our stack here.
7156 	 *
7157 	 * TSOL Note: Since we are not in WRITER mode, UDP packets
7158 	 * to different destination may require different labels.
7159 	 * We use conn_lock to ensure that lastdst, sticky ipp_hopopts,
7160 	 * and sticky ipp_hopoptslen are consistent for the current
7161 	 * destination and are updated atomically.
7162 	 */
7163 	mutex_enter(&connp->conn_lock);
7164 	if (is_system_labeled()) {
7165 		/* Using UDP MLP requires SCM_UCRED from user */
7166 		if (connp->conn_mlp_type != mlptSingle &&
7167 		    !attrs.udpattr_credset) {
7168 			DTRACE_PROBE4(
7169 			    tx__ip__log__info__output__udp6,
7170 			    char *, "MLP mp(1) lacks SCM_UCRED attr(2) on q(3)",
7171 			    mblk_t *, mp1, udpattrs_t *, &attrs, queue_t *, q);
7172 			*error = ECONNREFUSED;
7173 			mutex_exit(&connp->conn_lock);
7174 			goto done;
7175 		}
7176 		if ((opt_present ||
7177 		    !IN6_ARE_ADDR_EQUAL(&udp->udp_v6lastdst, &ip6_dst)) &&
7178 		    (*error = udp_update_label_v6(q, mp, &ip6_dst)) != 0) {
7179 			mutex_exit(&connp->conn_lock);
7180 			goto done;
7181 		}
7182 	}
7183 
7184 	/*
7185 	 * If there's a security label here, then we ignore any options the
7186 	 * user may try to set.  We keep the peer's label as a hidden sticky
7187 	 * option. We make a private copy of this label before releasing the
7188 	 * lock so that label is kept consistent with the destination addr.
7189 	 */
7190 	if (udp->udp_label_len_v6 > 0) {
7191 		ignore &= ~IPPF_HOPOPTS;
7192 		ipp->ipp_fields &= ~IPPF_HOPOPTS;
7193 	}
7194 
7195 	if ((udp->udp_sticky_ipp.ipp_fields == 0) && (ipp->ipp_fields == 0)) {
7196 		/* No sticky options nor ancillary data. */
7197 		mutex_exit(&connp->conn_lock);
7198 		goto no_options;
7199 	}
7200 
7201 	/*
7202 	 * Go through the options figuring out where each is going to
7203 	 * come from and build two masks.  The first mask indicates if
7204 	 * the option exists at all.  The second mask indicates if the
7205 	 * option is sticky or ancillary.
7206 	 */
7207 	if (!(ignore & IPPF_HOPOPTS)) {
7208 		if (ipp->ipp_fields & IPPF_HOPOPTS) {
7209 			option_exists |= IPPF_HOPOPTS;
7210 			udp_ip_hdr_len += ipp->ipp_hopoptslen;
7211 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_HOPOPTS) {
7212 			option_exists |= IPPF_HOPOPTS;
7213 			is_sticky |= IPPF_HOPOPTS;
7214 			ASSERT(udp->udp_sticky_ipp.ipp_hopoptslen != 0);
7215 			hopoptsptr = kmem_alloc(
7216 			    udp->udp_sticky_ipp.ipp_hopoptslen, KM_NOSLEEP);
7217 			if (hopoptsptr == NULL) {
7218 				*error = ENOMEM;
7219 				mutex_exit(&connp->conn_lock);
7220 				goto done;
7221 			}
7222 			hopoptslen = udp->udp_sticky_ipp.ipp_hopoptslen;
7223 			bcopy(udp->udp_sticky_ipp.ipp_hopopts, hopoptsptr,
7224 			    hopoptslen);
7225 			udp_ip_hdr_len += hopoptslen;
7226 		}
7227 	}
7228 	mutex_exit(&connp->conn_lock);
7229 
7230 	if (!(ignore & IPPF_RTHDR)) {
7231 		if (ipp->ipp_fields & IPPF_RTHDR) {
7232 			option_exists |= IPPF_RTHDR;
7233 			udp_ip_hdr_len += ipp->ipp_rthdrlen;
7234 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_RTHDR) {
7235 			option_exists |= IPPF_RTHDR;
7236 			is_sticky |= IPPF_RTHDR;
7237 			udp_ip_hdr_len += udp->udp_sticky_ipp.ipp_rthdrlen;
7238 		}
7239 	}
7240 
7241 	if (!(ignore & IPPF_RTDSTOPTS) && (option_exists & IPPF_RTHDR)) {
7242 		if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
7243 			option_exists |= IPPF_RTDSTOPTS;
7244 			udp_ip_hdr_len += ipp->ipp_rtdstoptslen;
7245 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_RTDSTOPTS) {
7246 			option_exists |= IPPF_RTDSTOPTS;
7247 			is_sticky |= IPPF_RTDSTOPTS;
7248 			udp_ip_hdr_len += udp->udp_sticky_ipp.ipp_rtdstoptslen;
7249 		}
7250 	}
7251 
7252 	if (!(ignore & IPPF_DSTOPTS)) {
7253 		if (ipp->ipp_fields & IPPF_DSTOPTS) {
7254 			option_exists |= IPPF_DSTOPTS;
7255 			udp_ip_hdr_len += ipp->ipp_dstoptslen;
7256 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_DSTOPTS) {
7257 			option_exists |= IPPF_DSTOPTS;
7258 			is_sticky |= IPPF_DSTOPTS;
7259 			udp_ip_hdr_len += udp->udp_sticky_ipp.ipp_dstoptslen;
7260 		}
7261 	}
7262 
7263 	if (!(ignore & IPPF_IFINDEX)) {
7264 		if (ipp->ipp_fields & IPPF_IFINDEX) {
7265 			option_exists |= IPPF_IFINDEX;
7266 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_IFINDEX) {
7267 			option_exists |= IPPF_IFINDEX;
7268 			is_sticky |= IPPF_IFINDEX;
7269 		}
7270 	}
7271 
7272 	if (!(ignore & IPPF_ADDR)) {
7273 		if (ipp->ipp_fields & IPPF_ADDR) {
7274 			option_exists |= IPPF_ADDR;
7275 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_ADDR) {
7276 			option_exists |= IPPF_ADDR;
7277 			is_sticky |= IPPF_ADDR;
7278 		}
7279 	}
7280 
7281 	if (!(ignore & IPPF_DONTFRAG)) {
7282 		if (ipp->ipp_fields & IPPF_DONTFRAG) {
7283 			option_exists |= IPPF_DONTFRAG;
7284 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_DONTFRAG) {
7285 			option_exists |= IPPF_DONTFRAG;
7286 			is_sticky |= IPPF_DONTFRAG;
7287 		}
7288 	}
7289 
7290 	if (!(ignore & IPPF_USE_MIN_MTU)) {
7291 		if (ipp->ipp_fields & IPPF_USE_MIN_MTU) {
7292 			option_exists |= IPPF_USE_MIN_MTU;
7293 		} else if (udp->udp_sticky_ipp.ipp_fields &
7294 		    IPPF_USE_MIN_MTU) {
7295 			option_exists |= IPPF_USE_MIN_MTU;
7296 			is_sticky |= IPPF_USE_MIN_MTU;
7297 		}
7298 	}
7299 
7300 	if (!(ignore & IPPF_HOPLIMIT) && (ipp->ipp_fields & IPPF_HOPLIMIT))
7301 		option_exists |= IPPF_HOPLIMIT;
7302 	/* IPV6_HOPLIMIT can never be sticky */
7303 	ASSERT(!(udp->udp_sticky_ipp.ipp_fields & IPPF_HOPLIMIT));
7304 
7305 	if (!(ignore & IPPF_UNICAST_HOPS) &&
7306 	    (udp->udp_sticky_ipp.ipp_fields & IPPF_UNICAST_HOPS)) {
7307 		option_exists |= IPPF_UNICAST_HOPS;
7308 		is_sticky |= IPPF_UNICAST_HOPS;
7309 	}
7310 
7311 	if (!(ignore & IPPF_MULTICAST_HOPS) &&
7312 	    (udp->udp_sticky_ipp.ipp_fields & IPPF_MULTICAST_HOPS)) {
7313 		option_exists |= IPPF_MULTICAST_HOPS;
7314 		is_sticky |= IPPF_MULTICAST_HOPS;
7315 	}
7316 
7317 	if (!(ignore & IPPF_TCLASS)) {
7318 		if (ipp->ipp_fields & IPPF_TCLASS) {
7319 			option_exists |= IPPF_TCLASS;
7320 		} else if (udp->udp_sticky_ipp.ipp_fields & IPPF_TCLASS) {
7321 			option_exists |= IPPF_TCLASS;
7322 			is_sticky |= IPPF_TCLASS;
7323 		}
7324 	}
7325 
7326 no_options:
7327 
7328 	/*
7329 	 * If any options carried in the ip6i_t were specified, we
7330 	 * need to account for the ip6i_t in the data we'll be sending
7331 	 * down.
7332 	 */
7333 	if (option_exists & IPPF_HAS_IP6I)
7334 		udp_ip_hdr_len += sizeof (ip6i_t);
7335 
7336 	/* check/fix buffer config, setup pointers into it */
7337 	ip6h = (ip6_t *)&mp1->b_rptr[-udp_ip_hdr_len];
7338 	if (DB_REF(mp1) != 1 || ((unsigned char *)ip6h < DB_BASE(mp1)) ||
7339 	    !OK_32PTR(ip6h)) {
7340 		/* Try to get everything in a single mblk next time */
7341 		if (udp_ip_hdr_len > udp->udp_max_hdr_len) {
7342 			udp->udp_max_hdr_len = udp_ip_hdr_len;
7343 			(void) mi_set_sth_wroff(UDP_RD(q),
7344 			    udp->udp_max_hdr_len + udp_wroff_extra);
7345 		}
7346 		mp2 = allocb(udp_ip_hdr_len + udp_wroff_extra, BPRI_LO);
7347 		if (mp2 == NULL) {
7348 			*error = ENOMEM;
7349 			goto done;
7350 		}
7351 		mp2->b_wptr = DB_LIM(mp2);
7352 		mp2->b_cont = mp1;
7353 		mp1 = mp2;
7354 		if (DB_TYPE(mp) != M_DATA)
7355 			mp->b_cont = mp1;
7356 		else
7357 			mp = mp1;
7358 
7359 		ip6h = (ip6_t *)(mp1->b_wptr - udp_ip_hdr_len);
7360 	}
7361 	mp1->b_rptr = (unsigned char *)ip6h;
7362 	ip6i = (ip6i_t *)ip6h;
7363 
7364 #define	ANCIL_OR_STICKY_PTR(f) ((is_sticky & f) ? &udp->udp_sticky_ipp : ipp)
7365 	if (option_exists & IPPF_HAS_IP6I) {
7366 		ip6h = (ip6_t *)&ip6i[1];
7367 		ip6i->ip6i_flags = 0;
7368 		ip6i->ip6i_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
7369 
7370 		/* sin6_scope_id takes precendence over IPPF_IFINDEX */
7371 		if (option_exists & IPPF_SCOPE_ID) {
7372 			ip6i->ip6i_flags |= IP6I_IFINDEX;
7373 			ip6i->ip6i_ifindex = sin6->sin6_scope_id;
7374 		} else if (option_exists & IPPF_IFINDEX) {
7375 			tipp = ANCIL_OR_STICKY_PTR(IPPF_IFINDEX);
7376 			ASSERT(tipp->ipp_ifindex != 0);
7377 			ip6i->ip6i_flags |= IP6I_IFINDEX;
7378 			ip6i->ip6i_ifindex = tipp->ipp_ifindex;
7379 		}
7380 
7381 		if (option_exists & IPPF_ADDR) {
7382 			/*
7383 			 * Enable per-packet source address verification if
7384 			 * IPV6_PKTINFO specified the source address.
7385 			 * ip6_src is set in the transport's _wput function.
7386 			 */
7387 			ip6i->ip6i_flags |= IP6I_VERIFY_SRC;
7388 		}
7389 
7390 		if (option_exists & IPPF_DONTFRAG) {
7391 			ip6i->ip6i_flags |= IP6I_DONTFRAG;
7392 		}
7393 
7394 		if (option_exists & IPPF_USE_MIN_MTU) {
7395 			ip6i->ip6i_flags = IP6I_API_USE_MIN_MTU(
7396 			    ip6i->ip6i_flags, ipp->ipp_use_min_mtu);
7397 		}
7398 
7399 		if (option_exists & IPPF_NEXTHOP) {
7400 			tipp = ANCIL_OR_STICKY_PTR(IPPF_NEXTHOP);
7401 			ASSERT(!IN6_IS_ADDR_UNSPECIFIED(&tipp->ipp_nexthop));
7402 			ip6i->ip6i_flags |= IP6I_NEXTHOP;
7403 			ip6i->ip6i_nexthop = tipp->ipp_nexthop;
7404 		}
7405 
7406 		/*
7407 		 * tell IP this is an ip6i_t private header
7408 		 */
7409 		ip6i->ip6i_nxt = IPPROTO_RAW;
7410 	}
7411 
7412 	/* Initialize IPv6 header */
7413 	ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
7414 	bzero(&ip6h->ip6_src, sizeof (ip6h->ip6_src));
7415 
7416 	/* Set the hoplimit of the outgoing packet. */
7417 	if (option_exists & IPPF_HOPLIMIT) {
7418 		/* IPV6_HOPLIMIT ancillary data overrides all other settings. */
7419 		ip6h->ip6_hops = ipp->ipp_hoplimit;
7420 		ip6i->ip6i_flags |= IP6I_HOPLIMIT;
7421 	} else if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
7422 		ip6h->ip6_hops = udp->udp_multicast_ttl;
7423 		if (option_exists & IPPF_MULTICAST_HOPS)
7424 			ip6i->ip6i_flags |= IP6I_HOPLIMIT;
7425 	} else {
7426 		ip6h->ip6_hops = udp->udp_ttl;
7427 		if (option_exists & IPPF_UNICAST_HOPS)
7428 			ip6i->ip6i_flags |= IP6I_HOPLIMIT;
7429 	}
7430 
7431 	if (option_exists & IPPF_ADDR) {
7432 		tipp = ANCIL_OR_STICKY_PTR(IPPF_ADDR);
7433 		ASSERT(!IN6_IS_ADDR_UNSPECIFIED(&tipp->ipp_addr));
7434 		ip6h->ip6_src = tipp->ipp_addr;
7435 	} else {
7436 		/*
7437 		 * The source address was not set using IPV6_PKTINFO.
7438 		 * First look at the bound source.
7439 		 * If unspecified fallback to __sin6_src_id.
7440 		 */
7441 		ip6h->ip6_src = udp->udp_v6src;
7442 		if (sin6->__sin6_src_id != 0 &&
7443 		    IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src)) {
7444 			ip_srcid_find_id(sin6->__sin6_src_id,
7445 			    &ip6h->ip6_src, connp->conn_zoneid);
7446 		}
7447 	}
7448 
7449 	nxthdr_ptr = (uint8_t *)&ip6h->ip6_nxt;
7450 	cp = (uint8_t *)&ip6h[1];
7451 
7452 	/*
7453 	 * Here's where we have to start stringing together
7454 	 * any extension headers in the right order:
7455 	 * Hop-by-hop, destination, routing, and final destination opts.
7456 	 */
7457 	if (option_exists & IPPF_HOPOPTS) {
7458 		/* Hop-by-hop options */
7459 		ip6_hbh_t *hbh = (ip6_hbh_t *)cp;
7460 		tipp = ANCIL_OR_STICKY_PTR(IPPF_HOPOPTS);
7461 		if (hopoptslen == 0) {
7462 			hopoptsptr = tipp->ipp_hopopts;
7463 			hopoptslen = tipp->ipp_hopoptslen;
7464 			is_ancillary = B_TRUE;
7465 		}
7466 
7467 		*nxthdr_ptr = IPPROTO_HOPOPTS;
7468 		nxthdr_ptr = &hbh->ip6h_nxt;
7469 
7470 		bcopy(hopoptsptr, cp, hopoptslen);
7471 		cp += hopoptslen;
7472 
7473 		if (hopoptsptr != NULL && !is_ancillary) {
7474 			kmem_free(hopoptsptr, hopoptslen);
7475 			hopoptsptr = NULL;
7476 			hopoptslen = 0;
7477 		}
7478 	}
7479 	/*
7480 	 * En-route destination options
7481 	 * Only do them if there's a routing header as well
7482 	 */
7483 	if (option_exists & IPPF_RTDSTOPTS) {
7484 		ip6_dest_t *dst = (ip6_dest_t *)cp;
7485 		tipp = ANCIL_OR_STICKY_PTR(IPPF_RTDSTOPTS);
7486 
7487 		*nxthdr_ptr = IPPROTO_DSTOPTS;
7488 		nxthdr_ptr = &dst->ip6d_nxt;
7489 
7490 		bcopy(tipp->ipp_rtdstopts, cp, tipp->ipp_rtdstoptslen);
7491 		cp += tipp->ipp_rtdstoptslen;
7492 	}
7493 	/*
7494 	 * Routing header next
7495 	 */
7496 	if (option_exists & IPPF_RTHDR) {
7497 		ip6_rthdr_t *rt = (ip6_rthdr_t *)cp;
7498 		tipp = ANCIL_OR_STICKY_PTR(IPPF_RTHDR);
7499 
7500 		*nxthdr_ptr = IPPROTO_ROUTING;
7501 		nxthdr_ptr = &rt->ip6r_nxt;
7502 
7503 		bcopy(tipp->ipp_rthdr, cp, tipp->ipp_rthdrlen);
7504 		cp += tipp->ipp_rthdrlen;
7505 	}
7506 	/*
7507 	 * Do ultimate destination options
7508 	 */
7509 	if (option_exists & IPPF_DSTOPTS) {
7510 		ip6_dest_t *dest = (ip6_dest_t *)cp;
7511 		tipp = ANCIL_OR_STICKY_PTR(IPPF_DSTOPTS);
7512 
7513 		*nxthdr_ptr = IPPROTO_DSTOPTS;
7514 		nxthdr_ptr = &dest->ip6d_nxt;
7515 
7516 		bcopy(tipp->ipp_dstopts, cp, tipp->ipp_dstoptslen);
7517 		cp += tipp->ipp_dstoptslen;
7518 	}
7519 	/*
7520 	 * Now set the last header pointer to the proto passed in
7521 	 */
7522 	ASSERT((int)(cp - (uint8_t *)ip6i) == (udp_ip_hdr_len - UDPH_SIZE));
7523 	*nxthdr_ptr = IPPROTO_UDP;
7524 
7525 	/* Update UDP header */
7526 	udph = (udpha_t *)((uchar_t *)ip6i + udp_ip_hdr_len - UDPH_SIZE);
7527 	udph->uha_dst_port = sin6->sin6_port;
7528 	udph->uha_src_port = udp->udp_port;
7529 
7530 	/*
7531 	 * Copy in the destination address
7532 	 */
7533 	ip6h->ip6_dst = ip6_dst;
7534 
7535 	ip6h->ip6_vcf =
7536 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
7537 	    (sin6->sin6_flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
7538 
7539 	if (option_exists & IPPF_TCLASS) {
7540 		tipp = ANCIL_OR_STICKY_PTR(IPPF_TCLASS);
7541 		ip6h->ip6_vcf = IPV6_TCLASS_FLOW(ip6h->ip6_vcf,
7542 		    tipp->ipp_tclass);
7543 	}
7544 
7545 	if (option_exists & IPPF_RTHDR) {
7546 		ip6_rthdr_t	*rth;
7547 
7548 		/*
7549 		 * Perform any processing needed for source routing.
7550 		 * We know that all extension headers will be in the same mblk
7551 		 * as the IPv6 header.
7552 		 */
7553 		rth = ip_find_rthdr_v6(ip6h, mp1->b_wptr);
7554 		if (rth != NULL && rth->ip6r_segleft != 0) {
7555 			if (rth->ip6r_type != IPV6_RTHDR_TYPE_0) {
7556 				/*
7557 				 * Drop packet - only support Type 0 routing.
7558 				 * Notify the application as well.
7559 				 */
7560 				*error = EPROTO;
7561 				goto done;
7562 			}
7563 
7564 			/*
7565 			 * rth->ip6r_len is twice the number of
7566 			 * addresses in the header. Thus it must be even.
7567 			 */
7568 			if (rth->ip6r_len & 0x1) {
7569 				*error = EPROTO;
7570 				goto done;
7571 			}
7572 			/*
7573 			 * Shuffle the routing header and ip6_dst
7574 			 * addresses, and get the checksum difference
7575 			 * between the first hop (in ip6_dst) and
7576 			 * the destination (in the last routing hdr entry).
7577 			 */
7578 			csum = ip_massage_options_v6(ip6h, rth);
7579 			/*
7580 			 * Verify that the first hop isn't a mapped address.
7581 			 * Routers along the path need to do this verification
7582 			 * for subsequent hops.
7583 			 */
7584 			if (IN6_IS_ADDR_V4MAPPED(&ip6h->ip6_dst)) {
7585 				*error = EADDRNOTAVAIL;
7586 				goto done;
7587 			}
7588 
7589 			cp += (rth->ip6r_len + 1)*8;
7590 		}
7591 	}
7592 
7593 	/* count up length of UDP packet */
7594 	ip_len = (mp1->b_wptr - (unsigned char *)ip6h) - IPV6_HDR_LEN;
7595 	if ((mp2 = mp1->b_cont) != NULL) {
7596 		do {
7597 			ASSERT((uintptr_t)MBLKL(mp2) <= (uintptr_t)UINT_MAX);
7598 			ip_len += (uint32_t)MBLKL(mp2);
7599 		} while ((mp2 = mp2->b_cont) != NULL);
7600 	}
7601 
7602 	/*
7603 	 * If the size of the packet is greater than the maximum allowed by
7604 	 * ip, return an error. Passing this down could cause panics because
7605 	 * the size will have wrapped and be inconsistent with the msg size.
7606 	 */
7607 	if (ip_len > IP_MAXPACKET) {
7608 		*error = EMSGSIZE;
7609 		goto done;
7610 	}
7611 
7612 	/* Store the UDP length. Subtract length of extension hdrs */
7613 	udph->uha_length = htons(ip_len + IPV6_HDR_LEN -
7614 	    (int)((uchar_t *)udph - (uchar_t *)ip6h));
7615 
7616 	/*
7617 	 * We make it easy for IP to include our pseudo header
7618 	 * by putting our length in uh_checksum, modified (if
7619 	 * we have a routing header) by the checksum difference
7620 	 * between the ultimate destination and first hop addresses.
7621 	 * Note: UDP over IPv6 must always checksum the packet.
7622 	 */
7623 	csum += udph->uha_length;
7624 	csum = (csum & 0xFFFF) + (csum >> 16);
7625 	udph->uha_checksum = (uint16_t)csum;
7626 
7627 #ifdef _LITTLE_ENDIAN
7628 	ip_len = htons(ip_len);
7629 #endif
7630 	ip6h->ip6_plen = ip_len;
7631 	if (DB_CRED(mp) != NULL)
7632 		mblk_setcred(mp1, DB_CRED(mp));
7633 
7634 	if (DB_TYPE(mp) != M_DATA) {
7635 		ASSERT(mp != mp1);
7636 		freeb(mp);
7637 	}
7638 
7639 	/* mp has been consumed and we'll return success */
7640 	ASSERT(*error == 0);
7641 	mp = NULL;
7642 
7643 	/* We're done. Pass the packet to IP */
7644 	BUMP_MIB(&udp_mib, udpOutDatagrams);
7645 	ip_output_v6(connp, mp1, q, IP_WPUT);
7646 
7647 done:
7648 	if (hopoptsptr != NULL && !is_ancillary) {
7649 		kmem_free(hopoptsptr, hopoptslen);
7650 		hopoptsptr = NULL;
7651 	}
7652 	if (*error != 0) {
7653 		ASSERT(mp != NULL);
7654 		BUMP_MIB(&udp_mib, udpOutErrors);
7655 	}
7656 	return (mp);
7657 }
7658 
7659 static void
7660 udp_wput_other(queue_t *q, mblk_t *mp)
7661 {
7662 	uchar_t	*rptr = mp->b_rptr;
7663 	struct datab *db;
7664 	struct iocblk *iocp;
7665 	cred_t	*cr;
7666 	conn_t	*connp = Q_TO_CONN(q);
7667 	udp_t	*udp = connp->conn_udp;
7668 
7669 	TRACE_1(TR_FAC_UDP, TR_UDP_WPUT_OTHER_START,
7670 		"udp_wput_other_start: q %p", q);
7671 
7672 	db = mp->b_datap;
7673 
7674 	cr = DB_CREDDEF(mp, connp->conn_cred);
7675 
7676 	switch (db->db_type) {
7677 	case M_PROTO:
7678 	case M_PCPROTO:
7679 		if (mp->b_wptr - rptr < sizeof (t_scalar_t)) {
7680 			freemsg(mp);
7681 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7682 				"udp_wput_other_end: q %p (%S)",
7683 				q, "protoshort");
7684 			return;
7685 		}
7686 		switch (((t_primp_t)rptr)->type) {
7687 		case T_ADDR_REQ:
7688 			udp_addr_req(q, mp);
7689 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7690 				"udp_wput_other_end: q %p (%S)", q, "addrreq");
7691 			return;
7692 		case O_T_BIND_REQ:
7693 		case T_BIND_REQ:
7694 			udp_bind(q, mp);
7695 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7696 				"udp_wput_other_end: q %p (%S)", q, "bindreq");
7697 			return;
7698 		case T_CONN_REQ:
7699 			udp_connect(q, mp);
7700 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7701 				"udp_wput_other_end: q %p (%S)", q, "connreq");
7702 			return;
7703 		case T_CAPABILITY_REQ:
7704 			udp_capability_req(q, mp);
7705 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7706 				"udp_wput_other_end: q %p (%S)", q, "capabreq");
7707 			return;
7708 		case T_INFO_REQ:
7709 			udp_info_req(q, mp);
7710 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7711 				"udp_wput_other_end: q %p (%S)", q, "inforeq");
7712 			return;
7713 		case T_UNITDATA_REQ:
7714 			/*
7715 			 * If a T_UNITDATA_REQ gets here, the address must
7716 			 * be bad.  Valid T_UNITDATA_REQs are handled
7717 			 * in udp_wput.
7718 			 */
7719 			udp_ud_err(q, mp, NULL, 0, EADDRNOTAVAIL);
7720 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7721 				"udp_wput_other_end: q %p (%S)",
7722 				q, "unitdatareq");
7723 			return;
7724 		case T_UNBIND_REQ:
7725 			udp_unbind(q, mp);
7726 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7727 			    "udp_wput_other_end: q %p (%S)", q, "unbindreq");
7728 			return;
7729 		case T_SVR4_OPTMGMT_REQ:
7730 			if (!snmpcom_req(q, mp, udp_snmp_set, udp_snmp_get, cr))
7731 				/*
7732 				 * Use upper queue for option processing in
7733 				 * case the request is not handled at this
7734 				 * level and needs to be passed down to IP.
7735 				 */
7736 				(void) svr4_optcom_req(_WR(UDP_RD(q)),
7737 				    mp, cr, &udp_opt_obj);
7738 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7739 			    "udp_wput_other_end: q %p (%S)",
7740 			    q, "optmgmtreq");
7741 			return;
7742 
7743 		case T_OPTMGMT_REQ:
7744 			/*
7745 			 * Use upper queue for option processing in
7746 			 * case the request is not handled at this
7747 			 * level and needs to be passed down to IP.
7748 			 */
7749 			(void) tpi_optcom_req(_WR(UDP_RD(q)),
7750 			    mp, cr, &udp_opt_obj);
7751 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7752 				"udp_wput_other_end: q %p (%S)",
7753 				q, "optmgmtreq");
7754 			return;
7755 
7756 		case T_DISCON_REQ:
7757 			udp_disconnect(q, mp);
7758 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7759 				"udp_wput_other_end: q %p (%S)",
7760 				q, "disconreq");
7761 			return;
7762 
7763 		/* The following TPI message is not supported by udp. */
7764 		case O_T_CONN_RES:
7765 		case T_CONN_RES:
7766 			udp_err_ack(q, mp, TNOTSUPPORT, 0);
7767 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7768 				"udp_wput_other_end: q %p (%S)",
7769 				q, "connres/disconreq");
7770 			return;
7771 
7772 		/* The following 3 TPI messages are illegal for udp. */
7773 		case T_DATA_REQ:
7774 		case T_EXDATA_REQ:
7775 		case T_ORDREL_REQ:
7776 			udp_err_ack(q, mp, TNOTSUPPORT, 0);
7777 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7778 				"udp_wput_other_end: q %p (%S)",
7779 				q, "data/exdata/ordrel");
7780 			return;
7781 		default:
7782 			break;
7783 		}
7784 		break;
7785 	case M_FLUSH:
7786 		if (*rptr & FLUSHW)
7787 			flushq(q, FLUSHDATA);
7788 		break;
7789 	case M_IOCTL:
7790 		iocp = (struct iocblk *)mp->b_rptr;
7791 		switch (iocp->ioc_cmd) {
7792 		case TI_GETPEERNAME:
7793 			if (udp->udp_state != TS_DATA_XFER) {
7794 				/*
7795 				 * If a default destination address has not
7796 				 * been associated with the stream, then we
7797 				 * don't know the peer's name.
7798 				 */
7799 				iocp->ioc_error = ENOTCONN;
7800 				iocp->ioc_count = 0;
7801 				mp->b_datap->db_type = M_IOCACK;
7802 				putnext(UDP_RD(q), mp);
7803 				TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7804 					"udp_wput_other_end: q %p (%S)",
7805 					q, "getpeername");
7806 				return;
7807 			}
7808 			/* FALLTHRU */
7809 		case TI_GETMYNAME: {
7810 			/*
7811 			 * For TI_GETPEERNAME and TI_GETMYNAME, we first
7812 			 * need to copyin the user's strbuf structure.
7813 			 * Processing will continue in the M_IOCDATA case
7814 			 * below.
7815 			 */
7816 			mi_copyin(q, mp, NULL,
7817 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
7818 			TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7819 				"udp_wput_other_end: q %p (%S)",
7820 				q, "getmyname");
7821 			return;
7822 			}
7823 		case ND_SET:
7824 			/* nd_getset performs the necessary checking */
7825 		case ND_GET:
7826 			if (nd_getset(q, udp_g_nd, mp)) {
7827 				putnext(UDP_RD(q), mp);
7828 				TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7829 					"udp_wput_other_end: q %p (%S)",
7830 					q, "get");
7831 				return;
7832 			}
7833 			break;
7834 		case _SIOCSOCKFALLBACK:
7835 			/*
7836 			 * Either sockmod is about to be popped and the
7837 			 * socket would now be treated as a plain stream,
7838 			 * or a module is about to be pushed so we could
7839 			 * no longer use read-side synchronous stream.
7840 			 * Drain any queued data and disable direct sockfs
7841 			 * interface from now on.
7842 			 */
7843 			if (!udp->udp_issocket) {
7844 				DB_TYPE(mp) = M_IOCNAK;
7845 				iocp->ioc_error = EINVAL;
7846 			} else {
7847 				udp->udp_issocket = B_FALSE;
7848 				if (udp->udp_direct_sockfs) {
7849 					/*
7850 					 * Disable read-side synchronous
7851 					 * stream interface and drain any
7852 					 * queued data.
7853 					 */
7854 					udp_rcv_drain(UDP_RD(q), udp,
7855 					    B_FALSE);
7856 					ASSERT(!udp->udp_direct_sockfs);
7857 					UDP_STAT(udp_sock_fallback);
7858 				}
7859 				DB_TYPE(mp) = M_IOCACK;
7860 				iocp->ioc_error = 0;
7861 			}
7862 			iocp->ioc_count = 0;
7863 			iocp->ioc_rval = 0;
7864 			putnext(UDP_RD(q), mp);
7865 			return;
7866 		default:
7867 			break;
7868 		}
7869 		break;
7870 	case M_IOCDATA:
7871 		udp_wput_iocdata(q, mp);
7872 		TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7873 			"udp_wput_other_end: q %p (%S)", q, "iocdata");
7874 		return;
7875 	default:
7876 		/* Unrecognized messages are passed through without change. */
7877 		break;
7878 	}
7879 	TRACE_2(TR_FAC_UDP, TR_UDP_WPUT_OTHER_END,
7880 		"udp_wput_other_end: q %p (%S)", q, "end");
7881 	ip_output(connp, mp, q, IP_WPUT);
7882 }
7883 
7884 /* ARGSUSED */
7885 static void
7886 udp_wput_other_wrapper(void *arg, mblk_t *mp, void *arg2)
7887 {
7888 	udp_wput_other(((conn_t *)arg)->conn_wq, mp);
7889 	udp_exit((conn_t *)arg);
7890 }
7891 
7892 /*
7893  * udp_wput_iocdata is called by udp_wput_other to handle all M_IOCDATA
7894  * messages.
7895  */
7896 static void
7897 udp_wput_iocdata(queue_t *q, mblk_t *mp)
7898 {
7899 	mblk_t	*mp1;
7900 	STRUCT_HANDLE(strbuf, sb);
7901 	uint16_t port;
7902 	in6_addr_t	v6addr;
7903 	ipaddr_t	v4addr;
7904 	uint32_t	flowinfo = 0;
7905 	int		addrlen;
7906 	udp_t		*udp = Q_TO_UDP(q);
7907 
7908 	/* Make sure it is one of ours. */
7909 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
7910 	case TI_GETMYNAME:
7911 	case TI_GETPEERNAME:
7912 		break;
7913 	default:
7914 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
7915 		return;
7916 	}
7917 
7918 	q = WR(UDP_RD(q));
7919 	switch (mi_copy_state(q, mp, &mp1)) {
7920 	case -1:
7921 		return;
7922 	case MI_COPY_CASE(MI_COPY_IN, 1):
7923 		break;
7924 	case MI_COPY_CASE(MI_COPY_OUT, 1):
7925 		/*
7926 		 * The address has been copied out, so now
7927 		 * copyout the strbuf.
7928 		 */
7929 		mi_copyout(q, mp);
7930 		return;
7931 	case MI_COPY_CASE(MI_COPY_OUT, 2):
7932 		/*
7933 		 * The address and strbuf have been copied out.
7934 		 * We're done, so just acknowledge the original
7935 		 * M_IOCTL.
7936 		 */
7937 		mi_copy_done(q, mp, 0);
7938 		return;
7939 	default:
7940 		/*
7941 		 * Something strange has happened, so acknowledge
7942 		 * the original M_IOCTL with an EPROTO error.
7943 		 */
7944 		mi_copy_done(q, mp, EPROTO);
7945 		return;
7946 	}
7947 
7948 	/*
7949 	 * Now we have the strbuf structure for TI_GETMYNAME
7950 	 * and TI_GETPEERNAME.  Next we copyout the requested
7951 	 * address and then we'll copyout the strbuf.
7952 	 */
7953 	STRUCT_SET_HANDLE(sb, ((struct iocblk *)mp->b_rptr)->ioc_flag,
7954 	    (void *)mp1->b_rptr);
7955 	if (udp->udp_family == AF_INET)
7956 		addrlen = sizeof (sin_t);
7957 	else
7958 		addrlen = sizeof (sin6_t);
7959 
7960 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
7961 		mi_copy_done(q, mp, EINVAL);
7962 		return;
7963 	}
7964 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
7965 	case TI_GETMYNAME:
7966 		if (udp->udp_family == AF_INET) {
7967 			ASSERT(udp->udp_ipversion == IPV4_VERSION);
7968 			if (!IN6_IS_ADDR_V4MAPPED_ANY(&udp->udp_v6src) &&
7969 			    !IN6_IS_ADDR_UNSPECIFIED(&udp->udp_v6src)) {
7970 				v4addr = V4_PART_OF_V6(udp->udp_v6src);
7971 			} else {
7972 				/*
7973 				 * INADDR_ANY
7974 				 * udp_v6src is not set, we might be bound to
7975 				 * broadcast/multicast. Use udp_bound_v6src as
7976 				 * local address instead (that could
7977 				 * also still be INADDR_ANY)
7978 				 */
7979 				v4addr = V4_PART_OF_V6(udp->udp_bound_v6src);
7980 			}
7981 		} else {
7982 			/* udp->udp_family == AF_INET6 */
7983 			if (!IN6_IS_ADDR_UNSPECIFIED(&udp->udp_v6src)) {
7984 				v6addr = udp->udp_v6src;
7985 			} else {
7986 				/*
7987 				 * UNSPECIFIED
7988 				 * udp_v6src is not set, we might be bound to
7989 				 * broadcast/multicast. Use udp_bound_v6src as
7990 				 * local address instead (that could
7991 				 * also still be UNSPECIFIED)
7992 				 */
7993 				v6addr = udp->udp_bound_v6src;
7994 			}
7995 		}
7996 		port = udp->udp_port;
7997 		break;
7998 	case TI_GETPEERNAME:
7999 		if (udp->udp_state != TS_DATA_XFER) {
8000 			mi_copy_done(q, mp, ENOTCONN);
8001 			return;
8002 		}
8003 		if (udp->udp_family == AF_INET) {
8004 			ASSERT(udp->udp_ipversion == IPV4_VERSION);
8005 			v4addr = V4_PART_OF_V6(udp->udp_v6dst);
8006 		} else {
8007 			/* udp->udp_family == AF_INET6) */
8008 			v6addr = udp->udp_v6dst;
8009 			flowinfo = udp->udp_flowinfo;
8010 		}
8011 		port = udp->udp_dstport;
8012 		break;
8013 	default:
8014 		mi_copy_done(q, mp, EPROTO);
8015 		return;
8016 	}
8017 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
8018 	if (!mp1)
8019 		return;
8020 
8021 	if (udp->udp_family == AF_INET) {
8022 		sin_t *sin;
8023 
8024 		STRUCT_FSET(sb, len, (int)sizeof (sin_t));
8025 		sin = (sin_t *)mp1->b_rptr;
8026 		mp1->b_wptr = (uchar_t *)&sin[1];
8027 		*sin = sin_null;
8028 		sin->sin_family = AF_INET;
8029 		sin->sin_addr.s_addr = v4addr;
8030 		sin->sin_port = port;
8031 	} else {
8032 		/* udp->udp_family == AF_INET6 */
8033 		sin6_t *sin6;
8034 
8035 		STRUCT_FSET(sb, len, (int)sizeof (sin6_t));
8036 		sin6 = (sin6_t *)mp1->b_rptr;
8037 		mp1->b_wptr = (uchar_t *)&sin6[1];
8038 		*sin6 = sin6_null;
8039 		sin6->sin6_family = AF_INET6;
8040 		sin6->sin6_flowinfo = flowinfo;
8041 		sin6->sin6_addr = v6addr;
8042 		sin6->sin6_port = port;
8043 	}
8044 	/* Copy out the address */
8045 	mi_copyout(q, mp);
8046 }
8047 
8048 
8049 static int
8050 udp_unitdata_opt_process(queue_t *q, mblk_t *mp, int *errorp,
8051     udpattrs_t *udpattrs)
8052 {
8053 	struct T_unitdata_req *udreqp;
8054 	int is_absreq_failure;
8055 	cred_t *cr;
8056 	conn_t	*connp = Q_TO_CONN(q);
8057 
8058 	ASSERT(((t_primp_t)mp->b_rptr)->type);
8059 
8060 	cr = DB_CREDDEF(mp, connp->conn_cred);
8061 
8062 	udreqp = (struct T_unitdata_req *)mp->b_rptr;
8063 
8064 	/*
8065 	 * Use upper queue for option processing since the callback
8066 	 * routines expect to be called in UDP instance instead of IP.
8067 	 */
8068 	*errorp = tpi_optcom_buf(_WR(UDP_RD(q)), mp, &udreqp->OPT_length,
8069 	    udreqp->OPT_offset, cr, &udp_opt_obj,
8070 	    udpattrs, &is_absreq_failure);
8071 
8072 	if (*errorp != 0) {
8073 		/*
8074 		 * Note: No special action needed in this
8075 		 * module for "is_absreq_failure"
8076 		 */
8077 		return (-1);		/* failure */
8078 	}
8079 	ASSERT(is_absreq_failure == 0);
8080 	return (0);	/* success */
8081 }
8082 
8083 void
8084 udp_ddi_init(void)
8085 {
8086 	int i;
8087 
8088 	UDP6_MAJ = ddi_name_to_major(UDP6);
8089 
8090 	udp_max_optsize = optcom_max_optsize(udp_opt_obj.odb_opt_des_arr,
8091 	    udp_opt_obj.odb_opt_arr_cnt);
8092 
8093 	if (udp_bind_fanout_size & (udp_bind_fanout_size - 1)) {
8094 		/* Not a power of two. Round up to nearest power of two */
8095 		for (i = 0; i < 31; i++) {
8096 			if (udp_bind_fanout_size < (1 << i))
8097 				break;
8098 		}
8099 		udp_bind_fanout_size = 1 << i;
8100 	}
8101 	udp_bind_fanout = kmem_zalloc(udp_bind_fanout_size *
8102 	    sizeof (udp_fanout_t), KM_SLEEP);
8103 	for (i = 0; i < udp_bind_fanout_size; i++) {
8104 		mutex_init(&udp_bind_fanout[i].uf_lock, NULL, MUTEX_DEFAULT,
8105 		    NULL);
8106 	}
8107 	(void) udp_param_register(udp_param_arr, A_CNT(udp_param_arr));
8108 
8109 	udp_kstat_init();
8110 
8111 	udp_cache = kmem_cache_create("udp_cache", sizeof (udp_t),
8112 	    CACHE_ALIGN_SIZE, NULL, NULL, NULL, NULL, NULL, 0);
8113 }
8114 
8115 void
8116 udp_ddi_destroy(void)
8117 {
8118 	int i;
8119 
8120 	nd_free(&udp_g_nd);
8121 
8122 	for (i = 0; i < udp_bind_fanout_size; i++) {
8123 		mutex_destroy(&udp_bind_fanout[i].uf_lock);
8124 	}
8125 
8126 	kmem_free(udp_bind_fanout, udp_bind_fanout_size *
8127 	    sizeof (udp_fanout_t));
8128 
8129 	udp_kstat_fini();
8130 
8131 	kmem_cache_destroy(udp_cache);
8132 }
8133 
8134 static void
8135 udp_kstat_init(void)
8136 {
8137 	udp_named_kstat_t template = {
8138 		{ "inDatagrams",	KSTAT_DATA_UINT32, 0 },
8139 		{ "inErrors",		KSTAT_DATA_UINT32, 0 },
8140 		{ "outDatagrams",	KSTAT_DATA_UINT32, 0 },
8141 		{ "entrySize",		KSTAT_DATA_INT32, 0 },
8142 		{ "entry6Size",		KSTAT_DATA_INT32, 0 },
8143 		{ "outErrors",		KSTAT_DATA_UINT32, 0 },
8144 	};
8145 
8146 	udp_mibkp = kstat_create(UDP_MOD_NAME, 0, UDP_MOD_NAME,
8147 	    "mib2", KSTAT_TYPE_NAMED, NUM_OF_FIELDS(udp_named_kstat_t), 0);
8148 
8149 	if (udp_mibkp == NULL)
8150 		return;
8151 
8152 	template.entrySize.value.ui32 = sizeof (mib2_udpEntry_t);
8153 	template.entry6Size.value.ui32 = sizeof (mib2_udp6Entry_t);
8154 
8155 	bcopy(&template, udp_mibkp->ks_data, sizeof (template));
8156 
8157 	udp_mibkp->ks_update = udp_kstat_update;
8158 
8159 	kstat_install(udp_mibkp);
8160 
8161 	if ((udp_ksp = kstat_create(UDP_MOD_NAME, 0, "udpstat",
8162 	    "net", KSTAT_TYPE_NAMED,
8163 	    sizeof (udp_statistics) / sizeof (kstat_named_t),
8164 	    KSTAT_FLAG_VIRTUAL)) != NULL) {
8165 		udp_ksp->ks_data = &udp_statistics;
8166 		kstat_install(udp_ksp);
8167 	}
8168 }
8169 
8170 static void
8171 udp_kstat_fini(void)
8172 {
8173 	if (udp_ksp != NULL) {
8174 		kstat_delete(udp_ksp);
8175 		udp_ksp = NULL;
8176 	}
8177 	if (udp_mibkp != NULL) {
8178 		kstat_delete(udp_mibkp);
8179 		udp_mibkp = NULL;
8180 	}
8181 }
8182 
8183 static int
8184 udp_kstat_update(kstat_t *kp, int rw)
8185 {
8186 	udp_named_kstat_t *udpkp;
8187 
8188 	if ((kp == NULL) || (kp->ks_data == NULL))
8189 		return (EIO);
8190 
8191 	if (rw == KSTAT_WRITE)
8192 		return (EACCES);
8193 
8194 	udpkp = (udp_named_kstat_t *)kp->ks_data;
8195 
8196 	udpkp->inDatagrams.value.ui32 =	udp_mib.udpInDatagrams;
8197 	udpkp->inErrors.value.ui32 =	udp_mib.udpInErrors;
8198 	udpkp->outDatagrams.value.ui32 = udp_mib.udpOutDatagrams;
8199 	udpkp->outErrors.value.ui32 =	udp_mib.udpOutErrors;
8200 
8201 	return (0);
8202 }
8203 
8204 /* ARGSUSED */
8205 static void
8206 udp_rput(queue_t *q, mblk_t *mp)
8207 {
8208 	/*
8209 	 * We get here whenever we do qreply() from IP,
8210 	 * i.e as part of handlings ioctls, etc.
8211 	 */
8212 	putnext(q, mp);
8213 }
8214 
8215 /*
8216  * Read-side synchronous stream info entry point, called as a
8217  * result of handling certain STREAMS ioctl operations.
8218  */
8219 static int
8220 udp_rinfop(queue_t *q, infod_t *dp)
8221 {
8222 	mblk_t	*mp;
8223 	uint_t	cmd = dp->d_cmd;
8224 	int	res = 0;
8225 	int	error = 0;
8226 	udp_t	*udp = Q_TO_UDP(RD(UDP_WR(q)));
8227 	struct stdata *stp = STREAM(q);
8228 
8229 	mutex_enter(&udp->udp_drain_lock);
8230 	/* If shutdown on read has happened, return nothing */
8231 	mutex_enter(&stp->sd_lock);
8232 	if (stp->sd_flag & STREOF) {
8233 		mutex_exit(&stp->sd_lock);
8234 		goto done;
8235 	}
8236 	mutex_exit(&stp->sd_lock);
8237 
8238 	if ((mp = udp->udp_rcv_list_head) == NULL)
8239 		goto done;
8240 
8241 	ASSERT(DB_TYPE(mp) != M_DATA && mp->b_cont != NULL);
8242 
8243 	if (cmd & INFOD_COUNT) {
8244 		/*
8245 		 * Return the number of messages.
8246 		 */
8247 		dp->d_count += udp->udp_rcv_msgcnt;
8248 		res |= INFOD_COUNT;
8249 	}
8250 	if (cmd & INFOD_BYTES) {
8251 		/*
8252 		 * Return size of all data messages.
8253 		 */
8254 		dp->d_bytes += udp->udp_rcv_cnt;
8255 		res |= INFOD_BYTES;
8256 	}
8257 	if (cmd & INFOD_FIRSTBYTES) {
8258 		/*
8259 		 * Return size of first data message.
8260 		 */
8261 		dp->d_bytes = msgdsize(mp);
8262 		res |= INFOD_FIRSTBYTES;
8263 		dp->d_cmd &= ~INFOD_FIRSTBYTES;
8264 	}
8265 	if (cmd & INFOD_COPYOUT) {
8266 		mblk_t *mp1 = mp->b_cont;
8267 		int n;
8268 		/*
8269 		 * Return data contents of first message.
8270 		 */
8271 		ASSERT(DB_TYPE(mp1) == M_DATA);
8272 		while (mp1 != NULL && dp->d_uiop->uio_resid > 0) {
8273 			n = MIN(dp->d_uiop->uio_resid, MBLKL(mp1));
8274 			if (n != 0 && (error = uiomove((char *)mp1->b_rptr, n,
8275 			    UIO_READ, dp->d_uiop)) != 0) {
8276 				goto done;
8277 			}
8278 			mp1 = mp1->b_cont;
8279 		}
8280 		res |= INFOD_COPYOUT;
8281 		dp->d_cmd &= ~INFOD_COPYOUT;
8282 	}
8283 done:
8284 	mutex_exit(&udp->udp_drain_lock);
8285 
8286 	dp->d_res |= res;
8287 
8288 	return (error);
8289 }
8290 
8291 /*
8292  * Read-side synchronous stream entry point.  This is called as a result
8293  * of recv/read operation done at sockfs, and is guaranteed to execute
8294  * outside of the interrupt thread context.  It returns a single datagram
8295  * (b_cont chain of T_UNITDATA_IND plus data) to the upper layer.
8296  */
8297 static int
8298 udp_rrw(queue_t *q, struiod_t *dp)
8299 {
8300 	mblk_t	*mp;
8301 	udp_t	*udp = Q_TO_UDP(_RD(UDP_WR(q)));
8302 
8303 	/* We should never get here when we're in SNMP mode */
8304 	ASSERT(!(udp->udp_connp->conn_flags & IPCL_UDPMOD));
8305 
8306 	/*
8307 	 * Dequeue datagram from the head of the list and return
8308 	 * it to caller; also ensure that RSLEEP sd_wakeq flag is
8309 	 * set/cleared depending on whether or not there's data
8310 	 * remaining in the list.
8311 	 */
8312 	mutex_enter(&udp->udp_drain_lock);
8313 	if (!udp->udp_direct_sockfs) {
8314 		mutex_exit(&udp->udp_drain_lock);
8315 		UDP_STAT(udp_rrw_busy);
8316 		return (EBUSY);
8317 	}
8318 	if ((mp = udp->udp_rcv_list_head) != NULL) {
8319 		uint_t size = msgdsize(mp);
8320 
8321 		/* Last datagram in the list? */
8322 		if ((udp->udp_rcv_list_head = mp->b_next) == NULL)
8323 			udp->udp_rcv_list_tail = NULL;
8324 		mp->b_next = NULL;
8325 
8326 		udp->udp_rcv_cnt -= size;
8327 		udp->udp_rcv_msgcnt--;
8328 		UDP_STAT(udp_rrw_msgcnt);
8329 
8330 		/* No longer flow-controlling? */
8331 		if (udp->udp_rcv_cnt < udp->udp_rcv_hiwat &&
8332 		    udp->udp_rcv_msgcnt < udp->udp_rcv_hiwat)
8333 			udp->udp_drain_qfull = B_FALSE;
8334 	}
8335 	if (udp->udp_rcv_list_head == NULL) {
8336 		/*
8337 		 * Either we just dequeued the last datagram or
8338 		 * we get here from sockfs and have nothing to
8339 		 * return; in this case clear RSLEEP.
8340 		 */
8341 		ASSERT(udp->udp_rcv_cnt == 0);
8342 		ASSERT(udp->udp_rcv_msgcnt == 0);
8343 		ASSERT(udp->udp_rcv_list_tail == NULL);
8344 		STR_WAKEUP_CLEAR(STREAM(q));
8345 	} else {
8346 		/*
8347 		 * More data follows; we need udp_rrw() to be
8348 		 * called in future to pick up the rest.
8349 		 */
8350 		STR_WAKEUP_SET(STREAM(q));
8351 	}
8352 	mutex_exit(&udp->udp_drain_lock);
8353 	dp->d_mp = mp;
8354 	return (0);
8355 }
8356 
8357 /*
8358  * Enqueue a completely-built T_UNITDATA_IND message into the receive
8359  * list; this is typically executed within the interrupt thread context
8360  * and so we do things as quickly as possible.
8361  */
8362 static void
8363 udp_rcv_enqueue(queue_t *q, udp_t *udp, mblk_t *mp, uint_t pkt_len)
8364 {
8365 	ASSERT(q == RD(q));
8366 	ASSERT(pkt_len == msgdsize(mp));
8367 	ASSERT(mp->b_next == NULL && mp->b_cont != NULL);
8368 	ASSERT(DB_TYPE(mp) == M_PROTO && DB_TYPE(mp->b_cont) == M_DATA);
8369 	ASSERT(MBLKL(mp) >= sizeof (struct T_unitdata_ind));
8370 
8371 	mutex_enter(&udp->udp_drain_lock);
8372 	/*
8373 	 * Wake up and signal the receiving app; it is okay to do this
8374 	 * before enqueueing the mp because we are holding the drain lock.
8375 	 * One of the advantages of synchronous stream is the ability for
8376 	 * us to find out when the application performs a read on the
8377 	 * socket by way of udp_rrw() entry point being called.  We need
8378 	 * to generate SIGPOLL/SIGIO for each received data in the case
8379 	 * of asynchronous socket just as in the strrput() case.  However,
8380 	 * we only wake the application up when necessary, i.e. during the
8381 	 * first enqueue.  When udp_rrw() is called, we send up a single
8382 	 * datagram upstream and call STR_WAKEUP_SET() again when there
8383 	 * are still data remaining in our receive queue.
8384 	 */
8385 	if (udp->udp_rcv_list_head == NULL) {
8386 		STR_WAKEUP_SET(STREAM(q));
8387 		udp->udp_rcv_list_head = mp;
8388 	} else {
8389 		udp->udp_rcv_list_tail->b_next = mp;
8390 	}
8391 	udp->udp_rcv_list_tail = mp;
8392 	udp->udp_rcv_cnt += pkt_len;
8393 	udp->udp_rcv_msgcnt++;
8394 
8395 	/* Need to flow-control? */
8396 	if (udp->udp_rcv_cnt >= udp->udp_rcv_hiwat ||
8397 	    udp->udp_rcv_msgcnt >= udp->udp_rcv_hiwat)
8398 		udp->udp_drain_qfull = B_TRUE;
8399 
8400 	/* Update poll events and send SIGPOLL/SIGIO if necessary */
8401 	STR_SENDSIG(STREAM(q));
8402 	mutex_exit(&udp->udp_drain_lock);
8403 }
8404 
8405 /*
8406  * Drain the contents of receive list to the module upstream; we do
8407  * this during close or when we fallback to the slow mode due to
8408  * sockmod being popped or a module being pushed on top of us.
8409  */
8410 static void
8411 udp_rcv_drain(queue_t *q, udp_t *udp, boolean_t closing)
8412 {
8413 	mblk_t *mp;
8414 
8415 	ASSERT(q == RD(q));
8416 
8417 	mutex_enter(&udp->udp_drain_lock);
8418 	/*
8419 	 * There is no race with a concurrent udp_input() sending
8420 	 * up packets using putnext() after we have cleared the
8421 	 * udp_direct_sockfs flag but before we have completed
8422 	 * sending up the packets in udp_rcv_list, since we are
8423 	 * either a writer or we have quiesced the conn.
8424 	 */
8425 	udp->udp_direct_sockfs = B_FALSE;
8426 	mutex_exit(&udp->udp_drain_lock);
8427 
8428 	if (udp->udp_rcv_list_head != NULL)
8429 		UDP_STAT(udp_drain);
8430 
8431 	/*
8432 	 * Send up everything via putnext(); note here that we
8433 	 * don't need the udp_drain_lock to protect us since
8434 	 * nothing can enter udp_rrw() and that we currently
8435 	 * have exclusive access to this udp.
8436 	 */
8437 	while ((mp = udp->udp_rcv_list_head) != NULL) {
8438 		udp->udp_rcv_list_head = mp->b_next;
8439 		mp->b_next = NULL;
8440 		udp->udp_rcv_cnt -= msgdsize(mp);
8441 		udp->udp_rcv_msgcnt--;
8442 		if (closing) {
8443 			freemsg(mp);
8444 		} else {
8445 			putnext(q, mp);
8446 		}
8447 	}
8448 	ASSERT(udp->udp_rcv_cnt == 0);
8449 	ASSERT(udp->udp_rcv_msgcnt == 0);
8450 	ASSERT(udp->udp_rcv_list_head == NULL);
8451 	udp->udp_rcv_list_tail = NULL;
8452 	udp->udp_drain_qfull = B_FALSE;
8453 }
8454 
8455 static size_t
8456 udp_set_rcv_hiwat(udp_t *udp, size_t size)
8457 {
8458 	/* We add a bit of extra buffering */
8459 	size += size >> 1;
8460 	if (size > udp_max_buf)
8461 		size = udp_max_buf;
8462 
8463 	udp->udp_rcv_hiwat = size;
8464 	return (size);
8465 }
8466 
8467 /*
8468  * Little helper for IPsec's NAT-T processing.
8469  */
8470 boolean_t
8471 udp_compute_checksum(void)
8472 {
8473 	return (udp_do_checksum);
8474 }
8475