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