xref: /titanic_41/usr/src/uts/common/inet/ip/ip.c (revision cbab2b2687744cbfdc12fae90f8088127a0b266c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/kstatcom.h>
72 
73 #include <netinet/igmp_var.h>
74 #include <netinet/ip6.h>
75 #include <netinet/icmp6.h>
76 #include <netinet/sctp.h>
77 
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip6_asp.h>
82 #include <inet/tcp.h>
83 #include <inet/tcp_impl.h>
84 #include <inet/ip_multi.h>
85 #include <inet/ip_if.h>
86 #include <inet/ip_ire.h>
87 #include <inet/ip_rts.h>
88 #include <inet/optcom.h>
89 #include <inet/ip_ndp.h>
90 #include <inet/ip_listutils.h>
91 #include <netinet/igmp.h>
92 #include <netinet/ip_mroute.h>
93 #include <inet/ipp_common.h>
94 
95 #include <net/pfkeyv2.h>
96 #include <inet/ipsec_info.h>
97 #include <inet/sadb.h>
98 #include <inet/ipsec_impl.h>
99 #include <sys/iphada.h>
100 #include <inet/tun.h>
101 #include <inet/ipdrop.h>
102 
103 #include <sys/ethernet.h>
104 #include <net/if_types.h>
105 #include <sys/cpuvar.h>
106 
107 #include <ipp/ipp.h>
108 #include <ipp/ipp_impl.h>
109 #include <ipp/ipgpc/ipgpc.h>
110 
111 #include <sys/multidata.h>
112 #include <sys/pattr.h>
113 
114 #include <inet/ipclassifier.h>
115 #include <inet/sctp_ip.h>
116 #include <inet/sctp/sctp_impl.h>
117 #include <inet/udp_impl.h>
118 
119 #include <sys/tsol/label.h>
120 #include <sys/tsol/tnet.h>
121 
122 #include <rpc/pmap_prot.h>
123 
124 /*
125  * Values for squeue switch:
126  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
127  * IP_SQUEUE_ENTER: squeue_enter
128  * IP_SQUEUE_FILL: squeue_fill
129  */
130 int ip_squeue_enter = 2;
131 squeue_func_t ip_input_proc;
132 /*
133  * IP statistics.
134  */
135 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
136 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
137 
138 typedef struct ip_stat {
139 	kstat_named_t	ipsec_fanout_proto;
140 	kstat_named_t	ip_udp_fannorm;
141 	kstat_named_t	ip_udp_fanmb;
142 	kstat_named_t	ip_udp_fanothers;
143 	kstat_named_t	ip_udp_fast_path;
144 	kstat_named_t	ip_udp_slow_path;
145 	kstat_named_t	ip_udp_input_err;
146 	kstat_named_t	ip_tcppullup;
147 	kstat_named_t	ip_tcpoptions;
148 	kstat_named_t	ip_multipkttcp;
149 	kstat_named_t	ip_tcp_fast_path;
150 	kstat_named_t	ip_tcp_slow_path;
151 	kstat_named_t	ip_tcp_input_error;
152 	kstat_named_t	ip_db_ref;
153 	kstat_named_t	ip_notaligned1;
154 	kstat_named_t	ip_notaligned2;
155 	kstat_named_t	ip_multimblk3;
156 	kstat_named_t	ip_multimblk4;
157 	kstat_named_t	ip_ipoptions;
158 	kstat_named_t	ip_classify_fail;
159 	kstat_named_t	ip_opt;
160 	kstat_named_t	ip_udp_rput_local;
161 	kstat_named_t	ipsec_proto_ahesp;
162 	kstat_named_t	ip_conn_flputbq;
163 	kstat_named_t	ip_conn_walk_drain;
164 	kstat_named_t   ip_out_sw_cksum;
165 	kstat_named_t   ip_in_sw_cksum;
166 	kstat_named_t   ip_trash_ire_reclaim_calls;
167 	kstat_named_t   ip_trash_ire_reclaim_success;
168 	kstat_named_t   ip_ire_arp_timer_expired;
169 	kstat_named_t   ip_ire_redirect_timer_expired;
170 	kstat_named_t	ip_ire_pmtu_timer_expired;
171 	kstat_named_t	ip_input_multi_squeue;
172 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
173 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
174 	kstat_named_t	ip_tcp_in_sw_cksum_err;
175 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
176 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
177 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
178 	kstat_named_t	ip_udp_in_sw_cksum_err;
179 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
180 	kstat_named_t	ip_frag_mdt_pkt_out;
181 	kstat_named_t	ip_frag_mdt_discarded;
182 	kstat_named_t	ip_frag_mdt_allocfail;
183 	kstat_named_t	ip_frag_mdt_addpdescfail;
184 	kstat_named_t	ip_frag_mdt_allocd;
185 } ip_stat_t;
186 
187 static ip_stat_t ip_statistics = {
188 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
189 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
190 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
191 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
192 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
195 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
196 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
197 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
198 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
201 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
202 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
203 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
204 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
205 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
206 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
207 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
208 	{ "ip_opt",				KSTAT_DATA_UINT64 },
209 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
210 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
211 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
212 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
213 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
214 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
215 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
216 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
217 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
218 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
219 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
220 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
221 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
222 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
223 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
224 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
225 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
226 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
228 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
229 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
230 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
231 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
232 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
234 };
235 
236 static kstat_t *ip_kstat;
237 
238 #define	TCP6 "tcp6"
239 #define	TCP "tcp"
240 #define	SCTP "sctp"
241 #define	SCTP6 "sctp6"
242 
243 major_t TCP6_MAJ;
244 major_t TCP_MAJ;
245 major_t SCTP_MAJ;
246 major_t SCTP6_MAJ;
247 
248 int ip_poll_normal_ms = 100;
249 int ip_poll_normal_ticks = 0;
250 
251 /*
252  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
253  */
254 
255 struct listptr_s {
256 	mblk_t	*lp_head;	/* pointer to the head of the list */
257 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
258 };
259 
260 typedef struct listptr_s listptr_t;
261 
262 /*
263  * This is used by ip_snmp_get_mib2_ip_route_media and
264  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
265  */
266 typedef struct iproutedata_s {
267 	uint_t		ird_idx;
268 	listptr_t	ird_route;	/* ipRouteEntryTable */
269 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
270 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
271 } iproutedata_t;
272 
273 /*
274  * Cluster specific hooks. These should be NULL when booted as a non-cluster
275  */
276 
277 /*
278  * Hook functions to enable cluster networking
279  * On non-clustered systems these vectors must always be NULL.
280  *
281  * Hook function to Check ip specified ip address is a shared ip address
282  * in the cluster
283  *
284  */
285 int (*cl_inet_isclusterwide)(uint8_t protocol,
286     sa_family_t addr_family, uint8_t *laddrp) = NULL;
287 
288 /*
289  * Hook function to generate cluster wide ip fragment identifier
290  */
291 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
292     uint8_t *laddrp, uint8_t *faddrp) = NULL;
293 
294 /*
295  * Synchronization notes:
296  *
297  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
298  * MT level protection given by STREAMS. IP uses a combination of its own
299  * internal serialization mechanism and standard Solaris locking techniques.
300  * The internal serialization is per phyint (no IPMP) or per IPMP group.
301  * This is used to serialize plumbing operations, IPMP operations, certain
302  * multicast operations, most set ioctls, igmp/mld timers etc.
303  *
304  * Plumbing is a long sequence of operations involving message
305  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
306  * involved in plumbing operations. A natural model is to serialize these
307  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
308  * parallel without any interference. But various set ioctls on hme0 are best
309  * serialized. However if the system uses IPMP, the operations are easier if
310  * they are serialized on a per IPMP group basis since IPMP operations
311  * happen across ill's of a group. Thus the lowest common denominator is to
312  * serialize most set ioctls, multicast join/leave operations, IPMP operations
313  * igmp/mld timer operations, and processing of DLPI control messages received
314  * from drivers on a per IPMP group basis. If the system does not employ
315  * IPMP the serialization is on a per phyint basis. This serialization is
316  * provided by the ipsq_t and primitives operating on this. Details can
317  * be found in ip_if.c above the core primitives operating on ipsq_t.
318  *
319  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
320  * Simiarly lookup of an ire by a thread also returns a refheld ire.
321  * In addition ipif's and ill's referenced by the ire are also indirectly
322  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
323  * the ipif's address or netmask change as long as an ipif is refheld
324  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
325  * address of an ipif has to go through the ipsq_t. This ensures that only
326  * 1 such exclusive operation proceeds at any time on the ipif. It then
327  * deletes all ires associated with this ipif, and waits for all refcnts
328  * associated with this ipif to come down to zero. The address is changed
329  * only after the ipif has been quiesced. Then the ipif is brought up again.
330  * More details are described above the comment in ip_sioctl_flags.
331  *
332  * Packet processing is based mostly on IREs and are fully multi-threaded
333  * using standard Solaris MT techniques.
334  *
335  * There are explicit locks in IP to handle:
336  * - The ip_g_head list maintained by mi_open_link() and friends.
337  *
338  * - The reassembly data structures (one lock per hash bucket)
339  *
340  * - conn_lock is meant to protect conn_t fields. The fields actually
341  *   protected by conn_lock are documented in the conn_t definition.
342  *
343  * - ire_lock to protect some of the fields of the ire, IRE tables
344  *   (one lock per hash bucket). Refer to ip_ire.c for details.
345  *
346  * - ndp_g_lock and nce_lock for protecting NCEs.
347  *
348  * - ill_lock protects fields of the ill and ipif. Details in ip.h
349  *
350  * - ill_g_lock: This is a global reader/writer lock. Protects the following
351  *	* The AVL tree based global multi list of all ills.
352  *	* The linked list of all ipifs of an ill
353  *	* The <ill-ipsq> mapping
354  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
355  *	* The illgroup list threaded by ill_group_next.
356  *	* <ill-phyint> association
357  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
358  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
359  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
360  *   will all have to hold the ill_g_lock as writer for the actual duration
361  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
362  *   may be found in the IPMP section.
363  *
364  * - ill_lock:  This is a per ill mutex.
365  *   It protects some members of the ill and is documented below.
366  *   It also protects the <ill-ipsq> mapping
367  *   It also protects the illgroup list threaded by ill_group_next.
368  *   It also protects the <ill-phyint> assoc.
369  *   It also protects the list of ipifs hanging off the ill.
370  *
371  * - ipsq_lock: This is a per ipsq_t mutex lock.
372  *   This protects all the other members of the ipsq struct except
373  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
374  *
375  * - illgrp_lock: This is a per ill_group mutex lock.
376  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
377  *   which dictates which is the next ill in an ill_group that is to be chosen
378  *   for sending outgoing packets, through creation of an IRE_CACHE that
379  *   references this ill.
380  *
381  * - phyint_lock: This is a per phyint mutex lock. Protects just the
382  *   phyint_flags
383  *
384  * - ip_g_nd_lock: This is a global reader/writer lock.
385  *   Any call to nd_load to load a new parameter to the ND table must hold the
386  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
387  *   as reader.
388  *
389  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
390  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
391  *   uniqueness check also done atomically.
392  *
393  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
394  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
395  *   as a writer when adding or deleting elements from these lists, and
396  *   as a reader when walking these lists to send a SADB update to the
397  *   IPsec capable ills.
398  *
399  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
400  *   group list linked by ill_usesrc_grp_next. It also protects the
401  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
402  *   group is being added or deleted.  This lock is taken as a reader when
403  *   walking the list/group(eg: to get the number of members in a usesrc group).
404  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
405  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
406  *   example, it is not necessary to take this lock in the initial portion
407  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
408  *   ip_sioctl_flags since the these operations are executed exclusively and
409  *   that ensures that the "usesrc group state" cannot change. The "usesrc
410  *   group state" change can happen only in the latter part of
411  *   ip_sioctl_slifusesrc and in ill_delete.
412  *
413  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
414  *
415  * To change the <ill-phyint> association, the ill_g_lock must be held
416  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
417  * must be held.
418  *
419  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
420  * and the ill_lock of the ill in question must be held.
421  *
422  * To change the <ill-illgroup> association the ill_g_lock must be held as
423  * writer and the ill_lock of the ill in question must be held.
424  *
425  * To add or delete an ipif from the list of ipifs hanging off the ill,
426  * ill_g_lock (writer) and ill_lock must be held and the thread must be
427  * a writer on the associated ipsq,.
428  *
429  * To add or delete an ill to the system, the ill_g_lock must be held as
430  * writer and the thread must be a writer on the associated ipsq.
431  *
432  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
433  * must be a writer on the associated ipsq.
434  *
435  * Lock hierarchy
436  *
437  * Some lock hierarchy scenarios are listed below.
438  *
439  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
440  * ill_g_lock -> illgrp_lock -> ill_lock
441  * ill_g_lock -> ill_lock(s) -> phyint_lock
442  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
443  * ill_g_lock -> ip_addr_avail_lock
444  * conn_lock -> irb_lock -> ill_lock -> ire_lock
445  * ill_g_lock -> ip_g_nd_lock
446  *
447  * When more than 1 ill lock is needed to be held, all ill lock addresses
448  * are sorted on address and locked starting from highest addressed lock
449  * downward.
450  *
451  * Mobile-IP scenarios
452  *
453  * irb_lock -> ill_lock -> ire_mrtun_lock
454  * irb_lock -> ill_lock -> ire_srcif_table_lock
455  *
456  * IPsec scenarios
457  *
458  * ipsa_lock -> ill_g_lock -> ill_lock
459  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
460  * ipsec_capab_ills_lock -> ipsa_lock
461  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
462  *
463  * Trusted Solaris scenarios
464  *
465  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
466  * igsa_lock -> gcdb_lock
467  * gcgrp_rwlock -> ire_lock
468  * gcgrp_rwlock -> gcdb_lock
469  *
470  * IPSEC notes :
471  *
472  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
473  * in front of the actual packet. For outbound datagrams, the M_CTL
474  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
475  * information used by the IPSEC code for applying the right level of
476  * protection. The information initialized by IP in the ipsec_out_t
477  * is determined by the per-socket policy or global policy in the system.
478  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
479  * ipsec_info.h) which starts out with nothing in it. It gets filled
480  * with the right information if it goes through the AH/ESP code, which
481  * happens if the incoming packet is secure. The information initialized
482  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
483  * the policy requirements needed by per-socket policy or global policy
484  * is met or not.
485  *
486  * If there is both per-socket policy (set using setsockopt) and there
487  * is also global policy match for the 5 tuples of the socket,
488  * ipsec_override_policy() makes the decision of which one to use.
489  *
490  * For fully connected sockets i.e dst, src [addr, port] is known,
491  * conn_policy_cached is set indicating that policy has been cached.
492  * conn_in_enforce_policy may or may not be set depending on whether
493  * there is a global policy match or per-socket policy match.
494  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
495  * Once the right policy is set on the conn_t, policy cannot change for
496  * this socket. This makes life simpler for TCP (UDP ?) where
497  * re-transmissions go out with the same policy. For symmetry, policy
498  * is cached for fully connected UDP sockets also. Thus if policy is cached,
499  * it also implies that policy is latched i.e policy cannot change
500  * on these sockets. As we have the right policy on the conn, we don't
501  * have to lookup global policy for every outbound and inbound datagram
502  * and thus serving as an optimization. Note that a global policy change
503  * does not affect fully connected sockets if they have policy. If fully
504  * connected sockets did not have any policy associated with it, global
505  * policy change may affect them.
506  *
507  * IP Flow control notes:
508  *
509  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
510  * cannot be sent down to the driver by IP, because of a canput failure, IP
511  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
512  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
513  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
514  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
515  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
516  * the queued messages, and removes the conn from the drain list, if all
517  * messages were drained. It also qenables the next conn in the drain list to
518  * continue the drain process.
519  *
520  * In reality the drain list is not a single list, but a configurable number
521  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
522  * list. If the ip_wsrv of the next qenabled conn does not run, because the
523  * stream closes, ip_close takes responsibility to qenable the next conn in
524  * the drain list. The directly called ip_wput path always does a putq, if
525  * it cannot putnext. Thus synchronization problems are handled between
526  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
527  * functions that manipulate this drain list. Furthermore conn_drain_insert
528  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
529  * running on a queue at any time. conn_drain_tail can be simultaneously called
530  * from both ip_wsrv and ip_close.
531  *
532  * IPQOS notes:
533  *
534  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
535  * and IPQoS modules. IPPF includes hooks in IP at different control points
536  * (callout positions) which direct packets to IPQoS modules for policy
537  * processing. Policies, if present, are global.
538  *
539  * The callout positions are located in the following paths:
540  *		o local_in (packets destined for this host)
541  *		o local_out (packets orginating from this host )
542  *		o fwd_in  (packets forwarded by this m/c - inbound)
543  *		o fwd_out (packets forwarded by this m/c - outbound)
544  * Hooks at these callout points can be enabled/disabled using the ndd variable
545  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
546  * By default all the callout positions are enabled.
547  *
548  * Outbound (local_out)
549  * Hooks are placed in ip_wput_ire and ipsec_out_process.
550  *
551  * Inbound (local_in)
552  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
553  * TCP and UDP fanout routines.
554  *
555  * Forwarding (in and out)
556  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
557  *
558  * IP Policy Framework processing (IPPF processing)
559  * Policy processing for a packet is initiated by ip_process, which ascertains
560  * that the classifier (ipgpc) is loaded and configured, failing which the
561  * packet resumes normal processing in IP. If the clasifier is present, the
562  * packet is acted upon by one or more IPQoS modules (action instances), per
563  * filters configured in ipgpc and resumes normal IP processing thereafter.
564  * An action instance can drop a packet in course of its processing.
565  *
566  * A boolean variable, ip_policy, is used in all the fanout routines that can
567  * invoke ip_process for a packet. This variable indicates if the packet should
568  * to be sent for policy processing. The variable is set to B_TRUE by default,
569  * i.e. when the routines are invoked in the normal ip procesing path for a
570  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
571  * ip_policy is set to B_FALSE for all the routines called in these two
572  * functions because, in the former case,  we don't process loopback traffic
573  * currently while in the latter, the packets have already been processed in
574  * icmp_inbound.
575  *
576  * Zones notes:
577  *
578  * The partitioning rules for networking are as follows:
579  * 1) Packets coming from a zone must have a source address belonging to that
580  * zone.
581  * 2) Packets coming from a zone can only be sent on a physical interface on
582  * which the zone has an IP address.
583  * 3) Between two zones on the same machine, packet delivery is only allowed if
584  * there's a matching route for the destination and zone in the forwarding
585  * table.
586  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
587  * different zones can bind to the same port with the wildcard address
588  * (INADDR_ANY).
589  *
590  * The granularity of interface partitioning is at the logical interface level.
591  * Therefore, every zone has its own IP addresses, and incoming packets can be
592  * attributed to a zone unambiguously. A logical interface is placed into a zone
593  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
594  * structure. Rule (1) is implemented by modifying the source address selection
595  * algorithm so that the list of eligible addresses is filtered based on the
596  * sending process zone.
597  *
598  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
599  * across all zones, depending on their type. Here is the break-up:
600  *
601  * IRE type				Shared/exclusive
602  * --------				----------------
603  * IRE_BROADCAST			Exclusive
604  * IRE_DEFAULT (default routes)		Shared (*)
605  * IRE_LOCAL				Exclusive
606  * IRE_LOOPBACK				Exclusive
607  * IRE_PREFIX (net routes)		Shared (*)
608  * IRE_CACHE				Exclusive
609  * IRE_IF_NORESOLVER (interface routes)	Exclusive
610  * IRE_IF_RESOLVER (interface routes)	Exclusive
611  * IRE_HOST (host routes)		Shared (*)
612  *
613  * (*) A zone can only use a default or off-subnet route if the gateway is
614  * directly reachable from the zone, that is, if the gateway's address matches
615  * one of the zone's logical interfaces.
616  *
617  * Multiple zones can share a common broadcast address; typically all zones
618  * share the 255.255.255.255 address. Incoming as well as locally originated
619  * broadcast packets must be dispatched to all the zones on the broadcast
620  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
621  * since some zones may not be on the 10.16.72/24 network. To handle this, each
622  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
623  * sent to every zone that has an IRE_BROADCAST entry for the destination
624  * address on the input ill, see conn_wantpacket().
625  *
626  * Applications in different zones can join the same multicast group address.
627  * For IPv4, group memberships are per-logical interface, so they're already
628  * inherently part of a zone. For IPv6, group memberships are per-physical
629  * interface, so we distinguish IPv6 group memberships based on group address,
630  * interface and zoneid. In both cases, received multicast packets are sent to
631  * every zone for which a group membership entry exists. On IPv6 we need to
632  * check that the target zone still has an address on the receiving physical
633  * interface; it could have been removed since the application issued the
634  * IPV6_JOIN_GROUP.
635  */
636 
637 /*
638  * Squeue Fanout flags:
639  *	0: No fanout.
640  *	1: Fanout across all squeues
641  */
642 boolean_t	ip_squeue_fanout = 0;
643 
644 /*
645  * Maximum dups allowed per packet.
646  */
647 uint_t ip_max_frag_dups = 10;
648 
649 #define	IS_SIMPLE_IPH(ipha)						\
650 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
651 
652 /* RFC1122 Conformance */
653 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
654 
655 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
656 
657 /* Leave room for ip_newroute to tack on the src and target addresses */
658 #define	OK_RESOLVER_MP(mp)						\
659 	((mp) && ((mp)->b_wptr - (mp)->b_rptr) >= (2 * IP_ADDR_LEN))
660 
661 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
662 
663 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
664 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
665 
666 static void	icmp_frag_needed(queue_t *, mblk_t *, int);
667 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
668     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
669 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
670 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
671 		    mblk_t *mp);
672 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
673 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
674 		    ill_t *, zoneid_t);
675 static void	icmp_options_update(ipha_t *);
676 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t);
677 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t);
678 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
679 static void	icmp_redirect(mblk_t *);
680 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
681 
682 static void	ip_arp_news(queue_t *, mblk_t *);
683 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
684 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
685 char		*ip_dot_addr(ipaddr_t, char *);
686 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
687 int		ip_close(queue_t *, int);
688 static char	*ip_dot_saddr(uchar_t *, char *);
689 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
690 		    boolean_t, boolean_t, ill_t *, zoneid_t);
691 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
692 		    boolean_t, boolean_t, zoneid_t);
693 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
694 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
695 static void	ip_lrput(queue_t *, mblk_t *);
696 ipaddr_t	ip_massage_options(ipha_t *);
697 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
698 ipaddr_t	ip_net_mask(ipaddr_t);
699 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *);
700 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
701 		    conn_t *, uint32_t);
702 static int	ip_hdr_complete(ipha_t *, zoneid_t);
703 char		*ip_nv_lookup(nv_t *, int);
704 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
705 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
706 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
707 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
708 			    size_t);
709 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
710 void	ip_rput(queue_t *, mblk_t *);
711 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
712 		    void *dummy_arg);
713 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
714 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
715 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
716 			    ire_t *);
717 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
718 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
719 		    uint16_t *);
720 int		ip_snmp_get(queue_t *, mblk_t *);
721 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
722 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
723 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
724 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
725 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
726 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
727 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
728 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
729 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
730 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
731 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
732 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
733 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
734 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
735 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
736 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
737 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
738 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
739 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
740 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
741 static boolean_t	ip_source_routed(ipha_t *);
742 static boolean_t	ip_source_route_included(ipha_t *);
743 
744 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t);
745 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
746 static void	ip_wput_local_options(ipha_t *);
747 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
748     zoneid_t);
749 
750 static void	conn_drain_init(void);
751 static void	conn_drain_fini(void);
752 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
753 
754 static void	conn_walk_drain(void);
755 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
756     zoneid_t);
757 
758 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
759     zoneid_t);
760 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
761     void *dummy_arg);
762 
763 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
764 
765 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
766     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
767     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
768 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
769 
770 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
771 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
772     caddr_t, cred_t *);
773 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
774     caddr_t cp, cred_t *cr);
775 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
776     cred_t *);
777 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
778     caddr_t cp, cred_t *cr);
779 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
780     cred_t *);
781 static squeue_func_t ip_squeue_switch(int);
782 
783 static void	ip_kstat_init(void);
784 static void	ip_kstat_fini(void);
785 static int	ip_kstat_update(kstat_t *kp, int rw);
786 static void	icmp_kstat_init(void);
787 static void	icmp_kstat_fini(void);
788 static int	icmp_kstat_update(kstat_t *kp, int rw);
789 
790 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
791 
792 static boolean_t	ip_no_forward(ipha_t *, ill_t *);
793 static boolean_t	ip_loopback_src_or_dst(ipha_t *, ill_t *);
794 
795 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
796     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
797 
798 void	ip_input(ill_t *, ill_rx_ring_t *, mblk_t *, size_t);
799 
800 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
801 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
802 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
803 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
804 
805 uint_t	ip_ire_default_count;	/* Number of IPv4 IRE_DEFAULT entries. */
806 uint_t	ip_ire_default_index;	/* Walking index used to mod in */
807 
808 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
809 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
810 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
811 
812 /* How long, in seconds, we allow frags to hang around. */
813 #define	IP_FRAG_TIMEOUT	60
814 
815 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
816 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
817 
818 /*
819  * Threshold which determines whether MDT should be used when
820  * generating IP fragments; payload size must be greater than
821  * this threshold for MDT to take place.
822  */
823 #define	IP_WPUT_FRAG_MDT_MIN	32768
824 
825 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
826 
827 /* Protected by ip_mi_lock */
828 static void	*ip_g_head;		/* Instance Data List Head */
829 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
830 
831 /* Only modified during _init and _fini thus no locking is needed. */
832 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
833 
834 
835 static long ip_rput_pullups;
836 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
837 
838 vmem_t *ip_minor_arena;
839 
840 /*
841  * MIB-2 stuff for SNMP (both IP and ICMP)
842  */
843 mib2_ip_t	ip_mib;
844 mib2_icmp_t	icmp_mib;
845 
846 #ifdef DEBUG
847 uint32_t ipsechw_debug = 0;
848 #endif
849 
850 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
851 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
852 
853 uint_t	loopback_packets = 0;
854 
855 /*
856  * Multirouting/CGTP stuff
857  */
858 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
859 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
860 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
861 /* Interval (in ms) between consecutive 'bad MTU' warnings */
862 hrtime_t ip_multirt_log_interval = 1000;
863 /* Time since last warning issued. */
864 static hrtime_t	multirt_bad_mtu_last_time = 0;
865 
866 kmutex_t ip_trash_timer_lock;
867 krwlock_t ip_g_nd_lock;
868 
869 /*
870  * XXX following really should only be in a header. Would need more
871  * header and .c clean up first.
872  */
873 extern optdb_obj_t	ip_opt_obj;
874 
875 ulong_t ip_squeue_enter_unbound = 0;
876 
877 /*
878  * Named Dispatch Parameter Table.
879  * All of these are alterable, within the min/max values given, at run time.
880  */
881 static ipparam_t	lcl_param_arr[] = {
882 	/* min	max	value	name */
883 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
884 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
885 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
886 	{  0,	1,	0,	"ip_respond_to_timestamp"},
887 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
888 	{  0,	1,	1,	"ip_send_redirects"},
889 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
890 	{  0,	10,	0,	"ip_debug"},
891 	{  0,	10,	0,	"ip_mrtdebug"},
892 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
893 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
894 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
895 	{  1,	255,	255,	"ip_def_ttl" },
896 	{  0,	1,	0,	"ip_forward_src_routed"},
897 	{  0,	256,	32,	"ip_wroff_extra" },
898 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
899 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
900 	{  0,	1,	1,	"ip_path_mtu_discovery" },
901 	{  0,	240,	30,	"ip_ignore_delete_time" },
902 	{  0,	1,	0,	"ip_ignore_redirect" },
903 	{  0,	1,	1,	"ip_output_queue" },
904 	{  1,	254,	1,	"ip_broadcast_ttl" },
905 	{  0,	99999,	100,	"ip_icmp_err_interval" },
906 	{  1,	99999,	10,	"ip_icmp_err_burst" },
907 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
908 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
909 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
910 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
911 	{  0,	1,	1,	"icmp_accept_clear_messages" },
912 	{  0,	1,	1,	"igmp_accept_clear_messages" },
913 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
914 				"ip_ndp_delay_first_probe_time"},
915 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
916 				"ip_ndp_max_unicast_solicit"},
917 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
918 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
919 	{  0,	1,	0,	"ip6_forward_src_routed"},
920 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
921 	{  0,	1,	1,	"ip6_send_redirects"},
922 	{  0,	1,	0,	"ip6_ignore_redirect" },
923 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
924 
925 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
926 
927 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
928 
929 	{  0,	1,	1,	"pim_accept_clear_messages" },
930 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
931 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
932 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
933 	{  0,	15,	0,	"ip_policy_mask" },
934 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
935 	{  0,	255,	1,	"ip_multirt_ttl" },
936 	{  0,	1,	1,	"ip_multidata_outbound" },
937 #ifdef DEBUG
938 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
939 #endif
940 };
941 
942 ipparam_t	*ip_param_arr = lcl_param_arr;
943 
944 /* Extended NDP table */
945 static ipndp_t	lcl_ndp_arr[] = {
946 	/* getf			setf		data			name */
947 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
948 	    "ip_forwarding" },
949 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
950 	    "ip6_forwarding" },
951 	{  ip_ill_report,	NULL,		NULL,
952 	    "ip_ill_status" },
953 	{  ip_ipif_report,	NULL,		NULL,
954 	    "ip_ipif_status" },
955 	{  ip_ire_report,	NULL,		NULL,
956 	    "ipv4_ire_status" },
957 	{  ip_ire_report_mrtun,	NULL,		NULL,
958 	    "ipv4_mrtun_ire_status" },
959 	{  ip_ire_report_srcif,	NULL,		NULL,
960 	    "ipv4_srcif_ire_status" },
961 	{  ip_ire_report_v6,	NULL,		NULL,
962 	    "ipv6_ire_status" },
963 	{  ip_conn_report,	NULL,		NULL,
964 	    "ip_conn_status" },
965 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
966 	    "ip_rput_pullups" },
967 	{  ndp_report,		NULL,		NULL,
968 	    "ip_ndp_cache_report" },
969 	{  ip_srcid_report,	NULL,		NULL,
970 	    "ip_srcid_status" },
971 	{ ip_param_generic_get, ip_squeue_profile_set,
972 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
973 	{ ip_param_generic_get, ip_squeue_bind_set,
974 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
975 	{ ip_param_generic_get, ip_input_proc_set,
976 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
977 	{ ip_param_generic_get, ip_int_set,
978 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
979 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
980 	    "ip_cgtp_filter" },
981 	{ ip_param_generic_get, ip_int_set,
982 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
983 };
984 
985 /*
986  * ip_g_forward controls IP forwarding.  It takes two values:
987  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
988  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
989  *
990  * RFC1122 says there must be a configuration switch to control forwarding,
991  * but that the default MUST be to not forward packets ever.  Implicit
992  * control based on configuration of multiple interfaces MUST NOT be
993  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
994  * and, in fact, it was the default.  That capability is now provided in the
995  * /etc/rc2.d/S69inet script.
996  */
997 int ip_g_forward = IP_FORWARD_DEFAULT;
998 
999 /* It also has an IPv6 counterpart. */
1000 
1001 int ipv6_forward = IP_FORWARD_DEFAULT;
1002 
1003 /* Following line is external, and in ip.h.  Normally marked with * *. */
1004 #define	ip_respond_to_address_mask_broadcast ip_param_arr[0].ip_param_value
1005 #define	ip_g_resp_to_echo_bcast		ip_param_arr[1].ip_param_value
1006 #define	ip_g_resp_to_echo_mcast		ip_param_arr[2].ip_param_value
1007 #define	ip_g_resp_to_timestamp		ip_param_arr[3].ip_param_value
1008 #define	ip_g_resp_to_timestamp_bcast	ip_param_arr[4].ip_param_value
1009 #define	ip_g_send_redirects		ip_param_arr[5].ip_param_value
1010 #define	ip_g_forward_directed_bcast	ip_param_arr[6].ip_param_value
1011 #define	ip_debug			ip_param_arr[7].ip_param_value	/* */
1012 #define	ip_mrtdebug			ip_param_arr[8].ip_param_value	/* */
1013 #define	ip_timer_interval		ip_param_arr[9].ip_param_value	/* */
1014 #define	ip_ire_arp_interval		ip_param_arr[10].ip_param_value  /* */
1015 #define	ip_ire_redir_interval		ip_param_arr[11].ip_param_value
1016 #define	ip_def_ttl			ip_param_arr[12].ip_param_value
1017 #define	ip_forward_src_routed		ip_param_arr[13].ip_param_value
1018 #define	ip_wroff_extra			ip_param_arr[14].ip_param_value
1019 #define	ip_ire_pathmtu_interval		ip_param_arr[15].ip_param_value
1020 #define	ip_icmp_return			ip_param_arr[16].ip_param_value
1021 #define	ip_path_mtu_discovery		ip_param_arr[17].ip_param_value /* */
1022 #define	ip_ignore_delete_time		ip_param_arr[18].ip_param_value /* */
1023 #define	ip_ignore_redirect		ip_param_arr[19].ip_param_value
1024 #define	ip_output_queue			ip_param_arr[20].ip_param_value
1025 #define	ip_broadcast_ttl		ip_param_arr[21].ip_param_value
1026 #define	ip_icmp_err_interval		ip_param_arr[22].ip_param_value
1027 #define	ip_icmp_err_burst		ip_param_arr[23].ip_param_value
1028 #define	ip_reass_queue_bytes		ip_param_arr[24].ip_param_value
1029 #define	ip_strict_dst_multihoming	ip_param_arr[25].ip_param_value
1030 #define	ip_addrs_per_if			ip_param_arr[26].ip_param_value
1031 #define	ipsec_override_persocket_policy	ip_param_arr[27].ip_param_value /* */
1032 #define	icmp_accept_clear_messages	ip_param_arr[28].ip_param_value
1033 #define	igmp_accept_clear_messages	ip_param_arr[29].ip_param_value
1034 
1035 /* IPv6 configuration knobs */
1036 #define	delay_first_probe_time		ip_param_arr[30].ip_param_value
1037 #define	max_unicast_solicit		ip_param_arr[31].ip_param_value
1038 #define	ipv6_def_hops			ip_param_arr[32].ip_param_value
1039 #define	ipv6_icmp_return		ip_param_arr[33].ip_param_value
1040 #define	ipv6_forward_src_routed		ip_param_arr[34].ip_param_value
1041 #define	ipv6_resp_echo_mcast		ip_param_arr[35].ip_param_value
1042 #define	ipv6_send_redirects		ip_param_arr[36].ip_param_value
1043 #define	ipv6_ignore_redirect		ip_param_arr[37].ip_param_value
1044 #define	ipv6_strict_dst_multihoming	ip_param_arr[38].ip_param_value
1045 #define	ip_ire_reclaim_fraction		ip_param_arr[39].ip_param_value
1046 #define	ipsec_policy_log_interval	ip_param_arr[40].ip_param_value
1047 #define	pim_accept_clear_messages	ip_param_arr[41].ip_param_value
1048 #define	ip_ndp_unsolicit_interval	ip_param_arr[42].ip_param_value
1049 #define	ip_ndp_unsolicit_count		ip_param_arr[43].ip_param_value
1050 #define	ipv6_ignore_home_address_opt	ip_param_arr[44].ip_param_value
1051 #define	ip_policy_mask			ip_param_arr[45].ip_param_value
1052 #define	ip_multirt_resolution_interval  ip_param_arr[46].ip_param_value
1053 #define	ip_multirt_ttl  		ip_param_arr[47].ip_param_value
1054 #define	ip_multidata_outbound		ip_param_arr[48].ip_param_value
1055 #ifdef DEBUG
1056 #define	ipv6_drop_inbound_icmpv6	ip_param_arr[49].ip_param_value
1057 #else
1058 #define	ipv6_drop_inbound_icmpv6	0
1059 #endif
1060 
1061 
1062 /*
1063  * Table of IP ioctls encoding the various properties of the ioctl and
1064  * indexed based on the last byte of the ioctl command. Occasionally there
1065  * is a clash, and there is more than 1 ioctl with the same last byte.
1066  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1067  * ioctls are encoded in the misc table. An entry in the ndx table is
1068  * retrieved by indexing on the last byte of the ioctl command and comparing
1069  * the ioctl command with the value in the ndx table. In the event of a
1070  * mismatch the misc table is then searched sequentially for the desired
1071  * ioctl command.
1072  *
1073  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1074  */
1075 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1076 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 
1087 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1088 			MISC_CMD, ip_siocaddrt, NULL },
1089 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1090 			MISC_CMD, ip_siocdelrt, NULL },
1091 
1092 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1093 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1094 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1095 			IF_CMD, ip_sioctl_get_addr, NULL },
1096 
1097 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1098 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1099 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1100 			IPI_GET_CMD | IPI_REPL,
1101 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1102 
1103 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1104 			IPI_PRIV | IPI_WR | IPI_REPL,
1105 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1106 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1107 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1108 			IF_CMD, ip_sioctl_get_flags, NULL },
1109 
1110 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* copyin size cannot be coded for SIOCGIFCONF */
1114 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1115 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1116 
1117 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1118 			IF_CMD, ip_sioctl_mtu, NULL },
1119 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1120 			IF_CMD, ip_sioctl_get_mtu, NULL },
1121 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1122 			IPI_GET_CMD | IPI_REPL,
1123 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1124 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1125 			IF_CMD, ip_sioctl_brdaddr, NULL },
1126 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1127 			IPI_GET_CMD | IPI_REPL,
1128 			IF_CMD, ip_sioctl_get_netmask, NULL },
1129 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1130 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1131 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1132 			IPI_GET_CMD | IPI_REPL,
1133 			IF_CMD, ip_sioctl_get_metric, NULL },
1134 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1135 			IF_CMD, ip_sioctl_metric, NULL },
1136 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 
1138 	/* See 166-168 below for extended SIOC*XARP ioctls */
1139 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1140 			MISC_CMD, ip_sioctl_arp, NULL },
1141 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1142 			MISC_CMD, ip_sioctl_arp, NULL },
1143 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1144 			MISC_CMD, ip_sioctl_arp, NULL },
1145 
1146 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 
1168 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1169 			MISC_CMD, if_unitsel, if_unitsel_restart },
1170 
1171 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 
1190 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1191 			IPI_PRIV | IPI_WR | IPI_MODOK,
1192 			IF_CMD, ip_sioctl_sifname, NULL },
1193 
1194 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1204 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1205 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1206 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1207 
1208 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1209 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1210 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1211 			IF_CMD, ip_sioctl_get_muxid, NULL },
1212 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1213 			IPI_PRIV | IPI_WR | IPI_REPL,
1214 			IF_CMD, ip_sioctl_muxid, NULL },
1215 
1216 	/* Both if and lif variants share same func */
1217 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1218 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1219 	/* Both if and lif variants share same func */
1220 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1221 			IPI_PRIV | IPI_WR | IPI_REPL,
1222 			IF_CMD, ip_sioctl_slifindex, NULL },
1223 
1224 	/* copyin size cannot be coded for SIOCGIFCONF */
1225 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1226 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1227 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1235 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1236 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1237 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1238 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1242 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1243 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1244 
1245 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1246 			IPI_PRIV | IPI_WR | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_removeif,
1248 			ip_sioctl_removeif_restart },
1249 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1250 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1251 			LIF_CMD, ip_sioctl_addif, NULL },
1252 #define	SIOCLIFADDR_NDX 112
1253 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1255 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1256 			IPI_GET_CMD | IPI_REPL,
1257 			LIF_CMD, ip_sioctl_get_addr, NULL },
1258 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1259 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1260 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1261 			IPI_GET_CMD | IPI_REPL,
1262 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1263 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1264 			IPI_PRIV | IPI_WR | IPI_REPL,
1265 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1266 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1267 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_flags, NULL },
1269 
1270 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1271 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1272 
1273 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1274 			ip_sioctl_get_lifconf, NULL },
1275 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1276 			LIF_CMD, ip_sioctl_mtu, NULL },
1277 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1279 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1280 			IPI_GET_CMD | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1282 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1283 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1284 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1285 			IPI_GET_CMD | IPI_REPL,
1286 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1287 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1288 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1289 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1290 			IPI_GET_CMD | IPI_REPL,
1291 			LIF_CMD, ip_sioctl_get_metric, NULL },
1292 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1293 			LIF_CMD, ip_sioctl_metric, NULL },
1294 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1295 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_slifname,
1297 			ip_sioctl_slifname_restart },
1298 
1299 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1300 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1301 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1302 			IPI_GET_CMD | IPI_REPL,
1303 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1304 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1305 			IPI_PRIV | IPI_WR | IPI_REPL,
1306 			LIF_CMD, ip_sioctl_muxid, NULL },
1307 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1308 			IPI_GET_CMD | IPI_REPL,
1309 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1310 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1311 			IPI_PRIV | IPI_WR | IPI_REPL,
1312 			LIF_CMD, ip_sioctl_slifindex, 0 },
1313 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1314 			LIF_CMD, ip_sioctl_token, NULL },
1315 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1316 			IPI_GET_CMD | IPI_REPL,
1317 			LIF_CMD, ip_sioctl_get_token, NULL },
1318 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1319 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1320 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1321 			IPI_GET_CMD | IPI_REPL,
1322 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1323 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1324 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1325 
1326 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1327 			IPI_GET_CMD | IPI_REPL,
1328 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1329 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1330 			LIF_CMD, ip_siocdelndp_v6, NULL },
1331 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1332 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1333 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1334 			LIF_CMD, ip_siocsetndp_v6, NULL },
1335 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1336 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1337 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1338 			MISC_CMD, ip_sioctl_tonlink, NULL },
1339 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1340 			MISC_CMD, ip_sioctl_tmysite, NULL },
1341 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1342 			TUN_CMD, ip_sioctl_tunparam, NULL },
1343 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1344 			IPI_PRIV | IPI_WR,
1345 			TUN_CMD, ip_sioctl_tunparam, NULL },
1346 
1347 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1348 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1349 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1350 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1351 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1352 
1353 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1354 			IPI_PRIV | IPI_WR | IPI_REPL,
1355 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1356 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1357 			IPI_PRIV | IPI_WR | IPI_REPL,
1358 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1359 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1360 			IPI_PRIV | IPI_WR,
1361 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1362 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1363 			IPI_GET_CMD | IPI_REPL,
1364 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1365 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1366 			IPI_GET_CMD | IPI_REPL,
1367 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1368 
1369 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1370 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1371 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1372 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1373 
1374 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1375 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1376 
1377 	/* These are handled in ip_sioctl_copyin_setup itself */
1378 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1379 			MISC_CMD, NULL, NULL },
1380 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1381 			MISC_CMD, NULL, NULL },
1382 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1383 
1384 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1385 			ip_sioctl_get_lifconf, NULL },
1386 
1387 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1388 			MISC_CMD, ip_sioctl_xarp, NULL },
1389 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1390 			MISC_CMD, ip_sioctl_xarp, NULL },
1391 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1392 			MISC_CMD, ip_sioctl_xarp, NULL },
1393 
1394 	/* SIOCPOPSOCKFS is not handled by IP */
1395 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1396 
1397 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1398 			IPI_GET_CMD | IPI_REPL,
1399 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1400 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1401 			IPI_PRIV | IPI_WR | IPI_REPL,
1402 			LIF_CMD, ip_sioctl_slifzone,
1403 			ip_sioctl_slifzone_restart },
1404 	/* 172-174 are SCTP ioctls and not handled by IP */
1405 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1406 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1407 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1408 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1409 			IPI_GET_CMD, LIF_CMD,
1410 			ip_sioctl_get_lifusesrc, 0 },
1411 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1412 			IPI_PRIV | IPI_WR,
1413 			LIF_CMD, ip_sioctl_slifusesrc,
1414 			NULL },
1415 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1416 			ip_sioctl_get_lifsrcof, NULL },
1417 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1418 			MISC_CMD, ip_sioctl_msfilter, NULL },
1419 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1420 			MISC_CMD, ip_sioctl_msfilter, NULL },
1421 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1422 			MISC_CMD, ip_sioctl_msfilter, NULL },
1423 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1424 			MISC_CMD, ip_sioctl_msfilter, NULL },
1425 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1426 			ip_sioctl_set_ipmpfailback, NULL }
1427 };
1428 
1429 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1430 
1431 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1432 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1433 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1434 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1435 		TUN_CMD, ip_sioctl_tunparam, NULL },
1436 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1437 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1438 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1439 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1440 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1441 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1442 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1443 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1444 		MISC_CMD, mrt_ioctl},
1445 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1446 		MISC_CMD, mrt_ioctl},
1447 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1448 		MISC_CMD, mrt_ioctl}
1449 };
1450 
1451 int ip_misc_ioctl_count =
1452     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1453 
1454 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1455 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1456 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1457 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1458 					/* Settable in /etc/system */
1459 
1460 /* Defined in ip_ire.c */
1461 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1462 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1463 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1464 
1465 static nv_t	ire_nv_arr[] = {
1466 	{ IRE_BROADCAST, "BROADCAST" },
1467 	{ IRE_LOCAL, "LOCAL" },
1468 	{ IRE_LOOPBACK, "LOOPBACK" },
1469 	{ IRE_CACHE, "CACHE" },
1470 	{ IRE_DEFAULT, "DEFAULT" },
1471 	{ IRE_PREFIX, "PREFIX" },
1472 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1473 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1474 	{ IRE_HOST, "HOST" },
1475 	{ IRE_HOST_REDIRECT, "HOST_REDIRECT" },
1476 	{ 0 }
1477 };
1478 
1479 nv_t	*ire_nv_tbl = ire_nv_arr;
1480 
1481 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1482 extern krwlock_t ipsec_capab_ills_lock;
1483 
1484 /* Packet dropper for IP IPsec processing failures */
1485 ipdropper_t ip_dropper;
1486 
1487 /* Simple ICMP IP Header Template */
1488 static ipha_t icmp_ipha = {
1489 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1490 };
1491 
1492 struct module_info ip_mod_info = {
1493 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1494 };
1495 
1496 static struct qinit rinit = {
1497 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1498 	&ip_mod_info
1499 };
1500 
1501 static struct qinit winit = {
1502 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1503 	&ip_mod_info
1504 };
1505 
1506 static struct qinit lrinit = {
1507 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1508 	&ip_mod_info
1509 };
1510 
1511 static struct qinit lwinit = {
1512 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1513 	&ip_mod_info
1514 };
1515 
1516 struct streamtab ipinfo = {
1517 	&rinit, &winit, &lrinit, &lwinit
1518 };
1519 
1520 #ifdef	DEBUG
1521 static boolean_t skip_sctp_cksum = B_FALSE;
1522 #endif
1523 /*
1524  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1525  */
1526 mblk_t *
1527 ip_copymsg(mblk_t *mp)
1528 {
1529 	mblk_t *nmp;
1530 	ipsec_info_t *in;
1531 
1532 	if (mp->b_datap->db_type != M_CTL)
1533 		return (copymsg(mp));
1534 
1535 	in = (ipsec_info_t *)mp->b_rptr;
1536 
1537 	/*
1538 	 * Note that M_CTL is also used for delivering ICMP error messages
1539 	 * upstream to transport layers.
1540 	 */
1541 	if (in->ipsec_info_type != IPSEC_OUT &&
1542 	    in->ipsec_info_type != IPSEC_IN)
1543 		return (copymsg(mp));
1544 
1545 	nmp = copymsg(mp->b_cont);
1546 
1547 	if (in->ipsec_info_type == IPSEC_OUT)
1548 		return (ipsec_out_tag(mp, nmp));
1549 	else
1550 		return (ipsec_in_tag(mp, nmp));
1551 }
1552 
1553 /* Generate an ICMP fragmentation needed message. */
1554 static void
1555 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu)
1556 {
1557 	icmph_t	icmph;
1558 	mblk_t *first_mp;
1559 	boolean_t mctl_present;
1560 
1561 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1562 
1563 	if (!(mp = icmp_pkt_err_ok(mp))) {
1564 		if (mctl_present)
1565 			freeb(first_mp);
1566 		return;
1567 	}
1568 
1569 	bzero(&icmph, sizeof (icmph_t));
1570 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1571 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1572 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1573 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1574 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1575 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
1576 }
1577 
1578 /*
1579  * icmp_inbound deals with ICMP messages in the following ways.
1580  *
1581  * 1) It needs to send a reply back and possibly delivering it
1582  *    to the "interested" upper clients.
1583  * 2) It needs to send it to the upper clients only.
1584  * 3) It needs to change some values in IP only.
1585  * 4) It needs to change some values in IP and upper layers e.g TCP.
1586  *
1587  * We need to accomodate icmp messages coming in clear until we get
1588  * everything secure from the wire. If icmp_accept_clear_messages
1589  * is zero we check with the global policy and act accordingly. If
1590  * it is non-zero, we accept the message without any checks. But
1591  * *this does not mean* that this will be delivered to the upper
1592  * clients. By accepting we might send replies back, change our MTU
1593  * value etc. but delivery to the ULP/clients depends on their policy
1594  * dispositions.
1595  *
1596  * We handle the above 4 cases in the context of IPSEC in the
1597  * following way :
1598  *
1599  * 1) Send the reply back in the same way as the request came in.
1600  *    If it came in encrypted, it goes out encrypted. If it came in
1601  *    clear, it goes out in clear. Thus, this will prevent chosen
1602  *    plain text attack.
1603  * 2) The client may or may not expect things to come in secure.
1604  *    If it comes in secure, the policy constraints are checked
1605  *    before delivering it to the upper layers. If it comes in
1606  *    clear, ipsec_inbound_accept_clear will decide whether to
1607  *    accept this in clear or not. In both the cases, if the returned
1608  *    message (IP header + 8 bytes) that caused the icmp message has
1609  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1610  *    sending up. If there are only 8 bytes of returned message, then
1611  *    upper client will not be notified.
1612  * 3) Check with global policy to see whether it matches the constaints.
1613  *    But this will be done only if icmp_accept_messages_in_clear is
1614  *    zero.
1615  * 4) If we need to change both in IP and ULP, then the decision taken
1616  *    while affecting the values in IP and while delivering up to TCP
1617  *    should be the same.
1618  *
1619  * 	There are two cases.
1620  *
1621  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1622  *	   failed), we will not deliver it to the ULP, even though they
1623  *	   are *willing* to accept in *clear*. This is fine as our global
1624  *	   disposition to icmp messages asks us reject the datagram.
1625  *
1626  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1627  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1628  *	   to deliver it to ULP (policy failed), it can lead to
1629  *	   consistency problems. The cases known at this time are
1630  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1631  *	   values :
1632  *
1633  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1634  *	     and Upper layer rejects. Then the communication will
1635  *	     come to a stop. This is solved by making similar decisions
1636  *	     at both levels. Currently, when we are unable to deliver
1637  *	     to the Upper Layer (due to policy failures) while IP has
1638  *	     adjusted ire_max_frag, the next outbound datagram would
1639  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1640  *	     will be with the right level of protection. Thus the right
1641  *	     value will be communicated even if we are not able to
1642  *	     communicate when we get from the wire initially. But this
1643  *	     assumes there would be at least one outbound datagram after
1644  *	     IP has adjusted its ire_max_frag value. To make things
1645  *	     simpler, we accept in clear after the validation of
1646  *	     AH/ESP headers.
1647  *
1648  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1649  *	     upper layer depending on the level of protection the upper
1650  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1651  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1652  *	     should be accepted in clear when the Upper layer expects secure.
1653  *	     Thus the communication may get aborted by some bad ICMP
1654  *	     packets.
1655  *
1656  * IPQoS Notes:
1657  * The only instance when a packet is sent for processing is when there
1658  * isn't an ICMP client and if we are interested in it.
1659  * If there is a client, IPPF processing will take place in the
1660  * ip_fanout_proto routine.
1661  *
1662  * Zones notes:
1663  * The packet is only processed in the context of the specified zone: typically
1664  * only this zone will reply to an echo request, and only interested clients in
1665  * this zone will receive a copy of the packet. This means that the caller must
1666  * call icmp_inbound() for each relevant zone.
1667  */
1668 static void
1669 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1670     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1671     ill_t *recv_ill, zoneid_t zoneid)
1672 {
1673 	icmph_t	*icmph;
1674 	ipha_t	*ipha;
1675 	int	iph_hdr_length;
1676 	int	hdr_length;
1677 	boolean_t	interested;
1678 	uint32_t	ts;
1679 	uchar_t	*wptr;
1680 	ipif_t	*ipif;
1681 	mblk_t *first_mp;
1682 	ipsec_in_t *ii;
1683 	ire_t *src_ire;
1684 	boolean_t onlink;
1685 	timestruc_t now;
1686 	uint32_t ill_index;
1687 
1688 	ASSERT(ill != NULL);
1689 
1690 	first_mp = mp;
1691 	if (mctl_present) {
1692 		mp = first_mp->b_cont;
1693 		ASSERT(mp != NULL);
1694 	}
1695 
1696 	ipha = (ipha_t *)mp->b_rptr;
1697 	if (icmp_accept_clear_messages == 0) {
1698 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1699 		    ipha, NULL, mctl_present);
1700 		if (first_mp == NULL)
1701 			return;
1702 	}
1703 
1704 	/*
1705 	 * On a labeled system, we have to check whether the zone itself is
1706 	 * permitted to receive raw traffic.
1707 	 */
1708 	if (is_system_labeled()) {
1709 		if (zoneid == ALL_ZONES)
1710 			zoneid = tsol_packet_to_zoneid(mp);
1711 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1712 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1713 			    zoneid));
1714 			BUMP_MIB(&icmp_mib, icmpInErrors);
1715 			freemsg(first_mp);
1716 			return;
1717 		}
1718 	}
1719 
1720 	/*
1721 	 * We have accepted the ICMP message. It means that we will
1722 	 * respond to the packet if needed. It may not be delivered
1723 	 * to the upper client depending on the policy constraints
1724 	 * and the disposition in ipsec_inbound_accept_clear.
1725 	 */
1726 
1727 	ASSERT(ill != NULL);
1728 
1729 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1730 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1731 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1732 		/* Last chance to get real. */
1733 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1734 			BUMP_MIB(&icmp_mib, icmpInErrors);
1735 			freemsg(first_mp);
1736 			return;
1737 		}
1738 		/* Refresh iph following the pullup. */
1739 		ipha = (ipha_t *)mp->b_rptr;
1740 	}
1741 	/* ICMP header checksum, including checksum field, should be zero. */
1742 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1743 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1744 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1745 		freemsg(first_mp);
1746 		return;
1747 	}
1748 	/* The IP header will always be a multiple of four bytes */
1749 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1750 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1751 	    icmph->icmph_code));
1752 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1753 	/* We will set "interested" to "true" if we want a copy */
1754 	interested = B_FALSE;
1755 	switch (icmph->icmph_type) {
1756 	case ICMP_ECHO_REPLY:
1757 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1758 		break;
1759 	case ICMP_DEST_UNREACHABLE:
1760 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1761 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1762 		interested = B_TRUE;	/* Pass up to transport */
1763 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1764 		break;
1765 	case ICMP_SOURCE_QUENCH:
1766 		interested = B_TRUE;	/* Pass up to transport */
1767 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1768 		break;
1769 	case ICMP_REDIRECT:
1770 		if (!ip_ignore_redirect)
1771 			interested = B_TRUE;
1772 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1773 		break;
1774 	case ICMP_ECHO_REQUEST:
1775 		/*
1776 		 * Whether to respond to echo requests that come in as IP
1777 		 * broadcasts or as IP multicast is subject to debate
1778 		 * (what isn't?).  We aim to please, you pick it.
1779 		 * Default is do it.
1780 		 */
1781 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1782 			/* unicast: always respond */
1783 			interested = B_TRUE;
1784 		} else if (CLASSD(ipha->ipha_dst)) {
1785 			/* multicast: respond based on tunable */
1786 			interested = ip_g_resp_to_echo_mcast;
1787 		} else if (broadcast) {
1788 			/* broadcast: respond based on tunable */
1789 			interested = ip_g_resp_to_echo_bcast;
1790 		}
1791 		BUMP_MIB(&icmp_mib, icmpInEchos);
1792 		break;
1793 	case ICMP_ROUTER_ADVERTISEMENT:
1794 	case ICMP_ROUTER_SOLICITATION:
1795 		break;
1796 	case ICMP_TIME_EXCEEDED:
1797 		interested = B_TRUE;	/* Pass up to transport */
1798 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1799 		break;
1800 	case ICMP_PARAM_PROBLEM:
1801 		interested = B_TRUE;	/* Pass up to transport */
1802 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1803 		break;
1804 	case ICMP_TIME_STAMP_REQUEST:
1805 		/* Response to Time Stamp Requests is local policy. */
1806 		if (ip_g_resp_to_timestamp &&
1807 		    /* So is whether to respond if it was an IP broadcast. */
1808 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1809 			int tstamp_len = 3 * sizeof (uint32_t);
1810 
1811 			if (wptr +  tstamp_len > mp->b_wptr) {
1812 				if (!pullupmsg(mp, wptr + tstamp_len -
1813 				    mp->b_rptr)) {
1814 					BUMP_MIB(&ip_mib, ipInDiscards);
1815 					freemsg(first_mp);
1816 					return;
1817 				}
1818 				/* Refresh ipha following the pullup. */
1819 				ipha = (ipha_t *)mp->b_rptr;
1820 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1821 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1822 			}
1823 			interested = B_TRUE;
1824 		}
1825 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1826 		break;
1827 	case ICMP_TIME_STAMP_REPLY:
1828 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1829 		break;
1830 	case ICMP_INFO_REQUEST:
1831 		/* Per RFC 1122 3.2.2.7, ignore this. */
1832 	case ICMP_INFO_REPLY:
1833 		break;
1834 	case ICMP_ADDRESS_MASK_REQUEST:
1835 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1836 		    /* TODO m_pullup of complete header? */
1837 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1838 			interested = B_TRUE;
1839 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1840 		break;
1841 	case ICMP_ADDRESS_MASK_REPLY:
1842 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1843 		break;
1844 	default:
1845 		interested = B_TRUE;	/* Pass up to transport */
1846 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1847 		break;
1848 	}
1849 	/* See if there is an ICMP client. */
1850 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1851 		/* If there is an ICMP client and we want one too, copy it. */
1852 		mblk_t *first_mp1;
1853 
1854 		if (!interested) {
1855 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1856 			    ip_policy, recv_ill, zoneid);
1857 			return;
1858 		}
1859 		first_mp1 = ip_copymsg(first_mp);
1860 		if (first_mp1 != NULL) {
1861 			ip_fanout_proto(q, first_mp1, ill, ipha,
1862 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1863 		}
1864 	} else if (!interested) {
1865 		freemsg(first_mp);
1866 		return;
1867 	} else {
1868 		/*
1869 		 * Initiate policy processing for this packet if ip_policy
1870 		 * is true.
1871 		 */
1872 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1873 			ill_index = ill->ill_phyint->phyint_ifindex;
1874 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1875 			if (mp == NULL) {
1876 				if (mctl_present) {
1877 					freeb(first_mp);
1878 				}
1879 				BUMP_MIB(&icmp_mib, icmpInErrors);
1880 				return;
1881 			}
1882 		}
1883 	}
1884 	/* We want to do something with it. */
1885 	/* Check db_ref to make sure we can modify the packet. */
1886 	if (mp->b_datap->db_ref > 1) {
1887 		mblk_t	*first_mp1;
1888 
1889 		first_mp1 = ip_copymsg(first_mp);
1890 		freemsg(first_mp);
1891 		if (!first_mp1) {
1892 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1893 			return;
1894 		}
1895 		first_mp = first_mp1;
1896 		if (mctl_present) {
1897 			mp = first_mp->b_cont;
1898 			ASSERT(mp != NULL);
1899 		} else {
1900 			mp = first_mp;
1901 		}
1902 		ipha = (ipha_t *)mp->b_rptr;
1903 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1904 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1905 	}
1906 	switch (icmph->icmph_type) {
1907 	case ICMP_ADDRESS_MASK_REQUEST:
1908 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1909 		if (ipif == NULL) {
1910 			freemsg(first_mp);
1911 			return;
1912 		}
1913 		/*
1914 		 * outging interface must be IPv4
1915 		 */
1916 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1917 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1918 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1919 		ipif_refrele(ipif);
1920 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1921 		break;
1922 	case ICMP_ECHO_REQUEST:
1923 		icmph->icmph_type = ICMP_ECHO_REPLY;
1924 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1925 		break;
1926 	case ICMP_TIME_STAMP_REQUEST: {
1927 		uint32_t *tsp;
1928 
1929 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1930 		tsp = (uint32_t *)wptr;
1931 		tsp++;		/* Skip past 'originate time' */
1932 		/* Compute # of milliseconds since midnight */
1933 		gethrestime(&now);
1934 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1935 		    now.tv_nsec / (NANOSEC / MILLISEC);
1936 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1937 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1938 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1939 		break;
1940 	}
1941 	default:
1942 		ipha = (ipha_t *)&icmph[1];
1943 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1944 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1945 				BUMP_MIB(&ip_mib, ipInDiscards);
1946 				freemsg(first_mp);
1947 				return;
1948 			}
1949 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1950 			ipha = (ipha_t *)&icmph[1];
1951 		}
1952 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1953 			BUMP_MIB(&ip_mib, ipInDiscards);
1954 			freemsg(first_mp);
1955 			return;
1956 		}
1957 		hdr_length = IPH_HDR_LENGTH(ipha);
1958 		if (hdr_length < sizeof (ipha_t)) {
1959 			BUMP_MIB(&ip_mib, ipInDiscards);
1960 			freemsg(first_mp);
1961 			return;
1962 		}
1963 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1964 			if (!pullupmsg(mp,
1965 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1966 				BUMP_MIB(&ip_mib, ipInDiscards);
1967 				freemsg(first_mp);
1968 				return;
1969 			}
1970 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1971 			ipha = (ipha_t *)&icmph[1];
1972 		}
1973 		switch (icmph->icmph_type) {
1974 		case ICMP_REDIRECT:
1975 			/*
1976 			 * As there is no upper client to deliver, we don't
1977 			 * need the first_mp any more.
1978 			 */
1979 			if (mctl_present) {
1980 				freeb(first_mp);
1981 			}
1982 			icmp_redirect(mp);
1983 			return;
1984 		case ICMP_DEST_UNREACHABLE:
1985 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1986 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1987 				    zoneid, mp)) {
1988 					freemsg(first_mp);
1989 					return;
1990 				}
1991 			}
1992 			/* FALLTHRU */
1993 		default :
1994 			/*
1995 			 * IPQoS notes: Since we have already done IPQoS
1996 			 * processing we don't want to do it again in
1997 			 * the fanout routines called by
1998 			 * icmp_inbound_error_fanout, hence the last
1999 			 * argument, ip_policy, is B_FALSE.
2000 			 */
2001 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2002 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2003 			    B_FALSE, recv_ill, zoneid);
2004 		}
2005 		return;
2006 	}
2007 	/* Send out an ICMP packet */
2008 	icmph->icmph_checksum = 0;
2009 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2010 	if (icmph->icmph_checksum == 0)
2011 		icmph->icmph_checksum = 0xFFFF;
2012 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2013 		ipif_t	*ipif_chosen;
2014 		/*
2015 		 * Make it look like it was directed to us, so we don't look
2016 		 * like a fool with a broadcast or multicast source address.
2017 		 */
2018 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2019 		/*
2020 		 * Make sure that we haven't grabbed an interface that's DOWN.
2021 		 */
2022 		if (ipif != NULL) {
2023 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2024 			    ipha->ipha_src, zoneid);
2025 			if (ipif_chosen != NULL) {
2026 				ipif_refrele(ipif);
2027 				ipif = ipif_chosen;
2028 			}
2029 		}
2030 		if (ipif == NULL) {
2031 			ip0dbg(("icmp_inbound: "
2032 			    "No source for broadcast/multicast:\n"
2033 			    "\tsrc 0x%x dst 0x%x ill %p "
2034 			    "ipif_lcl_addr 0x%x\n",
2035 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2036 			    (void *)ill,
2037 			    ill->ill_ipif->ipif_lcl_addr));
2038 			freemsg(first_mp);
2039 			return;
2040 		}
2041 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2042 		ipha->ipha_dst = ipif->ipif_src_addr;
2043 		ipif_refrele(ipif);
2044 	}
2045 	/* Reset time to live. */
2046 	ipha->ipha_ttl = ip_def_ttl;
2047 	{
2048 		/* Swap source and destination addresses */
2049 		ipaddr_t tmp;
2050 
2051 		tmp = ipha->ipha_src;
2052 		ipha->ipha_src = ipha->ipha_dst;
2053 		ipha->ipha_dst = tmp;
2054 	}
2055 	ipha->ipha_ident = 0;
2056 	if (!IS_SIMPLE_IPH(ipha))
2057 		icmp_options_update(ipha);
2058 
2059 	/*
2060 	 * ICMP echo replies should go out on the same interface
2061 	 * the request came on as probes used by in.mpathd for detecting
2062 	 * NIC failures are ECHO packets. We turn-off load spreading
2063 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2064 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2065 	 * function. This is in turn handled by ip_wput and ip_newroute
2066 	 * to make sure that the packet goes out on the interface it came
2067 	 * in on. If we don't turnoff load spreading, the packets might get
2068 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2069 	 * to go out and in.mpathd would wrongly detect a failure or
2070 	 * mis-detect a NIC failure for link failure. As load spreading
2071 	 * can happen only if ill_group is not NULL, we do only for
2072 	 * that case and this does not affect the normal case.
2073 	 *
2074 	 * We turn off load spreading only on echo packets that came from
2075 	 * on-link hosts. If the interface route has been deleted, this will
2076 	 * not be enforced as we can't do much. For off-link hosts, as the
2077 	 * default routes in IPv4 does not typically have an ire_ipif
2078 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2079 	 * Moreover, expecting a default route through this interface may
2080 	 * not be correct. We use ipha_dst because of the swap above.
2081 	 */
2082 	onlink = B_FALSE;
2083 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2084 		/*
2085 		 * First, we need to make sure that it is not one of our
2086 		 * local addresses. If we set onlink when it is one of
2087 		 * our local addresses, we will end up creating IRE_CACHES
2088 		 * for one of our local addresses. Then, we will never
2089 		 * accept packets for them afterwards.
2090 		 */
2091 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2092 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2093 		if (src_ire == NULL) {
2094 			ipif = ipif_get_next_ipif(NULL, ill);
2095 			if (ipif == NULL) {
2096 				BUMP_MIB(&ip_mib, ipInDiscards);
2097 				freemsg(mp);
2098 				return;
2099 			}
2100 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2101 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2102 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2103 			ipif_refrele(ipif);
2104 			if (src_ire != NULL) {
2105 				onlink = B_TRUE;
2106 				ire_refrele(src_ire);
2107 			}
2108 		} else {
2109 			ire_refrele(src_ire);
2110 		}
2111 	}
2112 	if (!mctl_present) {
2113 		/*
2114 		 * This packet should go out the same way as it
2115 		 * came in i.e in clear. To make sure that global
2116 		 * policy will not be applied to this in ip_wput_ire,
2117 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2118 		 */
2119 		ASSERT(first_mp == mp);
2120 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2121 			BUMP_MIB(&ip_mib, ipInDiscards);
2122 			freemsg(mp);
2123 			return;
2124 		}
2125 		ii = (ipsec_in_t *)first_mp->b_rptr;
2126 
2127 		/* This is not a secure packet */
2128 		ii->ipsec_in_secure = B_FALSE;
2129 		if (onlink) {
2130 			ii->ipsec_in_attach_if = B_TRUE;
2131 			ii->ipsec_in_ill_index =
2132 			    ill->ill_phyint->phyint_ifindex;
2133 			ii->ipsec_in_rill_index =
2134 			    recv_ill->ill_phyint->phyint_ifindex;
2135 		}
2136 		first_mp->b_cont = mp;
2137 	} else if (onlink) {
2138 		ii = (ipsec_in_t *)first_mp->b_rptr;
2139 		ii->ipsec_in_attach_if = B_TRUE;
2140 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2141 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2142 	} else {
2143 		ii = (ipsec_in_t *)first_mp->b_rptr;
2144 	}
2145 	ii->ipsec_in_zoneid = zoneid;
2146 	ASSERT(zoneid != ALL_ZONES);
2147 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2148 		BUMP_MIB(&ip_mib, ipInDiscards);
2149 		return;
2150 	}
2151 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2152 	put(WR(q), first_mp);
2153 }
2154 
2155 static ipaddr_t
2156 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2157 {
2158 	conn_t *connp;
2159 	connf_t *connfp;
2160 	ipaddr_t nexthop_addr = INADDR_ANY;
2161 	int hdr_length = IPH_HDR_LENGTH(ipha);
2162 	uint16_t *up;
2163 	uint32_t ports;
2164 
2165 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2166 	switch (ipha->ipha_protocol) {
2167 		case IPPROTO_TCP:
2168 		{
2169 			tcph_t *tcph;
2170 
2171 			/* do a reverse lookup */
2172 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2173 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2174 			    TCPS_LISTEN);
2175 			break;
2176 		}
2177 		case IPPROTO_UDP:
2178 		{
2179 			uint32_t dstport, srcport;
2180 
2181 			((uint16_t *)&ports)[0] = up[1];
2182 			((uint16_t *)&ports)[1] = up[0];
2183 
2184 			/* Extract ports in net byte order */
2185 			dstport = htons(ntohl(ports) & 0xFFFF);
2186 			srcport = htons(ntohl(ports) >> 16);
2187 
2188 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2189 			mutex_enter(&connfp->connf_lock);
2190 			connp = connfp->connf_head;
2191 
2192 			/* do a reverse lookup */
2193 			while ((connp != NULL) &&
2194 			    (!IPCL_UDP_MATCH(connp, dstport,
2195 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2196 			    connp->conn_zoneid != zoneid)) {
2197 				connp = connp->conn_next;
2198 			}
2199 			if (connp != NULL)
2200 				CONN_INC_REF(connp);
2201 			mutex_exit(&connfp->connf_lock);
2202 			break;
2203 		}
2204 		case IPPROTO_SCTP:
2205 		{
2206 			in6_addr_t map_src, map_dst;
2207 
2208 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2209 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2210 			((uint16_t *)&ports)[0] = up[1];
2211 			((uint16_t *)&ports)[1] = up[0];
2212 
2213 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2214 			    0, zoneid)) == NULL) {
2215 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2216 				    zoneid, ports, ipha);
2217 			} else {
2218 				CONN_INC_REF(connp);
2219 				SCTP_REFRELE(CONN2SCTP(connp));
2220 			}
2221 			break;
2222 		}
2223 		default:
2224 		{
2225 			ipha_t ripha;
2226 
2227 			ripha.ipha_src = ipha->ipha_dst;
2228 			ripha.ipha_dst = ipha->ipha_src;
2229 			ripha.ipha_protocol = ipha->ipha_protocol;
2230 
2231 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2232 			mutex_enter(&connfp->connf_lock);
2233 			connp = connfp->connf_head;
2234 			for (connp = connfp->connf_head; connp != NULL;
2235 			    connp = connp->conn_next) {
2236 				if (IPCL_PROTO_MATCH(connp,
2237 				    ipha->ipha_protocol, &ripha, ill,
2238 				    0, zoneid)) {
2239 					CONN_INC_REF(connp);
2240 					break;
2241 				}
2242 			}
2243 			mutex_exit(&connfp->connf_lock);
2244 		}
2245 	}
2246 	if (connp != NULL) {
2247 		if (connp->conn_nexthop_set)
2248 			nexthop_addr = connp->conn_nexthop_v4;
2249 		CONN_DEC_REF(connp);
2250 	}
2251 	return (nexthop_addr);
2252 }
2253 
2254 /* Table from RFC 1191 */
2255 static int icmp_frag_size_table[] =
2256 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2257 
2258 /*
2259  * Process received ICMP Packet too big.
2260  * After updating any IRE it does the fanout to any matching transport streams.
2261  * Assumes the message has been pulled up till the IP header that caused
2262  * the error.
2263  *
2264  * Returns B_FALSE on failure and B_TRUE on success.
2265  */
2266 static boolean_t
2267 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2268     zoneid_t zoneid, mblk_t *mp)
2269 {
2270 	ire_t	*ire, *first_ire;
2271 	int	mtu;
2272 	int	hdr_length;
2273 	ipaddr_t nexthop_addr;
2274 
2275 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2276 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2277 
2278 	hdr_length = IPH_HDR_LENGTH(ipha);
2279 
2280 	/* Drop if the original packet contained a source route */
2281 	if (ip_source_route_included(ipha)) {
2282 		return (B_FALSE);
2283 	}
2284 	/*
2285 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2286 	 * header.
2287 	 */
2288 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2289 	    mp->b_wptr) {
2290 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2291 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2292 			BUMP_MIB(&ip_mib, ipInDiscards);
2293 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2294 			return (B_FALSE);
2295 		}
2296 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2297 		ipha = (ipha_t *)&icmph[1];
2298 	}
2299 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2300 	if (nexthop_addr != INADDR_ANY) {
2301 		/* nexthop set */
2302 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2303 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2304 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2305 	} else {
2306 		/* nexthop not set */
2307 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2308 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2309 	}
2310 
2311 	if (!first_ire) {
2312 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2313 		    ntohl(ipha->ipha_dst)));
2314 		return (B_FALSE);
2315 	}
2316 	/* Check for MTU discovery advice as described in RFC 1191 */
2317 	mtu = ntohs(icmph->icmph_du_mtu);
2318 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2319 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2320 	    ire = ire->ire_next) {
2321 		/*
2322 		 * Look for the connection to which this ICMP message is
2323 		 * directed. If it has the IP_NEXTHOP option set, then the
2324 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2325 		 * option. Else the search is limited to regular IREs.
2326 		 */
2327 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2328 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2329 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2330 		    (nexthop_addr != INADDR_ANY)))
2331 			continue;
2332 
2333 		mutex_enter(&ire->ire_lock);
2334 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2335 			/* Reduce the IRE max frag value as advised. */
2336 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2337 			    mtu, ire->ire_max_frag));
2338 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2339 		} else {
2340 			uint32_t length;
2341 			int	i;
2342 
2343 			/*
2344 			 * Use the table from RFC 1191 to figure out
2345 			 * the next "plateau" based on the length in
2346 			 * the original IP packet.
2347 			 */
2348 			length = ntohs(ipha->ipha_length);
2349 			if (ire->ire_max_frag <= length &&
2350 			    ire->ire_max_frag >= length - hdr_length) {
2351 				/*
2352 				 * Handle broken BSD 4.2 systems that
2353 				 * return the wrong iph_length in ICMP
2354 				 * errors.
2355 				 */
2356 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2357 				    length, ire->ire_max_frag));
2358 				length -= hdr_length;
2359 			}
2360 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2361 				if (length > icmp_frag_size_table[i])
2362 					break;
2363 			}
2364 			if (i == A_CNT(icmp_frag_size_table)) {
2365 				/* Smaller than 68! */
2366 				ip1dbg(("Too big for packet size %d\n",
2367 				    length));
2368 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2369 				ire->ire_frag_flag = 0;
2370 			} else {
2371 				mtu = icmp_frag_size_table[i];
2372 				ip1dbg(("Calculated mtu %d, packet size %d, "
2373 				    "before %d", mtu, length,
2374 				    ire->ire_max_frag));
2375 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2376 				ip1dbg((", after %d\n", ire->ire_max_frag));
2377 			}
2378 			/* Record the new max frag size for the ULP. */
2379 			icmph->icmph_du_zero = 0;
2380 			icmph->icmph_du_mtu =
2381 			    htons((uint16_t)ire->ire_max_frag);
2382 		}
2383 		mutex_exit(&ire->ire_lock);
2384 	}
2385 	rw_exit(&first_ire->ire_bucket->irb_lock);
2386 	ire_refrele(first_ire);
2387 	return (B_TRUE);
2388 }
2389 
2390 /*
2391  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2392  * calls this function.
2393  */
2394 static mblk_t *
2395 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2396 {
2397 	ipha_t *ipha;
2398 	icmph_t *icmph;
2399 	ipha_t *in_ipha;
2400 	int length;
2401 
2402 	ASSERT(mp->b_datap->db_type == M_DATA);
2403 
2404 	/*
2405 	 * For Self-encapsulated packets, we added an extra IP header
2406 	 * without the options. Inner IP header is the one from which
2407 	 * the outer IP header was formed. Thus, we need to remove the
2408 	 * outer IP header. To do this, we pullup the whole message
2409 	 * and overlay whatever follows the outer IP header over the
2410 	 * outer IP header.
2411 	 */
2412 
2413 	if (!pullupmsg(mp, -1)) {
2414 		BUMP_MIB(&ip_mib, ipInDiscards);
2415 		return (NULL);
2416 	}
2417 
2418 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2419 	ipha = (ipha_t *)&icmph[1];
2420 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2421 
2422 	/*
2423 	 * The length that we want to overlay is following the inner
2424 	 * IP header. Subtracting the IP header + icmp header + outer
2425 	 * IP header's length should give us the length that we want to
2426 	 * overlay.
2427 	 */
2428 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2429 	    hdr_length;
2430 	/*
2431 	 * Overlay whatever follows the inner header over the
2432 	 * outer header.
2433 	 */
2434 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2435 
2436 	/* Set the wptr to account for the outer header */
2437 	mp->b_wptr -= hdr_length;
2438 	return (mp);
2439 }
2440 
2441 /*
2442  * Try to pass the ICMP message upstream in case the ULP cares.
2443  *
2444  * If the packet that caused the ICMP error is secure, we send
2445  * it to AH/ESP to make sure that the attached packet has a
2446  * valid association. ipha in the code below points to the
2447  * IP header of the packet that caused the error.
2448  *
2449  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2450  * in the context of IPSEC. Normally we tell the upper layer
2451  * whenever we send the ire (including ip_bind), the IPSEC header
2452  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2453  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2454  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2455  * same thing. As TCP has the IPSEC options size that needs to be
2456  * adjusted, we just pass the MTU unchanged.
2457  *
2458  * IFN could have been generated locally or by some router.
2459  *
2460  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2461  *	    This happens because IP adjusted its value of MTU on an
2462  *	    earlier IFN message and could not tell the upper layer,
2463  *	    the new adjusted value of MTU e.g. Packet was encrypted
2464  *	    or there was not enough information to fanout to upper
2465  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2466  *	    generates the IFN, where IPSEC processing has *not* been
2467  *	    done.
2468  *
2469  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2470  *	    could have generated this. This happens because ire_max_frag
2471  *	    value in IP was set to a new value, while the IPSEC processing
2472  *	    was being done and after we made the fragmentation check in
2473  *	    ip_wput_ire. Thus on return from IPSEC processing,
2474  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2475  *	    and generates the IFN. As IPSEC processing is over, we fanout
2476  *	    to AH/ESP to remove the header.
2477  *
2478  *	    In both these cases, ipsec_in_loopback will be set indicating
2479  *	    that IFN was generated locally.
2480  *
2481  * ROUTER : IFN could be secure or non-secure.
2482  *
2483  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2484  *	      packet in error has AH/ESP headers to validate the AH/ESP
2485  *	      headers. AH/ESP will verify whether there is a valid SA or
2486  *	      not and send it back. We will fanout again if we have more
2487  *	      data in the packet.
2488  *
2489  *	      If the packet in error does not have AH/ESP, we handle it
2490  *	      like any other case.
2491  *
2492  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2493  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2494  *	      for validation. AH/ESP will verify whether there is a
2495  *	      valid SA or not and send it back. We will fanout again if
2496  *	      we have more data in the packet.
2497  *
2498  *	      If the packet in error does not have AH/ESP, we handle it
2499  *	      like any other case.
2500  */
2501 static void
2502 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2503     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2504     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2505     zoneid_t zoneid)
2506 {
2507 	uint16_t *up;	/* Pointer to ports in ULP header */
2508 	uint32_t ports;	/* reversed ports for fanout */
2509 	ipha_t ripha;	/* With reversed addresses */
2510 	mblk_t *first_mp;
2511 	ipsec_in_t *ii;
2512 	tcph_t	*tcph;
2513 	conn_t	*connp;
2514 
2515 	first_mp = mp;
2516 	if (mctl_present) {
2517 		mp = first_mp->b_cont;
2518 		ASSERT(mp != NULL);
2519 
2520 		ii = (ipsec_in_t *)first_mp->b_rptr;
2521 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2522 	} else {
2523 		ii = NULL;
2524 	}
2525 
2526 	switch (ipha->ipha_protocol) {
2527 	case IPPROTO_UDP:
2528 		/*
2529 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2530 		 * transport header.
2531 		 */
2532 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2533 		    mp->b_wptr) {
2534 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2535 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2536 				BUMP_MIB(&ip_mib, ipInDiscards);
2537 				goto drop_pkt;
2538 			}
2539 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2540 			ipha = (ipha_t *)&icmph[1];
2541 		}
2542 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2543 
2544 		/*
2545 		 * Attempt to find a client stream based on port.
2546 		 * Note that we do a reverse lookup since the header is
2547 		 * in the form we sent it out.
2548 		 * The ripha header is only used for the IP_UDP_MATCH and we
2549 		 * only set the src and dst addresses and protocol.
2550 		 */
2551 		ripha.ipha_src = ipha->ipha_dst;
2552 		ripha.ipha_dst = ipha->ipha_src;
2553 		ripha.ipha_protocol = ipha->ipha_protocol;
2554 		((uint16_t *)&ports)[0] = up[1];
2555 		((uint16_t *)&ports)[1] = up[0];
2556 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2557 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2558 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2559 		    icmph->icmph_type, icmph->icmph_code));
2560 
2561 		/* Have to change db_type after any pullupmsg */
2562 		DB_TYPE(mp) = M_CTL;
2563 
2564 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2565 		    mctl_present, ip_policy, recv_ill, zoneid);
2566 		return;
2567 
2568 	case IPPROTO_TCP:
2569 		/*
2570 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2571 		 * transport header.
2572 		 */
2573 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2574 		    mp->b_wptr) {
2575 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2576 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2577 				BUMP_MIB(&ip_mib, ipInDiscards);
2578 				goto drop_pkt;
2579 			}
2580 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2581 			ipha = (ipha_t *)&icmph[1];
2582 		}
2583 		/*
2584 		 * Find a TCP client stream for this packet.
2585 		 * Note that we do a reverse lookup since the header is
2586 		 * in the form we sent it out.
2587 		 */
2588 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2589 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2590 		if (connp == NULL) {
2591 			BUMP_MIB(&ip_mib, ipInDiscards);
2592 			goto drop_pkt;
2593 		}
2594 
2595 		/* Have to change db_type after any pullupmsg */
2596 		DB_TYPE(mp) = M_CTL;
2597 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2598 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2599 		return;
2600 
2601 	case IPPROTO_SCTP:
2602 		/*
2603 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2604 		 * transport header.
2605 		 */
2606 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2607 		    mp->b_wptr) {
2608 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2609 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2610 				BUMP_MIB(&ip_mib, ipInDiscards);
2611 				goto drop_pkt;
2612 			}
2613 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2614 			ipha = (ipha_t *)&icmph[1];
2615 		}
2616 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2617 		/*
2618 		 * Find a SCTP client stream for this packet.
2619 		 * Note that we do a reverse lookup since the header is
2620 		 * in the form we sent it out.
2621 		 * The ripha header is only used for the matching and we
2622 		 * only set the src and dst addresses, protocol, and version.
2623 		 */
2624 		ripha.ipha_src = ipha->ipha_dst;
2625 		ripha.ipha_dst = ipha->ipha_src;
2626 		ripha.ipha_protocol = ipha->ipha_protocol;
2627 		ripha.ipha_version_and_hdr_length =
2628 		    ipha->ipha_version_and_hdr_length;
2629 		((uint16_t *)&ports)[0] = up[1];
2630 		((uint16_t *)&ports)[1] = up[0];
2631 
2632 		/* Have to change db_type after any pullupmsg */
2633 		DB_TYPE(mp) = M_CTL;
2634 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2635 		    mctl_present, ip_policy, 0, zoneid);
2636 		return;
2637 
2638 	case IPPROTO_ESP:
2639 	case IPPROTO_AH: {
2640 		int ipsec_rc;
2641 
2642 		/*
2643 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2644 		 * We will re-use the IPSEC_IN if it is already present as
2645 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2646 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2647 		 * one and attach it in the front.
2648 		 */
2649 		if (ii != NULL) {
2650 			/*
2651 			 * ip_fanout_proto_again converts the ICMP errors
2652 			 * that come back from AH/ESP to M_DATA so that
2653 			 * if it is non-AH/ESP and we do a pullupmsg in
2654 			 * this function, it would work. Convert it back
2655 			 * to M_CTL before we send up as this is a ICMP
2656 			 * error. This could have been generated locally or
2657 			 * by some router. Validate the inner IPSEC
2658 			 * headers.
2659 			 *
2660 			 * NOTE : ill_index is used by ip_fanout_proto_again
2661 			 * to locate the ill.
2662 			 */
2663 			ASSERT(ill != NULL);
2664 			ii->ipsec_in_ill_index =
2665 			    ill->ill_phyint->phyint_ifindex;
2666 			ii->ipsec_in_rill_index =
2667 			    recv_ill->ill_phyint->phyint_ifindex;
2668 			DB_TYPE(first_mp->b_cont) = M_CTL;
2669 		} else {
2670 			/*
2671 			 * IPSEC_IN is not present. We attach a ipsec_in
2672 			 * message and send up to IPSEC for validating
2673 			 * and removing the IPSEC headers. Clear
2674 			 * ipsec_in_secure so that when we return
2675 			 * from IPSEC, we don't mistakenly think that this
2676 			 * is a secure packet came from the network.
2677 			 *
2678 			 * NOTE : ill_index is used by ip_fanout_proto_again
2679 			 * to locate the ill.
2680 			 */
2681 			ASSERT(first_mp == mp);
2682 			first_mp = ipsec_in_alloc(B_TRUE);
2683 			if (first_mp == NULL) {
2684 				freemsg(mp);
2685 				BUMP_MIB(&ip_mib, ipInDiscards);
2686 				return;
2687 			}
2688 			ii = (ipsec_in_t *)first_mp->b_rptr;
2689 
2690 			/* This is not a secure packet */
2691 			ii->ipsec_in_secure = B_FALSE;
2692 			first_mp->b_cont = mp;
2693 			DB_TYPE(mp) = M_CTL;
2694 			ASSERT(ill != NULL);
2695 			ii->ipsec_in_ill_index =
2696 			    ill->ill_phyint->phyint_ifindex;
2697 			ii->ipsec_in_rill_index =
2698 			    recv_ill->ill_phyint->phyint_ifindex;
2699 		}
2700 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2701 
2702 		if (!ipsec_loaded()) {
2703 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2704 			return;
2705 		}
2706 
2707 		if (ipha->ipha_protocol == IPPROTO_ESP)
2708 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2709 		else
2710 			ipsec_rc = ipsecah_icmp_error(first_mp);
2711 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2712 			return;
2713 
2714 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2715 		return;
2716 	}
2717 	default:
2718 		/*
2719 		 * The ripha header is only used for the lookup and we
2720 		 * only set the src and dst addresses and protocol.
2721 		 */
2722 		ripha.ipha_src = ipha->ipha_dst;
2723 		ripha.ipha_dst = ipha->ipha_src;
2724 		ripha.ipha_protocol = ipha->ipha_protocol;
2725 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2726 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2727 		    ntohl(ipha->ipha_dst),
2728 		    icmph->icmph_type, icmph->icmph_code));
2729 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2730 			ipha_t *in_ipha;
2731 
2732 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2733 			    mp->b_wptr) {
2734 				if (!pullupmsg(mp, (uchar_t *)ipha +
2735 				    hdr_length + sizeof (ipha_t) -
2736 				    mp->b_rptr)) {
2737 
2738 					BUMP_MIB(&ip_mib, ipInDiscards);
2739 					goto drop_pkt;
2740 				}
2741 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2742 				ipha = (ipha_t *)&icmph[1];
2743 			}
2744 			/*
2745 			 * Caller has verified that length has to be
2746 			 * at least the size of IP header.
2747 			 */
2748 			ASSERT(hdr_length >= sizeof (ipha_t));
2749 			/*
2750 			 * Check the sanity of the inner IP header like
2751 			 * we did for the outer header.
2752 			 */
2753 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2754 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2755 				BUMP_MIB(&ip_mib, ipInDiscards);
2756 				goto drop_pkt;
2757 			}
2758 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2759 				BUMP_MIB(&ip_mib, ipInDiscards);
2760 				goto drop_pkt;
2761 			}
2762 			/* Check for Self-encapsulated tunnels */
2763 			if (in_ipha->ipha_src == ipha->ipha_src &&
2764 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2765 
2766 				mp = icmp_inbound_self_encap_error(mp,
2767 				    iph_hdr_length, hdr_length);
2768 				if (mp == NULL)
2769 					goto drop_pkt;
2770 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2771 				ipha = (ipha_t *)&icmph[1];
2772 				hdr_length = IPH_HDR_LENGTH(ipha);
2773 				/*
2774 				 * The packet in error is self-encapsualted.
2775 				 * And we are finding it further encapsulated
2776 				 * which we could not have possibly generated.
2777 				 */
2778 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2779 					BUMP_MIB(&ip_mib, ipInDiscards);
2780 					goto drop_pkt;
2781 				}
2782 				icmp_inbound_error_fanout(q, ill, first_mp,
2783 				    icmph, ipha, iph_hdr_length, hdr_length,
2784 				    mctl_present, ip_policy, recv_ill, zoneid);
2785 				return;
2786 			}
2787 		}
2788 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2789 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2790 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2791 		    ii != NULL &&
2792 		    ii->ipsec_in_loopback &&
2793 		    ii->ipsec_in_secure) {
2794 			/*
2795 			 * For IP tunnels that get a looped-back
2796 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2797 			 * reported new MTU to take into account the IPsec
2798 			 * headers protecting this configured tunnel.
2799 			 *
2800 			 * This allows the tunnel module (tun.c) to blindly
2801 			 * accept the MTU reported in an ICMP "too big"
2802 			 * message.
2803 			 *
2804 			 * Non-looped back ICMP messages will just be
2805 			 * handled by the security protocols (if needed),
2806 			 * and the first subsequent packet will hit this
2807 			 * path.
2808 			 */
2809 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2810 			    ipsec_in_extra_length(first_mp));
2811 		}
2812 		/* Have to change db_type after any pullupmsg */
2813 		DB_TYPE(mp) = M_CTL;
2814 
2815 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2816 		    ip_policy, recv_ill, zoneid);
2817 		return;
2818 	}
2819 	/* NOTREACHED */
2820 drop_pkt:;
2821 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2822 	freemsg(first_mp);
2823 }
2824 
2825 /*
2826  * Common IP options parser.
2827  *
2828  * Setup routine: fill in *optp with options-parsing state, then
2829  * tail-call ipoptp_next to return the first option.
2830  */
2831 uint8_t
2832 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2833 {
2834 	uint32_t totallen; /* total length of all options */
2835 
2836 	totallen = ipha->ipha_version_and_hdr_length -
2837 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2838 	totallen <<= 2;
2839 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2840 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2841 	optp->ipoptp_flags = 0;
2842 	return (ipoptp_next(optp));
2843 }
2844 
2845 /*
2846  * Common IP options parser: extract next option.
2847  */
2848 uint8_t
2849 ipoptp_next(ipoptp_t *optp)
2850 {
2851 	uint8_t *end = optp->ipoptp_end;
2852 	uint8_t *cur = optp->ipoptp_next;
2853 	uint8_t opt, len, pointer;
2854 
2855 	/*
2856 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2857 	 * has been corrupted.
2858 	 */
2859 	ASSERT(cur <= end);
2860 
2861 	if (cur == end)
2862 		return (IPOPT_EOL);
2863 
2864 	opt = cur[IPOPT_OPTVAL];
2865 
2866 	/*
2867 	 * Skip any NOP options.
2868 	 */
2869 	while (opt == IPOPT_NOP) {
2870 		cur++;
2871 		if (cur == end)
2872 			return (IPOPT_EOL);
2873 		opt = cur[IPOPT_OPTVAL];
2874 	}
2875 
2876 	if (opt == IPOPT_EOL)
2877 		return (IPOPT_EOL);
2878 
2879 	/*
2880 	 * Option requiring a length.
2881 	 */
2882 	if ((cur + 1) >= end) {
2883 		optp->ipoptp_flags |= IPOPTP_ERROR;
2884 		return (IPOPT_EOL);
2885 	}
2886 	len = cur[IPOPT_OLEN];
2887 	if (len < 2) {
2888 		optp->ipoptp_flags |= IPOPTP_ERROR;
2889 		return (IPOPT_EOL);
2890 	}
2891 	optp->ipoptp_cur = cur;
2892 	optp->ipoptp_len = len;
2893 	optp->ipoptp_next = cur + len;
2894 	if (cur + len > end) {
2895 		optp->ipoptp_flags |= IPOPTP_ERROR;
2896 		return (IPOPT_EOL);
2897 	}
2898 
2899 	/*
2900 	 * For the options which require a pointer field, make sure
2901 	 * its there, and make sure it points to either something
2902 	 * inside this option, or the end of the option.
2903 	 */
2904 	switch (opt) {
2905 	case IPOPT_RR:
2906 	case IPOPT_TS:
2907 	case IPOPT_LSRR:
2908 	case IPOPT_SSRR:
2909 		if (len <= IPOPT_OFFSET) {
2910 			optp->ipoptp_flags |= IPOPTP_ERROR;
2911 			return (opt);
2912 		}
2913 		pointer = cur[IPOPT_OFFSET];
2914 		if (pointer - 1 > len) {
2915 			optp->ipoptp_flags |= IPOPTP_ERROR;
2916 			return (opt);
2917 		}
2918 		break;
2919 	}
2920 
2921 	/*
2922 	 * Sanity check the pointer field based on the type of the
2923 	 * option.
2924 	 */
2925 	switch (opt) {
2926 	case IPOPT_RR:
2927 	case IPOPT_SSRR:
2928 	case IPOPT_LSRR:
2929 		if (pointer < IPOPT_MINOFF_SR)
2930 			optp->ipoptp_flags |= IPOPTP_ERROR;
2931 		break;
2932 	case IPOPT_TS:
2933 		if (pointer < IPOPT_MINOFF_IT)
2934 			optp->ipoptp_flags |= IPOPTP_ERROR;
2935 		/*
2936 		 * Note that the Internet Timestamp option also
2937 		 * contains two four bit fields (the Overflow field,
2938 		 * and the Flag field), which follow the pointer
2939 		 * field.  We don't need to check that these fields
2940 		 * fall within the length of the option because this
2941 		 * was implicitely done above.  We've checked that the
2942 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2943 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2944 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2945 		 */
2946 		ASSERT(len > IPOPT_POS_OV_FLG);
2947 		break;
2948 	}
2949 
2950 	return (opt);
2951 }
2952 
2953 /*
2954  * Use the outgoing IP header to create an IP_OPTIONS option the way
2955  * it was passed down from the application.
2956  */
2957 int
2958 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2959 {
2960 	ipoptp_t	opts;
2961 	const uchar_t	*opt;
2962 	uint8_t		optval;
2963 	uint8_t		optlen;
2964 	uint32_t	len = 0;
2965 	uchar_t	*buf1 = buf;
2966 
2967 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2968 	len += IP_ADDR_LEN;
2969 	bzero(buf1, IP_ADDR_LEN);
2970 
2971 	/*
2972 	 * OK to cast away const here, as we don't store through the returned
2973 	 * opts.ipoptp_cur pointer.
2974 	 */
2975 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2976 	    optval != IPOPT_EOL;
2977 	    optval = ipoptp_next(&opts)) {
2978 		int	off;
2979 
2980 		opt = opts.ipoptp_cur;
2981 		optlen = opts.ipoptp_len;
2982 		switch (optval) {
2983 		case IPOPT_SSRR:
2984 		case IPOPT_LSRR:
2985 
2986 			/*
2987 			 * Insert ipha_dst as the first entry in the source
2988 			 * route and move down the entries on step.
2989 			 * The last entry gets placed at buf1.
2990 			 */
2991 			buf[IPOPT_OPTVAL] = optval;
2992 			buf[IPOPT_OLEN] = optlen;
2993 			buf[IPOPT_OFFSET] = optlen;
2994 
2995 			off = optlen - IP_ADDR_LEN;
2996 			if (off < 0) {
2997 				/* No entries in source route */
2998 				break;
2999 			}
3000 			/* Last entry in source route */
3001 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3002 			off -= IP_ADDR_LEN;
3003 
3004 			while (off > 0) {
3005 				bcopy(opt + off,
3006 				    buf + off + IP_ADDR_LEN,
3007 				    IP_ADDR_LEN);
3008 				off -= IP_ADDR_LEN;
3009 			}
3010 			/* ipha_dst into first slot */
3011 			bcopy(&ipha->ipha_dst,
3012 			    buf + off + IP_ADDR_LEN,
3013 			    IP_ADDR_LEN);
3014 			buf += optlen;
3015 			len += optlen;
3016 			break;
3017 
3018 		case IPOPT_COMSEC:
3019 		case IPOPT_SECURITY:
3020 			/* if passing up a label is not ok, then remove */
3021 			if (is_system_labeled())
3022 				break;
3023 			/* FALLTHROUGH */
3024 		default:
3025 			bcopy(opt, buf, optlen);
3026 			buf += optlen;
3027 			len += optlen;
3028 			break;
3029 		}
3030 	}
3031 done:
3032 	/* Pad the resulting options */
3033 	while (len & 0x3) {
3034 		*buf++ = IPOPT_EOL;
3035 		len++;
3036 	}
3037 	return (len);
3038 }
3039 
3040 /*
3041  * Update any record route or timestamp options to include this host.
3042  * Reverse any source route option.
3043  * This routine assumes that the options are well formed i.e. that they
3044  * have already been checked.
3045  */
3046 static void
3047 icmp_options_update(ipha_t *ipha)
3048 {
3049 	ipoptp_t	opts;
3050 	uchar_t		*opt;
3051 	uint8_t		optval;
3052 	ipaddr_t	src;		/* Our local address */
3053 	ipaddr_t	dst;
3054 
3055 	ip2dbg(("icmp_options_update\n"));
3056 	src = ipha->ipha_src;
3057 	dst = ipha->ipha_dst;
3058 
3059 	for (optval = ipoptp_first(&opts, ipha);
3060 	    optval != IPOPT_EOL;
3061 	    optval = ipoptp_next(&opts)) {
3062 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3063 		opt = opts.ipoptp_cur;
3064 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3065 		    optval, opts.ipoptp_len));
3066 		switch (optval) {
3067 			int off1, off2;
3068 		case IPOPT_SSRR:
3069 		case IPOPT_LSRR:
3070 			/*
3071 			 * Reverse the source route.  The first entry
3072 			 * should be the next to last one in the current
3073 			 * source route (the last entry is our address).
3074 			 * The last entry should be the final destination.
3075 			 */
3076 			off1 = IPOPT_MINOFF_SR - 1;
3077 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3078 			if (off2 < 0) {
3079 				/* No entries in source route */
3080 				ip1dbg((
3081 				    "icmp_options_update: bad src route\n"));
3082 				break;
3083 			}
3084 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3085 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3086 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3087 			off2 -= IP_ADDR_LEN;
3088 
3089 			while (off1 < off2) {
3090 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3091 				bcopy((char *)opt + off2, (char *)opt + off1,
3092 				    IP_ADDR_LEN);
3093 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3094 				off1 += IP_ADDR_LEN;
3095 				off2 -= IP_ADDR_LEN;
3096 			}
3097 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3098 			break;
3099 		}
3100 	}
3101 }
3102 
3103 /*
3104  * Process received ICMP Redirect messages.
3105  */
3106 /* ARGSUSED */
3107 static void
3108 icmp_redirect(mblk_t *mp)
3109 {
3110 	ipha_t	*ipha;
3111 	int	iph_hdr_length;
3112 	icmph_t	*icmph;
3113 	ipha_t	*ipha_err;
3114 	ire_t	*ire;
3115 	ire_t	*prev_ire;
3116 	ire_t	*save_ire;
3117 	ipaddr_t  src, dst, gateway;
3118 	iulp_t	ulp_info = { 0 };
3119 	int	error;
3120 
3121 	ipha = (ipha_t *)mp->b_rptr;
3122 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3123 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3124 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3125 		BUMP_MIB(&icmp_mib, icmpInErrors);
3126 		freemsg(mp);
3127 		return;
3128 	}
3129 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3130 	ipha_err = (ipha_t *)&icmph[1];
3131 	src = ipha->ipha_src;
3132 	dst = ipha_err->ipha_dst;
3133 	gateway = icmph->icmph_rd_gateway;
3134 	/* Make sure the new gateway is reachable somehow. */
3135 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3136 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3137 	/*
3138 	 * Make sure we had a route for the dest in question and that
3139 	 * that route was pointing to the old gateway (the source of the
3140 	 * redirect packet.)
3141 	 */
3142 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3143 	    NULL, MATCH_IRE_GW);
3144 	/*
3145 	 * Check that
3146 	 *	the redirect was not from ourselves
3147 	 *	the new gateway and the old gateway are directly reachable
3148 	 */
3149 	if (!prev_ire ||
3150 	    !ire ||
3151 	    ire->ire_type == IRE_LOCAL) {
3152 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3153 		freemsg(mp);
3154 		if (ire != NULL)
3155 			ire_refrele(ire);
3156 		if (prev_ire != NULL)
3157 			ire_refrele(prev_ire);
3158 		return;
3159 	}
3160 
3161 	/*
3162 	 * Should we use the old ULP info to create the new gateway?  From
3163 	 * a user's perspective, we should inherit the info so that it
3164 	 * is a "smooth" transition.  If we do not do that, then new
3165 	 * connections going thru the new gateway will have no route metrics,
3166 	 * which is counter-intuitive to user.  From a network point of
3167 	 * view, this may or may not make sense even though the new gateway
3168 	 * is still directly connected to us so the route metrics should not
3169 	 * change much.
3170 	 *
3171 	 * But if the old ire_uinfo is not initialized, we do another
3172 	 * recursive lookup on the dest using the new gateway.  There may
3173 	 * be a route to that.  If so, use it to initialize the redirect
3174 	 * route.
3175 	 */
3176 	if (prev_ire->ire_uinfo.iulp_set) {
3177 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3178 	} else {
3179 		ire_t *tmp_ire;
3180 		ire_t *sire;
3181 
3182 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3183 		    ALL_ZONES, 0, NULL,
3184 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3185 		if (sire != NULL) {
3186 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3187 			/*
3188 			 * If sire != NULL, ire_ftable_lookup() should not
3189 			 * return a NULL value.
3190 			 */
3191 			ASSERT(tmp_ire != NULL);
3192 			ire_refrele(tmp_ire);
3193 			ire_refrele(sire);
3194 		} else if (tmp_ire != NULL) {
3195 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3196 			    sizeof (iulp_t));
3197 			ire_refrele(tmp_ire);
3198 		}
3199 	}
3200 	if (prev_ire->ire_type == IRE_CACHE)
3201 		ire_delete(prev_ire);
3202 	ire_refrele(prev_ire);
3203 	/*
3204 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3205 	 * require TOS routing
3206 	 */
3207 	switch (icmph->icmph_code) {
3208 	case 0:
3209 	case 1:
3210 		/* TODO: TOS specificity for cases 2 and 3 */
3211 	case 2:
3212 	case 3:
3213 		break;
3214 	default:
3215 		freemsg(mp);
3216 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3217 		ire_refrele(ire);
3218 		return;
3219 	}
3220 	/*
3221 	 * Create a Route Association.  This will allow us to remember that
3222 	 * someone we believe told us to use the particular gateway.
3223 	 */
3224 	save_ire = ire;
3225 	ire = ire_create(
3226 		(uchar_t *)&dst,			/* dest addr */
3227 		(uchar_t *)&ip_g_all_ones,		/* mask */
3228 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3229 		(uchar_t *)&gateway,			/* gateway addr */
3230 		NULL,					/* no in_srcaddr */
3231 		&save_ire->ire_max_frag,		/* max frag */
3232 		NULL,					/* Fast Path header */
3233 		NULL,					/* no rfq */
3234 		NULL,					/* no stq */
3235 		IRE_HOST_REDIRECT,
3236 		NULL,
3237 		NULL,
3238 		NULL,
3239 		0,
3240 		0,
3241 		0,
3242 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3243 		&ulp_info,
3244 		NULL,
3245 		NULL);
3246 
3247 	if (ire == NULL) {
3248 		freemsg(mp);
3249 		ire_refrele(save_ire);
3250 		return;
3251 	}
3252 	error = ire_add(&ire, NULL, NULL, NULL);
3253 	ire_refrele(save_ire);
3254 	if (error == 0) {
3255 		ire_refrele(ire);		/* Held in ire_add_v4 */
3256 		/* tell routing sockets that we received a redirect */
3257 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3258 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3259 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3260 	}
3261 
3262 	/*
3263 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
3264 	 * This together with the added IRE has the effect of
3265 	 * modifying an existing redirect.
3266 	 */
3267 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
3268 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3269 	if (prev_ire) {
3270 		ire_delete(prev_ire);
3271 		ire_refrele(prev_ire);
3272 	}
3273 
3274 	freemsg(mp);
3275 }
3276 
3277 /*
3278  * Generate an ICMP parameter problem message.
3279  */
3280 static void
3281 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3282 {
3283 	icmph_t	icmph;
3284 	boolean_t mctl_present;
3285 	mblk_t *first_mp;
3286 
3287 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3288 
3289 	if (!(mp = icmp_pkt_err_ok(mp))) {
3290 		if (mctl_present)
3291 			freeb(first_mp);
3292 		return;
3293 	}
3294 
3295 	bzero(&icmph, sizeof (icmph_t));
3296 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3297 	icmph.icmph_pp_ptr = ptr;
3298 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3299 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3300 }
3301 
3302 /*
3303  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3304  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3305  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3306  * an icmp error packet can be sent.
3307  * Assigns an appropriate source address to the packet. If ipha_dst is
3308  * one of our addresses use it for source. Otherwise pick a source based
3309  * on a route lookup back to ipha_src.
3310  * Note that ipha_src must be set here since the
3311  * packet is likely to arrive on an ill queue in ip_wput() which will
3312  * not set a source address.
3313  */
3314 static void
3315 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3316     boolean_t mctl_present)
3317 {
3318 	ipaddr_t dst;
3319 	icmph_t	*icmph;
3320 	ipha_t	*ipha;
3321 	uint_t	len_needed;
3322 	size_t	msg_len;
3323 	mblk_t	*mp1;
3324 	ipaddr_t src;
3325 	ire_t	*ire;
3326 	mblk_t *ipsec_mp;
3327 	ipsec_out_t	*io = NULL;
3328 	boolean_t xmit_if_on = B_FALSE;
3329 	zoneid_t	zoneid;
3330 
3331 	if (mctl_present) {
3332 		/*
3333 		 * If it is :
3334 		 *
3335 		 * 1) a IPSEC_OUT, then this is caused by outbound
3336 		 *    datagram originating on this host. IPSEC processing
3337 		 *    may or may not have been done. Refer to comments above
3338 		 *    icmp_inbound_error_fanout for details.
3339 		 *
3340 		 * 2) a IPSEC_IN if we are generating a icmp_message
3341 		 *    for an incoming datagram destined for us i.e called
3342 		 *    from ip_fanout_send_icmp.
3343 		 */
3344 		ipsec_info_t *in;
3345 		ipsec_mp = mp;
3346 		mp = ipsec_mp->b_cont;
3347 
3348 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3349 		ipha = (ipha_t *)mp->b_rptr;
3350 
3351 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3352 		    in->ipsec_info_type == IPSEC_IN);
3353 
3354 		if (in->ipsec_info_type == IPSEC_IN) {
3355 			/*
3356 			 * Convert the IPSEC_IN to IPSEC_OUT.
3357 			 */
3358 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3359 				BUMP_MIB(&ip_mib, ipOutDiscards);
3360 				return;
3361 			}
3362 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3363 		} else {
3364 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3365 			io = (ipsec_out_t *)in;
3366 			if (io->ipsec_out_xmit_if)
3367 				xmit_if_on = B_TRUE;
3368 			/*
3369 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3370 			 * ire lookup.
3371 			 */
3372 			io->ipsec_out_proc_begin = B_FALSE;
3373 		}
3374 		zoneid = io->ipsec_out_zoneid;
3375 		ASSERT(zoneid != ALL_ZONES);
3376 	} else {
3377 		/*
3378 		 * This is in clear. The icmp message we are building
3379 		 * here should go out in clear.
3380 		 *
3381 		 * Pardon the convolution of it all, but it's easier to
3382 		 * allocate a "use cleartext" IPSEC_IN message and convert
3383 		 * it than it is to allocate a new one.
3384 		 */
3385 		ipsec_in_t *ii;
3386 		ASSERT(DB_TYPE(mp) == M_DATA);
3387 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3388 			freemsg(mp);
3389 			BUMP_MIB(&ip_mib, ipOutDiscards);
3390 			return;
3391 		}
3392 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3393 
3394 		/* This is not a secure packet */
3395 		ii->ipsec_in_secure = B_FALSE;
3396 		if (CONN_Q(q)) {
3397 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3398 		} else {
3399 			zoneid = GLOBAL_ZONEID;
3400 		}
3401 		ii->ipsec_in_zoneid = zoneid;
3402 		ASSERT(zoneid != ALL_ZONES);
3403 		ipsec_mp->b_cont = mp;
3404 		ipha = (ipha_t *)mp->b_rptr;
3405 		/*
3406 		 * Convert the IPSEC_IN to IPSEC_OUT.
3407 		 */
3408 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3409 			BUMP_MIB(&ip_mib, ipOutDiscards);
3410 			return;
3411 		}
3412 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3413 	}
3414 
3415 	/* Remember our eventual destination */
3416 	dst = ipha->ipha_src;
3417 
3418 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3419 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3420 	if (ire != NULL &&
3421 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3422 		src = ipha->ipha_dst;
3423 	} else if (!xmit_if_on) {
3424 		if (ire != NULL)
3425 			ire_refrele(ire);
3426 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3427 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3428 		if (ire == NULL) {
3429 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3430 			freemsg(ipsec_mp);
3431 			return;
3432 		}
3433 		src = ire->ire_src_addr;
3434 	} else {
3435 		ipif_t	*ipif = NULL;
3436 		ill_t	*ill;
3437 		/*
3438 		 * This must be an ICMP error coming from
3439 		 * ip_mrtun_forward(). The src addr should
3440 		 * be equal to the IP-addr of the outgoing
3441 		 * interface.
3442 		 */
3443 		if (io == NULL) {
3444 			/* This is not a IPSEC_OUT type control msg */
3445 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3446 			freemsg(ipsec_mp);
3447 			return;
3448 		}
3449 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3450 		    NULL, NULL, NULL, NULL);
3451 		if (ill != NULL) {
3452 			ipif = ipif_get_next_ipif(NULL, ill);
3453 			ill_refrele(ill);
3454 		}
3455 		if (ipif == NULL) {
3456 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3457 			freemsg(ipsec_mp);
3458 			return;
3459 		}
3460 		src = ipif->ipif_src_addr;
3461 		ipif_refrele(ipif);
3462 	}
3463 
3464 	if (ire != NULL)
3465 		ire_refrele(ire);
3466 
3467 	/*
3468 	 * Check if we can send back more then 8 bytes in addition
3469 	 * to the IP header. We will include as much as 64 bytes.
3470 	 */
3471 	len_needed = IPH_HDR_LENGTH(ipha);
3472 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3473 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3474 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3475 	}
3476 	len_needed += ip_icmp_return;
3477 	msg_len = msgdsize(mp);
3478 	if (msg_len > len_needed) {
3479 		(void) adjmsg(mp, len_needed - msg_len);
3480 		msg_len = len_needed;
3481 	}
3482 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3483 	if (mp1 == NULL) {
3484 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3485 		freemsg(ipsec_mp);
3486 		return;
3487 	}
3488 	/*
3489 	 * On an unlabeled system, dblks don't necessarily have creds.
3490 	 */
3491 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3492 	if (DB_CRED(mp) != NULL)
3493 		mblk_setcred(mp1, DB_CRED(mp));
3494 	mp1->b_cont = mp;
3495 	mp = mp1;
3496 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3497 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3498 	    io->ipsec_out_type == IPSEC_OUT);
3499 	ipsec_mp->b_cont = mp;
3500 
3501 	/*
3502 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3503 	 * node generates be accepted in peace by all on-host destinations.
3504 	 * If we do NOT assume that all on-host destinations trust
3505 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3506 	 * (Look for ipsec_out_icmp_loopback).
3507 	 */
3508 	io->ipsec_out_icmp_loopback = B_TRUE;
3509 
3510 	ipha = (ipha_t *)mp->b_rptr;
3511 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3512 	*ipha = icmp_ipha;
3513 	ipha->ipha_src = src;
3514 	ipha->ipha_dst = dst;
3515 	ipha->ipha_ttl = ip_def_ttl;
3516 	msg_len += sizeof (icmp_ipha) + len;
3517 	if (msg_len > IP_MAXPACKET) {
3518 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3519 		msg_len = IP_MAXPACKET;
3520 	}
3521 	ipha->ipha_length = htons((uint16_t)msg_len);
3522 	icmph = (icmph_t *)&ipha[1];
3523 	bcopy(stuff, icmph, len);
3524 	icmph->icmph_checksum = 0;
3525 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3526 	if (icmph->icmph_checksum == 0)
3527 		icmph->icmph_checksum = 0xFFFF;
3528 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3529 	put(q, ipsec_mp);
3530 }
3531 
3532 /*
3533  * Determine if an ICMP error packet can be sent given the rate limit.
3534  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3535  * in milliseconds) and a burst size. Burst size number of packets can
3536  * be sent arbitrarely closely spaced.
3537  * The state is tracked using two variables to implement an approximate
3538  * token bucket filter:
3539  *	icmp_pkt_err_last - lbolt value when the last burst started
3540  *	icmp_pkt_err_sent - number of packets sent in current burst
3541  */
3542 boolean_t
3543 icmp_err_rate_limit(void)
3544 {
3545 	clock_t now = TICK_TO_MSEC(lbolt);
3546 	uint_t refilled; /* Number of packets refilled in tbf since last */
3547 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3548 
3549 	if (err_interval == 0)
3550 		return (B_FALSE);
3551 
3552 	if (icmp_pkt_err_last > now) {
3553 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3554 		icmp_pkt_err_last = 0;
3555 		icmp_pkt_err_sent = 0;
3556 	}
3557 	/*
3558 	 * If we are in a burst update the token bucket filter.
3559 	 * Update the "last" time to be close to "now" but make sure
3560 	 * we don't loose precision.
3561 	 */
3562 	if (icmp_pkt_err_sent != 0) {
3563 		refilled = (now - icmp_pkt_err_last)/err_interval;
3564 		if (refilled > icmp_pkt_err_sent) {
3565 			icmp_pkt_err_sent = 0;
3566 		} else {
3567 			icmp_pkt_err_sent -= refilled;
3568 			icmp_pkt_err_last += refilled * err_interval;
3569 		}
3570 	}
3571 	if (icmp_pkt_err_sent == 0) {
3572 		/* Start of new burst */
3573 		icmp_pkt_err_last = now;
3574 	}
3575 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3576 		icmp_pkt_err_sent++;
3577 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3578 		    icmp_pkt_err_sent));
3579 		return (B_FALSE);
3580 	}
3581 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3582 	return (B_TRUE);
3583 }
3584 
3585 /*
3586  * Check if it is ok to send an IPv4 ICMP error packet in
3587  * response to the IPv4 packet in mp.
3588  * Free the message and return null if no
3589  * ICMP error packet should be sent.
3590  */
3591 static mblk_t *
3592 icmp_pkt_err_ok(mblk_t *mp)
3593 {
3594 	icmph_t	*icmph;
3595 	ipha_t	*ipha;
3596 	uint_t	len_needed;
3597 	ire_t	*src_ire;
3598 	ire_t	*dst_ire;
3599 
3600 	if (!mp)
3601 		return (NULL);
3602 	ipha = (ipha_t *)mp->b_rptr;
3603 	if (ip_csum_hdr(ipha)) {
3604 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3605 		freemsg(mp);
3606 		return (NULL);
3607 	}
3608 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3609 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3610 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3611 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3612 	if (src_ire != NULL || dst_ire != NULL ||
3613 	    CLASSD(ipha->ipha_dst) ||
3614 	    CLASSD(ipha->ipha_src) ||
3615 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3616 		/* Note: only errors to the fragment with offset 0 */
3617 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3618 		freemsg(mp);
3619 		if (src_ire != NULL)
3620 			ire_refrele(src_ire);
3621 		if (dst_ire != NULL)
3622 			ire_refrele(dst_ire);
3623 		return (NULL);
3624 	}
3625 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3626 		/*
3627 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3628 		 * errors in response to any ICMP errors.
3629 		 */
3630 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3631 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3632 			if (!pullupmsg(mp, len_needed)) {
3633 				BUMP_MIB(&icmp_mib, icmpInErrors);
3634 				freemsg(mp);
3635 				return (NULL);
3636 			}
3637 			ipha = (ipha_t *)mp->b_rptr;
3638 		}
3639 		icmph = (icmph_t *)
3640 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3641 		switch (icmph->icmph_type) {
3642 		case ICMP_DEST_UNREACHABLE:
3643 		case ICMP_SOURCE_QUENCH:
3644 		case ICMP_TIME_EXCEEDED:
3645 		case ICMP_PARAM_PROBLEM:
3646 		case ICMP_REDIRECT:
3647 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3648 			freemsg(mp);
3649 			return (NULL);
3650 		default:
3651 			break;
3652 		}
3653 	}
3654 	/*
3655 	 * If this is a labeled system, then check to see if we're allowed to
3656 	 * send a response to this particular sender.  If not, then just drop.
3657 	 */
3658 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3659 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3660 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3661 		freemsg(mp);
3662 		return (NULL);
3663 	}
3664 	if (icmp_err_rate_limit()) {
3665 		/*
3666 		 * Only send ICMP error packets every so often.
3667 		 * This should be done on a per port/source basis,
3668 		 * but for now this will suffice.
3669 		 */
3670 		freemsg(mp);
3671 		return (NULL);
3672 	}
3673 	return (mp);
3674 }
3675 
3676 /*
3677  * Generate an ICMP redirect message.
3678  */
3679 static void
3680 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3681 {
3682 	icmph_t	icmph;
3683 
3684 	/*
3685 	 * We are called from ip_rput where we could
3686 	 * not have attached an IPSEC_IN.
3687 	 */
3688 	ASSERT(mp->b_datap->db_type == M_DATA);
3689 
3690 	if (!(mp = icmp_pkt_err_ok(mp))) {
3691 		return;
3692 	}
3693 
3694 	bzero(&icmph, sizeof (icmph_t));
3695 	icmph.icmph_type = ICMP_REDIRECT;
3696 	icmph.icmph_code = 1;
3697 	icmph.icmph_rd_gateway = gateway;
3698 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3699 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3700 }
3701 
3702 /*
3703  * Generate an ICMP time exceeded message.
3704  */
3705 void
3706 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3707 {
3708 	icmph_t	icmph;
3709 	boolean_t mctl_present;
3710 	mblk_t *first_mp;
3711 
3712 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3713 
3714 	if (!(mp = icmp_pkt_err_ok(mp))) {
3715 		if (mctl_present)
3716 			freeb(first_mp);
3717 		return;
3718 	}
3719 
3720 	bzero(&icmph, sizeof (icmph_t));
3721 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3722 	icmph.icmph_code = code;
3723 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3724 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3725 }
3726 
3727 /*
3728  * Generate an ICMP unreachable message.
3729  */
3730 void
3731 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3732 {
3733 	icmph_t	icmph;
3734 	mblk_t *first_mp;
3735 	boolean_t mctl_present;
3736 
3737 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3738 
3739 	if (!(mp = icmp_pkt_err_ok(mp))) {
3740 		if (mctl_present)
3741 			freeb(first_mp);
3742 		return;
3743 	}
3744 
3745 	bzero(&icmph, sizeof (icmph_t));
3746 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3747 	icmph.icmph_code = code;
3748 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3749 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3750 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3751 }
3752 
3753 /*
3754  * News from ARP.  ARP sends notification of interesting events down
3755  * to its clients using M_CTL messages with the interesting ARP packet
3756  * attached via b_cont.
3757  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3758  * queue as opposed to ARP sending the message to all the clients, i.e. all
3759  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3760  * table if a cache IRE is found to delete all the entries for the address in
3761  * the packet.
3762  */
3763 static void
3764 ip_arp_news(queue_t *q, mblk_t *mp)
3765 {
3766 	arcn_t		*arcn;
3767 	arh_t		*arh;
3768 	char		*cp1;
3769 	uchar_t		*cp2;
3770 	ire_t		*ire = NULL;
3771 	int		i1;
3772 	char		hbuf[128];
3773 	char		sbuf[16];
3774 	ipaddr_t	src;
3775 	in6_addr_t	v6src;
3776 	boolean_t	isv6 = B_FALSE;
3777 
3778 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3779 		if (q->q_next) {
3780 			putnext(q, mp);
3781 		} else
3782 			freemsg(mp);
3783 		return;
3784 	}
3785 	arh = (arh_t *)mp->b_cont->b_rptr;
3786 	/* Is it one we are interested in? */
3787 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3788 		isv6 = B_TRUE;
3789 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3790 		    IPV6_ADDR_LEN);
3791 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3792 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3793 		    IP_ADDR_LEN);
3794 	} else {
3795 		freemsg(mp);
3796 		return;
3797 	}
3798 
3799 	arcn = (arcn_t *)mp->b_rptr;
3800 	switch (arcn->arcn_code) {
3801 	case AR_CN_BOGON:
3802 		/*
3803 		 * Someone is sending ARP packets with a source protocol
3804 		 * address which we have published.  Either they are
3805 		 * pretending to be us, or we have been asked to proxy
3806 		 * for a machine that can do fine for itself, or two
3807 		 * different machines are providing proxy service for the
3808 		 * same protocol address, or something.  We try and do
3809 		 * something appropriate here.
3810 		 */
3811 		cp2 = (uchar_t *)&arh[1];
3812 		cp1 = hbuf;
3813 		*cp1 = '\0';
3814 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3815 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3816 		if (cp1 != hbuf)
3817 			cp1[-1] = '\0';
3818 		(void) ip_dot_addr(src, sbuf);
3819 		if (isv6)
3820 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
3821 		else
3822 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
3823 
3824 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3825 			cmn_err(CE_WARN,
3826 			    "IP: Hardware address '%s' trying"
3827 			    " to be our address %s!",
3828 			    hbuf, sbuf);
3829 		} else {
3830 			cmn_err(CE_WARN,
3831 			    "IP: Proxy ARP problem?  "
3832 			    "Hardware address '%s' thinks it is %s",
3833 			    hbuf, sbuf);
3834 		}
3835 		if (ire != NULL)
3836 			ire_refrele(ire);
3837 		break;
3838 	case AR_CN_ANNOUNCE:
3839 		if (isv6) {
3840 			/*
3841 			 * For XRESOLV interfaces.
3842 			 * Delete the IRE cache entry and NCE for this
3843 			 * v6 address
3844 			 */
3845 			ip_ire_clookup_and_delete_v6(&v6src);
3846 			/*
3847 			 * If v6src is a non-zero, it's a router address
3848 			 * as below. Do the same sort of thing to clean
3849 			 * out off-net IRE_CACHE entries that go through
3850 			 * the router.
3851 			 */
3852 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3853 				ire_walk_v6(ire_delete_cache_gw_v6,
3854 				    (char *)&v6src, ALL_ZONES);
3855 			}
3856 			break;
3857 		}
3858 		/*
3859 		 * ARP gives us a copy of any broadcast packet with identical
3860 		 * sender and receiver protocol address, in
3861 		 * case we want to intuit something from it.  Such a packet
3862 		 * usually means that a machine has just come up on the net.
3863 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3864 		 * immediately pick up the rare case of a host changing
3865 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3866 		 *
3867 		 * The address in "src" may be an entry for a router.
3868 		 * (Default router, or non-default router.)  If
3869 		 * that's true, then any off-net IRE_CACHE entries
3870 		 * that go through the router with address "src"
3871 		 * must be clobbered.  Use ire_walk to achieve this
3872 		 * goal.
3873 		 *
3874 		 * It should be possible to determine if the address
3875 		 * in src is or is not for a router.  This way,
3876 		 * the ire_walk() isn't called all of the time here.
3877 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3878 		 * as it would remove all IRE_CACHE entries for onlink
3879 		 * destinations. All onlink destinations have
3880 		 * ire_gateway_addr == 0.
3881 		 */
3882 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3883 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3884 		    0, NULL, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3885 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3886 			    ALL_ZONES);
3887 		}
3888 		/* From ire_ftable_lookup */
3889 		if (ire != NULL)
3890 			ire_refrele(ire);
3891 		break;
3892 	default:
3893 		if (ire != NULL)
3894 			ire_refrele(ire);
3895 		break;
3896 	}
3897 	freemsg(mp);
3898 }
3899 
3900 /*
3901  * Create a mblk suitable for carrying the interface index and/or source link
3902  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3903  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3904  * application.
3905  */
3906 mblk_t *
3907 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3908 {
3909 	mblk_t		*mp;
3910 	in_pktinfo_t	*pinfo;
3911 	ipha_t *ipha;
3912 	struct ether_header *pether;
3913 
3914 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3915 	if (mp == NULL) {
3916 		ip1dbg(("ip_add_info: allocation failure.\n"));
3917 		return (data_mp);
3918 	}
3919 
3920 	ipha	= (ipha_t *)data_mp->b_rptr;
3921 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3922 	bzero(pinfo, sizeof (in_pktinfo_t));
3923 	pinfo->in_pkt_flags = (uchar_t)flags;
3924 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3925 
3926 	if (flags & IPF_RECVIF)
3927 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3928 
3929 	pether = (struct ether_header *)((char *)ipha
3930 	    - sizeof (struct ether_header));
3931 	/*
3932 	 * Make sure the interface is an ethernet type, since this option
3933 	 * is currently supported only on this type of interface. Also make
3934 	 * sure we are pointing correctly above db_base.
3935 	 */
3936 
3937 	if ((flags & IPF_RECVSLLA) &&
3938 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3939 	    (ill->ill_type == IFT_ETHER) &&
3940 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3941 
3942 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3943 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3944 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3945 	} else {
3946 		/*
3947 		 * Clear the bit. Indicate to upper layer that IP is not
3948 		 * sending this ancillary info.
3949 		 */
3950 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3951 	}
3952 
3953 	mp->b_datap->db_type = M_CTL;
3954 	mp->b_wptr += sizeof (in_pktinfo_t);
3955 	mp->b_cont = data_mp;
3956 
3957 	return (mp);
3958 }
3959 
3960 /*
3961  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3962  * part of the bind request.
3963  */
3964 
3965 boolean_t
3966 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3967 {
3968 	ipsec_in_t *ii;
3969 
3970 	ASSERT(policy_mp != NULL);
3971 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3972 
3973 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3974 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3975 
3976 	connp->conn_policy = ii->ipsec_in_policy;
3977 	ii->ipsec_in_policy = NULL;
3978 
3979 	if (ii->ipsec_in_action != NULL) {
3980 		if (connp->conn_latch == NULL) {
3981 			connp->conn_latch = iplatch_create();
3982 			if (connp->conn_latch == NULL)
3983 				return (B_FALSE);
3984 		}
3985 		ipsec_latch_inbound(connp->conn_latch, ii);
3986 	}
3987 	return (B_TRUE);
3988 }
3989 
3990 /*
3991  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3992  * and to arrange for power-fanout assist.  The ULP is identified by
3993  * adding a single byte at the end of the original bind message.
3994  * A ULP other than UDP or TCP that wishes to be recognized passes
3995  * down a bind with a zero length address.
3996  *
3997  * The binding works as follows:
3998  * - A zero byte address means just bind to the protocol.
3999  * - A four byte address is treated as a request to validate
4000  *   that the address is a valid local address, appropriate for
4001  *   an application to bind to. This does not affect any fanout
4002  *   information in IP.
4003  * - A sizeof sin_t byte address is used to bind to only the local address
4004  *   and port.
4005  * - A sizeof ipa_conn_t byte address contains complete fanout information
4006  *   consisting of local and remote addresses and ports.  In
4007  *   this case, the addresses are both validated as appropriate
4008  *   for this operation, and, if so, the information is retained
4009  *   for use in the inbound fanout.
4010  *
4011  * The ULP (except in the zero-length bind) can append an
4012  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4013  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4014  * a copy of the source or destination IRE (source for local bind;
4015  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4016  * policy information contained should be copied on to the conn.
4017  *
4018  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4019  */
4020 mblk_t *
4021 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4022 {
4023 	ssize_t		len;
4024 	struct T_bind_req	*tbr;
4025 	sin_t		*sin;
4026 	ipa_conn_t	*ac;
4027 	uchar_t		*ucp;
4028 	mblk_t		*mp1;
4029 	boolean_t	ire_requested;
4030 	boolean_t	ipsec_policy_set = B_FALSE;
4031 	int		error = 0;
4032 	int		protocol;
4033 	ipa_conn_x_t	*acx;
4034 
4035 	ASSERT(!connp->conn_af_isv6);
4036 	connp->conn_pkt_isv6 = B_FALSE;
4037 
4038 	len = MBLKL(mp);
4039 	if (len < (sizeof (*tbr) + 1)) {
4040 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4041 		    "ip_bind: bogus msg, len %ld", len);
4042 		/* XXX: Need to return something better */
4043 		goto bad_addr;
4044 	}
4045 	/* Back up and extract the protocol identifier. */
4046 	mp->b_wptr--;
4047 	protocol = *mp->b_wptr & 0xFF;
4048 	tbr = (struct T_bind_req *)mp->b_rptr;
4049 	/* Reset the message type in preparation for shipping it back. */
4050 	DB_TYPE(mp) = M_PCPROTO;
4051 
4052 	connp->conn_ulp = (uint8_t)protocol;
4053 
4054 	/*
4055 	 * Check for a zero length address.  This is from a protocol that
4056 	 * wants to register to receive all packets of its type.
4057 	 */
4058 	if (tbr->ADDR_length == 0) {
4059 		/*
4060 		 * These protocols are now intercepted in ip_bind_v6().
4061 		 * Reject protocol-level binds here for now.
4062 		 *
4063 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4064 		 * so that the protocol type cannot be SCTP.
4065 		 */
4066 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4067 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4068 			goto bad_addr;
4069 		}
4070 
4071 		/*
4072 		 *
4073 		 * The udp module never sends down a zero-length address,
4074 		 * and allowing this on a labeled system will break MLP
4075 		 * functionality.
4076 		 */
4077 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4078 			goto bad_addr;
4079 
4080 		if (connp->conn_mac_exempt)
4081 			goto bad_addr;
4082 
4083 		/* No hash here really.  The table is big enough. */
4084 		connp->conn_srcv6 = ipv6_all_zeros;
4085 
4086 		ipcl_proto_insert(connp, protocol);
4087 
4088 		tbr->PRIM_type = T_BIND_ACK;
4089 		return (mp);
4090 	}
4091 
4092 	/* Extract the address pointer from the message. */
4093 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4094 	    tbr->ADDR_length);
4095 	if (ucp == NULL) {
4096 		ip1dbg(("ip_bind: no address\n"));
4097 		goto bad_addr;
4098 	}
4099 	if (!OK_32PTR(ucp)) {
4100 		ip1dbg(("ip_bind: unaligned address\n"));
4101 		goto bad_addr;
4102 	}
4103 	/*
4104 	 * Check for trailing mps.
4105 	 */
4106 
4107 	mp1 = mp->b_cont;
4108 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4109 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4110 
4111 	switch (tbr->ADDR_length) {
4112 	default:
4113 		ip1dbg(("ip_bind: bad address length %d\n",
4114 		    (int)tbr->ADDR_length));
4115 		goto bad_addr;
4116 
4117 	case IP_ADDR_LEN:
4118 		/* Verification of local address only */
4119 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4120 		    ire_requested, ipsec_policy_set, B_FALSE);
4121 		break;
4122 
4123 	case sizeof (sin_t):
4124 		sin = (sin_t *)ucp;
4125 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4126 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4127 		if (protocol == IPPROTO_TCP)
4128 			connp->conn_recv = tcp_conn_request;
4129 		break;
4130 
4131 	case sizeof (ipa_conn_t):
4132 		ac = (ipa_conn_t *)ucp;
4133 		/* For raw socket, the local port is not set. */
4134 		if (ac->ac_lport == 0)
4135 			ac->ac_lport = connp->conn_lport;
4136 		/* Always verify destination reachability. */
4137 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4138 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4139 		    ipsec_policy_set, B_TRUE, B_TRUE);
4140 		if (protocol == IPPROTO_TCP)
4141 			connp->conn_recv = tcp_input;
4142 		break;
4143 
4144 	case sizeof (ipa_conn_x_t):
4145 		acx = (ipa_conn_x_t *)ucp;
4146 		/*
4147 		 * Whether or not to verify destination reachability depends
4148 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4149 		 */
4150 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4151 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4152 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4153 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4154 		if (protocol == IPPROTO_TCP)
4155 			connp->conn_recv = tcp_input;
4156 		break;
4157 	}
4158 	if (error == EINPROGRESS)
4159 		return (NULL);
4160 	else if (error != 0)
4161 		goto bad_addr;
4162 	/*
4163 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4164 	 * We can't do this in ip_bind_insert_ire because the policy
4165 	 * may not have been inherited at that point in time and hence
4166 	 * conn_out_enforce_policy may not be set.
4167 	 */
4168 	mp1 = mp->b_cont;
4169 	if (ire_requested && connp->conn_out_enforce_policy &&
4170 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4171 		ire_t *ire = (ire_t *)mp1->b_rptr;
4172 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4173 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4174 	}
4175 
4176 	/* Send it home. */
4177 	mp->b_datap->db_type = M_PCPROTO;
4178 	tbr->PRIM_type = T_BIND_ACK;
4179 	return (mp);
4180 
4181 bad_addr:
4182 	/*
4183 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4184 	 * a unix errno.
4185 	 */
4186 	if (error > 0)
4187 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4188 	else
4189 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4190 	return (mp);
4191 }
4192 
4193 /*
4194  * Here address is verified to be a valid local address.
4195  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4196  * address is also considered a valid local address.
4197  * In the case of a broadcast/multicast address, however, the
4198  * upper protocol is expected to reset the src address
4199  * to 0 if it sees a IRE_BROADCAST type returned so that
4200  * no packets are emitted with broadcast/multicast address as
4201  * source address (that violates hosts requirements RFC1122)
4202  * The addresses valid for bind are:
4203  *	(1) - INADDR_ANY (0)
4204  *	(2) - IP address of an UP interface
4205  *	(3) - IP address of a DOWN interface
4206  *	(4) - valid local IP broadcast addresses. In this case
4207  *	the conn will only receive packets destined to
4208  *	the specified broadcast address.
4209  *	(5) - a multicast address. In this case
4210  *	the conn will only receive packets destined to
4211  *	the specified multicast address. Note: the
4212  *	application still has to issue an
4213  *	IP_ADD_MEMBERSHIP socket option.
4214  *
4215  * On error, return -1 for TBADADDR otherwise pass the
4216  * errno with TSYSERR reply.
4217  *
4218  * In all the above cases, the bound address must be valid in the current zone.
4219  * When the address is loopback, multicast or broadcast, there might be many
4220  * matching IREs so bind has to look up based on the zone.
4221  *
4222  * Note: lport is in network byte order.
4223  */
4224 int
4225 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4226     boolean_t ire_requested, boolean_t ipsec_policy_set,
4227     boolean_t fanout_insert)
4228 {
4229 	int		error = 0;
4230 	ire_t		*src_ire;
4231 	mblk_t		*policy_mp;
4232 	ipif_t		*ipif;
4233 	zoneid_t	zoneid;
4234 
4235 	if (ipsec_policy_set) {
4236 		policy_mp = mp->b_cont;
4237 	}
4238 
4239 	/*
4240 	 * If it was previously connected, conn_fully_bound would have
4241 	 * been set.
4242 	 */
4243 	connp->conn_fully_bound = B_FALSE;
4244 
4245 	src_ire = NULL;
4246 	ipif = NULL;
4247 
4248 	zoneid = connp->conn_zoneid;
4249 
4250 	if (src_addr) {
4251 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4252 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4253 		/*
4254 		 * If an address other than 0.0.0.0 is requested,
4255 		 * we verify that it is a valid address for bind
4256 		 * Note: Following code is in if-else-if form for
4257 		 * readability compared to a condition check.
4258 		 */
4259 		/* LINTED - statement has no consequent */
4260 		if (IRE_IS_LOCAL(src_ire)) {
4261 			/*
4262 			 * (2) Bind to address of local UP interface
4263 			 */
4264 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4265 			/*
4266 			 * (4) Bind to broadcast address
4267 			 * Note: permitted only from transports that
4268 			 * request IRE
4269 			 */
4270 			if (!ire_requested)
4271 				error = EADDRNOTAVAIL;
4272 		} else {
4273 			/*
4274 			 * (3) Bind to address of local DOWN interface
4275 			 * (ipif_lookup_addr() looks up all interfaces
4276 			 * but we do not get here for UP interfaces
4277 			 * - case (2) above)
4278 			 * We put the protocol byte back into the mblk
4279 			 * since we may come back via ip_wput_nondata()
4280 			 * later with this mblk if ipif_lookup_addr chooses
4281 			 * to defer processing.
4282 			 */
4283 			*mp->b_wptr++ = (char)connp->conn_ulp;
4284 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4285 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4286 			    &error)) != NULL) {
4287 				ipif_refrele(ipif);
4288 			} else if (error == EINPROGRESS) {
4289 				if (src_ire != NULL)
4290 					ire_refrele(src_ire);
4291 				return (EINPROGRESS);
4292 			} else if (CLASSD(src_addr)) {
4293 				error = 0;
4294 				if (src_ire != NULL)
4295 					ire_refrele(src_ire);
4296 				/*
4297 				 * (5) bind to multicast address.
4298 				 * Fake out the IRE returned to upper
4299 				 * layer to be a broadcast IRE.
4300 				 */
4301 				src_ire = ire_ctable_lookup(
4302 				    INADDR_BROADCAST, INADDR_ANY,
4303 				    IRE_BROADCAST, NULL, zoneid, NULL,
4304 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4305 				if (src_ire == NULL || !ire_requested)
4306 					error = EADDRNOTAVAIL;
4307 			} else {
4308 				/*
4309 				 * Not a valid address for bind
4310 				 */
4311 				error = EADDRNOTAVAIL;
4312 			}
4313 			/*
4314 			 * Just to keep it consistent with the processing in
4315 			 * ip_bind_v4()
4316 			 */
4317 			mp->b_wptr--;
4318 		}
4319 		if (error) {
4320 			/* Red Alert!  Attempting to be a bogon! */
4321 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4322 			    ntohl(src_addr)));
4323 			goto bad_addr;
4324 		}
4325 	}
4326 
4327 	/*
4328 	 * Allow setting new policies. For example, disconnects come
4329 	 * down as ipa_t bind. As we would have set conn_policy_cached
4330 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4331 	 * can change after the disconnect.
4332 	 */
4333 	connp->conn_policy_cached = B_FALSE;
4334 
4335 	/*
4336 	 * If not fanout_insert this was just an address verification
4337 	 */
4338 	if (fanout_insert) {
4339 		/*
4340 		 * The addresses have been verified. Time to insert in
4341 		 * the correct fanout list.
4342 		 */
4343 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4344 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4345 		connp->conn_lport = lport;
4346 		connp->conn_fport = 0;
4347 		/*
4348 		 * Do we need to add a check to reject Multicast packets
4349 		 */
4350 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4351 	}
4352 
4353 	if (error == 0) {
4354 		if (ire_requested) {
4355 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4356 				error = -1;
4357 				/* Falls through to bad_addr */
4358 			}
4359 		} else if (ipsec_policy_set) {
4360 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4361 				error = -1;
4362 				/* Falls through to bad_addr */
4363 			}
4364 		}
4365 	}
4366 bad_addr:
4367 	if (error != 0) {
4368 		if (connp->conn_anon_port) {
4369 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4370 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4371 			    B_FALSE);
4372 		}
4373 		connp->conn_mlp_type = mlptSingle;
4374 	}
4375 	if (src_ire != NULL)
4376 		IRE_REFRELE(src_ire);
4377 	if (ipsec_policy_set) {
4378 		ASSERT(policy_mp == mp->b_cont);
4379 		ASSERT(policy_mp != NULL);
4380 		freeb(policy_mp);
4381 		/*
4382 		 * As of now assume that nothing else accompanies
4383 		 * IPSEC_POLICY_SET.
4384 		 */
4385 		mp->b_cont = NULL;
4386 	}
4387 	return (error);
4388 }
4389 
4390 /*
4391  * Verify that both the source and destination addresses
4392  * are valid.  If verify_dst is false, then the destination address may be
4393  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4394  * destination reachability, while tunnels do not.
4395  * Note that we allow connect to broadcast and multicast
4396  * addresses when ire_requested is set. Thus the ULP
4397  * has to check for IRE_BROADCAST and multicast.
4398  *
4399  * Returns zero if ok.
4400  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4401  * (for use with TSYSERR reply).
4402  *
4403  * Note: lport and fport are in network byte order.
4404  */
4405 int
4406 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4407     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4408     boolean_t ire_requested, boolean_t ipsec_policy_set,
4409     boolean_t fanout_insert, boolean_t verify_dst)
4410 {
4411 	ire_t		*src_ire;
4412 	ire_t		*dst_ire;
4413 	int		error = 0;
4414 	int 		protocol;
4415 	mblk_t		*policy_mp;
4416 	ire_t		*sire = NULL;
4417 	ire_t		*md_dst_ire = NULL;
4418 	ill_t		*md_ill = NULL;
4419 	zoneid_t	zoneid;
4420 	ipaddr_t	src_addr = *src_addrp;
4421 
4422 	src_ire = dst_ire = NULL;
4423 	protocol = *mp->b_wptr & 0xFF;
4424 
4425 	/*
4426 	 * If we never got a disconnect before, clear it now.
4427 	 */
4428 	connp->conn_fully_bound = B_FALSE;
4429 
4430 	if (ipsec_policy_set) {
4431 		policy_mp = mp->b_cont;
4432 	}
4433 
4434 	zoneid = connp->conn_zoneid;
4435 
4436 	if (CLASSD(dst_addr)) {
4437 		/* Pick up an IRE_BROADCAST */
4438 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4439 		    NULL, zoneid, MBLK_GETLABEL(mp),
4440 		    (MATCH_IRE_RECURSIVE |
4441 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4442 		    MATCH_IRE_SECATTR));
4443 	} else {
4444 		/*
4445 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4446 		 * and onlink ipif is not found set ENETUNREACH error.
4447 		 */
4448 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4449 			ipif_t *ipif;
4450 
4451 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4452 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4453 			if (ipif == NULL) {
4454 				error = ENETUNREACH;
4455 				goto bad_addr;
4456 			}
4457 			ipif_refrele(ipif);
4458 		}
4459 
4460 		if (connp->conn_nexthop_set) {
4461 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4462 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4463 			    MATCH_IRE_SECATTR);
4464 		} else {
4465 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4466 			    &sire, zoneid, MBLK_GETLABEL(mp),
4467 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4468 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4469 			    MATCH_IRE_SECATTR));
4470 		}
4471 	}
4472 	/*
4473 	 * dst_ire can't be a broadcast when not ire_requested.
4474 	 * We also prevent ire's with src address INADDR_ANY to
4475 	 * be used, which are created temporarily for
4476 	 * sending out packets from endpoints that have
4477 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4478 	 * reachable.  If verify_dst is false, the destination needn't be
4479 	 * reachable.
4480 	 *
4481 	 * If we match on a reject or black hole, then we've got a
4482 	 * local failure.  May as well fail out the connect() attempt,
4483 	 * since it's never going to succeed.
4484 	 */
4485 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4486 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4487 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4488 		/*
4489 		 * If we're verifying destination reachability, we always want
4490 		 * to complain here.
4491 		 *
4492 		 * If we're not verifying destination reachability but the
4493 		 * destination has a route, we still want to fail on the
4494 		 * temporary address and broadcast address tests.
4495 		 */
4496 		if (verify_dst || (dst_ire != NULL)) {
4497 			if (ip_debug > 2) {
4498 				pr_addr_dbg("ip_bind_connected: bad connected "
4499 				    "dst %s\n", AF_INET, &dst_addr);
4500 			}
4501 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4502 				error = ENETUNREACH;
4503 			else
4504 				error = EHOSTUNREACH;
4505 			goto bad_addr;
4506 		}
4507 	}
4508 
4509 	/*
4510 	 * We now know that routing will allow us to reach the destination.
4511 	 * Check whether Trusted Solaris policy allows communication with this
4512 	 * host, and pretend that the destination is unreachable if not.
4513 	 *
4514 	 * This is never a problem for TCP, since that transport is known to
4515 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4516 	 * handling.  If the remote is unreachable, it will be detected at that
4517 	 * point, so there's no reason to check it here.
4518 	 *
4519 	 * Note that for sendto (and other datagram-oriented friends), this
4520 	 * check is done as part of the data path label computation instead.
4521 	 * The check here is just to make non-TCP connect() report the right
4522 	 * error.
4523 	 */
4524 	if (dst_ire != NULL && is_system_labeled() &&
4525 	    !IPCL_IS_TCP(connp) &&
4526 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4527 	    connp->conn_mac_exempt) != 0) {
4528 		error = EHOSTUNREACH;
4529 		if (ip_debug > 2) {
4530 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4531 			    AF_INET, &dst_addr);
4532 		}
4533 		goto bad_addr;
4534 	}
4535 
4536 	/*
4537 	 * If the app does a connect(), it means that it will most likely
4538 	 * send more than 1 packet to the destination.  It makes sense
4539 	 * to clear the temporary flag.
4540 	 */
4541 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4542 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4543 		irb_t *irb = dst_ire->ire_bucket;
4544 
4545 		rw_enter(&irb->irb_lock, RW_WRITER);
4546 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4547 		irb->irb_tmp_ire_cnt--;
4548 		rw_exit(&irb->irb_lock);
4549 	}
4550 
4551 	/*
4552 	 * See if we should notify ULP about MDT; we do this whether or not
4553 	 * ire_requested is TRUE, in order to handle active connects; MDT
4554 	 * eligibility tests for passive connects are handled separately
4555 	 * through tcp_adapt_ire().  We do this before the source address
4556 	 * selection, because dst_ire may change after a call to
4557 	 * ipif_select_source().  This is a best-effort check, as the
4558 	 * packet for this connection may not actually go through
4559 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4560 	 * calling ip_newroute().  This is why we further check on the
4561 	 * IRE during Multidata packet transmission in tcp_multisend().
4562 	 */
4563 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4564 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4565 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4566 	    ILL_MDT_CAPABLE(md_ill)) {
4567 		md_dst_ire = dst_ire;
4568 		IRE_REFHOLD(md_dst_ire);
4569 	}
4570 
4571 	if (dst_ire != NULL &&
4572 	    dst_ire->ire_type == IRE_LOCAL &&
4573 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4574 		/*
4575 		 * If the IRE belongs to a different zone, look for a matching
4576 		 * route in the forwarding table and use the source address from
4577 		 * that route.
4578 		 */
4579 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4580 		    zoneid, 0, NULL,
4581 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4582 		    MATCH_IRE_RJ_BHOLE);
4583 		if (src_ire == NULL) {
4584 			error = EHOSTUNREACH;
4585 			goto bad_addr;
4586 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4587 			if (!(src_ire->ire_type & IRE_HOST))
4588 				error = ENETUNREACH;
4589 			else
4590 				error = EHOSTUNREACH;
4591 			goto bad_addr;
4592 		}
4593 		if (src_addr == INADDR_ANY)
4594 			src_addr = src_ire->ire_src_addr;
4595 		ire_refrele(src_ire);
4596 		src_ire = NULL;
4597 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4598 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4599 			src_addr = sire->ire_src_addr;
4600 			ire_refrele(dst_ire);
4601 			dst_ire = sire;
4602 			sire = NULL;
4603 		} else {
4604 			/*
4605 			 * Pick a source address so that a proper inbound
4606 			 * load spreading would happen.
4607 			 */
4608 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4609 			ipif_t *src_ipif = NULL;
4610 			ire_t *ipif_ire;
4611 
4612 			/*
4613 			 * Supply a local source address such that inbound
4614 			 * load spreading happens.
4615 			 *
4616 			 * Determine the best source address on this ill for
4617 			 * the destination.
4618 			 *
4619 			 * 1) For broadcast, we should return a broadcast ire
4620 			 *    found above so that upper layers know that the
4621 			 *    destination address is a broadcast address.
4622 			 *
4623 			 * 2) If this is part of a group, select a better
4624 			 *    source address so that better inbound load
4625 			 *    balancing happens. Do the same if the ipif
4626 			 *    is DEPRECATED.
4627 			 *
4628 			 * 3) If the outgoing interface is part of a usesrc
4629 			 *    group, then try selecting a source address from
4630 			 *    the usesrc ILL.
4631 			 */
4632 			if ((dst_ire->ire_zoneid != zoneid &&
4633 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4634 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4635 			    ((dst_ill->ill_group != NULL) ||
4636 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4637 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4638 				/*
4639 				 * If the destination is reachable via a
4640 				 * given gateway, the selected source address
4641 				 * should be in the same subnet as the gateway.
4642 				 * Otherwise, the destination is not reachable.
4643 				 *
4644 				 * If there are no interfaces on the same subnet
4645 				 * as the destination, ipif_select_source gives
4646 				 * first non-deprecated interface which might be
4647 				 * on a different subnet than the gateway.
4648 				 * This is not desirable. Hence pass the dst_ire
4649 				 * source address to ipif_select_source.
4650 				 * It is sure that the destination is reachable
4651 				 * with the dst_ire source address subnet.
4652 				 * So passing dst_ire source address to
4653 				 * ipif_select_source will make sure that the
4654 				 * selected source will be on the same subnet
4655 				 * as dst_ire source address.
4656 				 */
4657 				ipaddr_t saddr =
4658 				    dst_ire->ire_ipif->ipif_src_addr;
4659 				src_ipif = ipif_select_source(dst_ill,
4660 				    saddr, zoneid);
4661 				if (src_ipif != NULL) {
4662 					if (IS_VNI(src_ipif->ipif_ill)) {
4663 						/*
4664 						 * For VNI there is no
4665 						 * interface route
4666 						 */
4667 						src_addr =
4668 						    src_ipif->ipif_src_addr;
4669 					} else {
4670 						ipif_ire =
4671 						    ipif_to_ire(src_ipif);
4672 						if (ipif_ire != NULL) {
4673 							IRE_REFRELE(dst_ire);
4674 							dst_ire = ipif_ire;
4675 						}
4676 						src_addr =
4677 						    dst_ire->ire_src_addr;
4678 					}
4679 					ipif_refrele(src_ipif);
4680 				} else {
4681 					src_addr = dst_ire->ire_src_addr;
4682 				}
4683 			} else {
4684 				src_addr = dst_ire->ire_src_addr;
4685 			}
4686 		}
4687 	}
4688 
4689 	/*
4690 	 * We do ire_route_lookup() here (and not
4691 	 * interface lookup as we assert that
4692 	 * src_addr should only come from an
4693 	 * UP interface for hard binding.
4694 	 */
4695 	ASSERT(src_ire == NULL);
4696 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4697 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4698 	/* src_ire must be a local|loopback */
4699 	if (!IRE_IS_LOCAL(src_ire)) {
4700 		if (ip_debug > 2) {
4701 			pr_addr_dbg("ip_bind_connected: bad connected "
4702 			    "src %s\n", AF_INET, &src_addr);
4703 		}
4704 		error = EADDRNOTAVAIL;
4705 		goto bad_addr;
4706 	}
4707 
4708 	/*
4709 	 * If the source address is a loopback address, the
4710 	 * destination had best be local or multicast.
4711 	 * The transports that can't handle multicast will reject
4712 	 * those addresses.
4713 	 */
4714 	if (src_ire->ire_type == IRE_LOOPBACK &&
4715 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4716 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4717 		error = -1;
4718 		goto bad_addr;
4719 	}
4720 
4721 	/*
4722 	 * Allow setting new policies. For example, disconnects come
4723 	 * down as ipa_t bind. As we would have set conn_policy_cached
4724 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4725 	 * can change after the disconnect.
4726 	 */
4727 	connp->conn_policy_cached = B_FALSE;
4728 
4729 	/*
4730 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4731 	 * can handle their passed-in conn's.
4732 	 */
4733 
4734 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4735 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4736 	connp->conn_lport = lport;
4737 	connp->conn_fport = fport;
4738 	*src_addrp = src_addr;
4739 
4740 	ASSERT(!(ipsec_policy_set && ire_requested));
4741 	if (ire_requested) {
4742 		iulp_t *ulp_info = NULL;
4743 
4744 		/*
4745 		 * Note that sire will not be NULL if this is an off-link
4746 		 * connection and there is not cache for that dest yet.
4747 		 *
4748 		 * XXX Because of an existing bug, if there are multiple
4749 		 * default routes, the IRE returned now may not be the actual
4750 		 * default route used (default routes are chosen in a
4751 		 * round robin fashion).  So if the metrics for different
4752 		 * default routes are different, we may return the wrong
4753 		 * metrics.  This will not be a problem if the existing
4754 		 * bug is fixed.
4755 		 */
4756 		if (sire != NULL) {
4757 			ulp_info = &(sire->ire_uinfo);
4758 		}
4759 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4760 			error = -1;
4761 			goto bad_addr;
4762 		}
4763 	} else if (ipsec_policy_set) {
4764 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4765 			error = -1;
4766 			goto bad_addr;
4767 		}
4768 	}
4769 
4770 	/*
4771 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4772 	 * we'll cache that.  If we don't, we'll inherit global policy.
4773 	 *
4774 	 * We can't insert until the conn reflects the policy. Note that
4775 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4776 	 * connections where we don't have a policy. This is to prevent
4777 	 * global policy lookups in the inbound path.
4778 	 *
4779 	 * If we insert before we set conn_policy_cached,
4780 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4781 	 * because global policy cound be non-empty. We normally call
4782 	 * ipsec_check_policy() for conn_policy_cached connections only if
4783 	 * ipc_in_enforce_policy is set. But in this case,
4784 	 * conn_policy_cached can get set anytime since we made the
4785 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4786 	 * called, which will make the above assumption false.  Thus, we
4787 	 * need to insert after we set conn_policy_cached.
4788 	 */
4789 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4790 		goto bad_addr;
4791 
4792 	if (fanout_insert) {
4793 		/*
4794 		 * The addresses have been verified. Time to insert in
4795 		 * the correct fanout list.
4796 		 */
4797 		error = ipcl_conn_insert(connp, protocol, src_addr,
4798 		    dst_addr, connp->conn_ports);
4799 	}
4800 
4801 	if (error == 0) {
4802 		connp->conn_fully_bound = B_TRUE;
4803 		/*
4804 		 * Our initial checks for MDT have passed; the IRE is not
4805 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4806 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4807 		 * ip_mdinfo_return(), which performs further checks
4808 		 * against them and upon success, returns the MDT info
4809 		 * mblk which we will attach to the bind acknowledgment.
4810 		 */
4811 		if (md_dst_ire != NULL) {
4812 			mblk_t *mdinfo_mp;
4813 
4814 			ASSERT(md_ill != NULL);
4815 			ASSERT(md_ill->ill_mdt_capab != NULL);
4816 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4817 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4818 				linkb(mp, mdinfo_mp);
4819 		}
4820 	}
4821 bad_addr:
4822 	if (ipsec_policy_set) {
4823 		ASSERT(policy_mp == mp->b_cont);
4824 		ASSERT(policy_mp != NULL);
4825 		freeb(policy_mp);
4826 		/*
4827 		 * As of now assume that nothing else accompanies
4828 		 * IPSEC_POLICY_SET.
4829 		 */
4830 		mp->b_cont = NULL;
4831 	}
4832 	if (src_ire != NULL)
4833 		IRE_REFRELE(src_ire);
4834 	if (dst_ire != NULL)
4835 		IRE_REFRELE(dst_ire);
4836 	if (sire != NULL)
4837 		IRE_REFRELE(sire);
4838 	if (md_dst_ire != NULL)
4839 		IRE_REFRELE(md_dst_ire);
4840 	return (error);
4841 }
4842 
4843 /*
4844  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4845  * Prefers dst_ire over src_ire.
4846  */
4847 static boolean_t
4848 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4849 {
4850 	mblk_t	*mp1;
4851 	ire_t *ret_ire = NULL;
4852 
4853 	mp1 = mp->b_cont;
4854 	ASSERT(mp1 != NULL);
4855 
4856 	if (ire != NULL) {
4857 		/*
4858 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4859 		 * appended mblk. Its <upper protocol>'s
4860 		 * job to make sure there is room.
4861 		 */
4862 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4863 			return (0);
4864 
4865 		mp1->b_datap->db_type = IRE_DB_TYPE;
4866 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4867 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4868 		ret_ire = (ire_t *)mp1->b_rptr;
4869 		/*
4870 		 * Pass the latest setting of the ip_path_mtu_discovery and
4871 		 * copy the ulp info if any.
4872 		 */
4873 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4874 		    IPH_DF : 0;
4875 		if (ulp_info != NULL) {
4876 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4877 			    sizeof (iulp_t));
4878 		}
4879 		ret_ire->ire_mp = mp1;
4880 	} else {
4881 		/*
4882 		 * No IRE was found. Remove IRE mblk.
4883 		 */
4884 		mp->b_cont = mp1->b_cont;
4885 		freeb(mp1);
4886 	}
4887 
4888 	return (1);
4889 }
4890 
4891 /*
4892  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4893  * the final piece where we don't.  Return a pointer to the first mblk in the
4894  * result, and update the pointer to the next mblk to chew on.  If anything
4895  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4896  * NULL pointer.
4897  */
4898 mblk_t *
4899 ip_carve_mp(mblk_t **mpp, ssize_t len)
4900 {
4901 	mblk_t	*mp0;
4902 	mblk_t	*mp1;
4903 	mblk_t	*mp2;
4904 
4905 	if (!len || !mpp || !(mp0 = *mpp))
4906 		return (NULL);
4907 	/* If we aren't going to consume the first mblk, we need a dup. */
4908 	if (mp0->b_wptr - mp0->b_rptr > len) {
4909 		mp1 = dupb(mp0);
4910 		if (mp1) {
4911 			/* Partition the data between the two mblks. */
4912 			mp1->b_wptr = mp1->b_rptr + len;
4913 			mp0->b_rptr = mp1->b_wptr;
4914 			/*
4915 			 * after adjustments if mblk not consumed is now
4916 			 * unaligned, try to align it. If this fails free
4917 			 * all messages and let upper layer recover.
4918 			 */
4919 			if (!OK_32PTR(mp0->b_rptr)) {
4920 				if (!pullupmsg(mp0, -1)) {
4921 					freemsg(mp0);
4922 					freemsg(mp1);
4923 					*mpp = NULL;
4924 					return (NULL);
4925 				}
4926 			}
4927 		}
4928 		return (mp1);
4929 	}
4930 	/* Eat through as many mblks as we need to get len bytes. */
4931 	len -= mp0->b_wptr - mp0->b_rptr;
4932 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4933 		if (mp2->b_wptr - mp2->b_rptr > len) {
4934 			/*
4935 			 * We won't consume the entire last mblk.  Like
4936 			 * above, dup and partition it.
4937 			 */
4938 			mp1->b_cont = dupb(mp2);
4939 			mp1 = mp1->b_cont;
4940 			if (!mp1) {
4941 				/*
4942 				 * Trouble.  Rather than go to a lot of
4943 				 * trouble to clean up, we free the messages.
4944 				 * This won't be any worse than losing it on
4945 				 * the wire.
4946 				 */
4947 				freemsg(mp0);
4948 				freemsg(mp2);
4949 				*mpp = NULL;
4950 				return (NULL);
4951 			}
4952 			mp1->b_wptr = mp1->b_rptr + len;
4953 			mp2->b_rptr = mp1->b_wptr;
4954 			/*
4955 			 * after adjustments if mblk not consumed is now
4956 			 * unaligned, try to align it. If this fails free
4957 			 * all messages and let upper layer recover.
4958 			 */
4959 			if (!OK_32PTR(mp2->b_rptr)) {
4960 				if (!pullupmsg(mp2, -1)) {
4961 					freemsg(mp0);
4962 					freemsg(mp2);
4963 					*mpp = NULL;
4964 					return (NULL);
4965 				}
4966 			}
4967 			*mpp = mp2;
4968 			return (mp0);
4969 		}
4970 		/* Decrement len by the amount we just got. */
4971 		len -= mp2->b_wptr - mp2->b_rptr;
4972 	}
4973 	/*
4974 	 * len should be reduced to zero now.  If not our caller has
4975 	 * screwed up.
4976 	 */
4977 	if (len) {
4978 		/* Shouldn't happen! */
4979 		freemsg(mp0);
4980 		*mpp = NULL;
4981 		return (NULL);
4982 	}
4983 	/*
4984 	 * We consumed up to exactly the end of an mblk.  Detach the part
4985 	 * we are returning from the rest of the chain.
4986 	 */
4987 	mp1->b_cont = NULL;
4988 	*mpp = mp2;
4989 	return (mp0);
4990 }
4991 
4992 /* The ill stream is being unplumbed. Called from ip_close */
4993 int
4994 ip_modclose(ill_t *ill)
4995 {
4996 
4997 	boolean_t success;
4998 	ipsq_t	*ipsq;
4999 	ipif_t	*ipif;
5000 	queue_t	*q = ill->ill_rq;
5001 
5002 	/*
5003 	 * Forcibly enter the ipsq after some delay. This is to take
5004 	 * care of the case when some ioctl does not complete because
5005 	 * we sent a control message to the driver and it did not
5006 	 * send us a reply. We want to be able to at least unplumb
5007 	 * and replumb rather than force the user to reboot the system.
5008 	 */
5009 	success = ipsq_enter(ill, B_FALSE);
5010 
5011 	/*
5012 	 * Open/close/push/pop is guaranteed to be single threaded
5013 	 * per stream by STREAMS. FS guarantees that all references
5014 	 * from top are gone before close is called. So there can't
5015 	 * be another close thread that has set CONDEMNED on this ill.
5016 	 * and cause ipsq_enter to return failure.
5017 	 */
5018 	ASSERT(success);
5019 	ipsq = ill->ill_phyint->phyint_ipsq;
5020 
5021 	/*
5022 	 * Mark it condemned. No new reference will be made to this ill.
5023 	 * Lookup functions will return an error. Threads that try to
5024 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5025 	 * that the refcnt will drop down to zero.
5026 	 */
5027 	mutex_enter(&ill->ill_lock);
5028 	ill->ill_state_flags |= ILL_CONDEMNED;
5029 	for (ipif = ill->ill_ipif; ipif != NULL;
5030 	    ipif = ipif->ipif_next) {
5031 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5032 	}
5033 	/*
5034 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5035 	 * returns  error if ILL_CONDEMNED is set
5036 	 */
5037 	cv_broadcast(&ill->ill_cv);
5038 	mutex_exit(&ill->ill_lock);
5039 
5040 	/*
5041 	 * Shut down fragmentation reassembly.
5042 	 * ill_frag_timer won't start a timer again.
5043 	 * Now cancel any existing timer
5044 	 */
5045 	(void) untimeout(ill->ill_frag_timer_id);
5046 	(void) ill_frag_timeout(ill, 0);
5047 
5048 	/*
5049 	 * If MOVE was in progress, clear the
5050 	 * move_in_progress fields also.
5051 	 */
5052 	if (ill->ill_move_in_progress) {
5053 		ILL_CLEAR_MOVE(ill);
5054 	}
5055 
5056 	/*
5057 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5058 	 * this ill. Then wait for the refcnts to drop to zero.
5059 	 * ill_is_quiescent checks whether the ill is really quiescent.
5060 	 * Then make sure that threads that are waiting to enter the
5061 	 * ipsq have seen the error returned by ipsq_enter and have
5062 	 * gone away. Then we call ill_delete_tail which does the
5063 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5064 	 */
5065 	ill_delete(ill);
5066 	mutex_enter(&ill->ill_lock);
5067 	while (!ill_is_quiescent(ill))
5068 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5069 	while (ill->ill_waiters)
5070 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5071 
5072 	mutex_exit(&ill->ill_lock);
5073 
5074 	/* qprocsoff is called in ill_delete_tail */
5075 	ill_delete_tail(ill);
5076 
5077 	/*
5078 	 * Walk through all upper (conn) streams and qenable
5079 	 * those that have queued data.
5080 	 * close synchronization needs this to
5081 	 * be done to ensure that all upper layers blocked
5082 	 * due to flow control to the closing device
5083 	 * get unblocked.
5084 	 */
5085 	ip1dbg(("ip_wsrv: walking\n"));
5086 	conn_walk_drain();
5087 
5088 	mutex_enter(&ip_mi_lock);
5089 	mi_close_unlink(&ip_g_head, (IDP)ill);
5090 	mutex_exit(&ip_mi_lock);
5091 
5092 	/*
5093 	 * credp could be null if the open didn't succeed and ip_modopen
5094 	 * itself calls ip_close.
5095 	 */
5096 	if (ill->ill_credp != NULL)
5097 		crfree(ill->ill_credp);
5098 
5099 	mi_close_free((IDP)ill);
5100 	q->q_ptr = WR(q)->q_ptr = NULL;
5101 
5102 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5103 
5104 	return (0);
5105 }
5106 
5107 /*
5108  * This is called as part of close() for both IP and UDP
5109  * in order to quiesce the conn.
5110  */
5111 void
5112 ip_quiesce_conn(conn_t *connp)
5113 {
5114 	boolean_t	drain_cleanup_reqd = B_FALSE;
5115 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5116 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5117 
5118 	ASSERT(!IPCL_IS_TCP(connp));
5119 
5120 	/*
5121 	 * Mark the conn as closing, and this conn must not be
5122 	 * inserted in future into any list. Eg. conn_drain_insert(),
5123 	 * won't insert this conn into the conn_drain_list.
5124 	 * Similarly ill_pending_mp_add() will not add any mp to
5125 	 * the pending mp list, after this conn has started closing.
5126 	 *
5127 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5128 	 * cannot get set henceforth.
5129 	 */
5130 	mutex_enter(&connp->conn_lock);
5131 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5132 	connp->conn_state_flags |= CONN_CLOSING;
5133 	if (connp->conn_idl != NULL)
5134 		drain_cleanup_reqd = B_TRUE;
5135 	if (connp->conn_oper_pending_ill != NULL)
5136 		conn_ioctl_cleanup_reqd = B_TRUE;
5137 	if (connp->conn_ilg_inuse != 0)
5138 		ilg_cleanup_reqd = B_TRUE;
5139 	mutex_exit(&connp->conn_lock);
5140 
5141 	if (IPCL_IS_UDP(connp))
5142 		udp_quiesce_conn(connp);
5143 
5144 	if (conn_ioctl_cleanup_reqd)
5145 		conn_ioctl_cleanup(connp);
5146 
5147 	if (is_system_labeled() && connp->conn_anon_port) {
5148 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5149 		    connp->conn_mlp_type, connp->conn_ulp,
5150 		    ntohs(connp->conn_lport), B_FALSE);
5151 		connp->conn_anon_port = 0;
5152 	}
5153 	connp->conn_mlp_type = mlptSingle;
5154 
5155 	/*
5156 	 * Remove this conn from any fanout list it is on.
5157 	 * and then wait for any threads currently operating
5158 	 * on this endpoint to finish
5159 	 */
5160 	ipcl_hash_remove(connp);
5161 
5162 	/*
5163 	 * Remove this conn from the drain list, and do
5164 	 * any other cleanup that may be required.
5165 	 * (Only non-tcp streams may have a non-null conn_idl.
5166 	 * TCP streams are never flow controlled, and
5167 	 * conn_idl will be null)
5168 	 */
5169 	if (drain_cleanup_reqd)
5170 		conn_drain_tail(connp, B_TRUE);
5171 
5172 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5173 		(void) ip_mrouter_done(NULL);
5174 
5175 	if (ilg_cleanup_reqd)
5176 		ilg_delete_all(connp);
5177 
5178 	conn_delete_ire(connp, NULL);
5179 
5180 	/*
5181 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5182 	 * callers from write side can't be there now because close
5183 	 * is in progress. The only other caller is ipcl_walk
5184 	 * which checks for the condemned flag.
5185 	 */
5186 	mutex_enter(&connp->conn_lock);
5187 	connp->conn_state_flags |= CONN_CONDEMNED;
5188 	while (connp->conn_ref != 1)
5189 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5190 	connp->conn_state_flags |= CONN_QUIESCED;
5191 	mutex_exit(&connp->conn_lock);
5192 }
5193 
5194 /* ARGSUSED */
5195 int
5196 ip_close(queue_t *q, int flags)
5197 {
5198 	conn_t		*connp;
5199 
5200 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5201 
5202 	/*
5203 	 * Call the appropriate delete routine depending on whether this is
5204 	 * a module or device.
5205 	 */
5206 	if (WR(q)->q_next != NULL) {
5207 		/* This is a module close */
5208 		return (ip_modclose((ill_t *)q->q_ptr));
5209 	}
5210 
5211 	connp = q->q_ptr;
5212 	ip_quiesce_conn(connp);
5213 
5214 	qprocsoff(q);
5215 
5216 	/*
5217 	 * Now we are truly single threaded on this stream, and can
5218 	 * delete the things hanging off the connp, and finally the connp.
5219 	 * We removed this connp from the fanout list, it cannot be
5220 	 * accessed thru the fanouts, and we already waited for the
5221 	 * conn_ref to drop to 0. We are already in close, so
5222 	 * there cannot be any other thread from the top. qprocsoff
5223 	 * has completed, and service has completed or won't run in
5224 	 * future.
5225 	 */
5226 	ASSERT(connp->conn_ref == 1);
5227 
5228 	/*
5229 	 * A conn which was previously marked as IPCL_UDP cannot
5230 	 * retain the flag because it would have been cleared by
5231 	 * udp_close().
5232 	 */
5233 	ASSERT(!IPCL_IS_UDP(connp));
5234 
5235 	if (connp->conn_latch != NULL) {
5236 		IPLATCH_REFRELE(connp->conn_latch);
5237 		connp->conn_latch = NULL;
5238 	}
5239 	if (connp->conn_policy != NULL) {
5240 		IPPH_REFRELE(connp->conn_policy);
5241 		connp->conn_policy = NULL;
5242 	}
5243 	if (connp->conn_ipsec_opt_mp != NULL) {
5244 		freemsg(connp->conn_ipsec_opt_mp);
5245 		connp->conn_ipsec_opt_mp = NULL;
5246 	}
5247 
5248 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5249 
5250 	connp->conn_ref--;
5251 	ipcl_conn_destroy(connp);
5252 
5253 	q->q_ptr = WR(q)->q_ptr = NULL;
5254 	return (0);
5255 }
5256 
5257 int
5258 ip_snmpmod_close(queue_t *q)
5259 {
5260 	conn_t *connp = Q_TO_CONN(q);
5261 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5262 
5263 	qprocsoff(q);
5264 
5265 	if (connp->conn_flags & IPCL_UDPMOD)
5266 		udp_close_free(connp);
5267 
5268 	if (connp->conn_cred != NULL) {
5269 		crfree(connp->conn_cred);
5270 		connp->conn_cred = NULL;
5271 	}
5272 	CONN_DEC_REF(connp);
5273 	q->q_ptr = WR(q)->q_ptr = NULL;
5274 	return (0);
5275 }
5276 
5277 /*
5278  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5279  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5280  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5281  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5282  * queues as we never enqueue messages there and we don't handle any ioctls.
5283  * Everything else is freed.
5284  */
5285 void
5286 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5287 {
5288 	conn_t	*connp = q->q_ptr;
5289 	pfi_t	setfn;
5290 	pfi_t	getfn;
5291 
5292 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5293 
5294 	switch (DB_TYPE(mp)) {
5295 	case M_PROTO:
5296 	case M_PCPROTO:
5297 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5298 		    ((((union T_primitives *)mp->b_rptr)->type ==
5299 			T_SVR4_OPTMGMT_REQ) ||
5300 		    (((union T_primitives *)mp->b_rptr)->type ==
5301 			T_OPTMGMT_REQ))) {
5302 			/*
5303 			 * This is the only TPI primitive supported. Its
5304 			 * handling does not require tcp_t, but it does require
5305 			 * conn_t to check permissions.
5306 			 */
5307 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5308 
5309 			if (connp->conn_flags & IPCL_TCPMOD) {
5310 				setfn = tcp_snmp_set;
5311 				getfn = tcp_snmp_get;
5312 			} else {
5313 				setfn = udp_snmp_set;
5314 				getfn = udp_snmp_get;
5315 			}
5316 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5317 				freemsg(mp);
5318 				return;
5319 			}
5320 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5321 		    != NULL)
5322 			qreply(q, mp);
5323 		break;
5324 	case M_FLUSH:
5325 	case M_IOCTL:
5326 		putnext(q, mp);
5327 		break;
5328 	default:
5329 		freemsg(mp);
5330 		break;
5331 	}
5332 }
5333 
5334 /* Return the IP checksum for the IP header at "iph". */
5335 uint16_t
5336 ip_csum_hdr(ipha_t *ipha)
5337 {
5338 	uint16_t	*uph;
5339 	uint32_t	sum;
5340 	int		opt_len;
5341 
5342 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5343 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5344 	uph = (uint16_t *)ipha;
5345 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5346 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5347 	if (opt_len > 0) {
5348 		do {
5349 			sum += uph[10];
5350 			sum += uph[11];
5351 			uph += 2;
5352 		} while (--opt_len);
5353 	}
5354 	sum = (sum & 0xFFFF) + (sum >> 16);
5355 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5356 	if (sum == 0xffff)
5357 		sum = 0;
5358 	return ((uint16_t)sum);
5359 }
5360 
5361 void
5362 ip_ddi_destroy(void)
5363 {
5364 	tnet_fini();
5365 	tcp_ddi_destroy();
5366 	sctp_ddi_destroy();
5367 	ipsec_loader_destroy();
5368 	ipsec_policy_destroy();
5369 	ipsec_kstat_destroy();
5370 	nd_free(&ip_g_nd);
5371 	mutex_destroy(&igmp_timer_lock);
5372 	mutex_destroy(&mld_timer_lock);
5373 	mutex_destroy(&igmp_slowtimeout_lock);
5374 	mutex_destroy(&mld_slowtimeout_lock);
5375 	mutex_destroy(&ip_mi_lock);
5376 	mutex_destroy(&rts_clients.connf_lock);
5377 	ip_ire_fini();
5378 	ip6_asp_free();
5379 	conn_drain_fini();
5380 	ipcl_destroy();
5381 	inet_minor_destroy(ip_minor_arena);
5382 	icmp_kstat_fini();
5383 	ip_kstat_fini();
5384 	rw_destroy(&ipsec_capab_ills_lock);
5385 	rw_destroy(&ill_g_usesrc_lock);
5386 	ip_drop_unregister(&ip_dropper);
5387 }
5388 
5389 
5390 void
5391 ip_ddi_init(void)
5392 {
5393 	TCP6_MAJ = ddi_name_to_major(TCP6);
5394 	TCP_MAJ	= ddi_name_to_major(TCP);
5395 	SCTP_MAJ = ddi_name_to_major(SCTP);
5396 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5397 
5398 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5399 
5400 	/* IP's IPsec code calls the packet dropper */
5401 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5402 
5403 	if (!ip_g_nd) {
5404 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5405 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5406 			nd_free(&ip_g_nd);
5407 		}
5408 	}
5409 
5410 	ipsec_loader_init();
5411 	ipsec_policy_init();
5412 	ipsec_kstat_init();
5413 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5414 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5415 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5416 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5417 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5418 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5419 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5420 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5421 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5422 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5423 
5424 	/*
5425 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5426 	 * initial devices: ip, ip6, tcp, tcp6.
5427 	 */
5428 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5429 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5430 		cmn_err(CE_PANIC,
5431 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5432 	}
5433 
5434 	ipcl_init();
5435 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5436 	ip_ire_init();
5437 	ip6_asp_init();
5438 	ipif_init();
5439 	conn_drain_init();
5440 	tcp_ddi_init();
5441 	sctp_ddi_init();
5442 
5443 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5444 
5445 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5446 		"net", KSTAT_TYPE_NAMED,
5447 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5448 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5449 		ip_kstat->ks_data = &ip_statistics;
5450 		kstat_install(ip_kstat);
5451 	}
5452 	ip_kstat_init();
5453 	ip6_kstat_init();
5454 	icmp_kstat_init();
5455 	ipsec_loader_start();
5456 	tnet_init();
5457 }
5458 
5459 /*
5460  * Allocate and initialize a DLPI template of the specified length.  (May be
5461  * called as writer.)
5462  */
5463 mblk_t *
5464 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5465 {
5466 	mblk_t	*mp;
5467 
5468 	mp = allocb(len, BPRI_MED);
5469 	if (!mp)
5470 		return (NULL);
5471 
5472 	/*
5473 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5474 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5475 	 * that other DLPI are M_PROTO.
5476 	 */
5477 	if (prim == DL_INFO_REQ) {
5478 		mp->b_datap->db_type = M_PCPROTO;
5479 	} else {
5480 		mp->b_datap->db_type = M_PROTO;
5481 	}
5482 
5483 	mp->b_wptr = mp->b_rptr + len;
5484 	bzero(mp->b_rptr, len);
5485 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5486 	return (mp);
5487 }
5488 
5489 const char *
5490 dlpi_prim_str(int prim)
5491 {
5492 	switch (prim) {
5493 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5494 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5495 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5496 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5497 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5498 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5499 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5500 	case DL_OK_ACK:		return ("DL_OK_ACK");
5501 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5502 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5503 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5504 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5505 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5506 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5507 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5508 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5509 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5510 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5511 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5512 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5513 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5514 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5515 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5516 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5517 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5518 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5519 	default:		return ("<unknown primitive>");
5520 	}
5521 }
5522 
5523 const char *
5524 dlpi_err_str(int err)
5525 {
5526 	switch (err) {
5527 	case DL_ACCESS:		return ("DL_ACCESS");
5528 	case DL_BADADDR:	return ("DL_BADADDR");
5529 	case DL_BADCORR:	return ("DL_BADCORR");
5530 	case DL_BADDATA:	return ("DL_BADDATA");
5531 	case DL_BADPPA:		return ("DL_BADPPA");
5532 	case DL_BADPRIM:	return ("DL_BADPRIM");
5533 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5534 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5535 	case DL_BADSAP:		return ("DL_BADSAP");
5536 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5537 	case DL_BOUND:		return ("DL_BOUND");
5538 	case DL_INITFAILED:	return ("DL_INITFAILED");
5539 	case DL_NOADDR:		return ("DL_NOADDR");
5540 	case DL_NOTINIT:	return ("DL_NOTINIT");
5541 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5542 	case DL_SYSERR:		return ("DL_SYSERR");
5543 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5544 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5545 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5546 	case DL_TOOMANY:	return ("DL_TOOMANY");
5547 	case DL_NOTENAB:	return ("DL_NOTENAB");
5548 	case DL_BUSY:		return ("DL_BUSY");
5549 	case DL_NOAUTO:		return ("DL_NOAUTO");
5550 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5551 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5552 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5553 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5554 	case DL_PENDING:	return ("DL_PENDING");
5555 	default:		return ("<unknown error>");
5556 	}
5557 }
5558 
5559 /*
5560  * Debug formatting routine.  Returns a character string representation of the
5561  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5562  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5563  */
5564 char *
5565 ip_dot_addr(ipaddr_t addr, char *buf)
5566 {
5567 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5568 }
5569 
5570 /*
5571  * Debug formatting routine.  Returns a character string representation of the
5572  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5573  * as a pointer.  The "xxx" parts including left zero padding so the final
5574  * string will fit easily in tables.  It would be nice to take a padding
5575  * length argument instead.
5576  */
5577 static char *
5578 ip_dot_saddr(uchar_t *addr, char *buf)
5579 {
5580 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5581 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5582 	return (buf);
5583 }
5584 
5585 /*
5586  * Send an ICMP error after patching up the packet appropriately.  Returns
5587  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5588  */
5589 static boolean_t
5590 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5591     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5592 {
5593 	ipha_t *ipha;
5594 	mblk_t *first_mp;
5595 	boolean_t secure;
5596 	unsigned char db_type;
5597 
5598 	first_mp = mp;
5599 	if (mctl_present) {
5600 		mp = mp->b_cont;
5601 		secure = ipsec_in_is_secure(first_mp);
5602 		ASSERT(mp != NULL);
5603 	} else {
5604 		/*
5605 		 * If this is an ICMP error being reported - which goes
5606 		 * up as M_CTLs, we need to convert them to M_DATA till
5607 		 * we finish checking with global policy because
5608 		 * ipsec_check_global_policy() assumes M_DATA as clear
5609 		 * and M_CTL as secure.
5610 		 */
5611 		db_type = DB_TYPE(mp);
5612 		DB_TYPE(mp) = M_DATA;
5613 		secure = B_FALSE;
5614 	}
5615 	/*
5616 	 * We are generating an icmp error for some inbound packet.
5617 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5618 	 * Before we generate an error, check with global policy
5619 	 * to see whether this is allowed to enter the system. As
5620 	 * there is no "conn", we are checking with global policy.
5621 	 */
5622 	ipha = (ipha_t *)mp->b_rptr;
5623 	if (secure || ipsec_inbound_v4_policy_present) {
5624 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5625 		    ipha, NULL, mctl_present);
5626 		if (first_mp == NULL)
5627 			return (B_FALSE);
5628 	}
5629 
5630 	if (!mctl_present)
5631 		DB_TYPE(mp) = db_type;
5632 
5633 	if (flags & IP_FF_SEND_ICMP) {
5634 		if (flags & IP_FF_HDR_COMPLETE) {
5635 			if (ip_hdr_complete(ipha, zoneid)) {
5636 				freemsg(first_mp);
5637 				return (B_TRUE);
5638 			}
5639 		}
5640 		if (flags & IP_FF_CKSUM) {
5641 			/*
5642 			 * Have to correct checksum since
5643 			 * the packet might have been
5644 			 * fragmented and the reassembly code in ip_rput
5645 			 * does not restore the IP checksum.
5646 			 */
5647 			ipha->ipha_hdr_checksum = 0;
5648 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5649 		}
5650 		switch (icmp_type) {
5651 		case ICMP_DEST_UNREACHABLE:
5652 			icmp_unreachable(WR(q), first_mp, icmp_code);
5653 			break;
5654 		default:
5655 			freemsg(first_mp);
5656 			break;
5657 		}
5658 	} else {
5659 		freemsg(first_mp);
5660 		return (B_FALSE);
5661 	}
5662 
5663 	return (B_TRUE);
5664 }
5665 
5666 /*
5667  * Used to send an ICMP error message when a packet is received for
5668  * a protocol that is not supported. The mblk passed as argument
5669  * is consumed by this function.
5670  */
5671 void
5672 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5673 {
5674 	mblk_t *mp;
5675 	ipha_t *ipha;
5676 	ill_t *ill;
5677 	ipsec_in_t *ii;
5678 
5679 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5680 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5681 
5682 	mp = ipsec_mp->b_cont;
5683 	ipsec_mp->b_cont = NULL;
5684 	ipha = (ipha_t *)mp->b_rptr;
5685 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5686 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5687 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5688 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5689 		}
5690 	} else {
5691 		/* Get ill from index in ipsec_in_t. */
5692 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5693 		    B_TRUE, NULL, NULL, NULL, NULL);
5694 		if (ill != NULL) {
5695 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5696 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5697 			    0, B_FALSE, zoneid)) {
5698 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5699 			}
5700 
5701 			ill_refrele(ill);
5702 		} else { /* re-link for the freemsg() below. */
5703 			ipsec_mp->b_cont = mp;
5704 		}
5705 	}
5706 
5707 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5708 	freemsg(ipsec_mp);
5709 }
5710 
5711 /*
5712  * See if the inbound datagram has had IPsec processing applied to it.
5713  */
5714 boolean_t
5715 ipsec_in_is_secure(mblk_t *ipsec_mp)
5716 {
5717 	ipsec_in_t *ii;
5718 
5719 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5720 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5721 
5722 	if (ii->ipsec_in_loopback) {
5723 		return (ii->ipsec_in_secure);
5724 	} else {
5725 		return (ii->ipsec_in_ah_sa != NULL ||
5726 		    ii->ipsec_in_esp_sa != NULL ||
5727 		    ii->ipsec_in_decaps);
5728 	}
5729 }
5730 
5731 /*
5732  * Handle protocols with which IP is less intimate.  There
5733  * can be more than one stream bound to a particular
5734  * protocol.  When this is the case, normally each one gets a copy
5735  * of any incoming packets.
5736  *
5737  * IPSEC NOTE :
5738  *
5739  * Don't allow a secure packet going up a non-secure connection.
5740  * We don't allow this because
5741  *
5742  * 1) Reply might go out in clear which will be dropped at
5743  *    the sending side.
5744  * 2) If the reply goes out in clear it will give the
5745  *    adversary enough information for getting the key in
5746  *    most of the cases.
5747  *
5748  * Moreover getting a secure packet when we expect clear
5749  * implies that SA's were added without checking for
5750  * policy on both ends. This should not happen once ISAKMP
5751  * is used to negotiate SAs as SAs will be added only after
5752  * verifying the policy.
5753  *
5754  * NOTE : If the packet was tunneled and not multicast we only send
5755  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5756  * back to delivering packets to AF_INET6 raw sockets.
5757  *
5758  * IPQoS Notes:
5759  * Once we have determined the client, invoke IPPF processing.
5760  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5761  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5762  * ip_policy will be false.
5763  *
5764  * Zones notes:
5765  * Currently only applications in the global zone can create raw sockets for
5766  * protocols other than ICMP. So unlike the broadcast / multicast case of
5767  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5768  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5769  */
5770 static void
5771 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5772     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5773     zoneid_t zoneid)
5774 {
5775 	queue_t	*rq;
5776 	mblk_t	*mp1, *first_mp1;
5777 	uint_t	protocol = ipha->ipha_protocol;
5778 	ipaddr_t dst;
5779 	boolean_t one_only;
5780 	mblk_t *first_mp = mp;
5781 	boolean_t secure;
5782 	uint32_t ill_index;
5783 	conn_t	*connp, *first_connp, *next_connp;
5784 	connf_t	*connfp;
5785 	boolean_t shared_addr;
5786 
5787 	if (mctl_present) {
5788 		mp = first_mp->b_cont;
5789 		secure = ipsec_in_is_secure(first_mp);
5790 		ASSERT(mp != NULL);
5791 	} else {
5792 		secure = B_FALSE;
5793 	}
5794 	dst = ipha->ipha_dst;
5795 	/*
5796 	 * If the packet was tunneled and not multicast we only send to it
5797 	 * the first match.
5798 	 */
5799 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5800 	    !CLASSD(dst));
5801 
5802 	shared_addr = (zoneid == ALL_ZONES);
5803 	if (shared_addr) {
5804 		/*
5805 		 * We don't allow multilevel ports for raw IP, so no need to
5806 		 * check for that here.
5807 		 */
5808 		zoneid = tsol_packet_to_zoneid(mp);
5809 	}
5810 
5811 	connfp = &ipcl_proto_fanout[protocol];
5812 	mutex_enter(&connfp->connf_lock);
5813 	connp = connfp->connf_head;
5814 	for (connp = connfp->connf_head; connp != NULL;
5815 		connp = connp->conn_next) {
5816 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
5817 		    zoneid) &&
5818 		    (!is_system_labeled() ||
5819 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
5820 		    connp)))
5821 			break;
5822 	}
5823 
5824 	if (connp == NULL || connp->conn_upq == NULL) {
5825 		/*
5826 		 * No one bound to these addresses.  Is
5827 		 * there a client that wants all
5828 		 * unclaimed datagrams?
5829 		 */
5830 		mutex_exit(&connfp->connf_lock);
5831 		/*
5832 		 * Check for IPPROTO_ENCAP...
5833 		 */
5834 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5835 			/*
5836 			 * XXX If an IPsec mblk is here on a multicast
5837 			 * tunnel (using ip_mroute stuff), what should
5838 			 * I do?
5839 			 *
5840 			 * For now, just free the IPsec mblk before
5841 			 * passing it up to the multicast routing
5842 			 * stuff.
5843 			 *
5844 			 * BTW,  If I match a configured IP-in-IP
5845 			 * tunnel, ip_mroute_decap will never be
5846 			 * called.
5847 			 */
5848 			if (mp != first_mp)
5849 				freeb(first_mp);
5850 			ip_mroute_decap(q, mp);
5851 		} else {
5852 			/*
5853 			 * Otherwise send an ICMP protocol unreachable.
5854 			 */
5855 			if (ip_fanout_send_icmp(q, first_mp, flags,
5856 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5857 			    mctl_present, zoneid)) {
5858 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5859 			}
5860 		}
5861 		return;
5862 	}
5863 	CONN_INC_REF(connp);
5864 	first_connp = connp;
5865 
5866 	/*
5867 	 * Only send message to one tunnel driver by immediately
5868 	 * terminating the loop.
5869 	 */
5870 	connp = one_only ? NULL : connp->conn_next;
5871 
5872 	for (;;) {
5873 		while (connp != NULL) {
5874 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5875 			    flags, zoneid) &&
5876 			    (!is_system_labeled() ||
5877 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
5878 			    shared_addr, connp)))
5879 				break;
5880 			connp = connp->conn_next;
5881 		}
5882 
5883 		/*
5884 		 * Copy the packet.
5885 		 */
5886 		if (connp == NULL || connp->conn_upq == NULL ||
5887 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5888 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5889 			/*
5890 			 * No more interested clients or memory
5891 			 * allocation failed
5892 			 */
5893 			connp = first_connp;
5894 			break;
5895 		}
5896 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5897 		CONN_INC_REF(connp);
5898 		mutex_exit(&connfp->connf_lock);
5899 		rq = connp->conn_rq;
5900 		if (!canputnext(rq)) {
5901 			if (flags & IP_FF_RAWIP) {
5902 				BUMP_MIB(&ip_mib, rawipInOverflows);
5903 			} else {
5904 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5905 			}
5906 
5907 			freemsg(first_mp1);
5908 		} else {
5909 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5910 				first_mp1 = ipsec_check_inbound_policy
5911 				    (first_mp1, connp, ipha, NULL,
5912 				    mctl_present);
5913 			}
5914 			if (first_mp1 != NULL) {
5915 				/*
5916 				 * ip_fanout_proto also gets called from
5917 				 * icmp_inbound_error_fanout, in which case
5918 				 * the msg type is M_CTL.  Don't add info
5919 				 * in this case for the time being. In future
5920 				 * when there is a need for knowing the
5921 				 * inbound iface index for ICMP error msgs,
5922 				 * then this can be changed.
5923 				 */
5924 				if ((connp->conn_recvif != 0) &&
5925 				    (mp->b_datap->db_type != M_CTL)) {
5926 					/*
5927 					 * the actual data will be
5928 					 * contained in b_cont upon
5929 					 * successful return of the
5930 					 * following call else
5931 					 * original mblk is returned
5932 					 */
5933 					ASSERT(recv_ill != NULL);
5934 					mp1 = ip_add_info(mp1, recv_ill,
5935 						IPF_RECVIF);
5936 				}
5937 				BUMP_MIB(&ip_mib, ipInDelivers);
5938 				if (mctl_present)
5939 					freeb(first_mp1);
5940 				putnext(rq, mp1);
5941 			}
5942 		}
5943 		mutex_enter(&connfp->connf_lock);
5944 		/* Follow the next pointer before releasing the conn. */
5945 		next_connp = connp->conn_next;
5946 		CONN_DEC_REF(connp);
5947 		connp = next_connp;
5948 	}
5949 
5950 	/* Last one.  Send it upstream. */
5951 	mutex_exit(&connfp->connf_lock);
5952 
5953 	/*
5954 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5955 	 * will be set to false.
5956 	 */
5957 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5958 		ill_index = ill->ill_phyint->phyint_ifindex;
5959 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5960 		if (mp == NULL) {
5961 			CONN_DEC_REF(connp);
5962 			if (mctl_present) {
5963 				freeb(first_mp);
5964 			}
5965 			return;
5966 		}
5967 	}
5968 
5969 	rq = connp->conn_rq;
5970 	if (!canputnext(rq)) {
5971 		if (flags & IP_FF_RAWIP) {
5972 			BUMP_MIB(&ip_mib, rawipInOverflows);
5973 		} else {
5974 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5975 		}
5976 
5977 		freemsg(first_mp);
5978 	} else {
5979 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5980 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5981 			    ipha, NULL, mctl_present);
5982 		}
5983 		if (first_mp != NULL) {
5984 			/*
5985 			 * ip_fanout_proto also gets called
5986 			 * from icmp_inbound_error_fanout, in
5987 			 * which case the msg type is M_CTL.
5988 			 * Don't add info in this case for time
5989 			 * being. In future when there is a
5990 			 * need for knowing the inbound iface
5991 			 * index for ICMP error msgs, then this
5992 			 * can be changed
5993 			 */
5994 			if ((connp->conn_recvif != 0) &&
5995 			    (mp->b_datap->db_type != M_CTL)) {
5996 				/*
5997 				 * the actual data will be contained in
5998 				 * b_cont upon successful return
5999 				 * of the following call else original
6000 				 * mblk is returned
6001 				 */
6002 				ASSERT(recv_ill != NULL);
6003 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6004 			}
6005 			BUMP_MIB(&ip_mib, ipInDelivers);
6006 			putnext(rq, mp);
6007 			if (mctl_present)
6008 				freeb(first_mp);
6009 		}
6010 	}
6011 	CONN_DEC_REF(connp);
6012 }
6013 
6014 /*
6015  * Fanout for TCP packets
6016  * The caller puts <fport, lport> in the ports parameter.
6017  *
6018  * IPQoS Notes
6019  * Before sending it to the client, invoke IPPF processing.
6020  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6021  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6022  * ip_policy is false.
6023  */
6024 static void
6025 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6026     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6027 {
6028 	mblk_t  *first_mp;
6029 	boolean_t secure;
6030 	uint32_t ill_index;
6031 	int	ip_hdr_len;
6032 	tcph_t	*tcph;
6033 	boolean_t syn_present = B_FALSE;
6034 	conn_t	*connp;
6035 
6036 	first_mp = mp;
6037 	if (mctl_present) {
6038 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6039 		mp = first_mp->b_cont;
6040 		secure = ipsec_in_is_secure(first_mp);
6041 		ASSERT(mp != NULL);
6042 	} else {
6043 		secure = B_FALSE;
6044 	}
6045 
6046 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6047 
6048 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6049 	    NULL) {
6050 		/*
6051 		 * No connected connection or listener. Send a
6052 		 * TH_RST via tcp_xmit_listeners_reset.
6053 		 */
6054 
6055 		/* Initiate IPPf processing, if needed. */
6056 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6057 			uint32_t ill_index;
6058 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6059 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6060 			if (first_mp == NULL)
6061 				return;
6062 		}
6063 		BUMP_MIB(&ip_mib, ipInDelivers);
6064 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6065 		    zoneid));
6066 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6067 		return;
6068 	}
6069 
6070 	/*
6071 	 * Allocate the SYN for the TCP connection here itself
6072 	 */
6073 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6074 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6075 		if (IPCL_IS_TCP(connp)) {
6076 			squeue_t *sqp;
6077 
6078 			/*
6079 			 * For fused tcp loopback, assign the eager's
6080 			 * squeue to be that of the active connect's.
6081 			 * Note that we don't check for IP_FF_LOOPBACK
6082 			 * here since this routine gets called only
6083 			 * for loopback (unlike the IPv6 counterpart).
6084 			 */
6085 			ASSERT(Q_TO_CONN(q) != NULL);
6086 			if (do_tcp_fusion &&
6087 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6088 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6089 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6090 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6091 				sqp = Q_TO_CONN(q)->conn_sqp;
6092 			} else {
6093 				sqp = IP_SQUEUE_GET(lbolt);
6094 			}
6095 
6096 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6097 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6098 			syn_present = B_TRUE;
6099 		}
6100 	}
6101 
6102 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6103 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6104 		if ((flags & TH_RST) || (flags & TH_URG)) {
6105 			CONN_DEC_REF(connp);
6106 			freemsg(first_mp);
6107 			return;
6108 		}
6109 		if (flags & TH_ACK) {
6110 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6111 			CONN_DEC_REF(connp);
6112 			return;
6113 		}
6114 
6115 		CONN_DEC_REF(connp);
6116 		freemsg(first_mp);
6117 		return;
6118 	}
6119 
6120 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6121 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6122 		    NULL, mctl_present);
6123 		if (first_mp == NULL) {
6124 			CONN_DEC_REF(connp);
6125 			return;
6126 		}
6127 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6128 			ASSERT(syn_present);
6129 			if (mctl_present) {
6130 				ASSERT(first_mp != mp);
6131 				first_mp->b_datap->db_struioflag |=
6132 				    STRUIO_POLICY;
6133 			} else {
6134 				ASSERT(first_mp == mp);
6135 				mp->b_datap->db_struioflag &=
6136 				    ~STRUIO_EAGER;
6137 				mp->b_datap->db_struioflag |=
6138 				    STRUIO_POLICY;
6139 			}
6140 		} else {
6141 			/*
6142 			 * Discard first_mp early since we're dealing with a
6143 			 * fully-connected conn_t and tcp doesn't do policy in
6144 			 * this case.
6145 			 */
6146 			if (mctl_present) {
6147 				freeb(first_mp);
6148 				mctl_present = B_FALSE;
6149 			}
6150 			first_mp = mp;
6151 		}
6152 	}
6153 
6154 	/*
6155 	 * Initiate policy processing here if needed. If we get here from
6156 	 * icmp_inbound_error_fanout, ip_policy is false.
6157 	 */
6158 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6159 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6160 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6161 		if (mp == NULL) {
6162 			CONN_DEC_REF(connp);
6163 			if (mctl_present)
6164 				freeb(first_mp);
6165 			return;
6166 		} else if (mctl_present) {
6167 			ASSERT(first_mp != mp);
6168 			first_mp->b_cont = mp;
6169 		} else {
6170 			first_mp = mp;
6171 		}
6172 	}
6173 
6174 
6175 
6176 	/* Handle IPv6 socket options. */
6177 	if (!syn_present &&
6178 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6179 		/* Add header */
6180 		ASSERT(recv_ill != NULL);
6181 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6182 		if (mp == NULL) {
6183 			CONN_DEC_REF(connp);
6184 			if (mctl_present)
6185 				freeb(first_mp);
6186 			return;
6187 		} else if (mctl_present) {
6188 			/*
6189 			 * ip_add_info might return a new mp.
6190 			 */
6191 			ASSERT(first_mp != mp);
6192 			first_mp->b_cont = mp;
6193 		} else {
6194 			first_mp = mp;
6195 		}
6196 	}
6197 
6198 	BUMP_MIB(&ip_mib, ipInDelivers);
6199 	if (IPCL_IS_TCP(connp)) {
6200 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6201 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6202 	} else {
6203 		putnext(connp->conn_rq, first_mp);
6204 		CONN_DEC_REF(connp);
6205 	}
6206 }
6207 
6208 /*
6209  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6210  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6211  * Caller is responsible for dropping references to the conn, and freeing
6212  * first_mp.
6213  *
6214  * IPQoS Notes
6215  * Before sending it to the client, invoke IPPF processing. Policy processing
6216  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6217  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6218  * ip_wput_local, ip_policy is false.
6219  */
6220 static void
6221 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6222     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6223     boolean_t ip_policy)
6224 {
6225 	boolean_t	mctl_present = (first_mp != NULL);
6226 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6227 	uint32_t	ill_index;
6228 
6229 	if (mctl_present)
6230 		first_mp->b_cont = mp;
6231 	else
6232 		first_mp = mp;
6233 
6234 	if (CONN_UDP_FLOWCTLD(connp)) {
6235 		BUMP_MIB(&ip_mib, udpInOverflows);
6236 		freemsg(first_mp);
6237 		return;
6238 	}
6239 
6240 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6241 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6242 		    NULL, mctl_present);
6243 		if (first_mp == NULL)
6244 			return;	/* Freed by ipsec_check_inbound_policy(). */
6245 	}
6246 	if (mctl_present)
6247 		freeb(first_mp);
6248 
6249 	if (connp->conn_recvif)
6250 		in_flags = IPF_RECVIF;
6251 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6252 		in_flags |= IPF_RECVSLLA;
6253 
6254 	/* Handle IPv6 options. */
6255 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6256 		in_flags |= IPF_RECVIF;
6257 
6258 	/*
6259 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6260 	 * freed if the packet is dropped. The caller will do so.
6261 	 */
6262 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6263 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6264 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6265 		if (mp == NULL) {
6266 			return;
6267 		}
6268 	}
6269 	if ((in_flags != 0) &&
6270 	    (mp->b_datap->db_type != M_CTL)) {
6271 		/*
6272 		 * The actual data will be contained in b_cont
6273 		 * upon successful return of the following call
6274 		 * else original mblk is returned
6275 		 */
6276 		ASSERT(recv_ill != NULL);
6277 		mp = ip_add_info(mp, recv_ill, in_flags);
6278 	}
6279 	BUMP_MIB(&ip_mib, ipInDelivers);
6280 
6281 	/* Send it upstream */
6282 	CONN_UDP_RECV(connp, mp);
6283 }
6284 
6285 /*
6286  * Fanout for UDP packets.
6287  * The caller puts <fport, lport> in the ports parameter.
6288  *
6289  * If SO_REUSEADDR is set all multicast and broadcast packets
6290  * will be delivered to all streams bound to the same port.
6291  *
6292  * Zones notes:
6293  * Multicast and broadcast packets will be distributed to streams in all zones.
6294  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6295  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6296  * packets. To maintain this behavior with multiple zones, the conns are grouped
6297  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6298  * each zone. If unset, all the following conns in the same zone are skipped.
6299  */
6300 static void
6301 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6302     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6303     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6304 {
6305 	uint32_t	dstport, srcport;
6306 	ipaddr_t	dst;
6307 	mblk_t		*first_mp;
6308 	boolean_t	secure;
6309 	in6_addr_t	v6src;
6310 	conn_t		*connp;
6311 	connf_t		*connfp;
6312 	conn_t		*first_connp;
6313 	conn_t		*next_connp;
6314 	mblk_t		*mp1, *first_mp1;
6315 	ipaddr_t	src;
6316 	zoneid_t	last_zoneid;
6317 	boolean_t	reuseaddr;
6318 	boolean_t	shared_addr;
6319 
6320 	first_mp = mp;
6321 	if (mctl_present) {
6322 		mp = first_mp->b_cont;
6323 		first_mp->b_cont = NULL;
6324 		secure = ipsec_in_is_secure(first_mp);
6325 		ASSERT(mp != NULL);
6326 	} else {
6327 		first_mp = NULL;
6328 		secure = B_FALSE;
6329 	}
6330 
6331 	/* Extract ports in net byte order */
6332 	dstport = htons(ntohl(ports) & 0xFFFF);
6333 	srcport = htons(ntohl(ports) >> 16);
6334 	dst = ipha->ipha_dst;
6335 	src = ipha->ipha_src;
6336 
6337 	shared_addr = (zoneid == ALL_ZONES);
6338 	if (shared_addr) {
6339 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6340 		if (zoneid == ALL_ZONES)
6341 			zoneid = tsol_packet_to_zoneid(mp);
6342 	}
6343 
6344 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6345 	mutex_enter(&connfp->connf_lock);
6346 	connp = connfp->connf_head;
6347 	if (!broadcast && !CLASSD(dst)) {
6348 		/*
6349 		 * Not broadcast or multicast. Send to the one (first)
6350 		 * client we find. No need to check conn_wantpacket()
6351 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6352 		 * IPv4 unicast packets.
6353 		 */
6354 		while ((connp != NULL) &&
6355 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
6356 		    srcport, src) || connp->conn_zoneid != zoneid)) {
6357 			connp = connp->conn_next;
6358 		}
6359 
6360 		if (connp == NULL || connp->conn_upq == NULL)
6361 			goto notfound;
6362 
6363 		if (is_system_labeled() &&
6364 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6365 		    connp))
6366 			goto notfound;
6367 
6368 		CONN_INC_REF(connp);
6369 		mutex_exit(&connfp->connf_lock);
6370 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6371 		    recv_ill, ip_policy);
6372 		IP_STAT(ip_udp_fannorm);
6373 		CONN_DEC_REF(connp);
6374 		return;
6375 	}
6376 
6377 	/*
6378 	 * Broadcast and multicast case
6379 	 *
6380 	 * Need to check conn_wantpacket().
6381 	 * If SO_REUSEADDR has been set on the first we send the
6382 	 * packet to all clients that have joined the group and
6383 	 * match the port.
6384 	 */
6385 
6386 	while (connp != NULL) {
6387 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6388 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6389 		    (!is_system_labeled() ||
6390 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6391 		    connp)))
6392 			break;
6393 		connp = connp->conn_next;
6394 	}
6395 
6396 	if (connp == NULL || connp->conn_upq == NULL)
6397 		goto notfound;
6398 
6399 	first_connp = connp;
6400 	/*
6401 	 * When SO_REUSEADDR is not set, send the packet only to the first
6402 	 * matching connection in its zone by keeping track of the zoneid.
6403 	 */
6404 	reuseaddr = first_connp->conn_reuseaddr;
6405 	last_zoneid = first_connp->conn_zoneid;
6406 
6407 	CONN_INC_REF(connp);
6408 	connp = connp->conn_next;
6409 	for (;;) {
6410 		while (connp != NULL) {
6411 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6412 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6413 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6414 			    (!is_system_labeled() ||
6415 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6416 			    shared_addr, connp)))
6417 				break;
6418 			connp = connp->conn_next;
6419 		}
6420 		/*
6421 		 * Just copy the data part alone. The mctl part is
6422 		 * needed just for verifying policy and it is never
6423 		 * sent up.
6424 		 */
6425 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6426 		    ((mp1 = copymsg(mp)) == NULL))) {
6427 			/*
6428 			 * No more interested clients or memory
6429 			 * allocation failed
6430 			 */
6431 			connp = first_connp;
6432 			break;
6433 		}
6434 		if (connp->conn_zoneid != last_zoneid) {
6435 			/*
6436 			 * Update the zoneid so that the packet isn't sent to
6437 			 * any more conns in the same zone unless SO_REUSEADDR
6438 			 * is set.
6439 			 */
6440 			reuseaddr = connp->conn_reuseaddr;
6441 			last_zoneid = connp->conn_zoneid;
6442 		}
6443 		if (first_mp != NULL) {
6444 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6445 			    ipsec_info_type == IPSEC_IN);
6446 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6447 			if (first_mp1 == NULL) {
6448 				freemsg(mp1);
6449 				connp = first_connp;
6450 				break;
6451 			}
6452 		} else {
6453 			first_mp1 = NULL;
6454 		}
6455 		CONN_INC_REF(connp);
6456 		mutex_exit(&connfp->connf_lock);
6457 		/*
6458 		 * IPQoS notes: We don't send the packet for policy
6459 		 * processing here, will do it for the last one (below).
6460 		 * i.e. we do it per-packet now, but if we do policy
6461 		 * processing per-conn, then we would need to do it
6462 		 * here too.
6463 		 */
6464 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6465 		    ipha, flags, recv_ill, B_FALSE);
6466 		mutex_enter(&connfp->connf_lock);
6467 		/* Follow the next pointer before releasing the conn. */
6468 		next_connp = connp->conn_next;
6469 		IP_STAT(ip_udp_fanmb);
6470 		CONN_DEC_REF(connp);
6471 		connp = next_connp;
6472 	}
6473 
6474 	/* Last one.  Send it upstream. */
6475 	mutex_exit(&connfp->connf_lock);
6476 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6477 	    ip_policy);
6478 	IP_STAT(ip_udp_fanmb);
6479 	CONN_DEC_REF(connp);
6480 	return;
6481 
6482 notfound:
6483 
6484 	mutex_exit(&connfp->connf_lock);
6485 	IP_STAT(ip_udp_fanothers);
6486 	/*
6487 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6488 	 * have already been matched above, since they live in the IPv4
6489 	 * fanout tables. This implies we only need to
6490 	 * check for IPv6 in6addr_any endpoints here.
6491 	 * Thus we compare using ipv6_all_zeros instead of the destination
6492 	 * address, except for the multicast group membership lookup which
6493 	 * uses the IPv4 destination.
6494 	 */
6495 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6496 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6497 	mutex_enter(&connfp->connf_lock);
6498 	connp = connfp->connf_head;
6499 	if (!broadcast && !CLASSD(dst)) {
6500 		while (connp != NULL) {
6501 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6502 			    srcport, v6src) && connp->conn_zoneid == zoneid &&
6503 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6504 			    !connp->conn_ipv6_v6only)
6505 				break;
6506 			connp = connp->conn_next;
6507 		}
6508 
6509 		if (connp != NULL && is_system_labeled() &&
6510 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6511 		    connp))
6512 			connp = NULL;
6513 
6514 		if (connp == NULL || connp->conn_upq == NULL) {
6515 			/*
6516 			 * No one bound to this port.  Is
6517 			 * there a client that wants all
6518 			 * unclaimed datagrams?
6519 			 */
6520 			mutex_exit(&connfp->connf_lock);
6521 
6522 			if (mctl_present)
6523 				first_mp->b_cont = mp;
6524 			else
6525 				first_mp = mp;
6526 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6527 				ip_fanout_proto(q, first_mp, ill, ipha,
6528 				    flags | IP_FF_RAWIP, mctl_present,
6529 				    ip_policy, recv_ill, zoneid);
6530 			} else {
6531 				if (ip_fanout_send_icmp(q, first_mp, flags,
6532 				    ICMP_DEST_UNREACHABLE,
6533 				    ICMP_PORT_UNREACHABLE,
6534 				    mctl_present, zoneid)) {
6535 					BUMP_MIB(&ip_mib, udpNoPorts);
6536 				}
6537 			}
6538 			return;
6539 		}
6540 
6541 		CONN_INC_REF(connp);
6542 		mutex_exit(&connfp->connf_lock);
6543 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6544 		    recv_ill, ip_policy);
6545 		CONN_DEC_REF(connp);
6546 		return;
6547 	}
6548 	/*
6549 	 * IPv4 multicast packet being delivered to an AF_INET6
6550 	 * in6addr_any endpoint.
6551 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6552 	 * and not conn_wantpacket_v6() since any multicast membership is
6553 	 * for an IPv4-mapped multicast address.
6554 	 * The packet is sent to all clients in all zones that have joined the
6555 	 * group and match the port.
6556 	 */
6557 	while (connp != NULL) {
6558 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6559 		    srcport, v6src) &&
6560 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6561 		    (!is_system_labeled() ||
6562 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6563 		    connp)))
6564 			break;
6565 		connp = connp->conn_next;
6566 	}
6567 
6568 	if (connp == NULL || connp->conn_upq == NULL) {
6569 		/*
6570 		 * No one bound to this port.  Is
6571 		 * there a client that wants all
6572 		 * unclaimed datagrams?
6573 		 */
6574 		mutex_exit(&connfp->connf_lock);
6575 
6576 		if (mctl_present)
6577 			first_mp->b_cont = mp;
6578 		else
6579 			first_mp = mp;
6580 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6581 			ip_fanout_proto(q, first_mp, ill, ipha,
6582 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6583 			    recv_ill, zoneid);
6584 		} else {
6585 			/*
6586 			 * We used to attempt to send an icmp error here, but
6587 			 * since this is known to be a multicast packet
6588 			 * and we don't send icmp errors in response to
6589 			 * multicast, just drop the packet and give up sooner.
6590 			 */
6591 			BUMP_MIB(&ip_mib, udpNoPorts);
6592 			freemsg(first_mp);
6593 		}
6594 		return;
6595 	}
6596 
6597 	first_connp = connp;
6598 
6599 	CONN_INC_REF(connp);
6600 	connp = connp->conn_next;
6601 	for (;;) {
6602 		while (connp != NULL) {
6603 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6604 			    ipv6_all_zeros, srcport, v6src) &&
6605 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6606 			    (!is_system_labeled() ||
6607 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6608 			    shared_addr, connp)))
6609 				break;
6610 			connp = connp->conn_next;
6611 		}
6612 		/*
6613 		 * Just copy the data part alone. The mctl part is
6614 		 * needed just for verifying policy and it is never
6615 		 * sent up.
6616 		 */
6617 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6618 		    ((mp1 = copymsg(mp)) == NULL))) {
6619 			/*
6620 			 * No more intested clients or memory
6621 			 * allocation failed
6622 			 */
6623 			connp = first_connp;
6624 			break;
6625 		}
6626 		if (first_mp != NULL) {
6627 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6628 			    ipsec_info_type == IPSEC_IN);
6629 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6630 			if (first_mp1 == NULL) {
6631 				freemsg(mp1);
6632 				connp = first_connp;
6633 				break;
6634 			}
6635 		} else {
6636 			first_mp1 = NULL;
6637 		}
6638 		CONN_INC_REF(connp);
6639 		mutex_exit(&connfp->connf_lock);
6640 		/*
6641 		 * IPQoS notes: We don't send the packet for policy
6642 		 * processing here, will do it for the last one (below).
6643 		 * i.e. we do it per-packet now, but if we do policy
6644 		 * processing per-conn, then we would need to do it
6645 		 * here too.
6646 		 */
6647 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6648 		    ipha, flags, recv_ill, B_FALSE);
6649 		mutex_enter(&connfp->connf_lock);
6650 		/* Follow the next pointer before releasing the conn. */
6651 		next_connp = connp->conn_next;
6652 		CONN_DEC_REF(connp);
6653 		connp = next_connp;
6654 	}
6655 
6656 	/* Last one.  Send it upstream. */
6657 	mutex_exit(&connfp->connf_lock);
6658 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6659 	    ip_policy);
6660 	CONN_DEC_REF(connp);
6661 }
6662 
6663 /*
6664  * Complete the ip_wput header so that it
6665  * is possible to generate ICMP
6666  * errors.
6667  */
6668 static int
6669 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6670 {
6671 	ire_t *ire;
6672 
6673 	if (ipha->ipha_src == INADDR_ANY) {
6674 		ire = ire_lookup_local(zoneid);
6675 		if (ire == NULL) {
6676 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6677 			return (1);
6678 		}
6679 		ipha->ipha_src = ire->ire_addr;
6680 		ire_refrele(ire);
6681 	}
6682 	ipha->ipha_ttl = ip_def_ttl;
6683 	ipha->ipha_hdr_checksum = 0;
6684 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6685 	return (0);
6686 }
6687 
6688 /*
6689  * Nobody should be sending
6690  * packets up this stream
6691  */
6692 static void
6693 ip_lrput(queue_t *q, mblk_t *mp)
6694 {
6695 	mblk_t *mp1;
6696 
6697 	switch (mp->b_datap->db_type) {
6698 	case M_FLUSH:
6699 		/* Turn around */
6700 		if (*mp->b_rptr & FLUSHW) {
6701 			*mp->b_rptr &= ~FLUSHR;
6702 			qreply(q, mp);
6703 			return;
6704 		}
6705 		break;
6706 	}
6707 	/* Could receive messages that passed through ar_rput */
6708 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6709 		mp1->b_prev = mp1->b_next = NULL;
6710 	freemsg(mp);
6711 }
6712 
6713 /* Nobody should be sending packets down this stream */
6714 /* ARGSUSED */
6715 void
6716 ip_lwput(queue_t *q, mblk_t *mp)
6717 {
6718 	freemsg(mp);
6719 }
6720 
6721 /*
6722  * Move the first hop in any source route to ipha_dst and remove that part of
6723  * the source route.  Called by other protocols.  Errors in option formatting
6724  * are ignored - will be handled by ip_wput_options Return the final
6725  * destination (either ipha_dst or the last entry in a source route.)
6726  */
6727 ipaddr_t
6728 ip_massage_options(ipha_t *ipha)
6729 {
6730 	ipoptp_t	opts;
6731 	uchar_t		*opt;
6732 	uint8_t		optval;
6733 	uint8_t		optlen;
6734 	ipaddr_t	dst;
6735 	int		i;
6736 	ire_t		*ire;
6737 
6738 	ip2dbg(("ip_massage_options\n"));
6739 	dst = ipha->ipha_dst;
6740 	for (optval = ipoptp_first(&opts, ipha);
6741 	    optval != IPOPT_EOL;
6742 	    optval = ipoptp_next(&opts)) {
6743 		opt = opts.ipoptp_cur;
6744 		switch (optval) {
6745 			uint8_t off;
6746 		case IPOPT_SSRR:
6747 		case IPOPT_LSRR:
6748 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6749 				ip1dbg(("ip_massage_options: bad src route\n"));
6750 				break;
6751 			}
6752 			optlen = opts.ipoptp_len;
6753 			off = opt[IPOPT_OFFSET];
6754 			off--;
6755 		redo_srr:
6756 			if (optlen < IP_ADDR_LEN ||
6757 			    off > optlen - IP_ADDR_LEN) {
6758 				/* End of source route */
6759 				ip1dbg(("ip_massage_options: end of SR\n"));
6760 				break;
6761 			}
6762 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6763 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6764 			    ntohl(dst)));
6765 			/*
6766 			 * Check if our address is present more than
6767 			 * once as consecutive hops in source route.
6768 			 * XXX verify per-interface ip_forwarding
6769 			 * for source route?
6770 			 */
6771 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6772 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
6773 			if (ire != NULL) {
6774 				ire_refrele(ire);
6775 				off += IP_ADDR_LEN;
6776 				goto redo_srr;
6777 			}
6778 			if (dst == htonl(INADDR_LOOPBACK)) {
6779 				ip1dbg(("ip_massage_options: loopback addr in "
6780 				    "source route!\n"));
6781 				break;
6782 			}
6783 			/*
6784 			 * Update ipha_dst to be the first hop and remove the
6785 			 * first hop from the source route (by overwriting
6786 			 * part of the option with NOP options).
6787 			 */
6788 			ipha->ipha_dst = dst;
6789 			/* Put the last entry in dst */
6790 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6791 			    3;
6792 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6793 
6794 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6795 			    ntohl(dst)));
6796 			/* Move down and overwrite */
6797 			opt[IP_ADDR_LEN] = opt[0];
6798 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6799 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6800 			for (i = 0; i < IP_ADDR_LEN; i++)
6801 				opt[i] = IPOPT_NOP;
6802 			break;
6803 		}
6804 	}
6805 	return (dst);
6806 }
6807 
6808 /*
6809  * This function's job is to forward data to the reverse tunnel (FA->HA)
6810  * after doing a few checks. It is assumed that the incoming interface
6811  * of the packet is always different than the outgoing interface and the
6812  * ire_type of the found ire has to be a non-resolver type.
6813  *
6814  * IPQoS notes
6815  * IP policy is invoked twice for a forwarded packet, once on the read side
6816  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6817  * enabled.
6818  */
6819 static void
6820 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6821 {
6822 	ipha_t		*ipha;
6823 	queue_t		*q;
6824 	uint32_t 	pkt_len;
6825 #define	rptr    ((uchar_t *)ipha)
6826 	uint32_t 	sum;
6827 	uint32_t 	max_frag;
6828 	mblk_t		*first_mp;
6829 	uint32_t	ill_index;
6830 
6831 	ASSERT(ire != NULL);
6832 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6833 	ASSERT(ire->ire_stq != NULL);
6834 
6835 	/* Initiate read side IPPF processing */
6836 	if (IPP_ENABLED(IPP_FWD_IN)) {
6837 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6838 		ip_process(IPP_FWD_IN, &mp, ill_index);
6839 		if (mp == NULL) {
6840 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6841 			    "dropped during IPPF processing\n"));
6842 			return;
6843 		}
6844 	}
6845 
6846 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6847 		ILLF_ROUTER) == 0) ||
6848 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6849 		BUMP_MIB(&ip_mib, ipForwProhibits);
6850 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6851 		    "forwarding is not turned on\n"));
6852 		goto drop_pkt;
6853 	}
6854 
6855 	/*
6856 	 * Don't forward if the interface is down
6857 	 */
6858 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6859 		BUMP_MIB(&ip_mib, ipInDiscards);
6860 		goto drop_pkt;
6861 	}
6862 
6863 	ipha = (ipha_t *)mp->b_rptr;
6864 	pkt_len = ntohs(ipha->ipha_length);
6865 	/* Adjust the checksum to reflect the ttl decrement. */
6866 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6867 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6868 	if (ipha->ipha_ttl-- <= 1) {
6869 		if (ip_csum_hdr(ipha)) {
6870 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6871 			goto drop_pkt;
6872 		}
6873 		q = ire->ire_stq;
6874 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6875 		    BPRI_HI)) == NULL) {
6876 			goto drop_pkt;
6877 		}
6878 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6879 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6880 
6881 		return;
6882 	}
6883 
6884 	/* Get the ill_index of the ILL */
6885 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6886 
6887 	/*
6888 	 * ip_mrtun_forward is only used by foreign agent to reverse
6889 	 * tunnel the incoming packet. So it does not do any option
6890 	 * processing for source routing.
6891 	 */
6892 	max_frag = ire->ire_max_frag;
6893 	if (pkt_len > max_frag) {
6894 		/*
6895 		 * It needs fragging on its way out.  We haven't
6896 		 * verified the header checksum yet.  Since we
6897 		 * are going to put a surely good checksum in the
6898 		 * outgoing header, we have to make sure that it
6899 		 * was good coming in.
6900 		 */
6901 		if (ip_csum_hdr(ipha)) {
6902 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6903 			goto drop_pkt;
6904 		}
6905 
6906 		/* Initiate write side IPPF processing */
6907 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6908 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6909 			if (mp == NULL) {
6910 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6911 				    "dropped/deferred during ip policy "\
6912 				    "processing\n"));
6913 				return;
6914 			}
6915 		}
6916 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6917 		    BPRI_HI)) == NULL) {
6918 			goto drop_pkt;
6919 		}
6920 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6921 		mp = first_mp;
6922 
6923 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6924 		return;
6925 	}
6926 
6927 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6928 
6929 	ASSERT(ire->ire_ipif != NULL);
6930 
6931 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6932 	if (mp == NULL) {
6933 		BUMP_MIB(&ip_mib, ipInDiscards);
6934 		return;
6935 	}
6936 
6937 	/* Now send the packet to the tunnel interface */
6938 	q = ire->ire_stq;
6939 	UPDATE_IB_PKT_COUNT(ire);
6940 	ire->ire_last_used_time = lbolt;
6941 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6942 	putnext(q, mp);
6943 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6944 	return;
6945 
6946 drop_pkt:;
6947 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6948 	freemsg(mp);
6949 #undef	rptr
6950 }
6951 
6952 /*
6953  * Fills the ipsec_out_t data structure with appropriate fields and
6954  * prepends it to mp which contains the IP hdr + data that was meant
6955  * to be forwarded. Please note that ipsec_out_info data structure
6956  * is used here to communicate the outgoing ill path at ip_wput()
6957  * for the ICMP error packet. This has nothing to do with ipsec IP
6958  * security. ipsec_out_t is really used to pass the info to the module
6959  * IP where this information cannot be extracted from conn.
6960  * This functions is called by ip_mrtun_forward().
6961  */
6962 void
6963 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6964 {
6965 	ipsec_out_t	*io;
6966 
6967 	ASSERT(xmit_ill != NULL);
6968 	first_mp->b_datap->db_type = M_CTL;
6969 	first_mp->b_wptr += sizeof (ipsec_info_t);
6970 	/*
6971 	 * This is to pass info to ip_wput in absence of conn.
6972 	 * ipsec_out_secure will be B_FALSE because of this.
6973 	 * Thus ipsec_out_secure being B_FALSE indicates that
6974 	 * this is not IPSEC security related information.
6975 	 */
6976 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6977 	io = (ipsec_out_t *)first_mp->b_rptr;
6978 	io->ipsec_out_type = IPSEC_OUT;
6979 	io->ipsec_out_len = sizeof (ipsec_out_t);
6980 	first_mp->b_cont = mp;
6981 	io->ipsec_out_ill_index =
6982 	    xmit_ill->ill_phyint->phyint_ifindex;
6983 	io->ipsec_out_xmit_if = B_TRUE;
6984 }
6985 
6986 /*
6987  * Return the network mask
6988  * associated with the specified address.
6989  */
6990 ipaddr_t
6991 ip_net_mask(ipaddr_t addr)
6992 {
6993 	uchar_t	*up = (uchar_t *)&addr;
6994 	ipaddr_t mask = 0;
6995 	uchar_t	*maskp = (uchar_t *)&mask;
6996 
6997 #if defined(__i386) || defined(__amd64)
6998 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
6999 #endif
7000 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7001 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7002 #endif
7003 	if (CLASSD(addr)) {
7004 		maskp[0] = 0xF0;
7005 		return (mask);
7006 	}
7007 	if (addr == 0)
7008 		return (0);
7009 	maskp[0] = 0xFF;
7010 	if ((up[0] & 0x80) == 0)
7011 		return (mask);
7012 
7013 	maskp[1] = 0xFF;
7014 	if ((up[0] & 0xC0) == 0x80)
7015 		return (mask);
7016 
7017 	maskp[2] = 0xFF;
7018 	if ((up[0] & 0xE0) == 0xC0)
7019 		return (mask);
7020 
7021 	/* Must be experimental or multicast, indicate as much */
7022 	return ((ipaddr_t)0);
7023 }
7024 
7025 /*
7026  * Select an ill for the packet by considering load spreading across
7027  * a different ill in the group if dst_ill is part of some group.
7028  */
7029 static ill_t *
7030 ip_newroute_get_dst_ill(ill_t *dst_ill)
7031 {
7032 	ill_t *ill;
7033 
7034 	/*
7035 	 * We schedule irrespective of whether the source address is
7036 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7037 	 */
7038 	ill = illgrp_scheduler(dst_ill);
7039 	if (ill == NULL)
7040 		return (NULL);
7041 
7042 	/*
7043 	 * For groups with names ip_sioctl_groupname ensures that all
7044 	 * ills are of same type. For groups without names, ifgrp_insert
7045 	 * ensures this.
7046 	 */
7047 	ASSERT(dst_ill->ill_type == ill->ill_type);
7048 
7049 	return (ill);
7050 }
7051 
7052 /*
7053  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7054  */
7055 ill_t *
7056 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7057 {
7058 	ill_t *ret_ill;
7059 
7060 	ASSERT(ifindex != 0);
7061 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7062 	if (ret_ill == NULL ||
7063 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7064 		if (isv6) {
7065 			if (ill != NULL) {
7066 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7067 			} else {
7068 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7069 			}
7070 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7071 			    "bad ifindex %d.\n", ifindex));
7072 		} else {
7073 			BUMP_MIB(&ip_mib, ipOutDiscards);
7074 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7075 			    "bad ifindex %d.\n", ifindex));
7076 		}
7077 		if (ret_ill != NULL)
7078 			ill_refrele(ret_ill);
7079 		freemsg(first_mp);
7080 		return (NULL);
7081 	}
7082 
7083 	return (ret_ill);
7084 }
7085 
7086 /*
7087  * IPv4 -
7088  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7089  * out a packet to a destination address for which we do not have specific
7090  * (or sufficient) routing information.
7091  *
7092  * NOTE : These are the scopes of some of the variables that point at IRE,
7093  *	  which needs to be followed while making any future modifications
7094  *	  to avoid memory leaks.
7095  *
7096  *	- ire and sire are the entries looked up initially by
7097  *	  ire_ftable_lookup.
7098  *	- ipif_ire is used to hold the interface ire associated with
7099  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7100  *	  it before branching out to error paths.
7101  *	- save_ire is initialized before ire_create, so that ire returned
7102  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7103  *	  before breaking out of the switch.
7104  *
7105  *	Thus on failures, we have to REFRELE only ire and sire, if they
7106  *	are not NULL.
7107  */
7108 void
7109 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
7110 {
7111 	areq_t	*areq;
7112 	ipaddr_t gw = 0;
7113 	ire_t	*ire = NULL;
7114 	mblk_t	*res_mp;
7115 	ipaddr_t *addrp;
7116 	ipaddr_t nexthop_addr;
7117 	ipif_t  *src_ipif = NULL;
7118 	ill_t	*dst_ill = NULL;
7119 	ipha_t  *ipha;
7120 	ire_t	*sire = NULL;
7121 	mblk_t	*first_mp;
7122 	ire_t	*save_ire;
7123 	mblk_t	*dlureq_mp;
7124 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7125 	ushort_t ire_marks = 0;
7126 	boolean_t mctl_present;
7127 	ipsec_out_t *io;
7128 	mblk_t	*saved_mp;
7129 	ire_t	*first_sire = NULL;
7130 	mblk_t	*copy_mp = NULL;
7131 	mblk_t	*xmit_mp = NULL;
7132 	ipaddr_t save_dst;
7133 	uint32_t multirt_flags =
7134 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7135 	boolean_t multirt_is_resolvable;
7136 	boolean_t multirt_resolve_next;
7137 	boolean_t do_attach_ill = B_FALSE;
7138 	boolean_t ip_nexthop = B_FALSE;
7139 	zoneid_t zoneid;
7140 	tsol_ire_gw_secattr_t *attrp = NULL;
7141 	tsol_gcgrp_t *gcgrp = NULL;
7142 	tsol_gcgrp_addr_t ga;
7143 
7144 	if (ip_debug > 2) {
7145 		/* ip1dbg */
7146 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7147 	}
7148 
7149 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7150 	if (mctl_present) {
7151 		io = (ipsec_out_t *)first_mp->b_rptr;
7152 		zoneid = io->ipsec_out_zoneid;
7153 		ASSERT(zoneid != ALL_ZONES);
7154 	} else if (connp != NULL) {
7155 		zoneid = connp->conn_zoneid;
7156 	} else {
7157 		zoneid = GLOBAL_ZONEID;
7158 	}
7159 
7160 	ipha = (ipha_t *)mp->b_rptr;
7161 
7162 	/* All multicast lookups come through ip_newroute_ipif() */
7163 	if (CLASSD(dst)) {
7164 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7165 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7166 		freemsg(first_mp);
7167 		return;
7168 	}
7169 
7170 	if (ip_loopback_src_or_dst(ipha, NULL)) {
7171 		goto icmp_err_ret;
7172 	}
7173 
7174 	if (mctl_present && io->ipsec_out_attach_if) {
7175 		/* ip_grab_attach_ill returns a held ill */
7176 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7177 		    io->ipsec_out_ill_index, B_FALSE);
7178 
7179 		/* Failure case frees things for us. */
7180 		if (attach_ill == NULL)
7181 			return;
7182 
7183 		/*
7184 		 * Check if we need an ire that will not be
7185 		 * looked up by anybody else i.e. HIDDEN.
7186 		 */
7187 		if (ill_is_probeonly(attach_ill))
7188 			ire_marks = IRE_MARK_HIDDEN;
7189 	}
7190 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7191 		ip_nexthop = B_TRUE;
7192 		nexthop_addr = io->ipsec_out_nexthop_addr;
7193 	}
7194 	/*
7195 	 * If this IRE is created for forwarding or it is not for
7196 	 * traffic for congestion controlled protocols, mark it as temporary.
7197 	 */
7198 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7199 		ire_marks |= IRE_MARK_TEMPORARY;
7200 
7201 	/*
7202 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7203 	 * chain until it gets the most specific information available.
7204 	 * For example, we know that there is no IRE_CACHE for this dest,
7205 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7206 	 * ire_ftable_lookup will look up the gateway, etc.
7207 	 * Check if in_ill != NULL. If it is true, the packet must be
7208 	 * from an incoming interface where RTA_SRCIFP is set.
7209 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7210 	 * to the destination, of equal netmask length in the forward table,
7211 	 * will be recursively explored. If no information is available
7212 	 * for the final gateway of that route, we force the returned ire
7213 	 * to be equal to sire using MATCH_IRE_PARENT.
7214 	 * At least, in this case we have a starting point (in the buckets)
7215 	 * to look for other routes to the destination in the forward table.
7216 	 * This is actually used only for multirouting, where a list
7217 	 * of routes has to be processed in sequence.
7218 	 */
7219 	if (in_ill != NULL) {
7220 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7221 		    in_ill, MATCH_IRE_TYPE);
7222 	} else if (ip_nexthop) {
7223 		/*
7224 		 * The first time we come here, we look for an IRE_INTERFACE
7225 		 * entry for the specified nexthop, set the dst to be the
7226 		 * nexthop address and create an IRE_CACHE entry for the
7227 		 * nexthop. The next time around, we are able to find an
7228 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7229 		 * nexthop address and create an IRE_CACHE entry for the
7230 		 * destination address via the specified nexthop.
7231 		 */
7232 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7233 		    MBLK_GETLABEL(mp));
7234 		if (ire != NULL) {
7235 			gw = nexthop_addr;
7236 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7237 		} else {
7238 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7239 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7240 			    MBLK_GETLABEL(mp),
7241 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7242 			if (ire != NULL) {
7243 				dst = nexthop_addr;
7244 			}
7245 		}
7246 	} else if (attach_ill == NULL) {
7247 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7248 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7249 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7250 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7251 		    MATCH_IRE_SECATTR);
7252 	} else {
7253 		/*
7254 		 * attach_ill is set only for communicating with
7255 		 * on-link hosts. So, don't look for DEFAULT.
7256 		 */
7257 		ipif_t	*attach_ipif;
7258 
7259 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7260 		if (attach_ipif == NULL) {
7261 			ill_refrele(attach_ill);
7262 			goto icmp_err_ret;
7263 		}
7264 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7265 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7266 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7267 		    MATCH_IRE_SECATTR);
7268 		ipif_refrele(attach_ipif);
7269 	}
7270 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7271 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7272 
7273 	/*
7274 	 * This loop is run only once in most cases.
7275 	 * We loop to resolve further routes only when the destination
7276 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7277 	 */
7278 	do {
7279 		/* Clear the previous iteration's values */
7280 		if (src_ipif != NULL) {
7281 			ipif_refrele(src_ipif);
7282 			src_ipif = NULL;
7283 		}
7284 		if (dst_ill != NULL) {
7285 			ill_refrele(dst_ill);
7286 			dst_ill = NULL;
7287 		}
7288 
7289 		multirt_resolve_next = B_FALSE;
7290 		/*
7291 		 * We check if packets have to be multirouted.
7292 		 * In this case, given the current <ire, sire> couple,
7293 		 * we look for the next suitable <ire, sire>.
7294 		 * This check is done in ire_multirt_lookup(),
7295 		 * which applies various criteria to find the next route
7296 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7297 		 * unchanged if it detects it has not been tried yet.
7298 		 */
7299 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7300 			ip3dbg(("ip_newroute: starting next_resolution "
7301 			    "with first_mp %p, tag %d\n",
7302 			    (void *)first_mp,
7303 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7304 
7305 			ASSERT(sire != NULL);
7306 			multirt_is_resolvable =
7307 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7308 				MBLK_GETLABEL(mp));
7309 
7310 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7311 			    "ire %p, sire %p\n",
7312 			    multirt_is_resolvable,
7313 			    (void *)ire, (void *)sire));
7314 
7315 			if (!multirt_is_resolvable) {
7316 				/*
7317 				 * No more multirt route to resolve; give up
7318 				 * (all routes resolved or no more
7319 				 * resolvable routes).
7320 				 */
7321 				if (ire != NULL) {
7322 					ire_refrele(ire);
7323 					ire = NULL;
7324 				}
7325 			} else {
7326 				ASSERT(sire != NULL);
7327 				ASSERT(ire != NULL);
7328 				/*
7329 				 * We simply use first_sire as a flag that
7330 				 * indicates if a resolvable multirt route
7331 				 * has already been found.
7332 				 * If it is not the case, we may have to send
7333 				 * an ICMP error to report that the
7334 				 * destination is unreachable.
7335 				 * We do not IRE_REFHOLD first_sire.
7336 				 */
7337 				if (first_sire == NULL) {
7338 					first_sire = sire;
7339 				}
7340 			}
7341 		}
7342 		if (ire == NULL) {
7343 			if (ip_debug > 3) {
7344 				/* ip2dbg */
7345 				pr_addr_dbg("ip_newroute: "
7346 				    "can't resolve %s\n", AF_INET, &dst);
7347 			}
7348 			ip3dbg(("ip_newroute: "
7349 			    "ire %p, sire %p, first_sire %p\n",
7350 			    (void *)ire, (void *)sire, (void *)first_sire));
7351 
7352 			if (sire != NULL) {
7353 				ire_refrele(sire);
7354 				sire = NULL;
7355 			}
7356 
7357 			if (first_sire != NULL) {
7358 				/*
7359 				 * At least one multirt route has been found
7360 				 * in the same call to ip_newroute();
7361 				 * there is no need to report an ICMP error.
7362 				 * first_sire was not IRE_REFHOLDed.
7363 				 */
7364 				MULTIRT_DEBUG_UNTAG(first_mp);
7365 				freemsg(first_mp);
7366 				return;
7367 			}
7368 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7369 			    RTA_DST);
7370 			if (attach_ill != NULL)
7371 				ill_refrele(attach_ill);
7372 			goto icmp_err_ret;
7373 		}
7374 
7375 		/*
7376 		 * When RTA_SRCIFP is used to add a route, then an interface
7377 		 * route is added in the source interface's routing table.
7378 		 * If the outgoing interface of this route is of type
7379 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7380 		 * ire_dlureq_mp is set to NULL. Later, when this route is
7381 		 * first used for forwarding packet, ip_newroute() is called
7382 		 * to resolve the hardware address of the outgoing ipif.
7383 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7384 		 * source interface based table. We only come here if the
7385 		 * outgoing interface is a resolver interface and we don't
7386 		 * have the ire_dlureq_mp information yet.
7387 		 * If in_ill is not null that means it is called from
7388 		 * ip_rput.
7389 		 */
7390 
7391 		ASSERT(ire->ire_in_ill == NULL ||
7392 		    (ire->ire_type == IRE_IF_RESOLVER &&
7393 		    ire->ire_dlureq_mp == NULL));
7394 
7395 		/*
7396 		 * Verify that the returned IRE does not have either
7397 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7398 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7399 		 */
7400 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7401 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7402 			if (attach_ill != NULL)
7403 				ill_refrele(attach_ill);
7404 			goto icmp_err_ret;
7405 		}
7406 		/*
7407 		 * Increment the ire_ob_pkt_count field for ire if it is an
7408 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7409 		 * increment the same for the parent IRE, sire, if it is some
7410 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7411 		 * and HOST_REDIRECT).
7412 		 */
7413 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7414 			UPDATE_OB_PKT_COUNT(ire);
7415 			ire->ire_last_used_time = lbolt;
7416 		}
7417 
7418 		if (sire != NULL) {
7419 			gw = sire->ire_gateway_addr;
7420 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7421 			    IRE_INTERFACE)) == 0);
7422 			UPDATE_OB_PKT_COUNT(sire);
7423 			sire->ire_last_used_time = lbolt;
7424 		}
7425 		/*
7426 		 * We have a route to reach the destination.
7427 		 *
7428 		 * 1) If the interface is part of ill group, try to get a new
7429 		 *    ill taking load spreading into account.
7430 		 *
7431 		 * 2) After selecting the ill, get a source address that
7432 		 *    might create good inbound load spreading.
7433 		 *    ipif_select_source does this for us.
7434 		 *
7435 		 * If the application specified the ill (ifindex), we still
7436 		 * load spread. Only if the packets needs to go out
7437 		 * specifically on a given ill e.g. binding to
7438 		 * IPIF_NOFAILOVER address, then we don't try to use a
7439 		 * different ill for load spreading.
7440 		 */
7441 		if (attach_ill == NULL) {
7442 			/*
7443 			 * Don't perform outbound load spreading in the
7444 			 * case of an RTF_MULTIRT route, as we actually
7445 			 * typically want to replicate outgoing packets
7446 			 * through particular interfaces.
7447 			 */
7448 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7449 				dst_ill = ire->ire_ipif->ipif_ill;
7450 				/* for uniformity */
7451 				ill_refhold(dst_ill);
7452 			} else {
7453 				/*
7454 				 * If we are here trying to create an IRE_CACHE
7455 				 * for an offlink destination and have the
7456 				 * IRE_CACHE for the next hop and the latter is
7457 				 * using virtual IP source address selection i.e
7458 				 * it's ire->ire_ipif is pointing to a virtual
7459 				 * network interface (vni) then
7460 				 * ip_newroute_get_dst_ll() will return the vni
7461 				 * interface as the dst_ill. Since the vni is
7462 				 * virtual i.e not associated with any physical
7463 				 * interface, it cannot be the dst_ill, hence
7464 				 * in such a case call ip_newroute_get_dst_ll()
7465 				 * with the stq_ill instead of the ire_ipif ILL.
7466 				 * The function returns a refheld ill.
7467 				 */
7468 				if ((ire->ire_type == IRE_CACHE) &&
7469 				    IS_VNI(ire->ire_ipif->ipif_ill))
7470 					dst_ill = ip_newroute_get_dst_ill(
7471 						ire->ire_stq->q_ptr);
7472 				else
7473 					dst_ill = ip_newroute_get_dst_ill(
7474 						ire->ire_ipif->ipif_ill);
7475 			}
7476 			if (dst_ill == NULL) {
7477 				if (ip_debug > 2) {
7478 					pr_addr_dbg("ip_newroute: "
7479 					    "no dst ill for dst"
7480 					    " %s\n", AF_INET, &dst);
7481 				}
7482 				goto icmp_err_ret;
7483 			}
7484 		} else {
7485 			dst_ill = ire->ire_ipif->ipif_ill;
7486 			/* for uniformity */
7487 			ill_refhold(dst_ill);
7488 			/*
7489 			 * We should have found a route matching ill as we
7490 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7491 			 * Rather than asserting, when there is a mismatch,
7492 			 * we just drop the packet.
7493 			 */
7494 			if (dst_ill != attach_ill) {
7495 				ip0dbg(("ip_newroute: Packet dropped as "
7496 				    "IPIF_NOFAILOVER ill is %s, "
7497 				    "ire->ire_ipif->ipif_ill is %s\n",
7498 				    attach_ill->ill_name,
7499 				    dst_ill->ill_name));
7500 				ill_refrele(attach_ill);
7501 				goto icmp_err_ret;
7502 			}
7503 		}
7504 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7505 		if (attach_ill != NULL) {
7506 			ill_refrele(attach_ill);
7507 			attach_ill = NULL;
7508 			do_attach_ill = B_TRUE;
7509 		}
7510 		ASSERT(dst_ill != NULL);
7511 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7512 
7513 		/*
7514 		 * Pick the best source address from dst_ill.
7515 		 *
7516 		 * 1) If it is part of a multipathing group, we would
7517 		 *    like to spread the inbound packets across different
7518 		 *    interfaces. ipif_select_source picks a random source
7519 		 *    across the different ills in the group.
7520 		 *
7521 		 * 2) If it is not part of a multipathing group, we try
7522 		 *    to pick the source address from the destination
7523 		 *    route. Clustering assumes that when we have multiple
7524 		 *    prefixes hosted on an interface, the prefix of the
7525 		 *    source address matches the prefix of the destination
7526 		 *    route. We do this only if the address is not
7527 		 *    DEPRECATED.
7528 		 *
7529 		 * 3) If the conn is in a different zone than the ire, we
7530 		 *    need to pick a source address from the right zone.
7531 		 *
7532 		 * NOTE : If we hit case (1) above, the prefix of the source
7533 		 *	  address picked may not match the prefix of the
7534 		 *	  destination routes prefix as ipif_select_source
7535 		 *	  does not look at "dst" while picking a source
7536 		 *	  address.
7537 		 *	  If we want the same behavior as (2), we will need
7538 		 *	  to change the behavior of ipif_select_source.
7539 		 */
7540 		ASSERT(src_ipif == NULL);
7541 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7542 			/*
7543 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7544 			 * Check that the ipif matching the requested source
7545 			 * address still exists.
7546 			 */
7547 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7548 			    zoneid, NULL, NULL, NULL, NULL);
7549 		}
7550 		if (src_ipif == NULL) {
7551 			ire_marks |= IRE_MARK_USESRC_CHECK;
7552 			if ((dst_ill->ill_group != NULL) ||
7553 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7554 			    (connp != NULL && ire->ire_zoneid != zoneid &&
7555 			    ire->ire_zoneid != ALL_ZONES) ||
7556 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7557 				/*
7558 				 * If the destination is reachable via a
7559 				 * given gateway, the selected source address
7560 				 * should be in the same subnet as the gateway.
7561 				 * Otherwise, the destination is not reachable.
7562 				 *
7563 				 * If there are no interfaces on the same subnet
7564 				 * as the destination, ipif_select_source gives
7565 				 * first non-deprecated interface which might be
7566 				 * on a different subnet than the gateway.
7567 				 * This is not desirable. Hence pass the dst_ire
7568 				 * source address to ipif_select_source.
7569 				 * It is sure that the destination is reachable
7570 				 * with the dst_ire source address subnet.
7571 				 * So passing dst_ire source address to
7572 				 * ipif_select_source will make sure that the
7573 				 * selected source will be on the same subnet
7574 				 * as dst_ire source address.
7575 				 */
7576 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7577 				src_ipif = ipif_select_source(dst_ill, saddr,
7578 				    zoneid);
7579 				if (src_ipif == NULL) {
7580 					if (ip_debug > 2) {
7581 						pr_addr_dbg("ip_newroute: "
7582 						    "no src for dst %s ",
7583 						    AF_INET, &dst);
7584 						printf("through interface %s\n",
7585 						    dst_ill->ill_name);
7586 					}
7587 					goto icmp_err_ret;
7588 				}
7589 			} else {
7590 				src_ipif = ire->ire_ipif;
7591 				ASSERT(src_ipif != NULL);
7592 				/* hold src_ipif for uniformity */
7593 				ipif_refhold(src_ipif);
7594 			}
7595 		}
7596 
7597 		/*
7598 		 * Assign a source address while we have the conn.
7599 		 * We can't have ip_wput_ire pick a source address when the
7600 		 * packet returns from arp since we need to look at
7601 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7602 		 * going through arp.
7603 		 *
7604 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7605 		 *	  it uses ip6i to store this information.
7606 		 */
7607 		if (ipha->ipha_src == INADDR_ANY &&
7608 		    (connp == NULL || !connp->conn_unspec_src)) {
7609 			ipha->ipha_src = src_ipif->ipif_src_addr;
7610 		}
7611 		if (ip_debug > 3) {
7612 			/* ip2dbg */
7613 			pr_addr_dbg("ip_newroute: first hop %s\n",
7614 			    AF_INET, &gw);
7615 		}
7616 		ip2dbg(("\tire type %s (%d)\n",
7617 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7618 
7619 		/*
7620 		 * The TTL of multirouted packets is bounded by the
7621 		 * ip_multirt_ttl ndd variable.
7622 		 */
7623 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7624 			/* Force TTL of multirouted packets */
7625 			if ((ip_multirt_ttl > 0) &&
7626 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7627 				ip2dbg(("ip_newroute: forcing multirt TTL "
7628 				    "to %d (was %d), dst 0x%08x\n",
7629 				    ip_multirt_ttl, ipha->ipha_ttl,
7630 				    ntohl(sire->ire_addr)));
7631 				ipha->ipha_ttl = ip_multirt_ttl;
7632 			}
7633 		}
7634 		/*
7635 		 * At this point in ip_newroute(), ire is either the
7636 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7637 		 * destination or an IRE_INTERFACE type that should be used
7638 		 * to resolve an on-subnet destination or an on-subnet
7639 		 * next-hop gateway.
7640 		 *
7641 		 * In the IRE_CACHE case, we have the following :
7642 		 *
7643 		 * 1) src_ipif - used for getting a source address.
7644 		 *
7645 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7646 		 *    means packets using this IRE_CACHE will go out on
7647 		 *    dst_ill.
7648 		 *
7649 		 * 3) The IRE sire will point to the prefix that is the
7650 		 *    longest  matching route for the destination. These
7651 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7652 		 *    and IRE_HOST_REDIRECT.
7653 		 *
7654 		 *    The newly created IRE_CACHE entry for the off-subnet
7655 		 *    destination is tied to both the prefix route and the
7656 		 *    interface route used to resolve the next-hop gateway
7657 		 *    via the ire_phandle and ire_ihandle fields,
7658 		 *    respectively.
7659 		 *
7660 		 * In the IRE_INTERFACE case, we have the following :
7661 		 *
7662 		 * 1) src_ipif - used for getting a source address.
7663 		 *
7664 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7665 		 *    means packets using the IRE_CACHE that we will build
7666 		 *    here will go out on dst_ill.
7667 		 *
7668 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7669 		 *    to be created will only be tied to the IRE_INTERFACE
7670 		 *    that was derived from the ire_ihandle field.
7671 		 *
7672 		 *    If sire is non-NULL, it means the destination is
7673 		 *    off-link and we will first create the IRE_CACHE for the
7674 		 *    gateway. Next time through ip_newroute, we will create
7675 		 *    the IRE_CACHE for the final destination as described
7676 		 *    above.
7677 		 *
7678 		 * In both cases, after the current resolution has been
7679 		 * completed (or possibly initialised, in the IRE_INTERFACE
7680 		 * case), the loop may be re-entered to attempt the resolution
7681 		 * of another RTF_MULTIRT route.
7682 		 *
7683 		 * When an IRE_CACHE entry for the off-subnet destination is
7684 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7685 		 * for further processing in emission loops.
7686 		 */
7687 		save_ire = ire;
7688 		switch (ire->ire_type) {
7689 		case IRE_CACHE: {
7690 			ire_t	*ipif_ire;
7691 			mblk_t	*ire_fp_mp;
7692 
7693 			if (gw == 0)
7694 				gw = ire->ire_gateway_addr;
7695 			/*
7696 			 * We need 3 ire's to create a new cache ire for an
7697 			 * off-link destination from the cache ire of the
7698 			 * gateway.
7699 			 *
7700 			 *	1. The prefix ire 'sire' (Note that this does
7701 			 *	   not apply to the conn_nexthop_set case)
7702 			 *	2. The cache ire of the gateway 'ire'
7703 			 *	3. The interface ire 'ipif_ire'
7704 			 *
7705 			 * We have (1) and (2). We lookup (3) below.
7706 			 *
7707 			 * If there is no interface route to the gateway,
7708 			 * it is a race condition, where we found the cache
7709 			 * but the interface route has been deleted.
7710 			 */
7711 			if (ip_nexthop) {
7712 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7713 			} else {
7714 				ipif_ire =
7715 				    ire_ihandle_lookup_offlink(ire, sire);
7716 			}
7717 			if (ipif_ire == NULL) {
7718 				ip1dbg(("ip_newroute: "
7719 				    "ire_ihandle_lookup_offlink failed\n"));
7720 				goto icmp_err_ret;
7721 			}
7722 			/*
7723 			 * XXX We are using the same dlureq_mp
7724 			 * (DL_UNITDATA_REQ) though the save_ire is not
7725 			 * pointing at the same ill.
7726 			 * This is incorrect. We need to send it up to the
7727 			 * resolver to get the right dlureq_mp. For ethernets
7728 			 * this may be okay (ill_type == DL_ETHER).
7729 			 */
7730 			dlureq_mp = save_ire->ire_dlureq_mp;
7731 			ire_fp_mp = NULL;
7732 			/*
7733 			 * save_ire's ire_fp_mp can't change since it is
7734 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7735 			 * LOCK_IRE_FP_MP does not do any useful work in
7736 			 * the case of IRE_CACHE. So we don't use it below.
7737 			 */
7738 			if (save_ire->ire_stq == dst_ill->ill_wq)
7739 				ire_fp_mp = save_ire->ire_fp_mp;
7740 
7741 			/*
7742 			 * Check cached gateway IRE for any security
7743 			 * attributes; if found, associate the gateway
7744 			 * credentials group to the destination IRE.
7745 			 */
7746 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
7747 				mutex_enter(&attrp->igsa_lock);
7748 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
7749 					GCGRP_REFHOLD(gcgrp);
7750 				mutex_exit(&attrp->igsa_lock);
7751 			}
7752 
7753 			ire = ire_create(
7754 			    (uchar_t *)&dst,		/* dest address */
7755 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7756 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7757 			    (uchar_t *)&gw,		/* gateway address */
7758 			    NULL,
7759 			    &save_ire->ire_max_frag,
7760 			    ire_fp_mp,			/* Fast Path header */
7761 			    dst_ill->ill_rq,		/* recv-from queue */
7762 			    dst_ill->ill_wq,		/* send-to queue */
7763 			    IRE_CACHE,			/* IRE type */
7764 			    save_ire->ire_dlureq_mp,
7765 			    src_ipif,
7766 			    in_ill,			/* incoming ill */
7767 			    (sire != NULL) ?
7768 				sire->ire_mask : 0, 	/* Parent mask */
7769 			    (sire != NULL) ?
7770 				sire->ire_phandle : 0,  /* Parent handle */
7771 			    ipif_ire->ire_ihandle,	/* Interface handle */
7772 			    (sire != NULL) ? (sire->ire_flags &
7773 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7774 			    (sire != NULL) ?
7775 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
7776 			    NULL,
7777 			    gcgrp);
7778 
7779 			if (ire == NULL) {
7780 				if (gcgrp != NULL) {
7781 					GCGRP_REFRELE(gcgrp);
7782 					gcgrp = NULL;
7783 				}
7784 				ire_refrele(ipif_ire);
7785 				ire_refrele(save_ire);
7786 				break;
7787 			}
7788 
7789 			/* reference now held by IRE */
7790 			gcgrp = NULL;
7791 
7792 			ire->ire_marks |= ire_marks;
7793 
7794 			/*
7795 			 * Prevent sire and ipif_ire from getting deleted.
7796 			 * The newly created ire is tied to both of them via
7797 			 * the phandle and ihandle respectively.
7798 			 */
7799 			if (sire != NULL) {
7800 				IRB_REFHOLD(sire->ire_bucket);
7801 				/* Has it been removed already ? */
7802 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7803 					IRB_REFRELE(sire->ire_bucket);
7804 					ire_refrele(ipif_ire);
7805 					ire_refrele(save_ire);
7806 					break;
7807 				}
7808 			}
7809 
7810 			IRB_REFHOLD(ipif_ire->ire_bucket);
7811 			/* Has it been removed already ? */
7812 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7813 				IRB_REFRELE(ipif_ire->ire_bucket);
7814 				if (sire != NULL)
7815 					IRB_REFRELE(sire->ire_bucket);
7816 				ire_refrele(ipif_ire);
7817 				ire_refrele(save_ire);
7818 				break;
7819 			}
7820 
7821 			xmit_mp = first_mp;
7822 			/*
7823 			 * In the case of multirouting, a copy
7824 			 * of the packet is done before its sending.
7825 			 * The copy is used to attempt another
7826 			 * route resolution, in a next loop.
7827 			 */
7828 			if (ire->ire_flags & RTF_MULTIRT) {
7829 				copy_mp = copymsg(first_mp);
7830 				if (copy_mp != NULL) {
7831 					xmit_mp = copy_mp;
7832 					MULTIRT_DEBUG_TAG(first_mp);
7833 				}
7834 			}
7835 			ire_add_then_send(q, ire, xmit_mp);
7836 			ire_refrele(save_ire);
7837 
7838 			/* Assert that sire is not deleted yet. */
7839 			if (sire != NULL) {
7840 				ASSERT(sire->ire_ptpn != NULL);
7841 				IRB_REFRELE(sire->ire_bucket);
7842 			}
7843 
7844 			/* Assert that ipif_ire is not deleted yet. */
7845 			ASSERT(ipif_ire->ire_ptpn != NULL);
7846 			IRB_REFRELE(ipif_ire->ire_bucket);
7847 			ire_refrele(ipif_ire);
7848 
7849 			/*
7850 			 * If copy_mp is not NULL, multirouting was
7851 			 * requested. We loop to initiate a next
7852 			 * route resolution attempt, starting from sire.
7853 			 */
7854 			if (copy_mp != NULL) {
7855 				/*
7856 				 * Search for the next unresolved
7857 				 * multirt route.
7858 				 */
7859 				copy_mp = NULL;
7860 				ipif_ire = NULL;
7861 				ire = NULL;
7862 				multirt_resolve_next = B_TRUE;
7863 				continue;
7864 			}
7865 			if (sire != NULL)
7866 				ire_refrele(sire);
7867 			ipif_refrele(src_ipif);
7868 			ill_refrele(dst_ill);
7869 			return;
7870 		}
7871 		case IRE_IF_NORESOLVER: {
7872 			/*
7873 			 * We have what we need to build an IRE_CACHE.
7874 			 *
7875 			 * Create a new dlureq_mp with the IP gateway address
7876 			 * in destination address in the DLPI hdr if the
7877 			 * physical length is exactly 4 bytes.
7878 			 */
7879 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7880 				uchar_t *addr;
7881 
7882 				if (gw)
7883 					addr = (uchar_t *)&gw;
7884 				else
7885 					addr = (uchar_t *)&dst;
7886 
7887 				dlureq_mp = ill_dlur_gen(addr,
7888 				    dst_ill->ill_phys_addr_length,
7889 				    dst_ill->ill_sap,
7890 				    dst_ill->ill_sap_length);
7891 			} else {
7892 				dlureq_mp = ire->ire_dlureq_mp;
7893 			}
7894 
7895 			if (dlureq_mp == NULL) {
7896 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7897 				break;
7898 			}
7899 
7900 			/*
7901 			 * TSol note: We are creating the ire cache for the
7902 			 * destination 'dst'. If 'dst' is offlink, going
7903 			 * through the first hop 'gw', the security attributes
7904 			 * of 'dst' must be set to point to the gateway
7905 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
7906 			 * is possible that 'dst' is a potential gateway that is
7907 			 * referenced by some route that has some security
7908 			 * attributes. Thus in the former case, we need to do a
7909 			 * gcgrp_lookup of 'gw' while in the latter case we
7910 			 * need to do gcgrp_lookup of 'dst' itself.
7911 			 */
7912 			ga.ga_af = AF_INET;
7913 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
7914 			    &ga.ga_addr);
7915 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
7916 
7917 			ire = ire_create(
7918 			    (uchar_t *)&dst,		/* dest address */
7919 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7920 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7921 			    (uchar_t *)&gw,		/* gateway address */
7922 			    NULL,
7923 			    &save_ire->ire_max_frag,
7924 			    NULL,			/* Fast Path header */
7925 			    dst_ill->ill_rq,		/* recv-from queue */
7926 			    dst_ill->ill_wq,		/* send-to queue */
7927 			    IRE_CACHE,
7928 			    dlureq_mp,
7929 			    src_ipif,
7930 			    in_ill,			/* Incoming ill */
7931 			    save_ire->ire_mask,		/* Parent mask */
7932 			    (sire != NULL) ?		/* Parent handle */
7933 				sire->ire_phandle : 0,
7934 			    save_ire->ire_ihandle,	/* Interface handle */
7935 			    (sire != NULL) ? sire->ire_flags &
7936 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7937 			    &(save_ire->ire_uinfo),
7938 			    NULL,
7939 			    gcgrp);
7940 
7941 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7942 				freeb(dlureq_mp);
7943 
7944 			if (ire == NULL) {
7945 				if (gcgrp != NULL) {
7946 					GCGRP_REFRELE(gcgrp);
7947 					gcgrp = NULL;
7948 				}
7949 				ire_refrele(save_ire);
7950 				break;
7951 			}
7952 
7953 			/* reference now held by IRE */
7954 			gcgrp = NULL;
7955 
7956 			ire->ire_marks |= ire_marks;
7957 
7958 			/* Prevent save_ire from getting deleted */
7959 			IRB_REFHOLD(save_ire->ire_bucket);
7960 			/* Has it been removed already ? */
7961 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7962 				IRB_REFRELE(save_ire->ire_bucket);
7963 				ire_refrele(save_ire);
7964 				break;
7965 			}
7966 
7967 			/*
7968 			 * In the case of multirouting, a copy
7969 			 * of the packet is made before it is sent.
7970 			 * The copy is used in the next
7971 			 * loop to attempt another resolution.
7972 			 */
7973 			xmit_mp = first_mp;
7974 			if ((sire != NULL) &&
7975 			    (sire->ire_flags & RTF_MULTIRT)) {
7976 				copy_mp = copymsg(first_mp);
7977 				if (copy_mp != NULL) {
7978 					xmit_mp = copy_mp;
7979 					MULTIRT_DEBUG_TAG(first_mp);
7980 				}
7981 			}
7982 			ire_add_then_send(q, ire, xmit_mp);
7983 
7984 			/* Assert that it is not deleted yet. */
7985 			ASSERT(save_ire->ire_ptpn != NULL);
7986 			IRB_REFRELE(save_ire->ire_bucket);
7987 			ire_refrele(save_ire);
7988 
7989 			if (copy_mp != NULL) {
7990 				/*
7991 				 * If we found a (no)resolver, we ignore any
7992 				 * trailing top priority IRE_CACHE in further
7993 				 * loops. This ensures that we do not omit any
7994 				 * (no)resolver.
7995 				 * This IRE_CACHE, if any, will be processed
7996 				 * by another thread entering ip_newroute().
7997 				 * IRE_CACHE entries, if any, will be processed
7998 				 * by another thread entering ip_newroute(),
7999 				 * (upon resolver response, for instance).
8000 				 * This aims to force parallel multirt
8001 				 * resolutions as soon as a packet must be sent.
8002 				 * In the best case, after the tx of only one
8003 				 * packet, all reachable routes are resolved.
8004 				 * Otherwise, the resolution of all RTF_MULTIRT
8005 				 * routes would require several emissions.
8006 				 */
8007 				multirt_flags &= ~MULTIRT_CACHEGW;
8008 
8009 				/*
8010 				 * Search for the next unresolved multirt
8011 				 * route.
8012 				 */
8013 				copy_mp = NULL;
8014 				save_ire = NULL;
8015 				ire = NULL;
8016 				multirt_resolve_next = B_TRUE;
8017 				continue;
8018 			}
8019 
8020 			/*
8021 			 * Don't need sire anymore
8022 			 */
8023 			if (sire != NULL)
8024 				ire_refrele(sire);
8025 
8026 			ipif_refrele(src_ipif);
8027 			ill_refrele(dst_ill);
8028 			return;
8029 		}
8030 		case IRE_IF_RESOLVER:
8031 			/*
8032 			 * We can't build an IRE_CACHE yet, but at least we
8033 			 * found a resolver that can help.
8034 			 */
8035 			res_mp = dst_ill->ill_resolver_mp;
8036 			if (!OK_RESOLVER_MP(res_mp))
8037 				break;
8038 
8039 			/*
8040 			 * To be at this point in the code with a non-zero gw
8041 			 * means that dst is reachable through a gateway that
8042 			 * we have never resolved.  By changing dst to the gw
8043 			 * addr we resolve the gateway first.
8044 			 * When ire_add_then_send() tries to put the IP dg
8045 			 * to dst, it will reenter ip_newroute() at which
8046 			 * time we will find the IRE_CACHE for the gw and
8047 			 * create another IRE_CACHE in case IRE_CACHE above.
8048 			 */
8049 			if (gw != INADDR_ANY) {
8050 				/*
8051 				 * The source ipif that was determined above was
8052 				 * relative to the destination address, not the
8053 				 * gateway's. If src_ipif was not taken out of
8054 				 * the IRE_IF_RESOLVER entry, we'll need to call
8055 				 * ipif_select_source() again.
8056 				 */
8057 				if (src_ipif != ire->ire_ipif) {
8058 					ipif_refrele(src_ipif);
8059 					src_ipif = ipif_select_source(dst_ill,
8060 					    gw, zoneid);
8061 					if (src_ipif == NULL) {
8062 						if (ip_debug > 2) {
8063 							pr_addr_dbg(
8064 							    "ip_newroute: no "
8065 							    "src for gw %s ",
8066 							    AF_INET, &gw);
8067 							printf("through "
8068 							    "interface %s\n",
8069 							    dst_ill->ill_name);
8070 						}
8071 						goto icmp_err_ret;
8072 					}
8073 				}
8074 				save_dst = dst;
8075 				dst = gw;
8076 				gw = INADDR_ANY;
8077 			}
8078 
8079 			/*
8080 			 * TSol note: Please see the corresponding note
8081 			 * of the IRE_IF_NORESOLVER case
8082 			 */
8083 			ga.ga_af = AF_INET;
8084 			IN6_IPADDR_TO_V4MAPPED(dst, &ga.ga_addr);
8085 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8086 
8087 			/*
8088 			 * We obtain a partial IRE_CACHE which we will pass
8089 			 * along with the resolver query.  When the response
8090 			 * comes back it will be there ready for us to add.
8091 			 * The ire_max_frag is atomically set under the
8092 			 * irebucket lock in ire_add_v[46].
8093 			 */
8094 			ire = ire_create_mp(
8095 			    (uchar_t *)&dst,		/* dest address */
8096 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8097 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8098 			    (uchar_t *)&gw,		/* gateway address */
8099 			    NULL,			/* no in_src_addr */
8100 			    NULL,			/* ire_max_frag */
8101 			    NULL,			/* Fast Path header */
8102 			    dst_ill->ill_rq,		/* recv-from queue */
8103 			    dst_ill->ill_wq,		/* send-to queue */
8104 			    IRE_CACHE,
8105 			    res_mp,
8106 			    src_ipif,			/* Interface ipif */
8107 			    in_ill,			/* Incoming ILL */
8108 			    save_ire->ire_mask,		/* Parent mask */
8109 			    0,
8110 			    save_ire->ire_ihandle,	/* Interface handle */
8111 			    0,				/* flags if any */
8112 			    &(save_ire->ire_uinfo),
8113 			    NULL,
8114 			    gcgrp);
8115 
8116 			if (ire == NULL) {
8117 				ire_refrele(save_ire);
8118 				if (gcgrp != NULL) {
8119 					GCGRP_REFRELE(gcgrp);
8120 					gcgrp = NULL;
8121 				}
8122 				break;
8123 			}
8124 
8125 			/* reference now held by IRE */
8126 			gcgrp = NULL;
8127 
8128 			if ((sire != NULL) &&
8129 			    (sire->ire_flags & RTF_MULTIRT)) {
8130 				copy_mp = copymsg(first_mp);
8131 				if (copy_mp != NULL)
8132 					MULTIRT_DEBUG_TAG(copy_mp);
8133 			}
8134 
8135 			ire->ire_marks |= ire_marks;
8136 
8137 			/*
8138 			 * Construct message chain for the resolver
8139 			 * of the form:
8140 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8141 			 * Packet could contain a IPSEC_OUT mp.
8142 			 *
8143 			 * NOTE : ire will be added later when the response
8144 			 * comes back from ARP. If the response does not
8145 			 * come back, ARP frees the packet. For this reason,
8146 			 * we can't REFHOLD the bucket of save_ire to prevent
8147 			 * deletions. We may not be able to REFRELE the bucket
8148 			 * if the response never comes back. Thus, before
8149 			 * adding the ire, ire_add_v4 will make sure that the
8150 			 * interface route does not get deleted. This is the
8151 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8152 			 * where we can always prevent deletions because of
8153 			 * the synchronous nature of adding IRES i.e
8154 			 * ire_add_then_send is called after creating the IRE.
8155 			 */
8156 			ASSERT(ire->ire_mp != NULL);
8157 			ire->ire_mp->b_cont = first_mp;
8158 			/* Have saved_mp handy, for cleanup if canput fails */
8159 			saved_mp = mp;
8160 			mp = ire->ire_dlureq_mp;
8161 			ASSERT(mp != NULL);
8162 			ire->ire_dlureq_mp = NULL;
8163 			linkb(mp, ire->ire_mp);
8164 
8165 
8166 			/*
8167 			 * Fill in the source and dest addrs for the resolver.
8168 			 * NOTE: this depends on memory layouts imposed by
8169 			 * ill_init().
8170 			 */
8171 			areq = (areq_t *)mp->b_rptr;
8172 			addrp = (ipaddr_t *)((char *)areq +
8173 			    areq->areq_sender_addr_offset);
8174 			if (do_attach_ill) {
8175 				/*
8176 				 * This is bind to no failover case.
8177 				 * arp packet also must go out on attach_ill.
8178 				 */
8179 				ASSERT(ipha->ipha_src != NULL);
8180 				*addrp = ipha->ipha_src;
8181 			} else {
8182 				*addrp = save_ire->ire_src_addr;
8183 			}
8184 
8185 			ire_refrele(save_ire);
8186 			addrp = (ipaddr_t *)((char *)areq +
8187 			    areq->areq_target_addr_offset);
8188 			*addrp = dst;
8189 			/* Up to the resolver. */
8190 			if (canputnext(dst_ill->ill_rq)) {
8191 				putnext(dst_ill->ill_rq, mp);
8192 				ire = NULL;
8193 				if (copy_mp != NULL) {
8194 					/*
8195 					 * If we found a resolver, we ignore
8196 					 * any trailing top priority IRE_CACHE
8197 					 * in the further loops. This ensures
8198 					 * that we do not omit any resolver.
8199 					 * IRE_CACHE entries, if any, will be
8200 					 * processed next time we enter
8201 					 * ip_newroute().
8202 					 */
8203 					multirt_flags &= ~MULTIRT_CACHEGW;
8204 					/*
8205 					 * Search for the next unresolved
8206 					 * multirt route.
8207 					 */
8208 					first_mp = copy_mp;
8209 					copy_mp = NULL;
8210 					/* Prepare the next resolution loop. */
8211 					mp = first_mp;
8212 					EXTRACT_PKT_MP(mp, first_mp,
8213 					    mctl_present);
8214 					if (mctl_present)
8215 						io = (ipsec_out_t *)
8216 						    first_mp->b_rptr;
8217 					ipha = (ipha_t *)mp->b_rptr;
8218 
8219 					ASSERT(sire != NULL);
8220 
8221 					dst = save_dst;
8222 					multirt_resolve_next = B_TRUE;
8223 					continue;
8224 				}
8225 
8226 				if (sire != NULL)
8227 					ire_refrele(sire);
8228 
8229 				/*
8230 				 * The response will come back in ip_wput
8231 				 * with db_type IRE_DB_TYPE.
8232 				 */
8233 				ipif_refrele(src_ipif);
8234 				ill_refrele(dst_ill);
8235 				return;
8236 			} else {
8237 				/* Prepare for cleanup */
8238 				ire->ire_dlureq_mp = mp;
8239 				mp->b_cont = NULL;
8240 				ire_delete(ire);
8241 				mp = saved_mp;
8242 				ire = NULL;
8243 				if (copy_mp != NULL) {
8244 					MULTIRT_DEBUG_UNTAG(copy_mp);
8245 					freemsg(copy_mp);
8246 					copy_mp = NULL;
8247 				}
8248 				break;
8249 			}
8250 		default:
8251 			break;
8252 		}
8253 	} while (multirt_resolve_next);
8254 
8255 	ip1dbg(("ip_newroute: dropped\n"));
8256 	/* Did this packet originate externally? */
8257 	if (mp->b_prev) {
8258 		mp->b_next = NULL;
8259 		mp->b_prev = NULL;
8260 		BUMP_MIB(&ip_mib, ipInDiscards);
8261 	} else {
8262 		BUMP_MIB(&ip_mib, ipOutDiscards);
8263 	}
8264 	ASSERT(copy_mp == NULL);
8265 	MULTIRT_DEBUG_UNTAG(first_mp);
8266 	freemsg(first_mp);
8267 	if (ire != NULL)
8268 		ire_refrele(ire);
8269 	if (sire != NULL)
8270 		ire_refrele(sire);
8271 	if (src_ipif != NULL)
8272 		ipif_refrele(src_ipif);
8273 	if (dst_ill != NULL)
8274 		ill_refrele(dst_ill);
8275 	return;
8276 
8277 icmp_err_ret:
8278 	ip1dbg(("ip_newroute: no route\n"));
8279 	if (src_ipif != NULL)
8280 		ipif_refrele(src_ipif);
8281 	if (dst_ill != NULL)
8282 		ill_refrele(dst_ill);
8283 	if (sire != NULL)
8284 		ire_refrele(sire);
8285 	/* Did this packet originate externally? */
8286 	if (mp->b_prev) {
8287 		mp->b_next = NULL;
8288 		mp->b_prev = NULL;
8289 		/* XXX ipInNoRoutes */
8290 		q = WR(q);
8291 	} else {
8292 		/*
8293 		 * Since ip_wput() isn't close to finished, we fill
8294 		 * in enough of the header for credible error reporting.
8295 		 */
8296 		if (ip_hdr_complete(ipha, zoneid)) {
8297 			/* Failed */
8298 			MULTIRT_DEBUG_UNTAG(first_mp);
8299 			freemsg(first_mp);
8300 			if (ire != NULL)
8301 				ire_refrele(ire);
8302 			return;
8303 		}
8304 	}
8305 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8306 
8307 	/*
8308 	 * At this point we will have ire only if RTF_BLACKHOLE
8309 	 * or RTF_REJECT flags are set on the IRE. It will not
8310 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8311 	 */
8312 	if (ire != NULL) {
8313 		if (ire->ire_flags & RTF_BLACKHOLE) {
8314 			ire_refrele(ire);
8315 			MULTIRT_DEBUG_UNTAG(first_mp);
8316 			freemsg(first_mp);
8317 			return;
8318 		}
8319 		ire_refrele(ire);
8320 	}
8321 	if (ip_source_routed(ipha)) {
8322 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
8323 		return;
8324 	}
8325 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8326 }
8327 
8328 /*
8329  * IPv4 -
8330  * ip_newroute_ipif is called by ip_wput_multicast and
8331  * ip_rput_forward_multicast whenever we need to send
8332  * out a packet to a destination address for which we do not have specific
8333  * routing information. It is used when the packet will be sent out
8334  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8335  * socket option is set or icmp error message wants to go out on a particular
8336  * interface for a unicast packet.
8337  *
8338  * In most cases, the destination address is resolved thanks to the ipif
8339  * intrinsic resolver. However, there are some cases where the call to
8340  * ip_newroute_ipif must take into account the potential presence of
8341  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8342  * that uses the interface. This is specified through flags,
8343  * which can be a combination of:
8344  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8345  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8346  *   and flags. Additionally, the packet source address has to be set to
8347  *   the specified address. The caller is thus expected to set this flag
8348  *   if the packet has no specific source address yet.
8349  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8350  *   flag, the resulting ire will inherit the flag. All unresolved routes
8351  *   to the destination must be explored in the same call to
8352  *   ip_newroute_ipif().
8353  */
8354 static void
8355 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8356     conn_t *connp, uint32_t flags)
8357 {
8358 	areq_t	*areq;
8359 	ire_t	*ire = NULL;
8360 	mblk_t	*res_mp;
8361 	ipaddr_t *addrp;
8362 	mblk_t *first_mp;
8363 	ire_t	*save_ire = NULL;
8364 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8365 	ipif_t	*src_ipif = NULL;
8366 	ushort_t ire_marks = 0;
8367 	ill_t	*dst_ill = NULL;
8368 	boolean_t mctl_present;
8369 	ipsec_out_t *io;
8370 	ipha_t *ipha;
8371 	int	ihandle = 0;
8372 	mblk_t	*saved_mp;
8373 	ire_t   *fire = NULL;
8374 	mblk_t  *copy_mp = NULL;
8375 	boolean_t multirt_resolve_next;
8376 	ipaddr_t ipha_dst;
8377 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
8378 
8379 	/*
8380 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8381 	 * here for uniformity
8382 	 */
8383 	ipif_refhold(ipif);
8384 
8385 	/*
8386 	 * This loop is run only once in most cases.
8387 	 * We loop to resolve further routes only when the destination
8388 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8389 	 */
8390 	do {
8391 		if (dst_ill != NULL) {
8392 			ill_refrele(dst_ill);
8393 			dst_ill = NULL;
8394 		}
8395 		if (src_ipif != NULL) {
8396 			ipif_refrele(src_ipif);
8397 			src_ipif = NULL;
8398 		}
8399 		multirt_resolve_next = B_FALSE;
8400 
8401 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8402 		    ipif->ipif_ill->ill_name));
8403 
8404 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8405 		if (mctl_present)
8406 			io = (ipsec_out_t *)first_mp->b_rptr;
8407 
8408 		ipha = (ipha_t *)mp->b_rptr;
8409 
8410 		/*
8411 		 * Save the packet destination address, we may need it after
8412 		 * the packet has been consumed.
8413 		 */
8414 		ipha_dst = ipha->ipha_dst;
8415 
8416 		/*
8417 		 * If the interface is a pt-pt interface we look for an
8418 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8419 		 * local_address and the pt-pt destination address. Otherwise
8420 		 * we just match the local address.
8421 		 * NOTE: dst could be different than ipha->ipha_dst in case
8422 		 * of sending igmp multicast packets over a point-to-point
8423 		 * connection.
8424 		 * Thus we must be careful enough to check ipha_dst to be a
8425 		 * multicast address, otherwise it will take xmit_if path for
8426 		 * multicast packets resulting into kernel stack overflow by
8427 		 * repeated calls to ip_newroute_ipif from ire_send().
8428 		 */
8429 		if (CLASSD(ipha_dst) &&
8430 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8431 			goto err_ret;
8432 		}
8433 
8434 		/*
8435 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8436 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8437 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8438 		 * propagate its flags to the new ire.
8439 		 */
8440 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8441 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8442 			ip2dbg(("ip_newroute_ipif: "
8443 			    "ipif_lookup_multi_ire("
8444 			    "ipif %p, dst %08x) = fire %p\n",
8445 			    (void *)ipif, ntohl(dst), (void *)fire));
8446 		}
8447 
8448 		if (mctl_present && io->ipsec_out_attach_if) {
8449 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8450 			    io->ipsec_out_ill_index, B_FALSE);
8451 
8452 			/* Failure case frees things for us. */
8453 			if (attach_ill == NULL) {
8454 				ipif_refrele(ipif);
8455 				if (fire != NULL)
8456 					ire_refrele(fire);
8457 				return;
8458 			}
8459 
8460 			/*
8461 			 * Check if we need an ire that will not be
8462 			 * looked up by anybody else i.e. HIDDEN.
8463 			 */
8464 			if (ill_is_probeonly(attach_ill)) {
8465 				ire_marks = IRE_MARK_HIDDEN;
8466 			}
8467 			/*
8468 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8469 			 * case.
8470 			 */
8471 			dst_ill = ipif->ipif_ill;
8472 			/* attach_ill has been refheld by ip_grab_attach_ill */
8473 			ASSERT(dst_ill == attach_ill);
8474 		} else {
8475 			/*
8476 			 * If this is set by IP_XMIT_IF, then make sure that
8477 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8478 			 * specified ill.
8479 			 */
8480 			ASSERT((connp == NULL) ||
8481 			    (connp->conn_xmit_if_ill == NULL) ||
8482 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8483 			/*
8484 			 * If the interface belongs to an interface group,
8485 			 * make sure the next possible interface in the group
8486 			 * is used.  This encourages load spreading among
8487 			 * peers in an interface group.
8488 			 * Note: load spreading is disabled for RTF_MULTIRT
8489 			 * routes.
8490 			 */
8491 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8492 			    (fire->ire_flags & RTF_MULTIRT)) {
8493 				/*
8494 				 * Don't perform outbound load spreading
8495 				 * in the case of an RTF_MULTIRT issued route,
8496 				 * we actually typically want to replicate
8497 				 * outgoing packets through particular
8498 				 * interfaces.
8499 				 */
8500 				dst_ill = ipif->ipif_ill;
8501 				ill_refhold(dst_ill);
8502 			} else {
8503 				dst_ill = ip_newroute_get_dst_ill(
8504 				    ipif->ipif_ill);
8505 			}
8506 			if (dst_ill == NULL) {
8507 				if (ip_debug > 2) {
8508 					pr_addr_dbg("ip_newroute_ipif: "
8509 					    "no dst ill for dst %s\n",
8510 					    AF_INET, &dst);
8511 				}
8512 				goto err_ret;
8513 			}
8514 		}
8515 
8516 		/*
8517 		 * Pick a source address preferring non-deprecated ones.
8518 		 * Unlike ip_newroute, we don't do any source address
8519 		 * selection here since for multicast it really does not help
8520 		 * in inbound load spreading as in the unicast case.
8521 		 */
8522 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8523 		    (fire->ire_flags & RTF_SETSRC)) {
8524 			/*
8525 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8526 			 * on that interface. This ire has RTF_SETSRC flag, so
8527 			 * the source address of the packet must be changed.
8528 			 * Check that the ipif matching the requested source
8529 			 * address still exists.
8530 			 */
8531 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8532 			    zoneid, NULL, NULL, NULL, NULL);
8533 		}
8534 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8535 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8536 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8537 		    (src_ipif == NULL)) {
8538 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8539 			if (src_ipif == NULL) {
8540 				if (ip_debug > 2) {
8541 					/* ip1dbg */
8542 					pr_addr_dbg("ip_newroute_ipif: "
8543 					    "no src for dst %s",
8544 					    AF_INET, &dst);
8545 				}
8546 				ip1dbg((" through interface %s\n",
8547 				    dst_ill->ill_name));
8548 				goto err_ret;
8549 			}
8550 			ipif_refrele(ipif);
8551 			ipif = src_ipif;
8552 			ipif_refhold(ipif);
8553 		}
8554 		if (src_ipif == NULL) {
8555 			src_ipif = ipif;
8556 			ipif_refhold(src_ipif);
8557 		}
8558 
8559 		/*
8560 		 * Assign a source address while we have the conn.
8561 		 * We can't have ip_wput_ire pick a source address when the
8562 		 * packet returns from arp since conn_unspec_src might be set
8563 		 * and we loose the conn when going through arp.
8564 		 */
8565 		if (ipha->ipha_src == INADDR_ANY &&
8566 		    (connp == NULL || !connp->conn_unspec_src)) {
8567 			ipha->ipha_src = src_ipif->ipif_src_addr;
8568 		}
8569 
8570 		/*
8571 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8572 		 * interface does not have an interface ire.
8573 		 * Example: Thousands of mobileip PPP interfaces to mobile
8574 		 * nodes. We don't want to create interface ires because
8575 		 * packets from other mobile nodes must not take the route
8576 		 * via interface ires to the visiting mobile node without
8577 		 * going through the home agent, in absence of mobileip
8578 		 * route optimization.
8579 		 */
8580 		if (CLASSD(ipha_dst) && (connp == NULL ||
8581 		    connp->conn_xmit_if_ill == NULL)) {
8582 			/* ipif_to_ire returns an held ire */
8583 			ire = ipif_to_ire(ipif);
8584 			if (ire == NULL)
8585 				goto err_ret;
8586 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8587 				goto err_ret;
8588 			/*
8589 			 * ihandle is needed when the ire is added to
8590 			 * cache table.
8591 			 */
8592 			save_ire = ire;
8593 			ihandle = save_ire->ire_ihandle;
8594 
8595 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8596 			    "flags %04x\n",
8597 			    (void *)ire, (void *)ipif, flags));
8598 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8599 			    (fire->ire_flags & RTF_MULTIRT)) {
8600 				/*
8601 				 * As requested by flags, an IRE_OFFSUBNET was
8602 				 * looked up on that interface. This ire has
8603 				 * RTF_MULTIRT flag, so the resolution loop will
8604 				 * be re-entered to resolve additional routes on
8605 				 * other interfaces. For that purpose, a copy of
8606 				 * the packet is performed at this point.
8607 				 */
8608 				fire->ire_last_used_time = lbolt;
8609 				copy_mp = copymsg(first_mp);
8610 				if (copy_mp) {
8611 					MULTIRT_DEBUG_TAG(copy_mp);
8612 				}
8613 			}
8614 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8615 			    (fire->ire_flags & RTF_SETSRC)) {
8616 				/*
8617 				 * As requested by flags, an IRE_OFFSUBET was
8618 				 * looked up on that interface. This ire has
8619 				 * RTF_SETSRC flag, so the source address of the
8620 				 * packet must be changed.
8621 				 */
8622 				ipha->ipha_src = fire->ire_src_addr;
8623 			}
8624 		} else {
8625 			ASSERT((connp == NULL) ||
8626 			    (connp->conn_xmit_if_ill != NULL) ||
8627 			    (connp->conn_dontroute));
8628 			/*
8629 			 * The only ways we can come here are:
8630 			 * 1) IP_XMIT_IF socket option is set
8631 			 * 2) ICMP error message generated from
8632 			 *    ip_mrtun_forward() routine and it needs
8633 			 *    to go through the specified ill.
8634 			 * 3) SO_DONTROUTE socket option is set
8635 			 * In all cases, the new ire will not be added
8636 			 * into cache table.
8637 			 */
8638 			ire_marks |= IRE_MARK_NOADD;
8639 		}
8640 
8641 		switch (ipif->ipif_net_type) {
8642 		case IRE_IF_NORESOLVER: {
8643 			/* We have what we need to build an IRE_CACHE. */
8644 			mblk_t	*dlureq_mp;
8645 
8646 			/*
8647 			 * Create a new dlureq_mp with the
8648 			 * IP gateway address as destination address in the
8649 			 * DLPI hdr if the physical length is exactly 4 bytes.
8650 			 */
8651 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8652 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8653 				    dst_ill->ill_phys_addr_length,
8654 				    dst_ill->ill_sap,
8655 				    dst_ill->ill_sap_length);
8656 			} else {
8657 				/* use the value set in ip_ll_subnet_defaults */
8658 				dlureq_mp = ill_dlur_gen(NULL,
8659 				    dst_ill->ill_phys_addr_length,
8660 				    dst_ill->ill_sap,
8661 				    dst_ill->ill_sap_length);
8662 			}
8663 
8664 			if (dlureq_mp == NULL)
8665 				break;
8666 			/*
8667 			 * The new ire inherits the IRE_OFFSUBNET flags
8668 			 * and source address, if this was requested.
8669 			 */
8670 			ire = ire_create(
8671 			    (uchar_t *)&dst,		/* dest address */
8672 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8673 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8674 			    NULL,			/* gateway address */
8675 			    NULL,
8676 			    &ipif->ipif_mtu,
8677 			    NULL,			/* Fast Path header */
8678 			    dst_ill->ill_rq,		/* recv-from queue */
8679 			    dst_ill->ill_wq,		/* send-to queue */
8680 			    IRE_CACHE,
8681 			    dlureq_mp,
8682 			    src_ipif,
8683 			    NULL,
8684 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8685 			    (fire != NULL) ?		/* Parent handle */
8686 				fire->ire_phandle : 0,
8687 			    ihandle,			/* Interface handle */
8688 			    (fire != NULL) ?
8689 				(fire->ire_flags &
8690 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8691 			    (save_ire == NULL ? &ire_uinfo_null :
8692 				&save_ire->ire_uinfo),
8693 			    NULL,
8694 			    NULL);
8695 
8696 			freeb(dlureq_mp);
8697 
8698 			if (ire == NULL) {
8699 				if (save_ire != NULL)
8700 					ire_refrele(save_ire);
8701 				break;
8702 			}
8703 
8704 			ire->ire_marks |= ire_marks;
8705 
8706 			/*
8707 			 * If IRE_MARK_NOADD is set then we need to convert
8708 			 * the max_fragp to a useable value now. This is
8709 			 * normally done in ire_add_v[46].
8710 			 */
8711 			if (ire->ire_marks & IRE_MARK_NOADD) {
8712 				uint_t  max_frag;
8713 
8714 				max_frag = *ire->ire_max_fragp;
8715 				ire->ire_max_fragp = NULL;
8716 				ire->ire_max_frag = max_frag;
8717 			}
8718 
8719 			/* Prevent save_ire from getting deleted */
8720 			if (save_ire != NULL) {
8721 				IRB_REFHOLD(save_ire->ire_bucket);
8722 				/* Has it been removed already ? */
8723 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8724 					IRB_REFRELE(save_ire->ire_bucket);
8725 					ire_refrele(save_ire);
8726 					break;
8727 				}
8728 			}
8729 
8730 			ire_add_then_send(q, ire, first_mp);
8731 
8732 			/* Assert that save_ire is not deleted yet. */
8733 			if (save_ire != NULL) {
8734 				ASSERT(save_ire->ire_ptpn != NULL);
8735 				IRB_REFRELE(save_ire->ire_bucket);
8736 				ire_refrele(save_ire);
8737 				save_ire = NULL;
8738 			}
8739 			if (fire != NULL) {
8740 				ire_refrele(fire);
8741 				fire = NULL;
8742 			}
8743 
8744 			/*
8745 			 * the resolution loop is re-entered if this
8746 			 * was requested through flags and if we
8747 			 * actually are in a multirouting case.
8748 			 */
8749 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8750 				boolean_t need_resolve =
8751 				    ire_multirt_need_resolve(ipha_dst,
8752 					MBLK_GETLABEL(copy_mp));
8753 				if (!need_resolve) {
8754 					MULTIRT_DEBUG_UNTAG(copy_mp);
8755 					freemsg(copy_mp);
8756 					copy_mp = NULL;
8757 				} else {
8758 					/*
8759 					 * ipif_lookup_group() calls
8760 					 * ire_lookup_multi() that uses
8761 					 * ire_ftable_lookup() to find
8762 					 * an IRE_INTERFACE for the group.
8763 					 * In the multirt case,
8764 					 * ire_lookup_multi() then invokes
8765 					 * ire_multirt_lookup() to find
8766 					 * the next resolvable ire.
8767 					 * As a result, we obtain an new
8768 					 * interface, derived from the
8769 					 * next ire.
8770 					 */
8771 					ipif_refrele(ipif);
8772 					ipif = ipif_lookup_group(ipha_dst,
8773 					    zoneid);
8774 					ip2dbg(("ip_newroute_ipif: "
8775 					    "multirt dst %08x, ipif %p\n",
8776 					    htonl(dst), (void *)ipif));
8777 					if (ipif != NULL) {
8778 						mp = copy_mp;
8779 						copy_mp = NULL;
8780 						multirt_resolve_next = B_TRUE;
8781 						continue;
8782 					} else {
8783 						freemsg(copy_mp);
8784 					}
8785 				}
8786 			}
8787 			if (ipif != NULL)
8788 				ipif_refrele(ipif);
8789 			ill_refrele(dst_ill);
8790 			ipif_refrele(src_ipif);
8791 			return;
8792 		}
8793 		case IRE_IF_RESOLVER:
8794 			/*
8795 			 * We can't build an IRE_CACHE yet, but at least
8796 			 * we found a resolver that can help.
8797 			 */
8798 			res_mp = dst_ill->ill_resolver_mp;
8799 			if (!OK_RESOLVER_MP(res_mp))
8800 				break;
8801 
8802 			/*
8803 			 * We obtain a partial IRE_CACHE which we will pass
8804 			 * along with the resolver query.  When the response
8805 			 * comes back it will be there ready for us to add.
8806 			 * The new ire inherits the IRE_OFFSUBNET flags
8807 			 * and source address, if this was requested.
8808 			 * The ire_max_frag is atomically set under the
8809 			 * irebucket lock in ire_add_v[46]. Only in the
8810 			 * case of IRE_MARK_NOADD, we set it here itself.
8811 			 */
8812 			ire = ire_create_mp(
8813 			    (uchar_t *)&dst,		/* dest address */
8814 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8815 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8816 			    NULL,			/* gateway address */
8817 			    NULL,			/* no in_src_addr */
8818 			    (ire_marks & IRE_MARK_NOADD) ?
8819 				ipif->ipif_mtu : 0,	/* max_frag */
8820 			    NULL,			/* Fast path header */
8821 			    dst_ill->ill_rq,		/* recv-from queue */
8822 			    dst_ill->ill_wq,		/* send-to queue */
8823 			    IRE_CACHE,
8824 			    res_mp,
8825 			    src_ipif,
8826 			    NULL,
8827 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8828 			    (fire != NULL) ?		/* Parent handle */
8829 				fire->ire_phandle : 0,
8830 			    ihandle,			/* Interface handle */
8831 			    (fire != NULL) ?		/* flags if any */
8832 				(fire->ire_flags &
8833 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8834 			    (save_ire == NULL ? &ire_uinfo_null :
8835 				&save_ire->ire_uinfo),
8836 			    NULL,
8837 			    NULL);
8838 
8839 			if (save_ire != NULL) {
8840 				ire_refrele(save_ire);
8841 				save_ire = NULL;
8842 			}
8843 			if (ire == NULL)
8844 				break;
8845 
8846 			ire->ire_marks |= ire_marks;
8847 			/*
8848 			 * Construct message chain for the resolver of the
8849 			 * form:
8850 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8851 			 *
8852 			 * NOTE : ire will be added later when the response
8853 			 * comes back from ARP. If the response does not
8854 			 * come back, ARP frees the packet. For this reason,
8855 			 * we can't REFHOLD the bucket of save_ire to prevent
8856 			 * deletions. We may not be able to REFRELE the
8857 			 * bucket if the response never comes back.
8858 			 * Thus, before adding the ire, ire_add_v4 will make
8859 			 * sure that the interface route does not get deleted.
8860 			 * This is the only case unlike ip_newroute_v6,
8861 			 * ip_newroute_ipif_v6 where we can always prevent
8862 			 * deletions because ire_add_then_send is called after
8863 			 * creating the IRE.
8864 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8865 			 * does not add this IRE into the IRE CACHE.
8866 			 */
8867 			ASSERT(ire->ire_mp != NULL);
8868 			ire->ire_mp->b_cont = first_mp;
8869 			/* Have saved_mp handy, for cleanup if canput fails */
8870 			saved_mp = mp;
8871 			mp = ire->ire_dlureq_mp;
8872 			ASSERT(mp != NULL);
8873 			ire->ire_dlureq_mp = NULL;
8874 			linkb(mp, ire->ire_mp);
8875 
8876 			/*
8877 			 * Fill in the source and dest addrs for the resolver.
8878 			 * NOTE: this depends on memory layouts imposed by
8879 			 * ill_init().
8880 			 */
8881 			areq = (areq_t *)mp->b_rptr;
8882 			addrp = (ipaddr_t *)((char *)areq +
8883 			    areq->areq_sender_addr_offset);
8884 			*addrp = ire->ire_src_addr;
8885 			addrp = (ipaddr_t *)((char *)areq +
8886 			    areq->areq_target_addr_offset);
8887 			*addrp = dst;
8888 			/* Up to the resolver. */
8889 			if (canputnext(dst_ill->ill_rq)) {
8890 				putnext(dst_ill->ill_rq, mp);
8891 				/*
8892 				 * The response will come back in ip_wput
8893 				 * with db_type IRE_DB_TYPE.
8894 				 */
8895 			} else {
8896 				ire->ire_dlureq_mp = mp;
8897 				mp->b_cont = NULL;
8898 				ire_delete(ire);
8899 				saved_mp->b_next = NULL;
8900 				saved_mp->b_prev = NULL;
8901 				freemsg(first_mp);
8902 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8903 			}
8904 
8905 			if (fire != NULL) {
8906 				ire_refrele(fire);
8907 				fire = NULL;
8908 			}
8909 
8910 
8911 			/*
8912 			 * The resolution loop is re-entered if this was
8913 			 * requested through flags and we actually are
8914 			 * in a multirouting case.
8915 			 */
8916 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8917 				boolean_t need_resolve =
8918 				    ire_multirt_need_resolve(ipha_dst,
8919 					MBLK_GETLABEL(copy_mp));
8920 				if (!need_resolve) {
8921 					MULTIRT_DEBUG_UNTAG(copy_mp);
8922 					freemsg(copy_mp);
8923 					copy_mp = NULL;
8924 				} else {
8925 					/*
8926 					 * ipif_lookup_group() calls
8927 					 * ire_lookup_multi() that uses
8928 					 * ire_ftable_lookup() to find
8929 					 * an IRE_INTERFACE for the group.
8930 					 * In the multirt case,
8931 					 * ire_lookup_multi() then invokes
8932 					 * ire_multirt_lookup() to find
8933 					 * the next resolvable ire.
8934 					 * As a result, we obtain an new
8935 					 * interface, derived from the
8936 					 * next ire.
8937 					 */
8938 					ipif_refrele(ipif);
8939 					ipif = ipif_lookup_group(ipha_dst,
8940 					    zoneid);
8941 					if (ipif != NULL) {
8942 						mp = copy_mp;
8943 						copy_mp = NULL;
8944 						multirt_resolve_next = B_TRUE;
8945 						continue;
8946 					} else {
8947 						freemsg(copy_mp);
8948 					}
8949 				}
8950 			}
8951 			if (ipif != NULL)
8952 				ipif_refrele(ipif);
8953 			ill_refrele(dst_ill);
8954 			ipif_refrele(src_ipif);
8955 			return;
8956 		default:
8957 			break;
8958 		}
8959 	} while (multirt_resolve_next);
8960 
8961 err_ret:
8962 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8963 	if (fire != NULL)
8964 		ire_refrele(fire);
8965 	ipif_refrele(ipif);
8966 	/* Did this packet originate externally? */
8967 	if (dst_ill != NULL)
8968 		ill_refrele(dst_ill);
8969 	if (src_ipif != NULL)
8970 		ipif_refrele(src_ipif);
8971 	if (mp->b_prev || mp->b_next) {
8972 		mp->b_next = NULL;
8973 		mp->b_prev = NULL;
8974 	} else {
8975 		/*
8976 		 * Since ip_wput() isn't close to finished, we fill
8977 		 * in enough of the header for credible error reporting.
8978 		 */
8979 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8980 			/* Failed */
8981 			freemsg(first_mp);
8982 			if (ire != NULL)
8983 				ire_refrele(ire);
8984 			return;
8985 		}
8986 	}
8987 	/*
8988 	 * At this point we will have ire only if RTF_BLACKHOLE
8989 	 * or RTF_REJECT flags are set on the IRE. It will not
8990 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8991 	 */
8992 	if (ire != NULL) {
8993 		if (ire->ire_flags & RTF_BLACKHOLE) {
8994 			ire_refrele(ire);
8995 			freemsg(first_mp);
8996 			return;
8997 		}
8998 		ire_refrele(ire);
8999 	}
9000 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
9001 }
9002 
9003 /* Name/Value Table Lookup Routine */
9004 char *
9005 ip_nv_lookup(nv_t *nv, int value)
9006 {
9007 	if (!nv)
9008 		return (NULL);
9009 	for (; nv->nv_name; nv++) {
9010 		if (nv->nv_value == value)
9011 			return (nv->nv_name);
9012 	}
9013 	return ("unknown");
9014 }
9015 
9016 /*
9017  * one day it can be patched to 1 from /etc/system for machines that have few
9018  * fast network interfaces feeding multiple cpus.
9019  */
9020 int ill_stream_putlocks = 0;
9021 
9022 /*
9023  * This is a module open, i.e. this is a control stream for access
9024  * to a DLPI device.  We allocate an ill_t as the instance data in
9025  * this case.
9026  */
9027 int
9028 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9029 {
9030 	uint32_t mem_cnt;
9031 	uint32_t cpu_cnt;
9032 	uint32_t min_cnt;
9033 	pgcnt_t mem_avail;
9034 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
9035 	ill_t	*ill;
9036 	int	err;
9037 
9038 	/*
9039 	 * Prevent unprivileged processes from pushing IP so that
9040 	 * they can't send raw IP.
9041 	 */
9042 	if (secpolicy_net_rawaccess(credp) != 0)
9043 		return (EPERM);
9044 
9045 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9046 	q->q_ptr = WR(q)->q_ptr = ill;
9047 
9048 	/*
9049 	 * ill_init initializes the ill fields and then sends down
9050 	 * down a DL_INFO_REQ after calling qprocson.
9051 	 */
9052 	err = ill_init(q, ill);
9053 	if (err != 0) {
9054 		mi_free(ill);
9055 		q->q_ptr = NULL;
9056 		WR(q)->q_ptr = NULL;
9057 		return (err);
9058 	}
9059 
9060 	/* ill_init initializes the ipsq marking this thread as writer */
9061 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9062 	/* Wait for the DL_INFO_ACK */
9063 	mutex_enter(&ill->ill_lock);
9064 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9065 		/*
9066 		 * Return value of 0 indicates a pending signal.
9067 		 */
9068 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9069 		if (err == 0) {
9070 			mutex_exit(&ill->ill_lock);
9071 			(void) ip_close(q, 0);
9072 			return (EINTR);
9073 		}
9074 	}
9075 	mutex_exit(&ill->ill_lock);
9076 
9077 	/*
9078 	 * ip_rput_other could have set an error  in ill_error on
9079 	 * receipt of M_ERROR.
9080 	 */
9081 
9082 	err = ill->ill_error;
9083 	if (err != 0) {
9084 		(void) ip_close(q, 0);
9085 		return (err);
9086 	}
9087 
9088 	/*
9089 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9090 	 * size and the cpu speed of the machine. This is upper
9091 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9092 	 * and is lower bounded by the compile time value of
9093 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9094 	 * ip6_ire_max_bucket_cnt.
9095 	 */
9096 	mem_avail = kmem_avail();
9097 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9098 	    ip_cache_table_size / sizeof (ire_t);
9099 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9100 
9101 	min_cnt = MIN(cpu_cnt, mem_cnt);
9102 	if (min_cnt < ip_ire_min_bucket_cnt)
9103 		min_cnt = ip_ire_min_bucket_cnt;
9104 	if (ip_ire_max_bucket_cnt > min_cnt) {
9105 		ip_ire_max_bucket_cnt = min_cnt;
9106 	}
9107 
9108 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9109 	    ip6_cache_table_size / sizeof (ire_t);
9110 	min_cnt = MIN(cpu_cnt, mem_cnt);
9111 	if (min_cnt < ip6_ire_min_bucket_cnt)
9112 		min_cnt = ip6_ire_min_bucket_cnt;
9113 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9114 		ip6_ire_max_bucket_cnt = min_cnt;
9115 	}
9116 
9117 	ill->ill_credp = credp;
9118 	crhold(credp);
9119 
9120 	mutex_enter(&ip_mi_lock);
9121 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9122 	mutex_exit(&ip_mi_lock);
9123 	if (err) {
9124 		(void) ip_close(q, 0);
9125 		return (err);
9126 	}
9127 	return (0);
9128 }
9129 
9130 /* IP open routine. */
9131 int
9132 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9133 {
9134 	conn_t 		*connp;
9135 	major_t		maj;
9136 
9137 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9138 
9139 	/* Allow reopen. */
9140 	if (q->q_ptr != NULL)
9141 		return (0);
9142 
9143 	if (sflag & MODOPEN) {
9144 		/* This is a module open */
9145 		return (ip_modopen(q, devp, flag, sflag, credp));
9146 	}
9147 
9148 	/*
9149 	 * We are opening as a device. This is an IP client stream, and we
9150 	 * allocate an conn_t as the instance data.
9151 	 */
9152 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9153 	connp->conn_upq = q;
9154 	q->q_ptr = WR(q)->q_ptr = connp;
9155 
9156 	if (flag & SO_SOCKSTR)
9157 		connp->conn_flags |= IPCL_SOCKET;
9158 
9159 	/* Minor tells us which /dev entry was opened */
9160 	if (geteminor(*devp) == IPV6_MINOR) {
9161 		connp->conn_flags |= IPCL_ISV6;
9162 		connp->conn_af_isv6 = B_TRUE;
9163 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9164 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9165 	} else {
9166 		connp->conn_af_isv6 = B_FALSE;
9167 		connp->conn_pkt_isv6 = B_FALSE;
9168 	}
9169 
9170 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9171 		q->q_ptr = WR(q)->q_ptr = NULL;
9172 		CONN_DEC_REF(connp);
9173 		return (EBUSY);
9174 	}
9175 
9176 	maj = getemajor(*devp);
9177 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9178 
9179 	/*
9180 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9181 	 */
9182 	connp->conn_cred = credp;
9183 	crhold(connp->conn_cred);
9184 
9185 	/*
9186 	 * If the caller has the process-wide flag set, then default to MAC
9187 	 * exempt mode.  This allows read-down to unlabeled hosts.
9188 	 */
9189 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9190 		connp->conn_mac_exempt = B_TRUE;
9191 
9192 	connp->conn_zoneid = getzoneid();
9193 
9194 	/*
9195 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9196 	 * administrative ops.  In these cases, we just need a normal conn_t
9197 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9198 	 * an error will be returned.
9199 	 */
9200 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9201 		connp->conn_rq = q;
9202 		connp->conn_wq = WR(q);
9203 	} else {
9204 		connp->conn_ulp = IPPROTO_SCTP;
9205 		connp->conn_rq = connp->conn_wq = NULL;
9206 	}
9207 	/* Non-zero default values */
9208 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9209 
9210 	/*
9211 	 * Make the conn globally visible to walkers
9212 	 */
9213 	mutex_enter(&connp->conn_lock);
9214 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9215 	mutex_exit(&connp->conn_lock);
9216 	ASSERT(connp->conn_ref == 1);
9217 
9218 	qprocson(q);
9219 
9220 	return (0);
9221 }
9222 
9223 /*
9224  * Change q_qinfo based on the value of isv6.
9225  * This can not called on an ill queue.
9226  * Note that there is no race since either q_qinfo works for conn queues - it
9227  * is just an optimization to enter the best wput routine directly.
9228  */
9229 void
9230 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9231 {
9232 	ASSERT(q->q_flag & QREADR);
9233 	ASSERT(WR(q)->q_next == NULL);
9234 	ASSERT(q->q_ptr != NULL);
9235 
9236 	if (minor == IPV6_MINOR)  {
9237 		if (bump_mib)
9238 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9239 		q->q_qinfo = &rinit_ipv6;
9240 		WR(q)->q_qinfo = &winit_ipv6;
9241 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9242 	} else {
9243 		if (bump_mib)
9244 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9245 		q->q_qinfo = &rinit;
9246 		WR(q)->q_qinfo = &winit;
9247 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9248 	}
9249 
9250 }
9251 
9252 /*
9253  * See if IPsec needs loading because of the options in mp.
9254  */
9255 static boolean_t
9256 ipsec_opt_present(mblk_t *mp)
9257 {
9258 	uint8_t *optcp, *next_optcp, *opt_endcp;
9259 	struct opthdr *opt;
9260 	struct T_opthdr *topt;
9261 	int opthdr_len;
9262 	t_uscalar_t optname, optlevel;
9263 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9264 	ipsec_req_t *ipsr;
9265 
9266 	/*
9267 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9268 	 * return TRUE.
9269 	 */
9270 
9271 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9272 	opt_endcp = optcp + tor->OPT_length;
9273 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9274 		opthdr_len = sizeof (struct T_opthdr);
9275 	} else {		/* O_OPTMGMT_REQ */
9276 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9277 		opthdr_len = sizeof (struct opthdr);
9278 	}
9279 	for (; optcp < opt_endcp; optcp = next_optcp) {
9280 		if (optcp + opthdr_len > opt_endcp)
9281 			return (B_FALSE);	/* Not enough option header. */
9282 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9283 			topt = (struct T_opthdr *)optcp;
9284 			optlevel = topt->level;
9285 			optname = topt->name;
9286 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9287 		} else {
9288 			opt = (struct opthdr *)optcp;
9289 			optlevel = opt->level;
9290 			optname = opt->name;
9291 			next_optcp = optcp + opthdr_len +
9292 			    _TPI_ALIGN_OPT(opt->len);
9293 		}
9294 		if ((next_optcp < optcp) || /* wraparound pointer space */
9295 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9296 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9297 			return (B_FALSE); /* bad option buffer */
9298 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9299 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9300 			/*
9301 			 * Check to see if it's an all-bypass or all-zeroes
9302 			 * IPsec request.  Don't bother loading IPsec if
9303 			 * the socket doesn't want to use it.  (A good example
9304 			 * is a bypass request.)
9305 			 *
9306 			 * Basically, if any of the non-NEVER bits are set,
9307 			 * load IPsec.
9308 			 */
9309 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9310 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9311 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9312 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9313 			    != 0)
9314 				return (B_TRUE);
9315 		}
9316 	}
9317 	return (B_FALSE);
9318 }
9319 
9320 /*
9321  * If conn is is waiting for ipsec to finish loading, kick it.
9322  */
9323 /* ARGSUSED */
9324 static void
9325 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9326 {
9327 	t_scalar_t	optreq_prim;
9328 	mblk_t		*mp;
9329 	cred_t		*cr;
9330 	int		err = 0;
9331 
9332 	/*
9333 	 * This function is called, after ipsec loading is complete.
9334 	 * Since IP checks exclusively and atomically (i.e it prevents
9335 	 * ipsec load from completing until ip_optcom_req completes)
9336 	 * whether ipsec load is complete, there cannot be a race with IP
9337 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9338 	 */
9339 	mutex_enter(&connp->conn_lock);
9340 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9341 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9342 		mp = connp->conn_ipsec_opt_mp;
9343 		connp->conn_ipsec_opt_mp = NULL;
9344 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9345 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9346 		mutex_exit(&connp->conn_lock);
9347 
9348 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9349 
9350 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9351 		if (optreq_prim == T_OPTMGMT_REQ) {
9352 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9353 			    &ip_opt_obj);
9354 		} else {
9355 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9356 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9357 			    &ip_opt_obj);
9358 		}
9359 		if (err != EINPROGRESS)
9360 			CONN_OPER_PENDING_DONE(connp);
9361 		return;
9362 	}
9363 	mutex_exit(&connp->conn_lock);
9364 }
9365 
9366 /*
9367  * Called from the ipsec_loader thread, outside any perimeter, to tell
9368  * ip qenable any of the queues waiting for the ipsec loader to
9369  * complete.
9370  *
9371  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9372  * are done with this lock held, so it's guaranteed that none of the
9373  * links will change along the way.
9374  */
9375 void
9376 ip_ipsec_load_complete()
9377 {
9378 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9379 }
9380 
9381 /*
9382  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9383  * determines the grp on which it has to become exclusive, queues the mp
9384  * and sq draining restarts the optmgmt
9385  */
9386 static boolean_t
9387 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9388 {
9389 	conn_t *connp;
9390 
9391 	/*
9392 	 * Take IPsec requests and treat them special.
9393 	 */
9394 	if (ipsec_opt_present(mp)) {
9395 		/* First check if IPsec is loaded. */
9396 		mutex_enter(&ipsec_loader_lock);
9397 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9398 			mutex_exit(&ipsec_loader_lock);
9399 			return (B_FALSE);
9400 		}
9401 		connp = Q_TO_CONN(q);
9402 		mutex_enter(&connp->conn_lock);
9403 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9404 
9405 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9406 		connp->conn_ipsec_opt_mp = mp;
9407 		mutex_exit(&connp->conn_lock);
9408 		mutex_exit(&ipsec_loader_lock);
9409 
9410 		ipsec_loader_loadnow();
9411 		return (B_TRUE);
9412 	}
9413 	return (B_FALSE);
9414 }
9415 
9416 /*
9417  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9418  * all of them are copied to the conn_t. If the req is "zero", the policy is
9419  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9420  * fields.
9421  * We keep only the latest setting of the policy and thus policy setting
9422  * is not incremental/cumulative.
9423  *
9424  * Requests to set policies with multiple alternative actions will
9425  * go through a different API.
9426  */
9427 int
9428 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9429 {
9430 	uint_t ah_req = 0;
9431 	uint_t esp_req = 0;
9432 	uint_t se_req = 0;
9433 	ipsec_selkey_t sel;
9434 	ipsec_act_t *actp = NULL;
9435 	uint_t nact;
9436 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9437 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9438 	ipsec_policy_root_t *pr;
9439 	ipsec_policy_head_t *ph;
9440 	int fam;
9441 	boolean_t is_pol_reset;
9442 	int error = 0;
9443 
9444 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9445 
9446 	/*
9447 	 * The IP_SEC_OPT option does not allow variable length parameters,
9448 	 * hence a request cannot be NULL.
9449 	 */
9450 	if (req == NULL)
9451 		return (EINVAL);
9452 
9453 	ah_req = req->ipsr_ah_req;
9454 	esp_req = req->ipsr_esp_req;
9455 	se_req = req->ipsr_self_encap_req;
9456 
9457 	/*
9458 	 * Are we dealing with a request to reset the policy (i.e.
9459 	 * zero requests).
9460 	 */
9461 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9462 	    (esp_req & REQ_MASK) == 0 &&
9463 	    (se_req & REQ_MASK) == 0);
9464 
9465 	if (!is_pol_reset) {
9466 		/*
9467 		 * If we couldn't load IPsec, fail with "protocol
9468 		 * not supported".
9469 		 * IPsec may not have been loaded for a request with zero
9470 		 * policies, so we don't fail in this case.
9471 		 */
9472 		mutex_enter(&ipsec_loader_lock);
9473 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9474 			mutex_exit(&ipsec_loader_lock);
9475 			return (EPROTONOSUPPORT);
9476 		}
9477 		mutex_exit(&ipsec_loader_lock);
9478 
9479 		/*
9480 		 * Test for valid requests. Invalid algorithms
9481 		 * need to be tested by IPSEC code because new
9482 		 * algorithms can be added dynamically.
9483 		 */
9484 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9485 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9486 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9487 			return (EINVAL);
9488 		}
9489 
9490 		/*
9491 		 * Only privileged users can issue these
9492 		 * requests.
9493 		 */
9494 		if (((ah_req & IPSEC_PREF_NEVER) ||
9495 		    (esp_req & IPSEC_PREF_NEVER) ||
9496 		    (se_req & IPSEC_PREF_NEVER)) &&
9497 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9498 			return (EPERM);
9499 		}
9500 
9501 		/*
9502 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9503 		 * are mutually exclusive.
9504 		 */
9505 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9506 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9507 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9508 			/* Both of them are set */
9509 			return (EINVAL);
9510 		}
9511 	}
9512 
9513 	mutex_enter(&connp->conn_lock);
9514 
9515 	/*
9516 	 * If we have already cached policies in ip_bind_connected*(), don't
9517 	 * let them change now. We cache policies for connections
9518 	 * whose src,dst [addr, port] is known.  The exception to this is
9519 	 * tunnels.  Tunnels are allowed to change policies after having
9520 	 * become fully bound.
9521 	 */
9522 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9523 		mutex_exit(&connp->conn_lock);
9524 		return (EINVAL);
9525 	}
9526 
9527 	/*
9528 	 * We have a zero policies, reset the connection policy if already
9529 	 * set. This will cause the connection to inherit the
9530 	 * global policy, if any.
9531 	 */
9532 	if (is_pol_reset) {
9533 		if (connp->conn_policy != NULL) {
9534 			IPPH_REFRELE(connp->conn_policy);
9535 			connp->conn_policy = NULL;
9536 		}
9537 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9538 		connp->conn_in_enforce_policy = B_FALSE;
9539 		connp->conn_out_enforce_policy = B_FALSE;
9540 		mutex_exit(&connp->conn_lock);
9541 		return (0);
9542 	}
9543 
9544 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9545 	if (ph == NULL)
9546 		goto enomem;
9547 
9548 	ipsec_actvec_from_req(req, &actp, &nact);
9549 	if (actp == NULL)
9550 		goto enomem;
9551 
9552 	/*
9553 	 * Always allocate IPv4 policy entries, since they can also
9554 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9555 	 */
9556 	bzero(&sel, sizeof (sel));
9557 	sel.ipsl_valid = IPSL_IPV4;
9558 
9559 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9560 	if (pin4 == NULL)
9561 		goto enomem;
9562 
9563 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9564 	if (pout4 == NULL)
9565 		goto enomem;
9566 
9567 	if (connp->conn_pkt_isv6) {
9568 		/*
9569 		 * We're looking at a v6 socket, also allocate the
9570 		 * v6-specific entries...
9571 		 */
9572 		sel.ipsl_valid = IPSL_IPV6;
9573 		pin6 = ipsec_policy_create(&sel, actp, nact,
9574 		    IPSEC_PRIO_SOCKET);
9575 		if (pin6 == NULL)
9576 			goto enomem;
9577 
9578 		pout6 = ipsec_policy_create(&sel, actp, nact,
9579 		    IPSEC_PRIO_SOCKET);
9580 		if (pout6 == NULL)
9581 			goto enomem;
9582 
9583 		/*
9584 		 * .. and file them away in the right place.
9585 		 */
9586 		fam = IPSEC_AF_V6;
9587 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9588 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9589 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9590 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9591 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9592 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9593 	}
9594 
9595 	ipsec_actvec_free(actp, nact);
9596 
9597 	/*
9598 	 * File the v4 policies.
9599 	 */
9600 	fam = IPSEC_AF_V4;
9601 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9602 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9603 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9604 
9605 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9606 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9607 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9608 
9609 	/*
9610 	 * If the requests need security, set enforce_policy.
9611 	 * If the requests are IPSEC_PREF_NEVER, one should
9612 	 * still set conn_out_enforce_policy so that an ipsec_out
9613 	 * gets attached in ip_wput. This is needed so that
9614 	 * for connections that we don't cache policy in ip_bind,
9615 	 * if global policy matches in ip_wput_attach_policy, we
9616 	 * don't wrongly inherit global policy. Similarly, we need
9617 	 * to set conn_in_enforce_policy also so that we don't verify
9618 	 * policy wrongly.
9619 	 */
9620 	if ((ah_req & REQ_MASK) != 0 ||
9621 	    (esp_req & REQ_MASK) != 0 ||
9622 	    (se_req & REQ_MASK) != 0) {
9623 		connp->conn_in_enforce_policy = B_TRUE;
9624 		connp->conn_out_enforce_policy = B_TRUE;
9625 		connp->conn_flags |= IPCL_CHECK_POLICY;
9626 	}
9627 
9628 	/*
9629 	 * Tunnels are allowed to set policy after having been fully bound.
9630 	 * If that's the case, cache policy here.
9631 	 */
9632 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9633 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9634 
9635 	mutex_exit(&connp->conn_lock);
9636 	return (error);
9637 #undef REQ_MASK
9638 
9639 	/*
9640 	 * Common memory-allocation-failure exit path.
9641 	 */
9642 enomem:
9643 	mutex_exit(&connp->conn_lock);
9644 	if (actp != NULL)
9645 		ipsec_actvec_free(actp, nact);
9646 	if (pin4 != NULL)
9647 		IPPOL_REFRELE(pin4);
9648 	if (pout4 != NULL)
9649 		IPPOL_REFRELE(pout4);
9650 	if (pin6 != NULL)
9651 		IPPOL_REFRELE(pin6);
9652 	if (pout6 != NULL)
9653 		IPPOL_REFRELE(pout6);
9654 	return (ENOMEM);
9655 }
9656 
9657 /*
9658  * Only for options that pass in an IP addr. Currently only V4 options
9659  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9660  * So this function assumes level is IPPROTO_IP
9661  */
9662 int
9663 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9664     mblk_t *first_mp)
9665 {
9666 	ipif_t *ipif = NULL;
9667 	int error;
9668 	ill_t *ill;
9669 
9670 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9671 
9672 	if (addr != INADDR_ANY || checkonly) {
9673 		ASSERT(connp != NULL);
9674 		if (option == IP_NEXTHOP) {
9675 			ipif =
9676 			    ipif_lookup_onlink_addr(addr, connp->conn_zoneid);
9677 		} else {
9678 			ipif = ipif_lookup_addr(addr, NULL, connp->conn_zoneid,
9679 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9680 			    &error);
9681 		}
9682 		if (ipif == NULL) {
9683 			if (error == EINPROGRESS)
9684 				return (error);
9685 			else if ((option == IP_MULTICAST_IF) ||
9686 			    (option == IP_NEXTHOP))
9687 				return (EHOSTUNREACH);
9688 			else
9689 				return (EINVAL);
9690 		} else if (checkonly) {
9691 			if (option == IP_MULTICAST_IF) {
9692 				ill = ipif->ipif_ill;
9693 				/* not supported by the virtual network iface */
9694 				if (IS_VNI(ill)) {
9695 					ipif_refrele(ipif);
9696 					return (EINVAL);
9697 				}
9698 			}
9699 			ipif_refrele(ipif);
9700 			return (0);
9701 		}
9702 		ill = ipif->ipif_ill;
9703 		mutex_enter(&connp->conn_lock);
9704 		mutex_enter(&ill->ill_lock);
9705 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9706 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9707 			mutex_exit(&ill->ill_lock);
9708 			mutex_exit(&connp->conn_lock);
9709 			ipif_refrele(ipif);
9710 			return (option == IP_MULTICAST_IF ?
9711 			    EHOSTUNREACH : EINVAL);
9712 		}
9713 	} else {
9714 		mutex_enter(&connp->conn_lock);
9715 	}
9716 
9717 	/* None of the options below are supported on the VNI */
9718 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9719 		mutex_exit(&ill->ill_lock);
9720 		mutex_exit(&connp->conn_lock);
9721 		ipif_refrele(ipif);
9722 		return (EINVAL);
9723 	}
9724 
9725 	switch (option) {
9726 	case IP_DONTFAILOVER_IF:
9727 		/*
9728 		 * This option is used by in.mpathd to ensure
9729 		 * that IPMP probe packets only go out on the
9730 		 * test interfaces. in.mpathd sets this option
9731 		 * on the non-failover interfaces.
9732 		 * For backward compatibility, this option
9733 		 * implicitly sets IP_MULTICAST_IF, as used
9734 		 * be done in bind(), so that ip_wput gets
9735 		 * this ipif to send mcast packets.
9736 		 */
9737 		if (ipif != NULL) {
9738 			ASSERT(addr != INADDR_ANY);
9739 			connp->conn_nofailover_ill = ipif->ipif_ill;
9740 			connp->conn_multicast_ipif = ipif;
9741 		} else {
9742 			ASSERT(addr == INADDR_ANY);
9743 			connp->conn_nofailover_ill = NULL;
9744 			connp->conn_multicast_ipif = NULL;
9745 		}
9746 		break;
9747 
9748 	case IP_MULTICAST_IF:
9749 		connp->conn_multicast_ipif = ipif;
9750 		break;
9751 	case IP_NEXTHOP:
9752 		connp->conn_nexthop_v4 = addr;
9753 		connp->conn_nexthop_set = B_TRUE;
9754 		break;
9755 	}
9756 
9757 	if (ipif != NULL) {
9758 		mutex_exit(&ill->ill_lock);
9759 		mutex_exit(&connp->conn_lock);
9760 		ipif_refrele(ipif);
9761 		return (0);
9762 	}
9763 	mutex_exit(&connp->conn_lock);
9764 	/* We succeded in cleared the option */
9765 	return (0);
9766 }
9767 
9768 /*
9769  * For options that pass in an ifindex specifying the ill. V6 options always
9770  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9771  */
9772 int
9773 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9774     int level, int option, mblk_t *first_mp)
9775 {
9776 	ill_t *ill = NULL;
9777 	int error = 0;
9778 
9779 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9780 	if (ifindex != 0) {
9781 		ASSERT(connp != NULL);
9782 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9783 		    first_mp, ip_restart_optmgmt, &error);
9784 		if (ill != NULL) {
9785 			if (checkonly) {
9786 				/* not supported by the virtual network iface */
9787 				if (IS_VNI(ill)) {
9788 					ill_refrele(ill);
9789 					return (EINVAL);
9790 				}
9791 				ill_refrele(ill);
9792 				return (0);
9793 			}
9794 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9795 			    0, NULL)) {
9796 				ill_refrele(ill);
9797 				ill = NULL;
9798 				mutex_enter(&connp->conn_lock);
9799 				goto setit;
9800 			}
9801 			mutex_enter(&connp->conn_lock);
9802 			mutex_enter(&ill->ill_lock);
9803 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9804 				mutex_exit(&ill->ill_lock);
9805 				mutex_exit(&connp->conn_lock);
9806 				ill_refrele(ill);
9807 				ill = NULL;
9808 				mutex_enter(&connp->conn_lock);
9809 			}
9810 			goto setit;
9811 		} else if (error == EINPROGRESS) {
9812 			return (error);
9813 		} else {
9814 			error = 0;
9815 		}
9816 	}
9817 	mutex_enter(&connp->conn_lock);
9818 setit:
9819 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9820 
9821 	/*
9822 	 * The options below assume that the ILL (if any) transmits and/or
9823 	 * receives traffic. Neither of which is true for the virtual network
9824 	 * interface, so fail setting these on a VNI.
9825 	 */
9826 	if (IS_VNI(ill)) {
9827 		ASSERT(ill != NULL);
9828 		mutex_exit(&ill->ill_lock);
9829 		mutex_exit(&connp->conn_lock);
9830 		ill_refrele(ill);
9831 		return (EINVAL);
9832 	}
9833 
9834 	if (level == IPPROTO_IP) {
9835 		switch (option) {
9836 		case IP_BOUND_IF:
9837 			connp->conn_incoming_ill = ill;
9838 			connp->conn_outgoing_ill = ill;
9839 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9840 			    0 : ifindex;
9841 			break;
9842 
9843 		case IP_XMIT_IF:
9844 			/*
9845 			 * Similar to IP_BOUND_IF, but this only
9846 			 * determines the outgoing interface for
9847 			 * unicast packets. Also no IRE_CACHE entry
9848 			 * is added for the destination of the
9849 			 * outgoing packets. This feature is needed
9850 			 * for mobile IP.
9851 			 */
9852 			connp->conn_xmit_if_ill = ill;
9853 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9854 			    0 : ifindex;
9855 			break;
9856 
9857 		case IP_MULTICAST_IF:
9858 			/*
9859 			 * This option is an internal special. The socket
9860 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9861 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9862 			 * specifies an ifindex and we try first on V6 ill's.
9863 			 * If we don't find one, we they try using on v4 ill's
9864 			 * intenally and we come here.
9865 			 */
9866 			if (!checkonly && ill != NULL) {
9867 				ipif_t	*ipif;
9868 				ipif = ill->ill_ipif;
9869 
9870 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9871 					mutex_exit(&ill->ill_lock);
9872 					mutex_exit(&connp->conn_lock);
9873 					ill_refrele(ill);
9874 					ill = NULL;
9875 					mutex_enter(&connp->conn_lock);
9876 				} else {
9877 					connp->conn_multicast_ipif = ipif;
9878 				}
9879 			}
9880 			break;
9881 		}
9882 	} else {
9883 		switch (option) {
9884 		case IPV6_BOUND_IF:
9885 			connp->conn_incoming_ill = ill;
9886 			connp->conn_outgoing_ill = ill;
9887 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9888 			    0 : ifindex;
9889 			break;
9890 
9891 		case IPV6_BOUND_PIF:
9892 			/*
9893 			 * Limit all transmit to this ill.
9894 			 * Unlike IPV6_BOUND_IF, using this option
9895 			 * prevents load spreading and failover from
9896 			 * happening when the interface is part of the
9897 			 * group. That's why we don't need to remember
9898 			 * the ifindex in orig_bound_ifindex as in
9899 			 * IPV6_BOUND_IF.
9900 			 */
9901 			connp->conn_outgoing_pill = ill;
9902 			break;
9903 
9904 		case IPV6_DONTFAILOVER_IF:
9905 			/*
9906 			 * This option is used by in.mpathd to ensure
9907 			 * that IPMP probe packets only go out on the
9908 			 * test interfaces. in.mpathd sets this option
9909 			 * on the non-failover interfaces.
9910 			 */
9911 			connp->conn_nofailover_ill = ill;
9912 			/*
9913 			 * For backward compatibility, this option
9914 			 * implicitly sets ip_multicast_ill as used in
9915 			 * IP_MULTICAST_IF so that ip_wput gets
9916 			 * this ipif to send mcast packets.
9917 			 */
9918 			connp->conn_multicast_ill = ill;
9919 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9920 			    0 : ifindex;
9921 			break;
9922 
9923 		case IPV6_MULTICAST_IF:
9924 			/*
9925 			 * Set conn_multicast_ill to be the IPv6 ill.
9926 			 * Set conn_multicast_ipif to be an IPv4 ipif
9927 			 * for ifindex to make IPv4 mapped addresses
9928 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9929 			 * Even if no IPv6 ill exists for the ifindex
9930 			 * we need to check for an IPv4 ifindex in order
9931 			 * for this to work with mapped addresses. In that
9932 			 * case only set conn_multicast_ipif.
9933 			 */
9934 			if (!checkonly) {
9935 				if (ifindex == 0) {
9936 					connp->conn_multicast_ill = NULL;
9937 					connp->conn_orig_multicast_ifindex = 0;
9938 					connp->conn_multicast_ipif = NULL;
9939 				} else if (ill != NULL) {
9940 					connp->conn_multicast_ill = ill;
9941 					connp->conn_orig_multicast_ifindex =
9942 					    ifindex;
9943 				}
9944 			}
9945 			break;
9946 		}
9947 	}
9948 
9949 	if (ill != NULL) {
9950 		mutex_exit(&ill->ill_lock);
9951 		mutex_exit(&connp->conn_lock);
9952 		ill_refrele(ill);
9953 		return (0);
9954 	}
9955 	mutex_exit(&connp->conn_lock);
9956 	/*
9957 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9958 	 * locate the ill and could not set the option (ifindex != 0)
9959 	 */
9960 	return (ifindex == 0 ? 0 : EINVAL);
9961 }
9962 
9963 /* This routine sets socket options. */
9964 /* ARGSUSED */
9965 int
9966 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9967     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9968     void *dummy, cred_t *cr, mblk_t *first_mp)
9969 {
9970 	int		*i1 = (int *)invalp;
9971 	conn_t		*connp = Q_TO_CONN(q);
9972 	int		error = 0;
9973 	boolean_t	checkonly;
9974 	ire_t		*ire;
9975 	boolean_t	found;
9976 
9977 	switch (optset_context) {
9978 
9979 	case SETFN_OPTCOM_CHECKONLY:
9980 		checkonly = B_TRUE;
9981 		/*
9982 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9983 		 * inlen != 0 implies value supplied and
9984 		 * 	we have to "pretend" to set it.
9985 		 * inlen == 0 implies that there is no
9986 		 * 	value part in T_CHECK request and just validation
9987 		 * done elsewhere should be enough, we just return here.
9988 		 */
9989 		if (inlen == 0) {
9990 			*outlenp = 0;
9991 			return (0);
9992 		}
9993 		break;
9994 	case SETFN_OPTCOM_NEGOTIATE:
9995 	case SETFN_UD_NEGOTIATE:
9996 	case SETFN_CONN_NEGOTIATE:
9997 		checkonly = B_FALSE;
9998 		break;
9999 	default:
10000 		/*
10001 		 * We should never get here
10002 		 */
10003 		*outlenp = 0;
10004 		return (EINVAL);
10005 	}
10006 
10007 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10008 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10009 
10010 	/*
10011 	 * For fixed length options, no sanity check
10012 	 * of passed in length is done. It is assumed *_optcom_req()
10013 	 * routines do the right thing.
10014 	 */
10015 
10016 	switch (level) {
10017 	case SOL_SOCKET:
10018 		/*
10019 		 * conn_lock protects the bitfields, and is used to
10020 		 * set the fields atomically.
10021 		 */
10022 		switch (name) {
10023 		case SO_BROADCAST:
10024 			if (!checkonly) {
10025 				/* TODO: use value someplace? */
10026 				mutex_enter(&connp->conn_lock);
10027 				connp->conn_broadcast = *i1 ? 1 : 0;
10028 				mutex_exit(&connp->conn_lock);
10029 			}
10030 			break;	/* goto sizeof (int) option return */
10031 		case SO_USELOOPBACK:
10032 			if (!checkonly) {
10033 				/* TODO: use value someplace? */
10034 				mutex_enter(&connp->conn_lock);
10035 				connp->conn_loopback = *i1 ? 1 : 0;
10036 				mutex_exit(&connp->conn_lock);
10037 			}
10038 			break;	/* goto sizeof (int) option return */
10039 		case SO_DONTROUTE:
10040 			if (!checkonly) {
10041 				mutex_enter(&connp->conn_lock);
10042 				connp->conn_dontroute = *i1 ? 1 : 0;
10043 				mutex_exit(&connp->conn_lock);
10044 			}
10045 			break;	/* goto sizeof (int) option return */
10046 		case SO_REUSEADDR:
10047 			if (!checkonly) {
10048 				mutex_enter(&connp->conn_lock);
10049 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10050 				mutex_exit(&connp->conn_lock);
10051 			}
10052 			break;	/* goto sizeof (int) option return */
10053 		case SO_PROTOTYPE:
10054 			if (!checkonly) {
10055 				mutex_enter(&connp->conn_lock);
10056 				connp->conn_proto = *i1;
10057 				mutex_exit(&connp->conn_lock);
10058 			}
10059 			break;	/* goto sizeof (int) option return */
10060 		case SO_ANON_MLP:
10061 			if (!checkonly) {
10062 				mutex_enter(&connp->conn_lock);
10063 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10064 				mutex_exit(&connp->conn_lock);
10065 			}
10066 			break;	/* goto sizeof (int) option return */
10067 		case SO_MAC_EXEMPT:
10068 			if (secpolicy_net_mac_aware(cr) != 0 ||
10069 			    IPCL_IS_BOUND(connp))
10070 				return (EACCES);
10071 			if (!checkonly) {
10072 				mutex_enter(&connp->conn_lock);
10073 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10074 				mutex_exit(&connp->conn_lock);
10075 			}
10076 			break;	/* goto sizeof (int) option return */
10077 		default:
10078 			/*
10079 			 * "soft" error (negative)
10080 			 * option not handled at this level
10081 			 * Note: Do not modify *outlenp
10082 			 */
10083 			return (-EINVAL);
10084 		}
10085 		break;
10086 	case IPPROTO_IP:
10087 		switch (name) {
10088 		case IP_NEXTHOP:
10089 		case IP_MULTICAST_IF:
10090 		case IP_DONTFAILOVER_IF: {
10091 			ipaddr_t addr = *i1;
10092 
10093 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10094 			    first_mp);
10095 			if (error != 0)
10096 				return (error);
10097 			break;	/* goto sizeof (int) option return */
10098 		}
10099 
10100 		case IP_MULTICAST_TTL:
10101 			/* Recorded in transport above IP */
10102 			*outvalp = *invalp;
10103 			*outlenp = sizeof (uchar_t);
10104 			return (0);
10105 		case IP_MULTICAST_LOOP:
10106 			if (!checkonly) {
10107 				mutex_enter(&connp->conn_lock);
10108 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10109 				mutex_exit(&connp->conn_lock);
10110 			}
10111 			*outvalp = *invalp;
10112 			*outlenp = sizeof (uchar_t);
10113 			return (0);
10114 		case IP_ADD_MEMBERSHIP:
10115 		case MCAST_JOIN_GROUP:
10116 		case IP_DROP_MEMBERSHIP:
10117 		case MCAST_LEAVE_GROUP: {
10118 			struct ip_mreq *mreqp;
10119 			struct group_req *greqp;
10120 			ire_t *ire;
10121 			boolean_t done = B_FALSE;
10122 			ipaddr_t group, ifaddr;
10123 			struct sockaddr_in *sin;
10124 			uint32_t *ifindexp;
10125 			boolean_t mcast_opt = B_TRUE;
10126 			mcast_record_t fmode;
10127 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10128 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10129 
10130 			switch (name) {
10131 			case IP_ADD_MEMBERSHIP:
10132 				mcast_opt = B_FALSE;
10133 				/* FALLTHRU */
10134 			case MCAST_JOIN_GROUP:
10135 				fmode = MODE_IS_EXCLUDE;
10136 				optfn = ip_opt_add_group;
10137 				break;
10138 
10139 			case IP_DROP_MEMBERSHIP:
10140 				mcast_opt = B_FALSE;
10141 				/* FALLTHRU */
10142 			case MCAST_LEAVE_GROUP:
10143 				fmode = MODE_IS_INCLUDE;
10144 				optfn = ip_opt_delete_group;
10145 				break;
10146 			}
10147 
10148 			if (mcast_opt) {
10149 				greqp = (struct group_req *)i1;
10150 				sin = (struct sockaddr_in *)&greqp->gr_group;
10151 				if (sin->sin_family != AF_INET) {
10152 					*outlenp = 0;
10153 					return (ENOPROTOOPT);
10154 				}
10155 				group = (ipaddr_t)sin->sin_addr.s_addr;
10156 				ifaddr = INADDR_ANY;
10157 				ifindexp = &greqp->gr_interface;
10158 			} else {
10159 				mreqp = (struct ip_mreq *)i1;
10160 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10161 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10162 				ifindexp = NULL;
10163 			}
10164 
10165 			/*
10166 			 * In the multirouting case, we need to replicate
10167 			 * the request on all interfaces that will take part
10168 			 * in replication.  We do so because multirouting is
10169 			 * reflective, thus we will probably receive multi-
10170 			 * casts on those interfaces.
10171 			 * The ip_multirt_apply_membership() succeeds if the
10172 			 * operation succeeds on at least one interface.
10173 			 */
10174 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10175 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10176 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10177 			if (ire != NULL) {
10178 				if (ire->ire_flags & RTF_MULTIRT) {
10179 					error = ip_multirt_apply_membership(
10180 					    optfn, ire, connp, checkonly, group,
10181 					    fmode, INADDR_ANY, first_mp);
10182 					done = B_TRUE;
10183 				}
10184 				ire_refrele(ire);
10185 			}
10186 			if (!done) {
10187 				error = optfn(connp, checkonly, group, ifaddr,
10188 				    ifindexp, fmode, INADDR_ANY, first_mp);
10189 			}
10190 			if (error) {
10191 				/*
10192 				 * EINPROGRESS is a soft error, needs retry
10193 				 * so don't make *outlenp zero.
10194 				 */
10195 				if (error != EINPROGRESS)
10196 					*outlenp = 0;
10197 				return (error);
10198 			}
10199 			/* OK return - copy input buffer into output buffer */
10200 			if (invalp != outvalp) {
10201 				/* don't trust bcopy for identical src/dst */
10202 				bcopy(invalp, outvalp, inlen);
10203 			}
10204 			*outlenp = inlen;
10205 			return (0);
10206 		}
10207 		case IP_BLOCK_SOURCE:
10208 		case IP_UNBLOCK_SOURCE:
10209 		case IP_ADD_SOURCE_MEMBERSHIP:
10210 		case IP_DROP_SOURCE_MEMBERSHIP:
10211 		case MCAST_BLOCK_SOURCE:
10212 		case MCAST_UNBLOCK_SOURCE:
10213 		case MCAST_JOIN_SOURCE_GROUP:
10214 		case MCAST_LEAVE_SOURCE_GROUP: {
10215 			struct ip_mreq_source *imreqp;
10216 			struct group_source_req *gsreqp;
10217 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10218 			uint32_t ifindex = 0;
10219 			mcast_record_t fmode;
10220 			struct sockaddr_in *sin;
10221 			ire_t *ire;
10222 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10223 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10224 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10225 
10226 			switch (name) {
10227 			case IP_BLOCK_SOURCE:
10228 				mcast_opt = B_FALSE;
10229 				/* FALLTHRU */
10230 			case MCAST_BLOCK_SOURCE:
10231 				fmode = MODE_IS_EXCLUDE;
10232 				optfn = ip_opt_add_group;
10233 				break;
10234 
10235 			case IP_UNBLOCK_SOURCE:
10236 				mcast_opt = B_FALSE;
10237 				/* FALLTHRU */
10238 			case MCAST_UNBLOCK_SOURCE:
10239 				fmode = MODE_IS_EXCLUDE;
10240 				optfn = ip_opt_delete_group;
10241 				break;
10242 
10243 			case IP_ADD_SOURCE_MEMBERSHIP:
10244 				mcast_opt = B_FALSE;
10245 				/* FALLTHRU */
10246 			case MCAST_JOIN_SOURCE_GROUP:
10247 				fmode = MODE_IS_INCLUDE;
10248 				optfn = ip_opt_add_group;
10249 				break;
10250 
10251 			case IP_DROP_SOURCE_MEMBERSHIP:
10252 				mcast_opt = B_FALSE;
10253 				/* FALLTHRU */
10254 			case MCAST_LEAVE_SOURCE_GROUP:
10255 				fmode = MODE_IS_INCLUDE;
10256 				optfn = ip_opt_delete_group;
10257 				break;
10258 			}
10259 
10260 			if (mcast_opt) {
10261 				gsreqp = (struct group_source_req *)i1;
10262 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10263 					*outlenp = 0;
10264 					return (ENOPROTOOPT);
10265 				}
10266 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10267 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10268 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10269 				src = (ipaddr_t)sin->sin_addr.s_addr;
10270 				ifindex = gsreqp->gsr_interface;
10271 			} else {
10272 				imreqp = (struct ip_mreq_source *)i1;
10273 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10274 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10275 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10276 			}
10277 
10278 			/*
10279 			 * In the multirouting case, we need to replicate
10280 			 * the request as noted in the mcast cases above.
10281 			 */
10282 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10283 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10284 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10285 			if (ire != NULL) {
10286 				if (ire->ire_flags & RTF_MULTIRT) {
10287 					error = ip_multirt_apply_membership(
10288 					    optfn, ire, connp, checkonly, grp,
10289 					    fmode, src, first_mp);
10290 					done = B_TRUE;
10291 				}
10292 				ire_refrele(ire);
10293 			}
10294 			if (!done) {
10295 				error = optfn(connp, checkonly, grp, ifaddr,
10296 				    &ifindex, fmode, src, first_mp);
10297 			}
10298 			if (error != 0) {
10299 				/*
10300 				 * EINPROGRESS is a soft error, needs retry
10301 				 * so don't make *outlenp zero.
10302 				 */
10303 				if (error != EINPROGRESS)
10304 					*outlenp = 0;
10305 				return (error);
10306 			}
10307 			/* OK return - copy input buffer into output buffer */
10308 			if (invalp != outvalp) {
10309 				bcopy(invalp, outvalp, inlen);
10310 			}
10311 			*outlenp = inlen;
10312 			return (0);
10313 		}
10314 		case IP_SEC_OPT:
10315 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10316 			if (error != 0) {
10317 				*outlenp = 0;
10318 				return (error);
10319 			}
10320 			break;
10321 		case IP_HDRINCL:
10322 		case IP_OPTIONS:
10323 		case T_IP_OPTIONS:
10324 		case IP_TOS:
10325 		case T_IP_TOS:
10326 		case IP_TTL:
10327 		case IP_RECVDSTADDR:
10328 		case IP_RECVOPTS:
10329 			/* OK return - copy input buffer into output buffer */
10330 			if (invalp != outvalp) {
10331 				/* don't trust bcopy for identical src/dst */
10332 				bcopy(invalp, outvalp, inlen);
10333 			}
10334 			*outlenp = inlen;
10335 			return (0);
10336 		case IP_RECVIF:
10337 			/* Retrieve the inbound interface index */
10338 			if (!checkonly) {
10339 				mutex_enter(&connp->conn_lock);
10340 				connp->conn_recvif = *i1 ? 1 : 0;
10341 				mutex_exit(&connp->conn_lock);
10342 			}
10343 			break;	/* goto sizeof (int) option return */
10344 		case IP_RECVSLLA:
10345 			/* Retrieve the source link layer address */
10346 			if (!checkonly) {
10347 				mutex_enter(&connp->conn_lock);
10348 				connp->conn_recvslla = *i1 ? 1 : 0;
10349 				mutex_exit(&connp->conn_lock);
10350 			}
10351 			break;	/* goto sizeof (int) option return */
10352 		case MRT_INIT:
10353 		case MRT_DONE:
10354 		case MRT_ADD_VIF:
10355 		case MRT_DEL_VIF:
10356 		case MRT_ADD_MFC:
10357 		case MRT_DEL_MFC:
10358 		case MRT_ASSERT:
10359 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10360 				*outlenp = 0;
10361 				return (error);
10362 			}
10363 			error = ip_mrouter_set((int)name, q, checkonly,
10364 			    (uchar_t *)invalp, inlen, first_mp);
10365 			if (error) {
10366 				*outlenp = 0;
10367 				return (error);
10368 			}
10369 			/* OK return - copy input buffer into output buffer */
10370 			if (invalp != outvalp) {
10371 				/* don't trust bcopy for identical src/dst */
10372 				bcopy(invalp, outvalp, inlen);
10373 			}
10374 			*outlenp = inlen;
10375 			return (0);
10376 		case IP_BOUND_IF:
10377 		case IP_XMIT_IF:
10378 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10379 			    level, name, first_mp);
10380 			if (error != 0)
10381 				return (error);
10382 			break; 		/* goto sizeof (int) option return */
10383 
10384 		case IP_UNSPEC_SRC:
10385 			/* Allow sending with a zero source address */
10386 			if (!checkonly) {
10387 				mutex_enter(&connp->conn_lock);
10388 				connp->conn_unspec_src = *i1 ? 1 : 0;
10389 				mutex_exit(&connp->conn_lock);
10390 			}
10391 			break;	/* goto sizeof (int) option return */
10392 		default:
10393 			/*
10394 			 * "soft" error (negative)
10395 			 * option not handled at this level
10396 			 * Note: Do not modify *outlenp
10397 			 */
10398 			return (-EINVAL);
10399 		}
10400 		break;
10401 	case IPPROTO_IPV6:
10402 		switch (name) {
10403 		case IPV6_BOUND_IF:
10404 		case IPV6_BOUND_PIF:
10405 		case IPV6_DONTFAILOVER_IF:
10406 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10407 			    level, name, first_mp);
10408 			if (error != 0)
10409 				return (error);
10410 			break; 		/* goto sizeof (int) option return */
10411 
10412 		case IPV6_MULTICAST_IF:
10413 			/*
10414 			 * The only possible errors are EINPROGRESS and
10415 			 * EINVAL. EINPROGRESS will be restarted and is not
10416 			 * a hard error. We call this option on both V4 and V6
10417 			 * If both return EINVAL, then this call returns
10418 			 * EINVAL. If at least one of them succeeds we
10419 			 * return success.
10420 			 */
10421 			found = B_FALSE;
10422 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10423 			    level, name, first_mp);
10424 			if (error == EINPROGRESS)
10425 				return (error);
10426 			if (error == 0)
10427 				found = B_TRUE;
10428 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10429 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10430 			if (error == 0)
10431 				found = B_TRUE;
10432 			if (!found)
10433 				return (error);
10434 			break; 		/* goto sizeof (int) option return */
10435 
10436 		case IPV6_MULTICAST_HOPS:
10437 			/* Recorded in transport above IP */
10438 			break;	/* goto sizeof (int) option return */
10439 		case IPV6_MULTICAST_LOOP:
10440 			if (!checkonly) {
10441 				mutex_enter(&connp->conn_lock);
10442 				connp->conn_multicast_loop = *i1;
10443 				mutex_exit(&connp->conn_lock);
10444 			}
10445 			break;	/* goto sizeof (int) option return */
10446 		case IPV6_JOIN_GROUP:
10447 		case MCAST_JOIN_GROUP:
10448 		case IPV6_LEAVE_GROUP:
10449 		case MCAST_LEAVE_GROUP: {
10450 			struct ipv6_mreq *ip_mreqp;
10451 			struct group_req *greqp;
10452 			ire_t *ire;
10453 			boolean_t done = B_FALSE;
10454 			in6_addr_t groupv6;
10455 			uint32_t ifindex;
10456 			boolean_t mcast_opt = B_TRUE;
10457 			mcast_record_t fmode;
10458 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10459 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10460 
10461 			switch (name) {
10462 			case IPV6_JOIN_GROUP:
10463 				mcast_opt = B_FALSE;
10464 				/* FALLTHRU */
10465 			case MCAST_JOIN_GROUP:
10466 				fmode = MODE_IS_EXCLUDE;
10467 				optfn = ip_opt_add_group_v6;
10468 				break;
10469 
10470 			case IPV6_LEAVE_GROUP:
10471 				mcast_opt = B_FALSE;
10472 				/* FALLTHRU */
10473 			case MCAST_LEAVE_GROUP:
10474 				fmode = MODE_IS_INCLUDE;
10475 				optfn = ip_opt_delete_group_v6;
10476 				break;
10477 			}
10478 
10479 			if (mcast_opt) {
10480 				struct sockaddr_in *sin;
10481 				struct sockaddr_in6 *sin6;
10482 				greqp = (struct group_req *)i1;
10483 				if (greqp->gr_group.ss_family == AF_INET) {
10484 					sin = (struct sockaddr_in *)
10485 					    &(greqp->gr_group);
10486 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10487 					    &groupv6);
10488 				} else {
10489 					sin6 = (struct sockaddr_in6 *)
10490 					    &(greqp->gr_group);
10491 					groupv6 = sin6->sin6_addr;
10492 				}
10493 				ifindex = greqp->gr_interface;
10494 			} else {
10495 				ip_mreqp = (struct ipv6_mreq *)i1;
10496 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10497 				ifindex = ip_mreqp->ipv6mr_interface;
10498 			}
10499 			/*
10500 			 * In the multirouting case, we need to replicate
10501 			 * the request on all interfaces that will take part
10502 			 * in replication.  We do so because multirouting is
10503 			 * reflective, thus we will probably receive multi-
10504 			 * casts on those interfaces.
10505 			 * The ip_multirt_apply_membership_v6() succeeds if
10506 			 * the operation succeeds on at least one interface.
10507 			 */
10508 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10509 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10510 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10511 			if (ire != NULL) {
10512 				if (ire->ire_flags & RTF_MULTIRT) {
10513 					error = ip_multirt_apply_membership_v6(
10514 					    optfn, ire, connp, checkonly,
10515 					    &groupv6, fmode, &ipv6_all_zeros,
10516 					    first_mp);
10517 					done = B_TRUE;
10518 				}
10519 				ire_refrele(ire);
10520 			}
10521 			if (!done) {
10522 				error = optfn(connp, checkonly, &groupv6,
10523 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10524 			}
10525 			if (error) {
10526 				/*
10527 				 * EINPROGRESS is a soft error, needs retry
10528 				 * so don't make *outlenp zero.
10529 				 */
10530 				if (error != EINPROGRESS)
10531 					*outlenp = 0;
10532 				return (error);
10533 			}
10534 			/* OK return - copy input buffer into output buffer */
10535 			if (invalp != outvalp) {
10536 				/* don't trust bcopy for identical src/dst */
10537 				bcopy(invalp, outvalp, inlen);
10538 			}
10539 			*outlenp = inlen;
10540 			return (0);
10541 		}
10542 		case MCAST_BLOCK_SOURCE:
10543 		case MCAST_UNBLOCK_SOURCE:
10544 		case MCAST_JOIN_SOURCE_GROUP:
10545 		case MCAST_LEAVE_SOURCE_GROUP: {
10546 			struct group_source_req *gsreqp;
10547 			in6_addr_t v6grp, v6src;
10548 			uint32_t ifindex;
10549 			mcast_record_t fmode;
10550 			ire_t *ire;
10551 			boolean_t done = B_FALSE;
10552 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10553 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10554 
10555 			switch (name) {
10556 			case MCAST_BLOCK_SOURCE:
10557 				fmode = MODE_IS_EXCLUDE;
10558 				optfn = ip_opt_add_group_v6;
10559 				break;
10560 			case MCAST_UNBLOCK_SOURCE:
10561 				fmode = MODE_IS_EXCLUDE;
10562 				optfn = ip_opt_delete_group_v6;
10563 				break;
10564 			case MCAST_JOIN_SOURCE_GROUP:
10565 				fmode = MODE_IS_INCLUDE;
10566 				optfn = ip_opt_add_group_v6;
10567 				break;
10568 			case MCAST_LEAVE_SOURCE_GROUP:
10569 				fmode = MODE_IS_INCLUDE;
10570 				optfn = ip_opt_delete_group_v6;
10571 				break;
10572 			}
10573 
10574 			gsreqp = (struct group_source_req *)i1;
10575 			ifindex = gsreqp->gsr_interface;
10576 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10577 				struct sockaddr_in *s;
10578 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10579 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10580 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10581 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10582 			} else {
10583 				struct sockaddr_in6 *s6;
10584 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10585 				v6grp = s6->sin6_addr;
10586 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10587 				v6src = s6->sin6_addr;
10588 			}
10589 
10590 			/*
10591 			 * In the multirouting case, we need to replicate
10592 			 * the request as noted in the mcast cases above.
10593 			 */
10594 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10595 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10596 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10597 			if (ire != NULL) {
10598 				if (ire->ire_flags & RTF_MULTIRT) {
10599 					error = ip_multirt_apply_membership_v6(
10600 					    optfn, ire, connp, checkonly,
10601 					    &v6grp, fmode, &v6src, first_mp);
10602 					done = B_TRUE;
10603 				}
10604 				ire_refrele(ire);
10605 			}
10606 			if (!done) {
10607 				error = optfn(connp, checkonly, &v6grp,
10608 				    ifindex, fmode, &v6src, first_mp);
10609 			}
10610 			if (error != 0) {
10611 				/*
10612 				 * EINPROGRESS is a soft error, needs retry
10613 				 * so don't make *outlenp zero.
10614 				 */
10615 				if (error != EINPROGRESS)
10616 					*outlenp = 0;
10617 				return (error);
10618 			}
10619 			/* OK return - copy input buffer into output buffer */
10620 			if (invalp != outvalp) {
10621 				bcopy(invalp, outvalp, inlen);
10622 			}
10623 			*outlenp = inlen;
10624 			return (0);
10625 		}
10626 		case IPV6_UNICAST_HOPS:
10627 			/* Recorded in transport above IP */
10628 			break;	/* goto sizeof (int) option return */
10629 		case IPV6_UNSPEC_SRC:
10630 			/* Allow sending with a zero source address */
10631 			if (!checkonly) {
10632 				mutex_enter(&connp->conn_lock);
10633 				connp->conn_unspec_src = *i1 ? 1 : 0;
10634 				mutex_exit(&connp->conn_lock);
10635 			}
10636 			break;	/* goto sizeof (int) option return */
10637 		case IPV6_RECVPKTINFO:
10638 			if (!checkonly) {
10639 				mutex_enter(&connp->conn_lock);
10640 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10641 				mutex_exit(&connp->conn_lock);
10642 			}
10643 			break;	/* goto sizeof (int) option return */
10644 		case IPV6_RECVTCLASS:
10645 			if (!checkonly) {
10646 				if (*i1 < 0 || *i1 > 1) {
10647 					return (EINVAL);
10648 				}
10649 				mutex_enter(&connp->conn_lock);
10650 				connp->conn_ipv6_recvtclass = *i1;
10651 				mutex_exit(&connp->conn_lock);
10652 			}
10653 			break;
10654 		case IPV6_RECVPATHMTU:
10655 			if (!checkonly) {
10656 				if (*i1 < 0 || *i1 > 1) {
10657 					return (EINVAL);
10658 				}
10659 				mutex_enter(&connp->conn_lock);
10660 				connp->conn_ipv6_recvpathmtu = *i1;
10661 				mutex_exit(&connp->conn_lock);
10662 			}
10663 			break;
10664 		case IPV6_RECVHOPLIMIT:
10665 			if (!checkonly) {
10666 				mutex_enter(&connp->conn_lock);
10667 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10668 				mutex_exit(&connp->conn_lock);
10669 			}
10670 			break;	/* goto sizeof (int) option return */
10671 		case IPV6_RECVHOPOPTS:
10672 			if (!checkonly) {
10673 				mutex_enter(&connp->conn_lock);
10674 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10675 				mutex_exit(&connp->conn_lock);
10676 			}
10677 			break;	/* goto sizeof (int) option return */
10678 		case IPV6_RECVDSTOPTS:
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			break;	/* goto sizeof (int) option return */
10685 		case IPV6_RECVRTHDR:
10686 			if (!checkonly) {
10687 				mutex_enter(&connp->conn_lock);
10688 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10689 				mutex_exit(&connp->conn_lock);
10690 			}
10691 			break;	/* goto sizeof (int) option return */
10692 		case IPV6_RECVRTHDRDSTOPTS:
10693 			if (!checkonly) {
10694 				mutex_enter(&connp->conn_lock);
10695 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10696 				mutex_exit(&connp->conn_lock);
10697 			}
10698 			break;	/* goto sizeof (int) option return */
10699 		case IPV6_PKTINFO:
10700 			if (inlen == 0)
10701 				return (-EINVAL);	/* clearing option */
10702 			error = ip6_set_pktinfo(cr, connp,
10703 			    (struct in6_pktinfo *)invalp, first_mp);
10704 			if (error != 0)
10705 				*outlenp = 0;
10706 			else
10707 				*outlenp = inlen;
10708 			return (error);
10709 		case IPV6_NEXTHOP: {
10710 			struct sockaddr_in6 *sin6;
10711 
10712 			/* Verify that the nexthop is reachable */
10713 			if (inlen == 0)
10714 				return (-EINVAL);	/* clearing option */
10715 
10716 			sin6 = (struct sockaddr_in6 *)invalp;
10717 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10718 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10719 			    NULL, MATCH_IRE_DEFAULT);
10720 
10721 			if (ire == NULL) {
10722 				*outlenp = 0;
10723 				return (EHOSTUNREACH);
10724 			}
10725 			ire_refrele(ire);
10726 			return (-EINVAL);
10727 		}
10728 		case IPV6_SEC_OPT:
10729 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10730 			if (error != 0) {
10731 				*outlenp = 0;
10732 				return (error);
10733 			}
10734 			break;
10735 		case IPV6_SRC_PREFERENCES: {
10736 			/*
10737 			 * This is implemented strictly in the ip module
10738 			 * (here and in tcp_opt_*() to accomodate tcp
10739 			 * sockets).  Modules above ip pass this option
10740 			 * down here since ip is the only one that needs to
10741 			 * be aware of source address preferences.
10742 			 *
10743 			 * This socket option only affects connected
10744 			 * sockets that haven't already bound to a specific
10745 			 * IPv6 address.  In other words, sockets that
10746 			 * don't call bind() with an address other than the
10747 			 * unspecified address and that call connect().
10748 			 * ip_bind_connected_v6() passes these preferences
10749 			 * to the ipif_select_source_v6() function.
10750 			 */
10751 			if (inlen != sizeof (uint32_t))
10752 				return (EINVAL);
10753 			error = ip6_set_src_preferences(connp,
10754 			    *(uint32_t *)invalp);
10755 			if (error != 0) {
10756 				*outlenp = 0;
10757 				return (error);
10758 			} else {
10759 				*outlenp = sizeof (uint32_t);
10760 			}
10761 			break;
10762 		}
10763 		case IPV6_V6ONLY:
10764 			if (*i1 < 0 || *i1 > 1) {
10765 				return (EINVAL);
10766 			}
10767 			mutex_enter(&connp->conn_lock);
10768 			connp->conn_ipv6_v6only = *i1;
10769 			mutex_exit(&connp->conn_lock);
10770 			break;
10771 		default:
10772 			return (-EINVAL);
10773 		}
10774 		break;
10775 	default:
10776 		/*
10777 		 * "soft" error (negative)
10778 		 * option not handled at this level
10779 		 * Note: Do not modify *outlenp
10780 		 */
10781 		return (-EINVAL);
10782 	}
10783 	/*
10784 	 * Common case of return from an option that is sizeof (int)
10785 	 */
10786 	*(int *)outvalp = *i1;
10787 	*outlenp = sizeof (int);
10788 	return (0);
10789 }
10790 
10791 /*
10792  * This routine gets default values of certain options whose default
10793  * values are maintained by protocol specific code
10794  */
10795 /* ARGSUSED */
10796 int
10797 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10798 {
10799 	int *i1 = (int *)ptr;
10800 
10801 	switch (level) {
10802 	case IPPROTO_IP:
10803 		switch (name) {
10804 		case IP_MULTICAST_TTL:
10805 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10806 			return (sizeof (uchar_t));
10807 		case IP_MULTICAST_LOOP:
10808 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10809 			return (sizeof (uchar_t));
10810 		default:
10811 			return (-1);
10812 		}
10813 	case IPPROTO_IPV6:
10814 		switch (name) {
10815 		case IPV6_UNICAST_HOPS:
10816 			*i1 = ipv6_def_hops;
10817 			return (sizeof (int));
10818 		case IPV6_MULTICAST_HOPS:
10819 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10820 			return (sizeof (int));
10821 		case IPV6_MULTICAST_LOOP:
10822 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10823 			return (sizeof (int));
10824 		case IPV6_V6ONLY:
10825 			*i1 = 1;
10826 			return (sizeof (int));
10827 		default:
10828 			return (-1);
10829 		}
10830 	default:
10831 		return (-1);
10832 	}
10833 	/* NOTREACHED */
10834 }
10835 
10836 /*
10837  * Given a destination address and a pointer to where to put the information
10838  * this routine fills in the mtuinfo.
10839  */
10840 int
10841 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10842     struct ip6_mtuinfo *mtuinfo)
10843 {
10844 	ire_t *ire;
10845 
10846 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10847 		return (-1);
10848 
10849 	bzero(mtuinfo, sizeof (*mtuinfo));
10850 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10851 	mtuinfo->ip6m_addr.sin6_port = port;
10852 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10853 
10854 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
10855 	if (ire != NULL) {
10856 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10857 		ire_refrele(ire);
10858 	} else {
10859 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10860 	}
10861 	return (sizeof (struct ip6_mtuinfo));
10862 }
10863 
10864 /*
10865  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10866  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10867  * isn't.  This doesn't matter as the error checking is done properly for the
10868  * other MRT options coming in through ip_opt_set.
10869  */
10870 int
10871 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10872 {
10873 	conn_t		*connp = Q_TO_CONN(q);
10874 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10875 
10876 	switch (level) {
10877 	case IPPROTO_IP:
10878 		switch (name) {
10879 		case MRT_VERSION:
10880 		case MRT_ASSERT:
10881 			(void) ip_mrouter_get(name, q, ptr);
10882 			return (sizeof (int));
10883 		case IP_SEC_OPT:
10884 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10885 		case IP_NEXTHOP:
10886 			if (connp->conn_nexthop_set) {
10887 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10888 				return (sizeof (ipaddr_t));
10889 			} else
10890 				return (0);
10891 		default:
10892 			break;
10893 		}
10894 		break;
10895 	case IPPROTO_IPV6:
10896 		switch (name) {
10897 		case IPV6_SEC_OPT:
10898 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10899 		case IPV6_SRC_PREFERENCES: {
10900 			return (ip6_get_src_preferences(connp,
10901 			    (uint32_t *)ptr));
10902 		}
10903 		case IPV6_V6ONLY:
10904 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10905 			return (sizeof (int));
10906 		case IPV6_PATHMTU:
10907 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10908 				(struct ip6_mtuinfo *)ptr));
10909 		default:
10910 			break;
10911 		}
10912 		break;
10913 	default:
10914 		break;
10915 	}
10916 	return (-1);
10917 }
10918 
10919 /* Named Dispatch routine to get a current value out of our parameter table. */
10920 /* ARGSUSED */
10921 static int
10922 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10923 {
10924 	ipparam_t *ippa = (ipparam_t *)cp;
10925 
10926 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10927 	return (0);
10928 }
10929 
10930 /* ARGSUSED */
10931 static int
10932 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10933 {
10934 
10935 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10936 	return (0);
10937 }
10938 
10939 /*
10940  * Set ip{,6}_forwarding values.  This means walking through all of the
10941  * ill's and toggling their forwarding values.
10942  */
10943 /* ARGSUSED */
10944 static int
10945 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10946 {
10947 	long new_value;
10948 	int *forwarding_value = (int *)cp;
10949 	ill_t *walker;
10950 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10951 	ill_walk_context_t ctx;
10952 
10953 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10954 	    new_value < 0 || new_value > 1) {
10955 		return (EINVAL);
10956 	}
10957 
10958 	*forwarding_value = new_value;
10959 
10960 	/*
10961 	 * Regardless of the current value of ip_forwarding, set all per-ill
10962 	 * values of ip_forwarding to the value being set.
10963 	 *
10964 	 * Bring all the ill's up to date with the new global value.
10965 	 */
10966 	rw_enter(&ill_g_lock, RW_READER);
10967 
10968 	if (isv6)
10969 		walker = ILL_START_WALK_V6(&ctx);
10970 	else
10971 		walker = ILL_START_WALK_V4(&ctx);
10972 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10973 		(void) ill_forward_set(q, mp, (new_value != 0),
10974 		    (caddr_t)walker);
10975 	}
10976 	rw_exit(&ill_g_lock);
10977 
10978 	return (0);
10979 }
10980 
10981 /*
10982  * Walk through the param array specified registering each element with the
10983  * Named Dispatch handler. This is called only during init. So it is ok
10984  * not to acquire any locks
10985  */
10986 static boolean_t
10987 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10988     ipndp_t *ipnd, size_t ipnd_cnt)
10989 {
10990 	for (; ippa_cnt-- > 0; ippa++) {
10991 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10992 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10993 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10994 				nd_free(&ip_g_nd);
10995 				return (B_FALSE);
10996 			}
10997 		}
10998 	}
10999 
11000 	for (; ipnd_cnt-- > 0; ipnd++) {
11001 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11002 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11003 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11004 			    ipnd->ip_ndp_data)) {
11005 				nd_free(&ip_g_nd);
11006 				return (B_FALSE);
11007 			}
11008 		}
11009 	}
11010 
11011 	return (B_TRUE);
11012 }
11013 
11014 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11015 /* ARGSUSED */
11016 static int
11017 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11018 {
11019 	long		new_value;
11020 	ipparam_t	*ippa = (ipparam_t *)cp;
11021 
11022 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11023 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11024 		return (EINVAL);
11025 	}
11026 	ippa->ip_param_value = new_value;
11027 	return (0);
11028 }
11029 
11030 /*
11031  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11032  * When an ipf is passed here for the first time, if
11033  * we already have in-order fragments on the queue, we convert from the fast-
11034  * path reassembly scheme to the hard-case scheme.  From then on, additional
11035  * fragments are reassembled here.  We keep track of the start and end offsets
11036  * of each piece, and the number of holes in the chain.  When the hole count
11037  * goes to zero, we are done!
11038  *
11039  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11040  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11041  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11042  * after the call to ip_reassemble().
11043  */
11044 int
11045 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11046     size_t msg_len)
11047 {
11048 	uint_t	end;
11049 	mblk_t	*next_mp;
11050 	mblk_t	*mp1;
11051 	uint_t	offset;
11052 	boolean_t incr_dups = B_TRUE;
11053 	boolean_t offset_zero_seen = B_FALSE;
11054 	boolean_t pkt_boundary_checked = B_FALSE;
11055 
11056 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11057 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11058 
11059 	/* Add in byte count */
11060 	ipf->ipf_count += msg_len;
11061 	if (ipf->ipf_end) {
11062 		/*
11063 		 * We were part way through in-order reassembly, but now there
11064 		 * is a hole.  We walk through messages already queued, and
11065 		 * mark them for hard case reassembly.  We know that up till
11066 		 * now they were in order starting from offset zero.
11067 		 */
11068 		offset = 0;
11069 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11070 			IP_REASS_SET_START(mp1, offset);
11071 			if (offset == 0) {
11072 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11073 				offset = -ipf->ipf_nf_hdr_len;
11074 			}
11075 			offset += mp1->b_wptr - mp1->b_rptr;
11076 			IP_REASS_SET_END(mp1, offset);
11077 		}
11078 		/* One hole at the end. */
11079 		ipf->ipf_hole_cnt = 1;
11080 		/* Brand it as a hard case, forever. */
11081 		ipf->ipf_end = 0;
11082 	}
11083 	/* Walk through all the new pieces. */
11084 	do {
11085 		end = start + (mp->b_wptr - mp->b_rptr);
11086 		/*
11087 		 * If start is 0, decrease 'end' only for the first mblk of
11088 		 * the fragment. Otherwise 'end' can get wrong value in the
11089 		 * second pass of the loop if first mblk is exactly the
11090 		 * size of ipf_nf_hdr_len.
11091 		 */
11092 		if (start == 0 && !offset_zero_seen) {
11093 			/* First segment */
11094 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11095 			end -= ipf->ipf_nf_hdr_len;
11096 			offset_zero_seen = B_TRUE;
11097 		}
11098 		next_mp = mp->b_cont;
11099 		/*
11100 		 * We are checking to see if there is any interesing data
11101 		 * to process.  If there isn't and the mblk isn't the
11102 		 * one which carries the unfragmentable header then we
11103 		 * drop it.  It's possible to have just the unfragmentable
11104 		 * header come through without any data.  That needs to be
11105 		 * saved.
11106 		 *
11107 		 * If the assert at the top of this function holds then the
11108 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11109 		 * is infrequently traveled enough that the test is left in
11110 		 * to protect against future code changes which break that
11111 		 * invariant.
11112 		 */
11113 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11114 			/* Empty.  Blast it. */
11115 			IP_REASS_SET_START(mp, 0);
11116 			IP_REASS_SET_END(mp, 0);
11117 			/*
11118 			 * If the ipf points to the mblk we are about to free,
11119 			 * update ipf to point to the next mblk (or NULL
11120 			 * if none).
11121 			 */
11122 			if (ipf->ipf_mp->b_cont == mp)
11123 				ipf->ipf_mp->b_cont = next_mp;
11124 			freeb(mp);
11125 			continue;
11126 		}
11127 		mp->b_cont = NULL;
11128 		IP_REASS_SET_START(mp, start);
11129 		IP_REASS_SET_END(mp, end);
11130 		if (!ipf->ipf_tail_mp) {
11131 			ipf->ipf_tail_mp = mp;
11132 			ipf->ipf_mp->b_cont = mp;
11133 			if (start == 0 || !more) {
11134 				ipf->ipf_hole_cnt = 1;
11135 				/*
11136 				 * if the first fragment comes in more than one
11137 				 * mblk, this loop will be executed for each
11138 				 * mblk. Need to adjust hole count so exiting
11139 				 * this routine will leave hole count at 1.
11140 				 */
11141 				if (next_mp)
11142 					ipf->ipf_hole_cnt++;
11143 			} else
11144 				ipf->ipf_hole_cnt = 2;
11145 			continue;
11146 		} else if (ipf->ipf_last_frag_seen && !more &&
11147 			    !pkt_boundary_checked) {
11148 			/*
11149 			 * We check datagram boundary only if this fragment
11150 			 * claims to be the last fragment and we have seen a
11151 			 * last fragment in the past too. We do this only
11152 			 * once for a given fragment.
11153 			 *
11154 			 * start cannot be 0 here as fragments with start=0
11155 			 * and MF=0 gets handled as a complete packet. These
11156 			 * fragments should not reach here.
11157 			 */
11158 
11159 			if (start + msgdsize(mp) !=
11160 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11161 				/*
11162 				 * We have two fragments both of which claim
11163 				 * to be the last fragment but gives conflicting
11164 				 * information about the whole datagram size.
11165 				 * Something fishy is going on. Drop the
11166 				 * fragment and free up the reassembly list.
11167 				 */
11168 				return (IP_REASS_FAILED);
11169 			}
11170 
11171 			/*
11172 			 * We shouldn't come to this code block again for this
11173 			 * particular fragment.
11174 			 */
11175 			pkt_boundary_checked = B_TRUE;
11176 		}
11177 
11178 		/* New stuff at or beyond tail? */
11179 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11180 		if (start >= offset) {
11181 			if (ipf->ipf_last_frag_seen) {
11182 				/* current fragment is beyond last fragment */
11183 				return (IP_REASS_FAILED);
11184 			}
11185 			/* Link it on end. */
11186 			ipf->ipf_tail_mp->b_cont = mp;
11187 			ipf->ipf_tail_mp = mp;
11188 			if (more) {
11189 				if (start != offset)
11190 					ipf->ipf_hole_cnt++;
11191 			} else if (start == offset && next_mp == NULL)
11192 					ipf->ipf_hole_cnt--;
11193 			continue;
11194 		}
11195 		mp1 = ipf->ipf_mp->b_cont;
11196 		offset = IP_REASS_START(mp1);
11197 		/* New stuff at the front? */
11198 		if (start < offset) {
11199 			if (start == 0) {
11200 				if (end >= offset) {
11201 					/* Nailed the hole at the begining. */
11202 					ipf->ipf_hole_cnt--;
11203 				}
11204 			} else if (end < offset) {
11205 				/*
11206 				 * A hole, stuff, and a hole where there used
11207 				 * to be just a hole.
11208 				 */
11209 				ipf->ipf_hole_cnt++;
11210 			}
11211 			mp->b_cont = mp1;
11212 			/* Check for overlap. */
11213 			while (end > offset) {
11214 				if (end < IP_REASS_END(mp1)) {
11215 					mp->b_wptr -= end - offset;
11216 					IP_REASS_SET_END(mp, offset);
11217 					if (ill->ill_isv6) {
11218 						BUMP_MIB(ill->ill_ip6_mib,
11219 						    ipv6ReasmPartDups);
11220 					} else {
11221 						BUMP_MIB(&ip_mib,
11222 						    ipReasmPartDups);
11223 					}
11224 					break;
11225 				}
11226 				/* Did we cover another hole? */
11227 				if ((mp1->b_cont &&
11228 				    IP_REASS_END(mp1) !=
11229 				    IP_REASS_START(mp1->b_cont) &&
11230 				    end >= IP_REASS_START(mp1->b_cont)) ||
11231 				    (!ipf->ipf_last_frag_seen && !more)) {
11232 					ipf->ipf_hole_cnt--;
11233 				}
11234 				/* Clip out mp1. */
11235 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11236 					/*
11237 					 * After clipping out mp1, this guy
11238 					 * is now hanging off the end.
11239 					 */
11240 					ipf->ipf_tail_mp = mp;
11241 				}
11242 				IP_REASS_SET_START(mp1, 0);
11243 				IP_REASS_SET_END(mp1, 0);
11244 				/* Subtract byte count */
11245 				ipf->ipf_count -= mp1->b_datap->db_lim -
11246 				    mp1->b_datap->db_base;
11247 				freeb(mp1);
11248 				if (ill->ill_isv6) {
11249 					BUMP_MIB(ill->ill_ip6_mib,
11250 					    ipv6ReasmPartDups);
11251 				} else {
11252 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11253 				}
11254 				mp1 = mp->b_cont;
11255 				if (!mp1)
11256 					break;
11257 				offset = IP_REASS_START(mp1);
11258 			}
11259 			ipf->ipf_mp->b_cont = mp;
11260 			continue;
11261 		}
11262 		/*
11263 		 * The new piece starts somewhere between the start of the head
11264 		 * and before the end of the tail.
11265 		 */
11266 		for (; mp1; mp1 = mp1->b_cont) {
11267 			offset = IP_REASS_END(mp1);
11268 			if (start < offset) {
11269 				if (end <= offset) {
11270 					/* Nothing new. */
11271 					IP_REASS_SET_START(mp, 0);
11272 					IP_REASS_SET_END(mp, 0);
11273 					/* Subtract byte count */
11274 					ipf->ipf_count -= mp->b_datap->db_lim -
11275 					    mp->b_datap->db_base;
11276 					if (incr_dups) {
11277 						ipf->ipf_num_dups++;
11278 						incr_dups = B_FALSE;
11279 					}
11280 					freeb(mp);
11281 					if (ill->ill_isv6) {
11282 						BUMP_MIB(ill->ill_ip6_mib,
11283 						    ipv6ReasmDuplicates);
11284 					} else {
11285 						BUMP_MIB(&ip_mib,
11286 						    ipReasmDuplicates);
11287 					}
11288 					break;
11289 				}
11290 				/*
11291 				 * Trim redundant stuff off beginning of new
11292 				 * piece.
11293 				 */
11294 				IP_REASS_SET_START(mp, offset);
11295 				mp->b_rptr += offset - start;
11296 				if (ill->ill_isv6) {
11297 					BUMP_MIB(ill->ill_ip6_mib,
11298 					    ipv6ReasmPartDups);
11299 				} else {
11300 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11301 				}
11302 				start = offset;
11303 				if (!mp1->b_cont) {
11304 					/*
11305 					 * After trimming, this guy is now
11306 					 * hanging off the end.
11307 					 */
11308 					mp1->b_cont = mp;
11309 					ipf->ipf_tail_mp = mp;
11310 					if (!more) {
11311 						ipf->ipf_hole_cnt--;
11312 					}
11313 					break;
11314 				}
11315 			}
11316 			if (start >= IP_REASS_START(mp1->b_cont))
11317 				continue;
11318 			/* Fill a hole */
11319 			if (start > offset)
11320 				ipf->ipf_hole_cnt++;
11321 			mp->b_cont = mp1->b_cont;
11322 			mp1->b_cont = mp;
11323 			mp1 = mp->b_cont;
11324 			offset = IP_REASS_START(mp1);
11325 			if (end >= offset) {
11326 				ipf->ipf_hole_cnt--;
11327 				/* Check for overlap. */
11328 				while (end > offset) {
11329 					if (end < IP_REASS_END(mp1)) {
11330 						mp->b_wptr -= end - offset;
11331 						IP_REASS_SET_END(mp, offset);
11332 						/*
11333 						 * TODO we might bump
11334 						 * this up twice if there is
11335 						 * overlap at both ends.
11336 						 */
11337 						if (ill->ill_isv6) {
11338 							BUMP_MIB(
11339 							    ill->ill_ip6_mib,
11340 							    ipv6ReasmPartDups);
11341 						} else {
11342 							BUMP_MIB(&ip_mib,
11343 							    ipReasmPartDups);
11344 						}
11345 						break;
11346 					}
11347 					/* Did we cover another hole? */
11348 					if ((mp1->b_cont &&
11349 					    IP_REASS_END(mp1)
11350 					    != IP_REASS_START(mp1->b_cont) &&
11351 					    end >=
11352 					    IP_REASS_START(mp1->b_cont)) ||
11353 					    (!ipf->ipf_last_frag_seen &&
11354 					    !more)) {
11355 						ipf->ipf_hole_cnt--;
11356 					}
11357 					/* Clip out mp1. */
11358 					if ((mp->b_cont = mp1->b_cont) ==
11359 					    NULL) {
11360 						/*
11361 						 * After clipping out mp1,
11362 						 * this guy is now hanging
11363 						 * off the end.
11364 						 */
11365 						ipf->ipf_tail_mp = mp;
11366 					}
11367 					IP_REASS_SET_START(mp1, 0);
11368 					IP_REASS_SET_END(mp1, 0);
11369 					/* Subtract byte count */
11370 					ipf->ipf_count -=
11371 					    mp1->b_datap->db_lim -
11372 					    mp1->b_datap->db_base;
11373 					freeb(mp1);
11374 					if (ill->ill_isv6) {
11375 						BUMP_MIB(ill->ill_ip6_mib,
11376 						    ipv6ReasmPartDups);
11377 					} else {
11378 						BUMP_MIB(&ip_mib,
11379 						    ipReasmPartDups);
11380 					}
11381 					mp1 = mp->b_cont;
11382 					if (!mp1)
11383 						break;
11384 					offset = IP_REASS_START(mp1);
11385 				}
11386 			}
11387 			break;
11388 		}
11389 	} while (start = end, mp = next_mp);
11390 
11391 	/* Fragment just processed could be the last one. Remember this fact */
11392 	if (!more)
11393 		ipf->ipf_last_frag_seen = B_TRUE;
11394 
11395 	/* Still got holes? */
11396 	if (ipf->ipf_hole_cnt)
11397 		return (IP_REASS_PARTIAL);
11398 	/* Clean up overloaded fields to avoid upstream disasters. */
11399 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11400 		IP_REASS_SET_START(mp1, 0);
11401 		IP_REASS_SET_END(mp1, 0);
11402 	}
11403 	return (IP_REASS_COMPLETE);
11404 }
11405 
11406 /*
11407  * ipsec processing for the fast path, used for input UDP Packets
11408  */
11409 static boolean_t
11410 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11411     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11412 {
11413 	uint32_t	ill_index;
11414 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11415 
11416 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11417 	/* The ill_index of the incoming ILL */
11418 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11419 
11420 	/* pass packet up to the transport */
11421 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11422 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11423 		    NULL, mctl_present);
11424 		if (*first_mpp == NULL) {
11425 			return (B_FALSE);
11426 		}
11427 	}
11428 
11429 	/* Initiate IPPF processing for fastpath UDP */
11430 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11431 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11432 		if (*mpp == NULL) {
11433 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11434 			    "deferred/dropped during IPPF processing\n"));
11435 			return (B_FALSE);
11436 		}
11437 	}
11438 	/*
11439 	 * We make the checks as below since we are in the fast path
11440 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11441 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11442 	 */
11443 	if (connp->conn_recvif || connp->conn_recvslla ||
11444 	    connp->conn_ipv6_recvpktinfo) {
11445 		if (connp->conn_recvif ||
11446 		    connp->conn_ipv6_recvpktinfo) {
11447 			in_flags = IPF_RECVIF;
11448 		}
11449 		if (connp->conn_recvslla) {
11450 			in_flags |= IPF_RECVSLLA;
11451 		}
11452 		/*
11453 		 * since in_flags are being set ill will be
11454 		 * referenced in ip_add_info, so it better not
11455 		 * be NULL.
11456 		 */
11457 		/*
11458 		 * the actual data will be contained in b_cont
11459 		 * upon successful return of the following call.
11460 		 * If the call fails then the original mblk is
11461 		 * returned.
11462 		 */
11463 		*mpp = ip_add_info(*mpp, ill, in_flags);
11464 	}
11465 
11466 	return (B_TRUE);
11467 }
11468 
11469 /*
11470  * Fragmentation reassembly.  Each ILL has a hash table for
11471  * queuing packets undergoing reassembly for all IPIFs
11472  * associated with the ILL.  The hash is based on the packet
11473  * IP ident field.  The ILL frag hash table was allocated
11474  * as a timer block at the time the ILL was created.  Whenever
11475  * there is anything on the reassembly queue, the timer will
11476  * be running.  Returns B_TRUE if successful else B_FALSE;
11477  * frees mp on failure.
11478  */
11479 static boolean_t
11480 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11481     uint32_t *cksum_val, uint16_t *cksum_flags)
11482 {
11483 	uint32_t	frag_offset_flags;
11484 	ill_t		*ill = (ill_t *)q->q_ptr;
11485 	mblk_t		*mp = *mpp;
11486 	mblk_t		*t_mp;
11487 	ipaddr_t	dst;
11488 	uint8_t		proto = ipha->ipha_protocol;
11489 	uint32_t	sum_val;
11490 	uint16_t	sum_flags;
11491 	ipf_t		*ipf;
11492 	ipf_t		**ipfp;
11493 	ipfb_t		*ipfb;
11494 	uint16_t	ident;
11495 	uint32_t	offset;
11496 	ipaddr_t	src;
11497 	uint_t		hdr_length;
11498 	uint32_t	end;
11499 	mblk_t		*mp1;
11500 	mblk_t		*tail_mp;
11501 	size_t		count;
11502 	size_t		msg_len;
11503 	uint8_t		ecn_info = 0;
11504 	uint32_t	packet_size;
11505 	boolean_t	pruned = B_FALSE;
11506 
11507 	if (cksum_val != NULL)
11508 		*cksum_val = 0;
11509 	if (cksum_flags != NULL)
11510 		*cksum_flags = 0;
11511 
11512 	/*
11513 	 * Drop the fragmented as early as possible, if
11514 	 * we don't have resource(s) to re-assemble.
11515 	 */
11516 	if (ip_reass_queue_bytes == 0) {
11517 		freemsg(mp);
11518 		return (B_FALSE);
11519 	}
11520 
11521 	/* Check for fragmentation offset; return if there's none */
11522 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11523 	    (IPH_MF | IPH_OFFSET)) == 0)
11524 		return (B_TRUE);
11525 
11526 	/*
11527 	 * We utilize hardware computed checksum info only for UDP since
11528 	 * IP fragmentation is a normal occurence for the protocol.  In
11529 	 * addition, checksum offload support for IP fragments carrying
11530 	 * UDP payload is commonly implemented across network adapters.
11531 	 */
11532 	ASSERT(ill != NULL);
11533 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11534 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11535 		mblk_t *mp1 = mp->b_cont;
11536 		int32_t len;
11537 
11538 		/* Record checksum information from the packet */
11539 		sum_val = (uint32_t)DB_CKSUM16(mp);
11540 		sum_flags = DB_CKSUMFLAGS(mp);
11541 
11542 		/* IP payload offset from beginning of mblk */
11543 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11544 
11545 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11546 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11547 		    offset >= DB_CKSUMSTART(mp) &&
11548 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11549 			uint32_t adj;
11550 			/*
11551 			 * Partial checksum has been calculated by hardware
11552 			 * and attached to the packet; in addition, any
11553 			 * prepended extraneous data is even byte aligned.
11554 			 * If any such data exists, we adjust the checksum;
11555 			 * this would also handle any postpended data.
11556 			 */
11557 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11558 			    mp, mp1, len, adj);
11559 
11560 			/* One's complement subtract extraneous checksum */
11561 			if (adj >= sum_val)
11562 				sum_val = ~(adj - sum_val) & 0xFFFF;
11563 			else
11564 				sum_val -= adj;
11565 		}
11566 	} else {
11567 		sum_val = 0;
11568 		sum_flags = 0;
11569 	}
11570 
11571 	/* Clear hardware checksumming flag */
11572 	DB_CKSUMFLAGS(mp) = 0;
11573 
11574 	ident = ipha->ipha_ident;
11575 	offset = (frag_offset_flags << 3) & 0xFFFF;
11576 	src = ipha->ipha_src;
11577 	dst = ipha->ipha_dst;
11578 	hdr_length = IPH_HDR_LENGTH(ipha);
11579 	end = ntohs(ipha->ipha_length) - hdr_length;
11580 
11581 	/* If end == 0 then we have a packet with no data, so just free it */
11582 	if (end == 0) {
11583 		freemsg(mp);
11584 		return (B_FALSE);
11585 	}
11586 
11587 	/* Record the ECN field info. */
11588 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11589 	if (offset != 0) {
11590 		/*
11591 		 * If this isn't the first piece, strip the header, and
11592 		 * add the offset to the end value.
11593 		 */
11594 		mp->b_rptr += hdr_length;
11595 		end += offset;
11596 	}
11597 
11598 	msg_len = MBLKSIZE(mp);
11599 	tail_mp = mp;
11600 	while (tail_mp->b_cont != NULL) {
11601 		tail_mp = tail_mp->b_cont;
11602 		msg_len += MBLKSIZE(tail_mp);
11603 	}
11604 
11605 	/* If the reassembly list for this ILL will get too big, prune it */
11606 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11607 	    ip_reass_queue_bytes) {
11608 		ill_frag_prune(ill,
11609 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11610 		    (ip_reass_queue_bytes - msg_len));
11611 		pruned = B_TRUE;
11612 	}
11613 
11614 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11615 	mutex_enter(&ipfb->ipfb_lock);
11616 
11617 	ipfp = &ipfb->ipfb_ipf;
11618 	/* Try to find an existing fragment queue for this packet. */
11619 	for (;;) {
11620 		ipf = ipfp[0];
11621 		if (ipf != NULL) {
11622 			/*
11623 			 * It has to match on ident and src/dst address.
11624 			 */
11625 			if (ipf->ipf_ident == ident &&
11626 			    ipf->ipf_src == src &&
11627 			    ipf->ipf_dst == dst &&
11628 			    ipf->ipf_protocol == proto) {
11629 				/*
11630 				 * If we have received too many
11631 				 * duplicate fragments for this packet
11632 				 * free it.
11633 				 */
11634 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11635 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11636 					freemsg(mp);
11637 					mutex_exit(&ipfb->ipfb_lock);
11638 					return (B_FALSE);
11639 				}
11640 				/* Found it. */
11641 				break;
11642 			}
11643 			ipfp = &ipf->ipf_hash_next;
11644 			continue;
11645 		}
11646 
11647 		/*
11648 		 * If we pruned the list, do we want to store this new
11649 		 * fragment?. We apply an optimization here based on the
11650 		 * fact that most fragments will be received in order.
11651 		 * So if the offset of this incoming fragment is zero,
11652 		 * it is the first fragment of a new packet. We will
11653 		 * keep it.  Otherwise drop the fragment, as we have
11654 		 * probably pruned the packet already (since the
11655 		 * packet cannot be found).
11656 		 */
11657 		if (pruned && offset != 0) {
11658 			mutex_exit(&ipfb->ipfb_lock);
11659 			freemsg(mp);
11660 			return (B_FALSE);
11661 		}
11662 
11663 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11664 			/*
11665 			 * Too many fragmented packets in this hash
11666 			 * bucket. Free the oldest.
11667 			 */
11668 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11669 		}
11670 
11671 		/* New guy.  Allocate a frag message. */
11672 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11673 		if (mp1 == NULL) {
11674 			BUMP_MIB(&ip_mib, ipInDiscards);
11675 			freemsg(mp);
11676 reass_done:
11677 			mutex_exit(&ipfb->ipfb_lock);
11678 			return (B_FALSE);
11679 		}
11680 
11681 
11682 		BUMP_MIB(&ip_mib, ipReasmReqds);
11683 		mp1->b_cont = mp;
11684 
11685 		/* Initialize the fragment header. */
11686 		ipf = (ipf_t *)mp1->b_rptr;
11687 		ipf->ipf_mp = mp1;
11688 		ipf->ipf_ptphn = ipfp;
11689 		ipfp[0] = ipf;
11690 		ipf->ipf_hash_next = NULL;
11691 		ipf->ipf_ident = ident;
11692 		ipf->ipf_protocol = proto;
11693 		ipf->ipf_src = src;
11694 		ipf->ipf_dst = dst;
11695 		ipf->ipf_nf_hdr_len = 0;
11696 		/* Record reassembly start time. */
11697 		ipf->ipf_timestamp = gethrestime_sec();
11698 		/* Record ipf generation and account for frag header */
11699 		ipf->ipf_gen = ill->ill_ipf_gen++;
11700 		ipf->ipf_count = MBLKSIZE(mp1);
11701 		ipf->ipf_last_frag_seen = B_FALSE;
11702 		ipf->ipf_ecn = ecn_info;
11703 		ipf->ipf_num_dups = 0;
11704 		ipfb->ipfb_frag_pkts++;
11705 		ipf->ipf_checksum = 0;
11706 		ipf->ipf_checksum_flags = 0;
11707 
11708 		/* Store checksum value in fragment header */
11709 		if (sum_flags != 0) {
11710 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11711 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11712 			ipf->ipf_checksum = sum_val;
11713 			ipf->ipf_checksum_flags = sum_flags;
11714 		}
11715 
11716 		/*
11717 		 * We handle reassembly two ways.  In the easy case,
11718 		 * where all the fragments show up in order, we do
11719 		 * minimal bookkeeping, and just clip new pieces on
11720 		 * the end.  If we ever see a hole, then we go off
11721 		 * to ip_reassemble which has to mark the pieces and
11722 		 * keep track of the number of holes, etc.  Obviously,
11723 		 * the point of having both mechanisms is so we can
11724 		 * handle the easy case as efficiently as possible.
11725 		 */
11726 		if (offset == 0) {
11727 			/* Easy case, in-order reassembly so far. */
11728 			ipf->ipf_count += msg_len;
11729 			ipf->ipf_tail_mp = tail_mp;
11730 			/*
11731 			 * Keep track of next expected offset in
11732 			 * ipf_end.
11733 			 */
11734 			ipf->ipf_end = end;
11735 			ipf->ipf_nf_hdr_len = hdr_length;
11736 		} else {
11737 			/* Hard case, hole at the beginning. */
11738 			ipf->ipf_tail_mp = NULL;
11739 			/*
11740 			 * ipf_end == 0 means that we have given up
11741 			 * on easy reassembly.
11742 			 */
11743 			ipf->ipf_end = 0;
11744 
11745 			/* Forget checksum offload from now on */
11746 			ipf->ipf_checksum_flags = 0;
11747 
11748 			/*
11749 			 * ipf_hole_cnt is set by ip_reassemble.
11750 			 * ipf_count is updated by ip_reassemble.
11751 			 * No need to check for return value here
11752 			 * as we don't expect reassembly to complete
11753 			 * or fail for the first fragment itself.
11754 			 */
11755 			(void) ip_reassemble(mp, ipf,
11756 			    (frag_offset_flags & IPH_OFFSET) << 3,
11757 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11758 		}
11759 		/* Update per ipfb and ill byte counts */
11760 		ipfb->ipfb_count += ipf->ipf_count;
11761 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11762 		ill->ill_frag_count += ipf->ipf_count;
11763 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11764 		/* If the frag timer wasn't already going, start it. */
11765 		mutex_enter(&ill->ill_lock);
11766 		ill_frag_timer_start(ill);
11767 		mutex_exit(&ill->ill_lock);
11768 		goto reass_done;
11769 	}
11770 
11771 	/*
11772 	 * If the packet's flag has changed (it could be coming up
11773 	 * from an interface different than the previous, therefore
11774 	 * possibly different checksum capability), then forget about
11775 	 * any stored checksum states.  Otherwise add the value to
11776 	 * the existing one stored in the fragment header.
11777 	 */
11778 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11779 		sum_val += ipf->ipf_checksum;
11780 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11781 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11782 		ipf->ipf_checksum = sum_val;
11783 	} else if (ipf->ipf_checksum_flags != 0) {
11784 		/* Forget checksum offload from now on */
11785 		ipf->ipf_checksum_flags = 0;
11786 	}
11787 
11788 	/*
11789 	 * We have a new piece of a datagram which is already being
11790 	 * reassembled.  Update the ECN info if all IP fragments
11791 	 * are ECN capable.  If there is one which is not, clear
11792 	 * all the info.  If there is at least one which has CE
11793 	 * code point, IP needs to report that up to transport.
11794 	 */
11795 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11796 		if (ecn_info == IPH_ECN_CE)
11797 			ipf->ipf_ecn = IPH_ECN_CE;
11798 	} else {
11799 		ipf->ipf_ecn = IPH_ECN_NECT;
11800 	}
11801 	if (offset && ipf->ipf_end == offset) {
11802 		/* The new fragment fits at the end */
11803 		ipf->ipf_tail_mp->b_cont = mp;
11804 		/* Update the byte count */
11805 		ipf->ipf_count += msg_len;
11806 		/* Update per ipfb and ill byte counts */
11807 		ipfb->ipfb_count += msg_len;
11808 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11809 		ill->ill_frag_count += msg_len;
11810 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11811 		if (frag_offset_flags & IPH_MF) {
11812 			/* More to come. */
11813 			ipf->ipf_end = end;
11814 			ipf->ipf_tail_mp = tail_mp;
11815 			goto reass_done;
11816 		}
11817 	} else {
11818 		/* Go do the hard cases. */
11819 		int ret;
11820 
11821 		if (offset == 0)
11822 			ipf->ipf_nf_hdr_len = hdr_length;
11823 
11824 		/* Save current byte count */
11825 		count = ipf->ipf_count;
11826 		ret = ip_reassemble(mp, ipf,
11827 		    (frag_offset_flags & IPH_OFFSET) << 3,
11828 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11829 		/* Count of bytes added and subtracted (freeb()ed) */
11830 		count = ipf->ipf_count - count;
11831 		if (count) {
11832 			/* Update per ipfb and ill byte counts */
11833 			ipfb->ipfb_count += count;
11834 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11835 			ill->ill_frag_count += count;
11836 			ASSERT(ill->ill_frag_count > 0);
11837 		}
11838 		if (ret == IP_REASS_PARTIAL) {
11839 			goto reass_done;
11840 		} else if (ret == IP_REASS_FAILED) {
11841 			/* Reassembly failed. Free up all resources */
11842 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11843 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11844 				IP_REASS_SET_START(t_mp, 0);
11845 				IP_REASS_SET_END(t_mp, 0);
11846 			}
11847 			freemsg(mp);
11848 			goto reass_done;
11849 		}
11850 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11851 	}
11852 	/*
11853 	 * We have completed reassembly.  Unhook the frag header from
11854 	 * the reassembly list.
11855 	 *
11856 	 * Before we free the frag header, record the ECN info
11857 	 * to report back to the transport.
11858 	 */
11859 	ecn_info = ipf->ipf_ecn;
11860 	BUMP_MIB(&ip_mib, ipReasmOKs);
11861 	ipfp = ipf->ipf_ptphn;
11862 
11863 	/* We need to supply these to caller */
11864 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11865 		sum_val = ipf->ipf_checksum;
11866 	else
11867 		sum_val = 0;
11868 
11869 	mp1 = ipf->ipf_mp;
11870 	count = ipf->ipf_count;
11871 	ipf = ipf->ipf_hash_next;
11872 	if (ipf != NULL)
11873 		ipf->ipf_ptphn = ipfp;
11874 	ipfp[0] = ipf;
11875 	ill->ill_frag_count -= count;
11876 	ASSERT(ipfb->ipfb_count >= count);
11877 	ipfb->ipfb_count -= count;
11878 	ipfb->ipfb_frag_pkts--;
11879 	mutex_exit(&ipfb->ipfb_lock);
11880 	/* Ditch the frag header. */
11881 	mp = mp1->b_cont;
11882 
11883 	freeb(mp1);
11884 
11885 	/* Restore original IP length in header. */
11886 	packet_size = (uint32_t)msgdsize(mp);
11887 	if (packet_size > IP_MAXPACKET) {
11888 		freemsg(mp);
11889 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11890 		return (B_FALSE);
11891 	}
11892 
11893 	if (DB_REF(mp) > 1) {
11894 		mblk_t *mp2 = copymsg(mp);
11895 
11896 		freemsg(mp);
11897 		if (mp2 == NULL) {
11898 			BUMP_MIB(&ip_mib, ipInDiscards);
11899 			return (B_FALSE);
11900 		}
11901 		mp = mp2;
11902 	}
11903 	ipha = (ipha_t *)mp->b_rptr;
11904 
11905 	ipha->ipha_length = htons((uint16_t)packet_size);
11906 	/* We're now complete, zip the frag state */
11907 	ipha->ipha_fragment_offset_and_flags = 0;
11908 	/* Record the ECN info. */
11909 	ipha->ipha_type_of_service &= 0xFC;
11910 	ipha->ipha_type_of_service |= ecn_info;
11911 	*mpp = mp;
11912 
11913 	/* Reassembly is successful; return checksum information if needed */
11914 	if (cksum_val != NULL)
11915 		*cksum_val = sum_val;
11916 	if (cksum_flags != NULL)
11917 		*cksum_flags = sum_flags;
11918 
11919 	return (B_TRUE);
11920 }
11921 
11922 /*
11923  * Perform ip header check sum update local options.
11924  * return B_TRUE if all is well, else return B_FALSE and release
11925  * the mp. caller is responsible for decrementing ire ref cnt.
11926  */
11927 static boolean_t
11928 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11929 {
11930 	mblk_t		*first_mp;
11931 	boolean_t	mctl_present;
11932 	uint16_t	sum;
11933 
11934 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11935 	/*
11936 	 * Don't do the checksum if it has gone through AH/ESP
11937 	 * processing.
11938 	 */
11939 	if (!mctl_present) {
11940 		sum = ip_csum_hdr(ipha);
11941 		if (sum != 0) {
11942 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11943 			freemsg(first_mp);
11944 			return (B_FALSE);
11945 		}
11946 	}
11947 
11948 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11949 		if (mctl_present)
11950 			freeb(first_mp);
11951 		return (B_FALSE);
11952 	}
11953 
11954 	return (B_TRUE);
11955 }
11956 
11957 /*
11958  * All udp packet are delivered to the local host via this routine.
11959  */
11960 void
11961 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11962     ill_t *recv_ill)
11963 {
11964 	uint32_t	sum;
11965 	uint32_t	u1;
11966 	boolean_t	mctl_present;
11967 	conn_t		*connp;
11968 	mblk_t		*first_mp;
11969 	uint16_t	*up;
11970 	ill_t		*ill = (ill_t *)q->q_ptr;
11971 	uint16_t	reass_hck_flags = 0;
11972 
11973 #define	rptr    ((uchar_t *)ipha)
11974 
11975 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11976 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11977 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11978 
11979 	/*
11980 	 * FAST PATH for udp packets
11981 	 */
11982 
11983 	/* u1 is # words of IP options */
11984 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11985 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11986 
11987 	/* IP options present */
11988 	if (u1 != 0)
11989 		goto ipoptions;
11990 
11991 	/* Check the IP header checksum.  */
11992 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11993 		/* Clear the IP header h/w cksum flag */
11994 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11995 	} else {
11996 #define	uph	((uint16_t *)ipha)
11997 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
11998 		    uph[6] + uph[7] + uph[8] + uph[9];
11999 #undef	uph
12000 		/* finish doing IP checksum */
12001 		sum = (sum & 0xFFFF) + (sum >> 16);
12002 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12003 		/*
12004 		 * Don't verify header checksum if this packet is coming
12005 		 * back from AH/ESP as we already did it.
12006 		 */
12007 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12008 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12009 			freemsg(first_mp);
12010 			return;
12011 		}
12012 	}
12013 
12014 	/*
12015 	 * Count for SNMP of inbound packets for ire.
12016 	 * if mctl is present this might be a secure packet and
12017 	 * has already been counted for in ip_proto_input().
12018 	 */
12019 	if (!mctl_present) {
12020 		UPDATE_IB_PKT_COUNT(ire);
12021 		ire->ire_last_used_time = lbolt;
12022 	}
12023 
12024 	/* packet part of fragmented IP packet? */
12025 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12026 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12027 		goto fragmented;
12028 	}
12029 
12030 	/* u1 = IP header length (20 bytes) */
12031 	u1 = IP_SIMPLE_HDR_LENGTH;
12032 
12033 	/* packet does not contain complete IP & UDP headers */
12034 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12035 		goto udppullup;
12036 
12037 	/* up points to UDP header */
12038 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12039 #define	iphs    ((uint16_t *)ipha)
12040 
12041 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12042 	if (up[3] != 0) {
12043 		mblk_t *mp1 = mp->b_cont;
12044 		boolean_t cksum_err;
12045 		uint16_t hck_flags = 0;
12046 
12047 		/* Pseudo-header checksum */
12048 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12049 		    iphs[9] + up[2];
12050 
12051 		/*
12052 		 * Revert to software checksum calculation if the interface
12053 		 * isn't capable of checksum offload or if IPsec is present.
12054 		 */
12055 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12056 			hck_flags = DB_CKSUMFLAGS(mp);
12057 
12058 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12059 			IP_STAT(ip_in_sw_cksum);
12060 
12061 		IP_CKSUM_RECV(hck_flags, u1,
12062 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12063 		    (int32_t)((uchar_t *)up - rptr),
12064 		    mp, mp1, cksum_err);
12065 
12066 		if (cksum_err) {
12067 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12068 
12069 			if (hck_flags & HCK_FULLCKSUM)
12070 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12071 			else if (hck_flags & HCK_PARTIALCKSUM)
12072 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12073 			else
12074 				IP_STAT(ip_udp_in_sw_cksum_err);
12075 
12076 			freemsg(first_mp);
12077 			return;
12078 		}
12079 	}
12080 
12081 	/* Non-fragmented broadcast or multicast packet? */
12082 	if (ire->ire_type == IRE_BROADCAST)
12083 		goto udpslowpath;
12084 
12085 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12086 	    ire->ire_zoneid)) != NULL) {
12087 		ASSERT(connp->conn_upq != NULL);
12088 		IP_STAT(ip_udp_fast_path);
12089 
12090 		if (CONN_UDP_FLOWCTLD(connp)) {
12091 			freemsg(mp);
12092 			BUMP_MIB(&ip_mib, udpInOverflows);
12093 		} else {
12094 			if (!mctl_present) {
12095 				BUMP_MIB(&ip_mib, ipInDelivers);
12096 			}
12097 			/*
12098 			 * mp and first_mp can change.
12099 			 */
12100 			if (ip_udp_check(q, connp, recv_ill,
12101 			    ipha, &mp, &first_mp, mctl_present)) {
12102 				/* Send it upstream */
12103 				CONN_UDP_RECV(connp, mp);
12104 			}
12105 		}
12106 		/*
12107 		 * freeb() cannot deal with null mblk being passed
12108 		 * in and first_mp can be set to null in the call
12109 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12110 		 */
12111 		if (mctl_present && first_mp != NULL) {
12112 			freeb(first_mp);
12113 		}
12114 		CONN_DEC_REF(connp);
12115 		return;
12116 	}
12117 
12118 	/*
12119 	 * if we got here we know the packet is not fragmented and
12120 	 * has no options. The classifier could not find a conn_t and
12121 	 * most likely its an icmp packet so send it through slow path.
12122 	 */
12123 
12124 	goto udpslowpath;
12125 
12126 ipoptions:
12127 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12128 		goto slow_done;
12129 	}
12130 
12131 	UPDATE_IB_PKT_COUNT(ire);
12132 	ire->ire_last_used_time = lbolt;
12133 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12134 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12135 fragmented:
12136 		/*
12137 		 * "sum" and "reass_hck_flags" are non-zero if the
12138 		 * reassembled packet has a valid hardware computed
12139 		 * checksum information associated with it.
12140 		 */
12141 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12142 			goto slow_done;
12143 		/*
12144 		 * Make sure that first_mp points back to mp as
12145 		 * the mp we came in with could have changed in
12146 		 * ip_rput_fragment().
12147 		 */
12148 		ASSERT(!mctl_present);
12149 		ipha = (ipha_t *)mp->b_rptr;
12150 		first_mp = mp;
12151 	}
12152 
12153 	/* Now we have a complete datagram, destined for this machine. */
12154 	u1 = IPH_HDR_LENGTH(ipha);
12155 	/* Pull up the UDP header, if necessary. */
12156 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12157 udppullup:
12158 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12159 			BUMP_MIB(&ip_mib, ipInDiscards);
12160 			freemsg(first_mp);
12161 			goto slow_done;
12162 		}
12163 		ipha = (ipha_t *)mp->b_rptr;
12164 	}
12165 
12166 	/*
12167 	 * Validate the checksum for the reassembled packet; for the
12168 	 * pullup case we calculate the payload checksum in software.
12169 	 */
12170 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12171 	if (up[3] != 0) {
12172 		boolean_t cksum_err;
12173 
12174 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12175 			IP_STAT(ip_in_sw_cksum);
12176 
12177 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12178 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12179 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12180 		    iphs[9] + up[2], sum, cksum_err);
12181 
12182 		if (cksum_err) {
12183 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12184 
12185 			if (reass_hck_flags & HCK_FULLCKSUM)
12186 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12187 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12188 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12189 			else
12190 				IP_STAT(ip_udp_in_sw_cksum_err);
12191 
12192 			freemsg(first_mp);
12193 			goto slow_done;
12194 		}
12195 	}
12196 udpslowpath:
12197 
12198 	/* Clear hardware checksum flag to be safe */
12199 	DB_CKSUMFLAGS(mp) = 0;
12200 
12201 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12202 	    (ire->ire_type == IRE_BROADCAST),
12203 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12204 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12205 
12206 slow_done:
12207 	IP_STAT(ip_udp_slow_path);
12208 	return;
12209 
12210 #undef  iphs
12211 #undef  rptr
12212 }
12213 
12214 /* ARGSUSED */
12215 static mblk_t *
12216 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12217     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12218     ill_rx_ring_t *ill_ring)
12219 {
12220 	conn_t		*connp;
12221 	uint32_t	sum;
12222 	uint32_t	u1;
12223 	uint16_t	*up;
12224 	int		offset;
12225 	ssize_t		len;
12226 	mblk_t		*mp1;
12227 	boolean_t	syn_present = B_FALSE;
12228 	tcph_t		*tcph;
12229 	uint_t		ip_hdr_len;
12230 	ill_t		*ill = (ill_t *)q->q_ptr;
12231 	zoneid_t	zoneid = ire->ire_zoneid;
12232 	boolean_t	cksum_err;
12233 	uint16_t	hck_flags = 0;
12234 
12235 #define	rptr	((uchar_t *)ipha)
12236 
12237 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12238 
12239 	/*
12240 	 * FAST PATH for tcp packets
12241 	 */
12242 
12243 	/* u1 is # words of IP options */
12244 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12245 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12246 
12247 	/* IP options present */
12248 	if (u1) {
12249 		goto ipoptions;
12250 	} else {
12251 		/* Check the IP header checksum.  */
12252 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12253 			/* Clear the IP header h/w cksum flag */
12254 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12255 		} else {
12256 #define	uph	((uint16_t *)ipha)
12257 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12258 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12259 #undef	uph
12260 			/* finish doing IP checksum */
12261 			sum = (sum & 0xFFFF) + (sum >> 16);
12262 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12263 			/*
12264 			 * Don't verify header checksum if this packet
12265 			 * is coming back from AH/ESP as we already did it.
12266 			 */
12267 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12268 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12269 				goto error;
12270 			}
12271 		}
12272 	}
12273 
12274 	if (!mctl_present) {
12275 		UPDATE_IB_PKT_COUNT(ire);
12276 		ire->ire_last_used_time = lbolt;
12277 	}
12278 
12279 	/* packet part of fragmented IP packet? */
12280 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12281 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12282 		goto fragmented;
12283 	}
12284 
12285 	/* u1 = IP header length (20 bytes) */
12286 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12287 
12288 	/* does packet contain IP+TCP headers? */
12289 	len = mp->b_wptr - rptr;
12290 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12291 		IP_STAT(ip_tcppullup);
12292 		goto tcppullup;
12293 	}
12294 
12295 	/* TCP options present? */
12296 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12297 
12298 	/*
12299 	 * If options need to be pulled up, then goto tcpoptions.
12300 	 * otherwise we are still in the fast path
12301 	 */
12302 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12303 		IP_STAT(ip_tcpoptions);
12304 		goto tcpoptions;
12305 	}
12306 
12307 	/* multiple mblks of tcp data? */
12308 	if ((mp1 = mp->b_cont) != NULL) {
12309 		/* more then two? */
12310 		if (mp1->b_cont != NULL) {
12311 			IP_STAT(ip_multipkttcp);
12312 			goto multipkttcp;
12313 		}
12314 		len += mp1->b_wptr - mp1->b_rptr;
12315 	}
12316 
12317 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12318 
12319 	/* part of pseudo checksum */
12320 
12321 	/* TCP datagram length */
12322 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12323 
12324 #define	iphs    ((uint16_t *)ipha)
12325 
12326 #ifdef	_BIG_ENDIAN
12327 	u1 += IPPROTO_TCP;
12328 #else
12329 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12330 #endif
12331 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12332 
12333 	/*
12334 	 * Revert to software checksum calculation if the interface
12335 	 * isn't capable of checksum offload or if IPsec is present.
12336 	 */
12337 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12338 		hck_flags = DB_CKSUMFLAGS(mp);
12339 
12340 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12341 		IP_STAT(ip_in_sw_cksum);
12342 
12343 	IP_CKSUM_RECV(hck_flags, u1,
12344 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12345 	    (int32_t)((uchar_t *)up - rptr),
12346 	    mp, mp1, cksum_err);
12347 
12348 	if (cksum_err) {
12349 		BUMP_MIB(&ip_mib, tcpInErrs);
12350 
12351 		if (hck_flags & HCK_FULLCKSUM)
12352 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12353 		else if (hck_flags & HCK_PARTIALCKSUM)
12354 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12355 		else
12356 			IP_STAT(ip_tcp_in_sw_cksum_err);
12357 
12358 		goto error;
12359 	}
12360 
12361 try_again:
12362 
12363 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12364 	    NULL) {
12365 		/* Send the TH_RST */
12366 		goto no_conn;
12367 	}
12368 
12369 	/*
12370 	 * TCP FAST PATH for AF_INET socket.
12371 	 *
12372 	 * TCP fast path to avoid extra work. An AF_INET socket type
12373 	 * does not have facility to receive extra information via
12374 	 * ip_process or ip_add_info. Also, when the connection was
12375 	 * established, we made a check if this connection is impacted
12376 	 * by any global IPSec policy or per connection policy (a
12377 	 * policy that comes in effect later will not apply to this
12378 	 * connection). Since all this can be determined at the
12379 	 * connection establishment time, a quick check of flags
12380 	 * can avoid extra work.
12381 	 */
12382 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12383 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12384 		ASSERT(first_mp == mp);
12385 		SET_SQUEUE(mp, tcp_rput_data, connp);
12386 		return (mp);
12387 	}
12388 
12389 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12390 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12391 		if (IPCL_IS_TCP(connp)) {
12392 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12393 			DB_CKSUMSTART(mp) =
12394 			    (intptr_t)ip_squeue_get(ill_ring);
12395 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12396 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12397 				SET_SQUEUE(mp, connp->conn_recv, connp);
12398 				return (mp);
12399 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12400 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12401 				ip_squeue_enter_unbound++;
12402 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12403 				    connp);
12404 				return (mp);
12405 			}
12406 			syn_present = B_TRUE;
12407 		}
12408 
12409 	}
12410 
12411 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12412 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12413 
12414 		/* No need to send this packet to TCP */
12415 		if ((flags & TH_RST) || (flags & TH_URG)) {
12416 			CONN_DEC_REF(connp);
12417 			freemsg(first_mp);
12418 			return (NULL);
12419 		}
12420 		if (flags & TH_ACK) {
12421 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
12422 			CONN_DEC_REF(connp);
12423 			return (NULL);
12424 		}
12425 
12426 		CONN_DEC_REF(connp);
12427 		freemsg(first_mp);
12428 		return (NULL);
12429 	}
12430 
12431 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12432 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12433 		    ipha, NULL, mctl_present);
12434 		if (first_mp == NULL) {
12435 			CONN_DEC_REF(connp);
12436 			return (NULL);
12437 		}
12438 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12439 			ASSERT(syn_present);
12440 			if (mctl_present) {
12441 				ASSERT(first_mp != mp);
12442 				first_mp->b_datap->db_struioflag |=
12443 				    STRUIO_POLICY;
12444 			} else {
12445 				ASSERT(first_mp == mp);
12446 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12447 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12448 			}
12449 		} else {
12450 			/*
12451 			 * Discard first_mp early since we're dealing with a
12452 			 * fully-connected conn_t and tcp doesn't do policy in
12453 			 * this case.
12454 			 */
12455 			if (mctl_present) {
12456 				freeb(first_mp);
12457 				mctl_present = B_FALSE;
12458 			}
12459 			first_mp = mp;
12460 		}
12461 	}
12462 
12463 	/* Initiate IPPF processing for fastpath */
12464 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12465 		uint32_t	ill_index;
12466 
12467 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12468 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12469 		if (mp == NULL) {
12470 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12471 			    "deferred/dropped during IPPF processing\n"));
12472 			CONN_DEC_REF(connp);
12473 			if (mctl_present)
12474 				freeb(first_mp);
12475 			return (NULL);
12476 		} else if (mctl_present) {
12477 			/*
12478 			 * ip_process might return a new mp.
12479 			 */
12480 			ASSERT(first_mp != mp);
12481 			first_mp->b_cont = mp;
12482 		} else {
12483 			first_mp = mp;
12484 		}
12485 
12486 	}
12487 
12488 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12489 		mp = ip_add_info(mp, recv_ill, flags);
12490 		if (mp == NULL) {
12491 			CONN_DEC_REF(connp);
12492 			if (mctl_present)
12493 				freeb(first_mp);
12494 			return (NULL);
12495 		} else if (mctl_present) {
12496 			/*
12497 			 * ip_add_info might return a new mp.
12498 			 */
12499 			ASSERT(first_mp != mp);
12500 			first_mp->b_cont = mp;
12501 		} else {
12502 			first_mp = mp;
12503 		}
12504 	}
12505 
12506 	if (IPCL_IS_TCP(connp)) {
12507 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12508 		return (first_mp);
12509 	} else {
12510 		putnext(connp->conn_rq, first_mp);
12511 		CONN_DEC_REF(connp);
12512 		return (NULL);
12513 	}
12514 
12515 no_conn:
12516 	/* Initiate IPPf processing, if needed. */
12517 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12518 		uint32_t ill_index;
12519 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12520 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12521 		if (first_mp == NULL) {
12522 			return (NULL);
12523 		}
12524 	}
12525 	BUMP_MIB(&ip_mib, ipInDelivers);
12526 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12527 	return (NULL);
12528 ipoptions:
12529 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12530 		goto slow_done;
12531 	}
12532 
12533 	UPDATE_IB_PKT_COUNT(ire);
12534 	ire->ire_last_used_time = lbolt;
12535 
12536 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12537 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12538 fragmented:
12539 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12540 			if (mctl_present)
12541 				freeb(first_mp);
12542 			goto slow_done;
12543 		}
12544 		/*
12545 		 * Make sure that first_mp points back to mp as
12546 		 * the mp we came in with could have changed in
12547 		 * ip_rput_fragment().
12548 		 */
12549 		ASSERT(!mctl_present);
12550 		ipha = (ipha_t *)mp->b_rptr;
12551 		first_mp = mp;
12552 	}
12553 
12554 	/* Now we have a complete datagram, destined for this machine. */
12555 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12556 
12557 	len = mp->b_wptr - mp->b_rptr;
12558 	/* Pull up a minimal TCP header, if necessary. */
12559 	if (len < (u1 + 20)) {
12560 tcppullup:
12561 		if (!pullupmsg(mp, u1 + 20)) {
12562 			BUMP_MIB(&ip_mib, ipInDiscards);
12563 			goto error;
12564 		}
12565 		ipha = (ipha_t *)mp->b_rptr;
12566 		len = mp->b_wptr - mp->b_rptr;
12567 	}
12568 
12569 	/*
12570 	 * Extract the offset field from the TCP header.  As usual, we
12571 	 * try to help the compiler more than the reader.
12572 	 */
12573 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12574 	if (offset != 5) {
12575 tcpoptions:
12576 		if (offset < 5) {
12577 			BUMP_MIB(&ip_mib, ipInDiscards);
12578 			goto error;
12579 		}
12580 		/*
12581 		 * There must be TCP options.
12582 		 * Make sure we can grab them.
12583 		 */
12584 		offset <<= 2;
12585 		offset += u1;
12586 		if (len < offset) {
12587 			if (!pullupmsg(mp, offset)) {
12588 				BUMP_MIB(&ip_mib, ipInDiscards);
12589 				goto error;
12590 			}
12591 			ipha = (ipha_t *)mp->b_rptr;
12592 			len = mp->b_wptr - rptr;
12593 		}
12594 	}
12595 
12596 	/* Get the total packet length in len, including headers. */
12597 	if (mp->b_cont) {
12598 multipkttcp:
12599 		len = msgdsize(mp);
12600 	}
12601 
12602 	/*
12603 	 * Check the TCP checksum by pulling together the pseudo-
12604 	 * header checksum, and passing it to ip_csum to be added in
12605 	 * with the TCP datagram.
12606 	 *
12607 	 * Since we are not using the hwcksum if available we must
12608 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12609 	 * If either of these fails along the way the mblk is freed.
12610 	 * If this logic ever changes and mblk is reused to say send
12611 	 * ICMP's back, then this flag may need to be cleared in
12612 	 * other places as well.
12613 	 */
12614 	DB_CKSUMFLAGS(mp) = 0;
12615 
12616 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12617 
12618 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12619 #ifdef	_BIG_ENDIAN
12620 	u1 += IPPROTO_TCP;
12621 #else
12622 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12623 #endif
12624 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12625 	/*
12626 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12627 	 */
12628 	IP_STAT(ip_in_sw_cksum);
12629 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12630 		BUMP_MIB(&ip_mib, tcpInErrs);
12631 		goto error;
12632 	}
12633 
12634 	IP_STAT(ip_tcp_slow_path);
12635 	goto try_again;
12636 #undef  iphs
12637 #undef  rptr
12638 
12639 error:
12640 	freemsg(first_mp);
12641 slow_done:
12642 	return (NULL);
12643 }
12644 
12645 /* ARGSUSED */
12646 static void
12647 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12648     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12649 {
12650 	conn_t		*connp;
12651 	uint32_t	sum;
12652 	uint32_t	u1;
12653 	ssize_t		len;
12654 	sctp_hdr_t	*sctph;
12655 	zoneid_t	zoneid = ire->ire_zoneid;
12656 	uint32_t	pktsum;
12657 	uint32_t	calcsum;
12658 	uint32_t	ports;
12659 	uint_t		ipif_seqid;
12660 	in6_addr_t	map_src, map_dst;
12661 	ill_t		*ill = (ill_t *)q->q_ptr;
12662 
12663 #define	rptr	((uchar_t *)ipha)
12664 
12665 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12666 
12667 	/* u1 is # words of IP options */
12668 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12669 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12670 
12671 	/* IP options present */
12672 	if (u1 > 0) {
12673 		goto ipoptions;
12674 	} else {
12675 		/* Check the IP header checksum.  */
12676 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12677 #define	uph	((uint16_t *)ipha)
12678 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12679 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12680 #undef	uph
12681 			/* finish doing IP checksum */
12682 			sum = (sum & 0xFFFF) + (sum >> 16);
12683 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12684 			/*
12685 			 * Don't verify header checksum if this packet
12686 			 * is coming back from AH/ESP as we already did it.
12687 			 */
12688 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12689 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12690 				goto error;
12691 			}
12692 		}
12693 		/*
12694 		 * Since there is no SCTP h/w cksum support yet, just
12695 		 * clear the flag.
12696 		 */
12697 		DB_CKSUMFLAGS(mp) = 0;
12698 	}
12699 
12700 	/*
12701 	 * Don't verify header checksum if this packet is coming
12702 	 * back from AH/ESP as we already did it.
12703 	 */
12704 	if (!mctl_present) {
12705 		UPDATE_IB_PKT_COUNT(ire);
12706 		ire->ire_last_used_time = lbolt;
12707 	}
12708 
12709 	/* packet part of fragmented IP packet? */
12710 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12711 	if (u1 & (IPH_MF | IPH_OFFSET))
12712 		goto fragmented;
12713 
12714 	/* u1 = IP header length (20 bytes) */
12715 	u1 = IP_SIMPLE_HDR_LENGTH;
12716 
12717 find_sctp_client:
12718 	/* Pullup if we don't have the sctp common header. */
12719 	len = MBLKL(mp);
12720 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12721 		if (mp->b_cont == NULL ||
12722 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12723 			BUMP_MIB(&ip_mib, ipInDiscards);
12724 			goto error;
12725 		}
12726 		ipha = (ipha_t *)mp->b_rptr;
12727 		len = MBLKL(mp);
12728 	}
12729 
12730 	sctph = (sctp_hdr_t *)(rptr + u1);
12731 #ifdef	DEBUG
12732 	if (!skip_sctp_cksum) {
12733 #endif
12734 		pktsum = sctph->sh_chksum;
12735 		sctph->sh_chksum = 0;
12736 		calcsum = sctp_cksum(mp, u1);
12737 		if (calcsum != pktsum) {
12738 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12739 			goto error;
12740 		}
12741 		sctph->sh_chksum = pktsum;
12742 #ifdef	DEBUG	/* skip_sctp_cksum */
12743 	}
12744 #endif
12745 	/* get the ports */
12746 	ports = *(uint32_t *)&sctph->sh_sport;
12747 
12748 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12749 	IRE_REFRELE(ire);
12750 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12751 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12752 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
12753 	    mp)) == NULL) {
12754 		/* Check for raw socket or OOTB handling */
12755 		goto no_conn;
12756 	}
12757 
12758 	/* Found a client; up it goes */
12759 	BUMP_MIB(&ip_mib, ipInDelivers);
12760 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12761 	return;
12762 
12763 no_conn:
12764 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12765 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12766 	return;
12767 
12768 ipoptions:
12769 	DB_CKSUMFLAGS(mp) = 0;
12770 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12771 		goto slow_done;
12772 
12773 	UPDATE_IB_PKT_COUNT(ire);
12774 	ire->ire_last_used_time = lbolt;
12775 
12776 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12777 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12778 fragmented:
12779 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12780 			goto slow_done;
12781 		/*
12782 		 * Make sure that first_mp points back to mp as
12783 		 * the mp we came in with could have changed in
12784 		 * ip_rput_fragment().
12785 		 */
12786 		ASSERT(!mctl_present);
12787 		ipha = (ipha_t *)mp->b_rptr;
12788 		first_mp = mp;
12789 	}
12790 
12791 	/* Now we have a complete datagram, destined for this machine. */
12792 	u1 = IPH_HDR_LENGTH(ipha);
12793 	goto find_sctp_client;
12794 #undef  iphs
12795 #undef  rptr
12796 
12797 error:
12798 	freemsg(first_mp);
12799 slow_done:
12800 	IRE_REFRELE(ire);
12801 }
12802 
12803 #define	VER_BITS	0xF0
12804 #define	VERSION_6	0x60
12805 
12806 static boolean_t
12807 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12808     ipaddr_t *dstp)
12809 {
12810 	uint_t	opt_len;
12811 	ipha_t *ipha;
12812 	ssize_t len;
12813 	uint_t	pkt_len;
12814 
12815 	IP_STAT(ip_ipoptions);
12816 	ipha = *iphapp;
12817 
12818 #define	rptr    ((uchar_t *)ipha)
12819 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12820 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12821 		BUMP_MIB(&ip_mib, ipInIPv6);
12822 		freemsg(mp);
12823 		return (B_FALSE);
12824 	}
12825 
12826 	/* multiple mblk or too short */
12827 	pkt_len = ntohs(ipha->ipha_length);
12828 
12829 	/* Get the number of words of IP options in the IP header. */
12830 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12831 	if (opt_len) {
12832 		/* IP Options present!  Validate and process. */
12833 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12834 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12835 			goto done;
12836 		}
12837 		/*
12838 		 * Recompute complete header length and make sure we
12839 		 * have access to all of it.
12840 		 */
12841 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12842 		if (len > (mp->b_wptr - rptr)) {
12843 			if (len > pkt_len) {
12844 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12845 				goto done;
12846 			}
12847 			if (!pullupmsg(mp, len)) {
12848 				BUMP_MIB(&ip_mib, ipInDiscards);
12849 				goto done;
12850 			}
12851 			ipha = (ipha_t *)mp->b_rptr;
12852 		}
12853 		/*
12854 		 * Go off to ip_rput_options which returns the next hop
12855 		 * destination address, which may have been affected
12856 		 * by source routing.
12857 		 */
12858 		IP_STAT(ip_opt);
12859 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12860 			return (B_FALSE);
12861 		}
12862 	}
12863 	*iphapp = ipha;
12864 	return (B_TRUE);
12865 done:
12866 	/* clear b_prev - used by ip_mroute_decap */
12867 	mp->b_prev = NULL;
12868 	freemsg(mp);
12869 	return (B_FALSE);
12870 #undef  rptr
12871 }
12872 
12873 /*
12874  * Deal with the fact that there is no ire for the destination.
12875  * The incoming ill (in_ill) is passed in to ip_newroute only
12876  * in the case of packets coming from mobile ip forward tunnel.
12877  * It must be null otherwise.
12878  */
12879 static void
12880 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12881     ipaddr_t dst)
12882 {
12883 	ipha_t	*ipha;
12884 	ill_t	*ill;
12885 
12886 	ipha = (ipha_t *)mp->b_rptr;
12887 	ill = (ill_t *)q->q_ptr;
12888 
12889 	ASSERT(ill != NULL);
12890 	/*
12891 	 * No IRE for this destination, so it can't be for us.
12892 	 * Unless we are forwarding, drop the packet.
12893 	 * We have to let source routed packets through
12894 	 * since we don't yet know if they are 'ping -l'
12895 	 * packets i.e. if they will go out over the
12896 	 * same interface as they came in on.
12897 	 */
12898 	if (ll_multicast) {
12899 		freemsg(mp);
12900 		return;
12901 	}
12902 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12903 		BUMP_MIB(&ip_mib, ipForwProhibits);
12904 		freemsg(mp);
12905 		return;
12906 	}
12907 
12908 	/* Check for Martian addresses */
12909 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12910 		freemsg(mp);
12911 		return;
12912 	}
12913 
12914 	/* Mark this packet as having originated externally */
12915 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12916 
12917 	/*
12918 	 * Clear the indication that this may have a hardware checksum
12919 	 * as we are not using it
12920 	 */
12921 	DB_CKSUMFLAGS(mp) = 0;
12922 
12923 	/*
12924 	 * Now hand the packet to ip_newroute.
12925 	 */
12926 	ip_newroute(q, mp, dst, in_ill, NULL);
12927 }
12928 
12929 /*
12930  * check ip header length and align it.
12931  */
12932 static boolean_t
12933 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12934 {
12935 	ssize_t len;
12936 	ill_t *ill;
12937 	ipha_t	*ipha;
12938 
12939 	len = MBLKL(mp);
12940 
12941 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12942 		if (!OK_32PTR(mp->b_rptr))
12943 			IP_STAT(ip_notaligned1);
12944 		else
12945 			IP_STAT(ip_notaligned2);
12946 		/* Guard against bogus device drivers */
12947 		if (len < 0) {
12948 			/* clear b_prev - used by ip_mroute_decap */
12949 			mp->b_prev = NULL;
12950 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12951 			freemsg(mp);
12952 			return (B_FALSE);
12953 		}
12954 
12955 		if (ip_rput_pullups++ == 0) {
12956 			ill = (ill_t *)q->q_ptr;
12957 			ipha = (ipha_t *)mp->b_rptr;
12958 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12959 			    "ip_check_and_align_header: %s forced us to "
12960 			    " pullup pkt, hdr len %ld, hdr addr %p",
12961 			    ill->ill_name, len, ipha);
12962 		}
12963 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12964 			/* clear b_prev - used by ip_mroute_decap */
12965 			mp->b_prev = NULL;
12966 			BUMP_MIB(&ip_mib, ipInDiscards);
12967 			freemsg(mp);
12968 			return (B_FALSE);
12969 		}
12970 	}
12971 	return (B_TRUE);
12972 }
12973 
12974 static boolean_t
12975 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12976 {
12977 	ill_group_t	*ill_group;
12978 	ill_group_t	*ire_group;
12979 	queue_t 	*q;
12980 	ill_t		*ire_ill;
12981 	uint_t		ill_ifindex;
12982 
12983 	q = *qp;
12984 	/*
12985 	 * We need to check to make sure the packet came in
12986 	 * on the queue associated with the destination IRE.
12987 	 * Note that for multicast packets and broadcast packets sent to
12988 	 * a broadcast address which is shared between multiple interfaces
12989 	 * we should not do this since we just got a random broadcast ire.
12990 	 */
12991 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12992 		boolean_t check_multi = B_TRUE;
12993 
12994 		/*
12995 		 * This packet came in on an interface other than the
12996 		 * one associated with the destination address.
12997 		 * "Gateway" it to the appropriate interface here.
12998 		 * As long as the ills belong to the same group,
12999 		 * we don't consider them to arriving on the wrong
13000 		 * interface. Thus, when the switch is doing inbound
13001 		 * load spreading, we won't drop packets when we
13002 		 * are doing strict multihoming checks. Note, the
13003 		 * same holds true for 'usesrc groups' where the
13004 		 * destination address may belong to another interface
13005 		 * to allow multipathing to happen
13006 		 */
13007 		ill_group = ill->ill_group;
13008 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13009 		ill_ifindex = ill->ill_usesrc_ifindex;
13010 		ire_group = ire_ill->ill_group;
13011 
13012 		/*
13013 		 * If it's part of the same IPMP group, or if it's a legal
13014 		 * address on the 'usesrc' interface, then bypass strict
13015 		 * checks.
13016 		 */
13017 		if (ill_group != NULL && ill_group == ire_group) {
13018 			check_multi = B_FALSE;
13019 		} else if (ill_ifindex != 0 &&
13020 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13021 			check_multi = B_FALSE;
13022 		}
13023 
13024 		if (check_multi &&
13025 		    ip_strict_dst_multihoming &&
13026 		    ((ill->ill_flags &
13027 		    ire->ire_ipif->ipif_ill->ill_flags &
13028 		    ILLF_ROUTER) == 0)) {
13029 			/* Drop packet */
13030 			BUMP_MIB(&ip_mib, ipForwProhibits);
13031 			freemsg(mp);
13032 			ire_refrele(ire);
13033 			return (B_TRUE);
13034 		}
13035 
13036 		/*
13037 		 * Change the queue (for non-virtual destination network
13038 		 * interfaces) and ip_rput_local will be called with the right
13039 		 * queue
13040 		 */
13041 		q = ire->ire_rfq;
13042 	}
13043 	/* Must be broadcast.  We'll take it. */
13044 	*qp = q;
13045 	return (B_FALSE);
13046 }
13047 
13048 static void
13049 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13050     ill_t *ill, int ll_multicast)
13051 {
13052 	ill_group_t	*ill_group;
13053 	ill_group_t	*ire_group;
13054 	queue_t	*dev_q;
13055 
13056 	ASSERT(ire->ire_stq != NULL);
13057 	if (ll_multicast != 0)
13058 		goto drop_pkt;
13059 
13060 	if (ip_no_forward(ipha, ill))
13061 		goto drop_pkt;
13062 
13063 	ill_group = ill->ill_group;
13064 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13065 	/*
13066 	 * Check if we want to forward this one at this time.
13067 	 * We allow source routed packets on a host provided that
13068 	 * they go out the same interface or same interface group
13069 	 * as they came in on.
13070 	 *
13071 	 * XXX To be quicker, we may wish to not chase pointers to
13072 	 * get the ILLF_ROUTER flag and instead store the
13073 	 * forwarding policy in the ire.  An unfortunate
13074 	 * side-effect of that would be requiring an ire flush
13075 	 * whenever the ILLF_ROUTER flag changes.
13076 	 */
13077 	if (((ill->ill_flags &
13078 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13079 	    ILLF_ROUTER) == 0) &&
13080 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13081 	    (ill_group != NULL && ill_group == ire_group)))) {
13082 		BUMP_MIB(&ip_mib, ipForwProhibits);
13083 		if (ip_source_routed(ipha)) {
13084 			q = WR(q);
13085 			/*
13086 			 * Clear the indication that this may have
13087 			 * hardware checksum as we are not using it.
13088 			 */
13089 			DB_CKSUMFLAGS(mp) = 0;
13090 			icmp_unreachable(q, mp,
13091 			    ICMP_SOURCE_ROUTE_FAILED);
13092 			ire_refrele(ire);
13093 			return;
13094 		}
13095 		goto drop_pkt;
13096 	}
13097 
13098 	/* Packet is being forwarded. Turning off hwcksum flag. */
13099 	DB_CKSUMFLAGS(mp) = 0;
13100 	if (ip_g_send_redirects) {
13101 		/*
13102 		 * Check whether the incoming interface and outgoing
13103 		 * interface is part of the same group. If so,
13104 		 * send redirects.
13105 		 *
13106 		 * Check the source address to see if it originated
13107 		 * on the same logical subnet it is going back out on.
13108 		 * If so, we should be able to send it a redirect.
13109 		 * Avoid sending a redirect if the destination
13110 		 * is directly connected (gw_addr == 0),
13111 		 * or if the packet was source routed out this
13112 		 * interface.
13113 		 */
13114 		ipaddr_t src;
13115 		mblk_t	*mp1;
13116 		ire_t	*src_ire = NULL;
13117 
13118 		/*
13119 		 * Check whether ire_rfq and q are from the same ill
13120 		 * or if they are not same, they at least belong
13121 		 * to the same group. If so, send redirects.
13122 		 */
13123 		if ((ire->ire_rfq == q ||
13124 		    (ill_group != NULL && ill_group == ire_group)) &&
13125 		    (ire->ire_gateway_addr != 0) &&
13126 		    !ip_source_routed(ipha)) {
13127 
13128 			src = ipha->ipha_src;
13129 			src_ire = ire_ftable_lookup(src, 0, 0,
13130 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13131 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13132 
13133 			if (src_ire != NULL) {
13134 				/*
13135 				 * The source is directly connected.
13136 				 * Just copy the ip header (which is
13137 				 * in the first mblk)
13138 				 */
13139 				mp1 = copyb(mp);
13140 				if (mp1 != NULL) {
13141 					icmp_send_redirect(WR(q), mp1,
13142 					    ire->ire_gateway_addr);
13143 				}
13144 				ire_refrele(src_ire);
13145 			}
13146 		}
13147 	}
13148 
13149 	dev_q = ire->ire_stq->q_next;
13150 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13151 		BUMP_MIB(&ip_mib, ipInDiscards);
13152 		freemsg(mp);
13153 		ire_refrele(ire);
13154 		return;
13155 	}
13156 
13157 	ip_rput_forward(ire, ipha, mp, ill);
13158 	IRE_REFRELE(ire);
13159 	return;
13160 
13161 drop_pkt:
13162 	ire_refrele(ire);
13163 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13164 	freemsg(mp);
13165 }
13166 
13167 static boolean_t
13168 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
13169     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13170 {
13171 	queue_t		*q;
13172 	ire_t		*ire;
13173 	uint16_t	hcksumflags;
13174 
13175 	q = *qp;
13176 	ire = *irep;
13177 
13178 	/*
13179 	 * Clear the indication that this may have hardware
13180 	 * checksum as we are not using it for forwarding.
13181 	 */
13182 	hcksumflags = DB_CKSUMFLAGS(mp);
13183 	DB_CKSUMFLAGS(mp) = 0;
13184 
13185 	/*
13186 	 * Directed broadcast forwarding: if the packet came in over a
13187 	 * different interface then it is routed out over we can forward it.
13188 	 */
13189 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13190 		ire_refrele(ire);
13191 		freemsg(mp);
13192 		BUMP_MIB(&ip_mib, ipInDiscards);
13193 		return (B_TRUE);
13194 	}
13195 	/*
13196 	 * For multicast we have set dst to be INADDR_BROADCAST
13197 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13198 	 * only for broadcast packets.
13199 	 */
13200 	if (!CLASSD(ipha->ipha_dst)) {
13201 		ire_t *new_ire;
13202 		ipif_t *ipif;
13203 		/*
13204 		 * For ill groups, as the switch duplicates broadcasts
13205 		 * across all the ports, we need to filter out and
13206 		 * send up only one copy. There is one copy for every
13207 		 * broadcast address on each ill. Thus, we look for a
13208 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13209 		 * later to see whether this ill is eligible to receive
13210 		 * them or not. ill_nominate_bcast_rcv() nominates only
13211 		 * one set of IREs for receiving.
13212 		 */
13213 
13214 		ipif = ipif_get_next_ipif(NULL, ill);
13215 		if (ipif == NULL) {
13216 			ire_refrele(ire);
13217 			freemsg(mp);
13218 			BUMP_MIB(&ip_mib, ipInDiscards);
13219 			return (B_TRUE);
13220 		}
13221 		new_ire = ire_ctable_lookup(dst, 0, 0,
13222 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13223 		ipif_refrele(ipif);
13224 
13225 		if (new_ire != NULL) {
13226 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13227 				ire_refrele(ire);
13228 				ire_refrele(new_ire);
13229 				freemsg(mp);
13230 				BUMP_MIB(&ip_mib, ipInDiscards);
13231 				return (B_TRUE);
13232 			}
13233 			/*
13234 			 * In the special case of multirouted broadcast
13235 			 * packets, we unconditionally need to "gateway"
13236 			 * them to the appropriate interface here.
13237 			 * In the normal case, this cannot happen, because
13238 			 * there is no broadcast IRE tagged with the
13239 			 * RTF_MULTIRT flag.
13240 			 */
13241 			if (new_ire->ire_flags & RTF_MULTIRT) {
13242 				ire_refrele(new_ire);
13243 				if (ire->ire_rfq != NULL) {
13244 					q = ire->ire_rfq;
13245 					*qp = q;
13246 				}
13247 			} else {
13248 				ire_refrele(ire);
13249 				ire = new_ire;
13250 			}
13251 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13252 			if (!ip_g_forward_directed_bcast) {
13253 				/*
13254 				 * Free the message if
13255 				 * ip_g_forward_directed_bcast is turned
13256 				 * off for non-local broadcast.
13257 				 */
13258 				ire_refrele(ire);
13259 				freemsg(mp);
13260 				BUMP_MIB(&ip_mib, ipInDiscards);
13261 				return (B_TRUE);
13262 			}
13263 		} else {
13264 			/*
13265 			 * This CGTP packet successfully passed the
13266 			 * CGTP filter, but the related CGTP
13267 			 * broadcast IRE has not been found,
13268 			 * meaning that the redundant ipif is
13269 			 * probably down. However, if we discarded
13270 			 * this packet, its duplicate would be
13271 			 * filtered out by the CGTP filter so none
13272 			 * of them would get through. So we keep
13273 			 * going with this one.
13274 			 */
13275 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13276 			if (ire->ire_rfq != NULL) {
13277 				q = ire->ire_rfq;
13278 				*qp = q;
13279 			}
13280 		}
13281 	}
13282 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13283 		/*
13284 		 * Verify that there are not more then one
13285 		 * IRE_BROADCAST with this broadcast address which
13286 		 * has ire_stq set.
13287 		 * TODO: simplify, loop over all IRE's
13288 		 */
13289 		ire_t	*ire1;
13290 		int	num_stq = 0;
13291 		mblk_t	*mp1;
13292 
13293 		/* Find the first one with ire_stq set */
13294 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13295 		for (ire1 = ire; ire1 &&
13296 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13297 		    ire1 = ire1->ire_next)
13298 			;
13299 		if (ire1) {
13300 			ire_refrele(ire);
13301 			ire = ire1;
13302 			IRE_REFHOLD(ire);
13303 		}
13304 
13305 		/* Check if there are additional ones with stq set */
13306 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13307 			if (ire->ire_addr != ire1->ire_addr)
13308 				break;
13309 			if (ire1->ire_stq) {
13310 				num_stq++;
13311 				break;
13312 			}
13313 		}
13314 		rw_exit(&ire->ire_bucket->irb_lock);
13315 		if (num_stq == 1 && ire->ire_stq != NULL) {
13316 			ip1dbg(("ip_rput_process_broadcast: directed "
13317 			    "broadcast to 0x%x\n",
13318 			    ntohl(ire->ire_addr)));
13319 			mp1 = copymsg(mp);
13320 			if (mp1) {
13321 				switch (ipha->ipha_protocol) {
13322 				case IPPROTO_UDP:
13323 					ip_udp_input(q, mp1, ipha, ire, ill);
13324 					break;
13325 				default:
13326 					ip_proto_input(q, mp1, ipha, ire, ill);
13327 					break;
13328 				}
13329 			}
13330 			/*
13331 			 * Adjust ttl to 2 (1+1 - the forward engine
13332 			 * will decrement it by one.
13333 			 */
13334 			if (ip_csum_hdr(ipha)) {
13335 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13336 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13337 				freemsg(mp);
13338 				ire_refrele(ire);
13339 				return (B_TRUE);
13340 			}
13341 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13342 			ipha->ipha_hdr_checksum = 0;
13343 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13344 			ip_rput_process_forward(q, mp, ire, ipha,
13345 			    ill, ll_multicast);
13346 			return (B_TRUE);
13347 		}
13348 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13349 		    ntohl(ire->ire_addr)));
13350 	}
13351 
13352 	*irep = ire;
13353 
13354 	/* Restore any hardware checksum flags */
13355 	DB_CKSUMFLAGS(mp) = hcksumflags;
13356 	return (B_FALSE);
13357 }
13358 
13359 /* ARGSUSED */
13360 static boolean_t
13361 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13362     int *ll_multicast, ipaddr_t *dstp)
13363 {
13364 	/*
13365 	 * Forward packets only if we have joined the allmulti
13366 	 * group on this interface.
13367 	 */
13368 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13369 		int retval;
13370 
13371 		/*
13372 		 * Clear the indication that this may have hardware
13373 		 * checksum as we are not using it.
13374 		 */
13375 		DB_CKSUMFLAGS(mp) = 0;
13376 		retval = ip_mforward(ill, ipha, mp);
13377 		/* ip_mforward updates mib variables if needed */
13378 		/* clear b_prev - used by ip_mroute_decap */
13379 		mp->b_prev = NULL;
13380 
13381 		switch (retval) {
13382 		case 0:
13383 			/*
13384 			 * pkt is okay and arrived on phyint.
13385 			 *
13386 			 * If we are running as a multicast router
13387 			 * we need to see all IGMP and/or PIM packets.
13388 			 */
13389 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13390 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13391 				goto done;
13392 			}
13393 			break;
13394 		case -1:
13395 			/* pkt is mal-formed, toss it */
13396 			goto drop_pkt;
13397 		case 1:
13398 			/* pkt is okay and arrived on a tunnel */
13399 			/*
13400 			 * If we are running a multicast router
13401 			 *  we need to see all igmp packets.
13402 			 */
13403 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13404 				*dstp = INADDR_BROADCAST;
13405 				*ll_multicast = 1;
13406 				return (B_FALSE);
13407 			}
13408 
13409 			goto drop_pkt;
13410 		}
13411 	}
13412 
13413 	ILM_WALKER_HOLD(ill);
13414 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
13415 		/*
13416 		 * This might just be caused by the fact that
13417 		 * multiple IP Multicast addresses map to the same
13418 		 * link layer multicast - no need to increment counter!
13419 		 */
13420 		ILM_WALKER_RELE(ill);
13421 		freemsg(mp);
13422 		return (B_TRUE);
13423 	}
13424 	ILM_WALKER_RELE(ill);
13425 done:
13426 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
13427 	/*
13428 	 * This assumes the we deliver to all streams for multicast
13429 	 * and broadcast packets.
13430 	 */
13431 	*dstp = INADDR_BROADCAST;
13432 	*ll_multicast = 1;
13433 	return (B_FALSE);
13434 drop_pkt:
13435 	ip2dbg(("ip_rput: drop pkt\n"));
13436 	freemsg(mp);
13437 	return (B_TRUE);
13438 }
13439 
13440 static boolean_t
13441 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
13442     int *ll_multicast, mblk_t **mpp)
13443 {
13444 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
13445 	boolean_t must_copy = B_FALSE;
13446 	struct iocblk   *iocp;
13447 	ipha_t		*ipha;
13448 
13449 #define	rptr    ((uchar_t *)ipha)
13450 
13451 	first_mp = *first_mpp;
13452 	mp = *mpp;
13453 
13454 	ASSERT(first_mp == mp);
13455 
13456 	/*
13457 	 * if db_ref > 1 then copymsg and free original. Packet may be
13458 	 * changed and do not want other entity who has a reference to this
13459 	 * message to trip over the changes. This is a blind change because
13460 	 * trying to catch all places that might change packet is too
13461 	 * difficult (since it may be a module above this one)
13462 	 *
13463 	 * This corresponds to the non-fast path case. We walk down the full
13464 	 * chain in this case, and check the db_ref count of all the dblks,
13465 	 * and do a copymsg if required. It is possible that the db_ref counts
13466 	 * of the data blocks in the mblk chain can be different.
13467 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
13468 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
13469 	 * 'snoop' is running.
13470 	 */
13471 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
13472 		if (mp1->b_datap->db_ref > 1) {
13473 			must_copy = B_TRUE;
13474 			break;
13475 		}
13476 	}
13477 
13478 	if (must_copy) {
13479 		mp1 = copymsg(mp);
13480 		if (mp1 == NULL) {
13481 			for (mp1 = mp; mp1 != NULL;
13482 			    mp1 = mp1->b_cont) {
13483 				mp1->b_next = NULL;
13484 				mp1->b_prev = NULL;
13485 			}
13486 			freemsg(mp);
13487 			BUMP_MIB(&ip_mib, ipInDiscards);
13488 			return (B_TRUE);
13489 		}
13490 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
13491 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
13492 			/* Copy b_next - used in M_BREAK messages */
13493 			to_mp->b_next = from_mp->b_next;
13494 			from_mp->b_next = NULL;
13495 			/* Copy b_prev - used by ip_mroute_decap */
13496 			to_mp->b_prev = from_mp->b_prev;
13497 			from_mp->b_prev = NULL;
13498 		}
13499 		*first_mpp = first_mp = mp1;
13500 		freemsg(mp);
13501 		mp = mp1;
13502 		*mpp = mp1;
13503 	}
13504 
13505 	ipha = (ipha_t *)mp->b_rptr;
13506 
13507 	/*
13508 	 * previous code has a case for M_DATA.
13509 	 * We want to check how that happens.
13510 	 */
13511 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13512 	switch (first_mp->b_datap->db_type) {
13513 	case M_PROTO:
13514 	case M_PCPROTO:
13515 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13516 		    DL_UNITDATA_IND) {
13517 			/* Go handle anything other than data elsewhere. */
13518 			ip_rput_dlpi(q, mp);
13519 			return (B_TRUE);
13520 		}
13521 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13522 		/* Ditch the DLPI header. */
13523 		mp1 = mp->b_cont;
13524 		ASSERT(first_mp == mp);
13525 		*first_mpp = mp1;
13526 		freeb(mp);
13527 		*mpp = mp1;
13528 		return (B_FALSE);
13529 	case M_BREAK:
13530 		/*
13531 		 * A packet arrives as M_BREAK following a cycle through
13532 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13533 		 * This is an IP datagram sans lower level header.
13534 		 * M_BREAK are also used to pass back in multicast packets
13535 		 * that are encapsulated with a source route.
13536 		 */
13537 		/* Ditch the M_BREAK mblk */
13538 		mp1 = mp->b_cont;
13539 		ASSERT(first_mp == mp);
13540 		*first_mpp = mp1;
13541 		freeb(mp);
13542 		mp = mp1;
13543 		mp->b_next = NULL;
13544 		*mpp = mp;
13545 		*ll_multicast = 0;
13546 		return (B_FALSE);
13547 	case M_IOCACK:
13548 		ip1dbg(("got iocack "));
13549 		iocp = (struct iocblk *)mp->b_rptr;
13550 		switch (iocp->ioc_cmd) {
13551 		case DL_IOC_HDR_INFO:
13552 			ill = (ill_t *)q->q_ptr;
13553 			ill_fastpath_ack(ill, mp);
13554 			return (B_TRUE);
13555 		case SIOCSTUNPARAM:
13556 		case OSIOCSTUNPARAM:
13557 			/* Go through qwriter_ip */
13558 			break;
13559 		case SIOCGTUNPARAM:
13560 		case OSIOCGTUNPARAM:
13561 			ip_rput_other(NULL, q, mp, NULL);
13562 			return (B_TRUE);
13563 		default:
13564 			putnext(q, mp);
13565 			return (B_TRUE);
13566 		}
13567 		/* FALLTHRU */
13568 	case M_ERROR:
13569 	case M_HANGUP:
13570 		/*
13571 		 * Since this is on the ill stream we unconditionally
13572 		 * bump up the refcount
13573 		 */
13574 		ill_refhold(ill);
13575 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13576 		    B_FALSE);
13577 		return (B_TRUE);
13578 	case M_CTL:
13579 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13580 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13581 			IPHADA_M_CTL)) {
13582 			/*
13583 			 * It's an IPsec accelerated packet.
13584 			 * Make sure that the ill from which we received the
13585 			 * packet has enabled IPsec hardware acceleration.
13586 			 */
13587 			if (!(ill->ill_capabilities &
13588 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13589 				/* IPsec kstats: bean counter */
13590 				freemsg(mp);
13591 				return (B_TRUE);
13592 			}
13593 
13594 			/*
13595 			 * Make mp point to the mblk following the M_CTL,
13596 			 * then process according to type of mp.
13597 			 * After this processing, first_mp will point to
13598 			 * the data-attributes and mp to the pkt following
13599 			 * the M_CTL.
13600 			 */
13601 			mp = first_mp->b_cont;
13602 			if (mp == NULL) {
13603 				freemsg(first_mp);
13604 				return (B_TRUE);
13605 			}
13606 			/*
13607 			 * A Hardware Accelerated packet can only be M_DATA
13608 			 * ESP or AH packet.
13609 			 */
13610 			if (mp->b_datap->db_type != M_DATA) {
13611 				/* non-M_DATA IPsec accelerated packet */
13612 				IPSECHW_DEBUG(IPSECHW_PKT,
13613 				    ("non-M_DATA IPsec accelerated pkt\n"));
13614 				freemsg(first_mp);
13615 				return (B_TRUE);
13616 			}
13617 			ipha = (ipha_t *)mp->b_rptr;
13618 			if (ipha->ipha_protocol != IPPROTO_AH &&
13619 			    ipha->ipha_protocol != IPPROTO_ESP) {
13620 				IPSECHW_DEBUG(IPSECHW_PKT,
13621 				    ("non-M_DATA IPsec accelerated pkt\n"));
13622 				freemsg(first_mp);
13623 				return (B_TRUE);
13624 			}
13625 			*mpp = mp;
13626 			return (B_FALSE);
13627 		}
13628 		putnext(q, mp);
13629 		return (B_TRUE);
13630 	case M_FLUSH:
13631 		if (*mp->b_rptr & FLUSHW) {
13632 			*mp->b_rptr &= ~FLUSHR;
13633 			qreply(q, mp);
13634 			return (B_TRUE);
13635 		}
13636 		freemsg(mp);
13637 		return (B_TRUE);
13638 	case M_IOCNAK:
13639 		ip1dbg(("got iocnak "));
13640 		iocp = (struct iocblk *)mp->b_rptr;
13641 		switch (iocp->ioc_cmd) {
13642 		case DL_IOC_HDR_INFO:
13643 		case SIOCSTUNPARAM:
13644 		case OSIOCSTUNPARAM:
13645 			/*
13646 			 * Since this is on the ill stream we unconditionally
13647 			 * bump up the refcount
13648 			 */
13649 			ill_refhold(ill);
13650 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13651 			    CUR_OP, B_FALSE);
13652 			return (B_TRUE);
13653 		case SIOCGTUNPARAM:
13654 		case OSIOCGTUNPARAM:
13655 			ip_rput_other(NULL, q, mp, NULL);
13656 			return (B_TRUE);
13657 		default:
13658 			break;
13659 		}
13660 		/* FALLTHRU */
13661 	default:
13662 		putnext(q, mp);
13663 		return (B_TRUE);
13664 	}
13665 }
13666 
13667 /* Read side put procedure.  Packets coming from the wire arrive here. */
13668 void
13669 ip_rput(queue_t *q, mblk_t *mp)
13670 {
13671 	ill_t		*ill;
13672 
13673 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13674 
13675 	ill = (ill_t *)q->q_ptr;
13676 
13677 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13678 		union DL_primitives *dl;
13679 
13680 		/*
13681 		 * Things are opening or closing. Only accept DLPI control
13682 		 * messages. In the open case, the ill->ill_ipif has not yet
13683 		 * been created. In the close case, things hanging off the
13684 		 * ill could have been freed already. In either case it
13685 		 * may not be safe to proceed further.
13686 		 */
13687 
13688 		dl = (union DL_primitives *)mp->b_rptr;
13689 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13690 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13691 			/*
13692 			 * Also SIOC[GS]TUN* ioctls can come here.
13693 			 */
13694 			inet_freemsg(mp);
13695 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13696 			    "ip_input_end: q %p (%S)", q, "uninit");
13697 			return;
13698 		}
13699 	}
13700 
13701 	/*
13702 	 * if db_ref > 1 then copymsg and free original. Packet may be
13703 	 * changed and we do not want the other entity who has a reference to
13704 	 * this message to trip over the changes. This is a blind change because
13705 	 * trying to catch all places that might change the packet is too
13706 	 * difficult.
13707 	 *
13708 	 * This corresponds to the fast path case, where we have a chain of
13709 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13710 	 * in the mblk chain. There doesn't seem to be a reason why a device
13711 	 * driver would send up data with varying db_ref counts in the mblk
13712 	 * chain. In any case the Fast path is a private interface, and our
13713 	 * drivers don't do such a thing. Given the above assumption, there is
13714 	 * no need to walk down the entire mblk chain (which could have a
13715 	 * potential performance problem)
13716 	 */
13717 	if (mp->b_datap->db_ref > 1) {
13718 		mblk_t  *mp1;
13719 		boolean_t adjusted = B_FALSE;
13720 		IP_STAT(ip_db_ref);
13721 
13722 		/*
13723 		 * The IP_RECVSLLA option depends on having the link layer
13724 		 * header. First check that:
13725 		 * a> the underlying device is of type ether, since this
13726 		 * option is currently supported only over ethernet.
13727 		 * b> there is enough room to copy over the link layer header.
13728 		 *
13729 		 * Once the checks are done, adjust rptr so that the link layer
13730 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13731 		 * be returned by some non-ethernet drivers but in this case the
13732 		 * second check will fail.
13733 		 */
13734 		if (ill->ill_type == IFT_ETHER &&
13735 		    (mp->b_rptr - mp->b_datap->db_base) >=
13736 		    sizeof (struct ether_header)) {
13737 			mp->b_rptr -= sizeof (struct ether_header);
13738 			adjusted = B_TRUE;
13739 		}
13740 		mp1 = copymsg(mp);
13741 		if (mp1 == NULL) {
13742 			/* Clear b_next - used in M_BREAK messages */
13743 			mp->b_next = NULL;
13744 			/* clear b_prev - used by ip_mroute_decap */
13745 			mp->b_prev = NULL;
13746 			freemsg(mp);
13747 			BUMP_MIB(&ip_mib, ipInDiscards);
13748 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13749 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13750 			return;
13751 		}
13752 		if (adjusted) {
13753 			/*
13754 			 * Copy is done. Restore the pointer in the _new_ mblk
13755 			 */
13756 			mp1->b_rptr += sizeof (struct ether_header);
13757 		}
13758 		/* Copy b_next - used in M_BREAK messages */
13759 		mp1->b_next = mp->b_next;
13760 		mp->b_next = NULL;
13761 		/* Copy b_prev - used by ip_mroute_decap */
13762 		mp1->b_prev = mp->b_prev;
13763 		mp->b_prev = NULL;
13764 		freemsg(mp);
13765 		mp = mp1;
13766 	}
13767 
13768 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13769 	    "ip_rput_end: q %p (%S)", q, "end");
13770 
13771 	ip_input(ill, NULL, mp, 0);
13772 }
13773 
13774 /*
13775  * Direct read side procedure capable of dealing with chains. GLDv3 based
13776  * drivers call this function directly with mblk chains while STREAMS
13777  * read side procedure ip_rput() calls this for single packet with ip_ring
13778  * set to NULL to process one packet at a time.
13779  *
13780  * The ill will always be valid if this function is called directly from
13781  * the driver.
13782  */
13783 /*ARGSUSED*/
13784 void
13785 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13786 {
13787 	ipaddr_t		dst;
13788 	ire_t			*ire;
13789 	ipha_t			*ipha;
13790 	uint_t			pkt_len;
13791 	ssize_t			len;
13792 	uint_t			opt_len;
13793 	int			ll_multicast;
13794 	int			cgtp_flt_pkt;
13795 	queue_t			*q = ill->ill_rq;
13796 	squeue_t		*curr_sqp = NULL;
13797 	mblk_t 			*head = NULL;
13798 	mblk_t			*tail = NULL;
13799 	mblk_t			*first_mp;
13800 	mblk_t 			*mp;
13801 	int			cnt = 0;
13802 
13803 	ASSERT(mp_chain != NULL);
13804 	ASSERT(ill != NULL);
13805 
13806 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13807 
13808 #define	rptr	((uchar_t *)ipha)
13809 
13810 	while (mp_chain != NULL) {
13811 		first_mp = mp = mp_chain;
13812 		mp_chain = mp_chain->b_next;
13813 		mp->b_next = NULL;
13814 		ll_multicast = 0;
13815 		ire = NULL;
13816 
13817 		/*
13818 		 * ip_input fast path
13819 		 */
13820 
13821 		/* mblk type is not M_DATA */
13822 		if (mp->b_datap->db_type != M_DATA) {
13823 			if (ip_rput_process_notdata(q, &first_mp, ill,
13824 			    &ll_multicast, &mp))
13825 				continue;
13826 		}
13827 
13828 		ASSERT(mp->b_datap->db_type == M_DATA);
13829 		ASSERT(mp->b_datap->db_ref == 1);
13830 
13831 
13832 		ipha = (ipha_t *)mp->b_rptr;
13833 		len = mp->b_wptr - rptr;
13834 
13835 		BUMP_MIB(&ip_mib, ipInReceives);
13836 
13837 		/*
13838 		 * IP header ptr not aligned?
13839 		 * OR IP header not complete in first mblk
13840 		 */
13841 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13842 			if (!ip_check_and_align_header(q, mp))
13843 				continue;
13844 			ipha = (ipha_t *)mp->b_rptr;
13845 			len = mp->b_wptr - rptr;
13846 		}
13847 
13848 		/* multiple mblk or too short */
13849 		pkt_len = ntohs(ipha->ipha_length);
13850 		len -= pkt_len;
13851 		if (len != 0) {
13852 			/*
13853 			 * Make sure we have data length consistent
13854 			 * with the IP header.
13855 			 */
13856 			if (mp->b_cont == NULL) {
13857 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13858 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13859 					ip2dbg(("ip_input: drop pkt\n"));
13860 					freemsg(mp);
13861 					continue;
13862 				}
13863 				mp->b_wptr = rptr + pkt_len;
13864 			} else if (len += msgdsize(mp->b_cont)) {
13865 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13866 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13867 					ip2dbg(("ip_input: drop pkt\n"));
13868 					freemsg(mp);
13869 					continue;
13870 				}
13871 				(void) adjmsg(mp, -len);
13872 				IP_STAT(ip_multimblk3);
13873 			}
13874 		}
13875 
13876 		if (ip_loopback_src_or_dst(ipha, ill)) {
13877 			ip2dbg(("ip_input: drop pkt\n"));
13878 			freemsg(mp);
13879 			continue;
13880 		}
13881 
13882 		/*
13883 		 * Attach any necessary label information to this packet.
13884 		 */
13885 		if (is_system_labeled() &&
13886 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
13887 			BUMP_MIB(&ip_mib, ipInDiscards);
13888 			freemsg(mp);
13889 			continue;
13890 		}
13891 
13892 		opt_len = ipha->ipha_version_and_hdr_length -
13893 		    IP_SIMPLE_HDR_VERSION;
13894 		/* IP version bad or there are IP options */
13895 		if (opt_len) {
13896 			if (len != 0)
13897 				IP_STAT(ip_multimblk4);
13898 			else
13899 				IP_STAT(ip_ipoptions);
13900 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13901 				continue;
13902 		} else {
13903 			dst = ipha->ipha_dst;
13904 		}
13905 
13906 		/*
13907 		 * Invoke the CGTP (multirouting) filtering module to process
13908 		 * the incoming packet. Packets identified as duplicates
13909 		 * must be discarded. Filtering is active only if the
13910 		 * the ip_cgtp_filter ndd variable is non-zero.
13911 		 */
13912 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13913 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13914 			cgtp_flt_pkt =
13915 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
13916 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13917 				freemsg(first_mp);
13918 				continue;
13919 			}
13920 		}
13921 
13922 		/*
13923 		 * If rsvpd is running, let RSVP daemon handle its processing
13924 		 * and forwarding of RSVP multicast/unicast packets.
13925 		 * If rsvpd is not running but mrouted is running, RSVP
13926 		 * multicast packets are forwarded as multicast traffic
13927 		 * and RSVP unicast packets are forwarded by unicast router.
13928 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13929 		 * packets are not forwarded, but the unicast packets are
13930 		 * forwarded like unicast traffic.
13931 		 */
13932 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13933 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13934 			/* RSVP packet and rsvpd running. Treat as ours */
13935 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13936 			/*
13937 			 * This assumes that we deliver to all streams for
13938 			 * multicast and broadcast packets.
13939 			 * We have to force ll_multicast to 1 to handle the
13940 			 * M_DATA messages passed in from ip_mroute_decap.
13941 			 */
13942 			dst = INADDR_BROADCAST;
13943 			ll_multicast = 1;
13944 		} else if (CLASSD(dst)) {
13945 			/* packet is multicast */
13946 			mp->b_next = NULL;
13947 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13948 			    &ll_multicast, &dst))
13949 				continue;
13950 		}
13951 
13952 
13953 		/*
13954 		 * Check if the packet is coming from the Mobile IP
13955 		 * forward tunnel interface
13956 		 */
13957 		if (ill->ill_srcif_refcnt > 0) {
13958 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13959 			    NULL, ill, MATCH_IRE_TYPE);
13960 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13961 			    ire->ire_ipif->ipif_net_type ==
13962 			    IRE_IF_RESOLVER) {
13963 				/* We need to resolve the link layer info */
13964 				ire_refrele(ire);
13965 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13966 				    ll_multicast, dst);
13967 				continue;
13968 			}
13969 		}
13970 
13971 		if (ire == NULL) {
13972 			ire = ire_cache_lookup(dst, ALL_ZONES,
13973 			    MBLK_GETLABEL(mp));
13974 		}
13975 
13976 		/*
13977 		 * If mipagent is running and reverse tunnel is created as per
13978 		 * mobile node request, then any packet coming through the
13979 		 * incoming interface from the mobile-node, should be reverse
13980 		 * tunneled to it's home agent except those that are destined
13981 		 * to foreign agent only.
13982 		 * This needs source address based ire lookup. The routing
13983 		 * entries for source address based lookup are only created by
13984 		 * mipagent program only when a reverse tunnel is created.
13985 		 * Reference : RFC2002, RFC2344
13986 		 */
13987 		if (ill->ill_mrtun_refcnt > 0) {
13988 			ipaddr_t	srcaddr;
13989 			ire_t		*tmp_ire;
13990 
13991 			tmp_ire = ire;	/* Save, we might need it later */
13992 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13993 			    ire->ire_type != IRE_BROADCAST)) {
13994 				srcaddr = ipha->ipha_src;
13995 				ire = ire_mrtun_lookup(srcaddr, ill);
13996 				if (ire != NULL) {
13997 					/*
13998 					 * Should not be getting iphada packet
13999 					 * here. we should only get those for
14000 					 * IRE_LOCAL traffic, excluded above.
14001 					 * Fail-safe (drop packet) in the event
14002 					 * hardware is misbehaving.
14003 					 */
14004 					if (first_mp != mp) {
14005 						/* IPsec KSTATS: beancount me */
14006 						freemsg(first_mp);
14007 					} else {
14008 						/*
14009 						 * This packet must be forwarded
14010 						 * to Reverse Tunnel
14011 						 */
14012 						ip_mrtun_forward(ire, ill, mp);
14013 					}
14014 					ire_refrele(ire);
14015 					if (tmp_ire != NULL)
14016 						ire_refrele(tmp_ire);
14017 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14018 					    "ip_input_end: q %p (%S)",
14019 					    q, "uninit");
14020 					continue;
14021 				}
14022 			}
14023 			/*
14024 			 * If this packet is from a non-mobilenode  or a
14025 			 * mobile-node which does not request reverse
14026 			 * tunnel service
14027 			 */
14028 			ire = tmp_ire;
14029 		}
14030 
14031 
14032 		/*
14033 		 * If we reach here that means the incoming packet satisfies
14034 		 * one of the following conditions:
14035 		 *   - packet is from a mobile node which does not request
14036 		 *	reverse tunnel
14037 		 *   - packet is from a non-mobile node, which is the most
14038 		 *	common case
14039 		 *   - packet is from a reverse tunnel enabled mobile node
14040 		 *	and destined to foreign agent only
14041 		 */
14042 
14043 		if (ire == NULL) {
14044 			/*
14045 			 * No IRE for this destination, so it can't be for us.
14046 			 * Unless we are forwarding, drop the packet.
14047 			 * We have to let source routed packets through
14048 			 * since we don't yet know if they are 'ping -l'
14049 			 * packets i.e. if they will go out over the
14050 			 * same interface as they came in on.
14051 			 */
14052 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14053 			continue;
14054 		}
14055 
14056 		/*
14057 		 * Broadcast IRE may indicate either broadcast or
14058 		 * multicast packet
14059 		 */
14060 		if (ire->ire_type == IRE_BROADCAST) {
14061 			/*
14062 			 * Skip broadcast checks if packet is UDP multicast;
14063 			 * we'd rather not enter ip_rput_process_broadcast()
14064 			 * unless the packet is broadcast for real, since
14065 			 * that routine is a no-op for multicast.
14066 			 */
14067 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
14068 			    !CLASSD(ipha->ipha_dst)) &&
14069 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
14070 			    dst, cgtp_flt_pkt, ll_multicast)) {
14071 				continue;
14072 			}
14073 		} else if (ire->ire_stq != NULL) {
14074 			/* fowarding? */
14075 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14076 			    ll_multicast);
14077 			continue;
14078 		}
14079 
14080 		/* packet not for us */
14081 		if (ire->ire_rfq != q) {
14082 			if (ip_rput_notforus(&q, mp, ire, ill)) {
14083 				continue;
14084 			}
14085 		}
14086 
14087 		switch (ipha->ipha_protocol) {
14088 		case IPPROTO_TCP:
14089 			ASSERT(first_mp == mp);
14090 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14091 				mp, 0, q, ip_ring)) != NULL) {
14092 				if (curr_sqp == NULL) {
14093 					curr_sqp = GET_SQUEUE(mp);
14094 					ASSERT(cnt == 0);
14095 					cnt++;
14096 					head = tail = mp;
14097 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14098 					ASSERT(tail != NULL);
14099 					cnt++;
14100 					tail->b_next = mp;
14101 					tail = mp;
14102 				} else {
14103 					/*
14104 					 * A different squeue. Send the
14105 					 * chain for the previous squeue on
14106 					 * its way. This shouldn't happen
14107 					 * often unless interrupt binding
14108 					 * changes.
14109 					 */
14110 					IP_STAT(ip_input_multi_squeue);
14111 					squeue_enter_chain(curr_sqp, head,
14112 					    tail, cnt, SQTAG_IP_INPUT);
14113 					curr_sqp = GET_SQUEUE(mp);
14114 					head = mp;
14115 					tail = mp;
14116 					cnt = 1;
14117 				}
14118 			}
14119 			IRE_REFRELE(ire);
14120 			continue;
14121 		case IPPROTO_UDP:
14122 			ASSERT(first_mp == mp);
14123 			ip_udp_input(q, mp, ipha, ire, ill);
14124 			IRE_REFRELE(ire);
14125 			continue;
14126 		case IPPROTO_SCTP:
14127 			ASSERT(first_mp == mp);
14128 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14129 			    q, dst);
14130 			continue;
14131 		default:
14132 			ip_proto_input(q, first_mp, ipha, ire, ill);
14133 			IRE_REFRELE(ire);
14134 			continue;
14135 		}
14136 	}
14137 
14138 	if (head != NULL)
14139 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14140 
14141 	/*
14142 	 * This code is there just to make netperf/ttcp look good.
14143 	 *
14144 	 * Its possible that after being in polling mode (and having cleared
14145 	 * the backlog), squeues have turned the interrupt frequency higher
14146 	 * to improve latency at the expense of more CPU utilization (less
14147 	 * packets per interrupts or more number of interrupts). Workloads
14148 	 * like ttcp/netperf do manage to tickle polling once in a while
14149 	 * but for the remaining time, stay in higher interrupt mode since
14150 	 * their packet arrival rate is pretty uniform and this shows up
14151 	 * as higher CPU utilization. Since people care about CPU utilization
14152 	 * while running netperf/ttcp, turn the interrupt frequency back to
14153 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14154 	 */
14155 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14156 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14157 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14158 			ip_ring->rr_blank(ip_ring->rr_handle,
14159 			    ip_ring->rr_normal_blank_time,
14160 			    ip_ring->rr_normal_pkt_cnt);
14161 		}
14162 	}
14163 
14164 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14165 	    "ip_input_end: q %p (%S)", q, "end");
14166 #undef	rptr
14167 }
14168 
14169 static void
14170 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14171     t_uscalar_t err)
14172 {
14173 	if (dl_err == DL_SYSERR) {
14174 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14175 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14176 		    ill->ill_name, dlpi_prim_str(prim), err);
14177 		return;
14178 	}
14179 
14180 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14181 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14182 	    dlpi_err_str(dl_err));
14183 }
14184 
14185 /*
14186  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14187  * than DL_UNITDATA_IND messages. If we need to process this message
14188  * exclusively, we call qwriter_ip, in which case we also need to call
14189  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14190  */
14191 void
14192 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14193 {
14194 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14195 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14196 	ill_t		*ill;
14197 
14198 	ip1dbg(("ip_rput_dlpi"));
14199 	ill = (ill_t *)q->q_ptr;
14200 	switch (dloa->dl_primitive) {
14201 	case DL_ERROR_ACK:
14202 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14203 		    "%s (0x%x), unix %u\n", ill->ill_name,
14204 		    dlpi_prim_str(dlea->dl_error_primitive),
14205 		    dlea->dl_error_primitive,
14206 		    dlpi_err_str(dlea->dl_errno),
14207 		    dlea->dl_errno,
14208 		    dlea->dl_unix_errno));
14209 		switch (dlea->dl_error_primitive) {
14210 		case DL_UNBIND_REQ:
14211 			mutex_enter(&ill->ill_lock);
14212 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14213 			cv_signal(&ill->ill_cv);
14214 			mutex_exit(&ill->ill_lock);
14215 			/* FALLTHRU */
14216 		case DL_NOTIFY_REQ:
14217 		case DL_ATTACH_REQ:
14218 		case DL_DETACH_REQ:
14219 		case DL_INFO_REQ:
14220 		case DL_BIND_REQ:
14221 		case DL_ENABMULTI_REQ:
14222 		case DL_PHYS_ADDR_REQ:
14223 		case DL_CAPABILITY_REQ:
14224 		case DL_CONTROL_REQ:
14225 			/*
14226 			 * Refhold the ill to match qwriter_ip which does a
14227 			 * refrele. Since this is on the ill stream we
14228 			 * unconditionally bump up the refcount without
14229 			 * checking for ILL_CAN_LOOKUP
14230 			 */
14231 			ill_refhold(ill);
14232 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14233 			    CUR_OP, B_FALSE);
14234 			return;
14235 		case DL_DISABMULTI_REQ:
14236 			freemsg(mp);	/* Don't want to pass this up */
14237 			return;
14238 		default:
14239 			break;
14240 		}
14241 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14242 		    dlea->dl_errno, dlea->dl_unix_errno);
14243 		freemsg(mp);
14244 		return;
14245 	case DL_INFO_ACK:
14246 	case DL_BIND_ACK:
14247 	case DL_PHYS_ADDR_ACK:
14248 	case DL_NOTIFY_ACK:
14249 	case DL_CAPABILITY_ACK:
14250 	case DL_CONTROL_ACK:
14251 		/*
14252 		 * Refhold the ill to match qwriter_ip which does a refrele
14253 		 * Since this is on the ill stream we unconditionally
14254 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14255 		 */
14256 		ill_refhold(ill);
14257 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14258 		    CUR_OP, B_FALSE);
14259 		return;
14260 	case DL_NOTIFY_IND:
14261 		ill_refhold(ill);
14262 		/*
14263 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14264 		 * relation to the current ioctl in progress (if any). Hence we
14265 		 * pass in NEW_OP in this case.
14266 		 */
14267 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14268 		    NEW_OP, B_FALSE);
14269 		return;
14270 	case DL_OK_ACK:
14271 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14272 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14273 		switch (dloa->dl_correct_primitive) {
14274 		case DL_UNBIND_REQ:
14275 			mutex_enter(&ill->ill_lock);
14276 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14277 			cv_signal(&ill->ill_cv);
14278 			mutex_exit(&ill->ill_lock);
14279 			/* FALLTHRU */
14280 		case DL_ATTACH_REQ:
14281 		case DL_DETACH_REQ:
14282 			/*
14283 			 * Refhold the ill to match qwriter_ip which does a
14284 			 * refrele. Since this is on the ill stream we
14285 			 * unconditionally bump up the refcount
14286 			 */
14287 			ill_refhold(ill);
14288 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14289 			    CUR_OP, B_FALSE);
14290 			return;
14291 		case DL_ENABMULTI_REQ:
14292 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14293 				ill->ill_dlpi_multicast_state = IDMS_OK;
14294 			break;
14295 
14296 		}
14297 		break;
14298 	default:
14299 		break;
14300 	}
14301 	freemsg(mp);
14302 }
14303 
14304 /*
14305  * Handling of DLPI messages that require exclusive access to the ipsq.
14306  *
14307  * Need to do ill_pending_mp_release on ioctl completion, which could
14308  * happen here. (along with mi_copy_done)
14309  */
14310 /* ARGSUSED */
14311 static void
14312 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14313 {
14314 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14315 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14316 	int		err = 0;
14317 	ill_t		*ill;
14318 	ipif_t		*ipif = NULL;
14319 	mblk_t		*mp1 = NULL;
14320 	conn_t		*connp = NULL;
14321 	t_uscalar_t	physaddr_req;
14322 	mblk_t		*mp_hw;
14323 	union DL_primitives *dlp;
14324 	boolean_t	success;
14325 	boolean_t	ioctl_aborted = B_FALSE;
14326 	boolean_t	log = B_TRUE;
14327 
14328 	ip1dbg(("ip_rput_dlpi_writer .."));
14329 	ill = (ill_t *)q->q_ptr;
14330 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14331 
14332 	ASSERT(IAM_WRITER_ILL(ill));
14333 
14334 	/*
14335 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14336 	 * both are null or non-null. However we can assert that only
14337 	 * after grabbing the ipsq_lock. So we don't make any assertion
14338 	 * here and in other places in the code.
14339 	 */
14340 	ipif = ipsq->ipsq_pending_ipif;
14341 	/*
14342 	 * The current ioctl could have been aborted by the user and a new
14343 	 * ioctl to bring up another ill could have started. We could still
14344 	 * get a response from the driver later.
14345 	 */
14346 	if (ipif != NULL && ipif->ipif_ill != ill)
14347 		ioctl_aborted = B_TRUE;
14348 
14349 	switch (dloa->dl_primitive) {
14350 	case DL_ERROR_ACK:
14351 		switch (dlea->dl_error_primitive) {
14352 		case DL_UNBIND_REQ:
14353 		case DL_ATTACH_REQ:
14354 		case DL_DETACH_REQ:
14355 		case DL_INFO_REQ:
14356 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14357 			break;
14358 		case DL_NOTIFY_REQ:
14359 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
14360 			log = B_FALSE;
14361 			break;
14362 		case DL_PHYS_ADDR_REQ:
14363 			/*
14364 			 * For IPv6 only, there are two additional
14365 			 * phys_addr_req's sent to the driver to get the
14366 			 * IPv6 token and lla. This allows IP to acquire
14367 			 * the hardware address format for a given interface
14368 			 * without having built in knowledge of the hardware
14369 			 * address. ill_phys_addr_pend keeps track of the last
14370 			 * DL_PAR sent so we know which response we are
14371 			 * dealing with. ill_dlpi_done will update
14372 			 * ill_phys_addr_pend when it sends the next req.
14373 			 * We don't complete the IOCTL until all three DL_PARs
14374 			 * have been attempted, so set *_len to 0 and break.
14375 			 */
14376 			physaddr_req = ill->ill_phys_addr_pend;
14377 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14378 			if (physaddr_req == DL_IPV6_TOKEN) {
14379 				ill->ill_token_length = 0;
14380 				log = B_FALSE;
14381 				break;
14382 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14383 				ill->ill_nd_lla_len = 0;
14384 				log = B_FALSE;
14385 				break;
14386 			}
14387 			/*
14388 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
14389 			 * We presumably have an IOCTL hanging out waiting
14390 			 * for completion. Find it and complete the IOCTL
14391 			 * with the error noted.
14392 			 * However, ill_dl_phys was called on an ill queue
14393 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
14394 			 * set. But the ioctl is known to be pending on ill_wq.
14395 			 */
14396 			if (!ill->ill_ifname_pending)
14397 				break;
14398 			ill->ill_ifname_pending = 0;
14399 			if (!ioctl_aborted)
14400 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14401 			if (mp1 != NULL) {
14402 				/*
14403 				 * This operation (SIOCSLIFNAME) must have
14404 				 * happened on the ill. Assert there is no conn
14405 				 */
14406 				ASSERT(connp == NULL);
14407 				q = ill->ill_wq;
14408 			}
14409 			break;
14410 		case DL_BIND_REQ:
14411 			ill_dlpi_done(ill, DL_BIND_REQ);
14412 			if (ill->ill_ifname_pending)
14413 				break;
14414 			/*
14415 			 * Something went wrong with the bind.  We presumably
14416 			 * have an IOCTL hanging out waiting for completion.
14417 			 * Find it, take down the interface that was coming
14418 			 * up, and complete the IOCTL with the error noted.
14419 			 */
14420 			if (!ioctl_aborted)
14421 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14422 			if (mp1 != NULL) {
14423 				/*
14424 				 * This operation (SIOCSLIFFLAGS) must have
14425 				 * happened from a conn.
14426 				 */
14427 				ASSERT(connp != NULL);
14428 				q = CONNP_TO_WQ(connp);
14429 				if (ill->ill_move_in_progress) {
14430 					ILL_CLEAR_MOVE(ill);
14431 				}
14432 				(void) ipif_down(ipif, NULL, NULL);
14433 				/* error is set below the switch */
14434 			}
14435 			break;
14436 		case DL_ENABMULTI_REQ:
14437 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
14438 
14439 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14440 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
14441 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
14442 				ipif_t *ipif;
14443 
14444 				log = B_FALSE;
14445 				printf("ip: joining multicasts failed (%d)"
14446 				    " on %s - will use link layer "
14447 				    "broadcasts for multicast\n",
14448 				    dlea->dl_errno, ill->ill_name);
14449 
14450 				/*
14451 				 * Set up the multicast mapping alone.
14452 				 * writer, so ok to access ill->ill_ipif
14453 				 * without any lock.
14454 				 */
14455 				ipif = ill->ill_ipif;
14456 				mutex_enter(&ill->ill_phyint->phyint_lock);
14457 				ill->ill_phyint->phyint_flags |=
14458 				    PHYI_MULTI_BCAST;
14459 				mutex_exit(&ill->ill_phyint->phyint_lock);
14460 
14461 				if (!ill->ill_isv6) {
14462 					(void) ipif_arp_setup_multicast(ipif,
14463 					    NULL);
14464 				} else {
14465 					(void) ipif_ndp_setup_multicast(ipif,
14466 					    NULL);
14467 				}
14468 			}
14469 			freemsg(mp);	/* Don't want to pass this up */
14470 			return;
14471 		case DL_CAPABILITY_REQ:
14472 		case DL_CONTROL_REQ:
14473 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
14474 			    "DL_CAPABILITY/CONTROL REQ\n"));
14475 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14476 			ill->ill_capab_state = IDMS_FAILED;
14477 			freemsg(mp);
14478 			return;
14479 		}
14480 		/*
14481 		 * Note the error for IOCTL completion (mp1 is set when
14482 		 * ready to complete ioctl). If ill_ifname_pending_err is
14483 		 * set, an error occured during plumbing (ill_ifname_pending),
14484 		 * so we want to report that error.
14485 		 *
14486 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
14487 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
14488 		 * expected to get errack'd if the driver doesn't support
14489 		 * these flags (e.g. ethernet). log will be set to B_FALSE
14490 		 * if these error conditions are encountered.
14491 		 */
14492 		if (mp1 != NULL) {
14493 			if (ill->ill_ifname_pending_err != 0)  {
14494 				err = ill->ill_ifname_pending_err;
14495 				ill->ill_ifname_pending_err = 0;
14496 			} else {
14497 				err = dlea->dl_unix_errno ?
14498 				    dlea->dl_unix_errno : ENXIO;
14499 			}
14500 		/*
14501 		 * If we're plumbing an interface and an error hasn't already
14502 		 * been saved, set ill_ifname_pending_err to the error passed
14503 		 * up. Ignore the error if log is B_FALSE (see comment above).
14504 		 */
14505 		} else if (log && ill->ill_ifname_pending &&
14506 		    ill->ill_ifname_pending_err == 0) {
14507 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
14508 			dlea->dl_unix_errno : ENXIO;
14509 		}
14510 
14511 		if (log)
14512 			ip_dlpi_error(ill, dlea->dl_error_primitive,
14513 			    dlea->dl_errno, dlea->dl_unix_errno);
14514 		break;
14515 	case DL_CAPABILITY_ACK: {
14516 		boolean_t reneg_flag = B_FALSE;
14517 		/* Call a routine to handle this one. */
14518 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
14519 		/*
14520 		 * Check if the ACK is due to renegotiation case since we
14521 		 * will need to send a new CAPABILITY_REQ later.
14522 		 */
14523 		if (ill->ill_capab_state == IDMS_RENEG) {
14524 			/* This is the ack for a renogiation case */
14525 			reneg_flag = B_TRUE;
14526 			ill->ill_capab_state = IDMS_UNKNOWN;
14527 		}
14528 		ill_capability_ack(ill, mp);
14529 		if (reneg_flag)
14530 			ill_capability_probe(ill);
14531 		break;
14532 	}
14533 	case DL_CONTROL_ACK:
14534 		/* We treat all of these as "fire and forget" */
14535 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14536 		break;
14537 	case DL_INFO_ACK:
14538 		/* Call a routine to handle this one. */
14539 		ill_dlpi_done(ill, DL_INFO_REQ);
14540 		ip_ll_subnet_defaults(ill, mp);
14541 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14542 		return;
14543 	case DL_BIND_ACK:
14544 		/*
14545 		 * We should have an IOCTL waiting on this unless
14546 		 * sent by ill_dl_phys, in which case just return
14547 		 */
14548 		ill_dlpi_done(ill, DL_BIND_REQ);
14549 		if (ill->ill_ifname_pending)
14550 			break;
14551 
14552 		if (!ioctl_aborted)
14553 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14554 		if (mp1 == NULL)
14555 			break;
14556 		ASSERT(connp != NULL);
14557 		q = CONNP_TO_WQ(connp);
14558 
14559 		/*
14560 		 * We are exclusive. So nothing can change even after
14561 		 * we get the pending mp. If need be we can put it back
14562 		 * and restart, as in calling ipif_arp_up()  below.
14563 		 */
14564 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14565 
14566 		mutex_enter(&ill->ill_lock);
14567 		ill->ill_dl_up = 1;
14568 		mutex_exit(&ill->ill_lock);
14569 
14570 		/*
14571 		 * Now bring up the resolver, when that is
14572 		 * done we'll create IREs and we are done.
14573 		 */
14574 		if (ill->ill_isv6) {
14575 			/*
14576 			 * v6 interfaces.
14577 			 * Unlike ARP which has to do another bind
14578 			 * and attach, once we get here we are
14579 			 * done withh NDP. Except in the case of
14580 			 * ILLF_XRESOLV, in which case we send an
14581 			 * AR_INTERFACE_UP to the external resolver.
14582 			 * If all goes well, the ioctl will complete
14583 			 * in ip_rput(). If there's an error, we
14584 			 * complete it here.
14585 			 */
14586 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14587 			    B_FALSE);
14588 			if (err == 0) {
14589 				if (ill->ill_flags & ILLF_XRESOLV) {
14590 					mutex_enter(&connp->conn_lock);
14591 					mutex_enter(&ill->ill_lock);
14592 					success = ipsq_pending_mp_add(
14593 					    connp, ipif, q, mp1, 0);
14594 					mutex_exit(&ill->ill_lock);
14595 					mutex_exit(&connp->conn_lock);
14596 					if (success) {
14597 						err = ipif_resolver_up(ipif,
14598 						    B_FALSE);
14599 						if (err == EINPROGRESS) {
14600 							freemsg(mp);
14601 							return;
14602 						}
14603 						ASSERT(err != 0);
14604 						mp1 = ipsq_pending_mp_get(ipsq,
14605 						    &connp);
14606 						ASSERT(mp1 != NULL);
14607 					} else {
14608 						/* conn has started closing */
14609 						err = EINTR;
14610 					}
14611 				} else { /* Non XRESOLV interface */
14612 					err = ipif_up_done_v6(ipif);
14613 				}
14614 			}
14615 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14616 			/*
14617 			 * ARP and other v4 external resolvers.
14618 			 * Leave the pending mblk intact so that
14619 			 * the ioctl completes in ip_rput().
14620 			 */
14621 			mutex_enter(&connp->conn_lock);
14622 			mutex_enter(&ill->ill_lock);
14623 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14624 			mutex_exit(&ill->ill_lock);
14625 			mutex_exit(&connp->conn_lock);
14626 			if (success) {
14627 				err = ipif_resolver_up(ipif, B_FALSE);
14628 				if (err == EINPROGRESS) {
14629 					freemsg(mp);
14630 					return;
14631 				}
14632 				ASSERT(err != 0);
14633 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14634 			} else {
14635 				/* The conn has started closing */
14636 				err = EINTR;
14637 			}
14638 		} else {
14639 			/*
14640 			 * This one is complete. Reply to pending ioctl.
14641 			 */
14642 			err = ipif_up_done(ipif);
14643 		}
14644 
14645 		if ((err == 0) && (ill->ill_up_ipifs)) {
14646 			err = ill_up_ipifs(ill, q, mp1);
14647 			if (err == EINPROGRESS) {
14648 				freemsg(mp);
14649 				return;
14650 			}
14651 		}
14652 
14653 		if (ill->ill_up_ipifs) {
14654 			ill_group_cleanup(ill);
14655 		}
14656 
14657 		break;
14658 	case DL_NOTIFY_IND: {
14659 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14660 		ire_t *ire;
14661 		boolean_t need_ire_walk_v4 = B_FALSE;
14662 		boolean_t need_ire_walk_v6 = B_FALSE;
14663 
14664 		/*
14665 		 * Change the address everywhere we need to.
14666 		 * What we're getting here is a link-level addr or phys addr.
14667 		 * The new addr is at notify + notify->dl_addr_offset
14668 		 * The address length is notify->dl_addr_length;
14669 		 */
14670 		switch (notify->dl_notification) {
14671 		case DL_NOTE_PHYS_ADDR:
14672 			mp_hw = copyb(mp);
14673 			if (mp_hw == NULL) {
14674 				err = ENOMEM;
14675 				break;
14676 			}
14677 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14678 			/*
14679 			 * We currently don't support changing
14680 			 * the token via DL_NOTIFY_IND.
14681 			 * When we do support it, we have to consider
14682 			 * what the implications are with respect to
14683 			 * the token and the link local address.
14684 			 */
14685 			mutex_enter(&ill->ill_lock);
14686 			if (dlp->notify_ind.dl_data ==
14687 			    DL_IPV6_LINK_LAYER_ADDR) {
14688 				if (ill->ill_nd_lla_mp != NULL)
14689 					freemsg(ill->ill_nd_lla_mp);
14690 				ill->ill_nd_lla_mp = mp_hw;
14691 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14692 				    dlp->notify_ind.dl_addr_offset;
14693 				ill->ill_nd_lla_len =
14694 				    dlp->notify_ind.dl_addr_length -
14695 				    ABS(ill->ill_sap_length);
14696 				mutex_exit(&ill->ill_lock);
14697 				break;
14698 			} else if (dlp->notify_ind.dl_data ==
14699 			    DL_CURR_PHYS_ADDR) {
14700 				if (ill->ill_phys_addr_mp != NULL)
14701 					freemsg(ill->ill_phys_addr_mp);
14702 				ill->ill_phys_addr_mp = mp_hw;
14703 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14704 				    dlp->notify_ind.dl_addr_offset;
14705 				ill->ill_phys_addr_length =
14706 				    dlp->notify_ind.dl_addr_length -
14707 				    ABS(ill->ill_sap_length);
14708 				if (ill->ill_isv6 &&
14709 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14710 					if (ill->ill_nd_lla_mp != NULL)
14711 						freemsg(ill->ill_nd_lla_mp);
14712 					ill->ill_nd_lla_mp = copyb(mp_hw);
14713 					ill->ill_nd_lla = (uchar_t *)
14714 					    ill->ill_nd_lla_mp->b_rptr +
14715 					    dlp->notify_ind.dl_addr_offset;
14716 					ill->ill_nd_lla_len =
14717 					    ill->ill_phys_addr_length;
14718 				}
14719 			}
14720 			mutex_exit(&ill->ill_lock);
14721 			/*
14722 			 * Send out gratuitous arp request for our new
14723 			 * hardware address.
14724 			 */
14725 			for (ipif = ill->ill_ipif; ipif != NULL;
14726 			    ipif = ipif->ipif_next) {
14727 				if (!(ipif->ipif_flags & IPIF_UP))
14728 					continue;
14729 				if (ill->ill_isv6) {
14730 					ipif_ndp_down(ipif);
14731 					/*
14732 					 * Set B_TRUE to enable
14733 					 * ipif_ndp_up() to send out
14734 					 * unsolicited advertisements.
14735 					 */
14736 					err = ipif_ndp_up(ipif,
14737 					    &ipif->ipif_v6lcl_addr,
14738 					    B_TRUE);
14739 					if (err) {
14740 						ip1dbg((
14741 						    "ip_rput_dlpi_writer: "
14742 						    "Failed to update ndp "
14743 						    "err %d\n", err));
14744 					}
14745 				} else {
14746 					/*
14747 					 * IPv4 ARP case
14748 					 *
14749 					 * Set B_TRUE, as we only want
14750 					 * ipif_resolver_up to send an
14751 					 * AR_ENTRY_ADD request up to
14752 					 * ARP.
14753 					 */
14754 					err = ipif_resolver_up(ipif,
14755 					    B_TRUE);
14756 					if (err) {
14757 						ip1dbg((
14758 						    "ip_rput_dlpi_writer: "
14759 						    "Failed to update arp "
14760 						    "err %d\n", err));
14761 					}
14762 				}
14763 			}
14764 			/*
14765 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14766 			 * case so that all old fastpath information can be
14767 			 * purged from IRE caches.
14768 			 */
14769 		/* FALLTHRU */
14770 		case DL_NOTE_FASTPATH_FLUSH:
14771 			/*
14772 			 * Any fastpath probe sent henceforth will get the
14773 			 * new fp mp. So we first delete any ires that are
14774 			 * waiting for the fastpath. Then walk all ires and
14775 			 * delete the ire or delete the fp mp. In the case of
14776 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14777 			 * recreate the ire's without going through a complex
14778 			 * ipif up/down dance. So we don't delete the ire
14779 			 * itself, but just the ire_fp_mp for these 2 ire's
14780 			 * In the case of the other ire's we delete the ire's
14781 			 * themselves. Access to ire_fp_mp is completely
14782 			 * protected by ire_lock for IRE_MIPRTUN and
14783 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14784 			 * other cases for performance.
14785 			 */
14786 			if (ill->ill_isv6) {
14787 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14788 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14789 				    NULL);
14790 			} else {
14791 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14792 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14793 				    IRE_CACHE | IRE_BROADCAST,
14794 				    ire_fastpath_flush, NULL, ill);
14795 				mutex_enter(&ire_mrtun_lock);
14796 				if (ire_mrtun_count != 0) {
14797 					mutex_exit(&ire_mrtun_lock);
14798 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14799 					    IRE_MIPRTUN, ire_fastpath_flush,
14800 					    NULL, ill);
14801 				} else {
14802 					mutex_exit(&ire_mrtun_lock);
14803 				}
14804 			}
14805 			break;
14806 		case DL_NOTE_SDU_SIZE:
14807 			/*
14808 			 * Change the MTU size of the interface, of all
14809 			 * attached ipif's, and of all relevant ire's.  The
14810 			 * new value's a uint32_t at notify->dl_data.
14811 			 * Mtu change Vs. new ire creation - protocol below.
14812 			 *
14813 			 * a Mark the ipif as IPIF_CHANGING.
14814 			 * b Set the new mtu in the ipif.
14815 			 * c Change the ire_max_frag on all affected ires
14816 			 * d Unmark the IPIF_CHANGING
14817 			 *
14818 			 * To see how the protocol works, assume an interface
14819 			 * route is also being added simultaneously by
14820 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14821 			 * the ire. If the ire is created before step a,
14822 			 * it will be cleaned up by step c. If the ire is
14823 			 * created after step d, it will see the new value of
14824 			 * ipif_mtu. Any attempt to create the ire between
14825 			 * steps a to d will fail because of the IPIF_CHANGING
14826 			 * flag. Note that ire_create() is passed a pointer to
14827 			 * the ipif_mtu, and not the value. During ire_add
14828 			 * under the bucket lock, the ire_max_frag of the
14829 			 * new ire being created is set from the ipif/ire from
14830 			 * which it is being derived.
14831 			 */
14832 			mutex_enter(&ill->ill_lock);
14833 			ill->ill_max_frag = (uint_t)notify->dl_data;
14834 
14835 			/*
14836 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14837 			 * leave it alone
14838 			 */
14839 			if (ill->ill_mtu_userspecified) {
14840 				mutex_exit(&ill->ill_lock);
14841 				break;
14842 			}
14843 			ill->ill_max_mtu = ill->ill_max_frag;
14844 			if (ill->ill_isv6) {
14845 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14846 					ill->ill_max_mtu = IPV6_MIN_MTU;
14847 			} else {
14848 				if (ill->ill_max_mtu < IP_MIN_MTU)
14849 					ill->ill_max_mtu = IP_MIN_MTU;
14850 			}
14851 			for (ipif = ill->ill_ipif; ipif != NULL;
14852 			    ipif = ipif->ipif_next) {
14853 				/*
14854 				 * Don't override the mtu if the user
14855 				 * has explicitly set it.
14856 				 */
14857 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14858 					continue;
14859 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14860 				if (ipif->ipif_isv6)
14861 					ire = ipif_to_ire_v6(ipif);
14862 				else
14863 					ire = ipif_to_ire(ipif);
14864 				if (ire != NULL) {
14865 					ire->ire_max_frag = ipif->ipif_mtu;
14866 					ire_refrele(ire);
14867 				}
14868 				if (ipif->ipif_flags & IPIF_UP) {
14869 					if (ill->ill_isv6)
14870 						need_ire_walk_v6 = B_TRUE;
14871 					else
14872 						need_ire_walk_v4 = B_TRUE;
14873 				}
14874 			}
14875 			mutex_exit(&ill->ill_lock);
14876 			if (need_ire_walk_v4)
14877 				ire_walk_v4(ill_mtu_change, (char *)ill,
14878 				    ALL_ZONES);
14879 			if (need_ire_walk_v6)
14880 				ire_walk_v6(ill_mtu_change, (char *)ill,
14881 				    ALL_ZONES);
14882 			break;
14883 		case DL_NOTE_LINK_UP:
14884 		case DL_NOTE_LINK_DOWN: {
14885 			/*
14886 			 * We are writer. ill / phyint / ipsq assocs stable.
14887 			 * The RUNNING flag reflects the state of the link.
14888 			 */
14889 			phyint_t *phyint = ill->ill_phyint;
14890 			uint64_t new_phyint_flags;
14891 			boolean_t changed = B_FALSE;
14892 
14893 			mutex_enter(&phyint->phyint_lock);
14894 			new_phyint_flags =
14895 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14896 			    phyint->phyint_flags | PHYI_RUNNING :
14897 			    phyint->phyint_flags & ~PHYI_RUNNING;
14898 			if (new_phyint_flags != phyint->phyint_flags) {
14899 				phyint->phyint_flags = new_phyint_flags;
14900 				changed = B_TRUE;
14901 			}
14902 			mutex_exit(&phyint->phyint_lock);
14903 			/*
14904 			 * If the flags have changed, send a message to
14905 			 * the routing socket.
14906 			 */
14907 			if (changed) {
14908 				if (phyint->phyint_illv4 != NULL) {
14909 					ip_rts_ifmsg(
14910 					    phyint->phyint_illv4->ill_ipif);
14911 				}
14912 				if (phyint->phyint_illv6 != NULL) {
14913 					ip_rts_ifmsg(
14914 					    phyint->phyint_illv6->ill_ipif);
14915 				}
14916 			}
14917 			break;
14918 		}
14919 		case DL_NOTE_PROMISC_ON_PHYS:
14920 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14921 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14922 			mutex_enter(&ill->ill_lock);
14923 			ill->ill_promisc_on_phys = B_TRUE;
14924 			mutex_exit(&ill->ill_lock);
14925 			break;
14926 		case DL_NOTE_PROMISC_OFF_PHYS:
14927 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14928 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14929 			mutex_enter(&ill->ill_lock);
14930 			ill->ill_promisc_on_phys = B_FALSE;
14931 			mutex_exit(&ill->ill_lock);
14932 			break;
14933 		case DL_NOTE_CAPAB_RENEG:
14934 			/*
14935 			 * Something changed on the driver side.
14936 			 * It wants us to renegotiate the capabilities
14937 			 * on this ill. The most likely cause is the
14938 			 * aggregation interface under us where a
14939 			 * port got added or went away.
14940 			 *
14941 			 * We reset the capabilities and set the
14942 			 * state to IDMS_RENG so that when the ack
14943 			 * comes back, we can start the
14944 			 * renegotiation process.
14945 			 */
14946 			ill_capability_reset(ill);
14947 			ill->ill_capab_state = IDMS_RENEG;
14948 			break;
14949 		default:
14950 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14951 			    "type 0x%x for DL_NOTIFY_IND\n",
14952 			    notify->dl_notification));
14953 			break;
14954 		}
14955 
14956 		/*
14957 		 * As this is an asynchronous operation, we
14958 		 * should not call ill_dlpi_done
14959 		 */
14960 		break;
14961 	}
14962 	case DL_NOTIFY_ACK:
14963 		/*
14964 		 * Don't really need to check for what notifications
14965 		 * are supported; we'll process what gets sent upstream,
14966 		 * and we know it'll be something we support changing
14967 		 * based on our DL_NOTIFY_REQ.
14968 		 */
14969 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14970 		break;
14971 	case DL_PHYS_ADDR_ACK: {
14972 		/*
14973 		 * We should have an IOCTL waiting on this when request
14974 		 * sent by ill_dl_phys.
14975 		 * However, ill_dl_phys was called on an ill queue (from
14976 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14977 		 * ioctl is known to be pending on ill_wq.
14978 		 * There are two additional phys_addr_req's sent to the
14979 		 * driver to get the token and lla. ill_phys_addr_pend
14980 		 * keeps track of the last one sent so we know which
14981 		 * response we are dealing with. ill_dlpi_done will
14982 		 * update ill_phys_addr_pend when it sends the next req.
14983 		 * We don't complete the IOCTL until all three DL_PARs
14984 		 * have been attempted.
14985 		 *
14986 		 * We don't need any lock to update ill_nd_lla* fields,
14987 		 * since the ill is not yet up, We grab the lock just
14988 		 * for uniformity with other code that accesses ill_nd_lla.
14989 		 */
14990 		physaddr_req = ill->ill_phys_addr_pend;
14991 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14992 		if (physaddr_req == DL_IPV6_TOKEN ||
14993 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14994 			if (physaddr_req == DL_IPV6_TOKEN) {
14995 				/*
14996 				 * bcopy to low-order bits of ill_token
14997 				 *
14998 				 * XXX Temporary hack - currently,
14999 				 * all known tokens are 64 bits,
15000 				 * so I'll cheat for the moment.
15001 				 */
15002 				dlp = (union DL_primitives *)mp->b_rptr;
15003 
15004 				mutex_enter(&ill->ill_lock);
15005 				bcopy((uchar_t *)(mp->b_rptr +
15006 				dlp->physaddr_ack.dl_addr_offset),
15007 				(void *)&ill->ill_token.s6_addr32[2],
15008 				dlp->physaddr_ack.dl_addr_length);
15009 				ill->ill_token_length =
15010 					dlp->physaddr_ack.dl_addr_length;
15011 				mutex_exit(&ill->ill_lock);
15012 			} else {
15013 				ASSERT(ill->ill_nd_lla_mp == NULL);
15014 				mp_hw = copyb(mp);
15015 				if (mp_hw == NULL) {
15016 					err = ENOMEM;
15017 					break;
15018 				}
15019 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15020 				mutex_enter(&ill->ill_lock);
15021 				ill->ill_nd_lla_mp = mp_hw;
15022 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15023 				dlp->physaddr_ack.dl_addr_offset;
15024 				ill->ill_nd_lla_len =
15025 					dlp->physaddr_ack.dl_addr_length;
15026 				mutex_exit(&ill->ill_lock);
15027 			}
15028 			break;
15029 		}
15030 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15031 		ASSERT(ill->ill_phys_addr_mp == NULL);
15032 		if (!ill->ill_ifname_pending)
15033 			break;
15034 		ill->ill_ifname_pending = 0;
15035 		if (!ioctl_aborted)
15036 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15037 		if (mp1 != NULL) {
15038 			ASSERT(connp == NULL);
15039 			q = ill->ill_wq;
15040 		}
15041 		/*
15042 		 * If any error acks received during the plumbing sequence,
15043 		 * ill_ifname_pending_err will be set. Break out and send up
15044 		 * the error to the pending ioctl.
15045 		 */
15046 		if (ill->ill_ifname_pending_err != 0) {
15047 			err = ill->ill_ifname_pending_err;
15048 			ill->ill_ifname_pending_err = 0;
15049 			break;
15050 		}
15051 		/*
15052 		 * Get the interface token.  If the zeroth interface
15053 		 * address is zero then set the address to the link local
15054 		 * address
15055 		 */
15056 		mp_hw = copyb(mp);
15057 		if (mp_hw == NULL) {
15058 			err = ENOMEM;
15059 			break;
15060 		}
15061 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15062 		ill->ill_phys_addr_mp = mp_hw;
15063 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15064 				dlp->physaddr_ack.dl_addr_offset;
15065 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15066 		    ill->ill_phys_addr_length == 0 ||
15067 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15068 			/*
15069 			 * Compatibility: atun driver returns a length of 0.
15070 			 * ipdptp has an ill_phys_addr_length of zero(from
15071 			 * DL_BIND_ACK) but a non-zero length here.
15072 			 * ipd has an ill_phys_addr_length of 4(from
15073 			 * DL_BIND_ACK) but a non-zero length here.
15074 			 */
15075 			ill->ill_phys_addr = NULL;
15076 		} else if (dlp->physaddr_ack.dl_addr_length !=
15077 		    ill->ill_phys_addr_length) {
15078 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15079 			    "Address length mismatch %d %d\n",
15080 			    dlp->physaddr_ack.dl_addr_length,
15081 			    ill->ill_phys_addr_length));
15082 			err = EINVAL;
15083 			break;
15084 		}
15085 		mutex_enter(&ill->ill_lock);
15086 		if (ill->ill_nd_lla_mp == NULL) {
15087 			ill->ill_nd_lla_mp = copyb(mp_hw);
15088 			if (ill->ill_nd_lla_mp == NULL) {
15089 				err = ENOMEM;
15090 				mutex_exit(&ill->ill_lock);
15091 				break;
15092 			}
15093 			ill->ill_nd_lla =
15094 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15095 			    dlp->physaddr_ack.dl_addr_offset;
15096 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15097 		}
15098 		mutex_exit(&ill->ill_lock);
15099 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15100 			(void) ill_setdefaulttoken(ill);
15101 
15102 		/*
15103 		 * If the ill zero interface has a zero address assign
15104 		 * it the proper link local address.
15105 		 */
15106 		ASSERT(ill->ill_ipif->ipif_id == 0);
15107 		if (ipif != NULL &&
15108 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15109 			(void) ipif_setlinklocal(ipif);
15110 		break;
15111 	}
15112 	case DL_OK_ACK:
15113 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15114 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15115 		    dloa->dl_correct_primitive));
15116 		switch (dloa->dl_correct_primitive) {
15117 		case DL_UNBIND_REQ:
15118 		case DL_ATTACH_REQ:
15119 		case DL_DETACH_REQ:
15120 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15121 			break;
15122 		}
15123 		break;
15124 	default:
15125 		break;
15126 	}
15127 
15128 	freemsg(mp);
15129 	if (mp1) {
15130 		struct iocblk *iocp;
15131 		int mode;
15132 
15133 		/*
15134 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15135 		 * SIOCSLIFNAME do a copyout.
15136 		 */
15137 		iocp = (struct iocblk *)mp1->b_rptr;
15138 
15139 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15140 		    iocp->ioc_cmd == SIOCSLIFNAME)
15141 			mode = COPYOUT;
15142 		else
15143 			mode = NO_COPYOUT;
15144 		/*
15145 		 * The ioctl must complete now without EINPROGRESS
15146 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15147 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15148 		 * stuck for ever in the ipsq.
15149 		 */
15150 		ASSERT(err != EINPROGRESS);
15151 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15152 
15153 	}
15154 }
15155 
15156 /*
15157  * ip_rput_other is called by ip_rput to handle messages modifying the global
15158  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15159  */
15160 /* ARGSUSED */
15161 void
15162 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15163 {
15164 	ill_t		*ill;
15165 	struct iocblk	*iocp;
15166 	mblk_t		*mp1;
15167 	conn_t		*connp = NULL;
15168 
15169 	ip1dbg(("ip_rput_other "));
15170 	ill = (ill_t *)q->q_ptr;
15171 	/*
15172 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15173 	 * in which case ipsq is NULL.
15174 	 */
15175 	if (ipsq != NULL) {
15176 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15177 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15178 	}
15179 
15180 	switch (mp->b_datap->db_type) {
15181 	case M_ERROR:
15182 	case M_HANGUP:
15183 		/*
15184 		 * The device has a problem.  We force the ILL down.  It can
15185 		 * be brought up again manually using SIOCSIFFLAGS (via
15186 		 * ifconfig or equivalent).
15187 		 */
15188 		ASSERT(ipsq != NULL);
15189 		if (mp->b_rptr < mp->b_wptr)
15190 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15191 		if (ill->ill_error == 0)
15192 			ill->ill_error = ENXIO;
15193 		if (!ill_down_start(q, mp))
15194 			return;
15195 		ipif_all_down_tail(ipsq, q, mp, NULL);
15196 		break;
15197 	case M_IOCACK:
15198 		iocp = (struct iocblk *)mp->b_rptr;
15199 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15200 		switch (iocp->ioc_cmd) {
15201 		case SIOCSTUNPARAM:
15202 		case OSIOCSTUNPARAM:
15203 			ASSERT(ipsq != NULL);
15204 			/*
15205 			 * Finish socket ioctl passed through to tun.
15206 			 * We should have an IOCTL waiting on this.
15207 			 */
15208 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15209 			if (ill->ill_isv6) {
15210 				struct iftun_req *ta;
15211 
15212 				/*
15213 				 * if a source or destination is
15214 				 * being set, try and set the link
15215 				 * local address for the tunnel
15216 				 */
15217 				ta = (struct iftun_req *)mp->b_cont->
15218 				    b_cont->b_rptr;
15219 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15220 					ipif_set_tun_llink(ill, ta);
15221 				}
15222 
15223 			}
15224 			if (mp1 != NULL) {
15225 				/*
15226 				 * Now copy back the b_next/b_prev used by
15227 				 * mi code for the mi_copy* functions.
15228 				 * See ip_sioctl_tunparam() for the reason.
15229 				 * Also protect against missing b_cont.
15230 				 */
15231 				if (mp->b_cont != NULL) {
15232 					mp->b_cont->b_next =
15233 					    mp1->b_cont->b_next;
15234 					mp->b_cont->b_prev =
15235 					    mp1->b_cont->b_prev;
15236 				}
15237 				inet_freemsg(mp1);
15238 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15239 				ASSERT(connp != NULL);
15240 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15241 				    iocp->ioc_error, NO_COPYOUT,
15242 				    ipsq->ipsq_current_ipif, ipsq);
15243 			} else {
15244 				ASSERT(connp == NULL);
15245 				putnext(q, mp);
15246 			}
15247 			break;
15248 		case SIOCGTUNPARAM:
15249 		case OSIOCGTUNPARAM:
15250 			/*
15251 			 * This is really M_IOCDATA from the tunnel driver.
15252 			 * convert back and complete the ioctl.
15253 			 * We should have an IOCTL waiting on this.
15254 			 */
15255 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15256 			if (mp1) {
15257 				/*
15258 				 * Now copy back the b_next/b_prev used by
15259 				 * mi code for the mi_copy* functions.
15260 				 * See ip_sioctl_tunparam() for the reason.
15261 				 * Also protect against missing b_cont.
15262 				 */
15263 				if (mp->b_cont != NULL) {
15264 					mp->b_cont->b_next =
15265 					    mp1->b_cont->b_next;
15266 					mp->b_cont->b_prev =
15267 					    mp1->b_cont->b_prev;
15268 				}
15269 				inet_freemsg(mp1);
15270 				if (iocp->ioc_error == 0)
15271 					mp->b_datap->db_type = M_IOCDATA;
15272 				ASSERT(connp != NULL);
15273 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15274 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15275 			} else {
15276 				ASSERT(connp == NULL);
15277 				putnext(q, mp);
15278 			}
15279 			break;
15280 		default:
15281 			break;
15282 		}
15283 		break;
15284 	case M_IOCNAK:
15285 		iocp = (struct iocblk *)mp->b_rptr;
15286 
15287 		switch (iocp->ioc_cmd) {
15288 		int mode;
15289 		ipif_t	*ipif;
15290 
15291 		case DL_IOC_HDR_INFO:
15292 			/*
15293 			 * If this was the first attempt turn of the
15294 			 * fastpath probing.
15295 			 */
15296 			mutex_enter(&ill->ill_lock);
15297 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15298 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15299 				mutex_exit(&ill->ill_lock);
15300 				ill_fastpath_nack(ill);
15301 				ip1dbg(("ip_rput: DLPI fastpath off on "
15302 				    "interface %s\n",
15303 				    ill->ill_name));
15304 			} else {
15305 				mutex_exit(&ill->ill_lock);
15306 			}
15307 			freemsg(mp);
15308 			break;
15309 		case SIOCSTUNPARAM:
15310 		case OSIOCSTUNPARAM:
15311 			ASSERT(ipsq != NULL);
15312 			/*
15313 			 * Finish socket ioctl passed through to tun
15314 			 * We should have an IOCTL waiting on this.
15315 			 */
15316 			/* FALLTHRU */
15317 		case SIOCGTUNPARAM:
15318 		case OSIOCGTUNPARAM:
15319 			/*
15320 			 * This is really M_IOCDATA from the tunnel driver.
15321 			 * convert back and complete the ioctl.
15322 			 * We should have an IOCTL waiting on this.
15323 			 */
15324 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15325 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15326 				mp1 = ill_pending_mp_get(ill, &connp,
15327 				    iocp->ioc_id);
15328 				mode = COPYOUT;
15329 				ipsq = NULL;
15330 				ipif = NULL;
15331 			} else {
15332 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15333 				mode = NO_COPYOUT;
15334 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15335 				ipif = ipsq->ipsq_current_ipif;
15336 			}
15337 			if (mp1 != NULL) {
15338 				/*
15339 				 * Now copy back the b_next/b_prev used by
15340 				 * mi code for the mi_copy* functions.
15341 				 * See ip_sioctl_tunparam() for the reason.
15342 				 * Also protect against missing b_cont.
15343 				 */
15344 				if (mp->b_cont != NULL) {
15345 					mp->b_cont->b_next =
15346 					    mp1->b_cont->b_next;
15347 					mp->b_cont->b_prev =
15348 					    mp1->b_cont->b_prev;
15349 				}
15350 				inet_freemsg(mp1);
15351 				if (iocp->ioc_error == 0)
15352 					iocp->ioc_error = EINVAL;
15353 				ASSERT(connp != NULL);
15354 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15355 				    iocp->ioc_error, mode, ipif, ipsq);
15356 			} else {
15357 				ASSERT(connp == NULL);
15358 				putnext(q, mp);
15359 			}
15360 			break;
15361 		default:
15362 			break;
15363 		}
15364 	default:
15365 		break;
15366 	}
15367 }
15368 
15369 /*
15370  * NOTE : This function does not ire_refrele the ire argument passed in.
15371  *
15372  * IPQoS notes
15373  * IP policy is invoked twice for a forwarded packet, once on the read side
15374  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15375  * enabled. An additional parameter, in_ill, has been added for this purpose.
15376  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15377  * because ip_mroute drops this information.
15378  *
15379  */
15380 void
15381 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15382 {
15383 	uint32_t	pkt_len;
15384 	queue_t	*q;
15385 	uint32_t	sum;
15386 #define	rptr	((uchar_t *)ipha)
15387 	uint32_t	max_frag;
15388 	uint32_t	ill_index;
15389 
15390 	/* Get the ill_index of the incoming ILL */
15391 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15392 
15393 	/* Initiate Read side IPPF processing */
15394 	if (IPP_ENABLED(IPP_FWD_IN)) {
15395 		ip_process(IPP_FWD_IN, &mp, ill_index);
15396 		if (mp == NULL) {
15397 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15398 			    "during IPPF processing\n"));
15399 			return;
15400 		}
15401 	}
15402 	pkt_len = ntohs(ipha->ipha_length);
15403 
15404 	/* Adjust the checksum to reflect the ttl decrement. */
15405 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
15406 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
15407 
15408 	if (ipha->ipha_ttl-- <= 1) {
15409 		if (ip_csum_hdr(ipha)) {
15410 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15411 			goto drop_pkt;
15412 		}
15413 		/*
15414 		 * Note: ire_stq this will be NULL for multicast
15415 		 * datagrams using the long path through arp (the IRE
15416 		 * is not an IRE_CACHE). This should not cause
15417 		 * problems since we don't generate ICMP errors for
15418 		 * multicast packets.
15419 		 */
15420 		q = ire->ire_stq;
15421 		if (q)
15422 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
15423 		else
15424 			freemsg(mp);
15425 		return;
15426 	}
15427 
15428 	/*
15429 	 * Don't forward if the interface is down
15430 	 */
15431 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
15432 		BUMP_MIB(&ip_mib, ipInDiscards);
15433 		goto drop_pkt;
15434 	}
15435 
15436 	/* Get the ill_index of the outgoing ILL */
15437 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
15438 
15439 	if (is_system_labeled()) {
15440 		mblk_t *mp1;
15441 
15442 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
15443 			BUMP_MIB(&ip_mib, ipForwProhibits);
15444 			goto drop_pkt;
15445 		}
15446 		/* Size may have changed */
15447 		mp = mp1;
15448 		ipha = (ipha_t *)mp->b_rptr;
15449 		pkt_len = ntohs(ipha->ipha_length);
15450 	}
15451 
15452 	/* Check if there are options to update */
15453 	if (!IS_SIMPLE_IPH(ipha)) {
15454 		if (ip_csum_hdr(ipha)) {
15455 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15456 			goto drop_pkt;
15457 		}
15458 		if (ip_rput_forward_options(mp, ipha, ire)) {
15459 			return;
15460 		}
15461 
15462 		ipha->ipha_hdr_checksum = 0;
15463 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
15464 	}
15465 	max_frag = ire->ire_max_frag;
15466 	if (pkt_len > max_frag) {
15467 		/*
15468 		 * It needs fragging on its way out.  We haven't
15469 		 * verified the header checksum yet.  Since we
15470 		 * are going to put a surely good checksum in the
15471 		 * outgoing header, we have to make sure that it
15472 		 * was good coming in.
15473 		 */
15474 		if (ip_csum_hdr(ipha)) {
15475 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15476 			goto drop_pkt;
15477 		}
15478 		/* Initiate Write side IPPF processing */
15479 		if (IPP_ENABLED(IPP_FWD_OUT)) {
15480 			ip_process(IPP_FWD_OUT, &mp, ill_index);
15481 			if (mp == NULL) {
15482 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
15483 				    " during IPPF processing\n"));
15484 				return;
15485 			}
15486 		}
15487 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
15488 		return;
15489 	}
15490 
15491 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
15492 	if (mp == NULL) {
15493 		BUMP_MIB(&ip_mib, ipInDiscards);
15494 		return;
15495 	}
15496 
15497 	q = ire->ire_stq;
15498 	UPDATE_IB_PKT_COUNT(ire);
15499 	ire->ire_last_used_time = lbolt;
15500 	BUMP_MIB(&ip_mib, ipForwDatagrams);
15501 	putnext(q, mp);
15502 	return;
15503 
15504 drop_pkt:;
15505 	ip1dbg(("ip_rput_forward: drop pkt\n"));
15506 	freemsg(mp);
15507 #undef	rptr
15508 }
15509 
15510 void
15511 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
15512 {
15513 	ire_t	*ire;
15514 
15515 	ASSERT(!ipif->ipif_isv6);
15516 	/*
15517 	 * Find an IRE which matches the destination and the outgoing
15518 	 * queue in the cache table. All we need is an IRE_CACHE which
15519 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
15520 	 * then it is enough to have some IRE_CACHE in the group.
15521 	 */
15522 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
15523 		dst = ipif->ipif_pp_dst_addr;
15524 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
15525 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
15526 	if (ire == NULL) {
15527 		/*
15528 		 * Mark this packet to make it be delivered to
15529 		 * ip_rput_forward after the new ire has been
15530 		 * created.
15531 		 */
15532 		mp->b_prev = NULL;
15533 		mp->b_next = mp;
15534 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
15535 		    NULL, 0);
15536 	} else {
15537 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
15538 		IRE_REFRELE(ire);
15539 	}
15540 }
15541 
15542 /* Update any source route, record route or timestamp options */
15543 static int
15544 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15545 {
15546 	ipoptp_t	opts;
15547 	uchar_t		*opt;
15548 	uint8_t		optval;
15549 	uint8_t		optlen;
15550 	ipaddr_t	dst;
15551 	uint32_t	ts;
15552 	ire_t		*dst_ire = NULL;
15553 	ire_t		*tmp_ire = NULL;
15554 	timestruc_t	now;
15555 
15556 	ip2dbg(("ip_rput_forward_options\n"));
15557 	dst = ipha->ipha_dst;
15558 	for (optval = ipoptp_first(&opts, ipha);
15559 	    optval != IPOPT_EOL;
15560 	    optval = ipoptp_next(&opts)) {
15561 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15562 		opt = opts.ipoptp_cur;
15563 		optlen = opts.ipoptp_len;
15564 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15565 		    optval, opts.ipoptp_len));
15566 		switch (optval) {
15567 			uint32_t off;
15568 		case IPOPT_SSRR:
15569 		case IPOPT_LSRR:
15570 			/* Check if adminstratively disabled */
15571 			if (!ip_forward_src_routed) {
15572 				BUMP_MIB(&ip_mib, ipForwProhibits);
15573 				if (ire->ire_stq)
15574 					icmp_unreachable(ire->ire_stq, mp,
15575 					    ICMP_SOURCE_ROUTE_FAILED);
15576 				else {
15577 					ip0dbg(("ip_rput_forward_options: "
15578 					    "unable to send unreach\n"));
15579 					freemsg(mp);
15580 				}
15581 				return (-1);
15582 			}
15583 
15584 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15585 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15586 			if (dst_ire == NULL) {
15587 				/*
15588 				 * Must be partial since ip_rput_options
15589 				 * checked for strict.
15590 				 */
15591 				break;
15592 			}
15593 			off = opt[IPOPT_OFFSET];
15594 			off--;
15595 		redo_srr:
15596 			if (optlen < IP_ADDR_LEN ||
15597 			    off > optlen - IP_ADDR_LEN) {
15598 				/* End of source route */
15599 				ip1dbg((
15600 				    "ip_rput_forward_options: end of SR\n"));
15601 				ire_refrele(dst_ire);
15602 				break;
15603 			}
15604 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15605 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15606 			    IP_ADDR_LEN);
15607 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15608 			    ntohl(dst)));
15609 
15610 			/*
15611 			 * Check if our address is present more than
15612 			 * once as consecutive hops in source route.
15613 			 */
15614 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15615 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15616 			if (tmp_ire != NULL) {
15617 				ire_refrele(tmp_ire);
15618 				off += IP_ADDR_LEN;
15619 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15620 				goto redo_srr;
15621 			}
15622 			ipha->ipha_dst = dst;
15623 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15624 			ire_refrele(dst_ire);
15625 			break;
15626 		case IPOPT_RR:
15627 			off = opt[IPOPT_OFFSET];
15628 			off--;
15629 			if (optlen < IP_ADDR_LEN ||
15630 			    off > optlen - IP_ADDR_LEN) {
15631 				/* No more room - ignore */
15632 				ip1dbg((
15633 				    "ip_rput_forward_options: end of RR\n"));
15634 				break;
15635 			}
15636 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15637 			    IP_ADDR_LEN);
15638 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15639 			break;
15640 		case IPOPT_TS:
15641 			/* Insert timestamp if there is room */
15642 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15643 			case IPOPT_TS_TSONLY:
15644 				off = IPOPT_TS_TIMELEN;
15645 				break;
15646 			case IPOPT_TS_PRESPEC:
15647 			case IPOPT_TS_PRESPEC_RFC791:
15648 				/* Verify that the address matched */
15649 				off = opt[IPOPT_OFFSET] - 1;
15650 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15651 				dst_ire = ire_ctable_lookup(dst, 0,
15652 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
15653 				    MATCH_IRE_TYPE);
15654 
15655 				if (dst_ire == NULL) {
15656 					/* Not for us */
15657 					break;
15658 				}
15659 				ire_refrele(dst_ire);
15660 				/* FALLTHRU */
15661 			case IPOPT_TS_TSANDADDR:
15662 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15663 				break;
15664 			default:
15665 				/*
15666 				 * ip_*put_options should have already
15667 				 * dropped this packet.
15668 				 */
15669 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15670 				    "unknown IT - bug in ip_rput_options?\n");
15671 				return (0);	/* Keep "lint" happy */
15672 			}
15673 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15674 				/* Increase overflow counter */
15675 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15676 				opt[IPOPT_POS_OV_FLG] =
15677 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15678 				    (off << 4));
15679 				break;
15680 			}
15681 			off = opt[IPOPT_OFFSET] - 1;
15682 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15683 			case IPOPT_TS_PRESPEC:
15684 			case IPOPT_TS_PRESPEC_RFC791:
15685 			case IPOPT_TS_TSANDADDR:
15686 				bcopy(&ire->ire_src_addr,
15687 				    (char *)opt + off, IP_ADDR_LEN);
15688 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15689 				/* FALLTHRU */
15690 			case IPOPT_TS_TSONLY:
15691 				off = opt[IPOPT_OFFSET] - 1;
15692 				/* Compute # of milliseconds since midnight */
15693 				gethrestime(&now);
15694 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15695 				    now.tv_nsec / (NANOSEC / MILLISEC);
15696 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15697 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15698 				break;
15699 			}
15700 			break;
15701 		}
15702 	}
15703 	return (0);
15704 }
15705 
15706 /*
15707  * This is called after processing at least one of AH/ESP headers.
15708  *
15709  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15710  * the actual, physical interface on which the packet was received,
15711  * but, when ip_strict_dst_multihoming is set to 1, could be the
15712  * interface which had the ipha_dst configured when the packet went
15713  * through ip_rput. The ill_index corresponding to the recv_ill
15714  * is saved in ipsec_in_rill_index
15715  */
15716 void
15717 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15718 {
15719 	mblk_t *mp;
15720 	ipaddr_t dst;
15721 	in6_addr_t *v6dstp;
15722 	ipha_t *ipha;
15723 	ip6_t *ip6h;
15724 	ipsec_in_t *ii;
15725 	boolean_t ill_need_rele = B_FALSE;
15726 	boolean_t rill_need_rele = B_FALSE;
15727 	boolean_t ire_need_rele = B_FALSE;
15728 
15729 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15730 	ASSERT(ii->ipsec_in_ill_index != 0);
15731 
15732 	mp = ipsec_mp->b_cont;
15733 	ASSERT(mp != NULL);
15734 
15735 
15736 	if (ill == NULL) {
15737 		ASSERT(recv_ill == NULL);
15738 		/*
15739 		 * We need to get the original queue on which ip_rput_local
15740 		 * or ip_rput_data_v6 was called.
15741 		 */
15742 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15743 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15744 		ill_need_rele = B_TRUE;
15745 
15746 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15747 			recv_ill = ill_lookup_on_ifindex(
15748 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15749 			    NULL, NULL, NULL, NULL);
15750 			rill_need_rele = B_TRUE;
15751 		} else {
15752 			recv_ill = ill;
15753 		}
15754 
15755 		if ((ill == NULL) || (recv_ill == NULL)) {
15756 			ip0dbg(("ip_fanout_proto_again: interface "
15757 			    "disappeared\n"));
15758 			if (ill != NULL)
15759 				ill_refrele(ill);
15760 			if (recv_ill != NULL)
15761 				ill_refrele(recv_ill);
15762 			freemsg(ipsec_mp);
15763 			return;
15764 		}
15765 	}
15766 
15767 	ASSERT(ill != NULL && recv_ill != NULL);
15768 
15769 	if (mp->b_datap->db_type == M_CTL) {
15770 		/*
15771 		 * AH/ESP is returning the ICMP message after
15772 		 * removing their headers. Fanout again till
15773 		 * it gets to the right protocol.
15774 		 */
15775 		if (ii->ipsec_in_v4) {
15776 			icmph_t *icmph;
15777 			int iph_hdr_length;
15778 			int hdr_length;
15779 
15780 			ipha = (ipha_t *)mp->b_rptr;
15781 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15782 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15783 			ipha = (ipha_t *)&icmph[1];
15784 			hdr_length = IPH_HDR_LENGTH(ipha);
15785 			/*
15786 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15787 			 * Reset the type to M_DATA.
15788 			 */
15789 			mp->b_datap->db_type = M_DATA;
15790 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15791 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15792 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15793 		} else {
15794 			icmp6_t *icmp6;
15795 			int hdr_length;
15796 
15797 			ip6h = (ip6_t *)mp->b_rptr;
15798 			/* Don't call hdr_length_v6() unless you have to. */
15799 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15800 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15801 			else
15802 				hdr_length = IPV6_HDR_LEN;
15803 
15804 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15805 			/*
15806 			 * icmp_inbound_error_fanout_v6 may need to do
15807 			 * pullupmsg.  Reset the type to M_DATA.
15808 			 */
15809 			mp->b_datap->db_type = M_DATA;
15810 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15811 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15812 		}
15813 		if (ill_need_rele)
15814 			ill_refrele(ill);
15815 		if (rill_need_rele)
15816 			ill_refrele(recv_ill);
15817 		return;
15818 	}
15819 
15820 	if (ii->ipsec_in_v4) {
15821 		ipha = (ipha_t *)mp->b_rptr;
15822 		dst = ipha->ipha_dst;
15823 		if (CLASSD(dst)) {
15824 			/*
15825 			 * Multicast has to be delivered to all streams.
15826 			 */
15827 			dst = INADDR_BROADCAST;
15828 		}
15829 
15830 		if (ire == NULL) {
15831 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
15832 			    MBLK_GETLABEL(mp));
15833 			if (ire == NULL) {
15834 				if (ill_need_rele)
15835 					ill_refrele(ill);
15836 				if (rill_need_rele)
15837 					ill_refrele(recv_ill);
15838 				ip1dbg(("ip_fanout_proto_again: "
15839 				    "IRE not found"));
15840 				freemsg(ipsec_mp);
15841 				return;
15842 			}
15843 			ire_need_rele = B_TRUE;
15844 		}
15845 
15846 		switch (ipha->ipha_protocol) {
15847 			case IPPROTO_UDP:
15848 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15849 				    recv_ill);
15850 				if (ire_need_rele)
15851 					ire_refrele(ire);
15852 				break;
15853 			case IPPROTO_TCP:
15854 				if (!ire_need_rele)
15855 					IRE_REFHOLD(ire);
15856 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15857 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15858 				IRE_REFRELE(ire);
15859 				if (mp != NULL)
15860 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15861 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15862 				break;
15863 			case IPPROTO_SCTP:
15864 				if (!ire_need_rele)
15865 					IRE_REFHOLD(ire);
15866 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15867 				    ipsec_mp, 0, ill->ill_rq, dst);
15868 				break;
15869 			default:
15870 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15871 				    recv_ill);
15872 				if (ire_need_rele)
15873 					ire_refrele(ire);
15874 				break;
15875 		}
15876 	} else {
15877 		uint32_t rput_flags = 0;
15878 
15879 		ip6h = (ip6_t *)mp->b_rptr;
15880 		v6dstp = &ip6h->ip6_dst;
15881 		/*
15882 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15883 		 * address.
15884 		 *
15885 		 * Currently, we don't store that state in the IPSEC_IN
15886 		 * message, and we may need to.
15887 		 */
15888 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15889 		    IP6_IN_LLMCAST : 0);
15890 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15891 		    NULL);
15892 	}
15893 	if (ill_need_rele)
15894 		ill_refrele(ill);
15895 	if (rill_need_rele)
15896 		ill_refrele(recv_ill);
15897 }
15898 
15899 /*
15900  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15901  * returns 'true' if there are still fragments left on the queue, in
15902  * which case we restart the timer.
15903  */
15904 void
15905 ill_frag_timer(void *arg)
15906 {
15907 	ill_t	*ill = (ill_t *)arg;
15908 	boolean_t frag_pending;
15909 
15910 	mutex_enter(&ill->ill_lock);
15911 	ASSERT(!ill->ill_fragtimer_executing);
15912 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15913 		ill->ill_frag_timer_id = 0;
15914 		mutex_exit(&ill->ill_lock);
15915 		return;
15916 	}
15917 	ill->ill_fragtimer_executing = 1;
15918 	mutex_exit(&ill->ill_lock);
15919 
15920 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15921 
15922 	/*
15923 	 * Restart the timer, if we have fragments pending or if someone
15924 	 * wanted us to be scheduled again.
15925 	 */
15926 	mutex_enter(&ill->ill_lock);
15927 	ill->ill_fragtimer_executing = 0;
15928 	ill->ill_frag_timer_id = 0;
15929 	if (frag_pending || ill->ill_fragtimer_needrestart)
15930 		ill_frag_timer_start(ill);
15931 	mutex_exit(&ill->ill_lock);
15932 }
15933 
15934 void
15935 ill_frag_timer_start(ill_t *ill)
15936 {
15937 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15938 
15939 	/* If the ill is closing or opening don't proceed */
15940 	if (ill->ill_state_flags & ILL_CONDEMNED)
15941 		return;
15942 
15943 	if (ill->ill_fragtimer_executing) {
15944 		/*
15945 		 * ill_frag_timer is currently executing. Just record the
15946 		 * the fact that we want the timer to be restarted.
15947 		 * ill_frag_timer will post a timeout before it returns,
15948 		 * ensuring it will be called again.
15949 		 */
15950 		ill->ill_fragtimer_needrestart = 1;
15951 		return;
15952 	}
15953 
15954 	if (ill->ill_frag_timer_id == 0) {
15955 		/*
15956 		 * The timer is neither running nor is the timeout handler
15957 		 * executing. Post a timeout so that ill_frag_timer will be
15958 		 * called
15959 		 */
15960 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15961 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15962 		ill->ill_fragtimer_needrestart = 0;
15963 	}
15964 }
15965 
15966 /*
15967  * This routine is needed for loopback when forwarding multicasts.
15968  *
15969  * IPQoS Notes:
15970  * IPPF processing is done in fanout routines.
15971  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15972  * processing for IPSec packets is done when it comes back in clear.
15973  * NOTE : The callers of this function need to do the ire_refrele for the
15974  *	  ire that is being passed in.
15975  */
15976 void
15977 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15978     ill_t *recv_ill)
15979 {
15980 	ill_t	*ill = (ill_t *)q->q_ptr;
15981 	uint32_t	sum;
15982 	uint32_t	u1;
15983 	uint32_t	u2;
15984 	int		hdr_length;
15985 	boolean_t	mctl_present;
15986 	mblk_t		*first_mp = mp;
15987 	mblk_t		*hada_mp = NULL;
15988 	ipha_t		*inner_ipha;
15989 
15990 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15991 	    "ip_rput_locl_start: q %p", q);
15992 
15993 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15994 
15995 
15996 #define	rptr	((uchar_t *)ipha)
15997 #define	iphs	((uint16_t *)ipha)
15998 
15999 	/*
16000 	 * no UDP or TCP packet should come here anymore.
16001 	 */
16002 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16003 	    (ipha->ipha_protocol != IPPROTO_UDP));
16004 
16005 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16006 	if (mctl_present &&
16007 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16008 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16009 
16010 		/*
16011 		 * It's an IPsec accelerated packet.
16012 		 * Keep a pointer to the data attributes around until
16013 		 * we allocate the ipsec_info_t.
16014 		 */
16015 		IPSECHW_DEBUG(IPSECHW_PKT,
16016 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16017 		hada_mp = first_mp;
16018 		hada_mp->b_cont = NULL;
16019 		/*
16020 		 * Since it is accelerated, it comes directly from
16021 		 * the ill and the data attributes is followed by
16022 		 * the packet data.
16023 		 */
16024 		ASSERT(mp->b_datap->db_type != M_CTL);
16025 		first_mp = mp;
16026 		mctl_present = B_FALSE;
16027 	}
16028 
16029 	/*
16030 	 * IF M_CTL is not present, then ipsec_in_is_secure
16031 	 * should return B_TRUE. There is a case where loopback
16032 	 * packets has an M_CTL in the front with all the
16033 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16034 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16035 	 * packets never comes here, it is safe to ASSERT the
16036 	 * following.
16037 	 */
16038 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16039 
16040 
16041 	/* u1 is # words of IP options */
16042 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16043 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16044 
16045 	if (u1) {
16046 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16047 			if (hada_mp != NULL)
16048 				freemsg(hada_mp);
16049 			return;
16050 		}
16051 	} else {
16052 		/* Check the IP header checksum.  */
16053 #define	uph	((uint16_t *)ipha)
16054 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16055 		    uph[6] + uph[7] + uph[8] + uph[9];
16056 #undef  uph
16057 		/* finish doing IP checksum */
16058 		sum = (sum & 0xFFFF) + (sum >> 16);
16059 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16060 		/*
16061 		 * Don't verify header checksum if this packet is coming
16062 		 * back from AH/ESP as we already did it.
16063 		 */
16064 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16065 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16066 			goto drop_pkt;
16067 		}
16068 	}
16069 
16070 	/*
16071 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16072 	 * might be called more than once for secure packets, count only
16073 	 * the first time.
16074 	 */
16075 	if (!mctl_present) {
16076 		UPDATE_IB_PKT_COUNT(ire);
16077 		ire->ire_last_used_time = lbolt;
16078 	}
16079 
16080 	/* Check for fragmentation offset. */
16081 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16082 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16083 	if (u1) {
16084 		/*
16085 		 * We re-assemble fragments before we do the AH/ESP
16086 		 * processing. Thus, M_CTL should not be present
16087 		 * while we are re-assembling.
16088 		 */
16089 		ASSERT(!mctl_present);
16090 		ASSERT(first_mp == mp);
16091 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16092 			return;
16093 		}
16094 		/*
16095 		 * Make sure that first_mp points back to mp as
16096 		 * the mp we came in with could have changed in
16097 		 * ip_rput_fragment().
16098 		 */
16099 		ipha = (ipha_t *)mp->b_rptr;
16100 		first_mp = mp;
16101 	}
16102 
16103 	/*
16104 	 * Clear hardware checksumming flag as it is currently only
16105 	 * used by TCP and UDP.
16106 	 */
16107 	DB_CKSUMFLAGS(mp) = 0;
16108 
16109 	/* Now we have a complete datagram, destined for this machine. */
16110 	u1 = IPH_HDR_LENGTH(ipha);
16111 	switch (ipha->ipha_protocol) {
16112 	case IPPROTO_ICMP: {
16113 		ire_t		*ire_zone;
16114 		ilm_t		*ilm;
16115 		mblk_t		*mp1;
16116 		zoneid_t	last_zoneid;
16117 
16118 		if (CLASSD(ipha->ipha_dst) &&
16119 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16120 			ASSERT(ire->ire_type == IRE_BROADCAST);
16121 			/*
16122 			 * In the multicast case, applications may have joined
16123 			 * the group from different zones, so we need to deliver
16124 			 * the packet to each of them. Loop through the
16125 			 * multicast memberships structures (ilm) on the receive
16126 			 * ill and send a copy of the packet up each matching
16127 			 * one. However, we don't do this for multicasts sent on
16128 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16129 			 * they must stay in the sender's zone.
16130 			 *
16131 			 * ilm_add_v6() ensures that ilms in the same zone are
16132 			 * contiguous in the ill_ilm list. We use this property
16133 			 * to avoid sending duplicates needed when two
16134 			 * applications in the same zone join the same group on
16135 			 * different logical interfaces: we ignore the ilm if
16136 			 * its zoneid is the same as the last matching one.
16137 			 * In addition, the sending of the packet for
16138 			 * ire_zoneid is delayed until all of the other ilms
16139 			 * have been exhausted.
16140 			 */
16141 			last_zoneid = -1;
16142 			ILM_WALKER_HOLD(recv_ill);
16143 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16144 			    ilm = ilm->ilm_next) {
16145 				if ((ilm->ilm_flags & ILM_DELETED) ||
16146 				    ipha->ipha_dst != ilm->ilm_addr ||
16147 				    ilm->ilm_zoneid == last_zoneid ||
16148 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16149 				    ilm->ilm_zoneid == ALL_ZONES ||
16150 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16151 					continue;
16152 				mp1 = ip_copymsg(first_mp);
16153 				if (mp1 == NULL)
16154 					continue;
16155 				icmp_inbound(q, mp1, B_TRUE, ill,
16156 				    0, sum, mctl_present, B_TRUE,
16157 				    recv_ill, ilm->ilm_zoneid);
16158 				last_zoneid = ilm->ilm_zoneid;
16159 			}
16160 			ILM_WALKER_RELE(recv_ill);
16161 		} else if (ire->ire_type == IRE_BROADCAST) {
16162 			/*
16163 			 * In the broadcast case, there may be many zones
16164 			 * which need a copy of the packet delivered to them.
16165 			 * There is one IRE_BROADCAST per broadcast address
16166 			 * and per zone; we walk those using a helper function.
16167 			 * In addition, the sending of the packet for ire is
16168 			 * delayed until all of the other ires have been
16169 			 * processed.
16170 			 */
16171 			IRB_REFHOLD(ire->ire_bucket);
16172 			ire_zone = NULL;
16173 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16174 			    ire)) != NULL) {
16175 				mp1 = ip_copymsg(first_mp);
16176 				if (mp1 == NULL)
16177 					continue;
16178 
16179 				UPDATE_IB_PKT_COUNT(ire_zone);
16180 				ire_zone->ire_last_used_time = lbolt;
16181 				icmp_inbound(q, mp1, B_TRUE, ill,
16182 				    0, sum, mctl_present, B_TRUE,
16183 				    recv_ill, ire_zone->ire_zoneid);
16184 			}
16185 			IRB_REFRELE(ire->ire_bucket);
16186 		}
16187 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16188 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16189 		    ire->ire_zoneid);
16190 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16191 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16192 		return;
16193 	}
16194 	case IPPROTO_IGMP:
16195 		/*
16196 		 * If we are not willing to accept IGMP packets in clear,
16197 		 * then check with global policy.
16198 		 */
16199 		if (igmp_accept_clear_messages == 0) {
16200 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16201 			    ipha, NULL, mctl_present);
16202 			if (first_mp == NULL)
16203 				return;
16204 		}
16205 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16206 			freemsg(first_mp);
16207 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16208 			BUMP_MIB(&ip_mib, ipInDiscards);
16209 			return;
16210 		}
16211 		if (igmp_input(q, mp, ill)) {
16212 			/* Bad packet - discarded by igmp_input */
16213 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16214 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16215 			if (mctl_present)
16216 				freeb(first_mp);
16217 			return;
16218 		}
16219 		/*
16220 		 * igmp_input() may have pulled up the message so ipha needs to
16221 		 * be reinitialized.
16222 		 */
16223 		ipha = (ipha_t *)mp->b_rptr;
16224 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16225 			/* No user-level listener for IGMP packets */
16226 			goto drop_pkt;
16227 		}
16228 		/* deliver to local raw users */
16229 		break;
16230 	case IPPROTO_PIM:
16231 		/*
16232 		 * If we are not willing to accept PIM packets in clear,
16233 		 * then check with global policy.
16234 		 */
16235 		if (pim_accept_clear_messages == 0) {
16236 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16237 			    ipha, NULL, mctl_present);
16238 			if (first_mp == NULL)
16239 				return;
16240 		}
16241 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16242 			freemsg(first_mp);
16243 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16244 			BUMP_MIB(&ip_mib, ipInDiscards);
16245 			return;
16246 		}
16247 		if (pim_input(q, mp) != 0) {
16248 			/* Bad packet - discarded by pim_input */
16249 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16250 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16251 			if (mctl_present)
16252 				freeb(first_mp);
16253 			return;
16254 		}
16255 
16256 		/*
16257 		 * pim_input() may have pulled up the message so ipha needs to
16258 		 * be reinitialized.
16259 		 */
16260 		ipha = (ipha_t *)mp->b_rptr;
16261 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16262 			/* No user-level listener for PIM packets */
16263 			goto drop_pkt;
16264 		}
16265 		/* deliver to local raw users */
16266 		break;
16267 	case IPPROTO_ENCAP:
16268 		/*
16269 		 * Handle self-encapsulated packets (IP-in-IP where
16270 		 * the inner addresses == the outer addresses).
16271 		 */
16272 		hdr_length = IPH_HDR_LENGTH(ipha);
16273 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16274 		    mp->b_wptr) {
16275 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16276 			    sizeof (ipha_t) - mp->b_rptr)) {
16277 				BUMP_MIB(&ip_mib, ipInDiscards);
16278 				freemsg(first_mp);
16279 				return;
16280 			}
16281 			ipha = (ipha_t *)mp->b_rptr;
16282 		}
16283 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16284 		/*
16285 		 * Check the sanity of the inner IP header.
16286 		 */
16287 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16288 			BUMP_MIB(&ip_mib, ipInDiscards);
16289 			freemsg(first_mp);
16290 			return;
16291 		}
16292 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16293 			BUMP_MIB(&ip_mib, ipInDiscards);
16294 			freemsg(first_mp);
16295 			return;
16296 		}
16297 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16298 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16299 			ipsec_in_t *ii;
16300 
16301 			/*
16302 			 * Self-encapsulated tunnel packet. Remove
16303 			 * the outer IP header and fanout again.
16304 			 * We also need to make sure that the inner
16305 			 * header is pulled up until options.
16306 			 */
16307 			mp->b_rptr = (uchar_t *)inner_ipha;
16308 			ipha = inner_ipha;
16309 			hdr_length = IPH_HDR_LENGTH(ipha);
16310 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16311 				if (!pullupmsg(mp, (uchar_t *)ipha +
16312 				    + hdr_length - mp->b_rptr)) {
16313 					freemsg(first_mp);
16314 					return;
16315 				}
16316 				ipha = (ipha_t *)mp->b_rptr;
16317 			}
16318 			if (!mctl_present) {
16319 				ASSERT(first_mp == mp);
16320 				/*
16321 				 * This means that somebody is sending
16322 				 * Self-encapsualted packets without AH/ESP.
16323 				 * If AH/ESP was present, we would have already
16324 				 * allocated the first_mp.
16325 				 */
16326 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16327 				    NULL) {
16328 					ip1dbg(("ip_proto_input: IPSEC_IN "
16329 					    "allocation failure.\n"));
16330 					BUMP_MIB(&ip_mib, ipInDiscards);
16331 					freemsg(mp);
16332 					return;
16333 				}
16334 				first_mp->b_cont = mp;
16335 			}
16336 			/*
16337 			 * We generally store the ill_index if we need to
16338 			 * do IPSEC processing as we lose the ill queue when
16339 			 * we come back. But in this case, we never should
16340 			 * have to store the ill_index here as it should have
16341 			 * been stored previously when we processed the
16342 			 * AH/ESP header in this routine or for non-ipsec
16343 			 * cases, we still have the queue. But for some bad
16344 			 * packets from the wire, we can get to IPSEC after
16345 			 * this and we better store the index for that case.
16346 			 */
16347 			ill = (ill_t *)q->q_ptr;
16348 			ii = (ipsec_in_t *)first_mp->b_rptr;
16349 			ii->ipsec_in_ill_index =
16350 			    ill->ill_phyint->phyint_ifindex;
16351 			ii->ipsec_in_rill_index =
16352 			    recv_ill->ill_phyint->phyint_ifindex;
16353 			if (ii->ipsec_in_decaps) {
16354 				/*
16355 				 * This packet is self-encapsulated multiple
16356 				 * times. We don't want to recurse infinitely.
16357 				 * To keep it simple, drop the packet.
16358 				 */
16359 				BUMP_MIB(&ip_mib, ipInDiscards);
16360 				freemsg(first_mp);
16361 				return;
16362 			}
16363 			ii->ipsec_in_decaps = B_TRUE;
16364 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16365 			return;
16366 		}
16367 		break;
16368 	case IPPROTO_AH:
16369 	case IPPROTO_ESP: {
16370 		/*
16371 		 * Fast path for AH/ESP. If this is the first time
16372 		 * we are sending a datagram to AH/ESP, allocate
16373 		 * a IPSEC_IN message and prepend it. Otherwise,
16374 		 * just fanout.
16375 		 */
16376 
16377 		int ipsec_rc;
16378 		ipsec_in_t *ii;
16379 
16380 		IP_STAT(ipsec_proto_ahesp);
16381 		if (!mctl_present) {
16382 			ASSERT(first_mp == mp);
16383 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16384 				ip1dbg(("ip_proto_input: IPSEC_IN "
16385 				    "allocation failure.\n"));
16386 				freemsg(hada_mp); /* okay ifnull */
16387 				BUMP_MIB(&ip_mib, ipInDiscards);
16388 				freemsg(mp);
16389 				return;
16390 			}
16391 			/*
16392 			 * Store the ill_index so that when we come back
16393 			 * from IPSEC we ride on the same queue.
16394 			 */
16395 			ill = (ill_t *)q->q_ptr;
16396 			ii = (ipsec_in_t *)first_mp->b_rptr;
16397 			ii->ipsec_in_ill_index =
16398 			    ill->ill_phyint->phyint_ifindex;
16399 			ii->ipsec_in_rill_index =
16400 			    recv_ill->ill_phyint->phyint_ifindex;
16401 			first_mp->b_cont = mp;
16402 			/*
16403 			 * Cache hardware acceleration info.
16404 			 */
16405 			if (hada_mp != NULL) {
16406 				IPSECHW_DEBUG(IPSECHW_PKT,
16407 				    ("ip_rput_local: caching data attr.\n"));
16408 				ii->ipsec_in_accelerated = B_TRUE;
16409 				ii->ipsec_in_da = hada_mp;
16410 				hada_mp = NULL;
16411 			}
16412 		} else {
16413 			ii = (ipsec_in_t *)first_mp->b_rptr;
16414 		}
16415 
16416 		if (!ipsec_loaded()) {
16417 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
16418 			    ire->ire_zoneid);
16419 			return;
16420 		}
16421 
16422 		/* select inbound SA and have IPsec process the pkt */
16423 		if (ipha->ipha_protocol == IPPROTO_ESP) {
16424 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
16425 			if (esph == NULL)
16426 				return;
16427 			ASSERT(ii->ipsec_in_esp_sa != NULL);
16428 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
16429 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
16430 			    first_mp, esph);
16431 		} else {
16432 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
16433 			if (ah == NULL)
16434 				return;
16435 			ASSERT(ii->ipsec_in_ah_sa != NULL);
16436 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
16437 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
16438 			    first_mp, ah);
16439 		}
16440 
16441 		switch (ipsec_rc) {
16442 		case IPSEC_STATUS_SUCCESS:
16443 			break;
16444 		case IPSEC_STATUS_FAILED:
16445 			BUMP_MIB(&ip_mib, ipInDiscards);
16446 			/* FALLTHRU */
16447 		case IPSEC_STATUS_PENDING:
16448 			return;
16449 		}
16450 		/* we're done with IPsec processing, send it up */
16451 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
16452 		return;
16453 	}
16454 	default:
16455 		break;
16456 	}
16457 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
16458 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
16459 		    ire->ire_zoneid));
16460 		goto drop_pkt;
16461 	}
16462 	/*
16463 	 * Handle protocols with which IP is less intimate.  There
16464 	 * can be more than one stream bound to a particular
16465 	 * protocol.  When this is the case, each one gets a copy
16466 	 * of any incoming packets.
16467 	 */
16468 	ip_fanout_proto(q, first_mp, ill, ipha,
16469 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
16470 	    B_TRUE, recv_ill, ire->ire_zoneid);
16471 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16472 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
16473 	return;
16474 
16475 drop_pkt:
16476 	freemsg(first_mp);
16477 	if (hada_mp != NULL)
16478 		freeb(hada_mp);
16479 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16480 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
16481 #undef	rptr
16482 #undef  iphs
16483 
16484 }
16485 
16486 /*
16487  * Update any source route, record route or timestamp options.
16488  * Check that we are at end of strict source route.
16489  * The options have already been checked for sanity in ip_rput_options().
16490  */
16491 static boolean_t
16492 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
16493 {
16494 	ipoptp_t	opts;
16495 	uchar_t		*opt;
16496 	uint8_t		optval;
16497 	uint8_t		optlen;
16498 	ipaddr_t	dst;
16499 	uint32_t	ts;
16500 	ire_t		*dst_ire;
16501 	timestruc_t	now;
16502 
16503 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16504 
16505 	ip2dbg(("ip_rput_local_options\n"));
16506 
16507 	for (optval = ipoptp_first(&opts, ipha);
16508 	    optval != IPOPT_EOL;
16509 	    optval = ipoptp_next(&opts)) {
16510 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16511 		opt = opts.ipoptp_cur;
16512 		optlen = opts.ipoptp_len;
16513 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
16514 		    optval, optlen));
16515 		switch (optval) {
16516 			uint32_t off;
16517 		case IPOPT_SSRR:
16518 		case IPOPT_LSRR:
16519 			off = opt[IPOPT_OFFSET];
16520 			off--;
16521 			if (optlen < IP_ADDR_LEN ||
16522 			    off > optlen - IP_ADDR_LEN) {
16523 				/* End of source route */
16524 				ip1dbg(("ip_rput_local_options: end of SR\n"));
16525 				break;
16526 			}
16527 			/*
16528 			 * This will only happen if two consecutive entries
16529 			 * in the source route contains our address or if
16530 			 * it is a packet with a loose source route which
16531 			 * reaches us before consuming the whole source route
16532 			 */
16533 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
16534 			if (optval == IPOPT_SSRR) {
16535 				goto bad_src_route;
16536 			}
16537 			/*
16538 			 * Hack: instead of dropping the packet truncate the
16539 			 * source route to what has been used by filling the
16540 			 * rest with IPOPT_NOP.
16541 			 */
16542 			opt[IPOPT_OLEN] = (uint8_t)off;
16543 			while (off < optlen) {
16544 				opt[off++] = IPOPT_NOP;
16545 			}
16546 			break;
16547 		case IPOPT_RR:
16548 			off = opt[IPOPT_OFFSET];
16549 			off--;
16550 			if (optlen < IP_ADDR_LEN ||
16551 			    off > optlen - IP_ADDR_LEN) {
16552 				/* No more room - ignore */
16553 				ip1dbg((
16554 				    "ip_rput_local_options: end of RR\n"));
16555 				break;
16556 			}
16557 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16558 			    IP_ADDR_LEN);
16559 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16560 			break;
16561 		case IPOPT_TS:
16562 			/* Insert timestamp if there is romm */
16563 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16564 			case IPOPT_TS_TSONLY:
16565 				off = IPOPT_TS_TIMELEN;
16566 				break;
16567 			case IPOPT_TS_PRESPEC:
16568 			case IPOPT_TS_PRESPEC_RFC791:
16569 				/* Verify that the address matched */
16570 				off = opt[IPOPT_OFFSET] - 1;
16571 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16572 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16573 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16574 				if (dst_ire == NULL) {
16575 					/* Not for us */
16576 					break;
16577 				}
16578 				ire_refrele(dst_ire);
16579 				/* FALLTHRU */
16580 			case IPOPT_TS_TSANDADDR:
16581 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16582 				break;
16583 			default:
16584 				/*
16585 				 * ip_*put_options should have already
16586 				 * dropped this packet.
16587 				 */
16588 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16589 				    "unknown IT - bug in ip_rput_options?\n");
16590 				return (B_TRUE);	/* Keep "lint" happy */
16591 			}
16592 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16593 				/* Increase overflow counter */
16594 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16595 				opt[IPOPT_POS_OV_FLG] =
16596 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16597 				    (off << 4));
16598 				break;
16599 			}
16600 			off = opt[IPOPT_OFFSET] - 1;
16601 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16602 			case IPOPT_TS_PRESPEC:
16603 			case IPOPT_TS_PRESPEC_RFC791:
16604 			case IPOPT_TS_TSANDADDR:
16605 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16606 				    IP_ADDR_LEN);
16607 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16608 				/* FALLTHRU */
16609 			case IPOPT_TS_TSONLY:
16610 				off = opt[IPOPT_OFFSET] - 1;
16611 				/* Compute # of milliseconds since midnight */
16612 				gethrestime(&now);
16613 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16614 				    now.tv_nsec / (NANOSEC / MILLISEC);
16615 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16616 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16617 				break;
16618 			}
16619 			break;
16620 		}
16621 	}
16622 	return (B_TRUE);
16623 
16624 bad_src_route:
16625 	q = WR(q);
16626 	/* make sure we clear any indication of a hardware checksum */
16627 	DB_CKSUMFLAGS(mp) = 0;
16628 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16629 	return (B_FALSE);
16630 
16631 }
16632 
16633 /*
16634  * Process IP options in an inbound packet.  If an option affects the
16635  * effective destination address, return the next hop address via dstp.
16636  * Returns -1 if something fails in which case an ICMP error has been sent
16637  * and mp freed.
16638  */
16639 static int
16640 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16641 {
16642 	ipoptp_t	opts;
16643 	uchar_t		*opt;
16644 	uint8_t		optval;
16645 	uint8_t		optlen;
16646 	ipaddr_t	dst;
16647 	intptr_t	code = 0;
16648 	ire_t		*ire = NULL;
16649 
16650 	ip2dbg(("ip_rput_options\n"));
16651 	dst = ipha->ipha_dst;
16652 	for (optval = ipoptp_first(&opts, ipha);
16653 	    optval != IPOPT_EOL;
16654 	    optval = ipoptp_next(&opts)) {
16655 		opt = opts.ipoptp_cur;
16656 		optlen = opts.ipoptp_len;
16657 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16658 		    optval, optlen));
16659 		/*
16660 		 * Note: we need to verify the checksum before we
16661 		 * modify anything thus this routine only extracts the next
16662 		 * hop dst from any source route.
16663 		 */
16664 		switch (optval) {
16665 			uint32_t off;
16666 		case IPOPT_SSRR:
16667 		case IPOPT_LSRR:
16668 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16669 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16670 			if (ire == NULL) {
16671 				if (optval == IPOPT_SSRR) {
16672 					ip1dbg(("ip_rput_options: not next"
16673 					    " strict source route 0x%x\n",
16674 					    ntohl(dst)));
16675 					code = (char *)&ipha->ipha_dst -
16676 					    (char *)ipha;
16677 					goto param_prob; /* RouterReq's */
16678 				}
16679 				ip2dbg(("ip_rput_options: "
16680 				    "not next source route 0x%x\n",
16681 				    ntohl(dst)));
16682 				break;
16683 			}
16684 			ire_refrele(ire);
16685 
16686 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16687 				ip1dbg((
16688 				    "ip_rput_options: bad option offset\n"));
16689 				code = (char *)&opt[IPOPT_OLEN] -
16690 				    (char *)ipha;
16691 				goto param_prob;
16692 			}
16693 			off = opt[IPOPT_OFFSET];
16694 			off--;
16695 		redo_srr:
16696 			if (optlen < IP_ADDR_LEN ||
16697 			    off > optlen - IP_ADDR_LEN) {
16698 				/* End of source route */
16699 				ip1dbg(("ip_rput_options: end of SR\n"));
16700 				break;
16701 			}
16702 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16703 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16704 			    ntohl(dst)));
16705 
16706 			/*
16707 			 * Check if our address is present more than
16708 			 * once as consecutive hops in source route.
16709 			 * XXX verify per-interface ip_forwarding
16710 			 * for source route?
16711 			 */
16712 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16713 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16714 
16715 			if (ire != NULL) {
16716 				ire_refrele(ire);
16717 				off += IP_ADDR_LEN;
16718 				goto redo_srr;
16719 			}
16720 
16721 			if (dst == htonl(INADDR_LOOPBACK)) {
16722 				ip1dbg(("ip_rput_options: loopback addr in "
16723 				    "source route!\n"));
16724 				goto bad_src_route;
16725 			}
16726 			/*
16727 			 * For strict: verify that dst is directly
16728 			 * reachable.
16729 			 */
16730 			if (optval == IPOPT_SSRR) {
16731 				ire = ire_ftable_lookup(dst, 0, 0,
16732 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16733 				    MBLK_GETLABEL(mp),
16734 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
16735 				if (ire == NULL) {
16736 					ip1dbg(("ip_rput_options: SSRR not "
16737 					    "directly reachable: 0x%x\n",
16738 					    ntohl(dst)));
16739 					goto bad_src_route;
16740 				}
16741 				ire_refrele(ire);
16742 			}
16743 			/*
16744 			 * Defer update of the offset and the record route
16745 			 * until the packet is forwarded.
16746 			 */
16747 			break;
16748 		case IPOPT_RR:
16749 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16750 				ip1dbg((
16751 				    "ip_rput_options: bad option offset\n"));
16752 				code = (char *)&opt[IPOPT_OLEN] -
16753 				    (char *)ipha;
16754 				goto param_prob;
16755 			}
16756 			break;
16757 		case IPOPT_TS:
16758 			/*
16759 			 * Verify that length >= 5 and that there is either
16760 			 * room for another timestamp or that the overflow
16761 			 * counter is not maxed out.
16762 			 */
16763 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16764 			if (optlen < IPOPT_MINLEN_IT) {
16765 				goto param_prob;
16766 			}
16767 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16768 				ip1dbg((
16769 				    "ip_rput_options: bad option offset\n"));
16770 				code = (char *)&opt[IPOPT_OFFSET] -
16771 				    (char *)ipha;
16772 				goto param_prob;
16773 			}
16774 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16775 			case IPOPT_TS_TSONLY:
16776 				off = IPOPT_TS_TIMELEN;
16777 				break;
16778 			case IPOPT_TS_TSANDADDR:
16779 			case IPOPT_TS_PRESPEC:
16780 			case IPOPT_TS_PRESPEC_RFC791:
16781 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16782 				break;
16783 			default:
16784 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16785 				    (char *)ipha;
16786 				goto param_prob;
16787 			}
16788 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16789 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16790 				/*
16791 				 * No room and the overflow counter is 15
16792 				 * already.
16793 				 */
16794 				goto param_prob;
16795 			}
16796 			break;
16797 		}
16798 	}
16799 
16800 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16801 		*dstp = dst;
16802 		return (0);
16803 	}
16804 
16805 	ip1dbg(("ip_rput_options: error processing IP options."));
16806 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16807 
16808 param_prob:
16809 	q = WR(q);
16810 	/* make sure we clear any indication of a hardware checksum */
16811 	DB_CKSUMFLAGS(mp) = 0;
16812 	icmp_param_problem(q, mp, (uint8_t)code);
16813 	return (-1);
16814 
16815 bad_src_route:
16816 	q = WR(q);
16817 	/* make sure we clear any indication of a hardware checksum */
16818 	DB_CKSUMFLAGS(mp) = 0;
16819 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16820 	return (-1);
16821 }
16822 
16823 /*
16824  * IP & ICMP info in >=14 msg's ...
16825  *  - ip fixed part (mib2_ip_t)
16826  *  - icmp fixed part (mib2_icmp_t)
16827  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16828  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16829  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16830  *  - ipRouteAttributeTable (ip 102)	labeled routes
16831  *  - ip multicast membership (ip_member_t)
16832  *  - ip multicast source filtering (ip_grpsrc_t)
16833  *  - igmp fixed part (struct igmpstat)
16834  *  - multicast routing stats (struct mrtstat)
16835  *  - multicast routing vifs (array of struct vifctl)
16836  *  - multicast routing routes (array of struct mfcctl)
16837  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16838  *					One per ill plus one generic
16839  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16840  *					One per ill plus one generic
16841  *  - ipv6RouteEntry			all IPv6 IREs
16842  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
16843  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16844  *  - ipv6AddrEntry			all IPv6 ipifs
16845  *  - ipv6 multicast membership (ipv6_member_t)
16846  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16847  *
16848  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16849  * already present.
16850  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
16851  * already filled in by the caller.
16852  * Return value of 0 indicates that no messages were sent and caller
16853  * should free mpctl.
16854  */
16855 int
16856 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16857 {
16858 
16859 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16860 		return (0);
16861 	}
16862 
16863 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16864 		return (1);
16865 	}
16866 
16867 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16868 		return (1);
16869 	}
16870 
16871 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16872 		return (1);
16873 	}
16874 
16875 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16876 		return (1);
16877 	}
16878 
16879 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16880 		return (1);
16881 	}
16882 
16883 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16884 		return (1);
16885 	}
16886 
16887 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16888 		return (1);
16889 	}
16890 
16891 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16892 		return (1);
16893 	}
16894 
16895 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16896 		return (1);
16897 	}
16898 
16899 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16900 		return (1);
16901 	}
16902 
16903 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16904 		return (1);
16905 	}
16906 
16907 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16908 		return (1);
16909 	}
16910 
16911 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16912 		return (1);
16913 	}
16914 
16915 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16916 		return (1);
16917 	}
16918 
16919 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16920 		return (1);
16921 	}
16922 
16923 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16924 		return (1);
16925 	}
16926 
16927 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16928 		return (1);
16929 	}
16930 	freemsg(mpctl);
16931 	return (1);
16932 }
16933 
16934 
16935 /* Get global IPv4 statistics */
16936 static mblk_t *
16937 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16938 {
16939 	struct opthdr		*optp;
16940 	mblk_t			*mp2ctl;
16941 
16942 	/*
16943 	 * make a copy of the original message
16944 	 */
16945 	mp2ctl = copymsg(mpctl);
16946 
16947 	/* fixed length IP structure... */
16948 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16949 	optp->level = MIB2_IP;
16950 	optp->name = 0;
16951 	SET_MIB(ip_mib.ipForwarding,
16952 	    (WE_ARE_FORWARDING ? 1 : 2));
16953 	SET_MIB(ip_mib.ipDefaultTTL,
16954 	    (uint32_t)ip_def_ttl);
16955 	SET_MIB(ip_mib.ipReasmTimeout,
16956 	    ip_g_frag_timeout);
16957 	SET_MIB(ip_mib.ipAddrEntrySize,
16958 	    sizeof (mib2_ipAddrEntry_t));
16959 	SET_MIB(ip_mib.ipRouteEntrySize,
16960 	    sizeof (mib2_ipRouteEntry_t));
16961 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16962 	    sizeof (mib2_ipNetToMediaEntry_t));
16963 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16964 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16965 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
16966 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
16967 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16968 	    (int)sizeof (ip_mib))) {
16969 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16970 		    (uint_t)sizeof (ip_mib)));
16971 	}
16972 
16973 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16974 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16975 	    (int)optp->level, (int)optp->name, (int)optp->len));
16976 	qreply(q, mpctl);
16977 	return (mp2ctl);
16978 }
16979 
16980 /* Global IPv4 ICMP statistics */
16981 static mblk_t *
16982 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16983 {
16984 	struct opthdr		*optp;
16985 	mblk_t			*mp2ctl;
16986 
16987 	/*
16988 	 * Make a copy of the original message
16989 	 */
16990 	mp2ctl = copymsg(mpctl);
16991 
16992 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16993 	optp->level = MIB2_ICMP;
16994 	optp->name = 0;
16995 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
16996 	    (int)sizeof (icmp_mib))) {
16997 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
16998 		    (uint_t)sizeof (icmp_mib)));
16999 	}
17000 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17001 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17002 	    (int)optp->level, (int)optp->name, (int)optp->len));
17003 	qreply(q, mpctl);
17004 	return (mp2ctl);
17005 }
17006 
17007 /* Global IPv4 IGMP statistics */
17008 static mblk_t *
17009 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17010 {
17011 	struct opthdr		*optp;
17012 	mblk_t			*mp2ctl;
17013 
17014 	/*
17015 	 * make a copy of the original message
17016 	 */
17017 	mp2ctl = copymsg(mpctl);
17018 
17019 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17020 	optp->level = EXPER_IGMP;
17021 	optp->name = 0;
17022 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17023 	    (int)sizeof (igmpstat))) {
17024 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17025 		    (uint_t)sizeof (igmpstat)));
17026 	}
17027 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17028 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17029 	    (int)optp->level, (int)optp->name, (int)optp->len));
17030 	qreply(q, mpctl);
17031 	return (mp2ctl);
17032 }
17033 
17034 /* Global IPv4 Multicast Routing statistics */
17035 static mblk_t *
17036 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17037 {
17038 	struct opthdr		*optp;
17039 	mblk_t			*mp2ctl;
17040 
17041 	/*
17042 	 * make a copy of the original message
17043 	 */
17044 	mp2ctl = copymsg(mpctl);
17045 
17046 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17047 	optp->level = EXPER_DVMRP;
17048 	optp->name = 0;
17049 	if (!ip_mroute_stats(mpctl->b_cont)) {
17050 		ip0dbg(("ip_mroute_stats: failed\n"));
17051 	}
17052 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17053 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17054 	    (int)optp->level, (int)optp->name, (int)optp->len));
17055 	qreply(q, mpctl);
17056 	return (mp2ctl);
17057 }
17058 
17059 /* IPv4 address information */
17060 static mblk_t *
17061 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17062 {
17063 	struct opthdr		*optp;
17064 	mblk_t			*mp2ctl;
17065 	mblk_t			*mp_tail = NULL;
17066 	ill_t			*ill;
17067 	ipif_t			*ipif;
17068 	uint_t			bitval;
17069 	mib2_ipAddrEntry_t	mae;
17070 	zoneid_t		zoneid;
17071 	ill_walk_context_t ctx;
17072 
17073 	/*
17074 	 * make a copy of the original message
17075 	 */
17076 	mp2ctl = copymsg(mpctl);
17077 
17078 	/* ipAddrEntryTable */
17079 
17080 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17081 	optp->level = MIB2_IP;
17082 	optp->name = MIB2_IP_ADDR;
17083 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17084 
17085 	rw_enter(&ill_g_lock, RW_READER);
17086 	ill = ILL_START_WALK_V4(&ctx);
17087 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17088 		for (ipif = ill->ill_ipif; ipif != NULL;
17089 		    ipif = ipif->ipif_next) {
17090 			if (ipif->ipif_zoneid != zoneid &&
17091 			    ipif->ipif_zoneid != ALL_ZONES)
17092 				continue;
17093 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17094 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17095 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17096 
17097 			(void) ipif_get_name(ipif,
17098 			    mae.ipAdEntIfIndex.o_bytes,
17099 			    OCTET_LENGTH);
17100 			mae.ipAdEntIfIndex.o_length =
17101 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17102 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17103 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17104 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17105 			mae.ipAdEntInfo.ae_subnet_len =
17106 			    ip_mask_to_plen(ipif->ipif_net_mask);
17107 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17108 			for (bitval = 1;
17109 			    bitval &&
17110 			    !(bitval & ipif->ipif_brd_addr);
17111 			    bitval <<= 1)
17112 				noop;
17113 			mae.ipAdEntBcastAddr = bitval;
17114 			mae.ipAdEntReasmMaxSize = 65535;
17115 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17116 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17117 			mae.ipAdEntInfo.ae_broadcast_addr =
17118 			    ipif->ipif_brd_addr;
17119 			mae.ipAdEntInfo.ae_pp_dst_addr =
17120 			    ipif->ipif_pp_dst_addr;
17121 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17122 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17123 
17124 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17125 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17126 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17127 				    "allocate %u bytes\n",
17128 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17129 			}
17130 		}
17131 	}
17132 	rw_exit(&ill_g_lock);
17133 
17134 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17135 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17136 	    (int)optp->level, (int)optp->name, (int)optp->len));
17137 	qreply(q, mpctl);
17138 	return (mp2ctl);
17139 }
17140 
17141 /* IPv6 address information */
17142 static mblk_t *
17143 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17144 {
17145 	struct opthdr		*optp;
17146 	mblk_t			*mp2ctl;
17147 	mblk_t			*mp_tail = NULL;
17148 	ill_t			*ill;
17149 	ipif_t			*ipif;
17150 	mib2_ipv6AddrEntry_t	mae6;
17151 	zoneid_t		zoneid;
17152 	ill_walk_context_t	ctx;
17153 
17154 	/*
17155 	 * make a copy of the original message
17156 	 */
17157 	mp2ctl = copymsg(mpctl);
17158 
17159 	/* ipv6AddrEntryTable */
17160 
17161 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17162 	optp->level = MIB2_IP6;
17163 	optp->name = MIB2_IP6_ADDR;
17164 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17165 
17166 	rw_enter(&ill_g_lock, RW_READER);
17167 	ill = ILL_START_WALK_V6(&ctx);
17168 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17169 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17170 			if (ipif->ipif_zoneid != zoneid &&
17171 			    ipif->ipif_zoneid != ALL_ZONES)
17172 				continue;
17173 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17174 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17175 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17176 
17177 			(void) ipif_get_name(ipif,
17178 			    mae6.ipv6AddrIfIndex.o_bytes,
17179 			    OCTET_LENGTH);
17180 			mae6.ipv6AddrIfIndex.o_length =
17181 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17182 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17183 			mae6.ipv6AddrPfxLength =
17184 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17185 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17186 			mae6.ipv6AddrInfo.ae_subnet_len =
17187 			    mae6.ipv6AddrPfxLength;
17188 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17189 
17190 			/* Type: stateless(1), stateful(2), unknown(3) */
17191 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17192 				mae6.ipv6AddrType = 1;
17193 			else
17194 				mae6.ipv6AddrType = 2;
17195 			/* Anycast: true(1), false(2) */
17196 			if (ipif->ipif_flags & IPIF_ANYCAST)
17197 				mae6.ipv6AddrAnycastFlag = 1;
17198 			else
17199 				mae6.ipv6AddrAnycastFlag = 2;
17200 
17201 			/*
17202 			 * Address status: preferred(1), deprecated(2),
17203 			 * invalid(3), inaccessible(4), unknown(5)
17204 			 */
17205 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17206 				mae6.ipv6AddrStatus = 3;
17207 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17208 				mae6.ipv6AddrStatus = 2;
17209 			else
17210 				mae6.ipv6AddrStatus = 1;
17211 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17212 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17213 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17214 						ipif->ipif_v6pp_dst_addr;
17215 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17216 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17217 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17218 				(char *)&mae6,
17219 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17220 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17221 				    "allocate %u bytes\n",
17222 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17223 			}
17224 		}
17225 	}
17226 	rw_exit(&ill_g_lock);
17227 
17228 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17229 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17230 	    (int)optp->level, (int)optp->name, (int)optp->len));
17231 	qreply(q, mpctl);
17232 	return (mp2ctl);
17233 }
17234 
17235 /* IPv4 multicast group membership. */
17236 static mblk_t *
17237 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17238 {
17239 	struct opthdr		*optp;
17240 	mblk_t			*mp2ctl;
17241 	ill_t			*ill;
17242 	ipif_t			*ipif;
17243 	ilm_t			*ilm;
17244 	ip_member_t		ipm;
17245 	mblk_t			*mp_tail = NULL;
17246 	ill_walk_context_t	ctx;
17247 	zoneid_t		zoneid;
17248 
17249 	/*
17250 	 * make a copy of the original message
17251 	 */
17252 	mp2ctl = copymsg(mpctl);
17253 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17254 
17255 	/* ipGroupMember table */
17256 	optp = (struct opthdr *)&mpctl->b_rptr[
17257 	    sizeof (struct T_optmgmt_ack)];
17258 	optp->level = MIB2_IP;
17259 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17260 
17261 	rw_enter(&ill_g_lock, RW_READER);
17262 	ill = ILL_START_WALK_V4(&ctx);
17263 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17264 		ILM_WALKER_HOLD(ill);
17265 		for (ipif = ill->ill_ipif; ipif != NULL;
17266 		    ipif = ipif->ipif_next) {
17267 			if (ipif->ipif_zoneid != zoneid &&
17268 			    ipif->ipif_zoneid != ALL_ZONES)
17269 				continue;	/* not this zone */
17270 			(void) ipif_get_name(ipif,
17271 			    ipm.ipGroupMemberIfIndex.o_bytes,
17272 			    OCTET_LENGTH);
17273 			ipm.ipGroupMemberIfIndex.o_length =
17274 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17275 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17276 				ASSERT(ilm->ilm_ipif != NULL);
17277 				ASSERT(ilm->ilm_ill == NULL);
17278 				if (ilm->ilm_ipif != ipif)
17279 					continue;
17280 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17281 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17282 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17283 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17284 				    (char *)&ipm, (int)sizeof (ipm))) {
17285 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17286 					    "failed to allocate %u bytes\n",
17287 						(uint_t)sizeof (ipm)));
17288 				}
17289 			}
17290 		}
17291 		ILM_WALKER_RELE(ill);
17292 	}
17293 	rw_exit(&ill_g_lock);
17294 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17295 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17296 	    (int)optp->level, (int)optp->name, (int)optp->len));
17297 	qreply(q, mpctl);
17298 	return (mp2ctl);
17299 }
17300 
17301 /* IPv6 multicast group membership. */
17302 static mblk_t *
17303 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17304 {
17305 	struct opthdr		*optp;
17306 	mblk_t			*mp2ctl;
17307 	ill_t			*ill;
17308 	ilm_t			*ilm;
17309 	ipv6_member_t		ipm6;
17310 	mblk_t			*mp_tail = NULL;
17311 	ill_walk_context_t	ctx;
17312 	zoneid_t		zoneid;
17313 
17314 	/*
17315 	 * make a copy of the original message
17316 	 */
17317 	mp2ctl = copymsg(mpctl);
17318 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17319 
17320 	/* ip6GroupMember table */
17321 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17322 	optp->level = MIB2_IP6;
17323 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17324 
17325 	rw_enter(&ill_g_lock, RW_READER);
17326 	ill = ILL_START_WALK_V6(&ctx);
17327 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17328 		ILM_WALKER_HOLD(ill);
17329 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17330 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17331 			ASSERT(ilm->ilm_ipif == NULL);
17332 			ASSERT(ilm->ilm_ill != NULL);
17333 			if (ilm->ilm_zoneid != zoneid)
17334 				continue;	/* not this zone */
17335 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17336 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17337 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17338 			if (!snmp_append_data2(mpctl->b_cont,
17339 			    &mp_tail,
17340 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17341 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17342 				    "failed to allocate %u bytes\n",
17343 				    (uint_t)sizeof (ipm6)));
17344 			}
17345 		}
17346 		ILM_WALKER_RELE(ill);
17347 	}
17348 	rw_exit(&ill_g_lock);
17349 
17350 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17351 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17352 	    (int)optp->level, (int)optp->name, (int)optp->len));
17353 	qreply(q, mpctl);
17354 	return (mp2ctl);
17355 }
17356 
17357 /* IP multicast filtered sources */
17358 static mblk_t *
17359 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17360 {
17361 	struct opthdr		*optp;
17362 	mblk_t			*mp2ctl;
17363 	ill_t			*ill;
17364 	ipif_t			*ipif;
17365 	ilm_t			*ilm;
17366 	ip_grpsrc_t		ips;
17367 	mblk_t			*mp_tail = NULL;
17368 	ill_walk_context_t	ctx;
17369 	zoneid_t		zoneid;
17370 	int			i;
17371 	slist_t			*sl;
17372 
17373 	/*
17374 	 * make a copy of the original message
17375 	 */
17376 	mp2ctl = copymsg(mpctl);
17377 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17378 
17379 	/* ipGroupSource table */
17380 	optp = (struct opthdr *)&mpctl->b_rptr[
17381 	    sizeof (struct T_optmgmt_ack)];
17382 	optp->level = MIB2_IP;
17383 	optp->name = EXPER_IP_GROUP_SOURCES;
17384 
17385 	rw_enter(&ill_g_lock, RW_READER);
17386 	ill = ILL_START_WALK_V4(&ctx);
17387 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17388 		ILM_WALKER_HOLD(ill);
17389 		for (ipif = ill->ill_ipif; ipif != NULL;
17390 		    ipif = ipif->ipif_next) {
17391 			if (ipif->ipif_zoneid != zoneid)
17392 				continue;	/* not this zone */
17393 			(void) ipif_get_name(ipif,
17394 			    ips.ipGroupSourceIfIndex.o_bytes,
17395 			    OCTET_LENGTH);
17396 			ips.ipGroupSourceIfIndex.o_length =
17397 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17398 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17399 				ASSERT(ilm->ilm_ipif != NULL);
17400 				ASSERT(ilm->ilm_ill == NULL);
17401 				sl = ilm->ilm_filter;
17402 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17403 					continue;
17404 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17405 				for (i = 0; i < sl->sl_numsrc; i++) {
17406 					if (!IN6_IS_ADDR_V4MAPPED(
17407 					    &sl->sl_addr[i]))
17408 						continue;
17409 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
17410 					    ips.ipGroupSourceAddress);
17411 					if (snmp_append_data2(mpctl->b_cont,
17412 					    &mp_tail, (char *)&ips,
17413 					    (int)sizeof (ips)) == 0) {
17414 						ip1dbg(("ip_snmp_get_mib2_"
17415 						    "ip_group_src: failed to "
17416 						    "allocate %u bytes\n",
17417 						    (uint_t)sizeof (ips)));
17418 					}
17419 				}
17420 			}
17421 		}
17422 		ILM_WALKER_RELE(ill);
17423 	}
17424 	rw_exit(&ill_g_lock);
17425 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17426 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17427 	    (int)optp->level, (int)optp->name, (int)optp->len));
17428 	qreply(q, mpctl);
17429 	return (mp2ctl);
17430 }
17431 
17432 /* IPv6 multicast filtered sources. */
17433 static mblk_t *
17434 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
17435 {
17436 	struct opthdr		*optp;
17437 	mblk_t			*mp2ctl;
17438 	ill_t			*ill;
17439 	ilm_t			*ilm;
17440 	ipv6_grpsrc_t		ips6;
17441 	mblk_t			*mp_tail = NULL;
17442 	ill_walk_context_t	ctx;
17443 	zoneid_t		zoneid;
17444 	int			i;
17445 	slist_t			*sl;
17446 
17447 	/*
17448 	 * make a copy of the original message
17449 	 */
17450 	mp2ctl = copymsg(mpctl);
17451 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17452 
17453 	/* ip6GroupMember table */
17454 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17455 	optp->level = MIB2_IP6;
17456 	optp->name = EXPER_IP6_GROUP_SOURCES;
17457 
17458 	rw_enter(&ill_g_lock, RW_READER);
17459 	ill = ILL_START_WALK_V6(&ctx);
17460 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17461 		ILM_WALKER_HOLD(ill);
17462 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
17463 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17464 			ASSERT(ilm->ilm_ipif == NULL);
17465 			ASSERT(ilm->ilm_ill != NULL);
17466 			sl = ilm->ilm_filter;
17467 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
17468 				continue;
17469 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
17470 			for (i = 0; i < sl->sl_numsrc; i++) {
17471 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
17472 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17473 				    (char *)&ips6, (int)sizeof (ips6))) {
17474 					ip1dbg(("ip_snmp_get_mib2_ip6_"
17475 					    "group_src: failed to allocate "
17476 					    "%u bytes\n",
17477 					    (uint_t)sizeof (ips6)));
17478 				}
17479 			}
17480 		}
17481 		ILM_WALKER_RELE(ill);
17482 	}
17483 	rw_exit(&ill_g_lock);
17484 
17485 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17486 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17487 	    (int)optp->level, (int)optp->name, (int)optp->len));
17488 	qreply(q, mpctl);
17489 	return (mp2ctl);
17490 }
17491 
17492 /* Multicast routing virtual interface table. */
17493 static mblk_t *
17494 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
17495 {
17496 	struct opthdr		*optp;
17497 	mblk_t			*mp2ctl;
17498 
17499 	/*
17500 	 * make a copy of the original message
17501 	 */
17502 	mp2ctl = copymsg(mpctl);
17503 
17504 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17505 	optp->level = EXPER_DVMRP;
17506 	optp->name = EXPER_DVMRP_VIF;
17507 	if (!ip_mroute_vif(mpctl->b_cont)) {
17508 		ip0dbg(("ip_mroute_vif: failed\n"));
17509 	}
17510 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17511 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
17512 	    (int)optp->level, (int)optp->name, (int)optp->len));
17513 	qreply(q, mpctl);
17514 	return (mp2ctl);
17515 }
17516 
17517 /* Multicast routing table. */
17518 static mblk_t *
17519 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
17520 {
17521 	struct opthdr		*optp;
17522 	mblk_t			*mp2ctl;
17523 
17524 	/*
17525 	 * make a copy of the original message
17526 	 */
17527 	mp2ctl = copymsg(mpctl);
17528 
17529 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17530 	optp->level = EXPER_DVMRP;
17531 	optp->name = EXPER_DVMRP_MRT;
17532 	if (!ip_mroute_mrt(mpctl->b_cont)) {
17533 		ip0dbg(("ip_mroute_mrt: failed\n"));
17534 	}
17535 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17536 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
17537 	    (int)optp->level, (int)optp->name, (int)optp->len));
17538 	qreply(q, mpctl);
17539 	return (mp2ctl);
17540 }
17541 
17542 /*
17543  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
17544  * in one IRE walk.
17545  */
17546 static mblk_t *
17547 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
17548 {
17549 	struct opthdr	*optp;
17550 	mblk_t		*mp2ctl;	/* Returned */
17551 	mblk_t		*mp3ctl;	/* nettomedia */
17552 	mblk_t		*mp4ctl;	/* routeattrs */
17553 	iproutedata_t	ird;
17554 	zoneid_t	zoneid;
17555 
17556 	/*
17557 	 * make copies of the original message
17558 	 *	- mp2ctl is returned unchanged to the caller for his use
17559 	 *	- mpctl is sent upstream as ipRouteEntryTable
17560 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
17561 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
17562 	 */
17563 	mp2ctl = copymsg(mpctl);
17564 	mp3ctl = copymsg(mpctl);
17565 	mp4ctl = copymsg(mpctl);
17566 	if (mp3ctl == NULL || mp4ctl == NULL) {
17567 		freemsg(mp4ctl);
17568 		freemsg(mp3ctl);
17569 		freemsg(mp2ctl);
17570 		freemsg(mpctl);
17571 		return (NULL);
17572 	}
17573 
17574 	bzero(&ird, sizeof (ird));
17575 
17576 	ird.ird_route.lp_head = mpctl->b_cont;
17577 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17578 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17579 
17580 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17581 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
17582 	if (zoneid == GLOBAL_ZONEID) {
17583 		/*
17584 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17585 		 * the sys_net_config privilege, it can only run in the global
17586 		 * zone, so we don't display these IREs in the other zones.
17587 		 */
17588 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
17589 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
17590 	}
17591 
17592 	/* ipRouteEntryTable in mpctl */
17593 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17594 	optp->level = MIB2_IP;
17595 	optp->name = MIB2_IP_ROUTE;
17596 	optp->len = msgdsize(ird.ird_route.lp_head);
17597 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17598 	    (int)optp->level, (int)optp->name, (int)optp->len));
17599 	qreply(q, mpctl);
17600 
17601 	/* ipNetToMediaEntryTable in mp3ctl */
17602 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17603 	optp->level = MIB2_IP;
17604 	optp->name = MIB2_IP_MEDIA;
17605 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17606 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17607 	    (int)optp->level, (int)optp->name, (int)optp->len));
17608 	qreply(q, mp3ctl);
17609 
17610 	/* ipRouteAttributeTable in mp4ctl */
17611 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17612 	optp->level = MIB2_IP;
17613 	optp->name = EXPER_IP_RTATTR;
17614 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17615 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17616 	    (int)optp->level, (int)optp->name, (int)optp->len));
17617 	if (optp->len == 0)
17618 		freemsg(mp4ctl);
17619 	else
17620 		qreply(q, mp4ctl);
17621 
17622 	return (mp2ctl);
17623 }
17624 
17625 /*
17626  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
17627  * ipv6NetToMediaEntryTable in an NDP walk.
17628  */
17629 static mblk_t *
17630 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17631 {
17632 	struct opthdr	*optp;
17633 	mblk_t		*mp2ctl;	/* Returned */
17634 	mblk_t		*mp3ctl;	/* nettomedia */
17635 	mblk_t		*mp4ctl;	/* routeattrs */
17636 	iproutedata_t	ird;
17637 	zoneid_t	zoneid;
17638 
17639 	/*
17640 	 * make copies of the original message
17641 	 *	- mp2ctl is returned unchanged to the caller for his use
17642 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
17643 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
17644 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
17645 	 */
17646 	mp2ctl = copymsg(mpctl);
17647 	mp3ctl = copymsg(mpctl);
17648 	mp4ctl = copymsg(mpctl);
17649 	if (mp3ctl == NULL || mp4ctl == NULL) {
17650 		freemsg(mp4ctl);
17651 		freemsg(mp3ctl);
17652 		freemsg(mp2ctl);
17653 		freemsg(mpctl);
17654 		return (NULL);
17655 	}
17656 
17657 	bzero(&ird, sizeof (ird));
17658 
17659 	ird.ird_route.lp_head = mpctl->b_cont;
17660 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17661 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17662 
17663 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17664 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
17665 
17666 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17667 	optp->level = MIB2_IP6;
17668 	optp->name = MIB2_IP6_ROUTE;
17669 	optp->len = msgdsize(ird.ird_route.lp_head);
17670 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17671 	    (int)optp->level, (int)optp->name, (int)optp->len));
17672 	qreply(q, mpctl);
17673 
17674 	/* ipv6NetToMediaEntryTable in mp3ctl */
17675 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
17676 
17677 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17678 	optp->level = MIB2_IP6;
17679 	optp->name = MIB2_IP6_MEDIA;
17680 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17681 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17682 	    (int)optp->level, (int)optp->name, (int)optp->len));
17683 	qreply(q, mp3ctl);
17684 
17685 	/* ipv6RouteAttributeTable in mp4ctl */
17686 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17687 	optp->level = MIB2_IP6;
17688 	optp->name = EXPER_IP_RTATTR;
17689 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17690 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17691 	    (int)optp->level, (int)optp->name, (int)optp->len));
17692 	if (optp->len == 0)
17693 		freemsg(mp4ctl);
17694 	else
17695 		qreply(q, mp4ctl);
17696 
17697 	return (mp2ctl);
17698 }
17699 
17700 /*
17701  * ICMPv6 mib: One per ill
17702  */
17703 static mblk_t *
17704 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17705 {
17706 	struct opthdr		*optp;
17707 	mblk_t			*mp2ctl;
17708 	ill_t			*ill;
17709 	ill_walk_context_t	ctx;
17710 	mblk_t			*mp_tail = NULL;
17711 
17712 	/*
17713 	 * Make a copy of the original message
17714 	 */
17715 	mp2ctl = copymsg(mpctl);
17716 
17717 	/* fixed length IPv6 structure ... */
17718 
17719 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17720 	optp->level = MIB2_IP6;
17721 	optp->name = 0;
17722 	/* Include "unknown interface" ip6_mib */
17723 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17724 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17725 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17726 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17727 	    sizeof (mib2_ipv6IfStatsEntry_t));
17728 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17729 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17730 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17731 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17732 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17733 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17734 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17735 	    (int)sizeof (ip6_mib))) {
17736 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17737 		    (uint_t)sizeof (ip6_mib)));
17738 	}
17739 
17740 	rw_enter(&ill_g_lock, RW_READER);
17741 	ill = ILL_START_WALK_V6(&ctx);
17742 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17743 		ill->ill_ip6_mib->ipv6IfIndex =
17744 		    ill->ill_phyint->phyint_ifindex;
17745 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17746 		    ipv6_forward ? 1 : 2);
17747 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17748 		    ill->ill_max_hops);
17749 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17750 		    sizeof (mib2_ipv6IfStatsEntry_t));
17751 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17752 		    sizeof (mib2_ipv6AddrEntry_t));
17753 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17754 		    sizeof (mib2_ipv6RouteEntry_t));
17755 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17756 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17757 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17758 		    sizeof (ipv6_member_t));
17759 
17760 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17761 		    (char *)ill->ill_ip6_mib,
17762 		    (int)sizeof (*ill->ill_ip6_mib))) {
17763 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17764 				"%u bytes\n",
17765 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17766 		}
17767 	}
17768 	rw_exit(&ill_g_lock);
17769 
17770 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17771 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17772 	    (int)optp->level, (int)optp->name, (int)optp->len));
17773 	qreply(q, mpctl);
17774 	return (mp2ctl);
17775 }
17776 
17777 /*
17778  * ICMPv6 mib: One per ill
17779  */
17780 static mblk_t *
17781 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17782 {
17783 	struct opthdr		*optp;
17784 	mblk_t			*mp2ctl;
17785 	ill_t			*ill;
17786 	ill_walk_context_t	ctx;
17787 	mblk_t			*mp_tail = NULL;
17788 	/*
17789 	 * Make a copy of the original message
17790 	 */
17791 	mp2ctl = copymsg(mpctl);
17792 
17793 	/* fixed length ICMPv6 structure ... */
17794 
17795 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17796 	optp->level = MIB2_ICMP6;
17797 	optp->name = 0;
17798 	/* Include "unknown interface" icmp6_mib */
17799 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17800 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17801 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17802 	    (int)sizeof (icmp6_mib))) {
17803 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17804 		    (uint_t)sizeof (icmp6_mib)));
17805 	}
17806 
17807 	rw_enter(&ill_g_lock, RW_READER);
17808 	ill = ILL_START_WALK_V6(&ctx);
17809 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17810 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17811 		    ill->ill_phyint->phyint_ifindex;
17812 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17813 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17814 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17815 		    (char *)ill->ill_icmp6_mib,
17816 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17817 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17818 			    "%u bytes\n",
17819 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17820 		}
17821 	}
17822 	rw_exit(&ill_g_lock);
17823 
17824 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17825 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17826 	    (int)optp->level, (int)optp->name, (int)optp->len));
17827 	qreply(q, mpctl);
17828 	return (mp2ctl);
17829 }
17830 
17831 /*
17832  * ire_walk routine to create both ipRouteEntryTable and
17833  * ipNetToMediaEntryTable in one IRE walk
17834  */
17835 static void
17836 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
17837 {
17838 	ill_t				*ill;
17839 	ipif_t				*ipif;
17840 	mblk_t				*llmp;
17841 	dl_unitdata_req_t		*dlup;
17842 	mib2_ipRouteEntry_t		*re;
17843 	mib2_ipNetToMediaEntry_t	ntme;
17844 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
17845 	ipaddr_t			gw_addr;
17846 	tsol_ire_gw_secattr_t		*attrp;
17847 	tsol_gc_t			*gc = NULL;
17848 	tsol_gcgrp_t			*gcgrp = NULL;
17849 	uint_t				sacnt = 0;
17850 	int				i;
17851 
17852 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17853 
17854 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
17855 		return;
17856 
17857 	if ((attrp = ire->ire_gw_secattr) != NULL) {
17858 		mutex_enter(&attrp->igsa_lock);
17859 		if ((gc = attrp->igsa_gc) != NULL) {
17860 			gcgrp = gc->gc_grp;
17861 			ASSERT(gcgrp != NULL);
17862 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17863 			sacnt = 1;
17864 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
17865 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17866 			gc = gcgrp->gcgrp_head;
17867 			sacnt = gcgrp->gcgrp_count;
17868 		}
17869 		mutex_exit(&attrp->igsa_lock);
17870 
17871 		/* do nothing if there's no gc to report */
17872 		if (gc == NULL) {
17873 			ASSERT(sacnt == 0);
17874 			if (gcgrp != NULL) {
17875 				/* we might as well drop the lock now */
17876 				rw_exit(&gcgrp->gcgrp_rwlock);
17877 				gcgrp = NULL;
17878 			}
17879 			attrp = NULL;
17880 		}
17881 
17882 		ASSERT(gc == NULL || (gcgrp != NULL &&
17883 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
17884 	}
17885 	ASSERT(sacnt == 0 || gc != NULL);
17886 
17887 	if (sacnt != 0 &&
17888 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
17889 		kmem_free(re, sizeof (*re));
17890 		rw_exit(&gcgrp->gcgrp_rwlock);
17891 		return;
17892 	}
17893 
17894 	/*
17895 	 * Return all IRE types for route table... let caller pick and choose
17896 	 */
17897 	re->ipRouteDest = ire->ire_addr;
17898 	ipif = ire->ire_ipif;
17899 	re->ipRouteIfIndex.o_length = 0;
17900 	if (ire->ire_type == IRE_CACHE) {
17901 		ill = (ill_t *)ire->ire_stq->q_ptr;
17902 		re->ipRouteIfIndex.o_length =
17903 		    ill->ill_name_length == 0 ? 0 :
17904 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17905 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
17906 		    re->ipRouteIfIndex.o_length);
17907 	} else if (ipif != NULL) {
17908 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
17909 		    OCTET_LENGTH);
17910 		re->ipRouteIfIndex.o_length =
17911 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
17912 	}
17913 	re->ipRouteMetric1 = -1;
17914 	re->ipRouteMetric2 = -1;
17915 	re->ipRouteMetric3 = -1;
17916 	re->ipRouteMetric4 = -1;
17917 
17918 	gw_addr = ire->ire_gateway_addr;
17919 
17920 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17921 		re->ipRouteNextHop = ire->ire_src_addr;
17922 	else
17923 		re->ipRouteNextHop = gw_addr;
17924 	/* indirect(4), direct(3), or invalid(2) */
17925 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17926 		re->ipRouteType = 2;
17927 	else
17928 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
17929 	re->ipRouteProto = -1;
17930 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17931 	re->ipRouteMask = ire->ire_mask;
17932 	re->ipRouteMetric5 = -1;
17933 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
17934 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
17935 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17936 	llmp = ire->ire_dlureq_mp;
17937 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
17938 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
17939 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
17940 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17941 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17942 	re->ipRouteInfo.re_flags	= ire->ire_flags;
17943 	re->ipRouteInfo.re_in_ill.o_length = 0;
17944 	if (ire->ire_in_ill != NULL) {
17945 		re->ipRouteInfo.re_in_ill.o_length =
17946 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17947 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17948 		bcopy(ire->ire_in_ill->ill_name,
17949 		    re->ipRouteInfo.re_in_ill.o_bytes,
17950 		    re->ipRouteInfo.re_in_ill.o_length);
17951 	}
17952 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17953 
17954 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
17955 	    (char *)re, (int)sizeof (*re))) {
17956 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17957 		    (uint_t)sizeof (*re)));
17958 	}
17959 
17960 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
17961 		iaeptr->iae_routeidx = ird->ird_idx;
17962 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
17963 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
17964 	}
17965 
17966 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
17967 	    (char *)iae, sacnt * sizeof (*iae))) {
17968 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17969 		    (unsigned)(sacnt * sizeof (*iae))));
17970 	}
17971 
17972 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17973 		goto done;
17974 	/*
17975 	 * only IRE_CACHE entries that are for a directly connected subnet
17976 	 * get appended to net -> phys addr table
17977 	 * (others in arp)
17978 	 */
17979 	ntme.ipNetToMediaIfIndex.o_length = 0;
17980 	ill = ire_to_ill(ire);
17981 	ASSERT(ill != NULL);
17982 	ntme.ipNetToMediaIfIndex.o_length =
17983 	    ill->ill_name_length == 0 ? 0 :
17984 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17985 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17986 		    ntme.ipNetToMediaIfIndex.o_length);
17987 
17988 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17989 	if (llmp) {
17990 		uchar_t *addr;
17991 
17992 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17993 		/* Remove sap from  address */
17994 		if (ill->ill_sap_length < 0)
17995 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
17996 		else
17997 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
17998 			    ill->ill_sap_length;
17999 
18000 		ntme.ipNetToMediaPhysAddress.o_length =
18001 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18002 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18003 		    ntme.ipNetToMediaPhysAddress.o_length);
18004 	}
18005 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18006 	/* assume dynamic (may be changed in arp) */
18007 	ntme.ipNetToMediaType = 3;
18008 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18009 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18010 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18011 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18012 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18013 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18014 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18015 		    (uint_t)sizeof (ntme)));
18016 	}
18017 done:
18018 	/* bump route index for next pass */
18019 	ird->ird_idx++;
18020 
18021 	kmem_free(re, sizeof (*re));
18022 	if (sacnt != 0)
18023 		kmem_free(iae, sacnt * sizeof (*iae));
18024 
18025 	if (gcgrp != NULL)
18026 		rw_exit(&gcgrp->gcgrp_rwlock);
18027 }
18028 
18029 /*
18030  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18031  */
18032 static void
18033 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18034 {
18035 	ill_t				*ill;
18036 	ipif_t				*ipif;
18037 	mib2_ipv6RouteEntry_t		*re;
18038 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18039 	in6_addr_t			gw_addr_v6;
18040 	tsol_ire_gw_secattr_t		*attrp;
18041 	tsol_gc_t			*gc = NULL;
18042 	tsol_gcgrp_t			*gcgrp = NULL;
18043 	uint_t				sacnt = 0;
18044 	int				i;
18045 
18046 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18047 
18048 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18049 		return;
18050 
18051 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18052 		mutex_enter(&attrp->igsa_lock);
18053 		if ((gc = attrp->igsa_gc) != NULL) {
18054 			gcgrp = gc->gc_grp;
18055 			ASSERT(gcgrp != NULL);
18056 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18057 			sacnt = 1;
18058 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18059 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18060 			gc = gcgrp->gcgrp_head;
18061 			sacnt = gcgrp->gcgrp_count;
18062 		}
18063 		mutex_exit(&attrp->igsa_lock);
18064 
18065 		/* do nothing if there's no gc to report */
18066 		if (gc == NULL) {
18067 			ASSERT(sacnt == 0);
18068 			if (gcgrp != NULL) {
18069 				/* we might as well drop the lock now */
18070 				rw_exit(&gcgrp->gcgrp_rwlock);
18071 				gcgrp = NULL;
18072 			}
18073 			attrp = NULL;
18074 		}
18075 
18076 		ASSERT(gc == NULL || (gcgrp != NULL &&
18077 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18078 	}
18079 	ASSERT(sacnt == 0 || gc != NULL);
18080 
18081 	if (sacnt != 0 &&
18082 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18083 		kmem_free(re, sizeof (*re));
18084 		rw_exit(&gcgrp->gcgrp_rwlock);
18085 		return;
18086 	}
18087 
18088 	/*
18089 	 * Return all IRE types for route table... let caller pick and choose
18090 	 */
18091 	re->ipv6RouteDest = ire->ire_addr_v6;
18092 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18093 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18094 	re->ipv6RouteIfIndex.o_length = 0;
18095 	ipif = ire->ire_ipif;
18096 	if (ire->ire_type == IRE_CACHE) {
18097 		ill = (ill_t *)ire->ire_stq->q_ptr;
18098 		re->ipv6RouteIfIndex.o_length =
18099 		    ill->ill_name_length == 0 ? 0 :
18100 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18101 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18102 		    re->ipv6RouteIfIndex.o_length);
18103 	} else if (ipif != NULL) {
18104 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18105 		    OCTET_LENGTH);
18106 		re->ipv6RouteIfIndex.o_length =
18107 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18108 	}
18109 
18110 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18111 
18112 	mutex_enter(&ire->ire_lock);
18113 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18114 	mutex_exit(&ire->ire_lock);
18115 
18116 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18117 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18118 	else
18119 		re->ipv6RouteNextHop = gw_addr_v6;
18120 
18121 	/* remote(4), local(3), or discard(2) */
18122 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18123 		re->ipv6RouteType = 2;
18124 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18125 		re->ipv6RouteType = 3;
18126 	else
18127 		re->ipv6RouteType = 4;
18128 
18129 	re->ipv6RouteProtocol	= -1;
18130 	re->ipv6RoutePolicy	= 0;
18131 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18132 	re->ipv6RouteNextHopRDI	= 0;
18133 	re->ipv6RouteWeight	= 0;
18134 	re->ipv6RouteMetric	= 0;
18135 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18136 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18137 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18138 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18139 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18140 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18141 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18142 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18143 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18144 
18145 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18146 	    (char *)re, (int)sizeof (*re))) {
18147 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18148 		    (uint_t)sizeof (*re)));
18149 	}
18150 
18151 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18152 		iaeptr->iae_routeidx = ird->ird_idx;
18153 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18154 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18155 	}
18156 
18157 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18158 	    (char *)iae, sacnt * sizeof (*iae))) {
18159 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18160 		    (unsigned)(sacnt * sizeof (*iae))));
18161 	}
18162 
18163 	/* bump route index for next pass */
18164 	ird->ird_idx++;
18165 
18166 	kmem_free(re, sizeof (*re));
18167 	if (sacnt != 0)
18168 		kmem_free(iae, sacnt * sizeof (*iae));
18169 
18170 	if (gcgrp != NULL)
18171 		rw_exit(&gcgrp->gcgrp_rwlock);
18172 }
18173 
18174 /*
18175  * ndp_walk routine to create ipv6NetToMediaEntryTable
18176  */
18177 static int
18178 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18179 {
18180 	ill_t				*ill;
18181 	mib2_ipv6NetToMediaEntry_t	ntme;
18182 	dl_unitdata_req_t		*dl;
18183 
18184 	ill = nce->nce_ill;
18185 	ASSERT(ill->ill_isv6);
18186 
18187 	/*
18188 	 * Neighbor cache entry attached to IRE with on-link
18189 	 * destination.
18190 	 */
18191 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18192 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18193 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18194 	    (nce->nce_res_mp != NULL)) {
18195 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18196 		ntme.ipv6NetToMediaPhysAddress.o_length =
18197 		    dl->dl_dest_addr_length;
18198 	} else {
18199 		ntme.ipv6NetToMediaPhysAddress.o_length =
18200 		    ill->ill_phys_addr_length;
18201 	}
18202 	if (nce->nce_res_mp != NULL) {
18203 		bcopy((char *)nce->nce_res_mp->b_rptr +
18204 		    NCE_LL_ADDR_OFFSET(ill),
18205 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18206 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18207 	} else {
18208 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18209 		    ill->ill_phys_addr_length);
18210 	}
18211 	/*
18212 	 * Note: Returns ND_* states. Should be:
18213 	 * reachable(1), stale(2), delay(3), probe(4),
18214 	 * invalid(5), unknown(6)
18215 	 */
18216 	ntme.ipv6NetToMediaState = nce->nce_state;
18217 	ntme.ipv6NetToMediaLastUpdated = 0;
18218 
18219 	/* other(1), dynamic(2), static(3), local(4) */
18220 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18221 		ntme.ipv6NetToMediaType = 4;
18222 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18223 		ntme.ipv6NetToMediaType = 1;
18224 	} else {
18225 		ntme.ipv6NetToMediaType = 2;
18226 	}
18227 
18228 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18229 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18230 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18231 		    (uint_t)sizeof (ntme)));
18232 	}
18233 	return (0);
18234 }
18235 
18236 /*
18237  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18238  */
18239 /* ARGSUSED */
18240 int
18241 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18242 {
18243 	switch (level) {
18244 	case MIB2_IP:
18245 	case MIB2_ICMP:
18246 		switch (name) {
18247 		default:
18248 			break;
18249 		}
18250 		return (1);
18251 	default:
18252 		return (1);
18253 	}
18254 }
18255 
18256 /*
18257  * Called before the options are updated to check if this packet will
18258  * be source routed from here.
18259  * This routine assumes that the options are well formed i.e. that they
18260  * have already been checked.
18261  */
18262 static boolean_t
18263 ip_source_routed(ipha_t *ipha)
18264 {
18265 	ipoptp_t	opts;
18266 	uchar_t		*opt;
18267 	uint8_t		optval;
18268 	uint8_t		optlen;
18269 	ipaddr_t	dst;
18270 	ire_t		*ire;
18271 
18272 	if (IS_SIMPLE_IPH(ipha)) {
18273 		ip2dbg(("not source routed\n"));
18274 		return (B_FALSE);
18275 	}
18276 	dst = ipha->ipha_dst;
18277 	for (optval = ipoptp_first(&opts, ipha);
18278 	    optval != IPOPT_EOL;
18279 	    optval = ipoptp_next(&opts)) {
18280 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18281 		opt = opts.ipoptp_cur;
18282 		optlen = opts.ipoptp_len;
18283 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18284 		    optval, optlen));
18285 		switch (optval) {
18286 			uint32_t off;
18287 		case IPOPT_SSRR:
18288 		case IPOPT_LSRR:
18289 			/*
18290 			 * If dst is one of our addresses and there are some
18291 			 * entries left in the source route return (true).
18292 			 */
18293 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18294 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18295 			if (ire == NULL) {
18296 				ip2dbg(("ip_source_routed: not next"
18297 				    " source route 0x%x\n",
18298 				    ntohl(dst)));
18299 				return (B_FALSE);
18300 			}
18301 			ire_refrele(ire);
18302 			off = opt[IPOPT_OFFSET];
18303 			off--;
18304 			if (optlen < IP_ADDR_LEN ||
18305 			    off > optlen - IP_ADDR_LEN) {
18306 				/* End of source route */
18307 				ip1dbg(("ip_source_routed: end of SR\n"));
18308 				return (B_FALSE);
18309 			}
18310 			return (B_TRUE);
18311 		}
18312 	}
18313 	ip2dbg(("not source routed\n"));
18314 	return (B_FALSE);
18315 }
18316 
18317 /*
18318  * Check if the packet contains any source route.
18319  */
18320 static boolean_t
18321 ip_source_route_included(ipha_t *ipha)
18322 {
18323 	ipoptp_t	opts;
18324 	uint8_t		optval;
18325 
18326 	if (IS_SIMPLE_IPH(ipha))
18327 		return (B_FALSE);
18328 	for (optval = ipoptp_first(&opts, ipha);
18329 	    optval != IPOPT_EOL;
18330 	    optval = ipoptp_next(&opts)) {
18331 		switch (optval) {
18332 		case IPOPT_SSRR:
18333 		case IPOPT_LSRR:
18334 			return (B_TRUE);
18335 		}
18336 	}
18337 	return (B_FALSE);
18338 }
18339 
18340 /*
18341  * Called when the IRE expiration timer fires.
18342  */
18343 /* ARGSUSED */
18344 void
18345 ip_trash_timer_expire(void *args)
18346 {
18347 	int	flush_flag = 0;
18348 
18349 	/*
18350 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18351 	 * This lock makes sure that a new invocation of this function
18352 	 * that occurs due to an almost immediate timer firing will not
18353 	 * progress beyond this point until the current invocation is done
18354 	 */
18355 	mutex_enter(&ip_trash_timer_lock);
18356 	ip_ire_expire_id = 0;
18357 	mutex_exit(&ip_trash_timer_lock);
18358 
18359 	/* Periodic timer */
18360 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18361 		/*
18362 		 * Remove all IRE_CACHE entries since they might
18363 		 * contain arp information.
18364 		 */
18365 		flush_flag |= FLUSH_ARP_TIME;
18366 		ip_ire_arp_time_elapsed = 0;
18367 		IP_STAT(ip_ire_arp_timer_expired);
18368 	}
18369 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18370 		/* Remove all redirects */
18371 		flush_flag |= FLUSH_REDIRECT_TIME;
18372 		ip_ire_rd_time_elapsed = 0;
18373 		IP_STAT(ip_ire_redirect_timer_expired);
18374 	}
18375 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18376 		/* Increase path mtu */
18377 		flush_flag |= FLUSH_MTU_TIME;
18378 		ip_ire_pmtu_time_elapsed = 0;
18379 		IP_STAT(ip_ire_pmtu_timer_expired);
18380 	}
18381 	if (flush_flag != 0) {
18382 		/* Walk all IPv4 IRE's and update them */
18383 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
18384 		    ALL_ZONES);
18385 	}
18386 	if (flush_flag & FLUSH_MTU_TIME) {
18387 		/*
18388 		 * Walk all IPv6 IRE's and update them
18389 		 * Note that ARP and redirect timers are not
18390 		 * needed since NUD handles stale entries.
18391 		 */
18392 		flush_flag = FLUSH_MTU_TIME;
18393 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18394 		    ALL_ZONES);
18395 	}
18396 
18397 	ip_ire_arp_time_elapsed += ip_timer_interval;
18398 	ip_ire_rd_time_elapsed += ip_timer_interval;
18399 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
18400 
18401 	/*
18402 	 * Hold the lock to serialize timeout calls and prevent
18403 	 * stale values in ip_ire_expire_id. Otherwise it is possible
18404 	 * for the timer to fire and a new invocation of this function
18405 	 * to start before the return value of timeout has been stored
18406 	 * in ip_ire_expire_id by the current invocation.
18407 	 */
18408 	mutex_enter(&ip_trash_timer_lock);
18409 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
18410 	    MSEC_TO_TICK(ip_timer_interval));
18411 	mutex_exit(&ip_trash_timer_lock);
18412 }
18413 
18414 /*
18415  * Called by the memory allocator subsystem directly, when the system
18416  * is running low on memory.
18417  */
18418 /* ARGSUSED */
18419 void
18420 ip_trash_ire_reclaim(void *args)
18421 {
18422 	ire_cache_count_t icc;
18423 	ire_cache_reclaim_t icr;
18424 	ncc_cache_count_t ncc;
18425 	nce_cache_reclaim_t ncr;
18426 	uint_t delete_cnt;
18427 	/*
18428 	 * Memory reclaim call back.
18429 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
18430 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
18431 	 * entries, determine what fraction to free for
18432 	 * each category of IRE_CACHE entries giving absolute priority
18433 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
18434 	 * entry will be freed unless all offlink entries are freed).
18435 	 */
18436 	icc.icc_total = 0;
18437 	icc.icc_unused = 0;
18438 	icc.icc_offlink = 0;
18439 	icc.icc_pmtu = 0;
18440 	icc.icc_onlink = 0;
18441 	ire_walk(ire_cache_count, (char *)&icc);
18442 
18443 	/*
18444 	 * Free NCEs for IPv6 like the onlink ires.
18445 	 */
18446 	ncc.ncc_total = 0;
18447 	ncc.ncc_host = 0;
18448 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
18449 
18450 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
18451 	    icc.icc_pmtu + icc.icc_onlink);
18452 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
18453 	IP_STAT(ip_trash_ire_reclaim_calls);
18454 	if (delete_cnt == 0)
18455 		return;
18456 	IP_STAT(ip_trash_ire_reclaim_success);
18457 	/* Always delete all unused offlink entries */
18458 	icr.icr_unused = 1;
18459 	if (delete_cnt <= icc.icc_unused) {
18460 		/*
18461 		 * Only need to free unused entries.  In other words,
18462 		 * there are enough unused entries to free to meet our
18463 		 * target number of freed ire cache entries.
18464 		 */
18465 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
18466 		ncr.ncr_host = 0;
18467 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
18468 		/*
18469 		 * Only need to free unused entries, plus a fraction of offlink
18470 		 * entries.  It follows from the first if statement that
18471 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
18472 		 */
18473 		delete_cnt -= icc.icc_unused;
18474 		/* Round up # deleted by truncating fraction */
18475 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
18476 		icr.icr_pmtu = icr.icr_onlink = 0;
18477 		ncr.ncr_host = 0;
18478 	} else if (delete_cnt <=
18479 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
18480 		/*
18481 		 * Free all unused and offlink entries, plus a fraction of
18482 		 * pmtu entries.  It follows from the previous if statement
18483 		 * that icc_pmtu is non-zero, and that
18484 		 * delete_cnt != icc_unused + icc_offlink.
18485 		 */
18486 		icr.icr_offlink = 1;
18487 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
18488 		/* Round up # deleted by truncating fraction */
18489 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
18490 		icr.icr_onlink = 0;
18491 		ncr.ncr_host = 0;
18492 	} else {
18493 		/*
18494 		 * Free all unused, offlink, and pmtu entries, plus a fraction
18495 		 * of onlink entries.  If we're here, then we know that
18496 		 * icc_onlink is non-zero, and that
18497 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
18498 		 */
18499 		icr.icr_offlink = icr.icr_pmtu = 1;
18500 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
18501 		    icc.icc_pmtu;
18502 		/* Round up # deleted by truncating fraction */
18503 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
18504 		/* Using the same delete fraction as for onlink IREs */
18505 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
18506 	}
18507 #ifdef DEBUG
18508 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
18509 	    "fractions %d/%d/%d/%d\n",
18510 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
18511 	    icc.icc_unused, icc.icc_offlink,
18512 	    icc.icc_pmtu, icc.icc_onlink,
18513 	    icr.icr_unused, icr.icr_offlink,
18514 	    icr.icr_pmtu, icr.icr_onlink));
18515 #endif
18516 	ire_walk(ire_cache_reclaim, (char *)&icr);
18517 	if (ncr.ncr_host != 0)
18518 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
18519 		    (uchar_t *)&ncr);
18520 #ifdef DEBUG
18521 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
18522 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
18523 	ire_walk(ire_cache_count, (char *)&icc);
18524 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
18525 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
18526 	    icc.icc_pmtu, icc.icc_onlink));
18527 #endif
18528 }
18529 
18530 /*
18531  * ip_unbind is called when a copy of an unbind request is received from the
18532  * upper level protocol.  We remove this conn from any fanout hash list it is
18533  * on, and zero out the bind information.  No reply is expected up above.
18534  */
18535 mblk_t *
18536 ip_unbind(queue_t *q, mblk_t *mp)
18537 {
18538 	conn_t	*connp = Q_TO_CONN(q);
18539 
18540 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
18541 
18542 	if (is_system_labeled() && connp->conn_anon_port) {
18543 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
18544 		    connp->conn_mlp_type, connp->conn_ulp,
18545 		    ntohs(connp->conn_lport), B_FALSE);
18546 		connp->conn_anon_port = 0;
18547 	}
18548 	connp->conn_mlp_type = mlptSingle;
18549 
18550 	ipcl_hash_remove(connp);
18551 
18552 	ASSERT(mp->b_cont == NULL);
18553 	/*
18554 	 * Convert mp into a T_OK_ACK
18555 	 */
18556 	mp = mi_tpi_ok_ack_alloc(mp);
18557 
18558 	/*
18559 	 * should not happen in practice... T_OK_ACK is smaller than the
18560 	 * original message.
18561 	 */
18562 	if (mp == NULL)
18563 		return (NULL);
18564 
18565 	/*
18566 	 * Don't bzero the ports if its TCP since TCP still needs the
18567 	 * lport to remove it from its own bind hash. TCP will do the
18568 	 * cleanup.
18569 	 */
18570 	if (!IPCL_IS_TCP(connp))
18571 		bzero(&connp->u_port, sizeof (connp->u_port));
18572 
18573 	return (mp);
18574 }
18575 
18576 /*
18577  * Write side put procedure.  Outbound data, IOCTLs, responses from
18578  * resolvers, etc, come down through here.
18579  */
18580 void
18581 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
18582 {
18583 	conn_t		*connp = NULL;
18584 	queue_t		*q = (queue_t *)arg2;
18585 	ipha_t		*ipha;
18586 #define	rptr	((uchar_t *)ipha)
18587 	ire_t		*ire = NULL;
18588 	ire_t		*sctp_ire = NULL;
18589 	uint32_t	v_hlen_tos_len;
18590 	ipaddr_t	dst;
18591 	mblk_t		*first_mp = NULL;
18592 	boolean_t	mctl_present;
18593 	ipsec_out_t	*io;
18594 	int		match_flags;
18595 	ill_t		*attach_ill = NULL;
18596 					/* Bind to IPIF_NOFAILOVER ill etc. */
18597 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
18598 	ipif_t		*dst_ipif;
18599 	boolean_t	multirt_need_resolve = B_FALSE;
18600 	mblk_t		*copy_mp = NULL;
18601 	int		err;
18602 	zoneid_t	zoneid;
18603 	int	adjust;
18604 	uint16_t iplen;
18605 	boolean_t	need_decref = B_FALSE;
18606 	boolean_t	ignore_dontroute = B_FALSE;
18607 	boolean_t	ignore_nexthop = B_FALSE;
18608 	boolean_t	ip_nexthop = B_FALSE;
18609 	ipaddr_t	nexthop_addr;
18610 
18611 #ifdef	_BIG_ENDIAN
18612 #define	V_HLEN	(v_hlen_tos_len >> 24)
18613 #else
18614 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
18615 #endif
18616 
18617 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
18618 	    "ip_wput_start: q %p", q);
18619 
18620 	/*
18621 	 * ip_wput fast path
18622 	 */
18623 
18624 	/* is packet from ARP ? */
18625 	if (q->q_next != NULL)
18626 		goto qnext;
18627 
18628 	connp = (conn_t *)arg;
18629 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
18630 
18631 	/* is queue flow controlled? */
18632 	if ((q->q_first != NULL || connp->conn_draining) &&
18633 	    (caller == IP_WPUT)) {
18634 		ASSERT(!need_decref);
18635 		(void) putq(q, mp);
18636 		return;
18637 	}
18638 
18639 	/* Multidata transmit? */
18640 	if (DB_TYPE(mp) == M_MULTIDATA) {
18641 		/*
18642 		 * We should never get here, since all Multidata messages
18643 		 * originating from tcp should have been directed over to
18644 		 * tcp_multisend() in the first place.
18645 		 */
18646 		BUMP_MIB(&ip_mib, ipOutDiscards);
18647 		freemsg(mp);
18648 		return;
18649 	} else if (DB_TYPE(mp) != M_DATA)
18650 		goto notdata;
18651 
18652 	if (mp->b_flag & MSGHASREF) {
18653 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18654 		mp->b_flag &= ~MSGHASREF;
18655 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
18656 		need_decref = B_TRUE;
18657 	}
18658 	ipha = (ipha_t *)mp->b_rptr;
18659 
18660 	/* is IP header non-aligned or mblk smaller than basic IP header */
18661 #ifndef SAFETY_BEFORE_SPEED
18662 	if (!OK_32PTR(rptr) ||
18663 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
18664 		goto hdrtoosmall;
18665 #endif
18666 
18667 	ASSERT(OK_32PTR(ipha));
18668 
18669 	/*
18670 	 * This function assumes that mp points to an IPv4 packet.  If it's the
18671 	 * wrong version, we'll catch it again in ip_output_v6.
18672 	 *
18673 	 * Note that this is *only* locally-generated output here, and never
18674 	 * forwarded data, and that we need to deal only with transports that
18675 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
18676 	 * label.)
18677 	 */
18678 	if (is_system_labeled() &&
18679 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
18680 	    !connp->conn_ulp_labeled) {
18681 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
18682 		    connp->conn_mac_exempt);
18683 		ipha = (ipha_t *)mp->b_rptr;
18684 		if (err != 0) {
18685 			first_mp = mp;
18686 			if (err == EINVAL)
18687 				goto icmp_parameter_problem;
18688 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
18689 			goto drop_pkt;
18690 		}
18691 		iplen = ntohs(ipha->ipha_length) + adjust;
18692 		ipha->ipha_length = htons(iplen);
18693 	}
18694 
18695 	/*
18696 	 * If there is a policy, try to attach an ipsec_out in
18697 	 * the front. At the end, first_mp either points to a
18698 	 * M_DATA message or IPSEC_OUT message linked to a
18699 	 * M_DATA message. We have to do it now as we might
18700 	 * lose the "conn" if we go through ip_newroute.
18701 	 */
18702 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
18703 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
18704 		    ipha->ipha_protocol)) == NULL)) {
18705 			if (need_decref)
18706 				CONN_DEC_REF(connp);
18707 			return;
18708 		} else {
18709 			ASSERT(mp->b_datap->db_type == M_CTL);
18710 			first_mp = mp;
18711 			mp = mp->b_cont;
18712 			mctl_present = B_TRUE;
18713 		}
18714 	} else {
18715 		first_mp = mp;
18716 		mctl_present = B_FALSE;
18717 	}
18718 
18719 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18720 
18721 	/* is wrong version or IP options present */
18722 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
18723 		goto version_hdrlen_check;
18724 	dst = ipha->ipha_dst;
18725 
18726 	if (connp->conn_nofailover_ill != NULL) {
18727 		attach_ill = conn_get_held_ill(connp,
18728 		    &connp->conn_nofailover_ill, &err);
18729 		if (err == ILL_LOOKUP_FAILED) {
18730 			if (need_decref)
18731 				CONN_DEC_REF(connp);
18732 			freemsg(first_mp);
18733 			return;
18734 		}
18735 	}
18736 
18737 	/* is packet multicast? */
18738 	if (CLASSD(dst))
18739 		goto multicast;
18740 
18741 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
18742 	    (connp->conn_nexthop_set)) {
18743 		/*
18744 		 * If the destination is a broadcast or a loopback
18745 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
18746 		 * through the standard path. But in the case of local
18747 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
18748 		 * the standard path not IP_XMIT_IF.
18749 		 */
18750 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18751 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
18752 		    (ire->ire_type != IRE_LOOPBACK))) {
18753 			if ((connp->conn_dontroute ||
18754 			    connp->conn_nexthop_set) && (ire != NULL) &&
18755 			    (ire->ire_type == IRE_LOCAL))
18756 				goto standard_path;
18757 
18758 			if (ire != NULL) {
18759 				ire_refrele(ire);
18760 				/* No more access to ire */
18761 				ire = NULL;
18762 			}
18763 			/*
18764 			 * bypass routing checks and go directly to
18765 			 * interface.
18766 			 */
18767 			if (connp->conn_dontroute) {
18768 				goto dontroute;
18769 			} else if (connp->conn_nexthop_set) {
18770 				ip_nexthop = B_TRUE;
18771 				nexthop_addr = connp->conn_nexthop_v4;
18772 				goto send_from_ill;
18773 			}
18774 
18775 			/*
18776 			 * If IP_XMIT_IF socket option is set,
18777 			 * then we allow unicast and multicast
18778 			 * packets to go through the ill. It is
18779 			 * quite possible that the destination
18780 			 * is not in the ire cache table and we
18781 			 * do not want to go to ip_newroute()
18782 			 * instead we call ip_newroute_ipif.
18783 			 */
18784 			xmit_ill = conn_get_held_ill(connp,
18785 			    &connp->conn_xmit_if_ill, &err);
18786 			if (err == ILL_LOOKUP_FAILED) {
18787 				if (attach_ill != NULL)
18788 					ill_refrele(attach_ill);
18789 				if (need_decref)
18790 					CONN_DEC_REF(connp);
18791 				freemsg(first_mp);
18792 				return;
18793 			}
18794 			goto send_from_ill;
18795 		}
18796 standard_path:
18797 		/* Must be a broadcast, a loopback or a local ire */
18798 		if (ire != NULL) {
18799 			ire_refrele(ire);
18800 			/* No more access to ire */
18801 			ire = NULL;
18802 		}
18803 	}
18804 
18805 	if (attach_ill != NULL)
18806 		goto send_from_ill;
18807 
18808 	/*
18809 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18810 	 * this for the tcp global queue and listen end point
18811 	 * as it does not really have a real destination to
18812 	 * talk to.  This is also true for SCTP.
18813 	 */
18814 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18815 	    !connp->conn_fully_bound) {
18816 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18817 		if (ire == NULL)
18818 			goto noirefound;
18819 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18820 		    "ip_wput_end: q %p (%S)", q, "end");
18821 
18822 		/*
18823 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18824 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18825 		 */
18826 		if (ire->ire_flags & RTF_MULTIRT) {
18827 
18828 			/*
18829 			 * Force the TTL of multirouted packets if required.
18830 			 * The TTL of such packets is bounded by the
18831 			 * ip_multirt_ttl ndd variable.
18832 			 */
18833 			if ((ip_multirt_ttl > 0) &&
18834 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18835 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18836 				    "(was %d), dst 0x%08x\n",
18837 				    ip_multirt_ttl, ipha->ipha_ttl,
18838 				    ntohl(ire->ire_addr)));
18839 				ipha->ipha_ttl = ip_multirt_ttl;
18840 			}
18841 			/*
18842 			 * We look at this point if there are pending
18843 			 * unresolved routes. ire_multirt_resolvable()
18844 			 * checks in O(n) that all IRE_OFFSUBNET ire
18845 			 * entries for the packet's destination and
18846 			 * flagged RTF_MULTIRT are currently resolved.
18847 			 * If some remain unresolved, we make a copy
18848 			 * of the current message. It will be used
18849 			 * to initiate additional route resolutions.
18850 			 */
18851 			multirt_need_resolve =
18852 			    ire_multirt_need_resolve(ire->ire_addr,
18853 			    MBLK_GETLABEL(first_mp));
18854 			ip2dbg(("ip_wput[TCP]: ire %p, "
18855 			    "multirt_need_resolve %d, first_mp %p\n",
18856 			    (void *)ire, multirt_need_resolve,
18857 			    (void *)first_mp));
18858 			if (multirt_need_resolve) {
18859 				copy_mp = copymsg(first_mp);
18860 				if (copy_mp != NULL) {
18861 					MULTIRT_DEBUG_TAG(copy_mp);
18862 				}
18863 			}
18864 		}
18865 
18866 		ip_wput_ire(q, first_mp, ire, connp, caller);
18867 
18868 		/*
18869 		 * Try to resolve another multiroute if
18870 		 * ire_multirt_need_resolve() deemed it necessary.
18871 		 */
18872 		if (copy_mp != NULL) {
18873 			ip_newroute(q, copy_mp, dst, NULL, connp);
18874 		}
18875 		if (need_decref)
18876 			CONN_DEC_REF(connp);
18877 		return;
18878 	}
18879 
18880 	/*
18881 	 * Access to conn_ire_cache. (protected by conn_lock)
18882 	 *
18883 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18884 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18885 	 * send a packet or two with the IRE_CACHE that is going away.
18886 	 * Access to the ire requires an ire refhold on the ire prior to
18887 	 * its use since an interface unplumb thread may delete the cached
18888 	 * ire and release the refhold at any time.
18889 	 *
18890 	 * Caching an ire in the conn_ire_cache
18891 	 *
18892 	 * o Caching an ire pointer in the conn requires a strict check for
18893 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18894 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18895 	 * in the conn is done after making sure under the bucket lock that the
18896 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18897 	 * caching an ire after the unplumb thread has cleaned up the conn.
18898 	 * If the conn does not send a packet subsequently the unplumb thread
18899 	 * will be hanging waiting for the ire count to drop to zero.
18900 	 *
18901 	 * o We also need to atomically test for a null conn_ire_cache and
18902 	 * set the conn_ire_cache under the the protection of the conn_lock
18903 	 * to avoid races among concurrent threads trying to simultaneously
18904 	 * cache an ire in the conn_ire_cache.
18905 	 */
18906 	mutex_enter(&connp->conn_lock);
18907 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18908 
18909 	if (ire != NULL && ire->ire_addr == dst &&
18910 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18911 
18912 		IRE_REFHOLD(ire);
18913 		mutex_exit(&connp->conn_lock);
18914 
18915 	} else {
18916 		boolean_t cached = B_FALSE;
18917 		connp->conn_ire_cache = NULL;
18918 		mutex_exit(&connp->conn_lock);
18919 		/* Release the old ire */
18920 		if (ire != NULL && sctp_ire == NULL)
18921 			IRE_REFRELE_NOTR(ire);
18922 
18923 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18924 		if (ire == NULL)
18925 			goto noirefound;
18926 		IRE_REFHOLD_NOTR(ire);
18927 
18928 		mutex_enter(&connp->conn_lock);
18929 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18930 		    connp->conn_ire_cache == NULL) {
18931 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18932 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18933 				connp->conn_ire_cache = ire;
18934 				cached = B_TRUE;
18935 			}
18936 			rw_exit(&ire->ire_bucket->irb_lock);
18937 		}
18938 		mutex_exit(&connp->conn_lock);
18939 
18940 		/*
18941 		 * We can continue to use the ire but since it was
18942 		 * not cached, we should drop the extra reference.
18943 		 */
18944 		if (!cached)
18945 			IRE_REFRELE_NOTR(ire);
18946 	}
18947 
18948 
18949 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18950 	    "ip_wput_end: q %p (%S)", q, "end");
18951 
18952 	/*
18953 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18954 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18955 	 */
18956 	if (ire->ire_flags & RTF_MULTIRT) {
18957 
18958 		/*
18959 		 * Force the TTL of multirouted packets if required.
18960 		 * The TTL of such packets is bounded by the
18961 		 * ip_multirt_ttl ndd variable.
18962 		 */
18963 		if ((ip_multirt_ttl > 0) &&
18964 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18965 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18966 			    "(was %d), dst 0x%08x\n",
18967 			    ip_multirt_ttl, ipha->ipha_ttl,
18968 			    ntohl(ire->ire_addr)));
18969 			ipha->ipha_ttl = ip_multirt_ttl;
18970 		}
18971 
18972 		/*
18973 		 * At this point, we check to see if there are any pending
18974 		 * unresolved routes. ire_multirt_resolvable()
18975 		 * checks in O(n) that all IRE_OFFSUBNET ire
18976 		 * entries for the packet's destination and
18977 		 * flagged RTF_MULTIRT are currently resolved.
18978 		 * If some remain unresolved, we make a copy
18979 		 * of the current message. It will be used
18980 		 * to initiate additional route resolutions.
18981 		 */
18982 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
18983 		    MBLK_GETLABEL(first_mp));
18984 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18985 		    "multirt_need_resolve %d, first_mp %p\n",
18986 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18987 		if (multirt_need_resolve) {
18988 			copy_mp = copymsg(first_mp);
18989 			if (copy_mp != NULL) {
18990 				MULTIRT_DEBUG_TAG(copy_mp);
18991 			}
18992 		}
18993 	}
18994 
18995 	ip_wput_ire(q, first_mp, ire, connp, caller);
18996 
18997 	/*
18998 	 * Try to resolve another multiroute if
18999 	 * ire_multirt_resolvable() deemed it necessary
19000 	 */
19001 	if (copy_mp != NULL) {
19002 		ip_newroute(q, copy_mp, dst, NULL, connp);
19003 	}
19004 	if (need_decref)
19005 		CONN_DEC_REF(connp);
19006 	return;
19007 
19008 qnext:
19009 	/*
19010 	 * Upper Level Protocols pass down complete IP datagrams
19011 	 * as M_DATA messages.	Everything else is a sideshow.
19012 	 *
19013 	 * 1) We could be re-entering ip_wput because of ip_neworute
19014 	 *    in which case we could have a IPSEC_OUT message. We
19015 	 *    need to pass through ip_wput like other datagrams and
19016 	 *    hence cannot branch to ip_wput_nondata.
19017 	 *
19018 	 * 2) ARP, AH, ESP, and other clients who are on the module
19019 	 *    instance of IP stream, give us something to deal with.
19020 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19021 	 *
19022 	 * 3) ICMP replies also could come here.
19023 	 */
19024 	if (DB_TYPE(mp) != M_DATA) {
19025 	    notdata:
19026 		if (DB_TYPE(mp) == M_CTL) {
19027 			/*
19028 			 * M_CTL messages are used by ARP, AH and ESP to
19029 			 * communicate with IP. We deal with IPSEC_IN and
19030 			 * IPSEC_OUT here. ip_wput_nondata handles other
19031 			 * cases.
19032 			 */
19033 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19034 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19035 				first_mp = mp->b_cont;
19036 				first_mp->b_flag &= ~MSGHASREF;
19037 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19038 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19039 				CONN_DEC_REF(connp);
19040 				connp = NULL;
19041 			}
19042 			if (ii->ipsec_info_type == IPSEC_IN) {
19043 				/*
19044 				 * Either this message goes back to
19045 				 * IPSEC for further processing or to
19046 				 * ULP after policy checks.
19047 				 */
19048 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19049 				return;
19050 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19051 				io = (ipsec_out_t *)ii;
19052 				if (io->ipsec_out_proc_begin) {
19053 					/*
19054 					 * IPSEC processing has already started.
19055 					 * Complete it.
19056 					 * IPQoS notes: We don't care what is
19057 					 * in ipsec_out_ill_index since this
19058 					 * won't be processed for IPQoS policies
19059 					 * in ipsec_out_process.
19060 					 */
19061 					ipsec_out_process(q, mp, NULL,
19062 					    io->ipsec_out_ill_index);
19063 					return;
19064 				} else {
19065 					connp = (q->q_next != NULL) ?
19066 					    NULL : Q_TO_CONN(q);
19067 					first_mp = mp;
19068 					mp = mp->b_cont;
19069 					mctl_present = B_TRUE;
19070 				}
19071 				zoneid = io->ipsec_out_zoneid;
19072 				ASSERT(zoneid != ALL_ZONES);
19073 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19074 				/*
19075 				 * It's an IPsec control message requesting
19076 				 * an SADB update to be sent to the IPsec
19077 				 * hardware acceleration capable ills.
19078 				 */
19079 				ipsec_ctl_t *ipsec_ctl =
19080 				    (ipsec_ctl_t *)mp->b_rptr;
19081 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19082 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19083 				mblk_t *cmp = mp->b_cont;
19084 
19085 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19086 				ASSERT(cmp != NULL);
19087 
19088 				freeb(mp);
19089 				ill_ipsec_capab_send_all(satype, cmp, sa);
19090 				return;
19091 			} else {
19092 				/*
19093 				 * This must be ARP or special TSOL signaling.
19094 				 */
19095 				ip_wput_nondata(NULL, q, mp, NULL);
19096 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19097 				    "ip_wput_end: q %p (%S)", q, "nondata");
19098 				return;
19099 			}
19100 		} else {
19101 			/*
19102 			 * This must be non-(ARP/AH/ESP) messages.
19103 			 */
19104 			ASSERT(!need_decref);
19105 			ip_wput_nondata(NULL, q, mp, NULL);
19106 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19107 			    "ip_wput_end: q %p (%S)", q, "nondata");
19108 			return;
19109 		}
19110 	} else {
19111 		first_mp = mp;
19112 		mctl_present = B_FALSE;
19113 	}
19114 
19115 	ASSERT(first_mp != NULL);
19116 	/*
19117 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19118 	 * to make sure that this packet goes out on the same interface it
19119 	 * came in. We handle that here.
19120 	 */
19121 	if (mctl_present) {
19122 		uint_t ifindex;
19123 
19124 		io = (ipsec_out_t *)first_mp->b_rptr;
19125 		if (io->ipsec_out_attach_if ||
19126 		    io->ipsec_out_xmit_if ||
19127 		    io->ipsec_out_ip_nexthop) {
19128 			ill_t	*ill;
19129 
19130 			/*
19131 			 * We may have lost the conn context if we are
19132 			 * coming here from ip_newroute(). Copy the
19133 			 * nexthop information.
19134 			 */
19135 			if (io->ipsec_out_ip_nexthop) {
19136 				ip_nexthop = B_TRUE;
19137 				nexthop_addr = io->ipsec_out_nexthop_addr;
19138 
19139 				ipha = (ipha_t *)mp->b_rptr;
19140 				dst = ipha->ipha_dst;
19141 				goto send_from_ill;
19142 			} else {
19143 				ASSERT(io->ipsec_out_ill_index != 0);
19144 				ifindex = io->ipsec_out_ill_index;
19145 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19146 				    NULL, NULL, NULL, NULL);
19147 				/*
19148 				 * ipsec_out_xmit_if bit is used to tell
19149 				 * ip_wput to use the ill to send outgoing data
19150 				 * as we have no conn when data comes from ICMP
19151 				 * error msg routines. Currently this feature is
19152 				 * only used by ip_mrtun_forward routine.
19153 				 */
19154 				if (io->ipsec_out_xmit_if) {
19155 					xmit_ill = ill;
19156 					if (xmit_ill == NULL) {
19157 						ip1dbg(("ip_output:bad ifindex "
19158 						    "for xmit_ill %d\n",
19159 						    ifindex));
19160 						freemsg(first_mp);
19161 						BUMP_MIB(&ip_mib,
19162 						    ipOutDiscards);
19163 						ASSERT(!need_decref);
19164 						return;
19165 					}
19166 					/* Free up the ipsec_out_t mblk */
19167 					ASSERT(first_mp->b_cont == mp);
19168 					first_mp->b_cont = NULL;
19169 					freeb(first_mp);
19170 					/* Just send the IP header+ICMP+data */
19171 					first_mp = mp;
19172 					ipha = (ipha_t *)mp->b_rptr;
19173 					dst = ipha->ipha_dst;
19174 					goto send_from_ill;
19175 				} else {
19176 					attach_ill = ill;
19177 				}
19178 
19179 				if (attach_ill == NULL) {
19180 					ASSERT(xmit_ill == NULL);
19181 					ip1dbg(("ip_output: bad ifindex for "
19182 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19183 					    ifindex));
19184 					freemsg(first_mp);
19185 					BUMP_MIB(&ip_mib, ipOutDiscards);
19186 					ASSERT(!need_decref);
19187 					return;
19188 				}
19189 			}
19190 		}
19191 	}
19192 
19193 	ASSERT(xmit_ill == NULL);
19194 
19195 	/* We have a complete IP datagram heading outbound. */
19196 	ipha = (ipha_t *)mp->b_rptr;
19197 
19198 #ifndef SPEED_BEFORE_SAFETY
19199 	/*
19200 	 * Make sure we have a full-word aligned message and that at least
19201 	 * a simple IP header is accessible in the first message.  If not,
19202 	 * try a pullup.
19203 	 */
19204 	if (!OK_32PTR(rptr) ||
19205 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19206 	    hdrtoosmall:
19207 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19208 			BUMP_MIB(&ip_mib, ipOutDiscards);
19209 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19210 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19211 			if (first_mp == NULL)
19212 				first_mp = mp;
19213 			goto drop_pkt;
19214 		}
19215 
19216 		/* This function assumes that mp points to an IPv4 packet. */
19217 		if (is_system_labeled() && q->q_next == NULL &&
19218 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19219 		    !connp->conn_ulp_labeled) {
19220 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19221 			    &adjust, connp->conn_mac_exempt);
19222 			ipha = (ipha_t *)mp->b_rptr;
19223 			if (first_mp != NULL)
19224 				first_mp->b_cont = mp;
19225 			if (err != 0) {
19226 				if (first_mp == NULL)
19227 					first_mp = mp;
19228 				if (err == EINVAL)
19229 					goto icmp_parameter_problem;
19230 				ip2dbg(("ip_wput: label check failed (%d)\n",
19231 				    err));
19232 				goto drop_pkt;
19233 			}
19234 			iplen = ntohs(ipha->ipha_length) + adjust;
19235 			ipha->ipha_length = htons(iplen);
19236 		}
19237 
19238 		ipha = (ipha_t *)mp->b_rptr;
19239 		if (first_mp == NULL) {
19240 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19241 			/*
19242 			 * If we got here because of "goto hdrtoosmall"
19243 			 * We need to attach a IPSEC_OUT.
19244 			 */
19245 			if (connp->conn_out_enforce_policy) {
19246 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19247 				    NULL, ipha->ipha_protocol)) == NULL)) {
19248 					if (need_decref)
19249 						CONN_DEC_REF(connp);
19250 					return;
19251 				} else {
19252 					ASSERT(mp->b_datap->db_type == M_CTL);
19253 					first_mp = mp;
19254 					mp = mp->b_cont;
19255 					mctl_present = B_TRUE;
19256 				}
19257 			} else {
19258 				first_mp = mp;
19259 				mctl_present = B_FALSE;
19260 			}
19261 		}
19262 	}
19263 #endif
19264 
19265 	/* Most of the code below is written for speed, not readability */
19266 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19267 
19268 	/*
19269 	 * If ip_newroute() fails, we're going to need a full
19270 	 * header for the icmp wraparound.
19271 	 */
19272 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19273 		uint_t	v_hlen;
19274 	    version_hdrlen_check:
19275 		ASSERT(first_mp != NULL);
19276 		v_hlen = V_HLEN;
19277 		/*
19278 		 * siphon off IPv6 packets coming down from transport
19279 		 * layer modules here.
19280 		 * Note: high-order bit carries NUD reachability confirmation
19281 		 */
19282 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19283 			/*
19284 			 * XXX implement a IPv4 and IPv6 packet counter per
19285 			 * conn and switch when ratio exceeds e.g. 10:1
19286 			 */
19287 #ifdef notyet
19288 			if (q->q_next == NULL) /* Avoid ill queue */
19289 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19290 #endif
19291 			BUMP_MIB(&ip_mib, ipOutIPv6);
19292 			ASSERT(xmit_ill == NULL);
19293 			if (attach_ill != NULL)
19294 				ill_refrele(attach_ill);
19295 			if (need_decref)
19296 				mp->b_flag |= MSGHASREF;
19297 			(void) ip_output_v6(connp, first_mp, q, caller);
19298 			return;
19299 		}
19300 
19301 		if ((v_hlen >> 4) != IP_VERSION) {
19302 			BUMP_MIB(&ip_mib, ipOutDiscards);
19303 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19304 			    "ip_wput_end: q %p (%S)", q, "badvers");
19305 			goto drop_pkt;
19306 		}
19307 		/*
19308 		 * Is the header length at least 20 bytes?
19309 		 *
19310 		 * Are there enough bytes accessible in the header?  If
19311 		 * not, try a pullup.
19312 		 */
19313 		v_hlen &= 0xF;
19314 		v_hlen <<= 2;
19315 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19316 			BUMP_MIB(&ip_mib, ipOutDiscards);
19317 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19318 			    "ip_wput_end: q %p (%S)", q, "badlen");
19319 			goto drop_pkt;
19320 		}
19321 		if (v_hlen > (mp->b_wptr - rptr)) {
19322 			if (!pullupmsg(mp, v_hlen)) {
19323 				BUMP_MIB(&ip_mib, ipOutDiscards);
19324 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19325 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19326 				goto drop_pkt;
19327 			}
19328 			ipha = (ipha_t *)mp->b_rptr;
19329 		}
19330 		/*
19331 		 * Move first entry from any source route into ipha_dst and
19332 		 * verify the options
19333 		 */
19334 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19335 			ASSERT(xmit_ill == NULL);
19336 			if (attach_ill != NULL)
19337 				ill_refrele(attach_ill);
19338 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19339 			    "ip_wput_end: q %p (%S)", q, "badopts");
19340 			if (need_decref)
19341 				CONN_DEC_REF(connp);
19342 			return;
19343 		}
19344 	}
19345 	dst = ipha->ipha_dst;
19346 
19347 	/*
19348 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19349 	 * we have to run the packet through ip_newroute which will take
19350 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19351 	 * a resolver, or assigning a default gateway, etc.
19352 	 */
19353 	if (CLASSD(dst)) {
19354 		ipif_t	*ipif;
19355 		uint32_t setsrc = 0;
19356 
19357 	    multicast:
19358 		ASSERT(first_mp != NULL);
19359 		ASSERT(xmit_ill == NULL);
19360 		ip2dbg(("ip_wput: CLASSD\n"));
19361 		if (connp == NULL) {
19362 			/*
19363 			 * Use the first good ipif on the ill.
19364 			 * XXX Should this ever happen? (Appears
19365 			 * to show up with just ppp and no ethernet due
19366 			 * to in.rdisc.)
19367 			 * However, ire_send should be able to
19368 			 * call ip_wput_ire directly.
19369 			 *
19370 			 * XXX Also, this can happen for ICMP and other packets
19371 			 * with multicast source addresses.  Perhaps we should
19372 			 * fix things so that we drop the packet in question,
19373 			 * but for now, just run with it.
19374 			 */
19375 			ill_t *ill = (ill_t *)q->q_ptr;
19376 
19377 			/*
19378 			 * Don't honor attach_if for this case. If ill
19379 			 * is part of the group, ipif could belong to
19380 			 * any ill and we cannot maintain attach_ill
19381 			 * and ipif_ill same anymore and the assert
19382 			 * below would fail.
19383 			 */
19384 			if (mctl_present) {
19385 				io->ipsec_out_ill_index = 0;
19386 				io->ipsec_out_attach_if = B_FALSE;
19387 				ASSERT(attach_ill != NULL);
19388 				ill_refrele(attach_ill);
19389 				attach_ill = NULL;
19390 			}
19391 
19392 			ASSERT(attach_ill == NULL);
19393 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19394 			if (ipif == NULL) {
19395 				if (need_decref)
19396 					CONN_DEC_REF(connp);
19397 				freemsg(first_mp);
19398 				return;
19399 			}
19400 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
19401 			    ntohl(dst), ill->ill_name));
19402 		} else {
19403 			/*
19404 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
19405 			 * IP_XMIT_IF is honoured.
19406 			 * Block comment above this function explains the
19407 			 * locking mechanism used here
19408 			 */
19409 			xmit_ill = conn_get_held_ill(connp,
19410 			    &connp->conn_xmit_if_ill, &err);
19411 			if (err == ILL_LOOKUP_FAILED) {
19412 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
19413 				goto drop_pkt;
19414 			}
19415 			if (xmit_ill == NULL) {
19416 				ipif = conn_get_held_ipif(connp,
19417 				    &connp->conn_multicast_ipif, &err);
19418 				if (err == IPIF_LOOKUP_FAILED) {
19419 					ip1dbg(("ip_wput: No ipif for "
19420 					    "multicast\n"));
19421 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19422 					goto drop_pkt;
19423 				}
19424 			}
19425 			if (xmit_ill != NULL) {
19426 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19427 				if (ipif == NULL) {
19428 					ip1dbg(("ip_wput: No ipif for "
19429 					    "IP_XMIT_IF\n"));
19430 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19431 					goto drop_pkt;
19432 				}
19433 			} else if (ipif == NULL || ipif->ipif_isv6) {
19434 				/*
19435 				 * We must do this ipif determination here
19436 				 * else we could pass through ip_newroute
19437 				 * and come back here without the conn context.
19438 				 *
19439 				 * Note: we do late binding i.e. we bind to
19440 				 * the interface when the first packet is sent.
19441 				 * For performance reasons we do not rebind on
19442 				 * each packet but keep the binding until the
19443 				 * next IP_MULTICAST_IF option.
19444 				 *
19445 				 * conn_multicast_{ipif,ill} are shared between
19446 				 * IPv4 and IPv6 and AF_INET6 sockets can
19447 				 * send both IPv4 and IPv6 packets. Hence
19448 				 * we have to check that "isv6" matches above.
19449 				 */
19450 				if (ipif != NULL)
19451 					ipif_refrele(ipif);
19452 				ipif = ipif_lookup_group(dst, zoneid);
19453 				if (ipif == NULL) {
19454 					ip1dbg(("ip_wput: No ipif for "
19455 					    "multicast\n"));
19456 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19457 					goto drop_pkt;
19458 				}
19459 				err = conn_set_held_ipif(connp,
19460 				    &connp->conn_multicast_ipif, ipif);
19461 				if (err == IPIF_LOOKUP_FAILED) {
19462 					ipif_refrele(ipif);
19463 					ip1dbg(("ip_wput: No ipif for "
19464 					    "multicast\n"));
19465 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19466 					goto drop_pkt;
19467 				}
19468 			}
19469 		}
19470 		ASSERT(!ipif->ipif_isv6);
19471 		/*
19472 		 * As we may lose the conn by the time we reach ip_wput_ire,
19473 		 * we copy conn_multicast_loop and conn_dontroute on to an
19474 		 * ipsec_out. In case if this datagram goes out secure,
19475 		 * we need the ill_index also. Copy that also into the
19476 		 * ipsec_out.
19477 		 */
19478 		if (mctl_present) {
19479 			io = (ipsec_out_t *)first_mp->b_rptr;
19480 			ASSERT(first_mp->b_datap->db_type == M_CTL);
19481 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
19482 		} else {
19483 			ASSERT(mp == first_mp);
19484 			if ((first_mp = allocb(sizeof (ipsec_info_t),
19485 			    BPRI_HI)) == NULL) {
19486 				ipif_refrele(ipif);
19487 				first_mp = mp;
19488 				goto drop_pkt;
19489 			}
19490 			first_mp->b_datap->db_type = M_CTL;
19491 			first_mp->b_wptr += sizeof (ipsec_info_t);
19492 			/* ipsec_out_secure is B_FALSE now */
19493 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
19494 			io = (ipsec_out_t *)first_mp->b_rptr;
19495 			io->ipsec_out_type = IPSEC_OUT;
19496 			io->ipsec_out_len = sizeof (ipsec_out_t);
19497 			io->ipsec_out_use_global_policy = B_TRUE;
19498 			first_mp->b_cont = mp;
19499 			mctl_present = B_TRUE;
19500 		}
19501 		if (attach_ill != NULL) {
19502 			ASSERT(attach_ill == ipif->ipif_ill);
19503 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19504 
19505 			/*
19506 			 * Check if we need an ire that will not be
19507 			 * looked up by anybody else i.e. HIDDEN.
19508 			 */
19509 			if (ill_is_probeonly(attach_ill)) {
19510 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19511 			}
19512 			io->ipsec_out_ill_index =
19513 			    attach_ill->ill_phyint->phyint_ifindex;
19514 			io->ipsec_out_attach_if = B_TRUE;
19515 		} else {
19516 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
19517 			io->ipsec_out_ill_index =
19518 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
19519 		}
19520 		if (connp != NULL) {
19521 			io->ipsec_out_multicast_loop =
19522 			    connp->conn_multicast_loop;
19523 			io->ipsec_out_dontroute = connp->conn_dontroute;
19524 			io->ipsec_out_zoneid = connp->conn_zoneid;
19525 		}
19526 		/*
19527 		 * If the application uses IP_MULTICAST_IF with
19528 		 * different logical addresses of the same ILL, we
19529 		 * need to make sure that the soruce address of
19530 		 * the packet matches the logical IP address used
19531 		 * in the option. We do it by initializing ipha_src
19532 		 * here. This should keep IPSEC also happy as
19533 		 * when we return from IPSEC processing, we don't
19534 		 * have to worry about getting the right address on
19535 		 * the packet. Thus it is sufficient to look for
19536 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
19537 		 * MATCH_IRE_IPIF.
19538 		 *
19539 		 * NOTE : We need to do it for non-secure case also as
19540 		 * this might go out secure if there is a global policy
19541 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
19542 		 * address, the source should be initialized already and
19543 		 * hence we won't be initializing here.
19544 		 *
19545 		 * As we do not have the ire yet, it is possible that
19546 		 * we set the source address here and then later discover
19547 		 * that the ire implies the source address to be assigned
19548 		 * through the RTF_SETSRC flag.
19549 		 * In that case, the setsrc variable will remind us
19550 		 * that overwritting the source address by the one
19551 		 * of the RTF_SETSRC-flagged ire is allowed.
19552 		 */
19553 		if (ipha->ipha_src == INADDR_ANY &&
19554 		    (connp == NULL || !connp->conn_unspec_src)) {
19555 			ipha->ipha_src = ipif->ipif_src_addr;
19556 			setsrc = RTF_SETSRC;
19557 		}
19558 		/*
19559 		 * Find an IRE which matches the destination and the outgoing
19560 		 * queue (i.e. the outgoing interface.)
19561 		 * For loopback use a unicast IP address for
19562 		 * the ire lookup.
19563 		 */
19564 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
19565 		    PHYI_LOOPBACK) {
19566 			dst = ipif->ipif_lcl_addr;
19567 		}
19568 		/*
19569 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
19570 		 * We don't need to lookup ire in ctable as the packet
19571 		 * needs to be sent to the destination through the specified
19572 		 * ill irrespective of ires in the cache table.
19573 		 */
19574 		ire = NULL;
19575 		if (xmit_ill == NULL) {
19576 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
19577 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19578 		}
19579 
19580 		/*
19581 		 * refrele attach_ill as its not needed anymore.
19582 		 */
19583 		if (attach_ill != NULL) {
19584 			ill_refrele(attach_ill);
19585 			attach_ill = NULL;
19586 		}
19587 
19588 		if (ire == NULL) {
19589 			/*
19590 			 * Multicast loopback and multicast forwarding is
19591 			 * done in ip_wput_ire.
19592 			 *
19593 			 * Mark this packet to make it be delivered to
19594 			 * ip_wput_ire after the new ire has been
19595 			 * created.
19596 			 *
19597 			 * The call to ip_newroute_ipif takes into account
19598 			 * the setsrc reminder. In any case, we take care
19599 			 * of the RTF_MULTIRT flag.
19600 			 */
19601 			mp->b_prev = mp->b_next = NULL;
19602 			if (xmit_ill == NULL ||
19603 			    xmit_ill->ill_ipif_up_count > 0) {
19604 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
19605 				    setsrc | RTF_MULTIRT);
19606 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19607 				    "ip_wput_end: q %p (%S)", q, "noire");
19608 			} else {
19609 				freemsg(first_mp);
19610 			}
19611 			ipif_refrele(ipif);
19612 			if (xmit_ill != NULL)
19613 				ill_refrele(xmit_ill);
19614 			if (need_decref)
19615 				CONN_DEC_REF(connp);
19616 			return;
19617 		}
19618 
19619 		ipif_refrele(ipif);
19620 		ipif = NULL;
19621 		ASSERT(xmit_ill == NULL);
19622 
19623 		/*
19624 		 * Honor the RTF_SETSRC flag for multicast packets,
19625 		 * if allowed by the setsrc reminder.
19626 		 */
19627 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
19628 			ipha->ipha_src = ire->ire_src_addr;
19629 		}
19630 
19631 		/*
19632 		 * Unconditionally force the TTL to 1 for
19633 		 * multirouted multicast packets:
19634 		 * multirouted multicast should not cross
19635 		 * multicast routers.
19636 		 */
19637 		if (ire->ire_flags & RTF_MULTIRT) {
19638 			if (ipha->ipha_ttl > 1) {
19639 				ip2dbg(("ip_wput: forcing multicast "
19640 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
19641 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
19642 				ipha->ipha_ttl = 1;
19643 			}
19644 		}
19645 	} else {
19646 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19647 		if ((ire != NULL) && (ire->ire_type &
19648 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
19649 			ignore_dontroute = B_TRUE;
19650 			ignore_nexthop = B_TRUE;
19651 		}
19652 		if (ire != NULL) {
19653 			ire_refrele(ire);
19654 			ire = NULL;
19655 		}
19656 		/*
19657 		 * Guard against coming in from arp in which case conn is NULL.
19658 		 * Also guard against non M_DATA with dontroute set but
19659 		 * destined to local, loopback or broadcast addresses.
19660 		 */
19661 		if (connp != NULL && connp->conn_dontroute &&
19662 		    !ignore_dontroute) {
19663 dontroute:
19664 			/*
19665 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
19666 			 * routing protocols from seeing false direct
19667 			 * connectivity.
19668 			 */
19669 			ipha->ipha_ttl = 1;
19670 			/*
19671 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
19672 			 * along with SO_DONTROUTE, higher precedence is
19673 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
19674 			 */
19675 			if (connp->conn_xmit_if_ill == NULL) {
19676 				/* If suitable ipif not found, drop packet */
19677 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
19678 				if (dst_ipif == NULL) {
19679 					ip1dbg(("ip_wput: no route for "
19680 					    "dst using SO_DONTROUTE\n"));
19681 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19682 					mp->b_prev = mp->b_next = NULL;
19683 					if (first_mp == NULL)
19684 						first_mp = mp;
19685 					goto drop_pkt;
19686 				} else {
19687 					/*
19688 					 * If suitable ipif has been found, set
19689 					 * xmit_ill to the corresponding
19690 					 * ipif_ill because we'll be following
19691 					 * the IP_XMIT_IF logic.
19692 					 */
19693 					ASSERT(xmit_ill == NULL);
19694 					xmit_ill = dst_ipif->ipif_ill;
19695 					mutex_enter(&xmit_ill->ill_lock);
19696 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
19697 						mutex_exit(&xmit_ill->ill_lock);
19698 						xmit_ill = NULL;
19699 						ipif_refrele(dst_ipif);
19700 						ip1dbg(("ip_wput: no route for"
19701 						    " dst using"
19702 						    " SO_DONTROUTE\n"));
19703 						BUMP_MIB(&ip_mib,
19704 						    ipOutNoRoutes);
19705 						mp->b_prev = mp->b_next = NULL;
19706 						if (first_mp == NULL)
19707 							first_mp = mp;
19708 						goto drop_pkt;
19709 					}
19710 					ill_refhold_locked(xmit_ill);
19711 					mutex_exit(&xmit_ill->ill_lock);
19712 					ipif_refrele(dst_ipif);
19713 				}
19714 			}
19715 
19716 		}
19717 		/*
19718 		 * If we are bound to IPIF_NOFAILOVER address, look for
19719 		 * an IRE_CACHE matching the ill.
19720 		 */
19721 send_from_ill:
19722 		if (attach_ill != NULL) {
19723 			ipif_t	*attach_ipif;
19724 
19725 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19726 
19727 			/*
19728 			 * Check if we need an ire that will not be
19729 			 * looked up by anybody else i.e. HIDDEN.
19730 			 */
19731 			if (ill_is_probeonly(attach_ill)) {
19732 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19733 			}
19734 
19735 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
19736 			if (attach_ipif == NULL) {
19737 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
19738 				goto drop_pkt;
19739 			}
19740 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
19741 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19742 			ipif_refrele(attach_ipif);
19743 		} else if (xmit_ill != NULL || (connp != NULL &&
19744 			    connp->conn_xmit_if_ill != NULL)) {
19745 			/*
19746 			 * Mark this packet as originated locally
19747 			 */
19748 			mp->b_prev = mp->b_next = NULL;
19749 			/*
19750 			 * xmit_ill could be NULL if SO_DONTROUTE
19751 			 * is also set.
19752 			 */
19753 			if (xmit_ill == NULL) {
19754 				xmit_ill = conn_get_held_ill(connp,
19755 				    &connp->conn_xmit_if_ill, &err);
19756 				if (err == ILL_LOOKUP_FAILED) {
19757 					if (need_decref)
19758 						CONN_DEC_REF(connp);
19759 					freemsg(first_mp);
19760 					return;
19761 				}
19762 				if (xmit_ill == NULL) {
19763 					if (connp->conn_dontroute)
19764 						goto dontroute;
19765 					goto send_from_ill;
19766 				}
19767 			}
19768 			/*
19769 			 * could be SO_DONTROUTE case also.
19770 			 * check at least one interface is UP as
19771 			 * spcified by this ILL, and then call
19772 			 * ip_newroute_ipif()
19773 			 */
19774 			if (xmit_ill->ill_ipif_up_count > 0) {
19775 				ipif_t *ipif;
19776 
19777 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19778 				if (ipif != NULL) {
19779 					ip_newroute_ipif(q, first_mp, ipif,
19780 					    dst, connp, 0);
19781 					ipif_refrele(ipif);
19782 					ip1dbg(("ip_wput: ip_unicast_if\n"));
19783 				}
19784 			} else {
19785 				freemsg(first_mp);
19786 			}
19787 			ill_refrele(xmit_ill);
19788 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19789 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
19790 			if (need_decref)
19791 				CONN_DEC_REF(connp);
19792 			return;
19793 		} else if (ip_nexthop || (connp != NULL &&
19794 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
19795 			if (!ip_nexthop) {
19796 				ip_nexthop = B_TRUE;
19797 				nexthop_addr = connp->conn_nexthop_v4;
19798 			}
19799 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
19800 			    MATCH_IRE_GW;
19801 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19802 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
19803 		} else {
19804 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19805 		}
19806 		if (!ire) {
19807 			/*
19808 			 * Make sure we don't load spread if this
19809 			 * is IPIF_NOFAILOVER case.
19810 			 */
19811 			if ((attach_ill != NULL) ||
19812 			    (ip_nexthop && !ignore_nexthop)) {
19813 				if (mctl_present) {
19814 					io = (ipsec_out_t *)first_mp->b_rptr;
19815 					ASSERT(first_mp->b_datap->db_type ==
19816 					    M_CTL);
19817 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19818 				} else {
19819 					ASSERT(mp == first_mp);
19820 					first_mp = allocb(
19821 					    sizeof (ipsec_info_t), BPRI_HI);
19822 					if (first_mp == NULL) {
19823 						first_mp = mp;
19824 						goto drop_pkt;
19825 					}
19826 					first_mp->b_datap->db_type = M_CTL;
19827 					first_mp->b_wptr +=
19828 					    sizeof (ipsec_info_t);
19829 					/* ipsec_out_secure is B_FALSE now */
19830 					bzero(first_mp->b_rptr,
19831 					    sizeof (ipsec_info_t));
19832 					io = (ipsec_out_t *)first_mp->b_rptr;
19833 					io->ipsec_out_type = IPSEC_OUT;
19834 					io->ipsec_out_len =
19835 					    sizeof (ipsec_out_t);
19836 					io->ipsec_out_use_global_policy =
19837 					    B_TRUE;
19838 					first_mp->b_cont = mp;
19839 					mctl_present = B_TRUE;
19840 				}
19841 				if (attach_ill != NULL) {
19842 					io->ipsec_out_ill_index = attach_ill->
19843 					    ill_phyint->phyint_ifindex;
19844 					io->ipsec_out_attach_if = B_TRUE;
19845 				} else {
19846 					io->ipsec_out_ip_nexthop = ip_nexthop;
19847 					io->ipsec_out_nexthop_addr =
19848 					    nexthop_addr;
19849 				}
19850 			}
19851 noirefound:
19852 			/*
19853 			 * Mark this packet as having originated on
19854 			 * this machine.  This will be noted in
19855 			 * ire_add_then_send, which needs to know
19856 			 * whether to run it back through ip_wput or
19857 			 * ip_rput following successful resolution.
19858 			 */
19859 			mp->b_prev = NULL;
19860 			mp->b_next = NULL;
19861 			ip_newroute(q, first_mp, dst, NULL, connp);
19862 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19863 			    "ip_wput_end: q %p (%S)", q, "newroute");
19864 			if (attach_ill != NULL)
19865 				ill_refrele(attach_ill);
19866 			if (xmit_ill != NULL)
19867 				ill_refrele(xmit_ill);
19868 			if (need_decref)
19869 				CONN_DEC_REF(connp);
19870 			return;
19871 		}
19872 	}
19873 
19874 	/* We now know where we are going with it. */
19875 
19876 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19877 	    "ip_wput_end: q %p (%S)", q, "end");
19878 
19879 	/*
19880 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19881 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19882 	 */
19883 	if (ire->ire_flags & RTF_MULTIRT) {
19884 		/*
19885 		 * Force the TTL of multirouted packets if required.
19886 		 * The TTL of such packets is bounded by the
19887 		 * ip_multirt_ttl ndd variable.
19888 		 */
19889 		if ((ip_multirt_ttl > 0) &&
19890 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19891 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19892 			    "(was %d), dst 0x%08x\n",
19893 			    ip_multirt_ttl, ipha->ipha_ttl,
19894 			    ntohl(ire->ire_addr)));
19895 			ipha->ipha_ttl = ip_multirt_ttl;
19896 		}
19897 		/*
19898 		 * At this point, we check to see if there are any pending
19899 		 * unresolved routes. ire_multirt_resolvable()
19900 		 * checks in O(n) that all IRE_OFFSUBNET ire
19901 		 * entries for the packet's destination and
19902 		 * flagged RTF_MULTIRT are currently resolved.
19903 		 * If some remain unresolved, we make a copy
19904 		 * of the current message. It will be used
19905 		 * to initiate additional route resolutions.
19906 		 */
19907 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19908 		    MBLK_GETLABEL(first_mp));
19909 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19910 		    "multirt_need_resolve %d, first_mp %p\n",
19911 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19912 		if (multirt_need_resolve) {
19913 			copy_mp = copymsg(first_mp);
19914 			if (copy_mp != NULL) {
19915 				MULTIRT_DEBUG_TAG(copy_mp);
19916 			}
19917 		}
19918 	}
19919 
19920 	ip_wput_ire(q, first_mp, ire, connp, caller);
19921 	/*
19922 	 * Try to resolve another multiroute if
19923 	 * ire_multirt_resolvable() deemed it necessary.
19924 	 * At this point, we need to distinguish
19925 	 * multicasts from other packets. For multicasts,
19926 	 * we call ip_newroute_ipif() and request that both
19927 	 * multirouting and setsrc flags are checked.
19928 	 */
19929 	if (copy_mp != NULL) {
19930 		if (CLASSD(dst)) {
19931 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19932 			if (ipif) {
19933 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19934 				    RTF_SETSRC | RTF_MULTIRT);
19935 				ipif_refrele(ipif);
19936 			} else {
19937 				MULTIRT_DEBUG_UNTAG(copy_mp);
19938 				freemsg(copy_mp);
19939 				copy_mp = NULL;
19940 			}
19941 		} else {
19942 			ip_newroute(q, copy_mp, dst, NULL, connp);
19943 		}
19944 	}
19945 	if (attach_ill != NULL)
19946 		ill_refrele(attach_ill);
19947 	if (xmit_ill != NULL)
19948 		ill_refrele(xmit_ill);
19949 	if (need_decref)
19950 		CONN_DEC_REF(connp);
19951 	return;
19952 
19953 icmp_parameter_problem:
19954 	/* could not have originated externally */
19955 	ASSERT(mp->b_prev == NULL);
19956 	if (ip_hdr_complete(ipha, zoneid) == 0) {
19957 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
19958 		/* it's the IP header length that's in trouble */
19959 		icmp_param_problem(q, first_mp, 0);
19960 		first_mp = NULL;
19961 	}
19962 
19963 drop_pkt:
19964 	ip1dbg(("ip_wput: dropped packet\n"));
19965 	if (ire != NULL)
19966 		ire_refrele(ire);
19967 	if (need_decref)
19968 		CONN_DEC_REF(connp);
19969 	freemsg(first_mp);
19970 	if (attach_ill != NULL)
19971 		ill_refrele(attach_ill);
19972 	if (xmit_ill != NULL)
19973 		ill_refrele(xmit_ill);
19974 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19975 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19976 }
19977 
19978 void
19979 ip_wput(queue_t *q, mblk_t *mp)
19980 {
19981 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19982 }
19983 
19984 /*
19985  *
19986  * The following rules must be observed when accessing any ipif or ill
19987  * that has been cached in the conn. Typically conn_nofailover_ill,
19988  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19989  *
19990  * Access: The ipif or ill pointed to from the conn can be accessed under
19991  * the protection of the conn_lock or after it has been refheld under the
19992  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
19993  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
19994  * The reason for this is that a concurrent unplumb could actually be
19995  * cleaning up these cached pointers by walking the conns and might have
19996  * finished cleaning up the conn in question. The macros check that an
19997  * unplumb has not yet started on the ipif or ill.
19998  *
19999  * Caching: An ipif or ill pointer may be cached in the conn only after
20000  * making sure that an unplumb has not started. So the caching is done
20001  * while holding both the conn_lock and the ill_lock and after using the
20002  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20003  * flag before starting the cleanup of conns.
20004  *
20005  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20006  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20007  * or a reference to the ipif or a reference to an ire that references the
20008  * ipif. An ipif does not change its ill except for failover/failback. Since
20009  * failover/failback happens only after bringing down the ipif and making sure
20010  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20011  * the above holds.
20012  */
20013 ipif_t *
20014 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20015 {
20016 	ipif_t	*ipif;
20017 	ill_t	*ill;
20018 
20019 	*err = 0;
20020 	rw_enter(&ill_g_lock, RW_READER);
20021 	mutex_enter(&connp->conn_lock);
20022 	ipif = *ipifp;
20023 	if (ipif != NULL) {
20024 		ill = ipif->ipif_ill;
20025 		mutex_enter(&ill->ill_lock);
20026 		if (IPIF_CAN_LOOKUP(ipif)) {
20027 			ipif_refhold_locked(ipif);
20028 			mutex_exit(&ill->ill_lock);
20029 			mutex_exit(&connp->conn_lock);
20030 			rw_exit(&ill_g_lock);
20031 			return (ipif);
20032 		} else {
20033 			*err = IPIF_LOOKUP_FAILED;
20034 		}
20035 		mutex_exit(&ill->ill_lock);
20036 	}
20037 	mutex_exit(&connp->conn_lock);
20038 	rw_exit(&ill_g_lock);
20039 	return (NULL);
20040 }
20041 
20042 ill_t *
20043 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20044 {
20045 	ill_t	*ill;
20046 
20047 	*err = 0;
20048 	mutex_enter(&connp->conn_lock);
20049 	ill = *illp;
20050 	if (ill != NULL) {
20051 		mutex_enter(&ill->ill_lock);
20052 		if (ILL_CAN_LOOKUP(ill)) {
20053 			ill_refhold_locked(ill);
20054 			mutex_exit(&ill->ill_lock);
20055 			mutex_exit(&connp->conn_lock);
20056 			return (ill);
20057 		} else {
20058 			*err = ILL_LOOKUP_FAILED;
20059 		}
20060 		mutex_exit(&ill->ill_lock);
20061 	}
20062 	mutex_exit(&connp->conn_lock);
20063 	return (NULL);
20064 }
20065 
20066 static int
20067 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20068 {
20069 	ill_t	*ill;
20070 
20071 	ill = ipif->ipif_ill;
20072 	mutex_enter(&connp->conn_lock);
20073 	mutex_enter(&ill->ill_lock);
20074 	if (IPIF_CAN_LOOKUP(ipif)) {
20075 		*ipifp = ipif;
20076 		mutex_exit(&ill->ill_lock);
20077 		mutex_exit(&connp->conn_lock);
20078 		return (0);
20079 	}
20080 	mutex_exit(&ill->ill_lock);
20081 	mutex_exit(&connp->conn_lock);
20082 	return (IPIF_LOOKUP_FAILED);
20083 }
20084 
20085 /*
20086  * This is called if the outbound datagram needs fragmentation.
20087  *
20088  * NOTE : This function does not ire_refrele the ire argument passed in.
20089  */
20090 static void
20091 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20092 {
20093 	ipha_t		*ipha;
20094 	mblk_t		*mp;
20095 	uint32_t	v_hlen_tos_len;
20096 	uint32_t	max_frag;
20097 	uint32_t	frag_flag;
20098 	boolean_t	dont_use;
20099 
20100 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20101 		mp = ipsec_mp->b_cont;
20102 	} else {
20103 		mp = ipsec_mp;
20104 	}
20105 
20106 	ipha = (ipha_t *)mp->b_rptr;
20107 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20108 
20109 #ifdef	_BIG_ENDIAN
20110 #define	V_HLEN	(v_hlen_tos_len >> 24)
20111 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20112 #else
20113 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20114 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20115 #endif
20116 
20117 #ifndef SPEED_BEFORE_SAFETY
20118 	/*
20119 	 * Check that ipha_length is consistent with
20120 	 * the mblk length
20121 	 */
20122 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20123 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20124 		    LENGTH, msgdsize(mp)));
20125 		freemsg(ipsec_mp);
20126 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20127 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20128 		    "packet length mismatch");
20129 		return;
20130 	}
20131 #endif
20132 	/*
20133 	 * Don't use frag_flag if pre-built packet or source
20134 	 * routed or if multicast (since multicast packets do not solicit
20135 	 * ICMP "packet too big" messages). Get the values of
20136 	 * max_frag and frag_flag atomically by acquiring the
20137 	 * ire_lock.
20138 	 */
20139 	mutex_enter(&ire->ire_lock);
20140 	max_frag = ire->ire_max_frag;
20141 	frag_flag = ire->ire_frag_flag;
20142 	mutex_exit(&ire->ire_lock);
20143 
20144 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20145 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20146 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20147 
20148 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20149 	    (dont_use ? 0 : frag_flag));
20150 }
20151 
20152 /*
20153  * Used for deciding the MSS size for the upper layer. Thus
20154  * we need to check the outbound policy values in the conn.
20155  */
20156 int
20157 conn_ipsec_length(conn_t *connp)
20158 {
20159 	ipsec_latch_t *ipl;
20160 
20161 	ipl = connp->conn_latch;
20162 	if (ipl == NULL)
20163 		return (0);
20164 
20165 	if (ipl->ipl_out_policy == NULL)
20166 		return (0);
20167 
20168 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20169 }
20170 
20171 /*
20172  * Returns an estimate of the IPSEC headers size. This is used if
20173  * we don't want to call into IPSEC to get the exact size.
20174  */
20175 int
20176 ipsec_out_extra_length(mblk_t *ipsec_mp)
20177 {
20178 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20179 	ipsec_action_t *a;
20180 
20181 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20182 	if (!io->ipsec_out_secure)
20183 		return (0);
20184 
20185 	a = io->ipsec_out_act;
20186 
20187 	if (a == NULL) {
20188 		ASSERT(io->ipsec_out_policy != NULL);
20189 		a = io->ipsec_out_policy->ipsp_act;
20190 	}
20191 	ASSERT(a != NULL);
20192 
20193 	return (a->ipa_ovhd);
20194 }
20195 
20196 /*
20197  * Returns an estimate of the IPSEC headers size. This is used if
20198  * we don't want to call into IPSEC to get the exact size.
20199  */
20200 int
20201 ipsec_in_extra_length(mblk_t *ipsec_mp)
20202 {
20203 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20204 	ipsec_action_t *a;
20205 
20206 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20207 
20208 	a = ii->ipsec_in_action;
20209 	return (a == NULL ? 0 : a->ipa_ovhd);
20210 }
20211 
20212 /*
20213  * If there are any source route options, return the true final
20214  * destination. Otherwise, return the destination.
20215  */
20216 ipaddr_t
20217 ip_get_dst(ipha_t *ipha)
20218 {
20219 	ipoptp_t	opts;
20220 	uchar_t		*opt;
20221 	uint8_t		optval;
20222 	uint8_t		optlen;
20223 	ipaddr_t	dst;
20224 	uint32_t off;
20225 
20226 	dst = ipha->ipha_dst;
20227 
20228 	if (IS_SIMPLE_IPH(ipha))
20229 		return (dst);
20230 
20231 	for (optval = ipoptp_first(&opts, ipha);
20232 	    optval != IPOPT_EOL;
20233 	    optval = ipoptp_next(&opts)) {
20234 		opt = opts.ipoptp_cur;
20235 		optlen = opts.ipoptp_len;
20236 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20237 		switch (optval) {
20238 		case IPOPT_SSRR:
20239 		case IPOPT_LSRR:
20240 			off = opt[IPOPT_OFFSET];
20241 			/*
20242 			 * If one of the conditions is true, it means
20243 			 * end of options and dst already has the right
20244 			 * value.
20245 			 */
20246 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20247 				off = optlen - IP_ADDR_LEN;
20248 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20249 			}
20250 			return (dst);
20251 		default:
20252 			break;
20253 		}
20254 	}
20255 
20256 	return (dst);
20257 }
20258 
20259 mblk_t *
20260 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20261     conn_t *connp, boolean_t unspec_src)
20262 {
20263 	ipsec_out_t	*io;
20264 	mblk_t		*first_mp;
20265 	boolean_t policy_present;
20266 
20267 	first_mp = mp;
20268 	if (mp->b_datap->db_type == M_CTL) {
20269 		io = (ipsec_out_t *)first_mp->b_rptr;
20270 		/*
20271 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20272 		 *
20273 		 * 1) There is per-socket policy (including cached global
20274 		 *    policy).
20275 		 * 2) There is no per-socket policy, but it is
20276 		 *    a multicast packet that needs to go out
20277 		 *    on a specific interface. This is the case
20278 		 *    where (ip_wput and ip_wput_multicast) attaches
20279 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20280 		 *
20281 		 * In case (2) we check with global policy to
20282 		 * see if there is a match and set the ill_index
20283 		 * appropriately so that we can lookup the ire
20284 		 * properly in ip_wput_ipsec_out.
20285 		 */
20286 
20287 		/*
20288 		 * ipsec_out_use_global_policy is set to B_FALSE
20289 		 * in ipsec_in_to_out(). Refer to that function for
20290 		 * details.
20291 		 */
20292 		if ((io->ipsec_out_latch == NULL) &&
20293 		    (io->ipsec_out_use_global_policy)) {
20294 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20295 			    ire, connp, unspec_src));
20296 		}
20297 		if (!io->ipsec_out_secure) {
20298 			/*
20299 			 * If this is not a secure packet, drop
20300 			 * the IPSEC_OUT mp and treat it as a clear
20301 			 * packet. This happens when we are sending
20302 			 * a ICMP reply back to a clear packet. See
20303 			 * ipsec_in_to_out() for details.
20304 			 */
20305 			mp = first_mp->b_cont;
20306 			freeb(first_mp);
20307 		}
20308 		return (mp);
20309 	}
20310 	/*
20311 	 * See whether we need to attach a global policy here. We
20312 	 * don't depend on the conn (as it could be null) for deciding
20313 	 * what policy this datagram should go through because it
20314 	 * should have happened in ip_wput if there was some
20315 	 * policy. This normally happens for connections which are not
20316 	 * fully bound preventing us from caching policies in
20317 	 * ip_bind. Packets coming from the TCP listener/global queue
20318 	 * - which are non-hard_bound - could also be affected by
20319 	 * applying policy here.
20320 	 *
20321 	 * If this packet is coming from tcp global queue or listener,
20322 	 * we will be applying policy here.  This may not be *right*
20323 	 * if these packets are coming from the detached connection as
20324 	 * it could have gone in clear before. This happens only if a
20325 	 * TCP connection started when there is no policy and somebody
20326 	 * added policy before it became detached. Thus packets of the
20327 	 * detached connection could go out secure and the other end
20328 	 * would drop it because it will be expecting in clear. The
20329 	 * converse is not true i.e if somebody starts a TCP
20330 	 * connection and deletes the policy, all the packets will
20331 	 * still go out with the policy that existed before deleting
20332 	 * because ip_unbind sends up policy information which is used
20333 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20334 	 * TCP to attach a dummy IPSEC_OUT and set
20335 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20336 	 * affect performance for normal cases, we are not doing it.
20337 	 * Thus, set policy before starting any TCP connections.
20338 	 *
20339 	 * NOTE - We might apply policy even for a hard bound connection
20340 	 * - for which we cached policy in ip_bind - if somebody added
20341 	 * global policy after we inherited the policy in ip_bind.
20342 	 * This means that the packets that were going out in clear
20343 	 * previously would start going secure and hence get dropped
20344 	 * on the other side. To fix this, TCP attaches a dummy
20345 	 * ipsec_out and make sure that we don't apply global policy.
20346 	 */
20347 	if (ipha != NULL)
20348 		policy_present = ipsec_outbound_v4_policy_present;
20349 	else
20350 		policy_present = ipsec_outbound_v6_policy_present;
20351 	if (!policy_present)
20352 		return (mp);
20353 
20354 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20355 }
20356 
20357 ire_t *
20358 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20359 {
20360 	ipaddr_t addr;
20361 	ire_t *save_ire;
20362 	irb_t *irb;
20363 	ill_group_t *illgrp;
20364 	int	err;
20365 
20366 	save_ire = ire;
20367 	addr = ire->ire_addr;
20368 
20369 	ASSERT(ire->ire_type == IRE_BROADCAST);
20370 
20371 	illgrp = connp->conn_outgoing_ill->ill_group;
20372 	if (illgrp == NULL) {
20373 		*conn_outgoing_ill = conn_get_held_ill(connp,
20374 		    &connp->conn_outgoing_ill, &err);
20375 		if (err == ILL_LOOKUP_FAILED) {
20376 			ire_refrele(save_ire);
20377 			return (NULL);
20378 		}
20379 		return (save_ire);
20380 	}
20381 	/*
20382 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20383 	 * If it is part of the group, we need to send on the ire
20384 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20385 	 * to this group. This is okay as IP_BOUND_IF really means
20386 	 * any ill in the group. We depend on the fact that the
20387 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20388 	 * if such an ire exists. This is possible only if you have
20389 	 * at least one ill in the group that has not failed.
20390 	 *
20391 	 * First get to the ire that matches the address and group.
20392 	 *
20393 	 * We don't look for an ire with a matching zoneid because a given zone
20394 	 * won't always have broadcast ires on all ills in the group.
20395 	 */
20396 	irb = ire->ire_bucket;
20397 	rw_enter(&irb->irb_lock, RW_READER);
20398 	if (ire->ire_marks & IRE_MARK_NORECV) {
20399 		/*
20400 		 * If the current zone only has an ire broadcast for this
20401 		 * address marked NORECV, the ire we want is ahead in the
20402 		 * bucket, so we look it up deliberately ignoring the zoneid.
20403 		 */
20404 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
20405 			if (ire->ire_addr != addr)
20406 				continue;
20407 			/* skip over deleted ires */
20408 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
20409 				continue;
20410 		}
20411 	}
20412 	while (ire != NULL) {
20413 		/*
20414 		 * If a new interface is coming up, we could end up
20415 		 * seeing the loopback ire and the non-loopback ire
20416 		 * may not have been added yet. So check for ire_stq
20417 		 */
20418 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
20419 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
20420 			break;
20421 		}
20422 		ire = ire->ire_next;
20423 	}
20424 	if (ire != NULL && ire->ire_addr == addr &&
20425 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
20426 		IRE_REFHOLD(ire);
20427 		rw_exit(&irb->irb_lock);
20428 		ire_refrele(save_ire);
20429 		*conn_outgoing_ill = ire_to_ill(ire);
20430 		/*
20431 		 * Refhold the ill to make the conn_outgoing_ill
20432 		 * independent of the ire. ip_wput_ire goes in a loop
20433 		 * and may refrele the ire. Since we have an ire at this
20434 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
20435 		 */
20436 		ill_refhold(*conn_outgoing_ill);
20437 		return (ire);
20438 	}
20439 	rw_exit(&irb->irb_lock);
20440 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
20441 	/*
20442 	 * If we can't find a suitable ire, return the original ire.
20443 	 */
20444 	return (save_ire);
20445 }
20446 
20447 /*
20448  * This function does the ire_refrele of the ire passed in as the
20449  * argument. As this function looks up more ires i.e broadcast ires,
20450  * it needs to REFRELE them. Currently, for simplicity we don't
20451  * differentiate the one passed in and looked up here. We always
20452  * REFRELE.
20453  * IPQoS Notes:
20454  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
20455  * IPSec packets are done in ipsec_out_process.
20456  *
20457  */
20458 void
20459 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
20460 {
20461 	ipha_t		*ipha;
20462 #define	rptr	((uchar_t *)ipha)
20463 	mblk_t		*mp1;
20464 	queue_t		*stq;
20465 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
20466 	uint32_t	v_hlen_tos_len;
20467 	uint32_t	ttl_protocol;
20468 	ipaddr_t	src;
20469 	ipaddr_t	dst;
20470 	uint32_t	cksum;
20471 	ipaddr_t	orig_src;
20472 	ire_t		*ire1;
20473 	mblk_t		*next_mp;
20474 	uint_t		hlen;
20475 	uint16_t	*up;
20476 	uint32_t	max_frag = ire->ire_max_frag;
20477 	ill_t		*ill = ire_to_ill(ire);
20478 	int		clusterwide;
20479 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
20480 	int		ipsec_len;
20481 	mblk_t		*first_mp;
20482 	ipsec_out_t	*io;
20483 	boolean_t	conn_dontroute;		/* conn value for multicast */
20484 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
20485 	boolean_t	multicast_forward;	/* Should we forward ? */
20486 	boolean_t	unspec_src;
20487 	ill_t		*conn_outgoing_ill = NULL;
20488 	ill_t		*ire_ill;
20489 	ill_t		*ire1_ill;
20490 	uint32_t 	ill_index = 0;
20491 	boolean_t	multirt_send = B_FALSE;
20492 	int		err;
20493 	zoneid_t	zoneid;
20494 
20495 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
20496 	    "ip_wput_ire_start: q %p", q);
20497 
20498 	multicast_forward = B_FALSE;
20499 	unspec_src = (connp != NULL && connp->conn_unspec_src);
20500 
20501 	if (ire->ire_flags & RTF_MULTIRT) {
20502 		/*
20503 		 * Multirouting case. The bucket where ire is stored
20504 		 * probably holds other RTF_MULTIRT flagged ire
20505 		 * to the destination. In this call to ip_wput_ire,
20506 		 * we attempt to send the packet through all
20507 		 * those ires. Thus, we first ensure that ire is the
20508 		 * first RTF_MULTIRT ire in the bucket,
20509 		 * before walking the ire list.
20510 		 */
20511 		ire_t *first_ire;
20512 		irb_t *irb = ire->ire_bucket;
20513 		ASSERT(irb != NULL);
20514 
20515 		/* Make sure we do not omit any multiroute ire. */
20516 		IRB_REFHOLD(irb);
20517 		for (first_ire = irb->irb_ire;
20518 		    first_ire != NULL;
20519 		    first_ire = first_ire->ire_next) {
20520 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
20521 			    (first_ire->ire_addr == ire->ire_addr) &&
20522 			    !(first_ire->ire_marks &
20523 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
20524 				break;
20525 		}
20526 
20527 		if ((first_ire != NULL) && (first_ire != ire)) {
20528 			IRE_REFHOLD(first_ire);
20529 			ire_refrele(ire);
20530 			ire = first_ire;
20531 			ill = ire_to_ill(ire);
20532 		}
20533 		IRB_REFRELE(irb);
20534 	}
20535 
20536 	/*
20537 	 * conn_outgoing_ill is used only in the broadcast loop.
20538 	 * for performance we don't grab the mutexs in the fastpath
20539 	 */
20540 	if ((connp != NULL) &&
20541 	    (connp->conn_xmit_if_ill == NULL) &&
20542 	    (ire->ire_type == IRE_BROADCAST) &&
20543 	    ((connp->conn_nofailover_ill != NULL) ||
20544 	    (connp->conn_outgoing_ill != NULL))) {
20545 		/*
20546 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
20547 		 * option. So, see if this endpoint is bound to a
20548 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
20549 		 * that if the interface is failed, we will still send
20550 		 * the packet on the same ill which is what we want.
20551 		 */
20552 		conn_outgoing_ill = conn_get_held_ill(connp,
20553 		    &connp->conn_nofailover_ill, &err);
20554 		if (err == ILL_LOOKUP_FAILED) {
20555 			ire_refrele(ire);
20556 			freemsg(mp);
20557 			return;
20558 		}
20559 		if (conn_outgoing_ill == NULL) {
20560 			/*
20561 			 * Choose a good ill in the group to send the
20562 			 * packets on.
20563 			 */
20564 			ire = conn_set_outgoing_ill(connp, ire,
20565 			    &conn_outgoing_ill);
20566 			if (ire == NULL) {
20567 				freemsg(mp);
20568 				return;
20569 			}
20570 		}
20571 	}
20572 
20573 	if (mp->b_datap->db_type != M_CTL) {
20574 		ipha = (ipha_t *)mp->b_rptr;
20575 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
20576 	} else {
20577 		io = (ipsec_out_t *)mp->b_rptr;
20578 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20579 		zoneid = io->ipsec_out_zoneid;
20580 		ASSERT(zoneid != ALL_ZONES);
20581 		ipha = (ipha_t *)mp->b_cont->b_rptr;
20582 		dst = ipha->ipha_dst;
20583 		/*
20584 		 * For the multicast case, ipsec_out carries conn_dontroute and
20585 		 * conn_multicast_loop as conn may not be available here. We
20586 		 * need this for multicast loopback and forwarding which is done
20587 		 * later in the code.
20588 		 */
20589 		if (CLASSD(dst)) {
20590 			conn_dontroute = io->ipsec_out_dontroute;
20591 			conn_multicast_loop = io->ipsec_out_multicast_loop;
20592 			/*
20593 			 * If conn_dontroute is not set or conn_multicast_loop
20594 			 * is set, we need to do forwarding/loopback. For
20595 			 * datagrams from ip_wput_multicast, conn_dontroute is
20596 			 * set to B_TRUE and conn_multicast_loop is set to
20597 			 * B_FALSE so that we neither do forwarding nor
20598 			 * loopback.
20599 			 */
20600 			if (!conn_dontroute || conn_multicast_loop)
20601 				multicast_forward = B_TRUE;
20602 		}
20603 	}
20604 
20605 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
20606 	    ire->ire_zoneid != ALL_ZONES) {
20607 		/*
20608 		 * When a zone sends a packet to another zone, we try to deliver
20609 		 * the packet under the same conditions as if the destination
20610 		 * was a real node on the network. To do so, we look for a
20611 		 * matching route in the forwarding table.
20612 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
20613 		 * ip_newroute() does.
20614 		 */
20615 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
20616 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
20617 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
20618 		if (src_ire != NULL &&
20619 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
20620 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
20621 				ipha->ipha_src = src_ire->ire_src_addr;
20622 			ire_refrele(src_ire);
20623 		} else {
20624 			ire_refrele(ire);
20625 			if (conn_outgoing_ill != NULL)
20626 				ill_refrele(conn_outgoing_ill);
20627 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
20628 			if (src_ire != NULL) {
20629 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
20630 					ire_refrele(src_ire);
20631 					freemsg(mp);
20632 					return;
20633 				}
20634 				ire_refrele(src_ire);
20635 			}
20636 			if (ip_hdr_complete(ipha, zoneid)) {
20637 				/* Failed */
20638 				freemsg(mp);
20639 				return;
20640 			}
20641 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
20642 			return;
20643 		}
20644 	}
20645 
20646 	if (mp->b_datap->db_type == M_CTL ||
20647 	    ipsec_outbound_v4_policy_present) {
20648 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
20649 		    unspec_src);
20650 		if (mp == NULL) {
20651 			ire_refrele(ire);
20652 			if (conn_outgoing_ill != NULL)
20653 				ill_refrele(conn_outgoing_ill);
20654 			return;
20655 		}
20656 	}
20657 
20658 	first_mp = mp;
20659 	ipsec_len = 0;
20660 
20661 	if (first_mp->b_datap->db_type == M_CTL) {
20662 		io = (ipsec_out_t *)first_mp->b_rptr;
20663 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20664 		mp = first_mp->b_cont;
20665 		ipsec_len = ipsec_out_extra_length(first_mp);
20666 		ASSERT(ipsec_len >= 0);
20667 		zoneid = io->ipsec_out_zoneid;
20668 		ASSERT(zoneid != ALL_ZONES);
20669 
20670 		/*
20671 		 * Drop M_CTL here if IPsec processing is not needed.
20672 		 * (Non-IPsec use of M_CTL extracted any information it
20673 		 * needed above).
20674 		 */
20675 		if (ipsec_len == 0) {
20676 			freeb(first_mp);
20677 			first_mp = mp;
20678 		}
20679 	}
20680 
20681 	/*
20682 	 * Fast path for ip_wput_ire
20683 	 */
20684 
20685 	ipha = (ipha_t *)mp->b_rptr;
20686 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20687 	dst = ipha->ipha_dst;
20688 
20689 	/*
20690 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
20691 	 * if the socket is a SOCK_RAW type. The transport checksum should
20692 	 * be provided in the pre-built packet, so we don't need to compute it.
20693 	 * Also, other application set flags, like DF, should not be altered.
20694 	 * Other transport MUST pass down zero.
20695 	 */
20696 	ip_hdr_included = ipha->ipha_ident;
20697 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20698 
20699 	if (CLASSD(dst)) {
20700 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
20701 		    ntohl(dst),
20702 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
20703 		    ntohl(ire->ire_addr)));
20704 	}
20705 
20706 /* Macros to extract header fields from data already in registers */
20707 #ifdef	_BIG_ENDIAN
20708 #define	V_HLEN	(v_hlen_tos_len >> 24)
20709 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20710 #define	PROTO	(ttl_protocol & 0xFF)
20711 #else
20712 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20713 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20714 #define	PROTO	(ttl_protocol >> 8)
20715 #endif
20716 
20717 
20718 	orig_src = src = ipha->ipha_src;
20719 	/* (The loop back to "another" is explained down below.) */
20720 another:;
20721 	/*
20722 	 * Assign an ident value for this packet.  We assign idents on
20723 	 * a per destination basis out of the IRE.  There could be
20724 	 * other threads targeting the same destination, so we have to
20725 	 * arrange for a atomic increment.  Note that we use a 32-bit
20726 	 * atomic add because it has better performance than its
20727 	 * 16-bit sibling.
20728 	 *
20729 	 * If running in cluster mode and if the source address
20730 	 * belongs to a replicated service then vector through
20731 	 * cl_inet_ipident vector to allocate ip identifier
20732 	 * NOTE: This is a contract private interface with the
20733 	 * clustering group.
20734 	 */
20735 	clusterwide = 0;
20736 	if (cl_inet_ipident) {
20737 		ASSERT(cl_inet_isclusterwide);
20738 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20739 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
20740 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
20741 			    AF_INET, (uint8_t *)(uintptr_t)src,
20742 			    (uint8_t *)(uintptr_t)dst);
20743 			clusterwide = 1;
20744 		}
20745 	}
20746 	if (!clusterwide) {
20747 		ipha->ipha_ident =
20748 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
20749 	}
20750 
20751 #ifndef _BIG_ENDIAN
20752 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20753 #endif
20754 
20755 	/*
20756 	 * Set source address unless sent on an ill or conn_unspec_src is set.
20757 	 * This is needed to obey conn_unspec_src when packets go through
20758 	 * ip_newroute + arp.
20759 	 * Assumes ip_newroute{,_multi} sets the source address as well.
20760 	 */
20761 	if (src == INADDR_ANY && !unspec_src) {
20762 		/*
20763 		 * Assign the appropriate source address from the IRE if none
20764 		 * was specified.
20765 		 */
20766 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
20767 
20768 		/*
20769 		 * With IP multipathing, broadcast packets are sent on the ire
20770 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
20771 		 * the group. However, this ire might not be in the same zone so
20772 		 * we can't always use its source address. We look for a
20773 		 * broadcast ire in the same group and in the right zone.
20774 		 */
20775 		if (ire->ire_type == IRE_BROADCAST &&
20776 		    ire->ire_zoneid != zoneid) {
20777 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
20778 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
20779 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
20780 			if (src_ire != NULL) {
20781 				src = src_ire->ire_src_addr;
20782 				ire_refrele(src_ire);
20783 			} else {
20784 				ire_refrele(ire);
20785 				if (conn_outgoing_ill != NULL)
20786 					ill_refrele(conn_outgoing_ill);
20787 				freemsg(first_mp);
20788 				BUMP_MIB(&ip_mib, ipOutDiscards);
20789 				return;
20790 			}
20791 		} else {
20792 			src = ire->ire_src_addr;
20793 		}
20794 
20795 		if (connp == NULL) {
20796 			ip1dbg(("ip_wput_ire: no connp and no src "
20797 			    "address for dst 0x%x, using src 0x%x\n",
20798 			    ntohl(dst),
20799 			    ntohl(src)));
20800 		}
20801 		ipha->ipha_src = src;
20802 	}
20803 	stq = ire->ire_stq;
20804 
20805 	/*
20806 	 * We only allow ire chains for broadcasts since there will
20807 	 * be multiple IRE_CACHE entries for the same multicast
20808 	 * address (one per ipif).
20809 	 */
20810 	next_mp = NULL;
20811 
20812 	/* broadcast packet */
20813 	if (ire->ire_type == IRE_BROADCAST)
20814 		goto broadcast;
20815 
20816 	/* loopback ? */
20817 	if (stq == NULL)
20818 		goto nullstq;
20819 
20820 	/* The ill_index for outbound ILL */
20821 	ill_index = Q_TO_INDEX(stq);
20822 
20823 	BUMP_MIB(&ip_mib, ipOutRequests);
20824 	ttl_protocol = ((uint16_t *)ipha)[4];
20825 
20826 	/* pseudo checksum (do it in parts for IP header checksum) */
20827 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20828 
20829 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20830 		queue_t *dev_q = stq->q_next;
20831 
20832 		/* flow controlled */
20833 		if ((dev_q->q_next || dev_q->q_first) &&
20834 		    !canput(dev_q))
20835 			goto blocked;
20836 		if ((PROTO == IPPROTO_UDP) &&
20837 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20838 			hlen = (V_HLEN & 0xF) << 2;
20839 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20840 			if (*up != 0) {
20841 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20842 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20843 				/* Software checksum? */
20844 				if (DB_CKSUMFLAGS(mp) == 0) {
20845 					IP_STAT(ip_out_sw_cksum);
20846 					IP_STAT_UPDATE(
20847 					    ip_udp_out_sw_cksum_bytes,
20848 					    LENGTH - hlen);
20849 				}
20850 			}
20851 		}
20852 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20853 		hlen = (V_HLEN & 0xF) << 2;
20854 		if (PROTO == IPPROTO_TCP) {
20855 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20856 			/*
20857 			 * The packet header is processed once and for all, even
20858 			 * in the multirouting case. We disable hardware
20859 			 * checksum if the packet is multirouted, as it will be
20860 			 * replicated via several interfaces, and not all of
20861 			 * them may have this capability.
20862 			 */
20863 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20864 			    LENGTH, max_frag, ipsec_len, cksum);
20865 			/* Software checksum? */
20866 			if (DB_CKSUMFLAGS(mp) == 0) {
20867 				IP_STAT(ip_out_sw_cksum);
20868 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20869 				    LENGTH - hlen);
20870 			}
20871 		} else {
20872 			sctp_hdr_t	*sctph;
20873 
20874 			ASSERT(PROTO == IPPROTO_SCTP);
20875 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20876 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20877 			/*
20878 			 * Zero out the checksum field to ensure proper
20879 			 * checksum calculation.
20880 			 */
20881 			sctph->sh_chksum = 0;
20882 #ifdef	DEBUG
20883 			if (!skip_sctp_cksum)
20884 #endif
20885 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20886 		}
20887 	}
20888 
20889 	/*
20890 	 * If this is a multicast packet and originated from ip_wput
20891 	 * we need to do loopback and forwarding checks. If it comes
20892 	 * from ip_wput_multicast, we SHOULD not do this.
20893 	 */
20894 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20895 
20896 	/* checksum */
20897 	cksum += ttl_protocol;
20898 
20899 	/* fragment the packet */
20900 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20901 		goto fragmentit;
20902 	/*
20903 	 * Don't use frag_flag if packet is pre-built or source
20904 	 * routed or if multicast (since multicast packets do
20905 	 * not solicit ICMP "packet too big" messages).
20906 	 */
20907 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20908 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20909 	    !ip_source_route_included(ipha)) &&
20910 	    !CLASSD(ipha->ipha_dst))
20911 		ipha->ipha_fragment_offset_and_flags |=
20912 		    htons(ire->ire_frag_flag);
20913 
20914 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20915 		/* calculate IP header checksum */
20916 		cksum += ipha->ipha_ident;
20917 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20918 		cksum += ipha->ipha_fragment_offset_and_flags;
20919 
20920 		/* IP options present */
20921 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20922 		if (hlen)
20923 			goto checksumoptions;
20924 
20925 		/* calculate hdr checksum */
20926 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20927 		cksum = ~(cksum + (cksum >> 16));
20928 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20929 	}
20930 	if (ipsec_len != 0) {
20931 		/*
20932 		 * We will do the rest of the processing after
20933 		 * we come back from IPSEC in ip_wput_ipsec_out().
20934 		 */
20935 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20936 
20937 		io = (ipsec_out_t *)first_mp->b_rptr;
20938 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20939 				ill_phyint->phyint_ifindex;
20940 
20941 		ipsec_out_process(q, first_mp, ire, ill_index);
20942 		ire_refrele(ire);
20943 		if (conn_outgoing_ill != NULL)
20944 			ill_refrele(conn_outgoing_ill);
20945 		return;
20946 	}
20947 
20948 	/*
20949 	 * In most cases, the emission loop below is entered only
20950 	 * once. Only in the case where the ire holds the
20951 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20952 	 * flagged ires in the bucket, and send the packet
20953 	 * through all crossed RTF_MULTIRT routes.
20954 	 */
20955 	if (ire->ire_flags & RTF_MULTIRT) {
20956 		multirt_send = B_TRUE;
20957 	}
20958 	do {
20959 		if (multirt_send) {
20960 			irb_t *irb;
20961 			/*
20962 			 * We are in a multiple send case, need to get
20963 			 * the next ire and make a duplicate of the packet.
20964 			 * ire1 holds here the next ire to process in the
20965 			 * bucket. If multirouting is expected,
20966 			 * any non-RTF_MULTIRT ire that has the
20967 			 * right destination address is ignored.
20968 			 */
20969 			irb = ire->ire_bucket;
20970 			ASSERT(irb != NULL);
20971 
20972 			IRB_REFHOLD(irb);
20973 			for (ire1 = ire->ire_next;
20974 			    ire1 != NULL;
20975 			    ire1 = ire1->ire_next) {
20976 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20977 					continue;
20978 				if (ire1->ire_addr != ire->ire_addr)
20979 					continue;
20980 				if (ire1->ire_marks &
20981 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20982 					continue;
20983 
20984 				/* Got one */
20985 				IRE_REFHOLD(ire1);
20986 				break;
20987 			}
20988 			IRB_REFRELE(irb);
20989 
20990 			if (ire1 != NULL) {
20991 				next_mp = copyb(mp);
20992 				if ((next_mp == NULL) ||
20993 				    ((mp->b_cont != NULL) &&
20994 				    ((next_mp->b_cont =
20995 				    dupmsg(mp->b_cont)) == NULL))) {
20996 					freemsg(next_mp);
20997 					next_mp = NULL;
20998 					ire_refrele(ire1);
20999 					ire1 = NULL;
21000 				}
21001 			}
21002 
21003 			/* Last multiroute ire; don't loop anymore. */
21004 			if (ire1 == NULL) {
21005 				multirt_send = B_FALSE;
21006 			}
21007 		}
21008 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
21009 		if (mp == NULL) {
21010 			BUMP_MIB(&ip_mib, ipOutDiscards);
21011 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
21012 			    "during IPPF processing\n"));
21013 			ire_refrele(ire);
21014 			if (next_mp != NULL) {
21015 				freemsg(next_mp);
21016 				ire_refrele(ire1);
21017 			}
21018 			if (conn_outgoing_ill != NULL)
21019 				ill_refrele(conn_outgoing_ill);
21020 			return;
21021 		}
21022 		UPDATE_OB_PKT_COUNT(ire);
21023 		ire->ire_last_used_time = lbolt;
21024 
21025 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21026 		    "ip_wput_ire_end: q %p (%S)",
21027 		    q, "last copy out");
21028 		putnext(stq, mp);
21029 		IRE_REFRELE(ire);
21030 
21031 		if (multirt_send) {
21032 			ASSERT(ire1);
21033 			/*
21034 			 * Proceed with the next RTF_MULTIRT ire,
21035 			 * Also set up the send-to queue accordingly.
21036 			 */
21037 			ire = ire1;
21038 			ire1 = NULL;
21039 			stq = ire->ire_stq;
21040 			mp = next_mp;
21041 			next_mp = NULL;
21042 			ipha = (ipha_t *)mp->b_rptr;
21043 			ill_index = Q_TO_INDEX(stq);
21044 		}
21045 	} while (multirt_send);
21046 	if (conn_outgoing_ill != NULL)
21047 		ill_refrele(conn_outgoing_ill);
21048 	return;
21049 
21050 	/*
21051 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21052 	 */
21053 broadcast:
21054 	{
21055 		/*
21056 		 * Avoid broadcast storms by setting the ttl to 1
21057 		 * for broadcasts. This parameter can be set
21058 		 * via ndd, so make sure that for the SO_DONTROUTE
21059 		 * case that ipha_ttl is always set to 1.
21060 		 * In the event that we are replying to incoming
21061 		 * ICMP packets, conn could be NULL.
21062 		 */
21063 		if ((connp != NULL) && connp->conn_dontroute)
21064 			ipha->ipha_ttl = 1;
21065 		else
21066 			ipha->ipha_ttl = ip_broadcast_ttl;
21067 
21068 		/*
21069 		 * Note that we are not doing a IRB_REFHOLD here.
21070 		 * Actually we don't care if the list changes i.e
21071 		 * if somebody deletes an IRE from the list while
21072 		 * we drop the lock, the next time we come around
21073 		 * ire_next will be NULL and hence we won't send
21074 		 * out multiple copies which is fine.
21075 		 */
21076 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21077 		ire1 = ire->ire_next;
21078 		if (conn_outgoing_ill != NULL) {
21079 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21080 				ASSERT(ire1 == ire->ire_next);
21081 				if (ire1 != NULL && ire1->ire_addr == dst) {
21082 					ire_refrele(ire);
21083 					ire = ire1;
21084 					IRE_REFHOLD(ire);
21085 					ire1 = ire->ire_next;
21086 					continue;
21087 				}
21088 				rw_exit(&ire->ire_bucket->irb_lock);
21089 				/* Did not find a matching ill */
21090 				ip1dbg(("ip_wput_ire: broadcast with no "
21091 				    "matching IP_BOUND_IF ill %s\n",
21092 				    conn_outgoing_ill->ill_name));
21093 				freemsg(first_mp);
21094 				if (ire != NULL)
21095 					ire_refrele(ire);
21096 				ill_refrele(conn_outgoing_ill);
21097 				return;
21098 			}
21099 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21100 			/*
21101 			 * If the next IRE has the same address and is not one
21102 			 * of the two copies that we need to send, try to see
21103 			 * whether this copy should be sent at all. This
21104 			 * assumes that we insert loopbacks first and then
21105 			 * non-loopbacks. This is acheived by inserting the
21106 			 * loopback always before non-loopback.
21107 			 * This is used to send a single copy of a broadcast
21108 			 * packet out all physical interfaces that have an
21109 			 * matching IRE_BROADCAST while also looping
21110 			 * back one copy (to ip_wput_local) for each
21111 			 * matching physical interface. However, we avoid
21112 			 * sending packets out different logical that match by
21113 			 * having ipif_up/ipif_down supress duplicate
21114 			 * IRE_BROADCASTS.
21115 			 *
21116 			 * This feature is currently used to get broadcasts
21117 			 * sent to multiple interfaces, when the broadcast
21118 			 * address being used applies to multiple interfaces.
21119 			 * For example, a whole net broadcast will be
21120 			 * replicated on every connected subnet of
21121 			 * the target net.
21122 			 *
21123 			 * Each zone has its own set of IRE_BROADCASTs, so that
21124 			 * we're able to distribute inbound packets to multiple
21125 			 * zones who share a broadcast address. We avoid looping
21126 			 * back outbound packets in different zones but on the
21127 			 * same ill, as the application would see duplicates.
21128 			 *
21129 			 * If the interfaces are part of the same group,
21130 			 * we would want to send only one copy out for
21131 			 * whole group.
21132 			 *
21133 			 * This logic assumes that ire_add_v4() groups the
21134 			 * IRE_BROADCAST entries so that those with the same
21135 			 * ire_addr and ill_group are kept together.
21136 			 */
21137 			ire_ill = ire->ire_ipif->ipif_ill;
21138 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21139 				if (ire_ill->ill_group != NULL &&
21140 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21141 					/*
21142 					 * If the current zone only has an ire
21143 					 * broadcast for this address marked
21144 					 * NORECV, the ire we want is ahead in
21145 					 * the bucket, so we look it up
21146 					 * deliberately ignoring the zoneid.
21147 					 */
21148 					for (ire1 = ire->ire_bucket->irb_ire;
21149 					    ire1 != NULL;
21150 					    ire1 = ire1->ire_next) {
21151 						ire1_ill =
21152 						    ire1->ire_ipif->ipif_ill;
21153 						if (ire1->ire_addr != dst)
21154 							continue;
21155 						/* skip over the current ire */
21156 						if (ire1 == ire)
21157 							continue;
21158 						/* skip over deleted ires */
21159 						if (ire1->ire_marks &
21160 						    IRE_MARK_CONDEMNED)
21161 							continue;
21162 						/*
21163 						 * non-loopback ire in our
21164 						 * group: use it for the next
21165 						 * pass in the loop
21166 						 */
21167 						if (ire1->ire_stq != NULL &&
21168 						    ire1_ill->ill_group ==
21169 						    ire_ill->ill_group)
21170 							break;
21171 					}
21172 				}
21173 			} else {
21174 				while (ire1 != NULL && ire1->ire_addr == dst) {
21175 					ire1_ill = ire1->ire_ipif->ipif_ill;
21176 					/*
21177 					 * We can have two broadcast ires on the
21178 					 * same ill in different zones; here
21179 					 * we'll send a copy of the packet on
21180 					 * each ill and the fanout code will
21181 					 * call conn_wantpacket() to check that
21182 					 * the zone has the broadcast address
21183 					 * configured on the ill. If the two
21184 					 * ires are in the same group we only
21185 					 * send one copy up.
21186 					 */
21187 					if (ire1_ill != ire_ill &&
21188 					    (ire1_ill->ill_group == NULL ||
21189 					    ire_ill->ill_group == NULL ||
21190 					    ire1_ill->ill_group !=
21191 					    ire_ill->ill_group)) {
21192 						break;
21193 					}
21194 					ire1 = ire1->ire_next;
21195 				}
21196 			}
21197 		}
21198 		ASSERT(multirt_send == B_FALSE);
21199 		if (ire1 != NULL && ire1->ire_addr == dst) {
21200 			if ((ire->ire_flags & RTF_MULTIRT) &&
21201 			    (ire1->ire_flags & RTF_MULTIRT)) {
21202 				/*
21203 				 * We are in the multirouting case.
21204 				 * The message must be sent at least
21205 				 * on both ires. These ires have been
21206 				 * inserted AFTER the standard ones
21207 				 * in ip_rt_add(). There are thus no
21208 				 * other ire entries for the destination
21209 				 * address in the rest of the bucket
21210 				 * that do not have the RTF_MULTIRT
21211 				 * flag. We don't process a copy
21212 				 * of the message here. This will be
21213 				 * done in the final sending loop.
21214 				 */
21215 				multirt_send = B_TRUE;
21216 			} else {
21217 				next_mp = ip_copymsg(first_mp);
21218 				if (next_mp != NULL)
21219 					IRE_REFHOLD(ire1);
21220 			}
21221 		}
21222 		rw_exit(&ire->ire_bucket->irb_lock);
21223 	}
21224 
21225 	if (stq) {
21226 		/*
21227 		 * A non-NULL send-to queue means this packet is going
21228 		 * out of this machine.
21229 		 */
21230 
21231 		BUMP_MIB(&ip_mib, ipOutRequests);
21232 		ttl_protocol = ((uint16_t *)ipha)[4];
21233 		/*
21234 		 * We accumulate the pseudo header checksum in cksum.
21235 		 * This is pretty hairy code, so watch close.  One
21236 		 * thing to keep in mind is that UDP and TCP have
21237 		 * stored their respective datagram lengths in their
21238 		 * checksum fields.  This lines things up real nice.
21239 		 */
21240 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21241 		    (src >> 16) + (src & 0xFFFF);
21242 		/*
21243 		 * We assume the udp checksum field contains the
21244 		 * length, so to compute the pseudo header checksum,
21245 		 * all we need is the protocol number and src/dst.
21246 		 */
21247 		/* Provide the checksums for UDP and TCP. */
21248 		if ((PROTO == IPPROTO_TCP) &&
21249 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21250 			/* hlen gets the number of uchar_ts in the IP header */
21251 			hlen = (V_HLEN & 0xF) << 2;
21252 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21253 			IP_STAT(ip_out_sw_cksum);
21254 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21255 			    LENGTH - hlen);
21256 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21257 			if (*up == 0)
21258 				*up = 0xFFFF;
21259 		} else if (PROTO == IPPROTO_SCTP &&
21260 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21261 			sctp_hdr_t	*sctph;
21262 
21263 			hlen = (V_HLEN & 0xF) << 2;
21264 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21265 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21266 			sctph->sh_chksum = 0;
21267 #ifdef	DEBUG
21268 			if (!skip_sctp_cksum)
21269 #endif
21270 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21271 		} else {
21272 			queue_t *dev_q = stq->q_next;
21273 
21274 			if ((dev_q->q_next || dev_q->q_first) &&
21275 			    !canput(dev_q)) {
21276 			    blocked:
21277 				ipha->ipha_ident = ip_hdr_included;
21278 				/*
21279 				 * If we don't have a conn to apply
21280 				 * backpressure, free the message.
21281 				 * In the ire_send path, we don't know
21282 				 * the position to requeue the packet. Rather
21283 				 * than reorder packets, we just drop this
21284 				 * packet.
21285 				 */
21286 				if (ip_output_queue && connp != NULL &&
21287 				    caller != IRE_SEND) {
21288 					if (caller == IP_WSRV) {
21289 						connp->conn_did_putbq = 1;
21290 						(void) putbq(connp->conn_wq,
21291 						    first_mp);
21292 						conn_drain_insert(connp);
21293 						/*
21294 						 * This is the service thread,
21295 						 * and the queue is already
21296 						 * noenabled. The check for
21297 						 * canput and the putbq is not
21298 						 * atomic. So we need to check
21299 						 * again.
21300 						 */
21301 						if (canput(stq->q_next))
21302 							connp->conn_did_putbq
21303 							    = 0;
21304 						IP_STAT(ip_conn_flputbq);
21305 					} else {
21306 						/*
21307 						 * We are not the service proc.
21308 						 * ip_wsrv will be scheduled or
21309 						 * is already running.
21310 						 */
21311 						(void) putq(connp->conn_wq,
21312 						    first_mp);
21313 					}
21314 				} else {
21315 					BUMP_MIB(&ip_mib, ipOutDiscards);
21316 					freemsg(first_mp);
21317 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21318 					    "ip_wput_ire_end: q %p (%S)",
21319 					    q, "discard");
21320 				}
21321 				ire_refrele(ire);
21322 				if (next_mp) {
21323 					ire_refrele(ire1);
21324 					freemsg(next_mp);
21325 				}
21326 				if (conn_outgoing_ill != NULL)
21327 					ill_refrele(conn_outgoing_ill);
21328 				return;
21329 			}
21330 			if ((PROTO == IPPROTO_UDP) &&
21331 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21332 				/*
21333 				 * hlen gets the number of uchar_ts in the
21334 				 * IP header
21335 				 */
21336 				hlen = (V_HLEN & 0xF) << 2;
21337 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21338 				max_frag = ire->ire_max_frag;
21339 				if (*up != 0) {
21340 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21341 					    up, PROTO, hlen, LENGTH, max_frag,
21342 					    ipsec_len, cksum);
21343 					/* Software checksum? */
21344 					if (DB_CKSUMFLAGS(mp) == 0) {
21345 						IP_STAT(ip_out_sw_cksum);
21346 						IP_STAT_UPDATE(
21347 						    ip_udp_out_sw_cksum_bytes,
21348 						    LENGTH - hlen);
21349 					}
21350 				}
21351 			}
21352 		}
21353 		/*
21354 		 * Need to do this even when fragmenting. The local
21355 		 * loopback can be done without computing checksums
21356 		 * but forwarding out other interface must be done
21357 		 * after the IP checksum (and ULP checksums) have been
21358 		 * computed.
21359 		 *
21360 		 * NOTE : multicast_forward is set only if this packet
21361 		 * originated from ip_wput. For packets originating from
21362 		 * ip_wput_multicast, it is not set.
21363 		 */
21364 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21365 		    multi_loopback:
21366 			ip2dbg(("ip_wput: multicast, loop %d\n",
21367 			    conn_multicast_loop));
21368 
21369 			/*  Forget header checksum offload */
21370 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21371 
21372 			/*
21373 			 * Local loopback of multicasts?  Check the
21374 			 * ill.
21375 			 *
21376 			 * Note that the loopback function will not come
21377 			 * in through ip_rput - it will only do the
21378 			 * client fanout thus we need to do an mforward
21379 			 * as well.  The is different from the BSD
21380 			 * logic.
21381 			 */
21382 			if (ill != NULL) {
21383 				ilm_t	*ilm;
21384 
21385 				ILM_WALKER_HOLD(ill);
21386 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21387 				    ALL_ZONES);
21388 				ILM_WALKER_RELE(ill);
21389 				if (ilm != NULL) {
21390 					/*
21391 					 * Pass along the virtual output q.
21392 					 * ip_wput_local() will distribute the
21393 					 * packet to all the matching zones,
21394 					 * except the sending zone when
21395 					 * IP_MULTICAST_LOOP is false.
21396 					 */
21397 					ip_multicast_loopback(q, ill, first_mp,
21398 					    conn_multicast_loop ? 0 :
21399 					    IP_FF_NO_MCAST_LOOP, zoneid);
21400 				}
21401 			}
21402 			if (ipha->ipha_ttl == 0) {
21403 				/*
21404 				 * 0 => only to this host i.e. we are
21405 				 * done. We are also done if this was the
21406 				 * loopback interface since it is sufficient
21407 				 * to loopback one copy of a multicast packet.
21408 				 */
21409 				freemsg(first_mp);
21410 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21411 				    "ip_wput_ire_end: q %p (%S)",
21412 				    q, "loopback");
21413 				ire_refrele(ire);
21414 				if (conn_outgoing_ill != NULL)
21415 					ill_refrele(conn_outgoing_ill);
21416 				return;
21417 			}
21418 			/*
21419 			 * ILLF_MULTICAST is checked in ip_newroute
21420 			 * i.e. we don't need to check it here since
21421 			 * all IRE_CACHEs come from ip_newroute.
21422 			 * For multicast traffic, SO_DONTROUTE is interpreted
21423 			 * to mean only send the packet out the interface
21424 			 * (optionally specified with IP_MULTICAST_IF)
21425 			 * and do not forward it out additional interfaces.
21426 			 * RSVP and the rsvp daemon is an example of a
21427 			 * protocol and user level process that
21428 			 * handles it's own routing. Hence, it uses the
21429 			 * SO_DONTROUTE option to accomplish this.
21430 			 */
21431 
21432 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
21433 				/* Unconditionally redo the checksum */
21434 				ipha->ipha_hdr_checksum = 0;
21435 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21436 
21437 				/*
21438 				 * If this needs to go out secure, we need
21439 				 * to wait till we finish the IPSEC
21440 				 * processing.
21441 				 */
21442 				if (ipsec_len == 0 &&
21443 				    ip_mforward(ill, ipha, mp)) {
21444 					freemsg(first_mp);
21445 					ip1dbg(("ip_wput: mforward failed\n"));
21446 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21447 					    "ip_wput_ire_end: q %p (%S)",
21448 					    q, "mforward failed");
21449 					ire_refrele(ire);
21450 					if (conn_outgoing_ill != NULL)
21451 						ill_refrele(conn_outgoing_ill);
21452 					return;
21453 				}
21454 			}
21455 		}
21456 		max_frag = ire->ire_max_frag;
21457 		cksum += ttl_protocol;
21458 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
21459 			/* No fragmentation required for this one. */
21460 			/*
21461 			 * Don't use frag_flag if packet is pre-built or source
21462 			 * routed or if multicast (since multicast packets do
21463 			 * not solicit ICMP "packet too big" messages).
21464 			 */
21465 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21466 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21467 			    !ip_source_route_included(ipha)) &&
21468 			    !CLASSD(ipha->ipha_dst))
21469 				ipha->ipha_fragment_offset_and_flags |=
21470 				    htons(ire->ire_frag_flag);
21471 
21472 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21473 				/* Complete the IP header checksum. */
21474 				cksum += ipha->ipha_ident;
21475 				cksum += (v_hlen_tos_len >> 16)+
21476 				    (v_hlen_tos_len & 0xFFFF);
21477 				cksum += ipha->ipha_fragment_offset_and_flags;
21478 				hlen = (V_HLEN & 0xF) -
21479 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21480 				if (hlen) {
21481 				    checksumoptions:
21482 					/*
21483 					 * Account for the IP Options in the IP
21484 					 * header checksum.
21485 					 */
21486 					up = (uint16_t *)(rptr+
21487 					    IP_SIMPLE_HDR_LENGTH);
21488 					do {
21489 						cksum += up[0];
21490 						cksum += up[1];
21491 						up += 2;
21492 					} while (--hlen);
21493 				}
21494 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21495 				cksum = ~(cksum + (cksum >> 16));
21496 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
21497 			}
21498 			if (ipsec_len != 0) {
21499 				ipsec_out_process(q, first_mp, ire, ill_index);
21500 				if (!next_mp) {
21501 					ire_refrele(ire);
21502 					if (conn_outgoing_ill != NULL)
21503 						ill_refrele(conn_outgoing_ill);
21504 					return;
21505 				}
21506 				goto next;
21507 			}
21508 
21509 			/*
21510 			 * multirt_send has already been handled
21511 			 * for broadcast, but not yet for multicast
21512 			 * or IP options.
21513 			 */
21514 			if (next_mp == NULL) {
21515 				if (ire->ire_flags & RTF_MULTIRT) {
21516 					multirt_send = B_TRUE;
21517 				}
21518 			}
21519 
21520 			/*
21521 			 * In most cases, the emission loop below is
21522 			 * entered only once. Only in the case where
21523 			 * the ire holds the RTF_MULTIRT flag, do we loop
21524 			 * to process all RTF_MULTIRT ires in the bucket,
21525 			 * and send the packet through all crossed
21526 			 * RTF_MULTIRT routes.
21527 			 */
21528 			do {
21529 				if (multirt_send) {
21530 					irb_t *irb;
21531 
21532 					irb = ire->ire_bucket;
21533 					ASSERT(irb != NULL);
21534 					/*
21535 					 * We are in a multiple send case,
21536 					 * need to get the next IRE and make
21537 					 * a duplicate of the packet.
21538 					 */
21539 					IRB_REFHOLD(irb);
21540 					for (ire1 = ire->ire_next;
21541 					    ire1 != NULL;
21542 					    ire1 = ire1->ire_next) {
21543 						if (!(ire1->ire_flags &
21544 						    RTF_MULTIRT))
21545 							continue;
21546 						if (ire1->ire_addr !=
21547 						    ire->ire_addr)
21548 							continue;
21549 						if (ire1->ire_marks &
21550 						    (IRE_MARK_CONDEMNED|
21551 							IRE_MARK_HIDDEN))
21552 							continue;
21553 
21554 						/* Got one */
21555 						IRE_REFHOLD(ire1);
21556 						break;
21557 					}
21558 					IRB_REFRELE(irb);
21559 
21560 					if (ire1 != NULL) {
21561 						next_mp = copyb(mp);
21562 						if ((next_mp == NULL) ||
21563 						    ((mp->b_cont != NULL) &&
21564 						    ((next_mp->b_cont =
21565 						    dupmsg(mp->b_cont))
21566 						    == NULL))) {
21567 							freemsg(next_mp);
21568 							next_mp = NULL;
21569 							ire_refrele(ire1);
21570 							ire1 = NULL;
21571 						}
21572 					}
21573 
21574 					/*
21575 					 * Last multiroute ire; don't loop
21576 					 * anymore. The emission is over
21577 					 * and next_mp is NULL.
21578 					 */
21579 					if (ire1 == NULL) {
21580 						multirt_send = B_FALSE;
21581 					}
21582 				}
21583 
21584 				ASSERT(ipsec_len == 0);
21585 				mp1 = ip_wput_attach_llhdr(mp, ire,
21586 				    IPP_LOCAL_OUT, ill_index);
21587 				if (mp1 == NULL) {
21588 					BUMP_MIB(&ip_mib, ipOutDiscards);
21589 					if (next_mp) {
21590 						freemsg(next_mp);
21591 						ire_refrele(ire1);
21592 					}
21593 					ire_refrele(ire);
21594 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21595 					    "ip_wput_ire_end: q %p (%S)",
21596 					    q, "discard MDATA");
21597 					if (conn_outgoing_ill != NULL)
21598 						ill_refrele(conn_outgoing_ill);
21599 					return;
21600 				}
21601 				UPDATE_OB_PKT_COUNT(ire);
21602 				ire->ire_last_used_time = lbolt;
21603 
21604 				if (multirt_send) {
21605 					/*
21606 					 * We are in a multiple send case,
21607 					 * need to re-enter the sending loop
21608 					 * using the next ire.
21609 					 */
21610 					putnext(stq, mp1);
21611 					ire_refrele(ire);
21612 					ire = ire1;
21613 					stq = ire->ire_stq;
21614 					mp = next_mp;
21615 					next_mp = NULL;
21616 					ipha = (ipha_t *)mp->b_rptr;
21617 					ill_index = Q_TO_INDEX(stq);
21618 				}
21619 			} while (multirt_send);
21620 
21621 			if (!next_mp) {
21622 				/*
21623 				 * Last copy going out (the ultra-common
21624 				 * case).  Note that we intentionally replicate
21625 				 * the putnext rather than calling it before
21626 				 * the next_mp check in hopes of a little
21627 				 * tail-call action out of the compiler.
21628 				 */
21629 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21630 				    "ip_wput_ire_end: q %p (%S)",
21631 				    q, "last copy out(1)");
21632 				putnext(stq, mp1);
21633 				ire_refrele(ire);
21634 				if (conn_outgoing_ill != NULL)
21635 					ill_refrele(conn_outgoing_ill);
21636 				return;
21637 			}
21638 			/* More copies going out below. */
21639 			putnext(stq, mp1);
21640 		} else {
21641 			int offset;
21642 		    fragmentit:
21643 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21644 			/*
21645 			 * If this would generate a icmp_frag_needed message,
21646 			 * we need to handle it before we do the IPSEC
21647 			 * processing. Otherwise, we need to strip the IPSEC
21648 			 * headers before we send up the message to the ULPs
21649 			 * which becomes messy and difficult.
21650 			 */
21651 			if (ipsec_len != 0) {
21652 				if ((max_frag < (unsigned int)(LENGTH +
21653 				    ipsec_len)) && (offset & IPH_DF)) {
21654 
21655 					BUMP_MIB(&ip_mib, ipFragFails);
21656 					ipha->ipha_hdr_checksum = 0;
21657 					ipha->ipha_hdr_checksum =
21658 					    (uint16_t)ip_csum_hdr(ipha);
21659 					icmp_frag_needed(ire->ire_stq, first_mp,
21660 					    max_frag);
21661 					if (!next_mp) {
21662 						ire_refrele(ire);
21663 						if (conn_outgoing_ill != NULL) {
21664 							ill_refrele(
21665 							    conn_outgoing_ill);
21666 						}
21667 						return;
21668 					}
21669 				} else {
21670 					/*
21671 					 * This won't cause a icmp_frag_needed
21672 					 * message. to be gnerated. Send it on
21673 					 * the wire. Note that this could still
21674 					 * cause fragmentation and all we
21675 					 * do is the generation of the message
21676 					 * to the ULP if needed before IPSEC.
21677 					 */
21678 					if (!next_mp) {
21679 						ipsec_out_process(q, first_mp,
21680 						    ire, ill_index);
21681 						TRACE_2(TR_FAC_IP,
21682 						    TR_IP_WPUT_IRE_END,
21683 						    "ip_wput_ire_end: q %p "
21684 						    "(%S)", q,
21685 						    "last ipsec_out_process");
21686 						ire_refrele(ire);
21687 						if (conn_outgoing_ill != NULL) {
21688 							ill_refrele(
21689 							    conn_outgoing_ill);
21690 						}
21691 						return;
21692 					}
21693 					ipsec_out_process(q, first_mp,
21694 					    ire, ill_index);
21695 				}
21696 			} else {
21697 				/* Initiate IPPF processing */
21698 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21699 					ip_process(IPP_LOCAL_OUT, &mp,
21700 					    ill_index);
21701 					if (mp == NULL) {
21702 						BUMP_MIB(&ip_mib,
21703 						    ipOutDiscards);
21704 						if (next_mp != NULL) {
21705 							freemsg(next_mp);
21706 							ire_refrele(ire1);
21707 						}
21708 						ire_refrele(ire);
21709 						TRACE_2(TR_FAC_IP,
21710 						    TR_IP_WPUT_IRE_END,
21711 						    "ip_wput_ire: q %p (%S)",
21712 						    q, "discard MDATA");
21713 						if (conn_outgoing_ill != NULL) {
21714 							ill_refrele(
21715 							    conn_outgoing_ill);
21716 						}
21717 						return;
21718 					}
21719 				}
21720 				if (!next_mp) {
21721 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21722 					    "ip_wput_ire_end: q %p (%S)",
21723 					    q, "last fragmentation");
21724 					ip_wput_ire_fragmentit(mp, ire);
21725 					ire_refrele(ire);
21726 					if (conn_outgoing_ill != NULL)
21727 						ill_refrele(conn_outgoing_ill);
21728 					return;
21729 				}
21730 				ip_wput_ire_fragmentit(mp, ire);
21731 			}
21732 		}
21733 	} else {
21734 	    nullstq:
21735 		/* A NULL stq means the destination address is local. */
21736 		UPDATE_OB_PKT_COUNT(ire);
21737 		ire->ire_last_used_time = lbolt;
21738 		ASSERT(ire->ire_ipif != NULL);
21739 		if (!next_mp) {
21740 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21741 			    "ip_wput_ire_end: q %p (%S)",
21742 			    q, "local address");
21743 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
21744 			    first_mp, ire, 0, ire->ire_zoneid);
21745 			ire_refrele(ire);
21746 			if (conn_outgoing_ill != NULL)
21747 				ill_refrele(conn_outgoing_ill);
21748 			return;
21749 		}
21750 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
21751 		    ire, 0, ire->ire_zoneid);
21752 	}
21753 next:
21754 	/*
21755 	 * More copies going out to additional interfaces.
21756 	 * ire1 has already been held. We don't need the
21757 	 * "ire" anymore.
21758 	 */
21759 	ire_refrele(ire);
21760 	ire = ire1;
21761 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
21762 	mp = next_mp;
21763 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
21764 	ill = ire_to_ill(ire);
21765 	first_mp = mp;
21766 	if (ipsec_len != 0) {
21767 		ASSERT(first_mp->b_datap->db_type == M_CTL);
21768 		mp = mp->b_cont;
21769 	}
21770 	dst = ire->ire_addr;
21771 	ipha = (ipha_t *)mp->b_rptr;
21772 	/*
21773 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
21774 	 * Restore ipha_ident "no checksum" flag.
21775 	 */
21776 	src = orig_src;
21777 	ipha->ipha_ident = ip_hdr_included;
21778 	goto another;
21779 
21780 #undef	rptr
21781 #undef	Q_TO_INDEX
21782 }
21783 
21784 /*
21785  * Routine to allocate a message that is used to notify the ULP about MDT.
21786  * The caller may provide a pointer to the link-layer MDT capabilities,
21787  * or NULL if MDT is to be disabled on the stream.
21788  */
21789 mblk_t *
21790 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
21791 {
21792 	mblk_t *mp;
21793 	ip_mdt_info_t *mdti;
21794 	ill_mdt_capab_t *idst;
21795 
21796 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
21797 		DB_TYPE(mp) = M_CTL;
21798 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
21799 		mdti = (ip_mdt_info_t *)mp->b_rptr;
21800 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
21801 		idst = &(mdti->mdt_capab);
21802 
21803 		/*
21804 		 * If the caller provides us with the capability, copy
21805 		 * it over into our notification message; otherwise
21806 		 * we zero out the capability portion.
21807 		 */
21808 		if (isrc != NULL)
21809 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
21810 		else
21811 			bzero((caddr_t)idst, sizeof (*idst));
21812 	}
21813 	return (mp);
21814 }
21815 
21816 /*
21817  * Routine which determines whether MDT can be enabled on the destination
21818  * IRE and IPC combination, and if so, allocates and returns the MDT
21819  * notification mblk that may be used by ULP.  We also check if we need to
21820  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21821  * MDT usage in the past have been lifted.  This gets called during IP
21822  * and ULP binding.
21823  */
21824 mblk_t *
21825 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21826     ill_mdt_capab_t *mdt_cap)
21827 {
21828 	mblk_t *mp;
21829 	boolean_t rc = B_FALSE;
21830 
21831 	ASSERT(dst_ire != NULL);
21832 	ASSERT(connp != NULL);
21833 	ASSERT(mdt_cap != NULL);
21834 
21835 	/*
21836 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21837 	 * Multidata, which is handled in tcp_multisend().  This
21838 	 * is the reason why we do all these checks here, to ensure
21839 	 * that we don't enable Multidata for the cases which we
21840 	 * can't handle at the moment.
21841 	 */
21842 	do {
21843 		/* Only do TCP at the moment */
21844 		if (connp->conn_ulp != IPPROTO_TCP)
21845 			break;
21846 
21847 		/*
21848 		 * IPSEC outbound policy present?  Note that we get here
21849 		 * after calling ipsec_conn_cache_policy() where the global
21850 		 * policy checking is performed.  conn_latch will be
21851 		 * non-NULL as long as there's a policy defined,
21852 		 * i.e. conn_out_enforce_policy may be NULL in such case
21853 		 * when the connection is non-secure, and hence we check
21854 		 * further if the latch refers to an outbound policy.
21855 		 */
21856 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21857 			break;
21858 
21859 		/* CGTP (multiroute) is enabled? */
21860 		if (dst_ire->ire_flags & RTF_MULTIRT)
21861 			break;
21862 
21863 		/* Outbound IPQoS enabled? */
21864 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21865 			/*
21866 			 * In this case, we disable MDT for this and all
21867 			 * future connections going over the interface.
21868 			 */
21869 			mdt_cap->ill_mdt_on = 0;
21870 			break;
21871 		}
21872 
21873 		/* socket option(s) present? */
21874 		if (!CONN_IS_MD_FASTPATH(connp))
21875 			break;
21876 
21877 		rc = B_TRUE;
21878 	/* CONSTCOND */
21879 	} while (0);
21880 
21881 	/* Remember the result */
21882 	connp->conn_mdt_ok = rc;
21883 
21884 	if (!rc)
21885 		return (NULL);
21886 	else if (!mdt_cap->ill_mdt_on) {
21887 		/*
21888 		 * If MDT has been previously turned off in the past, and we
21889 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21890 		 * then enable it for this interface.
21891 		 */
21892 		mdt_cap->ill_mdt_on = 1;
21893 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21894 		    "interface %s\n", ill_name));
21895 	}
21896 
21897 	/* Allocate the MDT info mblk */
21898 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21899 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21900 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21901 		return (NULL);
21902 	}
21903 	return (mp);
21904 }
21905 
21906 /*
21907  * Create destination address attribute, and fill it with the physical
21908  * destination address and SAP taken from the template DL_UNITDATA_REQ
21909  * message block.
21910  */
21911 boolean_t
21912 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21913 {
21914 	dl_unitdata_req_t *dlurp;
21915 	pattr_t *pa;
21916 	pattrinfo_t pa_info;
21917 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21918 	uint_t das_len, das_off;
21919 
21920 	ASSERT(dlmp != NULL);
21921 
21922 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21923 	das_len = dlurp->dl_dest_addr_length;
21924 	das_off = dlurp->dl_dest_addr_offset;
21925 
21926 	pa_info.type = PATTR_DSTADDRSAP;
21927 	pa_info.len = sizeof (**das) + das_len - 1;
21928 
21929 	/* create and associate the attribute */
21930 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21931 	if (pa != NULL) {
21932 		ASSERT(*das != NULL);
21933 		(*das)->addr_is_group = 0;
21934 		(*das)->addr_len = (uint8_t)das_len;
21935 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21936 	}
21937 
21938 	return (pa != NULL);
21939 }
21940 
21941 /*
21942  * Create hardware checksum attribute and fill it with the values passed.
21943  */
21944 boolean_t
21945 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21946     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21947 {
21948 	pattr_t *pa;
21949 	pattrinfo_t pa_info;
21950 
21951 	ASSERT(mmd != NULL);
21952 
21953 	pa_info.type = PATTR_HCKSUM;
21954 	pa_info.len = sizeof (pattr_hcksum_t);
21955 
21956 	/* create and associate the attribute */
21957 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21958 	if (pa != NULL) {
21959 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21960 
21961 		hck->hcksum_start_offset = start_offset;
21962 		hck->hcksum_stuff_offset = stuff_offset;
21963 		hck->hcksum_end_offset = end_offset;
21964 		hck->hcksum_flags = flags;
21965 	}
21966 	return (pa != NULL);
21967 }
21968 
21969 /*
21970  * Create zerocopy attribute and fill it with the specified flags
21971  */
21972 boolean_t
21973 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21974 {
21975 	pattr_t *pa;
21976 	pattrinfo_t pa_info;
21977 
21978 	ASSERT(mmd != NULL);
21979 	pa_info.type = PATTR_ZCOPY;
21980 	pa_info.len = sizeof (pattr_zcopy_t);
21981 
21982 	/* create and associate the attribute */
21983 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21984 	if (pa != NULL) {
21985 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21986 
21987 		zcopy->zcopy_flags = flags;
21988 	}
21989 	return (pa != NULL);
21990 }
21991 
21992 /*
21993  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
21994  * block chain. We could rewrite to handle arbitrary message block chains but
21995  * that would make the code complicated and slow. Right now there three
21996  * restrictions:
21997  *
21998  *   1. The first message block must contain the complete IP header and
21999  *	at least 1 byte of payload data.
22000  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22001  *	so that we can use a single Multidata message.
22002  *   3. No frag must be distributed over two or more message blocks so
22003  *	that we don't need more than two packet descriptors per frag.
22004  *
22005  * The above restrictions allow us to support userland applications (which
22006  * will send down a single message block) and NFS over UDP (which will
22007  * send down a chain of at most three message blocks).
22008  *
22009  * We also don't use MDT for payloads with less than or equal to
22010  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22011  */
22012 boolean_t
22013 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22014 {
22015 	int	blocks;
22016 	ssize_t	total, missing, size;
22017 
22018 	ASSERT(mp != NULL);
22019 	ASSERT(hdr_len > 0);
22020 
22021 	size = MBLKL(mp) - hdr_len;
22022 	if (size <= 0)
22023 		return (B_FALSE);
22024 
22025 	/* The first mblk contains the header and some payload. */
22026 	blocks = 1;
22027 	total = size;
22028 	size %= len;
22029 	missing = (size == 0) ? 0 : (len - size);
22030 	mp = mp->b_cont;
22031 
22032 	while (mp != NULL) {
22033 		/*
22034 		 * Give up if we encounter a zero length message block.
22035 		 * In practice, this should rarely happen and therefore
22036 		 * not worth the trouble of freeing and re-linking the
22037 		 * mblk from the chain to handle such case.
22038 		 */
22039 		if ((size = MBLKL(mp)) == 0)
22040 			return (B_FALSE);
22041 
22042 		/* Too many payload buffers for a single Multidata message? */
22043 		if (++blocks > MULTIDATA_MAX_PBUFS)
22044 			return (B_FALSE);
22045 
22046 		total += size;
22047 		/* Is a frag distributed over two or more message blocks? */
22048 		if (missing > size)
22049 			return (B_FALSE);
22050 		size -= missing;
22051 
22052 		size %= len;
22053 		missing = (size == 0) ? 0 : (len - size);
22054 
22055 		mp = mp->b_cont;
22056 	}
22057 
22058 	return (total > ip_wput_frag_mdt_min);
22059 }
22060 
22061 /*
22062  * Outbound IPv4 fragmentation routine using MDT.
22063  */
22064 static void
22065 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22066     uint32_t frag_flag, int offset)
22067 {
22068 	ipha_t		*ipha_orig;
22069 	int		i1, ip_data_end;
22070 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22071 	mblk_t		*hdr_mp, *md_mp = NULL;
22072 	unsigned char	*hdr_ptr, *pld_ptr;
22073 	multidata_t	*mmd;
22074 	ip_pdescinfo_t	pdi;
22075 
22076 	ASSERT(DB_TYPE(mp) == M_DATA);
22077 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22078 
22079 	ipha_orig = (ipha_t *)mp->b_rptr;
22080 	mp->b_rptr += sizeof (ipha_t);
22081 
22082 	/* Calculate how many packets we will send out */
22083 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22084 	pkts = (i1 + len - 1) / len;
22085 	ASSERT(pkts > 1);
22086 
22087 	/* Allocate a message block which will hold all the IP Headers. */
22088 	wroff = ip_wroff_extra;
22089 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22090 
22091 	i1 = pkts * hdr_chunk_len;
22092 	/*
22093 	 * Create the header buffer, Multidata and destination address
22094 	 * and SAP attribute that should be associated with it.
22095 	 */
22096 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22097 	    ((hdr_mp->b_wptr += i1),
22098 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22099 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
22100 		freemsg(mp);
22101 		if (md_mp == NULL) {
22102 			freemsg(hdr_mp);
22103 		} else {
22104 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22105 			freemsg(md_mp);
22106 		}
22107 		IP_STAT(ip_frag_mdt_allocfail);
22108 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22109 		return;
22110 	}
22111 	IP_STAT(ip_frag_mdt_allocd);
22112 
22113 	/*
22114 	 * Add a payload buffer to the Multidata; this operation must not
22115 	 * fail, or otherwise our logic in this routine is broken.  There
22116 	 * is no memory allocation done by the routine, so any returned
22117 	 * failure simply tells us that we've done something wrong.
22118 	 *
22119 	 * A failure tells us that either we're adding the same payload
22120 	 * buffer more than once, or we're trying to add more buffers than
22121 	 * allowed.  None of the above cases should happen, and we panic
22122 	 * because either there's horrible heap corruption, and/or
22123 	 * programming mistake.
22124 	 */
22125 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22126 		goto pbuf_panic;
22127 
22128 	hdr_ptr = hdr_mp->b_rptr;
22129 	pld_ptr = mp->b_rptr;
22130 
22131 	/* Establish the ending byte offset, based on the starting offset. */
22132 	offset <<= 3;
22133 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22134 	    IP_SIMPLE_HDR_LENGTH;
22135 
22136 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22137 
22138 	while (pld_ptr < mp->b_wptr) {
22139 		ipha_t		*ipha;
22140 		uint16_t	offset_and_flags;
22141 		uint16_t	ip_len;
22142 		int		error;
22143 
22144 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22145 		ipha = (ipha_t *)(hdr_ptr + wroff);
22146 		ASSERT(OK_32PTR(ipha));
22147 		*ipha = *ipha_orig;
22148 
22149 		if (ip_data_end - offset > len) {
22150 			offset_and_flags = IPH_MF;
22151 		} else {
22152 			/*
22153 			 * Last frag. Set len to the length of this last piece.
22154 			 */
22155 			len = ip_data_end - offset;
22156 			/* A frag of a frag might have IPH_MF non-zero */
22157 			offset_and_flags =
22158 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22159 			    IPH_MF;
22160 		}
22161 		offset_and_flags |= (uint16_t)(offset >> 3);
22162 		offset_and_flags |= (uint16_t)frag_flag;
22163 		/* Store the offset and flags in the IP header. */
22164 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22165 
22166 		/* Store the length in the IP header. */
22167 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22168 		ipha->ipha_length = htons(ip_len);
22169 
22170 		/*
22171 		 * Set the IP header checksum.  Note that mp is just
22172 		 * the header, so this is easy to pass to ip_csum.
22173 		 */
22174 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22175 
22176 		/*
22177 		 * Record offset and size of header and data of the next packet
22178 		 * in the multidata message.
22179 		 */
22180 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22181 		PDESC_PLD_INIT(&pdi);
22182 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22183 		ASSERT(i1 > 0);
22184 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22185 		if (i1 == len) {
22186 			pld_ptr += len;
22187 		} else {
22188 			i1 = len - i1;
22189 			mp = mp->b_cont;
22190 			ASSERT(mp != NULL);
22191 			ASSERT(MBLKL(mp) >= i1);
22192 			/*
22193 			 * Attach the next payload message block to the
22194 			 * multidata message.
22195 			 */
22196 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22197 				goto pbuf_panic;
22198 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22199 			pld_ptr = mp->b_rptr + i1;
22200 		}
22201 
22202 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22203 		    KM_NOSLEEP)) == NULL) {
22204 			/*
22205 			 * Any failure other than ENOMEM indicates that we
22206 			 * have passed in invalid pdesc info or parameters
22207 			 * to mmd_addpdesc, which must not happen.
22208 			 *
22209 			 * EINVAL is a result of failure on boundary checks
22210 			 * against the pdesc info contents.  It should not
22211 			 * happen, and we panic because either there's
22212 			 * horrible heap corruption, and/or programming
22213 			 * mistake.
22214 			 */
22215 			if (error != ENOMEM) {
22216 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22217 				    "pdesc logic error detected for "
22218 				    "mmd %p pinfo %p (%d)\n",
22219 				    (void *)mmd, (void *)&pdi, error);
22220 				/* NOTREACHED */
22221 			}
22222 			IP_STAT(ip_frag_mdt_addpdescfail);
22223 			/* Free unattached payload message blocks as well */
22224 			md_mp->b_cont = mp->b_cont;
22225 			goto free_mmd;
22226 		}
22227 
22228 		/* Advance fragment offset. */
22229 		offset += len;
22230 
22231 		/* Advance to location for next header in the buffer. */
22232 		hdr_ptr += hdr_chunk_len;
22233 
22234 		/* Did we reach the next payload message block? */
22235 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22236 			mp = mp->b_cont;
22237 			/*
22238 			 * Attach the next message block with payload
22239 			 * data to the multidata message.
22240 			 */
22241 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22242 				goto pbuf_panic;
22243 			pld_ptr = mp->b_rptr;
22244 		}
22245 	}
22246 
22247 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22248 	ASSERT(mp->b_wptr == pld_ptr);
22249 
22250 	/* Update IP statistics */
22251 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22252 	BUMP_MIB(&ip_mib, ipFragOKs);
22253 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22254 
22255 	if (pkt_type == OB_PKT) {
22256 		ire->ire_ob_pkt_count += pkts;
22257 		if (ire->ire_ipif != NULL)
22258 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22259 	} else {
22260 		/*
22261 		 * The type is IB_PKT in the forwarding path and in
22262 		 * the mobile IP case when the packet is being reverse-
22263 		 * tunneled to the home agent.
22264 		 */
22265 		ire->ire_ib_pkt_count += pkts;
22266 		ASSERT(!IRE_IS_LOCAL(ire));
22267 		if (ire->ire_type & IRE_BROADCAST)
22268 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22269 		else
22270 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22271 	}
22272 	ire->ire_last_used_time = lbolt;
22273 	/* Send it down */
22274 	putnext(ire->ire_stq, md_mp);
22275 	return;
22276 
22277 pbuf_panic:
22278 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22279 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22280 	    pbuf_idx);
22281 	/* NOTREACHED */
22282 }
22283 
22284 /*
22285  * Outbound IP fragmentation routine.
22286  *
22287  * NOTE : This routine does not ire_refrele the ire that is passed in
22288  * as the argument.
22289  */
22290 static void
22291 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22292     uint32_t frag_flag)
22293 {
22294 	int		i1;
22295 	mblk_t		*ll_hdr_mp;
22296 	int 		ll_hdr_len;
22297 	int		hdr_len;
22298 	mblk_t		*hdr_mp;
22299 	ipha_t		*ipha;
22300 	int		ip_data_end;
22301 	int		len;
22302 	mblk_t		*mp = mp_orig;
22303 	int		offset;
22304 	queue_t		*q;
22305 	uint32_t	v_hlen_tos_len;
22306 	mblk_t		*first_mp;
22307 	boolean_t	mctl_present;
22308 	ill_t		*ill;
22309 	mblk_t		*xmit_mp;
22310 	mblk_t		*carve_mp;
22311 	ire_t		*ire1 = NULL;
22312 	ire_t		*save_ire = NULL;
22313 	mblk_t  	*next_mp = NULL;
22314 	boolean_t	last_frag = B_FALSE;
22315 	boolean_t	multirt_send = B_FALSE;
22316 	ire_t		*first_ire = NULL;
22317 	irb_t		*irb = NULL;
22318 
22319 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22320 	    "ip_wput_frag_start:");
22321 
22322 	if (mp->b_datap->db_type == M_CTL) {
22323 		first_mp = mp;
22324 		mp_orig = mp = mp->b_cont;
22325 		mctl_present = B_TRUE;
22326 	} else {
22327 		first_mp = mp;
22328 		mctl_present = B_FALSE;
22329 	}
22330 
22331 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22332 	ipha = (ipha_t *)mp->b_rptr;
22333 
22334 	/*
22335 	 * If the Don't Fragment flag is on, generate an ICMP destination
22336 	 * unreachable, fragmentation needed.
22337 	 */
22338 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22339 	if (offset & IPH_DF) {
22340 		BUMP_MIB(&ip_mib, ipFragFails);
22341 		/*
22342 		 * Need to compute hdr checksum if called from ip_wput_ire.
22343 		 * Note that ip_rput_forward verifies the checksum before
22344 		 * calling this routine so in that case this is a noop.
22345 		 */
22346 		ipha->ipha_hdr_checksum = 0;
22347 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22348 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22349 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22350 		    "ip_wput_frag_end:(%S)",
22351 		    "don't fragment");
22352 		return;
22353 	}
22354 	if (mctl_present)
22355 		freeb(first_mp);
22356 	/*
22357 	 * Establish the starting offset.  May not be zero if we are fragging
22358 	 * a fragment that is being forwarded.
22359 	 */
22360 	offset = offset & IPH_OFFSET;
22361 
22362 	/* TODO why is this test needed? */
22363 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22364 	if (((max_frag - LENGTH) & ~7) < 8) {
22365 		/* TODO: notify ulp somehow */
22366 		BUMP_MIB(&ip_mib, ipFragFails);
22367 		freemsg(mp);
22368 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22369 		    "ip_wput_frag_end:(%S)",
22370 		    "len < 8");
22371 		return;
22372 	}
22373 
22374 	hdr_len = (V_HLEN & 0xF) << 2;
22375 
22376 	ipha->ipha_hdr_checksum = 0;
22377 
22378 	/*
22379 	 * Establish the number of bytes maximum per frag, after putting
22380 	 * in the header.
22381 	 */
22382 	len = (max_frag - hdr_len) & ~7;
22383 
22384 	/* Check if we can use MDT to send out the frags. */
22385 	ASSERT(!IRE_IS_LOCAL(ire));
22386 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
22387 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
22388 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
22389 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
22390 		ASSERT(ill->ill_mdt_capab != NULL);
22391 		if (!ill->ill_mdt_capab->ill_mdt_on) {
22392 			/*
22393 			 * If MDT has been previously turned off in the past,
22394 			 * and we currently can do MDT (due to IPQoS policy
22395 			 * removal, etc.) then enable it for this interface.
22396 			 */
22397 			ill->ill_mdt_capab->ill_mdt_on = 1;
22398 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
22399 			    ill->ill_name));
22400 		}
22401 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
22402 		    offset);
22403 		return;
22404 	}
22405 
22406 	/* Get a copy of the header for the trailing frags */
22407 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
22408 	if (!hdr_mp) {
22409 		BUMP_MIB(&ip_mib, ipOutDiscards);
22410 		freemsg(mp);
22411 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22412 		    "ip_wput_frag_end:(%S)",
22413 		    "couldn't copy hdr");
22414 		return;
22415 	}
22416 	if (DB_CRED(mp) != NULL)
22417 		mblk_setcred(hdr_mp, DB_CRED(mp));
22418 
22419 	/* Store the starting offset, with the MoreFrags flag. */
22420 	i1 = offset | IPH_MF | frag_flag;
22421 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
22422 
22423 	/* Establish the ending byte offset, based on the starting offset. */
22424 	offset <<= 3;
22425 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
22426 
22427 	/* Store the length of the first fragment in the IP header. */
22428 	i1 = len + hdr_len;
22429 	ASSERT(i1 <= IP_MAXPACKET);
22430 	ipha->ipha_length = htons((uint16_t)i1);
22431 
22432 	/*
22433 	 * Compute the IP header checksum for the first frag.  We have to
22434 	 * watch out that we stop at the end of the header.
22435 	 */
22436 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22437 
22438 	/*
22439 	 * Now carve off the first frag.  Note that this will include the
22440 	 * original IP header.
22441 	 */
22442 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
22443 		BUMP_MIB(&ip_mib, ipOutDiscards);
22444 		freeb(hdr_mp);
22445 		freemsg(mp_orig);
22446 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22447 		    "ip_wput_frag_end:(%S)",
22448 		    "couldn't carve first");
22449 		return;
22450 	}
22451 
22452 	/*
22453 	 * Multirouting case. Each fragment is replicated
22454 	 * via all non-condemned RTF_MULTIRT routes
22455 	 * currently resolved.
22456 	 * We ensure that first_ire is the first RTF_MULTIRT
22457 	 * ire in the bucket.
22458 	 */
22459 	if (ire->ire_flags & RTF_MULTIRT) {
22460 		irb = ire->ire_bucket;
22461 		ASSERT(irb != NULL);
22462 
22463 		multirt_send = B_TRUE;
22464 
22465 		/* Make sure we do not omit any multiroute ire. */
22466 		IRB_REFHOLD(irb);
22467 		for (first_ire = irb->irb_ire;
22468 		    first_ire != NULL;
22469 		    first_ire = first_ire->ire_next) {
22470 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22471 			    (first_ire->ire_addr == ire->ire_addr) &&
22472 			    !(first_ire->ire_marks &
22473 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22474 				break;
22475 		}
22476 
22477 		if (first_ire != NULL) {
22478 			if (first_ire != ire) {
22479 				IRE_REFHOLD(first_ire);
22480 				/*
22481 				 * Do not release the ire passed in
22482 				 * as the argument.
22483 				 */
22484 				ire = first_ire;
22485 			} else {
22486 				first_ire = NULL;
22487 			}
22488 		}
22489 		IRB_REFRELE(irb);
22490 
22491 		/*
22492 		 * Save the first ire; we will need to restore it
22493 		 * for the trailing frags.
22494 		 * We REFHOLD save_ire, as each iterated ire will be
22495 		 * REFRELEd.
22496 		 */
22497 		save_ire = ire;
22498 		IRE_REFHOLD(save_ire);
22499 	}
22500 
22501 	/*
22502 	 * First fragment emission loop.
22503 	 * In most cases, the emission loop below is entered only
22504 	 * once. Only in the case where the ire holds the RTF_MULTIRT
22505 	 * flag, do we loop to process all RTF_MULTIRT ires in the
22506 	 * bucket, and send the fragment through all crossed
22507 	 * RTF_MULTIRT routes.
22508 	 */
22509 	do {
22510 		if (ire->ire_flags & RTF_MULTIRT) {
22511 			/*
22512 			 * We are in a multiple send case, need to get
22513 			 * the next ire and make a copy of the packet.
22514 			 * ire1 holds here the next ire to process in the
22515 			 * bucket. If multirouting is expected,
22516 			 * any non-RTF_MULTIRT ire that has the
22517 			 * right destination address is ignored.
22518 			 *
22519 			 * We have to take into account the MTU of
22520 			 * each walked ire. max_frag is set by the
22521 			 * the caller and generally refers to
22522 			 * the primary ire entry. Here we ensure that
22523 			 * no route with a lower MTU will be used, as
22524 			 * fragments are carved once for all ires,
22525 			 * then replicated.
22526 			 */
22527 			ASSERT(irb != NULL);
22528 			IRB_REFHOLD(irb);
22529 			for (ire1 = ire->ire_next;
22530 			    ire1 != NULL;
22531 			    ire1 = ire1->ire_next) {
22532 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22533 					continue;
22534 				if (ire1->ire_addr != ire->ire_addr)
22535 					continue;
22536 				if (ire1->ire_marks &
22537 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22538 					continue;
22539 				/*
22540 				 * Ensure we do not exceed the MTU
22541 				 * of the next route.
22542 				 */
22543 				if (ire1->ire_max_frag < max_frag) {
22544 					ip_multirt_bad_mtu(ire1, max_frag);
22545 					continue;
22546 				}
22547 
22548 				/* Got one. */
22549 				IRE_REFHOLD(ire1);
22550 				break;
22551 			}
22552 			IRB_REFRELE(irb);
22553 
22554 			if (ire1 != NULL) {
22555 				next_mp = copyb(mp);
22556 				if ((next_mp == NULL) ||
22557 				    ((mp->b_cont != NULL) &&
22558 				    ((next_mp->b_cont =
22559 				    dupmsg(mp->b_cont)) == NULL))) {
22560 					freemsg(next_mp);
22561 					next_mp = NULL;
22562 					ire_refrele(ire1);
22563 					ire1 = NULL;
22564 				}
22565 			}
22566 
22567 			/* Last multiroute ire; don't loop anymore. */
22568 			if (ire1 == NULL) {
22569 				multirt_send = B_FALSE;
22570 			}
22571 		}
22572 
22573 		ll_hdr_len = 0;
22574 		LOCK_IRE_FP_MP(ire);
22575 		ll_hdr_mp = ire->ire_fp_mp;
22576 		if (ll_hdr_mp != NULL) {
22577 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22578 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
22579 		} else {
22580 			ll_hdr_mp = ire->ire_dlureq_mp;
22581 		}
22582 
22583 		/* If there is a transmit header, get a copy for this frag. */
22584 		/*
22585 		 * TODO: should check db_ref before calling ip_carve_mp since
22586 		 * it might give us a dup.
22587 		 */
22588 		if (!ll_hdr_mp) {
22589 			/* No xmit header. */
22590 			xmit_mp = mp;
22591 		} else if (mp->b_datap->db_ref == 1 &&
22592 		    ll_hdr_len != 0 &&
22593 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22594 			/* M_DATA fastpath */
22595 			mp->b_rptr -= ll_hdr_len;
22596 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
22597 			xmit_mp = mp;
22598 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
22599 			UNLOCK_IRE_FP_MP(ire);
22600 			BUMP_MIB(&ip_mib, ipOutDiscards);
22601 			freeb(hdr_mp);
22602 			freemsg(mp);
22603 			freemsg(mp_orig);
22604 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22605 			    "ip_wput_frag_end:(%S)",
22606 			    "discard");
22607 
22608 			if (multirt_send) {
22609 				ASSERT(ire1);
22610 				ASSERT(next_mp);
22611 
22612 				freemsg(next_mp);
22613 				ire_refrele(ire1);
22614 			}
22615 			if (save_ire != NULL)
22616 				IRE_REFRELE(save_ire);
22617 
22618 			if (first_ire != NULL)
22619 				ire_refrele(first_ire);
22620 			return;
22621 		} else {
22622 			xmit_mp->b_cont = mp;
22623 			if (DB_CRED(mp) != NULL)
22624 				mblk_setcred(xmit_mp, DB_CRED(mp));
22625 			/* Get priority marking, if any. */
22626 			if (DB_TYPE(xmit_mp) == M_DATA)
22627 				xmit_mp->b_band = mp->b_band;
22628 		}
22629 		UNLOCK_IRE_FP_MP(ire);
22630 		q = ire->ire_stq;
22631 		BUMP_MIB(&ip_mib, ipFragCreates);
22632 		putnext(q, xmit_mp);
22633 		if (pkt_type != OB_PKT) {
22634 			/*
22635 			 * Update the packet count of trailing
22636 			 * RTF_MULTIRT ires.
22637 			 */
22638 			UPDATE_OB_PKT_COUNT(ire);
22639 		}
22640 
22641 		if (multirt_send) {
22642 			/*
22643 			 * We are in a multiple send case; look for
22644 			 * the next ire and re-enter the loop.
22645 			 */
22646 			ASSERT(ire1);
22647 			ASSERT(next_mp);
22648 			/* REFRELE the current ire before looping */
22649 			ire_refrele(ire);
22650 			ire = ire1;
22651 			ire1 = NULL;
22652 			mp = next_mp;
22653 			next_mp = NULL;
22654 		}
22655 	} while (multirt_send);
22656 
22657 	ASSERT(ire1 == NULL);
22658 
22659 	/* Restore the original ire; we need it for the trailing frags */
22660 	if (save_ire != NULL) {
22661 		/* REFRELE the last iterated ire */
22662 		ire_refrele(ire);
22663 		/* save_ire has been REFHOLDed */
22664 		ire = save_ire;
22665 		save_ire = NULL;
22666 		q = ire->ire_stq;
22667 	}
22668 
22669 	if (pkt_type == OB_PKT) {
22670 		UPDATE_OB_PKT_COUNT(ire);
22671 	} else {
22672 		UPDATE_IB_PKT_COUNT(ire);
22673 	}
22674 
22675 	/* Advance the offset to the second frag starting point. */
22676 	offset += len;
22677 	/*
22678 	 * Update hdr_len from the copied header - there might be less options
22679 	 * in the later fragments.
22680 	 */
22681 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
22682 	/* Loop until done. */
22683 	for (;;) {
22684 		uint16_t	offset_and_flags;
22685 		uint16_t	ip_len;
22686 
22687 		if (ip_data_end - offset > len) {
22688 			/*
22689 			 * Carve off the appropriate amount from the original
22690 			 * datagram.
22691 			 */
22692 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22693 				mp = NULL;
22694 				break;
22695 			}
22696 			/*
22697 			 * More frags after this one.  Get another copy
22698 			 * of the header.
22699 			 */
22700 			if (carve_mp->b_datap->db_ref == 1 &&
22701 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22702 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22703 				/* Inline IP header */
22704 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22705 				    hdr_mp->b_rptr;
22706 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22707 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22708 				mp = carve_mp;
22709 			} else {
22710 				if (!(mp = copyb(hdr_mp))) {
22711 					freemsg(carve_mp);
22712 					break;
22713 				}
22714 				/* Get priority marking, if any. */
22715 				mp->b_band = carve_mp->b_band;
22716 				mp->b_cont = carve_mp;
22717 			}
22718 			ipha = (ipha_t *)mp->b_rptr;
22719 			offset_and_flags = IPH_MF;
22720 		} else {
22721 			/*
22722 			 * Last frag.  Consume the header. Set len to
22723 			 * the length of this last piece.
22724 			 */
22725 			len = ip_data_end - offset;
22726 
22727 			/*
22728 			 * Carve off the appropriate amount from the original
22729 			 * datagram.
22730 			 */
22731 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22732 				mp = NULL;
22733 				break;
22734 			}
22735 			if (carve_mp->b_datap->db_ref == 1 &&
22736 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22737 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22738 				/* Inline IP header */
22739 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22740 				    hdr_mp->b_rptr;
22741 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22742 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22743 				mp = carve_mp;
22744 				freeb(hdr_mp);
22745 				hdr_mp = mp;
22746 			} else {
22747 				mp = hdr_mp;
22748 				/* Get priority marking, if any. */
22749 				mp->b_band = carve_mp->b_band;
22750 				mp->b_cont = carve_mp;
22751 			}
22752 			ipha = (ipha_t *)mp->b_rptr;
22753 			/* A frag of a frag might have IPH_MF non-zero */
22754 			offset_and_flags =
22755 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22756 			    IPH_MF;
22757 		}
22758 		offset_and_flags |= (uint16_t)(offset >> 3);
22759 		offset_and_flags |= (uint16_t)frag_flag;
22760 		/* Store the offset and flags in the IP header. */
22761 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22762 
22763 		/* Store the length in the IP header. */
22764 		ip_len = (uint16_t)(len + hdr_len);
22765 		ipha->ipha_length = htons(ip_len);
22766 
22767 		/*
22768 		 * Set the IP header checksum.	Note that mp is just
22769 		 * the header, so this is easy to pass to ip_csum.
22770 		 */
22771 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22772 
22773 		/* Attach a transmit header, if any, and ship it. */
22774 		if (pkt_type == OB_PKT) {
22775 			UPDATE_OB_PKT_COUNT(ire);
22776 		} else {
22777 			UPDATE_IB_PKT_COUNT(ire);
22778 		}
22779 
22780 		if (ire->ire_flags & RTF_MULTIRT) {
22781 			irb = ire->ire_bucket;
22782 			ASSERT(irb != NULL);
22783 
22784 			multirt_send = B_TRUE;
22785 
22786 			/*
22787 			 * Save the original ire; we will need to restore it
22788 			 * for the tailing frags.
22789 			 */
22790 			save_ire = ire;
22791 			IRE_REFHOLD(save_ire);
22792 		}
22793 		/*
22794 		 * Emission loop for this fragment, similar
22795 		 * to what is done for the first fragment.
22796 		 */
22797 		do {
22798 			if (multirt_send) {
22799 				/*
22800 				 * We are in a multiple send case, need to get
22801 				 * the next ire and make a copy of the packet.
22802 				 */
22803 				ASSERT(irb != NULL);
22804 				IRB_REFHOLD(irb);
22805 				for (ire1 = ire->ire_next;
22806 				    ire1 != NULL;
22807 				    ire1 = ire1->ire_next) {
22808 					if (!(ire1->ire_flags & RTF_MULTIRT))
22809 						continue;
22810 					if (ire1->ire_addr != ire->ire_addr)
22811 						continue;
22812 					if (ire1->ire_marks &
22813 					    (IRE_MARK_CONDEMNED|
22814 						IRE_MARK_HIDDEN))
22815 						continue;
22816 					/*
22817 					 * Ensure we do not exceed the MTU
22818 					 * of the next route.
22819 					 */
22820 					if (ire1->ire_max_frag < max_frag) {
22821 						ip_multirt_bad_mtu(ire1,
22822 						    max_frag);
22823 						continue;
22824 					}
22825 
22826 					/* Got one. */
22827 					IRE_REFHOLD(ire1);
22828 					break;
22829 				}
22830 				IRB_REFRELE(irb);
22831 
22832 				if (ire1 != NULL) {
22833 					next_mp = copyb(mp);
22834 					if ((next_mp == NULL) ||
22835 					    ((mp->b_cont != NULL) &&
22836 					    ((next_mp->b_cont =
22837 					    dupmsg(mp->b_cont)) == NULL))) {
22838 						freemsg(next_mp);
22839 						next_mp = NULL;
22840 						ire_refrele(ire1);
22841 						ire1 = NULL;
22842 					}
22843 				}
22844 
22845 				/* Last multiroute ire; don't loop anymore. */
22846 				if (ire1 == NULL) {
22847 					multirt_send = B_FALSE;
22848 				}
22849 			}
22850 
22851 			/* Update transmit header */
22852 			ll_hdr_len = 0;
22853 			LOCK_IRE_FP_MP(ire);
22854 			ll_hdr_mp = ire->ire_fp_mp;
22855 			if (ll_hdr_mp != NULL) {
22856 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22857 				ll_hdr_len = MBLKL(ll_hdr_mp);
22858 			} else {
22859 				ll_hdr_mp = ire->ire_dlureq_mp;
22860 			}
22861 
22862 			if (!ll_hdr_mp) {
22863 				xmit_mp = mp;
22864 			} else if (mp->b_datap->db_ref == 1 &&
22865 			    ll_hdr_len != 0 &&
22866 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22867 				/* M_DATA fastpath */
22868 				mp->b_rptr -= ll_hdr_len;
22869 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22870 				    ll_hdr_len);
22871 				xmit_mp = mp;
22872 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22873 				xmit_mp->b_cont = mp;
22874 				if (DB_CRED(mp) != NULL)
22875 					mblk_setcred(xmit_mp, DB_CRED(mp));
22876 				/* Get priority marking, if any. */
22877 				if (DB_TYPE(xmit_mp) == M_DATA)
22878 					xmit_mp->b_band = mp->b_band;
22879 			} else {
22880 				/*
22881 				 * Exit both the replication and
22882 				 * fragmentation loops.
22883 				 */
22884 				UNLOCK_IRE_FP_MP(ire);
22885 				goto drop_pkt;
22886 			}
22887 			UNLOCK_IRE_FP_MP(ire);
22888 			BUMP_MIB(&ip_mib, ipFragCreates);
22889 			putnext(q, xmit_mp);
22890 
22891 			if (pkt_type != OB_PKT) {
22892 				/*
22893 				 * Update the packet count of trailing
22894 				 * RTF_MULTIRT ires.
22895 				 */
22896 				UPDATE_OB_PKT_COUNT(ire);
22897 			}
22898 
22899 			/* All done if we just consumed the hdr_mp. */
22900 			if (mp == hdr_mp) {
22901 				last_frag = B_TRUE;
22902 			}
22903 
22904 			if (multirt_send) {
22905 				/*
22906 				 * We are in a multiple send case; look for
22907 				 * the next ire and re-enter the loop.
22908 				 */
22909 				ASSERT(ire1);
22910 				ASSERT(next_mp);
22911 				/* REFRELE the current ire before looping */
22912 				ire_refrele(ire);
22913 				ire = ire1;
22914 				ire1 = NULL;
22915 				q = ire->ire_stq;
22916 				mp = next_mp;
22917 				next_mp = NULL;
22918 			}
22919 		} while (multirt_send);
22920 		/*
22921 		 * Restore the original ire; we need it for the
22922 		 * trailing frags
22923 		 */
22924 		if (save_ire != NULL) {
22925 			ASSERT(ire1 == NULL);
22926 			/* REFRELE the last iterated ire */
22927 			ire_refrele(ire);
22928 			/* save_ire has been REFHOLDed */
22929 			ire = save_ire;
22930 			q = ire->ire_stq;
22931 			save_ire = NULL;
22932 		}
22933 
22934 		if (last_frag) {
22935 			BUMP_MIB(&ip_mib, ipFragOKs);
22936 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22937 			    "ip_wput_frag_end:(%S)",
22938 			    "consumed hdr_mp");
22939 
22940 			if (first_ire != NULL)
22941 				ire_refrele(first_ire);
22942 			return;
22943 		}
22944 		/* Otherwise, advance and loop. */
22945 		offset += len;
22946 	}
22947 
22948 drop_pkt:
22949 	/* Clean up following allocation failure. */
22950 	BUMP_MIB(&ip_mib, ipOutDiscards);
22951 	freemsg(mp);
22952 	if (mp != hdr_mp)
22953 		freeb(hdr_mp);
22954 	if (mp != mp_orig)
22955 		freemsg(mp_orig);
22956 
22957 	if (save_ire != NULL)
22958 		IRE_REFRELE(save_ire);
22959 	if (first_ire != NULL)
22960 		ire_refrele(first_ire);
22961 
22962 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22963 	    "ip_wput_frag_end:(%S)",
22964 	    "end--alloc failure");
22965 }
22966 
22967 /*
22968  * Copy the header plus those options which have the copy bit set
22969  */
22970 static mblk_t *
22971 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22972 {
22973 	mblk_t	*mp;
22974 	uchar_t	*up;
22975 
22976 	/*
22977 	 * Quick check if we need to look for options without the copy bit
22978 	 * set
22979 	 */
22980 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22981 	if (!mp)
22982 		return (mp);
22983 	mp->b_rptr += ip_wroff_extra;
22984 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22985 		bcopy(rptr, mp->b_rptr, hdr_len);
22986 		mp->b_wptr += hdr_len + ip_wroff_extra;
22987 		return (mp);
22988 	}
22989 	up  = mp->b_rptr;
22990 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22991 	up += IP_SIMPLE_HDR_LENGTH;
22992 	rptr += IP_SIMPLE_HDR_LENGTH;
22993 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
22994 	while (hdr_len > 0) {
22995 		uint32_t optval;
22996 		uint32_t optlen;
22997 
22998 		optval = *rptr;
22999 		if (optval == IPOPT_EOL)
23000 			break;
23001 		if (optval == IPOPT_NOP)
23002 			optlen = 1;
23003 		else
23004 			optlen = rptr[1];
23005 		if (optval & IPOPT_COPY) {
23006 			bcopy(rptr, up, optlen);
23007 			up += optlen;
23008 		}
23009 		rptr += optlen;
23010 		hdr_len -= optlen;
23011 	}
23012 	/*
23013 	 * Make sure that we drop an even number of words by filling
23014 	 * with EOL to the next word boundary.
23015 	 */
23016 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23017 	    hdr_len & 0x3; hdr_len++)
23018 		*up++ = IPOPT_EOL;
23019 	mp->b_wptr = up;
23020 	/* Update header length */
23021 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23022 	return (mp);
23023 }
23024 
23025 /*
23026  * Delivery to local recipients including fanout to multiple recipients.
23027  * Does not do checksumming of UDP/TCP.
23028  * Note: q should be the read side queue for either the ill or conn.
23029  * Note: rq should be the read side q for the lower (ill) stream.
23030  * We don't send packets to IPPF processing, thus the last argument
23031  * to all the fanout calls are B_FALSE.
23032  */
23033 void
23034 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23035     int fanout_flags, zoneid_t zoneid)
23036 {
23037 	uint32_t	protocol;
23038 	mblk_t		*first_mp;
23039 	boolean_t	mctl_present;
23040 	int		ire_type;
23041 #define	rptr	((uchar_t *)ipha)
23042 
23043 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23044 	    "ip_wput_local_start: q %p", q);
23045 
23046 	if (ire != NULL) {
23047 		ire_type = ire->ire_type;
23048 	} else {
23049 		/*
23050 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23051 		 * packet is not multicast, we can't tell the ire type.
23052 		 */
23053 		ASSERT(CLASSD(ipha->ipha_dst));
23054 		ire_type = IRE_BROADCAST;
23055 	}
23056 
23057 	first_mp = mp;
23058 	if (first_mp->b_datap->db_type == M_CTL) {
23059 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23060 		if (!io->ipsec_out_secure) {
23061 			/*
23062 			 * This ipsec_out_t was allocated in ip_wput
23063 			 * for multicast packets to store the ill_index.
23064 			 * As this is being delivered locally, we don't
23065 			 * need this anymore.
23066 			 */
23067 			mp = first_mp->b_cont;
23068 			freeb(first_mp);
23069 			first_mp = mp;
23070 			mctl_present = B_FALSE;
23071 		} else {
23072 			mctl_present = B_TRUE;
23073 			mp = first_mp->b_cont;
23074 			ASSERT(mp != NULL);
23075 			ipsec_out_to_in(first_mp);
23076 		}
23077 	} else {
23078 		mctl_present = B_FALSE;
23079 	}
23080 
23081 	loopback_packets++;
23082 
23083 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23084 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23085 	if (!IS_SIMPLE_IPH(ipha)) {
23086 		ip_wput_local_options(ipha);
23087 	}
23088 
23089 	protocol = ipha->ipha_protocol;
23090 	switch (protocol) {
23091 	case IPPROTO_ICMP: {
23092 		ire_t		*ire_zone;
23093 		ilm_t		*ilm;
23094 		mblk_t		*mp1;
23095 		zoneid_t	last_zoneid;
23096 
23097 		if (CLASSD(ipha->ipha_dst) &&
23098 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23099 			ASSERT(ire_type == IRE_BROADCAST);
23100 			/*
23101 			 * In the multicast case, applications may have joined
23102 			 * the group from different zones, so we need to deliver
23103 			 * the packet to each of them. Loop through the
23104 			 * multicast memberships structures (ilm) on the receive
23105 			 * ill and send a copy of the packet up each matching
23106 			 * one. However, we don't do this for multicasts sent on
23107 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23108 			 * they must stay in the sender's zone.
23109 			 *
23110 			 * ilm_add_v6() ensures that ilms in the same zone are
23111 			 * contiguous in the ill_ilm list. We use this property
23112 			 * to avoid sending duplicates needed when two
23113 			 * applications in the same zone join the same group on
23114 			 * different logical interfaces: we ignore the ilm if
23115 			 * its zoneid is the same as the last matching one.
23116 			 * In addition, the sending of the packet for
23117 			 * ire_zoneid is delayed until all of the other ilms
23118 			 * have been exhausted.
23119 			 */
23120 			last_zoneid = -1;
23121 			ILM_WALKER_HOLD(ill);
23122 			for (ilm = ill->ill_ilm; ilm != NULL;
23123 			    ilm = ilm->ilm_next) {
23124 				if ((ilm->ilm_flags & ILM_DELETED) ||
23125 				    ipha->ipha_dst != ilm->ilm_addr ||
23126 				    ilm->ilm_zoneid == last_zoneid ||
23127 				    ilm->ilm_zoneid == zoneid ||
23128 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23129 					continue;
23130 				mp1 = ip_copymsg(first_mp);
23131 				if (mp1 == NULL)
23132 					continue;
23133 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23134 				    mctl_present, B_FALSE, ill,
23135 				    ilm->ilm_zoneid);
23136 				last_zoneid = ilm->ilm_zoneid;
23137 			}
23138 			ILM_WALKER_RELE(ill);
23139 			/*
23140 			 * Loopback case: the sending endpoint has
23141 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23142 			 * dispatch the multicast packet to the sending zone.
23143 			 */
23144 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23145 				freemsg(first_mp);
23146 				return;
23147 			}
23148 		} else if (ire_type == IRE_BROADCAST) {
23149 			/*
23150 			 * In the broadcast case, there may be many zones
23151 			 * which need a copy of the packet delivered to them.
23152 			 * There is one IRE_BROADCAST per broadcast address
23153 			 * and per zone; we walk those using a helper function.
23154 			 * In addition, the sending of the packet for zoneid is
23155 			 * delayed until all of the other ires have been
23156 			 * processed.
23157 			 */
23158 			IRB_REFHOLD(ire->ire_bucket);
23159 			ire_zone = NULL;
23160 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23161 			    ire)) != NULL) {
23162 				mp1 = ip_copymsg(first_mp);
23163 				if (mp1 == NULL)
23164 					continue;
23165 
23166 				UPDATE_IB_PKT_COUNT(ire_zone);
23167 				ire_zone->ire_last_used_time = lbolt;
23168 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23169 				    mctl_present, B_FALSE, ill,
23170 				    ire_zone->ire_zoneid);
23171 			}
23172 			IRB_REFRELE(ire->ire_bucket);
23173 		}
23174 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23175 		    0, mctl_present, B_FALSE, ill, zoneid);
23176 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23177 		    "ip_wput_local_end: q %p (%S)",
23178 		    q, "icmp");
23179 		return;
23180 	}
23181 	case IPPROTO_IGMP:
23182 		if (igmp_input(q, mp, ill)) {
23183 			/* Bad packet - discarded by igmp_input */
23184 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23185 			    "ip_wput_local_end: q %p (%S)",
23186 			    q, "igmp_input--bad packet");
23187 			if (mctl_present)
23188 				freeb(first_mp);
23189 			return;
23190 		}
23191 		/*
23192 		 * igmp_input() may have pulled up the message so ipha needs to
23193 		 * be reinitialized.
23194 		 */
23195 		ipha = (ipha_t *)mp->b_rptr;
23196 		/* deliver to local raw users */
23197 		break;
23198 	case IPPROTO_ENCAP:
23199 		/*
23200 		 * This case is covered by either ip_fanout_proto, or by
23201 		 * the above security processing for self-tunneled packets.
23202 		 */
23203 		break;
23204 	case IPPROTO_UDP: {
23205 		uint16_t	*up;
23206 		uint32_t	ports;
23207 
23208 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23209 		    UDP_PORTS_OFFSET);
23210 		/* Force a 'valid' checksum. */
23211 		up[3] = 0;
23212 
23213 		ports = *(uint32_t *)up;
23214 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23215 		    (ire_type == IRE_BROADCAST),
23216 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23217 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23218 		    ill, zoneid);
23219 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23220 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23221 		return;
23222 	}
23223 	case IPPROTO_TCP: {
23224 
23225 		/*
23226 		 * For TCP, discard broadcast packets.
23227 		 */
23228 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23229 			freemsg(first_mp);
23230 			BUMP_MIB(&ip_mib, ipInDiscards);
23231 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23232 			return;
23233 		}
23234 
23235 		if (mp->b_datap->db_type == M_DATA) {
23236 			/*
23237 			 * M_DATA mblk, so init mblk (chain) for no struio().
23238 			 */
23239 			mblk_t	*mp1 = mp;
23240 
23241 			do
23242 				mp1->b_datap->db_struioflag = 0;
23243 			while ((mp1 = mp1->b_cont) != NULL);
23244 		}
23245 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23246 		    <= mp->b_wptr);
23247 		ip_fanout_tcp(q, first_mp, ill, ipha,
23248 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23249 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23250 		    mctl_present, B_FALSE, zoneid);
23251 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23252 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23253 		return;
23254 	}
23255 	case IPPROTO_SCTP:
23256 	{
23257 		uint32_t	ports;
23258 
23259 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23260 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23261 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23262 		    IP_FF_IP6INFO,
23263 		    mctl_present, B_FALSE, 0, zoneid);
23264 		return;
23265 	}
23266 
23267 	default:
23268 		break;
23269 	}
23270 	/*
23271 	 * Find a client for some other protocol.  We give
23272 	 * copies to multiple clients, if more than one is
23273 	 * bound.
23274 	 */
23275 	ip_fanout_proto(q, first_mp, ill, ipha,
23276 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23277 	    mctl_present, B_FALSE, ill, zoneid);
23278 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23279 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23280 #undef	rptr
23281 }
23282 
23283 /*
23284  * Update any source route, record route, or timestamp options.
23285  * Check that we are at end of strict source route.
23286  * The options have been sanity checked by ip_wput_options().
23287  */
23288 static void
23289 ip_wput_local_options(ipha_t *ipha)
23290 {
23291 	ipoptp_t	opts;
23292 	uchar_t		*opt;
23293 	uint8_t		optval;
23294 	uint8_t		optlen;
23295 	ipaddr_t	dst;
23296 	uint32_t	ts;
23297 	ire_t		*ire;
23298 	timestruc_t	now;
23299 
23300 	ip2dbg(("ip_wput_local_options\n"));
23301 	for (optval = ipoptp_first(&opts, ipha);
23302 	    optval != IPOPT_EOL;
23303 	    optval = ipoptp_next(&opts)) {
23304 		opt = opts.ipoptp_cur;
23305 		optlen = opts.ipoptp_len;
23306 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23307 		switch (optval) {
23308 			uint32_t off;
23309 		case IPOPT_SSRR:
23310 		case IPOPT_LSRR:
23311 			off = opt[IPOPT_OFFSET];
23312 			off--;
23313 			if (optlen < IP_ADDR_LEN ||
23314 			    off > optlen - IP_ADDR_LEN) {
23315 				/* End of source route */
23316 				break;
23317 			}
23318 			/*
23319 			 * This will only happen if two consecutive entries
23320 			 * in the source route contains our address or if
23321 			 * it is a packet with a loose source route which
23322 			 * reaches us before consuming the whole source route
23323 			 */
23324 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23325 			if (optval == IPOPT_SSRR) {
23326 				return;
23327 			}
23328 			/*
23329 			 * Hack: instead of dropping the packet truncate the
23330 			 * source route to what has been used by filling the
23331 			 * rest with IPOPT_NOP.
23332 			 */
23333 			opt[IPOPT_OLEN] = (uint8_t)off;
23334 			while (off < optlen) {
23335 				opt[off++] = IPOPT_NOP;
23336 			}
23337 			break;
23338 		case IPOPT_RR:
23339 			off = opt[IPOPT_OFFSET];
23340 			off--;
23341 			if (optlen < IP_ADDR_LEN ||
23342 			    off > optlen - IP_ADDR_LEN) {
23343 				/* No more room - ignore */
23344 				ip1dbg((
23345 				    "ip_wput_forward_options: end of RR\n"));
23346 				break;
23347 			}
23348 			dst = htonl(INADDR_LOOPBACK);
23349 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23350 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23351 			break;
23352 		case IPOPT_TS:
23353 			/* Insert timestamp if there is romm */
23354 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23355 			case IPOPT_TS_TSONLY:
23356 				off = IPOPT_TS_TIMELEN;
23357 				break;
23358 			case IPOPT_TS_PRESPEC:
23359 			case IPOPT_TS_PRESPEC_RFC791:
23360 				/* Verify that the address matched */
23361 				off = opt[IPOPT_OFFSET] - 1;
23362 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
23363 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
23364 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
23365 				if (ire == NULL) {
23366 					/* Not for us */
23367 					break;
23368 				}
23369 				ire_refrele(ire);
23370 				/* FALLTHRU */
23371 			case IPOPT_TS_TSANDADDR:
23372 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
23373 				break;
23374 			default:
23375 				/*
23376 				 * ip_*put_options should have already
23377 				 * dropped this packet.
23378 				 */
23379 				cmn_err(CE_PANIC, "ip_wput_local_options: "
23380 				    "unknown IT - bug in ip_wput_options?\n");
23381 				return;	/* Keep "lint" happy */
23382 			}
23383 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
23384 				/* Increase overflow counter */
23385 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
23386 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
23387 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
23388 				    (off << 4);
23389 				break;
23390 			}
23391 			off = opt[IPOPT_OFFSET] - 1;
23392 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23393 			case IPOPT_TS_PRESPEC:
23394 			case IPOPT_TS_PRESPEC_RFC791:
23395 			case IPOPT_TS_TSANDADDR:
23396 				dst = htonl(INADDR_LOOPBACK);
23397 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23398 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23399 				/* FALLTHRU */
23400 			case IPOPT_TS_TSONLY:
23401 				off = opt[IPOPT_OFFSET] - 1;
23402 				/* Compute # of milliseconds since midnight */
23403 				gethrestime(&now);
23404 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
23405 				    now.tv_nsec / (NANOSEC / MILLISEC);
23406 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
23407 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
23408 				break;
23409 			}
23410 			break;
23411 		}
23412 	}
23413 }
23414 
23415 /*
23416  * Send out a multicast packet on interface ipif.
23417  * The sender does not have an conn.
23418  * Caller verifies that this isn't a PHYI_LOOPBACK.
23419  */
23420 void
23421 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
23422 {
23423 	ipha_t	*ipha;
23424 	ire_t	*ire;
23425 	ipaddr_t	dst;
23426 	mblk_t		*first_mp;
23427 
23428 	/* igmp_sendpkt always allocates a ipsec_out_t */
23429 	ASSERT(mp->b_datap->db_type == M_CTL);
23430 	ASSERT(!ipif->ipif_isv6);
23431 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
23432 
23433 	first_mp = mp;
23434 	mp = first_mp->b_cont;
23435 	ASSERT(mp->b_datap->db_type == M_DATA);
23436 	ipha = (ipha_t *)mp->b_rptr;
23437 
23438 	/*
23439 	 * Find an IRE which matches the destination and the outgoing
23440 	 * queue (i.e. the outgoing interface.)
23441 	 */
23442 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
23443 		dst = ipif->ipif_pp_dst_addr;
23444 	else
23445 		dst = ipha->ipha_dst;
23446 	/*
23447 	 * The source address has already been initialized by the
23448 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
23449 	 * be sufficient rather than MATCH_IRE_IPIF.
23450 	 *
23451 	 * This function is used for sending IGMP packets. We need
23452 	 * to make sure that we send the packet out of the interface
23453 	 * (ipif->ipif_ill) where we joined the group. This is to
23454 	 * prevent from switches doing IGMP snooping to send us multicast
23455 	 * packets for a given group on the interface we have joined.
23456 	 * If we can't find an ire, igmp_sendpkt has already initialized
23457 	 * ipsec_out_attach_if so that this will not be load spread in
23458 	 * ip_newroute_ipif.
23459 	 */
23460 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
23461 	    MATCH_IRE_ILL);
23462 	if (!ire) {
23463 		/*
23464 		 * Mark this packet to make it be delivered to
23465 		 * ip_wput_ire after the new ire has been
23466 		 * created.
23467 		 */
23468 		mp->b_prev = NULL;
23469 		mp->b_next = NULL;
23470 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
23471 		return;
23472 	}
23473 
23474 	/*
23475 	 * Honor the RTF_SETSRC flag; this is the only case
23476 	 * where we force this addr whatever the current src addr is,
23477 	 * because this address is set by igmp_sendpkt(), and
23478 	 * cannot be specified by any user.
23479 	 */
23480 	if (ire->ire_flags & RTF_SETSRC) {
23481 		ipha->ipha_src = ire->ire_src_addr;
23482 	}
23483 
23484 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
23485 }
23486 
23487 /*
23488  * NOTE : This function does not ire_refrele the ire argument passed in.
23489  *
23490  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
23491  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
23492  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
23493  * the ire_lock to access the ire_fp_mp in this case.
23494  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
23495  * prepending a fastpath message IPQoS processing must precede it, we also set
23496  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
23497  * (IPQoS might have set the b_band for CoS marking).
23498  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
23499  * must follow it so that IPQoS can mark the dl_priority field for CoS
23500  * marking, if needed.
23501  */
23502 static mblk_t *
23503 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
23504 {
23505 	uint_t	hlen;
23506 	ipha_t *ipha;
23507 	mblk_t *mp1;
23508 	boolean_t qos_done = B_FALSE;
23509 	uchar_t	*ll_hdr;
23510 
23511 #define	rptr	((uchar_t *)ipha)
23512 
23513 	ipha = (ipha_t *)mp->b_rptr;
23514 	hlen = 0;
23515 	LOCK_IRE_FP_MP(ire);
23516 	if ((mp1 = ire->ire_fp_mp) != NULL) {
23517 		ASSERT(DB_TYPE(mp1) == M_DATA);
23518 		/* Initiate IPPF processing */
23519 		if ((proc != 0) && IPP_ENABLED(proc)) {
23520 			UNLOCK_IRE_FP_MP(ire);
23521 			ip_process(proc, &mp, ill_index);
23522 			if (mp == NULL)
23523 				return (NULL);
23524 
23525 			ipha = (ipha_t *)mp->b_rptr;
23526 			LOCK_IRE_FP_MP(ire);
23527 			if ((mp1 = ire->ire_fp_mp) == NULL) {
23528 				qos_done = B_TRUE;
23529 				goto no_fp_mp;
23530 			}
23531 			ASSERT(DB_TYPE(mp1) == M_DATA);
23532 		}
23533 		hlen = MBLKL(mp1);
23534 		/*
23535 		 * Check if we have enough room to prepend fastpath
23536 		 * header
23537 		 */
23538 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
23539 			ll_hdr = rptr - hlen;
23540 			bcopy(mp1->b_rptr, ll_hdr, hlen);
23541 			/* XXX ipha is not aligned here */
23542 			ipha = (ipha_t *)(rptr - hlen);
23543 			/*
23544 			 * Set the b_rptr to the start of the link layer
23545 			 * header
23546 			 */
23547 			mp->b_rptr = rptr;
23548 			mp1 = mp;
23549 		} else {
23550 			mp1 = copyb(mp1);
23551 			if (mp1 == NULL)
23552 				goto unlock_err;
23553 			mp1->b_band = mp->b_band;
23554 			mp1->b_cont = mp;
23555 			/*
23556 			 * certain system generated traffic may not
23557 			 * have cred/label in ip header block. This
23558 			 * is true even for a labeled system. But for
23559 			 * labeled traffic, inherit the label in the
23560 			 * new header.
23561 			 */
23562 			if (DB_CRED(mp) != NULL)
23563 				mblk_setcred(mp1, DB_CRED(mp));
23564 			/*
23565 			 * XXX disable ICK_VALID and compute checksum
23566 			 * here; can happen if ire_fp_mp changes and
23567 			 * it can't be copied now due to insufficient
23568 			 * space. (unlikely, fp mp can change, but it
23569 			 * does not increase in length)
23570 			 */
23571 		}
23572 		UNLOCK_IRE_FP_MP(ire);
23573 	} else {
23574 no_fp_mp:
23575 		mp1 = copyb(ire->ire_dlureq_mp);
23576 		if (mp1 == NULL) {
23577 unlock_err:
23578 			UNLOCK_IRE_FP_MP(ire);
23579 			freemsg(mp);
23580 			return (NULL);
23581 		}
23582 		UNLOCK_IRE_FP_MP(ire);
23583 		mp1->b_cont = mp;
23584 		/*
23585 		 * certain system generated traffic may not
23586 		 * have cred/label in ip header block. This
23587 		 * is true even for a labeled system. But for
23588 		 * labeled traffic, inherit the label in the
23589 		 * new header.
23590 		 */
23591 		if (DB_CRED(mp) != NULL)
23592 			mblk_setcred(mp1, DB_CRED(mp));
23593 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
23594 			ip_process(proc, &mp1, ill_index);
23595 			if (mp1 == NULL)
23596 				return (NULL);
23597 		}
23598 	}
23599 	return (mp1);
23600 #undef rptr
23601 }
23602 
23603 /*
23604  * Finish the outbound IPsec processing for an IPv6 packet. This function
23605  * is called from ipsec_out_process() if the IPsec packet was processed
23606  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23607  * asynchronously.
23608  */
23609 void
23610 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
23611     ire_t *ire_arg)
23612 {
23613 	in6_addr_t *v6dstp;
23614 	ire_t *ire;
23615 	mblk_t *mp;
23616 	uint_t	ill_index;
23617 	ipsec_out_t *io;
23618 	boolean_t attach_if, hwaccel;
23619 	uint32_t flags = IP6_NO_IPPOLICY;
23620 	int match_flags;
23621 	zoneid_t zoneid;
23622 	boolean_t ill_need_rele = B_FALSE;
23623 	boolean_t ire_need_rele = B_FALSE;
23624 
23625 	mp = ipsec_mp->b_cont;
23626 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23627 	ill_index = io->ipsec_out_ill_index;
23628 	if (io->ipsec_out_reachable) {
23629 		flags |= IPV6_REACHABILITY_CONFIRMATION;
23630 	}
23631 	attach_if = io->ipsec_out_attach_if;
23632 	hwaccel = io->ipsec_out_accelerated;
23633 	zoneid = io->ipsec_out_zoneid;
23634 	ASSERT(zoneid != ALL_ZONES);
23635 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23636 	/* Multicast addresses should have non-zero ill_index. */
23637 	v6dstp = &ip6h->ip6_dst;
23638 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
23639 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
23640 	ASSERT(!attach_if || ill_index != 0);
23641 	if (ill_index != 0) {
23642 		if (ill == NULL) {
23643 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
23644 			    B_TRUE);
23645 
23646 			/* Failure case frees things for us. */
23647 			if (ill == NULL)
23648 				return;
23649 
23650 			ill_need_rele = B_TRUE;
23651 		}
23652 		/*
23653 		 * If this packet needs to go out on a particular interface
23654 		 * honor it.
23655 		 */
23656 		if (attach_if) {
23657 			match_flags = MATCH_IRE_ILL;
23658 
23659 			/*
23660 			 * Check if we need an ire that will not be
23661 			 * looked up by anybody else i.e. HIDDEN.
23662 			 */
23663 			if (ill_is_probeonly(ill)) {
23664 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23665 			}
23666 		}
23667 	}
23668 	ASSERT(mp != NULL);
23669 
23670 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
23671 		boolean_t unspec_src;
23672 		ipif_t	*ipif;
23673 
23674 		/*
23675 		 * Use the ill_index to get the right ill.
23676 		 */
23677 		unspec_src = io->ipsec_out_unspec_src;
23678 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23679 		if (ipif == NULL) {
23680 			if (ill_need_rele)
23681 				ill_refrele(ill);
23682 			freemsg(ipsec_mp);
23683 			return;
23684 		}
23685 
23686 		if (ire_arg != NULL) {
23687 			ire = ire_arg;
23688 		} else {
23689 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23690 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23691 			ire_need_rele = B_TRUE;
23692 		}
23693 		if (ire != NULL) {
23694 			ipif_refrele(ipif);
23695 			/*
23696 			 * XXX Do the multicast forwarding now, as the IPSEC
23697 			 * processing has been done.
23698 			 */
23699 			goto send;
23700 		}
23701 
23702 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
23703 		mp->b_prev = NULL;
23704 		mp->b_next = NULL;
23705 
23706 		/*
23707 		 * If the IPsec packet was processed asynchronously,
23708 		 * drop it now.
23709 		 */
23710 		if (q == NULL) {
23711 			if (ill_need_rele)
23712 				ill_refrele(ill);
23713 			freemsg(ipsec_mp);
23714 			return;
23715 		}
23716 
23717 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
23718 		    unspec_src, zoneid);
23719 		ipif_refrele(ipif);
23720 	} else {
23721 		if (attach_if) {
23722 			ipif_t	*ipif;
23723 
23724 			ipif = ipif_get_next_ipif(NULL, ill);
23725 			if (ipif == NULL) {
23726 				if (ill_need_rele)
23727 					ill_refrele(ill);
23728 				freemsg(ipsec_mp);
23729 				return;
23730 			}
23731 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23732 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23733 			ire_need_rele = B_TRUE;
23734 			ipif_refrele(ipif);
23735 		} else {
23736 			if (ire_arg != NULL) {
23737 				ire = ire_arg;
23738 			} else {
23739 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
23740 				ire_need_rele = B_TRUE;
23741 			}
23742 		}
23743 		if (ire != NULL)
23744 			goto send;
23745 		/*
23746 		 * ire disappeared underneath.
23747 		 *
23748 		 * What we need to do here is the ip_newroute
23749 		 * logic to get the ire without doing the IPSEC
23750 		 * processing. Follow the same old path. But this
23751 		 * time, ip_wput or ire_add_then_send will call us
23752 		 * directly as all the IPSEC operations are done.
23753 		 */
23754 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
23755 		mp->b_prev = NULL;
23756 		mp->b_next = NULL;
23757 
23758 		/*
23759 		 * If the IPsec packet was processed asynchronously,
23760 		 * drop it now.
23761 		 */
23762 		if (q == NULL) {
23763 			if (ill_need_rele)
23764 				ill_refrele(ill);
23765 			freemsg(ipsec_mp);
23766 			return;
23767 		}
23768 
23769 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
23770 		    zoneid);
23771 	}
23772 	if (ill != NULL && ill_need_rele)
23773 		ill_refrele(ill);
23774 	return;
23775 send:
23776 	if (ill != NULL && ill_need_rele)
23777 		ill_refrele(ill);
23778 
23779 	/* Local delivery */
23780 	if (ire->ire_stq == NULL) {
23781 		ASSERT(q != NULL);
23782 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
23783 		    ire, 0);
23784 		if (ire_need_rele)
23785 			ire_refrele(ire);
23786 		return;
23787 	}
23788 	/*
23789 	 * Everything is done. Send it out on the wire.
23790 	 * We force the insertion of a fragment header using the
23791 	 * IPH_FRAG_HDR flag in two cases:
23792 	 * - after reception of an ICMPv6 "packet too big" message
23793 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
23794 	 * - for multirouted IPv6 packets, so that the receiver can
23795 	 *   discard duplicates according to their fragment identifier
23796 	 */
23797 	/* XXX fix flow control problems. */
23798 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
23799 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
23800 		if (hwaccel) {
23801 			/*
23802 			 * hardware acceleration does not handle these
23803 			 * "slow path" cases.
23804 			 */
23805 			/* IPsec KSTATS: should bump bean counter here. */
23806 			if (ire_need_rele)
23807 				ire_refrele(ire);
23808 			freemsg(ipsec_mp);
23809 			return;
23810 		}
23811 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
23812 		    (mp->b_cont ? msgdsize(mp) :
23813 		    mp->b_wptr - (uchar_t *)ip6h)) {
23814 			/* IPsec KSTATS: should bump bean counter here. */
23815 			ip0dbg(("Packet length mismatch: %d, %ld\n",
23816 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
23817 			    msgdsize(mp)));
23818 			if (ire_need_rele)
23819 				ire_refrele(ire);
23820 			freemsg(ipsec_mp);
23821 			return;
23822 		}
23823 		ASSERT(mp->b_prev == NULL);
23824 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
23825 		    ntohs(ip6h->ip6_plen) +
23826 		    IPV6_HDR_LEN, ire->ire_max_frag));
23827 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
23828 		    ire->ire_max_frag);
23829 	} else {
23830 		UPDATE_OB_PKT_COUNT(ire);
23831 		ire->ire_last_used_time = lbolt;
23832 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
23833 	}
23834 	if (ire_need_rele)
23835 		ire_refrele(ire);
23836 	freeb(ipsec_mp);
23837 }
23838 
23839 void
23840 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23841 {
23842 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23843 	da_ipsec_t *hada;	/* data attributes */
23844 	ill_t *ill = (ill_t *)q->q_ptr;
23845 
23846 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23847 
23848 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23849 		/* IPsec KSTATS: Bump lose counter here! */
23850 		freemsg(mp);
23851 		return;
23852 	}
23853 
23854 	/*
23855 	 * It's an IPsec packet that must be
23856 	 * accelerated by the Provider, and the
23857 	 * outbound ill is IPsec acceleration capable.
23858 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23859 	 * to the ill.
23860 	 * IPsec KSTATS: should bump packet counter here.
23861 	 */
23862 
23863 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23864 	if (hada_mp == NULL) {
23865 		/* IPsec KSTATS: should bump packet counter here. */
23866 		freemsg(mp);
23867 		return;
23868 	}
23869 
23870 	hada_mp->b_datap->db_type = M_CTL;
23871 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23872 	hada_mp->b_cont = mp;
23873 
23874 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23875 	bzero(hada, sizeof (da_ipsec_t));
23876 	hada->da_type = IPHADA_M_CTL;
23877 
23878 	putnext(q, hada_mp);
23879 }
23880 
23881 /*
23882  * Finish the outbound IPsec processing. This function is called from
23883  * ipsec_out_process() if the IPsec packet was processed
23884  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23885  * asynchronously.
23886  */
23887 void
23888 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23889     ire_t *ire_arg)
23890 {
23891 	uint32_t v_hlen_tos_len;
23892 	ipaddr_t	dst;
23893 	ipif_t	*ipif = NULL;
23894 	ire_t *ire;
23895 	ire_t *ire1 = NULL;
23896 	mblk_t *next_mp = NULL;
23897 	uint32_t max_frag;
23898 	boolean_t multirt_send = B_FALSE;
23899 	mblk_t *mp;
23900 	mblk_t *mp1;
23901 	uint_t	ill_index;
23902 	ipsec_out_t *io;
23903 	boolean_t attach_if;
23904 	int match_flags, offset;
23905 	irb_t *irb = NULL;
23906 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23907 	zoneid_t zoneid;
23908 	uint32_t cksum;
23909 	uint16_t *up;
23910 #ifdef	_BIG_ENDIAN
23911 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23912 #else
23913 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23914 #endif
23915 
23916 	mp = ipsec_mp->b_cont;
23917 	ASSERT(mp != NULL);
23918 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23919 	dst = ipha->ipha_dst;
23920 
23921 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23922 	ill_index = io->ipsec_out_ill_index;
23923 	attach_if = io->ipsec_out_attach_if;
23924 	zoneid = io->ipsec_out_zoneid;
23925 	ASSERT(zoneid != ALL_ZONES);
23926 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23927 	if (ill_index != 0) {
23928 		if (ill == NULL) {
23929 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23930 			    ill_index, B_FALSE);
23931 
23932 			/* Failure case frees things for us. */
23933 			if (ill == NULL)
23934 				return;
23935 
23936 			ill_need_rele = B_TRUE;
23937 		}
23938 		/*
23939 		 * If this packet needs to go out on a particular interface
23940 		 * honor it.
23941 		 */
23942 		if (attach_if) {
23943 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
23944 
23945 			/*
23946 			 * Check if we need an ire that will not be
23947 			 * looked up by anybody else i.e. HIDDEN.
23948 			 */
23949 			if (ill_is_probeonly(ill)) {
23950 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23951 			}
23952 		}
23953 	}
23954 
23955 	if (CLASSD(dst)) {
23956 		boolean_t conn_dontroute;
23957 		/*
23958 		 * Use the ill_index to get the right ipif.
23959 		 */
23960 		conn_dontroute = io->ipsec_out_dontroute;
23961 		if (ill_index == 0)
23962 			ipif = ipif_lookup_group(dst, zoneid);
23963 		else
23964 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23965 		if (ipif == NULL) {
23966 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23967 			    " multicast\n"));
23968 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23969 			freemsg(ipsec_mp);
23970 			goto done;
23971 		}
23972 		/*
23973 		 * ipha_src has already been intialized with the
23974 		 * value of the ipif in ip_wput. All we need now is
23975 		 * an ire to send this downstream.
23976 		 */
23977 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
23978 		    MBLK_GETLABEL(mp), match_flags);
23979 		if (ire != NULL) {
23980 			ill_t *ill1;
23981 			/*
23982 			 * Do the multicast forwarding now, as the IPSEC
23983 			 * processing has been done.
23984 			 */
23985 			if (ip_g_mrouter && !conn_dontroute &&
23986 			    (ill1 = ire_to_ill(ire))) {
23987 				if (ip_mforward(ill1, ipha, mp)) {
23988 					freemsg(ipsec_mp);
23989 					ip1dbg(("ip_wput_ipsec_out: mforward "
23990 					    "failed\n"));
23991 					ire_refrele(ire);
23992 					goto done;
23993 				}
23994 			}
23995 			goto send;
23996 		}
23997 
23998 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
23999 		mp->b_prev = NULL;
24000 		mp->b_next = NULL;
24001 
24002 		/*
24003 		 * If the IPsec packet was processed asynchronously,
24004 		 * drop it now.
24005 		 */
24006 		if (q == NULL) {
24007 			freemsg(ipsec_mp);
24008 			goto done;
24009 		}
24010 
24011 		/*
24012 		 * We may be using a wrong ipif to create the ire.
24013 		 * But it is okay as the source address is assigned
24014 		 * for the packet already. Next outbound packet would
24015 		 * create the IRE with the right IPIF in ip_wput.
24016 		 *
24017 		 * Also handle RTF_MULTIRT routes.
24018 		 */
24019 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24020 	} else {
24021 		if (attach_if) {
24022 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24023 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24024 		} else {
24025 			if (ire_arg != NULL) {
24026 				ire = ire_arg;
24027 				ire_need_rele = B_FALSE;
24028 			} else {
24029 				ire = ire_cache_lookup(dst, zoneid,
24030 				    MBLK_GETLABEL(mp));
24031 			}
24032 		}
24033 		if (ire != NULL) {
24034 			goto send;
24035 		}
24036 
24037 		/*
24038 		 * ire disappeared underneath.
24039 		 *
24040 		 * What we need to do here is the ip_newroute
24041 		 * logic to get the ire without doing the IPSEC
24042 		 * processing. Follow the same old path. But this
24043 		 * time, ip_wput or ire_add_then_put will call us
24044 		 * directly as all the IPSEC operations are done.
24045 		 */
24046 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24047 		mp->b_prev = NULL;
24048 		mp->b_next = NULL;
24049 
24050 		/*
24051 		 * If the IPsec packet was processed asynchronously,
24052 		 * drop it now.
24053 		 */
24054 		if (q == NULL) {
24055 			freemsg(ipsec_mp);
24056 			goto done;
24057 		}
24058 
24059 		/*
24060 		 * Since we're going through ip_newroute() again, we
24061 		 * need to make sure we don't:
24062 		 *
24063 		 *	1.) Trigger the ASSERT() with the ipha_ident
24064 		 *	    overloading.
24065 		 *	2.) Redo transport-layer checksumming, since we've
24066 		 *	    already done all that to get this far.
24067 		 *
24068 		 * The easiest way not do either of the above is to set
24069 		 * the ipha_ident field to IP_HDR_INCLUDED.
24070 		 */
24071 		ipha->ipha_ident = IP_HDR_INCLUDED;
24072 		ip_newroute(q, ipsec_mp, dst, NULL,
24073 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24074 	}
24075 	goto done;
24076 send:
24077 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24078 		/*
24079 		 * ESP NAT-Traversal packet.
24080 		 *
24081 		 * Just do software checksum for now.
24082 		 */
24083 
24084 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24085 		IP_STAT(ip_out_sw_cksum);
24086 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24087 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24088 #define	iphs	((uint16_t *)ipha)
24089 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24090 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24091 		    IP_SIMPLE_HDR_LENGTH);
24092 #undef iphs
24093 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24094 			cksum = 0xFFFF;
24095 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24096 			if (mp1->b_wptr - mp1->b_rptr >=
24097 			    offset + sizeof (uint16_t)) {
24098 				up = (uint16_t *)(mp1->b_rptr + offset);
24099 				*up = cksum;
24100 				break;	/* out of for loop */
24101 			} else {
24102 				offset -= (mp->b_wptr - mp->b_rptr);
24103 			}
24104 	} /* Otherwise, just keep the all-zero checksum. */
24105 
24106 	if (ire->ire_stq == NULL) {
24107 		/*
24108 		 * Loopbacks go through ip_wput_local except for one case.
24109 		 * We come here if we generate a icmp_frag_needed message
24110 		 * after IPSEC processing is over. When this function calls
24111 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24112 		 * icmp_frag_needed. The message generated comes back here
24113 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24114 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24115 		 * source address as it is usually set in ip_wput_ire. As
24116 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24117 		 * and we end up here. We can't enter ip_wput_ire once the
24118 		 * IPSEC processing is over and hence we need to do it here.
24119 		 */
24120 		ASSERT(q != NULL);
24121 		UPDATE_OB_PKT_COUNT(ire);
24122 		ire->ire_last_used_time = lbolt;
24123 		if (ipha->ipha_src == 0)
24124 			ipha->ipha_src = ire->ire_src_addr;
24125 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24126 		    ire, 0, zoneid);
24127 		if (ire_need_rele)
24128 			ire_refrele(ire);
24129 		goto done;
24130 	}
24131 
24132 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24133 		/*
24134 		 * We are through with IPSEC processing.
24135 		 * Fragment this and send it on the wire.
24136 		 */
24137 		if (io->ipsec_out_accelerated) {
24138 			/*
24139 			 * The packet has been accelerated but must
24140 			 * be fragmented. This should not happen
24141 			 * since AH and ESP must not accelerate
24142 			 * packets that need fragmentation, however
24143 			 * the configuration could have changed
24144 			 * since the AH or ESP processing.
24145 			 * Drop packet.
24146 			 * IPsec KSTATS: bump bean counter here.
24147 			 */
24148 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24149 			    "fragmented accelerated packet!\n"));
24150 			freemsg(ipsec_mp);
24151 		} else {
24152 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24153 		}
24154 		if (ire_need_rele)
24155 			ire_refrele(ire);
24156 		goto done;
24157 	}
24158 
24159 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24160 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24161 	    (void *)ire->ire_ipif, (void *)ipif));
24162 
24163 	/*
24164 	 * Multiroute the secured packet, unless IPsec really
24165 	 * requires the packet to go out only through a particular
24166 	 * interface.
24167 	 */
24168 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24169 		ire_t *first_ire;
24170 		irb = ire->ire_bucket;
24171 		ASSERT(irb != NULL);
24172 		/*
24173 		 * This ire has been looked up as the one that
24174 		 * goes through the given ipif;
24175 		 * make sure we do not omit any other multiroute ire
24176 		 * that may be present in the bucket before this one.
24177 		 */
24178 		IRB_REFHOLD(irb);
24179 		for (first_ire = irb->irb_ire;
24180 		    first_ire != NULL;
24181 		    first_ire = first_ire->ire_next) {
24182 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24183 			    (first_ire->ire_addr == ire->ire_addr) &&
24184 			    !(first_ire->ire_marks &
24185 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24186 				break;
24187 		}
24188 
24189 		if ((first_ire != NULL) && (first_ire != ire)) {
24190 			/*
24191 			 * Don't change the ire if the packet must
24192 			 * be fragmented if sent via this new one.
24193 			 */
24194 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24195 				IRE_REFHOLD(first_ire);
24196 				if (ire_need_rele)
24197 					ire_refrele(ire);
24198 				else
24199 					ire_need_rele = B_TRUE;
24200 				ire = first_ire;
24201 			}
24202 		}
24203 		IRB_REFRELE(irb);
24204 
24205 		multirt_send = B_TRUE;
24206 		max_frag = ire->ire_max_frag;
24207 	} else {
24208 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24209 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24210 			    "flag, attach_if %d\n", attach_if));
24211 		}
24212 	}
24213 
24214 	/*
24215 	 * In most cases, the emission loop below is entered only once.
24216 	 * Only in the case where the ire holds the RTF_MULTIRT
24217 	 * flag, we loop to process all RTF_MULTIRT ires in the
24218 	 * bucket, and send the packet through all crossed
24219 	 * RTF_MULTIRT routes.
24220 	 */
24221 	do {
24222 		if (multirt_send) {
24223 			/*
24224 			 * ire1 holds here the next ire to process in the
24225 			 * bucket. If multirouting is expected,
24226 			 * any non-RTF_MULTIRT ire that has the
24227 			 * right destination address is ignored.
24228 			 */
24229 			ASSERT(irb != NULL);
24230 			IRB_REFHOLD(irb);
24231 			for (ire1 = ire->ire_next;
24232 			    ire1 != NULL;
24233 			    ire1 = ire1->ire_next) {
24234 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24235 					continue;
24236 				if (ire1->ire_addr != ire->ire_addr)
24237 					continue;
24238 				if (ire1->ire_marks &
24239 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24240 					continue;
24241 				/* No loopback here */
24242 				if (ire1->ire_stq == NULL)
24243 					continue;
24244 				/*
24245 				 * Ensure we do not exceed the MTU
24246 				 * of the next route.
24247 				 */
24248 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24249 					ip_multirt_bad_mtu(ire1, max_frag);
24250 					continue;
24251 				}
24252 
24253 				IRE_REFHOLD(ire1);
24254 				break;
24255 			}
24256 			IRB_REFRELE(irb);
24257 			if (ire1 != NULL) {
24258 				/*
24259 				 * We are in a multiple send case, need to
24260 				 * make a copy of the packet.
24261 				 */
24262 				next_mp = copymsg(ipsec_mp);
24263 				if (next_mp == NULL) {
24264 					ire_refrele(ire1);
24265 					ire1 = NULL;
24266 				}
24267 			}
24268 		}
24269 
24270 		/* Everything is done. Send it out on the wire */
24271 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
24272 		if (mp1 == NULL) {
24273 			BUMP_MIB(&ip_mib, ipOutDiscards);
24274 			freemsg(ipsec_mp);
24275 			if (ire_need_rele)
24276 				ire_refrele(ire);
24277 			if (ire1 != NULL) {
24278 				ire_refrele(ire1);
24279 				freemsg(next_mp);
24280 			}
24281 			goto done;
24282 		}
24283 		UPDATE_OB_PKT_COUNT(ire);
24284 		ire->ire_last_used_time = lbolt;
24285 		if (!io->ipsec_out_accelerated) {
24286 			putnext(ire->ire_stq, mp1);
24287 		} else {
24288 			/*
24289 			 * Safety Pup says: make sure this is going to
24290 			 * the right interface!
24291 			 */
24292 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
24293 			int ifindex = ill1->ill_phyint->phyint_ifindex;
24294 
24295 			if (ifindex != io->ipsec_out_capab_ill_index) {
24296 				/* IPsec kstats: bump lose counter */
24297 				freemsg(mp1);
24298 			} else {
24299 				ipsec_hw_putnext(ire->ire_stq, mp1);
24300 			}
24301 		}
24302 
24303 		freeb(ipsec_mp);
24304 		if (ire_need_rele)
24305 			ire_refrele(ire);
24306 
24307 		if (ire1 != NULL) {
24308 			ire = ire1;
24309 			ire_need_rele = B_TRUE;
24310 			ASSERT(next_mp);
24311 			ipsec_mp = next_mp;
24312 			mp = ipsec_mp->b_cont;
24313 			ire1 = NULL;
24314 			next_mp = NULL;
24315 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
24316 		} else {
24317 			multirt_send = B_FALSE;
24318 		}
24319 	} while (multirt_send);
24320 done:
24321 	if (ill != NULL && ill_need_rele)
24322 		ill_refrele(ill);
24323 	if (ipif != NULL)
24324 		ipif_refrele(ipif);
24325 }
24326 
24327 /*
24328  * Get the ill corresponding to the specified ire, and compare its
24329  * capabilities with the protocol and algorithms specified by the
24330  * the SA obtained from ipsec_out. If they match, annotate the
24331  * ipsec_out structure to indicate that the packet needs acceleration.
24332  *
24333  *
24334  * A packet is eligible for outbound hardware acceleration if the
24335  * following conditions are satisfied:
24336  *
24337  * 1. the packet will not be fragmented
24338  * 2. the provider supports the algorithm
24339  * 3. there is no pending control message being exchanged
24340  * 4. snoop is not attached
24341  * 5. the destination address is not a broadcast or multicast address.
24342  *
24343  * Rationale:
24344  *	- Hardware drivers do not support fragmentation with
24345  *	  the current interface.
24346  *	- snoop, multicast, and broadcast may result in exposure of
24347  *	  a cleartext datagram.
24348  * We check all five of these conditions here.
24349  *
24350  * XXX would like to nuke "ire_t *" parameter here; problem is that
24351  * IRE is only way to figure out if a v4 address is a broadcast and
24352  * thus ineligible for acceleration...
24353  */
24354 static void
24355 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
24356 {
24357 	ipsec_out_t *io;
24358 	mblk_t *data_mp;
24359 	uint_t plen, overhead;
24360 
24361 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
24362 		return;
24363 
24364 	if (ill == NULL)
24365 		return;
24366 
24367 	/*
24368 	 * Destination address is a broadcast or multicast.  Punt.
24369 	 */
24370 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
24371 	    IRE_LOCAL)))
24372 		return;
24373 
24374 	data_mp = ipsec_mp->b_cont;
24375 
24376 	if (ill->ill_isv6) {
24377 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
24378 
24379 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
24380 			return;
24381 
24382 		plen = ip6h->ip6_plen;
24383 	} else {
24384 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
24385 
24386 		if (CLASSD(ipha->ipha_dst))
24387 			return;
24388 
24389 		plen = ipha->ipha_length;
24390 	}
24391 	/*
24392 	 * Is there a pending DLPI control message being exchanged
24393 	 * between IP/IPsec and the DLS Provider? If there is, it
24394 	 * could be a SADB update, and the state of the DLS Provider
24395 	 * SADB might not be in sync with the SADB maintained by
24396 	 * IPsec. To avoid dropping packets or using the wrong keying
24397 	 * material, we do not accelerate this packet.
24398 	 */
24399 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
24400 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24401 		    "ill_dlpi_pending! don't accelerate packet\n"));
24402 		return;
24403 	}
24404 
24405 	/*
24406 	 * Is the Provider in promiscous mode? If it does, we don't
24407 	 * accelerate the packet since it will bounce back up to the
24408 	 * listeners in the clear.
24409 	 */
24410 	if (ill->ill_promisc_on_phys) {
24411 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24412 		    "ill in promiscous mode, don't accelerate packet\n"));
24413 		return;
24414 	}
24415 
24416 	/*
24417 	 * Will the packet require fragmentation?
24418 	 */
24419 
24420 	/*
24421 	 * IPsec ESP note: this is a pessimistic estimate, but the same
24422 	 * as is used elsewhere.
24423 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
24424 	 *	+ 2-byte trailer
24425 	 */
24426 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
24427 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
24428 
24429 	if ((plen + overhead) > ill->ill_max_mtu)
24430 		return;
24431 
24432 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24433 
24434 	/*
24435 	 * Can the ill accelerate this IPsec protocol and algorithm
24436 	 * specified by the SA?
24437 	 */
24438 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
24439 	    ill->ill_isv6, sa)) {
24440 		return;
24441 	}
24442 
24443 	/*
24444 	 * Tell AH or ESP that the outbound ill is capable of
24445 	 * accelerating this packet.
24446 	 */
24447 	io->ipsec_out_is_capab_ill = B_TRUE;
24448 }
24449 
24450 /*
24451  * Select which AH & ESP SA's to use (if any) for the outbound packet.
24452  *
24453  * If this function returns B_TRUE, the requested SA's have been filled
24454  * into the ipsec_out_*_sa pointers.
24455  *
24456  * If the function returns B_FALSE, the packet has been "consumed", most
24457  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
24458  *
24459  * The SA references created by the protocol-specific "select"
24460  * function will be released when the ipsec_mp is freed, thanks to the
24461  * ipsec_out_free destructor -- see spd.c.
24462  */
24463 static boolean_t
24464 ipsec_out_select_sa(mblk_t *ipsec_mp)
24465 {
24466 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
24467 	ipsec_out_t *io;
24468 	ipsec_policy_t *pp;
24469 	ipsec_action_t *ap;
24470 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24471 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24472 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24473 
24474 	if (!io->ipsec_out_secure) {
24475 		/*
24476 		 * We came here by mistake.
24477 		 * Don't bother with ipsec processing
24478 		 * We should "discourage" this path in the future.
24479 		 */
24480 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24481 		return (B_FALSE);
24482 	}
24483 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24484 	ASSERT((io->ipsec_out_policy != NULL) ||
24485 	    (io->ipsec_out_act != NULL));
24486 
24487 	ASSERT(io->ipsec_out_failed == B_FALSE);
24488 
24489 	/*
24490 	 * IPSEC processing has started.
24491 	 */
24492 	io->ipsec_out_proc_begin = B_TRUE;
24493 	ap = io->ipsec_out_act;
24494 	if (ap == NULL) {
24495 		pp = io->ipsec_out_policy;
24496 		ASSERT(pp != NULL);
24497 		ap = pp->ipsp_act;
24498 		ASSERT(ap != NULL);
24499 	}
24500 
24501 	/*
24502 	 * We have an action.  now, let's select SA's.
24503 	 * (In the future, we can cache this in the conn_t..)
24504 	 */
24505 	if (ap->ipa_want_esp) {
24506 		if (io->ipsec_out_esp_sa == NULL) {
24507 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
24508 			    IPPROTO_ESP);
24509 		}
24510 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
24511 	}
24512 
24513 	if (ap->ipa_want_ah) {
24514 		if (io->ipsec_out_ah_sa == NULL) {
24515 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
24516 			    IPPROTO_AH);
24517 		}
24518 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
24519 		/*
24520 		 * The ESP and AH processing order needs to be preserved
24521 		 * when both protocols are required (ESP should be applied
24522 		 * before AH for an outbound packet). Force an ESP ACQUIRE
24523 		 * when both ESP and AH are required, and an AH ACQUIRE
24524 		 * is needed.
24525 		 */
24526 		if (ap->ipa_want_esp && need_ah_acquire)
24527 			need_esp_acquire = B_TRUE;
24528 	}
24529 
24530 	/*
24531 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
24532 	 * Release SAs that got referenced, but will not be used until we
24533 	 * acquire _all_ of the SAs we need.
24534 	 */
24535 	if (need_ah_acquire || need_esp_acquire) {
24536 		if (io->ipsec_out_ah_sa != NULL) {
24537 			IPSA_REFRELE(io->ipsec_out_ah_sa);
24538 			io->ipsec_out_ah_sa = NULL;
24539 		}
24540 		if (io->ipsec_out_esp_sa != NULL) {
24541 			IPSA_REFRELE(io->ipsec_out_esp_sa);
24542 			io->ipsec_out_esp_sa = NULL;
24543 		}
24544 
24545 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
24546 		return (B_FALSE);
24547 	}
24548 
24549 	return (B_TRUE);
24550 }
24551 
24552 /*
24553  * Process an IPSEC_OUT message and see what you can
24554  * do with it.
24555  * IPQoS Notes:
24556  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
24557  * IPSec.
24558  * XXX would like to nuke ire_t.
24559  * XXX ill_index better be "real"
24560  */
24561 void
24562 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
24563 {
24564 	ipsec_out_t *io;
24565 	ipsec_policy_t *pp;
24566 	ipsec_action_t *ap;
24567 	ipha_t *ipha;
24568 	ip6_t *ip6h;
24569 	mblk_t *mp;
24570 	ill_t *ill;
24571 	zoneid_t zoneid;
24572 	ipsec_status_t ipsec_rc;
24573 	boolean_t ill_need_rele = B_FALSE;
24574 
24575 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24576 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24577 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24578 	mp = ipsec_mp->b_cont;
24579 
24580 	/*
24581 	 * Initiate IPPF processing. We do it here to account for packets
24582 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
24583 	 * We can check for ipsec_out_proc_begin even for such packets, as
24584 	 * they will always be false (asserted below).
24585 	 */
24586 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
24587 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
24588 		    io->ipsec_out_ill_index : ill_index);
24589 		if (mp == NULL) {
24590 			ip2dbg(("ipsec_out_process: packet dropped "\
24591 			    "during IPPF processing\n"));
24592 			freeb(ipsec_mp);
24593 			BUMP_MIB(&ip_mib, ipOutDiscards);
24594 			return;
24595 		}
24596 	}
24597 
24598 	if (!io->ipsec_out_secure) {
24599 		/*
24600 		 * We came here by mistake.
24601 		 * Don't bother with ipsec processing
24602 		 * Should "discourage" this path in the future.
24603 		 */
24604 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24605 		goto done;
24606 	}
24607 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24608 	ASSERT((io->ipsec_out_policy != NULL) ||
24609 	    (io->ipsec_out_act != NULL));
24610 	ASSERT(io->ipsec_out_failed == B_FALSE);
24611 
24612 	if (!ipsec_loaded()) {
24613 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
24614 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24615 			BUMP_MIB(&ip_mib, ipOutDiscards);
24616 		} else {
24617 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
24618 		}
24619 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
24620 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
24621 		return;
24622 	}
24623 
24624 	/*
24625 	 * IPSEC processing has started.
24626 	 */
24627 	io->ipsec_out_proc_begin = B_TRUE;
24628 	ap = io->ipsec_out_act;
24629 	if (ap == NULL) {
24630 		pp = io->ipsec_out_policy;
24631 		ASSERT(pp != NULL);
24632 		ap = pp->ipsp_act;
24633 		ASSERT(ap != NULL);
24634 	}
24635 
24636 	/*
24637 	 * Save the outbound ill index. When the packet comes back
24638 	 * from IPsec, we make sure the ill hasn't changed or disappeared
24639 	 * before sending it the accelerated packet.
24640 	 */
24641 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
24642 		int ifindex;
24643 		ill = ire_to_ill(ire);
24644 		ifindex = ill->ill_phyint->phyint_ifindex;
24645 		io->ipsec_out_capab_ill_index = ifindex;
24646 	}
24647 
24648 	/*
24649 	 * The order of processing is first insert a IP header if needed.
24650 	 * Then insert the ESP header and then the AH header.
24651 	 */
24652 	if ((io->ipsec_out_se_done == B_FALSE) &&
24653 	    (ap->ipa_want_se)) {
24654 		/*
24655 		 * First get the outer IP header before sending
24656 		 * it to ESP.
24657 		 */
24658 		ipha_t *oipha, *iipha;
24659 		mblk_t *outer_mp, *inner_mp;
24660 
24661 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
24662 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
24663 			    "ipsec_out_process: "
24664 			    "Self-Encapsulation failed: Out of memory\n");
24665 			freemsg(ipsec_mp);
24666 			BUMP_MIB(&ip_mib, ipOutDiscards);
24667 			return;
24668 		}
24669 		inner_mp = ipsec_mp->b_cont;
24670 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
24671 		oipha = (ipha_t *)outer_mp->b_rptr;
24672 		iipha = (ipha_t *)inner_mp->b_rptr;
24673 		*oipha = *iipha;
24674 		outer_mp->b_wptr += sizeof (ipha_t);
24675 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
24676 		    sizeof (ipha_t));
24677 		oipha->ipha_protocol = IPPROTO_ENCAP;
24678 		oipha->ipha_version_and_hdr_length =
24679 		    IP_SIMPLE_HDR_VERSION;
24680 		oipha->ipha_hdr_checksum = 0;
24681 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
24682 		outer_mp->b_cont = inner_mp;
24683 		ipsec_mp->b_cont = outer_mp;
24684 
24685 		io->ipsec_out_se_done = B_TRUE;
24686 		io->ipsec_out_encaps = B_TRUE;
24687 	}
24688 
24689 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
24690 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
24691 	    !ipsec_out_select_sa(ipsec_mp))
24692 		return;
24693 
24694 	/*
24695 	 * By now, we know what SA's to use.  Toss over to ESP & AH
24696 	 * to do the heavy lifting.
24697 	 */
24698 	zoneid = io->ipsec_out_zoneid;
24699 	ASSERT(zoneid != ALL_ZONES);
24700 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
24701 		ASSERT(io->ipsec_out_esp_sa != NULL);
24702 		io->ipsec_out_esp_done = B_TRUE;
24703 		/*
24704 		 * Note that since hw accel can only apply one transform,
24705 		 * not two, we skip hw accel for ESP if we also have AH
24706 		 * This is an design limitation of the interface
24707 		 * which should be revisited.
24708 		 */
24709 		ASSERT(ire != NULL);
24710 		if (io->ipsec_out_ah_sa == NULL) {
24711 			ill = (ill_t *)ire->ire_stq->q_ptr;
24712 			ipsec_out_is_accelerated(ipsec_mp,
24713 			    io->ipsec_out_esp_sa, ill, ire);
24714 		}
24715 
24716 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
24717 		switch (ipsec_rc) {
24718 		case IPSEC_STATUS_SUCCESS:
24719 			break;
24720 		case IPSEC_STATUS_FAILED:
24721 			BUMP_MIB(&ip_mib, ipOutDiscards);
24722 			/* FALLTHRU */
24723 		case IPSEC_STATUS_PENDING:
24724 			return;
24725 		}
24726 	}
24727 
24728 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
24729 		ASSERT(io->ipsec_out_ah_sa != NULL);
24730 		io->ipsec_out_ah_done = B_TRUE;
24731 		if (ire == NULL) {
24732 			int idx = io->ipsec_out_capab_ill_index;
24733 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
24734 			    NULL, NULL, NULL, NULL);
24735 			ill_need_rele = B_TRUE;
24736 		} else {
24737 			ill = (ill_t *)ire->ire_stq->q_ptr;
24738 		}
24739 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
24740 		    ire);
24741 
24742 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
24743 		switch (ipsec_rc) {
24744 		case IPSEC_STATUS_SUCCESS:
24745 			break;
24746 		case IPSEC_STATUS_FAILED:
24747 			BUMP_MIB(&ip_mib, ipOutDiscards);
24748 			/* FALLTHRU */
24749 		case IPSEC_STATUS_PENDING:
24750 			if (ill != NULL && ill_need_rele)
24751 				ill_refrele(ill);
24752 			return;
24753 		}
24754 	}
24755 	/*
24756 	 * We are done with IPSEC processing. Send it over
24757 	 * the wire.
24758 	 */
24759 done:
24760 	mp = ipsec_mp->b_cont;
24761 	ipha = (ipha_t *)mp->b_rptr;
24762 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24763 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
24764 	} else {
24765 		ip6h = (ip6_t *)ipha;
24766 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
24767 	}
24768 	if (ill != NULL && ill_need_rele)
24769 		ill_refrele(ill);
24770 }
24771 
24772 /* ARGSUSED */
24773 void
24774 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
24775 {
24776 	opt_restart_t	*or;
24777 	int	err;
24778 	conn_t	*connp;
24779 
24780 	ASSERT(CONN_Q(q));
24781 	connp = Q_TO_CONN(q);
24782 
24783 	ASSERT(first_mp->b_datap->db_type == M_CTL);
24784 	or = (opt_restart_t *)first_mp->b_rptr;
24785 	/*
24786 	 * We don't need to pass any credentials here since this is just
24787 	 * a restart. The credentials are passed in when svr4_optcom_req
24788 	 * is called the first time (from ip_wput_nondata).
24789 	 */
24790 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
24791 		err = svr4_optcom_req(q, first_mp, NULL,
24792 		    &ip_opt_obj);
24793 	} else {
24794 		ASSERT(or->or_type == T_OPTMGMT_REQ);
24795 		err = tpi_optcom_req(q, first_mp, NULL,
24796 		    &ip_opt_obj);
24797 	}
24798 	if (err != EINPROGRESS) {
24799 		/* operation is done */
24800 		CONN_OPER_PENDING_DONE(connp);
24801 	}
24802 }
24803 
24804 /*
24805  * ioctls that go through a down/up sequence may need to wait for the down
24806  * to complete. This involves waiting for the ire and ipif refcnts to go down
24807  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
24808  */
24809 /* ARGSUSED */
24810 void
24811 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24812 {
24813 	struct iocblk *iocp;
24814 	mblk_t *mp1;
24815 	ipif_t	*ipif;
24816 	ip_ioctl_cmd_t *ipip;
24817 	int err;
24818 	sin_t	*sin;
24819 	struct lifreq *lifr;
24820 	struct ifreq *ifr;
24821 
24822 	iocp = (struct iocblk *)mp->b_rptr;
24823 	ASSERT(ipsq != NULL);
24824 	/* Existence of mp1 verified in ip_wput_nondata */
24825 	mp1 = mp->b_cont->b_cont;
24826 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24827 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
24828 		ill_t *ill;
24829 		/*
24830 		 * Special case where ipsq_current_ipif may not be set.
24831 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
24832 		 * ill could also have become part of a ipmp group in the
24833 		 * process, we are here as were not able to complete the
24834 		 * operation in ipif_set_values because we could not become
24835 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
24836 		 * will not be set so we need to set it.
24837 		 */
24838 		ill = (ill_t *)q->q_ptr;
24839 		ipsq->ipsq_current_ipif = ill->ill_ipif;
24840 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24841 	}
24842 
24843 	ipif = ipsq->ipsq_current_ipif;
24844 	ASSERT(ipif != NULL);
24845 	if (ipip->ipi_cmd_type == IF_CMD) {
24846 		/* This a old style SIOC[GS]IF* command */
24847 		ifr = (struct ifreq *)mp1->b_rptr;
24848 		sin = (sin_t *)&ifr->ifr_addr;
24849 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24850 		/* This a new style SIOC[GS]LIF* command */
24851 		lifr = (struct lifreq *)mp1->b_rptr;
24852 		sin = (sin_t *)&lifr->lifr_addr;
24853 	} else {
24854 		sin = NULL;
24855 	}
24856 
24857 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24858 	    (void *)mp1->b_rptr);
24859 
24860 	/* SIOCLIFREMOVEIF could have removed the ipif */
24861 	ip_ioctl_finish(q, mp, err,
24862 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24863 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24864 }
24865 
24866 /*
24867  * ioctl processing
24868  *
24869  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24870  * the ioctl command in the ioctl tables and determines the copyin data size
24871  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24872  * size.
24873  *
24874  * ioctl processing then continues when the M_IOCDATA makes its way down.
24875  * Now the ioctl is looked up again in the ioctl table, and its properties are
24876  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24877  * and the general ioctl processing function ip_process_ioctl is called.
24878  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24879  * so goes thru the serialization primitive ipsq_try_enter. Then the
24880  * appropriate function to handle the ioctl is called based on the entry in
24881  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24882  * which also refreleases the 'conn' that was refheld at the start of the
24883  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24884  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24885  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24886  *
24887  * Many exclusive ioctls go thru an internal down up sequence as part of
24888  * the operation. For example an attempt to change the IP address of an
24889  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24890  * does all the cleanup such as deleting all ires that use this address.
24891  * Then we need to wait till all references to the interface go away.
24892  */
24893 void
24894 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24895 {
24896 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24897 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24898 	cmd_info_t ci;
24899 	int err;
24900 	boolean_t entered_ipsq = B_FALSE;
24901 
24902 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24903 
24904 	if (ipip == NULL)
24905 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24906 
24907 	/*
24908 	 * SIOCLIFADDIF needs to go thru a special path since the
24909 	 * ill may not exist yet. This happens in the case of lo0
24910 	 * which is created using this ioctl.
24911 	 */
24912 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24913 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24914 		ip_ioctl_finish(q, mp, err,
24915 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24916 		    NULL, NULL);
24917 		return;
24918 	}
24919 
24920 	ci.ci_ipif = NULL;
24921 	switch (ipip->ipi_cmd_type) {
24922 	case IF_CMD:
24923 	case LIF_CMD:
24924 		/*
24925 		 * ioctls that pass in a [l]ifreq appear here.
24926 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24927 		 * ci.ci_ipif
24928 		 */
24929 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24930 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24931 		if (err != 0) {
24932 			ip_ioctl_finish(q, mp, err,
24933 			    ipip->ipi_flags & IPI_GET_CMD ?
24934 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24935 			return;
24936 		}
24937 		ASSERT(ci.ci_ipif != NULL);
24938 		break;
24939 
24940 	case TUN_CMD:
24941 		/*
24942 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24943 		 * a refheld ipif in ci.ci_ipif
24944 		 */
24945 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24946 		if (err != 0) {
24947 			ip_ioctl_finish(q, mp, err,
24948 			    ipip->ipi_flags & IPI_GET_CMD ?
24949 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24950 			return;
24951 		}
24952 		ASSERT(ci.ci_ipif != NULL);
24953 		break;
24954 
24955 	case MISC_CMD:
24956 		/*
24957 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24958 		 * For eg. SIOCGLIFCONF will appear here.
24959 		 */
24960 		switch (ipip->ipi_cmd) {
24961 		case IF_UNITSEL:
24962 			/* ioctl comes down the ill */
24963 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24964 			ipif_refhold(ci.ci_ipif);
24965 			break;
24966 		case SIOCGMSFILTER:
24967 		case SIOCSMSFILTER:
24968 		case SIOCGIPMSFILTER:
24969 		case SIOCSIPMSFILTER:
24970 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24971 			    ip_process_ioctl);
24972 			if (err != 0) {
24973 				ip_ioctl_finish(q, mp, err,
24974 				    ipip->ipi_flags & IPI_GET_CMD ?
24975 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24976 				return;
24977 			}
24978 			break;
24979 		}
24980 		err = 0;
24981 		ci.ci_sin = NULL;
24982 		ci.ci_sin6 = NULL;
24983 		ci.ci_lifr = NULL;
24984 		break;
24985 	}
24986 
24987 	/*
24988 	 * If ipsq is non-null, we are already being called exclusively
24989 	 */
24990 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
24991 	if (!(ipip->ipi_flags & IPI_WR)) {
24992 		/*
24993 		 * A return value of EINPROGRESS means the ioctl is
24994 		 * either queued and waiting for some reason or has
24995 		 * already completed.
24996 		 */
24997 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
24998 		    ci.ci_lifr);
24999 		if (ci.ci_ipif != NULL)
25000 			ipif_refrele(ci.ci_ipif);
25001 		ip_ioctl_finish(q, mp, err,
25002 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25003 		    NULL, NULL);
25004 		return;
25005 	}
25006 
25007 	ASSERT(ci.ci_ipif != NULL);
25008 
25009 	if (ipsq == NULL) {
25010 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25011 		    ip_process_ioctl, NEW_OP, B_TRUE);
25012 		entered_ipsq = B_TRUE;
25013 	}
25014 	/*
25015 	 * Release the ipif so that ipif_down and friends that wait for
25016 	 * references to go away are not misled about the current ipif_refcnt
25017 	 * values. We are writer so we can access the ipif even after releasing
25018 	 * the ipif.
25019 	 */
25020 	ipif_refrele(ci.ci_ipif);
25021 	if (ipsq == NULL)
25022 		return;
25023 
25024 	mutex_enter(&ipsq->ipsq_lock);
25025 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25026 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25027 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25028 	mutex_exit(&ipsq->ipsq_lock);
25029 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25030 	/*
25031 	 * For most set ioctls that come here, this serves as a single point
25032 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25033 	 * be any new references to the ipif. This helps functions that go
25034 	 * through this path and end up trying to wait for the refcnts
25035 	 * associated with the ipif to go down to zero. Some exceptions are
25036 	 * Failover, Failback, and Groupname commands that operate on more than
25037 	 * just the ci.ci_ipif. These commands internally determine the
25038 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25039 	 * flags on that set. Another exception is the Removeif command that
25040 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25041 	 * ipif to operate on.
25042 	 */
25043 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25044 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25045 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25046 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25047 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25048 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25049 
25050 	/*
25051 	 * A return value of EINPROGRESS means the ioctl is
25052 	 * either queued and waiting for some reason or has
25053 	 * already completed.
25054 	 */
25055 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25056 	    ci.ci_lifr);
25057 
25058 	/* SIOCLIFREMOVEIF could have removed the ipif */
25059 	ip_ioctl_finish(q, mp, err,
25060 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25061 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25062 
25063 	if (entered_ipsq)
25064 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25065 }
25066 
25067 /*
25068  * Complete the ioctl. Typically ioctls use the mi package and need to
25069  * do mi_copyout/mi_copy_done.
25070  */
25071 void
25072 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25073     ipif_t *ipif, ipsq_t *ipsq)
25074 {
25075 	conn_t	*connp = NULL;
25076 
25077 	if (err == EINPROGRESS)
25078 		return;
25079 
25080 	if (CONN_Q(q)) {
25081 		connp = Q_TO_CONN(q);
25082 		ASSERT(connp->conn_ref >= 2);
25083 	}
25084 
25085 	switch (mode) {
25086 	case COPYOUT:
25087 		if (err == 0)
25088 			mi_copyout(q, mp);
25089 		else
25090 			mi_copy_done(q, mp, err);
25091 		break;
25092 
25093 	case NO_COPYOUT:
25094 		mi_copy_done(q, mp, err);
25095 		break;
25096 
25097 	default:
25098 		/* An ioctl aborted through a conn close would take this path */
25099 		break;
25100 	}
25101 
25102 	/*
25103 	 * The refhold placed at the start of the ioctl is released here.
25104 	 */
25105 	if (connp != NULL)
25106 		CONN_OPER_PENDING_DONE(connp);
25107 
25108 	/*
25109 	 * If the ioctl were an exclusive ioctl it would have set
25110 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25111 	 */
25112 	if (ipif != NULL) {
25113 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25114 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25115 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25116 	}
25117 
25118 	/*
25119 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25120 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25121 	 * entering the ipsq
25122 	 */
25123 	if (ipsq != NULL) {
25124 		mutex_enter(&ipsq->ipsq_lock);
25125 		ipsq->ipsq_current_ipif = NULL;
25126 		mutex_exit(&ipsq->ipsq_lock);
25127 	}
25128 }
25129 
25130 /*
25131  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25132  */
25133 /* ARGSUSED */
25134 void
25135 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25136 {
25137 	conn_t *connp = arg;
25138 	tcp_t	*tcp;
25139 
25140 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25141 	tcp = connp->conn_tcp;
25142 
25143 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25144 		freemsg(mp);
25145 	else
25146 		tcp_rput_other(tcp, mp);
25147 	CONN_OPER_PENDING_DONE(connp);
25148 }
25149 
25150 /* Called from ip_wput for all non data messages */
25151 /* ARGSUSED */
25152 void
25153 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25154 {
25155 	mblk_t		*mp1;
25156 	ire_t		*ire;
25157 	ill_t		*ill;
25158 	struct iocblk	*iocp;
25159 	ip_ioctl_cmd_t	*ipip;
25160 	cred_t		*cr;
25161 	conn_t		*connp = NULL;
25162 	int		cmd, err;
25163 
25164 	if (CONN_Q(q))
25165 		connp = Q_TO_CONN(q);
25166 
25167 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25168 
25169 	/* Check if it is a queue to /dev/sctp. */
25170 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25171 	    connp->conn_rq == NULL) {
25172 		sctp_wput(q, mp);
25173 		return;
25174 	}
25175 
25176 	switch (DB_TYPE(mp)) {
25177 	case M_IOCTL:
25178 		/*
25179 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25180 		 * will arrange to copy in associated control structures.
25181 		 */
25182 		ip_sioctl_copyin_setup(q, mp);
25183 		return;
25184 	case M_IOCDATA:
25185 		/*
25186 		 * Ensure that this is associated with one of our trans-
25187 		 * parent ioctls.  If it's not ours, discard it if we're
25188 		 * running as a driver, or pass it on if we're a module.
25189 		 */
25190 		iocp = (struct iocblk *)mp->b_rptr;
25191 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25192 		if (ipip == NULL) {
25193 			if (q->q_next == NULL) {
25194 				goto nak;
25195 			} else {
25196 				putnext(q, mp);
25197 			}
25198 			return;
25199 		} else if ((q->q_next != NULL) &&
25200 		    !(ipip->ipi_flags & IPI_MODOK)) {
25201 			/*
25202 			 * the ioctl is one we recognise, but is not
25203 			 * consumed by IP as a module, pass M_IOCDATA
25204 			 * for processing downstream, but only for
25205 			 * common Streams ioctls.
25206 			 */
25207 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25208 				putnext(q, mp);
25209 				return;
25210 			} else {
25211 				goto nak;
25212 			}
25213 		}
25214 
25215 		/* IOCTL continuation following copyin or copyout. */
25216 		if (mi_copy_state(q, mp, NULL) == -1) {
25217 			/*
25218 			 * The copy operation failed.  mi_copy_state already
25219 			 * cleaned up, so we're out of here.
25220 			 */
25221 			return;
25222 		}
25223 		/*
25224 		 * If we just completed a copy in, we become writer and
25225 		 * continue processing in ip_sioctl_copyin_done.  If it
25226 		 * was a copy out, we call mi_copyout again.  If there is
25227 		 * nothing more to copy out, it will complete the IOCTL.
25228 		 */
25229 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25230 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25231 				mi_copy_done(q, mp, EPROTO);
25232 				return;
25233 			}
25234 			/*
25235 			 * Check for cases that need more copying.  A return
25236 			 * value of 0 means a second copyin has been started,
25237 			 * so we return; a return value of 1 means no more
25238 			 * copying is needed, so we continue.
25239 			 */
25240 			cmd = iocp->ioc_cmd;
25241 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25242 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25243 			    MI_COPY_COUNT(mp) == 1) {
25244 				if (ip_copyin_msfilter(q, mp) == 0)
25245 					return;
25246 			}
25247 			/*
25248 			 * Refhold the conn, till the ioctl completes. This is
25249 			 * needed in case the ioctl ends up in the pending mp
25250 			 * list. Every mp in the ill_pending_mp list and
25251 			 * the ipsq_pending_mp must have a refhold on the conn
25252 			 * to resume processing. The refhold is released when
25253 			 * the ioctl completes. (normally or abnormally)
25254 			 * In all cases ip_ioctl_finish is called to finish
25255 			 * the ioctl.
25256 			 */
25257 			if (connp != NULL) {
25258 				/* This is not a reentry */
25259 				ASSERT(ipsq == NULL);
25260 				CONN_INC_REF(connp);
25261 			} else {
25262 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25263 					mi_copy_done(q, mp, EINVAL);
25264 					return;
25265 				}
25266 			}
25267 
25268 			ip_process_ioctl(ipsq, q, mp, ipip);
25269 
25270 		} else {
25271 			mi_copyout(q, mp);
25272 		}
25273 		return;
25274 nak:
25275 		iocp->ioc_error = EINVAL;
25276 		mp->b_datap->db_type = M_IOCNAK;
25277 		iocp->ioc_count = 0;
25278 		qreply(q, mp);
25279 		return;
25280 
25281 	case M_IOCNAK:
25282 		/*
25283 		 * The only way we could get here is if a resolver didn't like
25284 		 * an IOCTL we sent it.	 This shouldn't happen.
25285 		 */
25286 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25287 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25288 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25289 		freemsg(mp);
25290 		return;
25291 	case M_IOCACK:
25292 		/* Finish socket ioctls passed through to ARP. */
25293 		ip_sioctl_iocack(q, mp);
25294 		return;
25295 	case M_FLUSH:
25296 		if (*mp->b_rptr & FLUSHW)
25297 			flushq(q, FLUSHALL);
25298 		if (q->q_next) {
25299 			/*
25300 			 * M_FLUSH is sent up to IP by some drivers during
25301 			 * unbind. ip_rput has already replied to it. We are
25302 			 * here for the M_FLUSH that we originated in IP
25303 			 * before sending the unbind request to the driver.
25304 			 * Just free it as we don't queue packets in IP
25305 			 * on the write side of the device instance.
25306 			 */
25307 			freemsg(mp);
25308 			return;
25309 		}
25310 		if (*mp->b_rptr & FLUSHR) {
25311 			*mp->b_rptr &= ~FLUSHW;
25312 			qreply(q, mp);
25313 			return;
25314 		}
25315 		freemsg(mp);
25316 		return;
25317 	case IRE_DB_REQ_TYPE:
25318 		/* An Upper Level Protocol wants a copy of an IRE. */
25319 		ip_ire_req(q, mp);
25320 		return;
25321 	case M_CTL:
25322 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
25323 			break;
25324 
25325 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
25326 		    IP_ULP_OUT_LABELED) {
25327 			out_labeled_t *olp;
25328 
25329 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
25330 				break;
25331 			olp = (out_labeled_t *)mp->b_rptr;
25332 			connp->conn_ulp_labeled = olp->out_qnext == q;
25333 			freemsg(mp);
25334 			return;
25335 		}
25336 
25337 		/* M_CTL messages are used by ARP to tell us things. */
25338 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
25339 			break;
25340 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
25341 		case AR_ENTRY_SQUERY:
25342 			ip_wput_ctl(q, mp);
25343 			return;
25344 		case AR_CLIENT_NOTIFY:
25345 			ip_arp_news(q, mp);
25346 			return;
25347 		case AR_DLPIOP_DONE:
25348 			ASSERT(q->q_next != NULL);
25349 			ill = (ill_t *)q->q_ptr;
25350 			/* qwriter_ip releases the refhold */
25351 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
25352 			ill_refhold(ill);
25353 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
25354 			    CUR_OP, B_FALSE);
25355 			return;
25356 		case AR_ARP_CLOSING:
25357 			/*
25358 			 * ARP (above us) is closing. If no ARP bringup is
25359 			 * currently pending, ack the message so that ARP
25360 			 * can complete its close. Also mark ill_arp_closing
25361 			 * so that new ARP bringups will fail. If any
25362 			 * ARP bringup is currently in progress, we will
25363 			 * ack this when the current ARP bringup completes.
25364 			 */
25365 			ASSERT(q->q_next != NULL);
25366 			ill = (ill_t *)q->q_ptr;
25367 			mutex_enter(&ill->ill_lock);
25368 			ill->ill_arp_closing = 1;
25369 			if (!ill->ill_arp_bringup_pending) {
25370 				mutex_exit(&ill->ill_lock);
25371 				qreply(q, mp);
25372 			} else {
25373 				mutex_exit(&ill->ill_lock);
25374 				freemsg(mp);
25375 			}
25376 			return;
25377 		default:
25378 			break;
25379 		}
25380 		break;
25381 	case M_PROTO:
25382 	case M_PCPROTO:
25383 		/*
25384 		 * The only PROTO messages we expect are ULP binds and
25385 		 * copies of option negotiation acknowledgements.
25386 		 */
25387 		switch (((union T_primitives *)mp->b_rptr)->type) {
25388 		case O_T_BIND_REQ:
25389 		case T_BIND_REQ: {
25390 			/* Request can get queued in bind */
25391 			ASSERT(connp != NULL);
25392 			/*
25393 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
25394 			 * instead of going through this path.  We only get
25395 			 * here in the following cases:
25396 			 *
25397 			 * a. Bind retries, where ipsq is non-NULL.
25398 			 * b. T_BIND_REQ is issued from non TCP/UDP
25399 			 *    transport, e.g. icmp for raw socket,
25400 			 *    in which case ipsq will be NULL.
25401 			 */
25402 			ASSERT(ipsq != NULL ||
25403 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
25404 
25405 			/* Don't increment refcnt if this is a re-entry */
25406 			if (ipsq == NULL)
25407 				CONN_INC_REF(connp);
25408 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
25409 			    connp, NULL) : ip_bind_v4(q, mp, connp);
25410 			if (mp == NULL)
25411 				return;
25412 			if (IPCL_IS_TCP(connp)) {
25413 				/*
25414 				 * In the case of TCP endpoint we
25415 				 * come here only for bind retries
25416 				 */
25417 				ASSERT(ipsq != NULL);
25418 				CONN_INC_REF(connp);
25419 				squeue_fill(connp->conn_sqp, mp,
25420 				    ip_resume_tcp_bind, connp,
25421 				    SQTAG_BIND_RETRY);
25422 				return;
25423 			} else if (IPCL_IS_UDP(connp)) {
25424 				/*
25425 				 * In the case of UDP endpoint we
25426 				 * come here only for bind retries
25427 				 */
25428 				ASSERT(ipsq != NULL);
25429 				udp_resume_bind(connp, mp);
25430 				return;
25431 			}
25432 			qreply(q, mp);
25433 			CONN_OPER_PENDING_DONE(connp);
25434 			return;
25435 		}
25436 		case T_SVR4_OPTMGMT_REQ:
25437 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
25438 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
25439 
25440 			ASSERT(connp != NULL);
25441 			if (!snmpcom_req(q, mp, ip_snmp_set,
25442 			    ip_snmp_get, cr)) {
25443 				/*
25444 				 * Call svr4_optcom_req so that it can
25445 				 * generate the ack. We don't come here
25446 				 * if this operation is being restarted.
25447 				 * ip_restart_optmgmt will drop the conn ref.
25448 				 * In the case of ipsec option after the ipsec
25449 				 * load is complete conn_restart_ipsec_waiter
25450 				 * drops the conn ref.
25451 				 */
25452 				ASSERT(ipsq == NULL);
25453 				CONN_INC_REF(connp);
25454 				if (ip_check_for_ipsec_opt(q, mp))
25455 					return;
25456 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
25457 				if (err != EINPROGRESS) {
25458 					/* Operation is done */
25459 					CONN_OPER_PENDING_DONE(connp);
25460 				}
25461 			}
25462 			return;
25463 		case T_OPTMGMT_REQ:
25464 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
25465 			/*
25466 			 * Note: No snmpcom_req support through new
25467 			 * T_OPTMGMT_REQ.
25468 			 * Call tpi_optcom_req so that it can
25469 			 * generate the ack.
25470 			 */
25471 			ASSERT(connp != NULL);
25472 			ASSERT(ipsq == NULL);
25473 			/*
25474 			 * We don't come here for restart. ip_restart_optmgmt
25475 			 * will drop the conn ref. In the case of ipsec option
25476 			 * after the ipsec load is complete
25477 			 * conn_restart_ipsec_waiter drops the conn ref.
25478 			 */
25479 			CONN_INC_REF(connp);
25480 			if (ip_check_for_ipsec_opt(q, mp))
25481 				return;
25482 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
25483 			if (err != EINPROGRESS) {
25484 				/* Operation is done */
25485 				CONN_OPER_PENDING_DONE(connp);
25486 			}
25487 			return;
25488 		case T_UNBIND_REQ:
25489 			mp = ip_unbind(q, mp);
25490 			qreply(q, mp);
25491 			return;
25492 		default:
25493 			/*
25494 			 * Have to drop any DLPI messages coming down from
25495 			 * arp (such as an info_req which would cause ip
25496 			 * to receive an extra info_ack if it was passed
25497 			 * through.
25498 			 */
25499 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
25500 			    (int)*(uint_t *)mp->b_rptr));
25501 			freemsg(mp);
25502 			return;
25503 		}
25504 		/* NOTREACHED */
25505 	case IRE_DB_TYPE: {
25506 		nce_t		*nce;
25507 		ill_t		*ill;
25508 		in6_addr_t	gw_addr_v6;
25509 
25510 
25511 		/*
25512 		 * This is a response back from a resolver.  It
25513 		 * consists of a message chain containing:
25514 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
25515 		 * The IRE_MBLK is the one we allocated in ip_newroute.
25516 		 * The LL_HDR_MBLK is the DLPI header to use to get
25517 		 * the attached packet, and subsequent ones for the
25518 		 * same destination, transmitted.
25519 		 */
25520 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
25521 			break;
25522 		/*
25523 		 * First, check to make sure the resolution succeeded.
25524 		 * If it failed, the second mblk will be empty.
25525 		 * If it is, free the chain, dropping the packet.
25526 		 * (We must ire_delete the ire; that frees the ire mblk)
25527 		 * We're doing this now to support PVCs for ATM; it's
25528 		 * a partial xresolv implementation. When we fully implement
25529 		 * xresolv interfaces, instead of freeing everything here
25530 		 * we'll initiate neighbor discovery.
25531 		 *
25532 		 * For v4 (ARP and other external resolvers) the resolver
25533 		 * frees the message, so no check is needed. This check
25534 		 * is required, though, for a full xresolve implementation.
25535 		 * Including this code here now both shows how external
25536 		 * resolvers can NACK a resolution request using an
25537 		 * existing design that has no specific provisions for NACKs,
25538 		 * and also takes into account that the current non-ARP
25539 		 * external resolver has been coded to use this method of
25540 		 * NACKing for all IPv6 (xresolv) cases,
25541 		 * whether our xresolv implementation is complete or not.
25542 		 *
25543 		 */
25544 		ire = (ire_t *)mp->b_rptr;
25545 		ill = ire_to_ill(ire);
25546 		mp1 = mp->b_cont;		/* dl_unitdata_req */
25547 		if (mp1->b_rptr == mp1->b_wptr) {
25548 			if (ire->ire_ipversion == IPV6_VERSION) {
25549 				/*
25550 				 * XRESOLV interface.
25551 				 */
25552 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
25553 				mutex_enter(&ire->ire_lock);
25554 				gw_addr_v6 = ire->ire_gateway_addr_v6;
25555 				mutex_exit(&ire->ire_lock);
25556 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25557 					nce = ndp_lookup(ill,
25558 					    &ire->ire_addr_v6, B_FALSE);
25559 				} else {
25560 					nce = ndp_lookup(ill, &gw_addr_v6,
25561 					    B_FALSE);
25562 				}
25563 				if (nce != NULL) {
25564 					nce_resolv_failed(nce);
25565 					ndp_delete(nce);
25566 					NCE_REFRELE(nce);
25567 				}
25568 			}
25569 			mp->b_cont = NULL;
25570 			freemsg(mp1);		/* frees the pkt as well */
25571 			ire_delete((ire_t *)mp->b_rptr);
25572 			return;
25573 		}
25574 		/*
25575 		 * Split them into IRE_MBLK and pkt and feed it into
25576 		 * ire_add_then_send. Then in ire_add_then_send
25577 		 * the IRE will be added, and then the packet will be
25578 		 * run back through ip_wput. This time it will make
25579 		 * it to the wire.
25580 		 */
25581 		mp->b_cont = NULL;
25582 		mp = mp1->b_cont;		/* now, mp points to pkt */
25583 		mp1->b_cont = NULL;
25584 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
25585 		if (ire->ire_ipversion == IPV6_VERSION) {
25586 			/*
25587 			 * XRESOLV interface. Find the nce and put a copy
25588 			 * of the dl_unitdata_req in nce_res_mp
25589 			 */
25590 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
25591 			mutex_enter(&ire->ire_lock);
25592 			gw_addr_v6 = ire->ire_gateway_addr_v6;
25593 			mutex_exit(&ire->ire_lock);
25594 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25595 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
25596 				    B_FALSE);
25597 			} else {
25598 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
25599 			}
25600 			if (nce != NULL) {
25601 				/*
25602 				 * We have to protect nce_res_mp here
25603 				 * from being accessed by other threads
25604 				 * while we change the mblk pointer.
25605 				 * Other functions will also lock the nce when
25606 				 * accessing nce_res_mp.
25607 				 *
25608 				 * The reason we change the mblk pointer
25609 				 * here rather than copying the resolved address
25610 				 * into the template is that, unlike with
25611 				 * ethernet, we have no guarantee that the
25612 				 * resolved address length will be
25613 				 * smaller than or equal to the lla length
25614 				 * with which the template was allocated,
25615 				 * (for ethernet, they're equal)
25616 				 * so we have to use the actual resolved
25617 				 * address mblk - which holds the real
25618 				 * dl_unitdata_req with the resolved address.
25619 				 *
25620 				 * Doing this is the same behavior as was
25621 				 * previously used in the v4 ARP case.
25622 				 */
25623 				mutex_enter(&nce->nce_lock);
25624 				if (nce->nce_res_mp != NULL)
25625 					freemsg(nce->nce_res_mp);
25626 				nce->nce_res_mp = mp1;
25627 				mutex_exit(&nce->nce_lock);
25628 				/*
25629 				 * We do a fastpath probe here because
25630 				 * we have resolved the address without
25631 				 * using Neighbor Discovery.
25632 				 * In the non-XRESOLV v6 case, the fastpath
25633 				 * probe is done right after neighbor
25634 				 * discovery completes.
25635 				 */
25636 				if (nce->nce_res_mp != NULL) {
25637 					int res;
25638 					nce_fastpath_list_add(nce);
25639 					res = ill_fastpath_probe(ill,
25640 					    nce->nce_res_mp);
25641 					if (res != 0 && res != EAGAIN)
25642 						nce_fastpath_list_delete(nce);
25643 				}
25644 
25645 				ire_add_then_send(q, ire, mp);
25646 				/*
25647 				 * Now we have to clean out any packets
25648 				 * that may have been queued on the nce
25649 				 * while it was waiting for address resolution
25650 				 * to complete.
25651 				 */
25652 				mutex_enter(&nce->nce_lock);
25653 				mp1 = nce->nce_qd_mp;
25654 				nce->nce_qd_mp = NULL;
25655 				mutex_exit(&nce->nce_lock);
25656 				while (mp1 != NULL) {
25657 					mblk_t *nxt_mp;
25658 					queue_t *fwdq = NULL;
25659 					ill_t   *inbound_ill;
25660 					uint_t ifindex;
25661 
25662 					nxt_mp = mp1->b_next;
25663 					mp1->b_next = NULL;
25664 					/*
25665 					 * Retrieve ifindex stored in
25666 					 * ip_rput_data_v6()
25667 					 */
25668 					ifindex =
25669 					    (uint_t)(uintptr_t)mp1->b_prev;
25670 					inbound_ill =
25671 						ill_lookup_on_ifindex(ifindex,
25672 						    B_TRUE, NULL, NULL, NULL,
25673 						    NULL);
25674 					mp1->b_prev = NULL;
25675 					if (inbound_ill != NULL)
25676 						fwdq = inbound_ill->ill_rq;
25677 
25678 					if (fwdq != NULL) {
25679 						put(fwdq, mp1);
25680 						ill_refrele(inbound_ill);
25681 					} else
25682 						put(WR(ill->ill_rq), mp1);
25683 					mp1 = nxt_mp;
25684 				}
25685 				NCE_REFRELE(nce);
25686 			} else {	/* nce is NULL; clean up */
25687 				ire_delete(ire);
25688 				freemsg(mp);
25689 				freemsg(mp1);
25690 				return;
25691 			}
25692 		} else {
25693 			ire->ire_dlureq_mp = mp1;
25694 			ire_add_then_send(q, ire, mp);
25695 		}
25696 		return;	/* All is well, the packet has been sent. */
25697 	}
25698 	default:
25699 		break;
25700 	}
25701 	if (q->q_next) {
25702 		putnext(q, mp);
25703 	} else
25704 		freemsg(mp);
25705 }
25706 
25707 /*
25708  * Process IP options in an outbound packet.  Modify the destination if there
25709  * is a source route option.
25710  * Returns non-zero if something fails in which case an ICMP error has been
25711  * sent and mp freed.
25712  */
25713 static int
25714 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
25715     boolean_t mctl_present, zoneid_t zoneid)
25716 {
25717 	ipoptp_t	opts;
25718 	uchar_t		*opt;
25719 	uint8_t		optval;
25720 	uint8_t		optlen;
25721 	ipaddr_t	dst;
25722 	intptr_t	code = 0;
25723 	mblk_t		*mp;
25724 	ire_t		*ire = NULL;
25725 
25726 	ip2dbg(("ip_wput_options\n"));
25727 	mp = ipsec_mp;
25728 	if (mctl_present) {
25729 		mp = ipsec_mp->b_cont;
25730 	}
25731 
25732 	dst = ipha->ipha_dst;
25733 	for (optval = ipoptp_first(&opts, ipha);
25734 	    optval != IPOPT_EOL;
25735 	    optval = ipoptp_next(&opts)) {
25736 		opt = opts.ipoptp_cur;
25737 		optlen = opts.ipoptp_len;
25738 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
25739 		    optval, optlen));
25740 		switch (optval) {
25741 			uint32_t off;
25742 		case IPOPT_SSRR:
25743 		case IPOPT_LSRR:
25744 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25745 				ip1dbg((
25746 				    "ip_wput_options: bad option offset\n"));
25747 				code = (char *)&opt[IPOPT_OLEN] -
25748 				    (char *)ipha;
25749 				goto param_prob;
25750 			}
25751 			off = opt[IPOPT_OFFSET];
25752 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
25753 			    ntohl(dst)));
25754 			/*
25755 			 * For strict: verify that dst is directly
25756 			 * reachable.
25757 			 */
25758 			if (optval == IPOPT_SSRR) {
25759 				ire = ire_ftable_lookup(dst, 0, 0,
25760 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25761 				    MBLK_GETLABEL(mp),
25762 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
25763 				if (ire == NULL) {
25764 					ip1dbg(("ip_wput_options: SSRR not"
25765 					    " directly reachable: 0x%x\n",
25766 					    ntohl(dst)));
25767 					goto bad_src_route;
25768 				}
25769 				ire_refrele(ire);
25770 			}
25771 			break;
25772 		case IPOPT_RR:
25773 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25774 				ip1dbg((
25775 				    "ip_wput_options: bad option offset\n"));
25776 				code = (char *)&opt[IPOPT_OLEN] -
25777 				    (char *)ipha;
25778 				goto param_prob;
25779 			}
25780 			break;
25781 		case IPOPT_TS:
25782 			/*
25783 			 * Verify that length >=5 and that there is either
25784 			 * room for another timestamp or that the overflow
25785 			 * counter is not maxed out.
25786 			 */
25787 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
25788 			if (optlen < IPOPT_MINLEN_IT) {
25789 				goto param_prob;
25790 			}
25791 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25792 				ip1dbg((
25793 				    "ip_wput_options: bad option offset\n"));
25794 				code = (char *)&opt[IPOPT_OFFSET] -
25795 				    (char *)ipha;
25796 				goto param_prob;
25797 			}
25798 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25799 			case IPOPT_TS_TSONLY:
25800 				off = IPOPT_TS_TIMELEN;
25801 				break;
25802 			case IPOPT_TS_TSANDADDR:
25803 			case IPOPT_TS_PRESPEC:
25804 			case IPOPT_TS_PRESPEC_RFC791:
25805 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25806 				break;
25807 			default:
25808 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
25809 				    (char *)ipha;
25810 				goto param_prob;
25811 			}
25812 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
25813 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
25814 				/*
25815 				 * No room and the overflow counter is 15
25816 				 * already.
25817 				 */
25818 				goto param_prob;
25819 			}
25820 			break;
25821 		}
25822 	}
25823 
25824 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
25825 		return (0);
25826 
25827 	ip1dbg(("ip_wput_options: error processing IP options."));
25828 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
25829 
25830 param_prob:
25831 	/*
25832 	 * Since ip_wput() isn't close to finished, we fill
25833 	 * in enough of the header for credible error reporting.
25834 	 */
25835 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25836 		/* Failed */
25837 		freemsg(ipsec_mp);
25838 		return (-1);
25839 	}
25840 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
25841 	return (-1);
25842 
25843 bad_src_route:
25844 	/*
25845 	 * Since ip_wput() isn't close to finished, we fill
25846 	 * in enough of the header for credible error reporting.
25847 	 */
25848 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25849 		/* Failed */
25850 		freemsg(ipsec_mp);
25851 		return (-1);
25852 	}
25853 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
25854 	return (-1);
25855 }
25856 
25857 /*
25858  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25859  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25860  * thru /etc/system.
25861  */
25862 #define	CONN_MAXDRAINCNT	64
25863 
25864 static void
25865 conn_drain_init(void)
25866 {
25867 	int i;
25868 
25869 	conn_drain_list_cnt = conn_drain_nthreads;
25870 
25871 	if ((conn_drain_list_cnt == 0) ||
25872 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25873 		/*
25874 		 * Default value of the number of drainers is the
25875 		 * number of cpus, subject to maximum of 8 drainers.
25876 		 */
25877 		if (boot_max_ncpus != -1)
25878 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25879 		else
25880 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25881 	}
25882 
25883 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25884 	    KM_SLEEP);
25885 
25886 	for (i = 0; i < conn_drain_list_cnt; i++) {
25887 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25888 		    MUTEX_DEFAULT, NULL);
25889 	}
25890 }
25891 
25892 static void
25893 conn_drain_fini(void)
25894 {
25895 	int i;
25896 
25897 	for (i = 0; i < conn_drain_list_cnt; i++)
25898 		mutex_destroy(&conn_drain_list[i].idl_lock);
25899 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25900 	conn_drain_list = NULL;
25901 }
25902 
25903 /*
25904  * Note: For an overview of how flowcontrol is handled in IP please see the
25905  * IP Flowcontrol notes at the top of this file.
25906  *
25907  * Flow control has blocked us from proceeding. Insert the given conn in one
25908  * of the conn drain lists. These conn wq's will be qenabled later on when
25909  * STREAMS flow control does a backenable. conn_walk_drain will enable
25910  * the first conn in each of these drain lists. Each of these qenabled conns
25911  * in turn enables the next in the list, after it runs, or when it closes,
25912  * thus sustaining the drain process.
25913  *
25914  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25915  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25916  * running at any time, on a given conn, since there can be only 1 service proc
25917  * running on a queue at any time.
25918  */
25919 void
25920 conn_drain_insert(conn_t *connp)
25921 {
25922 	idl_t	*idl;
25923 	uint_t	index;
25924 
25925 	mutex_enter(&connp->conn_lock);
25926 	if (connp->conn_state_flags & CONN_CLOSING) {
25927 		/*
25928 		 * The conn is closing as a result of which CONN_CLOSING
25929 		 * is set. Return.
25930 		 */
25931 		mutex_exit(&connp->conn_lock);
25932 		return;
25933 	} else if (connp->conn_idl == NULL) {
25934 		/*
25935 		 * Assign the next drain list round robin. We dont' use
25936 		 * a lock, and thus it may not be strictly round robin.
25937 		 * Atomicity of load/stores is enough to make sure that
25938 		 * conn_drain_list_index is always within bounds.
25939 		 */
25940 		index = conn_drain_list_index;
25941 		ASSERT(index < conn_drain_list_cnt);
25942 		connp->conn_idl = &conn_drain_list[index];
25943 		index++;
25944 		if (index == conn_drain_list_cnt)
25945 			index = 0;
25946 		conn_drain_list_index = index;
25947 	}
25948 	mutex_exit(&connp->conn_lock);
25949 
25950 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25951 	if ((connp->conn_drain_prev != NULL) ||
25952 	    (connp->conn_state_flags & CONN_CLOSING)) {
25953 		/*
25954 		 * The conn is already in the drain list, OR
25955 		 * the conn is closing. We need to check again for
25956 		 * the closing case again since close can happen
25957 		 * after we drop the conn_lock, and before we
25958 		 * acquire the CONN_DRAIN_LIST_LOCK.
25959 		 */
25960 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25961 		return;
25962 	} else {
25963 		idl = connp->conn_idl;
25964 	}
25965 
25966 	/*
25967 	 * The conn is not in the drain list. Insert it at the
25968 	 * tail of the drain list. The drain list is circular
25969 	 * and doubly linked. idl_conn points to the 1st element
25970 	 * in the list.
25971 	 */
25972 	if (idl->idl_conn == NULL) {
25973 		idl->idl_conn = connp;
25974 		connp->conn_drain_next = connp;
25975 		connp->conn_drain_prev = connp;
25976 	} else {
25977 		conn_t *head = idl->idl_conn;
25978 
25979 		connp->conn_drain_next = head;
25980 		connp->conn_drain_prev = head->conn_drain_prev;
25981 		head->conn_drain_prev->conn_drain_next = connp;
25982 		head->conn_drain_prev = connp;
25983 	}
25984 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25985 }
25986 
25987 /*
25988  * This conn is closing, and we are called from ip_close. OR
25989  * This conn has been serviced by ip_wsrv, and we need to do the tail
25990  * processing.
25991  * If this conn is part of the drain list, we may need to sustain the drain
25992  * process by qenabling the next conn in the drain list. We may also need to
25993  * remove this conn from the list, if it is done.
25994  */
25995 static void
25996 conn_drain_tail(conn_t *connp, boolean_t closing)
25997 {
25998 	idl_t *idl;
25999 
26000 	/*
26001 	 * connp->conn_idl is stable at this point, and no lock is needed
26002 	 * to check it. If we are called from ip_close, close has already
26003 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26004 	 * called us only because conn_idl is non-null. If we are called thru
26005 	 * service, conn_idl could be null, but it cannot change because
26006 	 * service is single-threaded per queue, and there cannot be another
26007 	 * instance of service trying to call conn_drain_insert on this conn
26008 	 * now.
26009 	 */
26010 	ASSERT(!closing || (connp->conn_idl != NULL));
26011 
26012 	/*
26013 	 * If connp->conn_idl is null, the conn has not been inserted into any
26014 	 * drain list even once since creation of the conn. Just return.
26015 	 */
26016 	if (connp->conn_idl == NULL)
26017 		return;
26018 
26019 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26020 
26021 	if (connp->conn_drain_prev == NULL) {
26022 		/* This conn is currently not in the drain list.  */
26023 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26024 		return;
26025 	}
26026 	idl = connp->conn_idl;
26027 	if (idl->idl_conn_draining == connp) {
26028 		/*
26029 		 * This conn is the current drainer. If this is the last conn
26030 		 * in the drain list, we need to do more checks, in the 'if'
26031 		 * below. Otherwwise we need to just qenable the next conn,
26032 		 * to sustain the draining, and is handled in the 'else'
26033 		 * below.
26034 		 */
26035 		if (connp->conn_drain_next == idl->idl_conn) {
26036 			/*
26037 			 * This conn is the last in this list. This round
26038 			 * of draining is complete. If idl_repeat is set,
26039 			 * it means another flow enabling has happened from
26040 			 * the driver/streams and we need to another round
26041 			 * of draining.
26042 			 * If there are more than 2 conns in the drain list,
26043 			 * do a left rotate by 1, so that all conns except the
26044 			 * conn at the head move towards the head by 1, and the
26045 			 * the conn at the head goes to the tail. This attempts
26046 			 * a more even share for all queues that are being
26047 			 * drained.
26048 			 */
26049 			if ((connp->conn_drain_next != connp) &&
26050 			    (idl->idl_conn->conn_drain_next != connp)) {
26051 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26052 			}
26053 			if (idl->idl_repeat) {
26054 				qenable(idl->idl_conn->conn_wq);
26055 				idl->idl_conn_draining = idl->idl_conn;
26056 				idl->idl_repeat = 0;
26057 			} else {
26058 				idl->idl_conn_draining = NULL;
26059 			}
26060 		} else {
26061 			/*
26062 			 * If the next queue that we are now qenable'ing,
26063 			 * is closing, it will remove itself from this list
26064 			 * and qenable the subsequent queue in ip_close().
26065 			 * Serialization is acheived thru idl_lock.
26066 			 */
26067 			qenable(connp->conn_drain_next->conn_wq);
26068 			idl->idl_conn_draining = connp->conn_drain_next;
26069 		}
26070 	}
26071 	if (!connp->conn_did_putbq || closing) {
26072 		/*
26073 		 * Remove ourself from the drain list, if we did not do
26074 		 * a putbq, or if the conn is closing.
26075 		 * Note: It is possible that q->q_first is non-null. It means
26076 		 * that these messages landed after we did a enableok() in
26077 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26078 		 * service them.
26079 		 */
26080 		if (connp->conn_drain_next == connp) {
26081 			/* Singleton in the list */
26082 			ASSERT(connp->conn_drain_prev == connp);
26083 			idl->idl_conn = NULL;
26084 			idl->idl_conn_draining = NULL;
26085 		} else {
26086 			connp->conn_drain_prev->conn_drain_next =
26087 			    connp->conn_drain_next;
26088 			connp->conn_drain_next->conn_drain_prev =
26089 			    connp->conn_drain_prev;
26090 			if (idl->idl_conn == connp)
26091 				idl->idl_conn = connp->conn_drain_next;
26092 			ASSERT(idl->idl_conn_draining != connp);
26093 
26094 		}
26095 		connp->conn_drain_next = NULL;
26096 		connp->conn_drain_prev = NULL;
26097 	}
26098 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26099 }
26100 
26101 /*
26102  * Write service routine. Shared perimeter entry point.
26103  * ip_wsrv can be called in any of the following ways.
26104  * 1. The device queue's messages has fallen below the low water mark
26105  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26106  *    the drain lists and backenable the first conn in each list.
26107  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
26108  *    qenabled non-tcp upper layers. We start dequeing messages and call
26109  *    ip_wput for each message.
26110  */
26111 
26112 void
26113 ip_wsrv(queue_t *q)
26114 {
26115 	conn_t	*connp;
26116 	ill_t	*ill;
26117 	mblk_t	*mp;
26118 
26119 	if (q->q_next) {
26120 		ill = (ill_t *)q->q_ptr;
26121 		if (ill->ill_state_flags == 0) {
26122 			/*
26123 			 * The device flow control has opened up.
26124 			 * Walk through conn drain lists and qenable the
26125 			 * first conn in each list. This makes sense only
26126 			 * if the stream is fully plumbed and setup.
26127 			 * Hence the if check above.
26128 			 */
26129 			ip1dbg(("ip_wsrv: walking\n"));
26130 			conn_walk_drain();
26131 		}
26132 		return;
26133 	}
26134 
26135 	connp = Q_TO_CONN(q);
26136 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
26137 
26138 	/*
26139 	 * 1. Set conn_draining flag to signal that service is active.
26140 	 *
26141 	 * 2. ip_output determines whether it has been called from service,
26142 	 *    based on the last parameter. If it is IP_WSRV it concludes it
26143 	 *    has been called from service.
26144 	 *
26145 	 * 3. Message ordering is preserved by the following logic.
26146 	 *    i. A directly called ip_output (i.e. not thru service) will queue
26147 	 *    the message at the tail, if conn_draining is set (i.e. service
26148 	 *    is running) or if q->q_first is non-null.
26149 	 *
26150 	 *    ii. If ip_output is called from service, and if ip_output cannot
26151 	 *    putnext due to flow control, it does a putbq.
26152 	 *
26153 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
26154 	 *    (causing an infinite loop).
26155 	 */
26156 	ASSERT(!connp->conn_did_putbq);
26157 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
26158 		connp->conn_draining = 1;
26159 		noenable(q);
26160 		while ((mp = getq(q)) != NULL) {
26161 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
26162 			if (connp->conn_did_putbq) {
26163 				/* ip_wput did a putbq */
26164 				break;
26165 			}
26166 		}
26167 		/*
26168 		 * At this point, a thread coming down from top, calling
26169 		 * ip_wput, may end up queueing the message. We have not yet
26170 		 * enabled the queue, so ip_wsrv won't be called again.
26171 		 * To avoid this race, check q->q_first again (in the loop)
26172 		 * If the other thread queued the message before we call
26173 		 * enableok(), we will catch it in the q->q_first check.
26174 		 * If the other thread queues the message after we call
26175 		 * enableok(), ip_wsrv will be called again by STREAMS.
26176 		 */
26177 		connp->conn_draining = 0;
26178 		enableok(q);
26179 	}
26180 
26181 	/* Enable the next conn for draining */
26182 	conn_drain_tail(connp, B_FALSE);
26183 
26184 	connp->conn_did_putbq = 0;
26185 }
26186 
26187 /*
26188  * Walk the list of all conn's calling the function provided with the
26189  * specified argument for each.	 Note that this only walks conn's that
26190  * have been bound.
26191  * Applies to both IPv4 and IPv6.
26192  */
26193 static void
26194 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
26195 {
26196 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
26197 	    func, arg, zoneid);
26198 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
26199 	    func, arg, zoneid);
26200 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
26201 	    func, arg, zoneid);
26202 	conn_walk_fanout_table(ipcl_proto_fanout,
26203 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
26204 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
26205 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
26206 }
26207 
26208 /*
26209  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
26210  * of conns that need to be drained, check if drain is already in progress.
26211  * If so set the idl_repeat bit, indicating that the last conn in the list
26212  * needs to reinitiate the drain once again, for the list. If drain is not
26213  * in progress for the list, initiate the draining, by qenabling the 1st
26214  * conn in the list. The drain is self-sustaining, each qenabled conn will
26215  * in turn qenable the next conn, when it is done/blocked/closing.
26216  */
26217 static void
26218 conn_walk_drain(void)
26219 {
26220 	int i;
26221 	idl_t *idl;
26222 
26223 	IP_STAT(ip_conn_walk_drain);
26224 
26225 	for (i = 0; i < conn_drain_list_cnt; i++) {
26226 		idl = &conn_drain_list[i];
26227 		mutex_enter(&idl->idl_lock);
26228 		if (idl->idl_conn == NULL) {
26229 			mutex_exit(&idl->idl_lock);
26230 			continue;
26231 		}
26232 		/*
26233 		 * If this list is not being drained currently by
26234 		 * an ip_wsrv thread, start the process.
26235 		 */
26236 		if (idl->idl_conn_draining == NULL) {
26237 			ASSERT(idl->idl_repeat == 0);
26238 			qenable(idl->idl_conn->conn_wq);
26239 			idl->idl_conn_draining = idl->idl_conn;
26240 		} else {
26241 			idl->idl_repeat = 1;
26242 		}
26243 		mutex_exit(&idl->idl_lock);
26244 	}
26245 }
26246 
26247 /*
26248  * Walk an conn hash table of `count' buckets, calling func for each entry.
26249  */
26250 static void
26251 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
26252     zoneid_t zoneid)
26253 {
26254 	conn_t	*connp;
26255 
26256 	while (count-- > 0) {
26257 		mutex_enter(&connfp->connf_lock);
26258 		for (connp = connfp->connf_head; connp != NULL;
26259 		    connp = connp->conn_next) {
26260 			if (zoneid == GLOBAL_ZONEID ||
26261 			    zoneid == connp->conn_zoneid) {
26262 				CONN_INC_REF(connp);
26263 				mutex_exit(&connfp->connf_lock);
26264 				(*func)(connp, arg);
26265 				mutex_enter(&connfp->connf_lock);
26266 				CONN_DEC_REF(connp);
26267 			}
26268 		}
26269 		mutex_exit(&connfp->connf_lock);
26270 		connfp++;
26271 	}
26272 }
26273 
26274 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
26275 static void
26276 conn_report1(conn_t *connp, void *mp)
26277 {
26278 	char	buf1[INET6_ADDRSTRLEN];
26279 	char	buf2[INET6_ADDRSTRLEN];
26280 	uint_t	print_len, buf_len;
26281 
26282 	ASSERT(connp != NULL);
26283 
26284 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
26285 	if (buf_len <= 0)
26286 		return;
26287 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
26288 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
26289 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
26290 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
26291 	    "%5d %s/%05d %s/%05d\n",
26292 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
26293 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
26294 	    buf1, connp->conn_lport,
26295 	    buf2, connp->conn_fport);
26296 	if (print_len < buf_len) {
26297 		((mblk_t *)mp)->b_wptr += print_len;
26298 	} else {
26299 		((mblk_t *)mp)->b_wptr += buf_len;
26300 	}
26301 }
26302 
26303 /*
26304  * Named Dispatch routine to produce a formatted report on all conns
26305  * that are listed in one of the fanout tables.
26306  * This report is accessed by using the ndd utility to "get" ND variable
26307  * "ip_conn_status".
26308  */
26309 /* ARGSUSED */
26310 static int
26311 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
26312 {
26313 	(void) mi_mpprintf(mp,
26314 	    "CONN      " MI_COL_HDRPAD_STR
26315 	    "rfq      " MI_COL_HDRPAD_STR
26316 	    "stq      " MI_COL_HDRPAD_STR
26317 	    " zone local                 remote");
26318 
26319 	/*
26320 	 * Because of the ndd constraint, at most we can have 64K buffer
26321 	 * to put in all conn info.  So to be more efficient, just
26322 	 * allocate a 64K buffer here, assuming we need that large buffer.
26323 	 * This should be OK as only privileged processes can do ndd /dev/ip.
26324 	 */
26325 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
26326 		/* The following may work even if we cannot get a large buf. */
26327 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
26328 		return (0);
26329 	}
26330 
26331 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
26332 	return (0);
26333 }
26334 
26335 /*
26336  * Determine if the ill and multicast aspects of that packets
26337  * "matches" the conn.
26338  */
26339 boolean_t
26340 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
26341     zoneid_t zoneid)
26342 {
26343 	ill_t *in_ill;
26344 	boolean_t found;
26345 	ipif_t *ipif;
26346 	ire_t *ire;
26347 	ipaddr_t dst, src;
26348 
26349 	dst = ipha->ipha_dst;
26350 	src = ipha->ipha_src;
26351 
26352 	/*
26353 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
26354 	 * unicast, broadcast and multicast reception to
26355 	 * conn_incoming_ill. conn_wantpacket itself is called
26356 	 * only for BROADCAST and multicast.
26357 	 *
26358 	 * 1) ip_rput supresses duplicate broadcasts if the ill
26359 	 *    is part of a group. Hence, we should be receiving
26360 	 *    just one copy of broadcast for the whole group.
26361 	 *    Thus, if it is part of the group the packet could
26362 	 *    come on any ill of the group and hence we need a
26363 	 *    match on the group. Otherwise, match on ill should
26364 	 *    be sufficient.
26365 	 *
26366 	 * 2) ip_rput does not suppress duplicate multicast packets.
26367 	 *    If there are two interfaces in a ill group and we have
26368 	 *    2 applications (conns) joined a multicast group G on
26369 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
26370 	 *    will give us two packets because we join G on both the
26371 	 *    interfaces rather than nominating just one interface
26372 	 *    for receiving multicast like broadcast above. So,
26373 	 *    we have to call ilg_lookup_ill to filter out duplicate
26374 	 *    copies, if ill is part of a group.
26375 	 */
26376 	in_ill = connp->conn_incoming_ill;
26377 	if (in_ill != NULL) {
26378 		if (in_ill->ill_group == NULL) {
26379 			if (in_ill != ill)
26380 				return (B_FALSE);
26381 		} else if (in_ill->ill_group != ill->ill_group) {
26382 			return (B_FALSE);
26383 		}
26384 	}
26385 
26386 	if (!CLASSD(dst)) {
26387 		if (connp->conn_zoneid == zoneid)
26388 			return (B_TRUE);
26389 		/*
26390 		 * The conn is in a different zone; we need to check that this
26391 		 * broadcast address is configured in the application's zone and
26392 		 * on one ill in the group.
26393 		 */
26394 		ipif = ipif_get_next_ipif(NULL, ill);
26395 		if (ipif == NULL)
26396 			return (B_FALSE);
26397 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
26398 		    connp->conn_zoneid, NULL,
26399 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
26400 		ipif_refrele(ipif);
26401 		if (ire != NULL) {
26402 			ire_refrele(ire);
26403 			return (B_TRUE);
26404 		} else {
26405 			return (B_FALSE);
26406 		}
26407 	}
26408 
26409 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
26410 	    connp->conn_zoneid == zoneid) {
26411 		/*
26412 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
26413 		 * disabled, therefore we don't dispatch the multicast packet to
26414 		 * the sending zone.
26415 		 */
26416 		return (B_FALSE);
26417 	}
26418 
26419 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
26420 	    connp->conn_zoneid != zoneid) {
26421 		/*
26422 		 * Multicast packet on the loopback interface: we only match
26423 		 * conns who joined the group in the specified zone.
26424 		 */
26425 		return (B_FALSE);
26426 	}
26427 
26428 	if (connp->conn_multi_router) {
26429 		/* multicast packet and multicast router socket: send up */
26430 		return (B_TRUE);
26431 	}
26432 
26433 	mutex_enter(&connp->conn_lock);
26434 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
26435 	mutex_exit(&connp->conn_lock);
26436 	return (found);
26437 }
26438 
26439 /*
26440  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
26441  */
26442 /* ARGSUSED */
26443 static void
26444 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
26445 {
26446 	ill_t *ill = (ill_t *)q->q_ptr;
26447 	mblk_t	*mp1, *mp2;
26448 	ipif_t  *ipif;
26449 	int err = 0;
26450 	conn_t *connp = NULL;
26451 	ipsq_t	*ipsq;
26452 	arc_t	*arc;
26453 
26454 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
26455 
26456 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
26457 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
26458 
26459 	ASSERT(IAM_WRITER_ILL(ill));
26460 	mp2 = mp->b_cont;
26461 	mp->b_cont = NULL;
26462 
26463 	/*
26464 	 * We have now received the arp bringup completion message
26465 	 * from ARP. Mark the arp bringup as done. Also if the arp
26466 	 * stream has already started closing, send up the AR_ARP_CLOSING
26467 	 * ack now since ARP is waiting in close for this ack.
26468 	 */
26469 	mutex_enter(&ill->ill_lock);
26470 	ill->ill_arp_bringup_pending = 0;
26471 	if (ill->ill_arp_closing) {
26472 		mutex_exit(&ill->ill_lock);
26473 		/* Let's reuse the mp for sending the ack */
26474 		arc = (arc_t *)mp->b_rptr;
26475 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
26476 		arc->arc_cmd = AR_ARP_CLOSING;
26477 		qreply(q, mp);
26478 	} else {
26479 		mutex_exit(&ill->ill_lock);
26480 		freeb(mp);
26481 	}
26482 
26483 	/* We should have an IOCTL waiting on this. */
26484 	ipsq = ill->ill_phyint->phyint_ipsq;
26485 	ipif = ipsq->ipsq_pending_ipif;
26486 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
26487 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
26488 	if (mp1 == NULL) {
26489 		/* bringup was aborted by the user */
26490 		freemsg(mp2);
26491 		return;
26492 	}
26493 	ASSERT(connp != NULL);
26494 	q = CONNP_TO_WQ(connp);
26495 	/*
26496 	 * If the DL_BIND_REQ fails, it is noted
26497 	 * in arc_name_offset.
26498 	 */
26499 	err = *((int *)mp2->b_rptr);
26500 	if (err == 0) {
26501 		if (ipif->ipif_isv6) {
26502 			if ((err = ipif_up_done_v6(ipif)) != 0)
26503 				ip0dbg(("ip_arp_done: init failed\n"));
26504 		} else {
26505 			if ((err = ipif_up_done(ipif)) != 0)
26506 				ip0dbg(("ip_arp_done: init failed\n"));
26507 		}
26508 	} else {
26509 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
26510 	}
26511 
26512 	freemsg(mp2);
26513 
26514 	if ((err == 0) && (ill->ill_up_ipifs)) {
26515 		err = ill_up_ipifs(ill, q, mp1);
26516 		if (err == EINPROGRESS)
26517 			return;
26518 	}
26519 
26520 	if (ill->ill_up_ipifs) {
26521 		ill_group_cleanup(ill);
26522 	}
26523 
26524 	/*
26525 	 * The ioctl must complete now without EINPROGRESS
26526 	 * since ipsq_pending_mp_get has removed the ioctl mblk
26527 	 * from ipsq_pending_mp. Otherwise the ioctl will be
26528 	 * stuck for ever in the ipsq.
26529 	 */
26530 	ASSERT(err != EINPROGRESS);
26531 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
26532 }
26533 
26534 /* Allocate the private structure */
26535 static int
26536 ip_priv_alloc(void **bufp)
26537 {
26538 	void	*buf;
26539 
26540 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
26541 		return (ENOMEM);
26542 
26543 	*bufp = buf;
26544 	return (0);
26545 }
26546 
26547 /* Function to delete the private structure */
26548 void
26549 ip_priv_free(void *buf)
26550 {
26551 	ASSERT(buf != NULL);
26552 	kmem_free(buf, sizeof (ip_priv_t));
26553 }
26554 
26555 /*
26556  * The entry point for IPPF processing.
26557  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
26558  * routine just returns.
26559  *
26560  * When called, ip_process generates an ipp_packet_t structure
26561  * which holds the state information for this packet and invokes the
26562  * the classifier (via ipp_packet_process). The classification, depending on
26563  * configured filters, results in a list of actions for this packet. Invoking
26564  * an action may cause the packet to be dropped, in which case the resulting
26565  * mblk (*mpp) is NULL. proc indicates the callout position for
26566  * this packet and ill_index is the interface this packet on or will leave
26567  * on (inbound and outbound resp.).
26568  */
26569 void
26570 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
26571 {
26572 	mblk_t		*mp;
26573 	ip_priv_t	*priv;
26574 	ipp_action_id_t	aid;
26575 	int		rc = 0;
26576 	ipp_packet_t	*pp;
26577 #define	IP_CLASS	"ip"
26578 
26579 	/* If the classifier is not loaded, return  */
26580 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
26581 		return;
26582 	}
26583 
26584 	mp = *mpp;
26585 	ASSERT(mp != NULL);
26586 
26587 	/* Allocate the packet structure */
26588 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
26589 	if (rc != 0) {
26590 		*mpp = NULL;
26591 		freemsg(mp);
26592 		return;
26593 	}
26594 
26595 	/* Allocate the private structure */
26596 	rc = ip_priv_alloc((void **)&priv);
26597 	if (rc != 0) {
26598 		*mpp = NULL;
26599 		freemsg(mp);
26600 		ipp_packet_free(pp);
26601 		return;
26602 	}
26603 	priv->proc = proc;
26604 	priv->ill_index = ill_index;
26605 	ipp_packet_set_private(pp, priv, ip_priv_free);
26606 	ipp_packet_set_data(pp, mp);
26607 
26608 	/* Invoke the classifier */
26609 	rc = ipp_packet_process(&pp);
26610 	if (pp != NULL) {
26611 		mp = ipp_packet_get_data(pp);
26612 		ipp_packet_free(pp);
26613 		if (rc != 0) {
26614 			freemsg(mp);
26615 			*mpp = NULL;
26616 		}
26617 	} else {
26618 		*mpp = NULL;
26619 	}
26620 #undef	IP_CLASS
26621 }
26622 
26623 /*
26624  * Propagate a multicast group membership operation (add/drop) on
26625  * all the interfaces crossed by the related multirt routes.
26626  * The call is considered successful if the operation succeeds
26627  * on at least one interface.
26628  */
26629 static int
26630 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
26631     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
26632     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
26633     mblk_t *first_mp)
26634 {
26635 	ire_t		*ire_gw;
26636 	irb_t		*irb;
26637 	int		error = 0;
26638 	opt_restart_t	*or;
26639 
26640 	irb = ire->ire_bucket;
26641 	ASSERT(irb != NULL);
26642 
26643 	ASSERT(DB_TYPE(first_mp) == M_CTL);
26644 
26645 	or = (opt_restart_t *)first_mp->b_rptr;
26646 	IRB_REFHOLD(irb);
26647 	for (; ire != NULL; ire = ire->ire_next) {
26648 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
26649 			continue;
26650 		if (ire->ire_addr != group)
26651 			continue;
26652 
26653 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
26654 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
26655 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
26656 		/* No resolver exists for the gateway; skip this ire. */
26657 		if (ire_gw == NULL)
26658 			continue;
26659 
26660 		/*
26661 		 * This function can return EINPROGRESS. If so the operation
26662 		 * will be restarted from ip_restart_optmgmt which will
26663 		 * call ip_opt_set and option processing will restart for
26664 		 * this option. So we may end up calling 'fn' more than once.
26665 		 * This requires that 'fn' is idempotent except for the
26666 		 * return value. The operation is considered a success if
26667 		 * it succeeds at least once on any one interface.
26668 		 */
26669 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
26670 		    NULL, fmode, src, first_mp);
26671 		if (error == 0)
26672 			or->or_private = CGTP_MCAST_SUCCESS;
26673 
26674 		if (ip_debug > 0) {
26675 			ulong_t	off;
26676 			char	*ksym;
26677 			ksym = kobj_getsymname((uintptr_t)fn, &off);
26678 			ip2dbg(("ip_multirt_apply_membership: "
26679 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
26680 			    "error %d [success %u]\n",
26681 			    ksym ? ksym : "?",
26682 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
26683 			    error, or->or_private));
26684 		}
26685 
26686 		ire_refrele(ire_gw);
26687 		if (error == EINPROGRESS) {
26688 			IRB_REFRELE(irb);
26689 			return (error);
26690 		}
26691 	}
26692 	IRB_REFRELE(irb);
26693 	/*
26694 	 * Consider the call as successful if we succeeded on at least
26695 	 * one interface. Otherwise, return the last encountered error.
26696 	 */
26697 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
26698 }
26699 
26700 
26701 /*
26702  * Issue a warning regarding a route crossing an interface with an
26703  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
26704  * amount of time is logged.
26705  */
26706 static void
26707 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
26708 {
26709 	hrtime_t	current = gethrtime();
26710 	char		buf[16];
26711 
26712 	/* Convert interval in ms to hrtime in ns */
26713 	if (multirt_bad_mtu_last_time +
26714 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
26715 	    current) {
26716 		cmn_err(CE_WARN, "ip: ignoring multiroute "
26717 		    "to %s, incorrect MTU %u (expected %u)\n",
26718 		    ip_dot_addr(ire->ire_addr, buf),
26719 		    ire->ire_max_frag, max_frag);
26720 
26721 		multirt_bad_mtu_last_time = current;
26722 	}
26723 }
26724 
26725 
26726 /*
26727  * Get the CGTP (multirouting) filtering status.
26728  * If 0, the CGTP hooks are transparent.
26729  */
26730 /* ARGSUSED */
26731 static int
26732 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
26733 {
26734 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26735 
26736 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
26737 	return (0);
26738 }
26739 
26740 
26741 /*
26742  * Set the CGTP (multirouting) filtering status.
26743  * If the status is changed from active to transparent
26744  * or from transparent to active, forward the new status
26745  * to the filtering module (if loaded).
26746  */
26747 /* ARGSUSED */
26748 static int
26749 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
26750     cred_t *ioc_cr)
26751 {
26752 	long		new_value;
26753 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26754 
26755 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
26756 	    new_value < 0 || new_value > 1) {
26757 		return (EINVAL);
26758 	}
26759 
26760 	/*
26761 	 * Do not enable CGTP filtering - thus preventing the hooks
26762 	 * from being invoked - if the version number of the
26763 	 * filtering module hooks does not match.
26764 	 */
26765 	if ((ip_cgtp_filter_ops != NULL) &&
26766 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
26767 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
26768 		    "(module hooks version %d, expecting %d)\n",
26769 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
26770 		return (ENOTSUP);
26771 	}
26772 
26773 	if ((!*ip_cgtp_filter_value) && new_value) {
26774 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
26775 		    ip_cgtp_filter_ops == NULL ?
26776 		    " (module not loaded)" : "");
26777 	}
26778 	if (*ip_cgtp_filter_value && (!new_value)) {
26779 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
26780 		    ip_cgtp_filter_ops == NULL ?
26781 		    " (module not loaded)" : "");
26782 	}
26783 
26784 	if (ip_cgtp_filter_ops != NULL) {
26785 		int	res;
26786 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
26787 			return (res);
26788 		}
26789 	}
26790 
26791 	*ip_cgtp_filter_value = (boolean_t)new_value;
26792 
26793 	return (0);
26794 }
26795 
26796 
26797 /*
26798  * Return the expected CGTP hooks version number.
26799  */
26800 int
26801 ip_cgtp_filter_supported(void)
26802 {
26803 	return (ip_cgtp_filter_rev);
26804 }
26805 
26806 
26807 /*
26808  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
26809  * or by invoking this function. In the first case, the version number
26810  * of the registered structure is checked at hooks activation time
26811  * in ip_cgtp_filter_set().
26812  */
26813 int
26814 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
26815 {
26816 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
26817 		return (ENOTSUP);
26818 
26819 	ip_cgtp_filter_ops = ops;
26820 	return (0);
26821 }
26822 
26823 static squeue_func_t
26824 ip_squeue_switch(int val)
26825 {
26826 	squeue_func_t rval = squeue_fill;
26827 
26828 	switch (val) {
26829 	case IP_SQUEUE_ENTER_NODRAIN:
26830 		rval = squeue_enter_nodrain;
26831 		break;
26832 	case IP_SQUEUE_ENTER:
26833 		rval = squeue_enter;
26834 		break;
26835 	default:
26836 		break;
26837 	}
26838 	return (rval);
26839 }
26840 
26841 /* ARGSUSED */
26842 static int
26843 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
26844     caddr_t addr, cred_t *cr)
26845 {
26846 	int *v = (int *)addr;
26847 	long new_value;
26848 
26849 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26850 		return (EINVAL);
26851 
26852 	ip_input_proc = ip_squeue_switch(new_value);
26853 	*v = new_value;
26854 	return (0);
26855 }
26856 
26857 /* ARGSUSED */
26858 static int
26859 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26860     caddr_t addr, cred_t *cr)
26861 {
26862 	int *v = (int *)addr;
26863 	long new_value;
26864 
26865 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26866 		return (EINVAL);
26867 
26868 	*v = new_value;
26869 	return (0);
26870 }
26871 
26872 static void
26873 ip_kstat_init(void)
26874 {
26875 	ip_named_kstat_t template = {
26876 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26877 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26878 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26879 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26880 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26881 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26882 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26883 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26884 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26885 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26886 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26887 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26888 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26889 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26890 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26891 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26892 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26893 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26894 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26895 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26896 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26897 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26898 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26899 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26900 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26901 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26902 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26903 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26904 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26905 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26906 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26907 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26908 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26909 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26910 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26911 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26912 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26913 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26914 	};
26915 
26916 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26917 					NUM_OF_FIELDS(ip_named_kstat_t),
26918 					0);
26919 	if (!ip_mibkp)
26920 		return;
26921 
26922 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26923 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26924 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26925 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26926 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26927 
26928 	template.netToMediaEntrySize.value.i32 =
26929 		sizeof (mib2_ipNetToMediaEntry_t);
26930 
26931 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26932 
26933 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26934 
26935 	ip_mibkp->ks_update = ip_kstat_update;
26936 
26937 	kstat_install(ip_mibkp);
26938 }
26939 
26940 static void
26941 ip_kstat_fini(void)
26942 {
26943 
26944 	if (ip_mibkp != NULL) {
26945 		kstat_delete(ip_mibkp);
26946 		ip_mibkp = NULL;
26947 	}
26948 }
26949 
26950 static int
26951 ip_kstat_update(kstat_t *kp, int rw)
26952 {
26953 	ip_named_kstat_t *ipkp;
26954 
26955 	if (!kp || !kp->ks_data)
26956 		return (EIO);
26957 
26958 	if (rw == KSTAT_WRITE)
26959 		return (EACCES);
26960 
26961 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26962 
26963 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26964 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26965 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26966 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26967 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26968 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26969 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26970 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26971 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26972 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26973 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26974 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26975 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26976 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26977 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26978 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26979 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26980 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26981 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26982 
26983 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26984 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26985 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26986 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
26987 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
26988 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
26989 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
26990 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
26991 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
26992 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
26993 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
26994 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
26995 
26996 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
26997 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
26998 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
26999 
27000 	return (0);
27001 }
27002 
27003 static void
27004 icmp_kstat_init(void)
27005 {
27006 	icmp_named_kstat_t template = {
27007 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27008 		{ "inErrors",		KSTAT_DATA_UINT32 },
27009 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27010 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27011 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27012 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27013 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27014 		{ "inEchos",		KSTAT_DATA_UINT32 },
27015 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27016 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27017 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27018 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27019 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27020 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27021 		{ "outErrors",		KSTAT_DATA_UINT32 },
27022 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27023 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27024 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27025 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27026 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27027 		{ "outEchos",		KSTAT_DATA_UINT32 },
27028 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27029 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27030 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27031 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27032 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27033 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27034 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27035 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27036 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27037 		{ "outDrops",		KSTAT_DATA_UINT32 },
27038 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27039 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27040 	};
27041 
27042 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27043 					NUM_OF_FIELDS(icmp_named_kstat_t),
27044 					0);
27045 	if (icmp_mibkp == NULL)
27046 		return;
27047 
27048 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27049 
27050 	icmp_mibkp->ks_update = icmp_kstat_update;
27051 
27052 	kstat_install(icmp_mibkp);
27053 }
27054 
27055 static void
27056 icmp_kstat_fini(void)
27057 {
27058 
27059 	if (icmp_mibkp != NULL) {
27060 		kstat_delete(icmp_mibkp);
27061 		icmp_mibkp = NULL;
27062 	}
27063 }
27064 
27065 static int
27066 icmp_kstat_update(kstat_t *kp, int rw)
27067 {
27068 	icmp_named_kstat_t *icmpkp;
27069 
27070 	if ((kp == NULL) || (kp->ks_data == NULL))
27071 		return (EIO);
27072 
27073 	if (rw == KSTAT_WRITE)
27074 		return (EACCES);
27075 
27076 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27077 
27078 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27079 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27080 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27081 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27082 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27083 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27084 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27085 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27086 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27087 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27088 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27089 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27090 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27091 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27092 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27093 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27094 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27095 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27096 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27097 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27098 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27099 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27100 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27101 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27102 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27103 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27104 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27105 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27106 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27107 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
27108 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
27109 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
27110 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
27111 
27112 	return (0);
27113 }
27114 
27115 /*
27116  * This is the fanout function for raw socket opened for SCTP.  Note
27117  * that it is called after SCTP checks that there is no socket which
27118  * wants a packet.  Then before SCTP handles this out of the blue packet,
27119  * this function is called to see if there is any raw socket for SCTP.
27120  * If there is and it is bound to the correct address, the packet will
27121  * be sent to that socket.  Note that only one raw socket can be bound to
27122  * a port.  This is assured in ipcl_sctp_hash_insert();
27123  */
27124 void
27125 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
27126     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
27127     uint_t ipif_seqid, zoneid_t zoneid)
27128 {
27129 	conn_t		*connp;
27130 	queue_t		*rq;
27131 	mblk_t		*first_mp;
27132 	boolean_t	secure;
27133 	ip6_t		*ip6h;
27134 
27135 	first_mp = mp;
27136 	if (mctl_present) {
27137 		mp = first_mp->b_cont;
27138 		secure = ipsec_in_is_secure(first_mp);
27139 		ASSERT(mp != NULL);
27140 	} else {
27141 		secure = B_FALSE;
27142 	}
27143 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
27144 
27145 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
27146 	if (connp == NULL) {
27147 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
27148 		    mctl_present);
27149 		return;
27150 	}
27151 	rq = connp->conn_rq;
27152 	if (!canputnext(rq)) {
27153 		CONN_DEC_REF(connp);
27154 		BUMP_MIB(&ip_mib, rawipInOverflows);
27155 		freemsg(first_mp);
27156 		return;
27157 	}
27158 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
27159 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
27160 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
27161 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
27162 		if (first_mp == NULL) {
27163 			CONN_DEC_REF(connp);
27164 			return;
27165 		}
27166 	}
27167 	/*
27168 	 * We probably should not send M_CTL message up to
27169 	 * raw socket.
27170 	 */
27171 	if (mctl_present)
27172 		freeb(first_mp);
27173 
27174 	/* Initiate IPPF processing here if needed. */
27175 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
27176 	    (!isv4 && IP6_IN_IPP(flags))) {
27177 		ip_process(IPP_LOCAL_IN, &mp,
27178 		    recv_ill->ill_phyint->phyint_ifindex);
27179 		if (mp == NULL) {
27180 			CONN_DEC_REF(connp);
27181 			return;
27182 		}
27183 	}
27184 
27185 	if (connp->conn_recvif || connp->conn_recvslla ||
27186 	    ((connp->conn_ipv6_recvpktinfo ||
27187 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
27188 	    (flags & IP_FF_IP6INFO))) {
27189 		int in_flags = 0;
27190 
27191 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
27192 			in_flags = IPF_RECVIF;
27193 		}
27194 		if (connp->conn_recvslla) {
27195 			in_flags |= IPF_RECVSLLA;
27196 		}
27197 		if (isv4) {
27198 			mp = ip_add_info(mp, recv_ill, in_flags);
27199 		} else {
27200 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
27201 			if (mp == NULL) {
27202 				CONN_DEC_REF(connp);
27203 				return;
27204 			}
27205 		}
27206 	}
27207 
27208 	BUMP_MIB(&ip_mib, ipInDelivers);
27209 	/*
27210 	 * We are sending the IPSEC_IN message also up. Refer
27211 	 * to comments above this function.
27212 	 */
27213 	putnext(rq, mp);
27214 	CONN_DEC_REF(connp);
27215 }
27216 
27217 /*
27218  * Martian Address Filtering [RFC 1812, Section 5.3.7]
27219  */
27220 static boolean_t
27221 ip_no_forward(ipha_t *ipha, ill_t *ill)
27222 {
27223 	ipaddr_t ip_src, ip_dst;
27224 	ire_t *src_ire = NULL;
27225 
27226 	ip_src = ntohl(ipha->ipha_src);
27227 	ip_dst = ntohl(ipha->ipha_dst);
27228 
27229 	if (ip_dst == INADDR_ANY)
27230 		goto dont_forward;
27231 
27232 	if (IN_CLASSD(ip_src))
27233 		goto dont_forward;
27234 
27235 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
27236 		goto dont_forward;
27237 
27238 	if (IN_BADCLASS(ip_dst))
27239 		goto dont_forward;
27240 
27241 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
27242 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
27243 	if (src_ire != NULL) {
27244 		ire_refrele(src_ire);
27245 		goto dont_forward;
27246 	}
27247 
27248 	return (B_FALSE);
27249 
27250 dont_forward:
27251 	if (ip_debug > 2) {
27252 		printf("ip_no_forward: dropping packet received on %s\n",
27253 		    ill->ill_name);
27254 		pr_addr_dbg("ip_no_forward: from src %s\n",
27255 		    AF_INET, &ipha->ipha_src);
27256 		pr_addr_dbg("ip_no_forward: to dst %s\n",
27257 		    AF_INET, &ipha->ipha_dst);
27258 	}
27259 	BUMP_MIB(&ip_mib, ipForwProhibits);
27260 	return (B_TRUE);
27261 }
27262 
27263 static boolean_t
27264 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
27265 {
27266 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
27267 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
27268 		if (ip_debug > 2) {
27269 			if (ill != NULL) {
27270 				printf("ip_loopback_src_or_dst: "
27271 				    "dropping packet received on %s\n",
27272 				    ill->ill_name);
27273 			} else {
27274 				printf("ip_loopback_src_or_dst: "
27275 				    "dropping packet\n");
27276 			}
27277 
27278 			pr_addr_dbg(
27279 			    "ip_loopback_src_or_dst: from src %s\n",
27280 			    AF_INET, &ipha->ipha_src);
27281 			pr_addr_dbg(
27282 			    "ip_loopback_src_or_dst: to dst %s\n",
27283 			    AF_INET, &ipha->ipha_dst);
27284 		}
27285 
27286 		BUMP_MIB(&ip_mib, ipInAddrErrors);
27287 		return (B_TRUE);
27288 	}
27289 	return (B_FALSE);
27290 }
27291 
27292 /*
27293  * Return B_TRUE if the buffers differ in length or content.
27294  * This is used for comparing extension header buffers.
27295  * Note that an extension header would be declared different
27296  * even if all that changed was the next header value in that header i.e.
27297  * what really changed is the next extension header.
27298  */
27299 boolean_t
27300 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
27301     uint_t blen)
27302 {
27303 	if (!b_valid)
27304 		blen = 0;
27305 
27306 	if (alen != blen)
27307 		return (B_TRUE);
27308 	if (alen == 0)
27309 		return (B_FALSE);	/* Both zero length */
27310 	return (bcmp(abuf, bbuf, alen));
27311 }
27312 
27313 /*
27314  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
27315  * Return B_FALSE if memory allocation fails - don't change any state!
27316  */
27317 boolean_t
27318 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27319     const void *src, uint_t srclen)
27320 {
27321 	void *dst;
27322 
27323 	if (!src_valid)
27324 		srclen = 0;
27325 
27326 	ASSERT(*dstlenp == 0);
27327 	if (src != NULL && srclen != 0) {
27328 		dst = mi_alloc(srclen, BPRI_MED);
27329 		if (dst == NULL)
27330 			return (B_FALSE);
27331 	} else {
27332 		dst = NULL;
27333 	}
27334 	if (*dstp != NULL)
27335 		mi_free(*dstp);
27336 	*dstp = dst;
27337 	*dstlenp = dst == NULL ? 0 : srclen;
27338 	return (B_TRUE);
27339 }
27340 
27341 /*
27342  * Replace what is in *dst, *dstlen with the source.
27343  * Assumes ip_allocbuf has already been called.
27344  */
27345 void
27346 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27347     const void *src, uint_t srclen)
27348 {
27349 	if (!src_valid)
27350 		srclen = 0;
27351 
27352 	ASSERT(*dstlenp == srclen);
27353 	if (src != NULL && srclen != 0)
27354 		bcopy(src, *dstp, srclen);
27355 }
27356 
27357 /*
27358  * Free the storage pointed to by the members of an ip6_pkt_t.
27359  */
27360 void
27361 ip6_pkt_free(ip6_pkt_t *ipp)
27362 {
27363 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
27364 
27365 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
27366 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
27367 		ipp->ipp_hopopts = NULL;
27368 		ipp->ipp_hopoptslen = 0;
27369 	}
27370 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
27371 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
27372 		ipp->ipp_rtdstopts = NULL;
27373 		ipp->ipp_rtdstoptslen = 0;
27374 	}
27375 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
27376 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
27377 		ipp->ipp_dstopts = NULL;
27378 		ipp->ipp_dstoptslen = 0;
27379 	}
27380 	if (ipp->ipp_fields & IPPF_RTHDR) {
27381 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
27382 		ipp->ipp_rthdr = NULL;
27383 		ipp->ipp_rthdrlen = 0;
27384 	}
27385 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
27386 	    IPPF_RTHDR);
27387 }
27388