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