xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 5d0bc3ededb82d77f7c33d8f58e517a837ba5140)
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 = IPCL_ZONEID(connp);
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 = IPCL_ZONEID(connp);
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) ||
6357 		    (connp->conn_zoneid != zoneid && !connp->conn_allzones))) {
6358 			connp = connp->conn_next;
6359 		}
6360 
6361 		if (connp == NULL || connp->conn_upq == NULL)
6362 			goto notfound;
6363 
6364 		if (is_system_labeled() &&
6365 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6366 		    connp))
6367 			goto notfound;
6368 
6369 		CONN_INC_REF(connp);
6370 		mutex_exit(&connfp->connf_lock);
6371 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6372 		    recv_ill, ip_policy);
6373 		IP_STAT(ip_udp_fannorm);
6374 		CONN_DEC_REF(connp);
6375 		return;
6376 	}
6377 
6378 	/*
6379 	 * Broadcast and multicast case
6380 	 *
6381 	 * Need to check conn_wantpacket().
6382 	 * If SO_REUSEADDR has been set on the first we send the
6383 	 * packet to all clients that have joined the group and
6384 	 * match the port.
6385 	 */
6386 
6387 	while (connp != NULL) {
6388 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6389 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6390 		    (!is_system_labeled() ||
6391 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6392 		    connp)))
6393 			break;
6394 		connp = connp->conn_next;
6395 	}
6396 
6397 	if (connp == NULL || connp->conn_upq == NULL)
6398 		goto notfound;
6399 
6400 	first_connp = connp;
6401 	/*
6402 	 * When SO_REUSEADDR is not set, send the packet only to the first
6403 	 * matching connection in its zone by keeping track of the zoneid.
6404 	 */
6405 	reuseaddr = first_connp->conn_reuseaddr;
6406 	last_zoneid = first_connp->conn_zoneid;
6407 
6408 	CONN_INC_REF(connp);
6409 	connp = connp->conn_next;
6410 	for (;;) {
6411 		while (connp != NULL) {
6412 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6413 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6414 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6415 			    (!is_system_labeled() ||
6416 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6417 			    shared_addr, connp)))
6418 				break;
6419 			connp = connp->conn_next;
6420 		}
6421 		/*
6422 		 * Just copy the data part alone. The mctl part is
6423 		 * needed just for verifying policy and it is never
6424 		 * sent up.
6425 		 */
6426 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6427 		    ((mp1 = copymsg(mp)) == NULL))) {
6428 			/*
6429 			 * No more interested clients or memory
6430 			 * allocation failed
6431 			 */
6432 			connp = first_connp;
6433 			break;
6434 		}
6435 		if (connp->conn_zoneid != last_zoneid) {
6436 			/*
6437 			 * Update the zoneid so that the packet isn't sent to
6438 			 * any more conns in the same zone unless SO_REUSEADDR
6439 			 * is set.
6440 			 */
6441 			reuseaddr = connp->conn_reuseaddr;
6442 			last_zoneid = connp->conn_zoneid;
6443 		}
6444 		if (first_mp != NULL) {
6445 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6446 			    ipsec_info_type == IPSEC_IN);
6447 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6448 			if (first_mp1 == NULL) {
6449 				freemsg(mp1);
6450 				connp = first_connp;
6451 				break;
6452 			}
6453 		} else {
6454 			first_mp1 = NULL;
6455 		}
6456 		CONN_INC_REF(connp);
6457 		mutex_exit(&connfp->connf_lock);
6458 		/*
6459 		 * IPQoS notes: We don't send the packet for policy
6460 		 * processing here, will do it for the last one (below).
6461 		 * i.e. we do it per-packet now, but if we do policy
6462 		 * processing per-conn, then we would need to do it
6463 		 * here too.
6464 		 */
6465 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6466 		    ipha, flags, recv_ill, B_FALSE);
6467 		mutex_enter(&connfp->connf_lock);
6468 		/* Follow the next pointer before releasing the conn. */
6469 		next_connp = connp->conn_next;
6470 		IP_STAT(ip_udp_fanmb);
6471 		CONN_DEC_REF(connp);
6472 		connp = next_connp;
6473 	}
6474 
6475 	/* Last one.  Send it upstream. */
6476 	mutex_exit(&connfp->connf_lock);
6477 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6478 	    ip_policy);
6479 	IP_STAT(ip_udp_fanmb);
6480 	CONN_DEC_REF(connp);
6481 	return;
6482 
6483 notfound:
6484 
6485 	mutex_exit(&connfp->connf_lock);
6486 	IP_STAT(ip_udp_fanothers);
6487 	/*
6488 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6489 	 * have already been matched above, since they live in the IPv4
6490 	 * fanout tables. This implies we only need to
6491 	 * check for IPv6 in6addr_any endpoints here.
6492 	 * Thus we compare using ipv6_all_zeros instead of the destination
6493 	 * address, except for the multicast group membership lookup which
6494 	 * uses the IPv4 destination.
6495 	 */
6496 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6497 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6498 	mutex_enter(&connfp->connf_lock);
6499 	connp = connfp->connf_head;
6500 	if (!broadcast && !CLASSD(dst)) {
6501 		while (connp != NULL) {
6502 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6503 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6504 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6505 			    !connp->conn_ipv6_v6only)
6506 				break;
6507 			connp = connp->conn_next;
6508 		}
6509 
6510 		if (connp != NULL && is_system_labeled() &&
6511 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6512 		    connp))
6513 			connp = NULL;
6514 
6515 		if (connp == NULL || connp->conn_upq == NULL) {
6516 			/*
6517 			 * No one bound to this port.  Is
6518 			 * there a client that wants all
6519 			 * unclaimed datagrams?
6520 			 */
6521 			mutex_exit(&connfp->connf_lock);
6522 
6523 			if (mctl_present)
6524 				first_mp->b_cont = mp;
6525 			else
6526 				first_mp = mp;
6527 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6528 				ip_fanout_proto(q, first_mp, ill, ipha,
6529 				    flags | IP_FF_RAWIP, mctl_present,
6530 				    ip_policy, recv_ill, zoneid);
6531 			} else {
6532 				if (ip_fanout_send_icmp(q, first_mp, flags,
6533 				    ICMP_DEST_UNREACHABLE,
6534 				    ICMP_PORT_UNREACHABLE,
6535 				    mctl_present, zoneid)) {
6536 					BUMP_MIB(&ip_mib, udpNoPorts);
6537 				}
6538 			}
6539 			return;
6540 		}
6541 
6542 		CONN_INC_REF(connp);
6543 		mutex_exit(&connfp->connf_lock);
6544 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6545 		    recv_ill, ip_policy);
6546 		CONN_DEC_REF(connp);
6547 		return;
6548 	}
6549 	/*
6550 	 * IPv4 multicast packet being delivered to an AF_INET6
6551 	 * in6addr_any endpoint.
6552 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6553 	 * and not conn_wantpacket_v6() since any multicast membership is
6554 	 * for an IPv4-mapped multicast address.
6555 	 * The packet is sent to all clients in all zones that have joined the
6556 	 * group and match the port.
6557 	 */
6558 	while (connp != NULL) {
6559 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6560 		    srcport, v6src) &&
6561 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6562 		    (!is_system_labeled() ||
6563 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6564 		    connp)))
6565 			break;
6566 		connp = connp->conn_next;
6567 	}
6568 
6569 	if (connp == NULL || connp->conn_upq == NULL) {
6570 		/*
6571 		 * No one bound to this port.  Is
6572 		 * there a client that wants all
6573 		 * unclaimed datagrams?
6574 		 */
6575 		mutex_exit(&connfp->connf_lock);
6576 
6577 		if (mctl_present)
6578 			first_mp->b_cont = mp;
6579 		else
6580 			first_mp = mp;
6581 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6582 			ip_fanout_proto(q, first_mp, ill, ipha,
6583 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6584 			    recv_ill, zoneid);
6585 		} else {
6586 			/*
6587 			 * We used to attempt to send an icmp error here, but
6588 			 * since this is known to be a multicast packet
6589 			 * and we don't send icmp errors in response to
6590 			 * multicast, just drop the packet and give up sooner.
6591 			 */
6592 			BUMP_MIB(&ip_mib, udpNoPorts);
6593 			freemsg(first_mp);
6594 		}
6595 		return;
6596 	}
6597 
6598 	first_connp = connp;
6599 
6600 	CONN_INC_REF(connp);
6601 	connp = connp->conn_next;
6602 	for (;;) {
6603 		while (connp != NULL) {
6604 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6605 			    ipv6_all_zeros, srcport, v6src) &&
6606 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6607 			    (!is_system_labeled() ||
6608 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6609 			    shared_addr, connp)))
6610 				break;
6611 			connp = connp->conn_next;
6612 		}
6613 		/*
6614 		 * Just copy the data part alone. The mctl part is
6615 		 * needed just for verifying policy and it is never
6616 		 * sent up.
6617 		 */
6618 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6619 		    ((mp1 = copymsg(mp)) == NULL))) {
6620 			/*
6621 			 * No more intested clients or memory
6622 			 * allocation failed
6623 			 */
6624 			connp = first_connp;
6625 			break;
6626 		}
6627 		if (first_mp != NULL) {
6628 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6629 			    ipsec_info_type == IPSEC_IN);
6630 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6631 			if (first_mp1 == NULL) {
6632 				freemsg(mp1);
6633 				connp = first_connp;
6634 				break;
6635 			}
6636 		} else {
6637 			first_mp1 = NULL;
6638 		}
6639 		CONN_INC_REF(connp);
6640 		mutex_exit(&connfp->connf_lock);
6641 		/*
6642 		 * IPQoS notes: We don't send the packet for policy
6643 		 * processing here, will do it for the last one (below).
6644 		 * i.e. we do it per-packet now, but if we do policy
6645 		 * processing per-conn, then we would need to do it
6646 		 * here too.
6647 		 */
6648 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6649 		    ipha, flags, recv_ill, B_FALSE);
6650 		mutex_enter(&connfp->connf_lock);
6651 		/* Follow the next pointer before releasing the conn. */
6652 		next_connp = connp->conn_next;
6653 		CONN_DEC_REF(connp);
6654 		connp = next_connp;
6655 	}
6656 
6657 	/* Last one.  Send it upstream. */
6658 	mutex_exit(&connfp->connf_lock);
6659 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6660 	    ip_policy);
6661 	CONN_DEC_REF(connp);
6662 }
6663 
6664 /*
6665  * Complete the ip_wput header so that it
6666  * is possible to generate ICMP
6667  * errors.
6668  */
6669 static int
6670 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6671 {
6672 	ire_t *ire;
6673 
6674 	if (ipha->ipha_src == INADDR_ANY) {
6675 		ire = ire_lookup_local(zoneid);
6676 		if (ire == NULL) {
6677 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6678 			return (1);
6679 		}
6680 		ipha->ipha_src = ire->ire_addr;
6681 		ire_refrele(ire);
6682 	}
6683 	ipha->ipha_ttl = ip_def_ttl;
6684 	ipha->ipha_hdr_checksum = 0;
6685 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6686 	return (0);
6687 }
6688 
6689 /*
6690  * Nobody should be sending
6691  * packets up this stream
6692  */
6693 static void
6694 ip_lrput(queue_t *q, mblk_t *mp)
6695 {
6696 	mblk_t *mp1;
6697 
6698 	switch (mp->b_datap->db_type) {
6699 	case M_FLUSH:
6700 		/* Turn around */
6701 		if (*mp->b_rptr & FLUSHW) {
6702 			*mp->b_rptr &= ~FLUSHR;
6703 			qreply(q, mp);
6704 			return;
6705 		}
6706 		break;
6707 	}
6708 	/* Could receive messages that passed through ar_rput */
6709 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6710 		mp1->b_prev = mp1->b_next = NULL;
6711 	freemsg(mp);
6712 }
6713 
6714 /* Nobody should be sending packets down this stream */
6715 /* ARGSUSED */
6716 void
6717 ip_lwput(queue_t *q, mblk_t *mp)
6718 {
6719 	freemsg(mp);
6720 }
6721 
6722 /*
6723  * Move the first hop in any source route to ipha_dst and remove that part of
6724  * the source route.  Called by other protocols.  Errors in option formatting
6725  * are ignored - will be handled by ip_wput_options Return the final
6726  * destination (either ipha_dst or the last entry in a source route.)
6727  */
6728 ipaddr_t
6729 ip_massage_options(ipha_t *ipha)
6730 {
6731 	ipoptp_t	opts;
6732 	uchar_t		*opt;
6733 	uint8_t		optval;
6734 	uint8_t		optlen;
6735 	ipaddr_t	dst;
6736 	int		i;
6737 	ire_t		*ire;
6738 
6739 	ip2dbg(("ip_massage_options\n"));
6740 	dst = ipha->ipha_dst;
6741 	for (optval = ipoptp_first(&opts, ipha);
6742 	    optval != IPOPT_EOL;
6743 	    optval = ipoptp_next(&opts)) {
6744 		opt = opts.ipoptp_cur;
6745 		switch (optval) {
6746 			uint8_t off;
6747 		case IPOPT_SSRR:
6748 		case IPOPT_LSRR:
6749 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6750 				ip1dbg(("ip_massage_options: bad src route\n"));
6751 				break;
6752 			}
6753 			optlen = opts.ipoptp_len;
6754 			off = opt[IPOPT_OFFSET];
6755 			off--;
6756 		redo_srr:
6757 			if (optlen < IP_ADDR_LEN ||
6758 			    off > optlen - IP_ADDR_LEN) {
6759 				/* End of source route */
6760 				ip1dbg(("ip_massage_options: end of SR\n"));
6761 				break;
6762 			}
6763 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6764 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6765 			    ntohl(dst)));
6766 			/*
6767 			 * Check if our address is present more than
6768 			 * once as consecutive hops in source route.
6769 			 * XXX verify per-interface ip_forwarding
6770 			 * for source route?
6771 			 */
6772 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6773 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
6774 			if (ire != NULL) {
6775 				ire_refrele(ire);
6776 				off += IP_ADDR_LEN;
6777 				goto redo_srr;
6778 			}
6779 			if (dst == htonl(INADDR_LOOPBACK)) {
6780 				ip1dbg(("ip_massage_options: loopback addr in "
6781 				    "source route!\n"));
6782 				break;
6783 			}
6784 			/*
6785 			 * Update ipha_dst to be the first hop and remove the
6786 			 * first hop from the source route (by overwriting
6787 			 * part of the option with NOP options).
6788 			 */
6789 			ipha->ipha_dst = dst;
6790 			/* Put the last entry in dst */
6791 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6792 			    3;
6793 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6794 
6795 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6796 			    ntohl(dst)));
6797 			/* Move down and overwrite */
6798 			opt[IP_ADDR_LEN] = opt[0];
6799 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6800 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6801 			for (i = 0; i < IP_ADDR_LEN; i++)
6802 				opt[i] = IPOPT_NOP;
6803 			break;
6804 		}
6805 	}
6806 	return (dst);
6807 }
6808 
6809 /*
6810  * This function's job is to forward data to the reverse tunnel (FA->HA)
6811  * after doing a few checks. It is assumed that the incoming interface
6812  * of the packet is always different than the outgoing interface and the
6813  * ire_type of the found ire has to be a non-resolver type.
6814  *
6815  * IPQoS notes
6816  * IP policy is invoked twice for a forwarded packet, once on the read side
6817  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6818  * enabled.
6819  */
6820 static void
6821 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6822 {
6823 	ipha_t		*ipha;
6824 	queue_t		*q;
6825 	uint32_t 	pkt_len;
6826 #define	rptr    ((uchar_t *)ipha)
6827 	uint32_t 	sum;
6828 	uint32_t 	max_frag;
6829 	mblk_t		*first_mp;
6830 	uint32_t	ill_index;
6831 
6832 	ASSERT(ire != NULL);
6833 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6834 	ASSERT(ire->ire_stq != NULL);
6835 
6836 	/* Initiate read side IPPF processing */
6837 	if (IPP_ENABLED(IPP_FWD_IN)) {
6838 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6839 		ip_process(IPP_FWD_IN, &mp, ill_index);
6840 		if (mp == NULL) {
6841 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6842 			    "dropped during IPPF processing\n"));
6843 			return;
6844 		}
6845 	}
6846 
6847 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6848 		ILLF_ROUTER) == 0) ||
6849 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6850 		BUMP_MIB(&ip_mib, ipForwProhibits);
6851 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6852 		    "forwarding is not turned on\n"));
6853 		goto drop_pkt;
6854 	}
6855 
6856 	/*
6857 	 * Don't forward if the interface is down
6858 	 */
6859 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6860 		BUMP_MIB(&ip_mib, ipInDiscards);
6861 		goto drop_pkt;
6862 	}
6863 
6864 	ipha = (ipha_t *)mp->b_rptr;
6865 	pkt_len = ntohs(ipha->ipha_length);
6866 	/* Adjust the checksum to reflect the ttl decrement. */
6867 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6868 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6869 	if (ipha->ipha_ttl-- <= 1) {
6870 		if (ip_csum_hdr(ipha)) {
6871 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6872 			goto drop_pkt;
6873 		}
6874 		q = ire->ire_stq;
6875 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6876 		    BPRI_HI)) == NULL) {
6877 			goto drop_pkt;
6878 		}
6879 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6880 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6881 
6882 		return;
6883 	}
6884 
6885 	/* Get the ill_index of the ILL */
6886 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6887 
6888 	/*
6889 	 * ip_mrtun_forward is only used by foreign agent to reverse
6890 	 * tunnel the incoming packet. So it does not do any option
6891 	 * processing for source routing.
6892 	 */
6893 	max_frag = ire->ire_max_frag;
6894 	if (pkt_len > max_frag) {
6895 		/*
6896 		 * It needs fragging on its way out.  We haven't
6897 		 * verified the header checksum yet.  Since we
6898 		 * are going to put a surely good checksum in the
6899 		 * outgoing header, we have to make sure that it
6900 		 * was good coming in.
6901 		 */
6902 		if (ip_csum_hdr(ipha)) {
6903 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6904 			goto drop_pkt;
6905 		}
6906 
6907 		/* Initiate write side IPPF processing */
6908 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6909 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6910 			if (mp == NULL) {
6911 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6912 				    "dropped/deferred during ip policy "\
6913 				    "processing\n"));
6914 				return;
6915 			}
6916 		}
6917 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6918 		    BPRI_HI)) == NULL) {
6919 			goto drop_pkt;
6920 		}
6921 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6922 		mp = first_mp;
6923 
6924 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6925 		return;
6926 	}
6927 
6928 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6929 
6930 	ASSERT(ire->ire_ipif != NULL);
6931 
6932 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6933 	if (mp == NULL) {
6934 		BUMP_MIB(&ip_mib, ipInDiscards);
6935 		return;
6936 	}
6937 
6938 	/* Now send the packet to the tunnel interface */
6939 	q = ire->ire_stq;
6940 	UPDATE_IB_PKT_COUNT(ire);
6941 	ire->ire_last_used_time = lbolt;
6942 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6943 	putnext(q, mp);
6944 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6945 	return;
6946 
6947 drop_pkt:;
6948 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6949 	freemsg(mp);
6950 #undef	rptr
6951 }
6952 
6953 /*
6954  * Fills the ipsec_out_t data structure with appropriate fields and
6955  * prepends it to mp which contains the IP hdr + data that was meant
6956  * to be forwarded. Please note that ipsec_out_info data structure
6957  * is used here to communicate the outgoing ill path at ip_wput()
6958  * for the ICMP error packet. This has nothing to do with ipsec IP
6959  * security. ipsec_out_t is really used to pass the info to the module
6960  * IP where this information cannot be extracted from conn.
6961  * This functions is called by ip_mrtun_forward().
6962  */
6963 void
6964 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6965 {
6966 	ipsec_out_t	*io;
6967 
6968 	ASSERT(xmit_ill != NULL);
6969 	first_mp->b_datap->db_type = M_CTL;
6970 	first_mp->b_wptr += sizeof (ipsec_info_t);
6971 	/*
6972 	 * This is to pass info to ip_wput in absence of conn.
6973 	 * ipsec_out_secure will be B_FALSE because of this.
6974 	 * Thus ipsec_out_secure being B_FALSE indicates that
6975 	 * this is not IPSEC security related information.
6976 	 */
6977 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6978 	io = (ipsec_out_t *)first_mp->b_rptr;
6979 	io->ipsec_out_type = IPSEC_OUT;
6980 	io->ipsec_out_len = sizeof (ipsec_out_t);
6981 	first_mp->b_cont = mp;
6982 	io->ipsec_out_ill_index =
6983 	    xmit_ill->ill_phyint->phyint_ifindex;
6984 	io->ipsec_out_xmit_if = B_TRUE;
6985 }
6986 
6987 /*
6988  * Return the network mask
6989  * associated with the specified address.
6990  */
6991 ipaddr_t
6992 ip_net_mask(ipaddr_t addr)
6993 {
6994 	uchar_t	*up = (uchar_t *)&addr;
6995 	ipaddr_t mask = 0;
6996 	uchar_t	*maskp = (uchar_t *)&mask;
6997 
6998 #if defined(__i386) || defined(__amd64)
6999 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7000 #endif
7001 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7002 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7003 #endif
7004 	if (CLASSD(addr)) {
7005 		maskp[0] = 0xF0;
7006 		return (mask);
7007 	}
7008 	if (addr == 0)
7009 		return (0);
7010 	maskp[0] = 0xFF;
7011 	if ((up[0] & 0x80) == 0)
7012 		return (mask);
7013 
7014 	maskp[1] = 0xFF;
7015 	if ((up[0] & 0xC0) == 0x80)
7016 		return (mask);
7017 
7018 	maskp[2] = 0xFF;
7019 	if ((up[0] & 0xE0) == 0xC0)
7020 		return (mask);
7021 
7022 	/* Must be experimental or multicast, indicate as much */
7023 	return ((ipaddr_t)0);
7024 }
7025 
7026 /*
7027  * Select an ill for the packet by considering load spreading across
7028  * a different ill in the group if dst_ill is part of some group.
7029  */
7030 static ill_t *
7031 ip_newroute_get_dst_ill(ill_t *dst_ill)
7032 {
7033 	ill_t *ill;
7034 
7035 	/*
7036 	 * We schedule irrespective of whether the source address is
7037 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7038 	 */
7039 	ill = illgrp_scheduler(dst_ill);
7040 	if (ill == NULL)
7041 		return (NULL);
7042 
7043 	/*
7044 	 * For groups with names ip_sioctl_groupname ensures that all
7045 	 * ills are of same type. For groups without names, ifgrp_insert
7046 	 * ensures this.
7047 	 */
7048 	ASSERT(dst_ill->ill_type == ill->ill_type);
7049 
7050 	return (ill);
7051 }
7052 
7053 /*
7054  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7055  */
7056 ill_t *
7057 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7058 {
7059 	ill_t *ret_ill;
7060 
7061 	ASSERT(ifindex != 0);
7062 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7063 	if (ret_ill == NULL ||
7064 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7065 		if (isv6) {
7066 			if (ill != NULL) {
7067 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7068 			} else {
7069 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7070 			}
7071 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7072 			    "bad ifindex %d.\n", ifindex));
7073 		} else {
7074 			BUMP_MIB(&ip_mib, ipOutDiscards);
7075 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7076 			    "bad ifindex %d.\n", ifindex));
7077 		}
7078 		if (ret_ill != NULL)
7079 			ill_refrele(ret_ill);
7080 		freemsg(first_mp);
7081 		return (NULL);
7082 	}
7083 
7084 	return (ret_ill);
7085 }
7086 
7087 /*
7088  * IPv4 -
7089  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7090  * out a packet to a destination address for which we do not have specific
7091  * (or sufficient) routing information.
7092  *
7093  * NOTE : These are the scopes of some of the variables that point at IRE,
7094  *	  which needs to be followed while making any future modifications
7095  *	  to avoid memory leaks.
7096  *
7097  *	- ire and sire are the entries looked up initially by
7098  *	  ire_ftable_lookup.
7099  *	- ipif_ire is used to hold the interface ire associated with
7100  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7101  *	  it before branching out to error paths.
7102  *	- save_ire is initialized before ire_create, so that ire returned
7103  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7104  *	  before breaking out of the switch.
7105  *
7106  *	Thus on failures, we have to REFRELE only ire and sire, if they
7107  *	are not NULL.
7108  */
7109 void
7110 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
7111 {
7112 	areq_t	*areq;
7113 	ipaddr_t gw = 0;
7114 	ire_t	*ire = NULL;
7115 	mblk_t	*res_mp;
7116 	ipaddr_t *addrp;
7117 	ipaddr_t nexthop_addr;
7118 	ipif_t  *src_ipif = NULL;
7119 	ill_t	*dst_ill = NULL;
7120 	ipha_t  *ipha;
7121 	ire_t	*sire = NULL;
7122 	mblk_t	*first_mp;
7123 	ire_t	*save_ire;
7124 	mblk_t	*dlureq_mp;
7125 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7126 	ushort_t ire_marks = 0;
7127 	boolean_t mctl_present;
7128 	ipsec_out_t *io;
7129 	mblk_t	*saved_mp;
7130 	ire_t	*first_sire = NULL;
7131 	mblk_t	*copy_mp = NULL;
7132 	mblk_t	*xmit_mp = NULL;
7133 	ipaddr_t save_dst;
7134 	uint32_t multirt_flags =
7135 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7136 	boolean_t multirt_is_resolvable;
7137 	boolean_t multirt_resolve_next;
7138 	boolean_t do_attach_ill = B_FALSE;
7139 	boolean_t ip_nexthop = B_FALSE;
7140 	zoneid_t zoneid;
7141 	tsol_ire_gw_secattr_t *attrp = NULL;
7142 	tsol_gcgrp_t *gcgrp = NULL;
7143 	tsol_gcgrp_addr_t ga;
7144 
7145 	if (ip_debug > 2) {
7146 		/* ip1dbg */
7147 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7148 	}
7149 
7150 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7151 	if (mctl_present) {
7152 		io = (ipsec_out_t *)first_mp->b_rptr;
7153 		zoneid = io->ipsec_out_zoneid;
7154 		ASSERT(zoneid != ALL_ZONES);
7155 	} else if (connp != NULL) {
7156 		zoneid = connp->conn_zoneid;
7157 	} else {
7158 		zoneid = GLOBAL_ZONEID;
7159 	}
7160 
7161 	ipha = (ipha_t *)mp->b_rptr;
7162 
7163 	/* All multicast lookups come through ip_newroute_ipif() */
7164 	if (CLASSD(dst)) {
7165 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7166 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7167 		freemsg(first_mp);
7168 		return;
7169 	}
7170 
7171 	if (ip_loopback_src_or_dst(ipha, NULL)) {
7172 		goto icmp_err_ret;
7173 	}
7174 
7175 	if (mctl_present && io->ipsec_out_attach_if) {
7176 		/* ip_grab_attach_ill returns a held ill */
7177 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7178 		    io->ipsec_out_ill_index, B_FALSE);
7179 
7180 		/* Failure case frees things for us. */
7181 		if (attach_ill == NULL)
7182 			return;
7183 
7184 		/*
7185 		 * Check if we need an ire that will not be
7186 		 * looked up by anybody else i.e. HIDDEN.
7187 		 */
7188 		if (ill_is_probeonly(attach_ill))
7189 			ire_marks = IRE_MARK_HIDDEN;
7190 	}
7191 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7192 		ip_nexthop = B_TRUE;
7193 		nexthop_addr = io->ipsec_out_nexthop_addr;
7194 	}
7195 	/*
7196 	 * If this IRE is created for forwarding or it is not for
7197 	 * traffic for congestion controlled protocols, mark it as temporary.
7198 	 */
7199 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7200 		ire_marks |= IRE_MARK_TEMPORARY;
7201 
7202 	/*
7203 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7204 	 * chain until it gets the most specific information available.
7205 	 * For example, we know that there is no IRE_CACHE for this dest,
7206 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7207 	 * ire_ftable_lookup will look up the gateway, etc.
7208 	 * Check if in_ill != NULL. If it is true, the packet must be
7209 	 * from an incoming interface where RTA_SRCIFP is set.
7210 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7211 	 * to the destination, of equal netmask length in the forward table,
7212 	 * will be recursively explored. If no information is available
7213 	 * for the final gateway of that route, we force the returned ire
7214 	 * to be equal to sire using MATCH_IRE_PARENT.
7215 	 * At least, in this case we have a starting point (in the buckets)
7216 	 * to look for other routes to the destination in the forward table.
7217 	 * This is actually used only for multirouting, where a list
7218 	 * of routes has to be processed in sequence.
7219 	 */
7220 	if (in_ill != NULL) {
7221 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7222 		    in_ill, MATCH_IRE_TYPE);
7223 	} else if (ip_nexthop) {
7224 		/*
7225 		 * The first time we come here, we look for an IRE_INTERFACE
7226 		 * entry for the specified nexthop, set the dst to be the
7227 		 * nexthop address and create an IRE_CACHE entry for the
7228 		 * nexthop. The next time around, we are able to find an
7229 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7230 		 * nexthop address and create an IRE_CACHE entry for the
7231 		 * destination address via the specified nexthop.
7232 		 */
7233 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7234 		    MBLK_GETLABEL(mp));
7235 		if (ire != NULL) {
7236 			gw = nexthop_addr;
7237 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7238 		} else {
7239 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7240 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7241 			    MBLK_GETLABEL(mp),
7242 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7243 			if (ire != NULL) {
7244 				dst = nexthop_addr;
7245 			}
7246 		}
7247 	} else if (attach_ill == NULL) {
7248 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7249 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7250 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7251 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7252 		    MATCH_IRE_SECATTR);
7253 	} else {
7254 		/*
7255 		 * attach_ill is set only for communicating with
7256 		 * on-link hosts. So, don't look for DEFAULT.
7257 		 */
7258 		ipif_t	*attach_ipif;
7259 
7260 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7261 		if (attach_ipif == NULL) {
7262 			ill_refrele(attach_ill);
7263 			goto icmp_err_ret;
7264 		}
7265 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7266 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7267 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7268 		    MATCH_IRE_SECATTR);
7269 		ipif_refrele(attach_ipif);
7270 	}
7271 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7272 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7273 
7274 	/*
7275 	 * This loop is run only once in most cases.
7276 	 * We loop to resolve further routes only when the destination
7277 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7278 	 */
7279 	do {
7280 		/* Clear the previous iteration's values */
7281 		if (src_ipif != NULL) {
7282 			ipif_refrele(src_ipif);
7283 			src_ipif = NULL;
7284 		}
7285 		if (dst_ill != NULL) {
7286 			ill_refrele(dst_ill);
7287 			dst_ill = NULL;
7288 		}
7289 
7290 		multirt_resolve_next = B_FALSE;
7291 		/*
7292 		 * We check if packets have to be multirouted.
7293 		 * In this case, given the current <ire, sire> couple,
7294 		 * we look for the next suitable <ire, sire>.
7295 		 * This check is done in ire_multirt_lookup(),
7296 		 * which applies various criteria to find the next route
7297 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7298 		 * unchanged if it detects it has not been tried yet.
7299 		 */
7300 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7301 			ip3dbg(("ip_newroute: starting next_resolution "
7302 			    "with first_mp %p, tag %d\n",
7303 			    (void *)first_mp,
7304 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7305 
7306 			ASSERT(sire != NULL);
7307 			multirt_is_resolvable =
7308 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7309 				MBLK_GETLABEL(mp));
7310 
7311 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7312 			    "ire %p, sire %p\n",
7313 			    multirt_is_resolvable,
7314 			    (void *)ire, (void *)sire));
7315 
7316 			if (!multirt_is_resolvable) {
7317 				/*
7318 				 * No more multirt route to resolve; give up
7319 				 * (all routes resolved or no more
7320 				 * resolvable routes).
7321 				 */
7322 				if (ire != NULL) {
7323 					ire_refrele(ire);
7324 					ire = NULL;
7325 				}
7326 			} else {
7327 				ASSERT(sire != NULL);
7328 				ASSERT(ire != NULL);
7329 				/*
7330 				 * We simply use first_sire as a flag that
7331 				 * indicates if a resolvable multirt route
7332 				 * has already been found.
7333 				 * If it is not the case, we may have to send
7334 				 * an ICMP error to report that the
7335 				 * destination is unreachable.
7336 				 * We do not IRE_REFHOLD first_sire.
7337 				 */
7338 				if (first_sire == NULL) {
7339 					first_sire = sire;
7340 				}
7341 			}
7342 		}
7343 		if (ire == NULL) {
7344 			if (ip_debug > 3) {
7345 				/* ip2dbg */
7346 				pr_addr_dbg("ip_newroute: "
7347 				    "can't resolve %s\n", AF_INET, &dst);
7348 			}
7349 			ip3dbg(("ip_newroute: "
7350 			    "ire %p, sire %p, first_sire %p\n",
7351 			    (void *)ire, (void *)sire, (void *)first_sire));
7352 
7353 			if (sire != NULL) {
7354 				ire_refrele(sire);
7355 				sire = NULL;
7356 			}
7357 
7358 			if (first_sire != NULL) {
7359 				/*
7360 				 * At least one multirt route has been found
7361 				 * in the same call to ip_newroute();
7362 				 * there is no need to report an ICMP error.
7363 				 * first_sire was not IRE_REFHOLDed.
7364 				 */
7365 				MULTIRT_DEBUG_UNTAG(first_mp);
7366 				freemsg(first_mp);
7367 				return;
7368 			}
7369 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7370 			    RTA_DST);
7371 			if (attach_ill != NULL)
7372 				ill_refrele(attach_ill);
7373 			goto icmp_err_ret;
7374 		}
7375 
7376 		/*
7377 		 * When RTA_SRCIFP is used to add a route, then an interface
7378 		 * route is added in the source interface's routing table.
7379 		 * If the outgoing interface of this route is of type
7380 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7381 		 * ire_dlureq_mp is set to NULL. Later, when this route is
7382 		 * first used for forwarding packet, ip_newroute() is called
7383 		 * to resolve the hardware address of the outgoing ipif.
7384 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7385 		 * source interface based table. We only come here if the
7386 		 * outgoing interface is a resolver interface and we don't
7387 		 * have the ire_dlureq_mp information yet.
7388 		 * If in_ill is not null that means it is called from
7389 		 * ip_rput.
7390 		 */
7391 
7392 		ASSERT(ire->ire_in_ill == NULL ||
7393 		    (ire->ire_type == IRE_IF_RESOLVER &&
7394 		    ire->ire_dlureq_mp == NULL));
7395 
7396 		/*
7397 		 * Verify that the returned IRE does not have either
7398 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7399 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7400 		 */
7401 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7402 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7403 			if (attach_ill != NULL)
7404 				ill_refrele(attach_ill);
7405 			goto icmp_err_ret;
7406 		}
7407 		/*
7408 		 * Increment the ire_ob_pkt_count field for ire if it is an
7409 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7410 		 * increment the same for the parent IRE, sire, if it is some
7411 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7412 		 * and HOST_REDIRECT).
7413 		 */
7414 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7415 			UPDATE_OB_PKT_COUNT(ire);
7416 			ire->ire_last_used_time = lbolt;
7417 		}
7418 
7419 		if (sire != NULL) {
7420 			gw = sire->ire_gateway_addr;
7421 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7422 			    IRE_INTERFACE)) == 0);
7423 			UPDATE_OB_PKT_COUNT(sire);
7424 			sire->ire_last_used_time = lbolt;
7425 		}
7426 		/*
7427 		 * We have a route to reach the destination.
7428 		 *
7429 		 * 1) If the interface is part of ill group, try to get a new
7430 		 *    ill taking load spreading into account.
7431 		 *
7432 		 * 2) After selecting the ill, get a source address that
7433 		 *    might create good inbound load spreading.
7434 		 *    ipif_select_source does this for us.
7435 		 *
7436 		 * If the application specified the ill (ifindex), we still
7437 		 * load spread. Only if the packets needs to go out
7438 		 * specifically on a given ill e.g. binding to
7439 		 * IPIF_NOFAILOVER address, then we don't try to use a
7440 		 * different ill for load spreading.
7441 		 */
7442 		if (attach_ill == NULL) {
7443 			/*
7444 			 * Don't perform outbound load spreading in the
7445 			 * case of an RTF_MULTIRT route, as we actually
7446 			 * typically want to replicate outgoing packets
7447 			 * through particular interfaces.
7448 			 */
7449 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7450 				dst_ill = ire->ire_ipif->ipif_ill;
7451 				/* for uniformity */
7452 				ill_refhold(dst_ill);
7453 			} else {
7454 				/*
7455 				 * If we are here trying to create an IRE_CACHE
7456 				 * for an offlink destination and have the
7457 				 * IRE_CACHE for the next hop and the latter is
7458 				 * using virtual IP source address selection i.e
7459 				 * it's ire->ire_ipif is pointing to a virtual
7460 				 * network interface (vni) then
7461 				 * ip_newroute_get_dst_ll() will return the vni
7462 				 * interface as the dst_ill. Since the vni is
7463 				 * virtual i.e not associated with any physical
7464 				 * interface, it cannot be the dst_ill, hence
7465 				 * in such a case call ip_newroute_get_dst_ll()
7466 				 * with the stq_ill instead of the ire_ipif ILL.
7467 				 * The function returns a refheld ill.
7468 				 */
7469 				if ((ire->ire_type == IRE_CACHE) &&
7470 				    IS_VNI(ire->ire_ipif->ipif_ill))
7471 					dst_ill = ip_newroute_get_dst_ill(
7472 						ire->ire_stq->q_ptr);
7473 				else
7474 					dst_ill = ip_newroute_get_dst_ill(
7475 						ire->ire_ipif->ipif_ill);
7476 			}
7477 			if (dst_ill == NULL) {
7478 				if (ip_debug > 2) {
7479 					pr_addr_dbg("ip_newroute: "
7480 					    "no dst ill for dst"
7481 					    " %s\n", AF_INET, &dst);
7482 				}
7483 				goto icmp_err_ret;
7484 			}
7485 		} else {
7486 			dst_ill = ire->ire_ipif->ipif_ill;
7487 			/* for uniformity */
7488 			ill_refhold(dst_ill);
7489 			/*
7490 			 * We should have found a route matching ill as we
7491 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7492 			 * Rather than asserting, when there is a mismatch,
7493 			 * we just drop the packet.
7494 			 */
7495 			if (dst_ill != attach_ill) {
7496 				ip0dbg(("ip_newroute: Packet dropped as "
7497 				    "IPIF_NOFAILOVER ill is %s, "
7498 				    "ire->ire_ipif->ipif_ill is %s\n",
7499 				    attach_ill->ill_name,
7500 				    dst_ill->ill_name));
7501 				ill_refrele(attach_ill);
7502 				goto icmp_err_ret;
7503 			}
7504 		}
7505 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7506 		if (attach_ill != NULL) {
7507 			ill_refrele(attach_ill);
7508 			attach_ill = NULL;
7509 			do_attach_ill = B_TRUE;
7510 		}
7511 		ASSERT(dst_ill != NULL);
7512 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7513 
7514 		/*
7515 		 * Pick the best source address from dst_ill.
7516 		 *
7517 		 * 1) If it is part of a multipathing group, we would
7518 		 *    like to spread the inbound packets across different
7519 		 *    interfaces. ipif_select_source picks a random source
7520 		 *    across the different ills in the group.
7521 		 *
7522 		 * 2) If it is not part of a multipathing group, we try
7523 		 *    to pick the source address from the destination
7524 		 *    route. Clustering assumes that when we have multiple
7525 		 *    prefixes hosted on an interface, the prefix of the
7526 		 *    source address matches the prefix of the destination
7527 		 *    route. We do this only if the address is not
7528 		 *    DEPRECATED.
7529 		 *
7530 		 * 3) If the conn is in a different zone than the ire, we
7531 		 *    need to pick a source address from the right zone.
7532 		 *
7533 		 * NOTE : If we hit case (1) above, the prefix of the source
7534 		 *	  address picked may not match the prefix of the
7535 		 *	  destination routes prefix as ipif_select_source
7536 		 *	  does not look at "dst" while picking a source
7537 		 *	  address.
7538 		 *	  If we want the same behavior as (2), we will need
7539 		 *	  to change the behavior of ipif_select_source.
7540 		 */
7541 		ASSERT(src_ipif == NULL);
7542 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7543 			/*
7544 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7545 			 * Check that the ipif matching the requested source
7546 			 * address still exists.
7547 			 */
7548 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7549 			    zoneid, NULL, NULL, NULL, NULL);
7550 		}
7551 		if (src_ipif == NULL) {
7552 			ire_marks |= IRE_MARK_USESRC_CHECK;
7553 			if ((dst_ill->ill_group != NULL) ||
7554 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7555 			    (connp != NULL && ire->ire_zoneid != zoneid &&
7556 			    ire->ire_zoneid != ALL_ZONES) ||
7557 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7558 				/*
7559 				 * If the destination is reachable via a
7560 				 * given gateway, the selected source address
7561 				 * should be in the same subnet as the gateway.
7562 				 * Otherwise, the destination is not reachable.
7563 				 *
7564 				 * If there are no interfaces on the same subnet
7565 				 * as the destination, ipif_select_source gives
7566 				 * first non-deprecated interface which might be
7567 				 * on a different subnet than the gateway.
7568 				 * This is not desirable. Hence pass the dst_ire
7569 				 * source address to ipif_select_source.
7570 				 * It is sure that the destination is reachable
7571 				 * with the dst_ire source address subnet.
7572 				 * So passing dst_ire source address to
7573 				 * ipif_select_source will make sure that the
7574 				 * selected source will be on the same subnet
7575 				 * as dst_ire source address.
7576 				 */
7577 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7578 				src_ipif = ipif_select_source(dst_ill, saddr,
7579 				    zoneid);
7580 				if (src_ipif == NULL) {
7581 					if (ip_debug > 2) {
7582 						pr_addr_dbg("ip_newroute: "
7583 						    "no src for dst %s ",
7584 						    AF_INET, &dst);
7585 						printf("through interface %s\n",
7586 						    dst_ill->ill_name);
7587 					}
7588 					goto icmp_err_ret;
7589 				}
7590 			} else {
7591 				src_ipif = ire->ire_ipif;
7592 				ASSERT(src_ipif != NULL);
7593 				/* hold src_ipif for uniformity */
7594 				ipif_refhold(src_ipif);
7595 			}
7596 		}
7597 
7598 		/*
7599 		 * Assign a source address while we have the conn.
7600 		 * We can't have ip_wput_ire pick a source address when the
7601 		 * packet returns from arp since we need to look at
7602 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7603 		 * going through arp.
7604 		 *
7605 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7606 		 *	  it uses ip6i to store this information.
7607 		 */
7608 		if (ipha->ipha_src == INADDR_ANY &&
7609 		    (connp == NULL || !connp->conn_unspec_src)) {
7610 			ipha->ipha_src = src_ipif->ipif_src_addr;
7611 		}
7612 		if (ip_debug > 3) {
7613 			/* ip2dbg */
7614 			pr_addr_dbg("ip_newroute: first hop %s\n",
7615 			    AF_INET, &gw);
7616 		}
7617 		ip2dbg(("\tire type %s (%d)\n",
7618 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7619 
7620 		/*
7621 		 * The TTL of multirouted packets is bounded by the
7622 		 * ip_multirt_ttl ndd variable.
7623 		 */
7624 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7625 			/* Force TTL of multirouted packets */
7626 			if ((ip_multirt_ttl > 0) &&
7627 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7628 				ip2dbg(("ip_newroute: forcing multirt TTL "
7629 				    "to %d (was %d), dst 0x%08x\n",
7630 				    ip_multirt_ttl, ipha->ipha_ttl,
7631 				    ntohl(sire->ire_addr)));
7632 				ipha->ipha_ttl = ip_multirt_ttl;
7633 			}
7634 		}
7635 		/*
7636 		 * At this point in ip_newroute(), ire is either the
7637 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7638 		 * destination or an IRE_INTERFACE type that should be used
7639 		 * to resolve an on-subnet destination or an on-subnet
7640 		 * next-hop gateway.
7641 		 *
7642 		 * In the IRE_CACHE case, we have the following :
7643 		 *
7644 		 * 1) src_ipif - used for getting a source address.
7645 		 *
7646 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7647 		 *    means packets using this IRE_CACHE will go out on
7648 		 *    dst_ill.
7649 		 *
7650 		 * 3) The IRE sire will point to the prefix that is the
7651 		 *    longest  matching route for the destination. These
7652 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7653 		 *    and IRE_HOST_REDIRECT.
7654 		 *
7655 		 *    The newly created IRE_CACHE entry for the off-subnet
7656 		 *    destination is tied to both the prefix route and the
7657 		 *    interface route used to resolve the next-hop gateway
7658 		 *    via the ire_phandle and ire_ihandle fields,
7659 		 *    respectively.
7660 		 *
7661 		 * In the IRE_INTERFACE case, we have the following :
7662 		 *
7663 		 * 1) src_ipif - used for getting a source address.
7664 		 *
7665 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7666 		 *    means packets using the IRE_CACHE that we will build
7667 		 *    here will go out on dst_ill.
7668 		 *
7669 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7670 		 *    to be created will only be tied to the IRE_INTERFACE
7671 		 *    that was derived from the ire_ihandle field.
7672 		 *
7673 		 *    If sire is non-NULL, it means the destination is
7674 		 *    off-link and we will first create the IRE_CACHE for the
7675 		 *    gateway. Next time through ip_newroute, we will create
7676 		 *    the IRE_CACHE for the final destination as described
7677 		 *    above.
7678 		 *
7679 		 * In both cases, after the current resolution has been
7680 		 * completed (or possibly initialised, in the IRE_INTERFACE
7681 		 * case), the loop may be re-entered to attempt the resolution
7682 		 * of another RTF_MULTIRT route.
7683 		 *
7684 		 * When an IRE_CACHE entry for the off-subnet destination is
7685 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7686 		 * for further processing in emission loops.
7687 		 */
7688 		save_ire = ire;
7689 		switch (ire->ire_type) {
7690 		case IRE_CACHE: {
7691 			ire_t	*ipif_ire;
7692 			mblk_t	*ire_fp_mp;
7693 
7694 			if (gw == 0)
7695 				gw = ire->ire_gateway_addr;
7696 			/*
7697 			 * We need 3 ire's to create a new cache ire for an
7698 			 * off-link destination from the cache ire of the
7699 			 * gateway.
7700 			 *
7701 			 *	1. The prefix ire 'sire' (Note that this does
7702 			 *	   not apply to the conn_nexthop_set case)
7703 			 *	2. The cache ire of the gateway 'ire'
7704 			 *	3. The interface ire 'ipif_ire'
7705 			 *
7706 			 * We have (1) and (2). We lookup (3) below.
7707 			 *
7708 			 * If there is no interface route to the gateway,
7709 			 * it is a race condition, where we found the cache
7710 			 * but the interface route has been deleted.
7711 			 */
7712 			if (ip_nexthop) {
7713 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7714 			} else {
7715 				ipif_ire =
7716 				    ire_ihandle_lookup_offlink(ire, sire);
7717 			}
7718 			if (ipif_ire == NULL) {
7719 				ip1dbg(("ip_newroute: "
7720 				    "ire_ihandle_lookup_offlink failed\n"));
7721 				goto icmp_err_ret;
7722 			}
7723 			/*
7724 			 * XXX We are using the same dlureq_mp
7725 			 * (DL_UNITDATA_REQ) though the save_ire is not
7726 			 * pointing at the same ill.
7727 			 * This is incorrect. We need to send it up to the
7728 			 * resolver to get the right dlureq_mp. For ethernets
7729 			 * this may be okay (ill_type == DL_ETHER).
7730 			 */
7731 			dlureq_mp = save_ire->ire_dlureq_mp;
7732 			ire_fp_mp = NULL;
7733 			/*
7734 			 * save_ire's ire_fp_mp can't change since it is
7735 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7736 			 * LOCK_IRE_FP_MP does not do any useful work in
7737 			 * the case of IRE_CACHE. So we don't use it below.
7738 			 */
7739 			if (save_ire->ire_stq == dst_ill->ill_wq)
7740 				ire_fp_mp = save_ire->ire_fp_mp;
7741 
7742 			/*
7743 			 * Check cached gateway IRE for any security
7744 			 * attributes; if found, associate the gateway
7745 			 * credentials group to the destination IRE.
7746 			 */
7747 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
7748 				mutex_enter(&attrp->igsa_lock);
7749 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
7750 					GCGRP_REFHOLD(gcgrp);
7751 				mutex_exit(&attrp->igsa_lock);
7752 			}
7753 
7754 			ire = ire_create(
7755 			    (uchar_t *)&dst,		/* dest address */
7756 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7757 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7758 			    (uchar_t *)&gw,		/* gateway address */
7759 			    NULL,
7760 			    &save_ire->ire_max_frag,
7761 			    ire_fp_mp,			/* Fast Path header */
7762 			    dst_ill->ill_rq,		/* recv-from queue */
7763 			    dst_ill->ill_wq,		/* send-to queue */
7764 			    IRE_CACHE,			/* IRE type */
7765 			    save_ire->ire_dlureq_mp,
7766 			    src_ipif,
7767 			    in_ill,			/* incoming ill */
7768 			    (sire != NULL) ?
7769 				sire->ire_mask : 0, 	/* Parent mask */
7770 			    (sire != NULL) ?
7771 				sire->ire_phandle : 0,  /* Parent handle */
7772 			    ipif_ire->ire_ihandle,	/* Interface handle */
7773 			    (sire != NULL) ? (sire->ire_flags &
7774 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7775 			    (sire != NULL) ?
7776 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
7777 			    NULL,
7778 			    gcgrp);
7779 
7780 			if (ire == NULL) {
7781 				if (gcgrp != NULL) {
7782 					GCGRP_REFRELE(gcgrp);
7783 					gcgrp = NULL;
7784 				}
7785 				ire_refrele(ipif_ire);
7786 				ire_refrele(save_ire);
7787 				break;
7788 			}
7789 
7790 			/* reference now held by IRE */
7791 			gcgrp = NULL;
7792 
7793 			ire->ire_marks |= ire_marks;
7794 
7795 			/*
7796 			 * Prevent sire and ipif_ire from getting deleted.
7797 			 * The newly created ire is tied to both of them via
7798 			 * the phandle and ihandle respectively.
7799 			 */
7800 			if (sire != NULL) {
7801 				IRB_REFHOLD(sire->ire_bucket);
7802 				/* Has it been removed already ? */
7803 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7804 					IRB_REFRELE(sire->ire_bucket);
7805 					ire_refrele(ipif_ire);
7806 					ire_refrele(save_ire);
7807 					break;
7808 				}
7809 			}
7810 
7811 			IRB_REFHOLD(ipif_ire->ire_bucket);
7812 			/* Has it been removed already ? */
7813 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7814 				IRB_REFRELE(ipif_ire->ire_bucket);
7815 				if (sire != NULL)
7816 					IRB_REFRELE(sire->ire_bucket);
7817 				ire_refrele(ipif_ire);
7818 				ire_refrele(save_ire);
7819 				break;
7820 			}
7821 
7822 			xmit_mp = first_mp;
7823 			/*
7824 			 * In the case of multirouting, a copy
7825 			 * of the packet is done before its sending.
7826 			 * The copy is used to attempt another
7827 			 * route resolution, in a next loop.
7828 			 */
7829 			if (ire->ire_flags & RTF_MULTIRT) {
7830 				copy_mp = copymsg(first_mp);
7831 				if (copy_mp != NULL) {
7832 					xmit_mp = copy_mp;
7833 					MULTIRT_DEBUG_TAG(first_mp);
7834 				}
7835 			}
7836 			ire_add_then_send(q, ire, xmit_mp);
7837 			ire_refrele(save_ire);
7838 
7839 			/* Assert that sire is not deleted yet. */
7840 			if (sire != NULL) {
7841 				ASSERT(sire->ire_ptpn != NULL);
7842 				IRB_REFRELE(sire->ire_bucket);
7843 			}
7844 
7845 			/* Assert that ipif_ire is not deleted yet. */
7846 			ASSERT(ipif_ire->ire_ptpn != NULL);
7847 			IRB_REFRELE(ipif_ire->ire_bucket);
7848 			ire_refrele(ipif_ire);
7849 
7850 			/*
7851 			 * If copy_mp is not NULL, multirouting was
7852 			 * requested. We loop to initiate a next
7853 			 * route resolution attempt, starting from sire.
7854 			 */
7855 			if (copy_mp != NULL) {
7856 				/*
7857 				 * Search for the next unresolved
7858 				 * multirt route.
7859 				 */
7860 				copy_mp = NULL;
7861 				ipif_ire = NULL;
7862 				ire = NULL;
7863 				multirt_resolve_next = B_TRUE;
7864 				continue;
7865 			}
7866 			if (sire != NULL)
7867 				ire_refrele(sire);
7868 			ipif_refrele(src_ipif);
7869 			ill_refrele(dst_ill);
7870 			return;
7871 		}
7872 		case IRE_IF_NORESOLVER: {
7873 			/*
7874 			 * We have what we need to build an IRE_CACHE.
7875 			 *
7876 			 * Create a new dlureq_mp with the IP gateway address
7877 			 * in destination address in the DLPI hdr if the
7878 			 * physical length is exactly 4 bytes.
7879 			 */
7880 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7881 				uchar_t *addr;
7882 
7883 				if (gw)
7884 					addr = (uchar_t *)&gw;
7885 				else
7886 					addr = (uchar_t *)&dst;
7887 
7888 				dlureq_mp = ill_dlur_gen(addr,
7889 				    dst_ill->ill_phys_addr_length,
7890 				    dst_ill->ill_sap,
7891 				    dst_ill->ill_sap_length);
7892 			} else {
7893 				dlureq_mp = ire->ire_dlureq_mp;
7894 			}
7895 
7896 			if (dlureq_mp == NULL) {
7897 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7898 				break;
7899 			}
7900 
7901 			/*
7902 			 * TSol note: We are creating the ire cache for the
7903 			 * destination 'dst'. If 'dst' is offlink, going
7904 			 * through the first hop 'gw', the security attributes
7905 			 * of 'dst' must be set to point to the gateway
7906 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
7907 			 * is possible that 'dst' is a potential gateway that is
7908 			 * referenced by some route that has some security
7909 			 * attributes. Thus in the former case, we need to do a
7910 			 * gcgrp_lookup of 'gw' while in the latter case we
7911 			 * need to do gcgrp_lookup of 'dst' itself.
7912 			 */
7913 			ga.ga_af = AF_INET;
7914 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
7915 			    &ga.ga_addr);
7916 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
7917 
7918 			ire = ire_create(
7919 			    (uchar_t *)&dst,		/* dest address */
7920 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7921 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7922 			    (uchar_t *)&gw,		/* gateway address */
7923 			    NULL,
7924 			    &save_ire->ire_max_frag,
7925 			    NULL,			/* Fast Path header */
7926 			    dst_ill->ill_rq,		/* recv-from queue */
7927 			    dst_ill->ill_wq,		/* send-to queue */
7928 			    IRE_CACHE,
7929 			    dlureq_mp,
7930 			    src_ipif,
7931 			    in_ill,			/* Incoming ill */
7932 			    save_ire->ire_mask,		/* Parent mask */
7933 			    (sire != NULL) ?		/* Parent handle */
7934 				sire->ire_phandle : 0,
7935 			    save_ire->ire_ihandle,	/* Interface handle */
7936 			    (sire != NULL) ? sire->ire_flags &
7937 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7938 			    &(save_ire->ire_uinfo),
7939 			    NULL,
7940 			    gcgrp);
7941 
7942 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7943 				freeb(dlureq_mp);
7944 
7945 			if (ire == NULL) {
7946 				if (gcgrp != NULL) {
7947 					GCGRP_REFRELE(gcgrp);
7948 					gcgrp = NULL;
7949 				}
7950 				ire_refrele(save_ire);
7951 				break;
7952 			}
7953 
7954 			/* reference now held by IRE */
7955 			gcgrp = NULL;
7956 
7957 			ire->ire_marks |= ire_marks;
7958 
7959 			/* Prevent save_ire from getting deleted */
7960 			IRB_REFHOLD(save_ire->ire_bucket);
7961 			/* Has it been removed already ? */
7962 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7963 				IRB_REFRELE(save_ire->ire_bucket);
7964 				ire_refrele(save_ire);
7965 				break;
7966 			}
7967 
7968 			/*
7969 			 * In the case of multirouting, a copy
7970 			 * of the packet is made before it is sent.
7971 			 * The copy is used in the next
7972 			 * loop to attempt another resolution.
7973 			 */
7974 			xmit_mp = first_mp;
7975 			if ((sire != NULL) &&
7976 			    (sire->ire_flags & RTF_MULTIRT)) {
7977 				copy_mp = copymsg(first_mp);
7978 				if (copy_mp != NULL) {
7979 					xmit_mp = copy_mp;
7980 					MULTIRT_DEBUG_TAG(first_mp);
7981 				}
7982 			}
7983 			ire_add_then_send(q, ire, xmit_mp);
7984 
7985 			/* Assert that it is not deleted yet. */
7986 			ASSERT(save_ire->ire_ptpn != NULL);
7987 			IRB_REFRELE(save_ire->ire_bucket);
7988 			ire_refrele(save_ire);
7989 
7990 			if (copy_mp != NULL) {
7991 				/*
7992 				 * If we found a (no)resolver, we ignore any
7993 				 * trailing top priority IRE_CACHE in further
7994 				 * loops. This ensures that we do not omit any
7995 				 * (no)resolver.
7996 				 * This IRE_CACHE, if any, will be processed
7997 				 * by another thread entering ip_newroute().
7998 				 * IRE_CACHE entries, if any, will be processed
7999 				 * by another thread entering ip_newroute(),
8000 				 * (upon resolver response, for instance).
8001 				 * This aims to force parallel multirt
8002 				 * resolutions as soon as a packet must be sent.
8003 				 * In the best case, after the tx of only one
8004 				 * packet, all reachable routes are resolved.
8005 				 * Otherwise, the resolution of all RTF_MULTIRT
8006 				 * routes would require several emissions.
8007 				 */
8008 				multirt_flags &= ~MULTIRT_CACHEGW;
8009 
8010 				/*
8011 				 * Search for the next unresolved multirt
8012 				 * route.
8013 				 */
8014 				copy_mp = NULL;
8015 				save_ire = NULL;
8016 				ire = NULL;
8017 				multirt_resolve_next = B_TRUE;
8018 				continue;
8019 			}
8020 
8021 			/*
8022 			 * Don't need sire anymore
8023 			 */
8024 			if (sire != NULL)
8025 				ire_refrele(sire);
8026 
8027 			ipif_refrele(src_ipif);
8028 			ill_refrele(dst_ill);
8029 			return;
8030 		}
8031 		case IRE_IF_RESOLVER:
8032 			/*
8033 			 * We can't build an IRE_CACHE yet, but at least we
8034 			 * found a resolver that can help.
8035 			 */
8036 			res_mp = dst_ill->ill_resolver_mp;
8037 			if (!OK_RESOLVER_MP(res_mp))
8038 				break;
8039 
8040 			/*
8041 			 * To be at this point in the code with a non-zero gw
8042 			 * means that dst is reachable through a gateway that
8043 			 * we have never resolved.  By changing dst to the gw
8044 			 * addr we resolve the gateway first.
8045 			 * When ire_add_then_send() tries to put the IP dg
8046 			 * to dst, it will reenter ip_newroute() at which
8047 			 * time we will find the IRE_CACHE for the gw and
8048 			 * create another IRE_CACHE in case IRE_CACHE above.
8049 			 */
8050 			if (gw != INADDR_ANY) {
8051 				/*
8052 				 * The source ipif that was determined above was
8053 				 * relative to the destination address, not the
8054 				 * gateway's. If src_ipif was not taken out of
8055 				 * the IRE_IF_RESOLVER entry, we'll need to call
8056 				 * ipif_select_source() again.
8057 				 */
8058 				if (src_ipif != ire->ire_ipif) {
8059 					ipif_refrele(src_ipif);
8060 					src_ipif = ipif_select_source(dst_ill,
8061 					    gw, zoneid);
8062 					if (src_ipif == NULL) {
8063 						if (ip_debug > 2) {
8064 							pr_addr_dbg(
8065 							    "ip_newroute: no "
8066 							    "src for gw %s ",
8067 							    AF_INET, &gw);
8068 							printf("through "
8069 							    "interface %s\n",
8070 							    dst_ill->ill_name);
8071 						}
8072 						goto icmp_err_ret;
8073 					}
8074 				}
8075 				save_dst = dst;
8076 				dst = gw;
8077 				gw = INADDR_ANY;
8078 			}
8079 
8080 			/*
8081 			 * TSol note: Please see the corresponding note
8082 			 * of the IRE_IF_NORESOLVER case
8083 			 */
8084 			ga.ga_af = AF_INET;
8085 			IN6_IPADDR_TO_V4MAPPED(dst, &ga.ga_addr);
8086 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8087 
8088 			/*
8089 			 * We obtain a partial IRE_CACHE which we will pass
8090 			 * along with the resolver query.  When the response
8091 			 * comes back it will be there ready for us to add.
8092 			 * The ire_max_frag is atomically set under the
8093 			 * irebucket lock in ire_add_v[46].
8094 			 */
8095 			ire = ire_create_mp(
8096 			    (uchar_t *)&dst,		/* dest address */
8097 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8098 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8099 			    (uchar_t *)&gw,		/* gateway address */
8100 			    NULL,			/* no in_src_addr */
8101 			    NULL,			/* ire_max_frag */
8102 			    NULL,			/* Fast Path header */
8103 			    dst_ill->ill_rq,		/* recv-from queue */
8104 			    dst_ill->ill_wq,		/* send-to queue */
8105 			    IRE_CACHE,
8106 			    res_mp,
8107 			    src_ipif,			/* Interface ipif */
8108 			    in_ill,			/* Incoming ILL */
8109 			    save_ire->ire_mask,		/* Parent mask */
8110 			    0,
8111 			    save_ire->ire_ihandle,	/* Interface handle */
8112 			    0,				/* flags if any */
8113 			    &(save_ire->ire_uinfo),
8114 			    NULL,
8115 			    gcgrp);
8116 
8117 			if (ire == NULL) {
8118 				ire_refrele(save_ire);
8119 				if (gcgrp != NULL) {
8120 					GCGRP_REFRELE(gcgrp);
8121 					gcgrp = NULL;
8122 				}
8123 				break;
8124 			}
8125 
8126 			/* reference now held by IRE */
8127 			gcgrp = NULL;
8128 
8129 			if ((sire != NULL) &&
8130 			    (sire->ire_flags & RTF_MULTIRT)) {
8131 				copy_mp = copymsg(first_mp);
8132 				if (copy_mp != NULL)
8133 					MULTIRT_DEBUG_TAG(copy_mp);
8134 			}
8135 
8136 			ire->ire_marks |= ire_marks;
8137 
8138 			/*
8139 			 * Construct message chain for the resolver
8140 			 * of the form:
8141 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8142 			 * Packet could contain a IPSEC_OUT mp.
8143 			 *
8144 			 * NOTE : ire will be added later when the response
8145 			 * comes back from ARP. If the response does not
8146 			 * come back, ARP frees the packet. For this reason,
8147 			 * we can't REFHOLD the bucket of save_ire to prevent
8148 			 * deletions. We may not be able to REFRELE the bucket
8149 			 * if the response never comes back. Thus, before
8150 			 * adding the ire, ire_add_v4 will make sure that the
8151 			 * interface route does not get deleted. This is the
8152 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8153 			 * where we can always prevent deletions because of
8154 			 * the synchronous nature of adding IRES i.e
8155 			 * ire_add_then_send is called after creating the IRE.
8156 			 */
8157 			ASSERT(ire->ire_mp != NULL);
8158 			ire->ire_mp->b_cont = first_mp;
8159 			/* Have saved_mp handy, for cleanup if canput fails */
8160 			saved_mp = mp;
8161 			mp = ire->ire_dlureq_mp;
8162 			ASSERT(mp != NULL);
8163 			ire->ire_dlureq_mp = NULL;
8164 			linkb(mp, ire->ire_mp);
8165 
8166 
8167 			/*
8168 			 * Fill in the source and dest addrs for the resolver.
8169 			 * NOTE: this depends on memory layouts imposed by
8170 			 * ill_init().
8171 			 */
8172 			areq = (areq_t *)mp->b_rptr;
8173 			addrp = (ipaddr_t *)((char *)areq +
8174 			    areq->areq_sender_addr_offset);
8175 			if (do_attach_ill) {
8176 				/*
8177 				 * This is bind to no failover case.
8178 				 * arp packet also must go out on attach_ill.
8179 				 */
8180 				ASSERT(ipha->ipha_src != NULL);
8181 				*addrp = ipha->ipha_src;
8182 			} else {
8183 				*addrp = save_ire->ire_src_addr;
8184 			}
8185 
8186 			ire_refrele(save_ire);
8187 			addrp = (ipaddr_t *)((char *)areq +
8188 			    areq->areq_target_addr_offset);
8189 			*addrp = dst;
8190 			/* Up to the resolver. */
8191 			if (canputnext(dst_ill->ill_rq)) {
8192 				putnext(dst_ill->ill_rq, mp);
8193 				ire = NULL;
8194 				if (copy_mp != NULL) {
8195 					/*
8196 					 * If we found a resolver, we ignore
8197 					 * any trailing top priority IRE_CACHE
8198 					 * in the further loops. This ensures
8199 					 * that we do not omit any resolver.
8200 					 * IRE_CACHE entries, if any, will be
8201 					 * processed next time we enter
8202 					 * ip_newroute().
8203 					 */
8204 					multirt_flags &= ~MULTIRT_CACHEGW;
8205 					/*
8206 					 * Search for the next unresolved
8207 					 * multirt route.
8208 					 */
8209 					first_mp = copy_mp;
8210 					copy_mp = NULL;
8211 					/* Prepare the next resolution loop. */
8212 					mp = first_mp;
8213 					EXTRACT_PKT_MP(mp, first_mp,
8214 					    mctl_present);
8215 					if (mctl_present)
8216 						io = (ipsec_out_t *)
8217 						    first_mp->b_rptr;
8218 					ipha = (ipha_t *)mp->b_rptr;
8219 
8220 					ASSERT(sire != NULL);
8221 
8222 					dst = save_dst;
8223 					multirt_resolve_next = B_TRUE;
8224 					continue;
8225 				}
8226 
8227 				if (sire != NULL)
8228 					ire_refrele(sire);
8229 
8230 				/*
8231 				 * The response will come back in ip_wput
8232 				 * with db_type IRE_DB_TYPE.
8233 				 */
8234 				ipif_refrele(src_ipif);
8235 				ill_refrele(dst_ill);
8236 				return;
8237 			} else {
8238 				/* Prepare for cleanup */
8239 				ire->ire_dlureq_mp = mp;
8240 				mp->b_cont = NULL;
8241 				ire_delete(ire);
8242 				mp = saved_mp;
8243 				ire = NULL;
8244 				if (copy_mp != NULL) {
8245 					MULTIRT_DEBUG_UNTAG(copy_mp);
8246 					freemsg(copy_mp);
8247 					copy_mp = NULL;
8248 				}
8249 				break;
8250 			}
8251 		default:
8252 			break;
8253 		}
8254 	} while (multirt_resolve_next);
8255 
8256 	ip1dbg(("ip_newroute: dropped\n"));
8257 	/* Did this packet originate externally? */
8258 	if (mp->b_prev) {
8259 		mp->b_next = NULL;
8260 		mp->b_prev = NULL;
8261 		BUMP_MIB(&ip_mib, ipInDiscards);
8262 	} else {
8263 		BUMP_MIB(&ip_mib, ipOutDiscards);
8264 	}
8265 	ASSERT(copy_mp == NULL);
8266 	MULTIRT_DEBUG_UNTAG(first_mp);
8267 	freemsg(first_mp);
8268 	if (ire != NULL)
8269 		ire_refrele(ire);
8270 	if (sire != NULL)
8271 		ire_refrele(sire);
8272 	if (src_ipif != NULL)
8273 		ipif_refrele(src_ipif);
8274 	if (dst_ill != NULL)
8275 		ill_refrele(dst_ill);
8276 	return;
8277 
8278 icmp_err_ret:
8279 	ip1dbg(("ip_newroute: no route\n"));
8280 	if (src_ipif != NULL)
8281 		ipif_refrele(src_ipif);
8282 	if (dst_ill != NULL)
8283 		ill_refrele(dst_ill);
8284 	if (sire != NULL)
8285 		ire_refrele(sire);
8286 	/* Did this packet originate externally? */
8287 	if (mp->b_prev) {
8288 		mp->b_next = NULL;
8289 		mp->b_prev = NULL;
8290 		/* XXX ipInNoRoutes */
8291 		q = WR(q);
8292 	} else {
8293 		/*
8294 		 * Since ip_wput() isn't close to finished, we fill
8295 		 * in enough of the header for credible error reporting.
8296 		 */
8297 		if (ip_hdr_complete(ipha, zoneid)) {
8298 			/* Failed */
8299 			MULTIRT_DEBUG_UNTAG(first_mp);
8300 			freemsg(first_mp);
8301 			if (ire != NULL)
8302 				ire_refrele(ire);
8303 			return;
8304 		}
8305 	}
8306 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8307 
8308 	/*
8309 	 * At this point we will have ire only if RTF_BLACKHOLE
8310 	 * or RTF_REJECT flags are set on the IRE. It will not
8311 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8312 	 */
8313 	if (ire != NULL) {
8314 		if (ire->ire_flags & RTF_BLACKHOLE) {
8315 			ire_refrele(ire);
8316 			MULTIRT_DEBUG_UNTAG(first_mp);
8317 			freemsg(first_mp);
8318 			return;
8319 		}
8320 		ire_refrele(ire);
8321 	}
8322 	if (ip_source_routed(ipha)) {
8323 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
8324 		return;
8325 	}
8326 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8327 }
8328 
8329 /*
8330  * IPv4 -
8331  * ip_newroute_ipif is called by ip_wput_multicast and
8332  * ip_rput_forward_multicast whenever we need to send
8333  * out a packet to a destination address for which we do not have specific
8334  * routing information. It is used when the packet will be sent out
8335  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8336  * socket option is set or icmp error message wants to go out on a particular
8337  * interface for a unicast packet.
8338  *
8339  * In most cases, the destination address is resolved thanks to the ipif
8340  * intrinsic resolver. However, there are some cases where the call to
8341  * ip_newroute_ipif must take into account the potential presence of
8342  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8343  * that uses the interface. This is specified through flags,
8344  * which can be a combination of:
8345  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8346  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8347  *   and flags. Additionally, the packet source address has to be set to
8348  *   the specified address. The caller is thus expected to set this flag
8349  *   if the packet has no specific source address yet.
8350  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8351  *   flag, the resulting ire will inherit the flag. All unresolved routes
8352  *   to the destination must be explored in the same call to
8353  *   ip_newroute_ipif().
8354  */
8355 static void
8356 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8357     conn_t *connp, uint32_t flags)
8358 {
8359 	areq_t	*areq;
8360 	ire_t	*ire = NULL;
8361 	mblk_t	*res_mp;
8362 	ipaddr_t *addrp;
8363 	mblk_t *first_mp;
8364 	ire_t	*save_ire = NULL;
8365 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8366 	ipif_t	*src_ipif = NULL;
8367 	ushort_t ire_marks = 0;
8368 	ill_t	*dst_ill = NULL;
8369 	boolean_t mctl_present;
8370 	ipsec_out_t *io;
8371 	ipha_t *ipha;
8372 	int	ihandle = 0;
8373 	mblk_t	*saved_mp;
8374 	ire_t   *fire = NULL;
8375 	mblk_t  *copy_mp = NULL;
8376 	boolean_t multirt_resolve_next;
8377 	ipaddr_t ipha_dst;
8378 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
8379 
8380 	/*
8381 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8382 	 * here for uniformity
8383 	 */
8384 	ipif_refhold(ipif);
8385 
8386 	/*
8387 	 * This loop is run only once in most cases.
8388 	 * We loop to resolve further routes only when the destination
8389 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8390 	 */
8391 	do {
8392 		if (dst_ill != NULL) {
8393 			ill_refrele(dst_ill);
8394 			dst_ill = NULL;
8395 		}
8396 		if (src_ipif != NULL) {
8397 			ipif_refrele(src_ipif);
8398 			src_ipif = NULL;
8399 		}
8400 		multirt_resolve_next = B_FALSE;
8401 
8402 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8403 		    ipif->ipif_ill->ill_name));
8404 
8405 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8406 		if (mctl_present)
8407 			io = (ipsec_out_t *)first_mp->b_rptr;
8408 
8409 		ipha = (ipha_t *)mp->b_rptr;
8410 
8411 		/*
8412 		 * Save the packet destination address, we may need it after
8413 		 * the packet has been consumed.
8414 		 */
8415 		ipha_dst = ipha->ipha_dst;
8416 
8417 		/*
8418 		 * If the interface is a pt-pt interface we look for an
8419 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8420 		 * local_address and the pt-pt destination address. Otherwise
8421 		 * we just match the local address.
8422 		 * NOTE: dst could be different than ipha->ipha_dst in case
8423 		 * of sending igmp multicast packets over a point-to-point
8424 		 * connection.
8425 		 * Thus we must be careful enough to check ipha_dst to be a
8426 		 * multicast address, otherwise it will take xmit_if path for
8427 		 * multicast packets resulting into kernel stack overflow by
8428 		 * repeated calls to ip_newroute_ipif from ire_send().
8429 		 */
8430 		if (CLASSD(ipha_dst) &&
8431 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8432 			goto err_ret;
8433 		}
8434 
8435 		/*
8436 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8437 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8438 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8439 		 * propagate its flags to the new ire.
8440 		 */
8441 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8442 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8443 			ip2dbg(("ip_newroute_ipif: "
8444 			    "ipif_lookup_multi_ire("
8445 			    "ipif %p, dst %08x) = fire %p\n",
8446 			    (void *)ipif, ntohl(dst), (void *)fire));
8447 		}
8448 
8449 		if (mctl_present && io->ipsec_out_attach_if) {
8450 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8451 			    io->ipsec_out_ill_index, B_FALSE);
8452 
8453 			/* Failure case frees things for us. */
8454 			if (attach_ill == NULL) {
8455 				ipif_refrele(ipif);
8456 				if (fire != NULL)
8457 					ire_refrele(fire);
8458 				return;
8459 			}
8460 
8461 			/*
8462 			 * Check if we need an ire that will not be
8463 			 * looked up by anybody else i.e. HIDDEN.
8464 			 */
8465 			if (ill_is_probeonly(attach_ill)) {
8466 				ire_marks = IRE_MARK_HIDDEN;
8467 			}
8468 			/*
8469 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8470 			 * case.
8471 			 */
8472 			dst_ill = ipif->ipif_ill;
8473 			/* attach_ill has been refheld by ip_grab_attach_ill */
8474 			ASSERT(dst_ill == attach_ill);
8475 		} else {
8476 			/*
8477 			 * If this is set by IP_XMIT_IF, then make sure that
8478 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8479 			 * specified ill.
8480 			 */
8481 			ASSERT((connp == NULL) ||
8482 			    (connp->conn_xmit_if_ill == NULL) ||
8483 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8484 			/*
8485 			 * If the interface belongs to an interface group,
8486 			 * make sure the next possible interface in the group
8487 			 * is used.  This encourages load spreading among
8488 			 * peers in an interface group.
8489 			 * Note: load spreading is disabled for RTF_MULTIRT
8490 			 * routes.
8491 			 */
8492 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8493 			    (fire->ire_flags & RTF_MULTIRT)) {
8494 				/*
8495 				 * Don't perform outbound load spreading
8496 				 * in the case of an RTF_MULTIRT issued route,
8497 				 * we actually typically want to replicate
8498 				 * outgoing packets through particular
8499 				 * interfaces.
8500 				 */
8501 				dst_ill = ipif->ipif_ill;
8502 				ill_refhold(dst_ill);
8503 			} else {
8504 				dst_ill = ip_newroute_get_dst_ill(
8505 				    ipif->ipif_ill);
8506 			}
8507 			if (dst_ill == NULL) {
8508 				if (ip_debug > 2) {
8509 					pr_addr_dbg("ip_newroute_ipif: "
8510 					    "no dst ill for dst %s\n",
8511 					    AF_INET, &dst);
8512 				}
8513 				goto err_ret;
8514 			}
8515 		}
8516 
8517 		/*
8518 		 * Pick a source address preferring non-deprecated ones.
8519 		 * Unlike ip_newroute, we don't do any source address
8520 		 * selection here since for multicast it really does not help
8521 		 * in inbound load spreading as in the unicast case.
8522 		 */
8523 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8524 		    (fire->ire_flags & RTF_SETSRC)) {
8525 			/*
8526 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8527 			 * on that interface. This ire has RTF_SETSRC flag, so
8528 			 * the source address of the packet must be changed.
8529 			 * Check that the ipif matching the requested source
8530 			 * address still exists.
8531 			 */
8532 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8533 			    zoneid, NULL, NULL, NULL, NULL);
8534 		}
8535 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8536 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8537 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8538 		    (src_ipif == NULL)) {
8539 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8540 			if (src_ipif == NULL) {
8541 				if (ip_debug > 2) {
8542 					/* ip1dbg */
8543 					pr_addr_dbg("ip_newroute_ipif: "
8544 					    "no src for dst %s",
8545 					    AF_INET, &dst);
8546 				}
8547 				ip1dbg((" through interface %s\n",
8548 				    dst_ill->ill_name));
8549 				goto err_ret;
8550 			}
8551 			ipif_refrele(ipif);
8552 			ipif = src_ipif;
8553 			ipif_refhold(ipif);
8554 		}
8555 		if (src_ipif == NULL) {
8556 			src_ipif = ipif;
8557 			ipif_refhold(src_ipif);
8558 		}
8559 
8560 		/*
8561 		 * Assign a source address while we have the conn.
8562 		 * We can't have ip_wput_ire pick a source address when the
8563 		 * packet returns from arp since conn_unspec_src might be set
8564 		 * and we loose the conn when going through arp.
8565 		 */
8566 		if (ipha->ipha_src == INADDR_ANY &&
8567 		    (connp == NULL || !connp->conn_unspec_src)) {
8568 			ipha->ipha_src = src_ipif->ipif_src_addr;
8569 		}
8570 
8571 		/*
8572 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8573 		 * interface does not have an interface ire.
8574 		 * Example: Thousands of mobileip PPP interfaces to mobile
8575 		 * nodes. We don't want to create interface ires because
8576 		 * packets from other mobile nodes must not take the route
8577 		 * via interface ires to the visiting mobile node without
8578 		 * going through the home agent, in absence of mobileip
8579 		 * route optimization.
8580 		 */
8581 		if (CLASSD(ipha_dst) && (connp == NULL ||
8582 		    connp->conn_xmit_if_ill == NULL)) {
8583 			/* ipif_to_ire returns an held ire */
8584 			ire = ipif_to_ire(ipif);
8585 			if (ire == NULL)
8586 				goto err_ret;
8587 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8588 				goto err_ret;
8589 			/*
8590 			 * ihandle is needed when the ire is added to
8591 			 * cache table.
8592 			 */
8593 			save_ire = ire;
8594 			ihandle = save_ire->ire_ihandle;
8595 
8596 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8597 			    "flags %04x\n",
8598 			    (void *)ire, (void *)ipif, flags));
8599 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8600 			    (fire->ire_flags & RTF_MULTIRT)) {
8601 				/*
8602 				 * As requested by flags, an IRE_OFFSUBNET was
8603 				 * looked up on that interface. This ire has
8604 				 * RTF_MULTIRT flag, so the resolution loop will
8605 				 * be re-entered to resolve additional routes on
8606 				 * other interfaces. For that purpose, a copy of
8607 				 * the packet is performed at this point.
8608 				 */
8609 				fire->ire_last_used_time = lbolt;
8610 				copy_mp = copymsg(first_mp);
8611 				if (copy_mp) {
8612 					MULTIRT_DEBUG_TAG(copy_mp);
8613 				}
8614 			}
8615 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8616 			    (fire->ire_flags & RTF_SETSRC)) {
8617 				/*
8618 				 * As requested by flags, an IRE_OFFSUBET was
8619 				 * looked up on that interface. This ire has
8620 				 * RTF_SETSRC flag, so the source address of the
8621 				 * packet must be changed.
8622 				 */
8623 				ipha->ipha_src = fire->ire_src_addr;
8624 			}
8625 		} else {
8626 			ASSERT((connp == NULL) ||
8627 			    (connp->conn_xmit_if_ill != NULL) ||
8628 			    (connp->conn_dontroute));
8629 			/*
8630 			 * The only ways we can come here are:
8631 			 * 1) IP_XMIT_IF socket option is set
8632 			 * 2) ICMP error message generated from
8633 			 *    ip_mrtun_forward() routine and it needs
8634 			 *    to go through the specified ill.
8635 			 * 3) SO_DONTROUTE socket option is set
8636 			 * In all cases, the new ire will not be added
8637 			 * into cache table.
8638 			 */
8639 			ire_marks |= IRE_MARK_NOADD;
8640 		}
8641 
8642 		switch (ipif->ipif_net_type) {
8643 		case IRE_IF_NORESOLVER: {
8644 			/* We have what we need to build an IRE_CACHE. */
8645 			mblk_t	*dlureq_mp;
8646 
8647 			/*
8648 			 * Create a new dlureq_mp with the
8649 			 * IP gateway address as destination address in the
8650 			 * DLPI hdr if the physical length is exactly 4 bytes.
8651 			 */
8652 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8653 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8654 				    dst_ill->ill_phys_addr_length,
8655 				    dst_ill->ill_sap,
8656 				    dst_ill->ill_sap_length);
8657 			} else {
8658 				/* use the value set in ip_ll_subnet_defaults */
8659 				dlureq_mp = ill_dlur_gen(NULL,
8660 				    dst_ill->ill_phys_addr_length,
8661 				    dst_ill->ill_sap,
8662 				    dst_ill->ill_sap_length);
8663 			}
8664 
8665 			if (dlureq_mp == NULL)
8666 				break;
8667 			/*
8668 			 * The new ire inherits the IRE_OFFSUBNET flags
8669 			 * and source address, if this was requested.
8670 			 */
8671 			ire = ire_create(
8672 			    (uchar_t *)&dst,		/* dest address */
8673 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8674 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8675 			    NULL,			/* gateway address */
8676 			    NULL,
8677 			    &ipif->ipif_mtu,
8678 			    NULL,			/* Fast Path header */
8679 			    dst_ill->ill_rq,		/* recv-from queue */
8680 			    dst_ill->ill_wq,		/* send-to queue */
8681 			    IRE_CACHE,
8682 			    dlureq_mp,
8683 			    src_ipif,
8684 			    NULL,
8685 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8686 			    (fire != NULL) ?		/* Parent handle */
8687 				fire->ire_phandle : 0,
8688 			    ihandle,			/* Interface handle */
8689 			    (fire != NULL) ?
8690 				(fire->ire_flags &
8691 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8692 			    (save_ire == NULL ? &ire_uinfo_null :
8693 				&save_ire->ire_uinfo),
8694 			    NULL,
8695 			    NULL);
8696 
8697 			freeb(dlureq_mp);
8698 
8699 			if (ire == NULL) {
8700 				if (save_ire != NULL)
8701 					ire_refrele(save_ire);
8702 				break;
8703 			}
8704 
8705 			ire->ire_marks |= ire_marks;
8706 
8707 			/*
8708 			 * If IRE_MARK_NOADD is set then we need to convert
8709 			 * the max_fragp to a useable value now. This is
8710 			 * normally done in ire_add_v[46].
8711 			 */
8712 			if (ire->ire_marks & IRE_MARK_NOADD) {
8713 				uint_t  max_frag;
8714 
8715 				max_frag = *ire->ire_max_fragp;
8716 				ire->ire_max_fragp = NULL;
8717 				ire->ire_max_frag = max_frag;
8718 			}
8719 
8720 			/* Prevent save_ire from getting deleted */
8721 			if (save_ire != NULL) {
8722 				IRB_REFHOLD(save_ire->ire_bucket);
8723 				/* Has it been removed already ? */
8724 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8725 					IRB_REFRELE(save_ire->ire_bucket);
8726 					ire_refrele(save_ire);
8727 					break;
8728 				}
8729 			}
8730 
8731 			ire_add_then_send(q, ire, first_mp);
8732 
8733 			/* Assert that save_ire is not deleted yet. */
8734 			if (save_ire != NULL) {
8735 				ASSERT(save_ire->ire_ptpn != NULL);
8736 				IRB_REFRELE(save_ire->ire_bucket);
8737 				ire_refrele(save_ire);
8738 				save_ire = NULL;
8739 			}
8740 			if (fire != NULL) {
8741 				ire_refrele(fire);
8742 				fire = NULL;
8743 			}
8744 
8745 			/*
8746 			 * the resolution loop is re-entered if this
8747 			 * was requested through flags and if we
8748 			 * actually are in a multirouting case.
8749 			 */
8750 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8751 				boolean_t need_resolve =
8752 				    ire_multirt_need_resolve(ipha_dst,
8753 					MBLK_GETLABEL(copy_mp));
8754 				if (!need_resolve) {
8755 					MULTIRT_DEBUG_UNTAG(copy_mp);
8756 					freemsg(copy_mp);
8757 					copy_mp = NULL;
8758 				} else {
8759 					/*
8760 					 * ipif_lookup_group() calls
8761 					 * ire_lookup_multi() that uses
8762 					 * ire_ftable_lookup() to find
8763 					 * an IRE_INTERFACE for the group.
8764 					 * In the multirt case,
8765 					 * ire_lookup_multi() then invokes
8766 					 * ire_multirt_lookup() to find
8767 					 * the next resolvable ire.
8768 					 * As a result, we obtain an new
8769 					 * interface, derived from the
8770 					 * next ire.
8771 					 */
8772 					ipif_refrele(ipif);
8773 					ipif = ipif_lookup_group(ipha_dst,
8774 					    zoneid);
8775 					ip2dbg(("ip_newroute_ipif: "
8776 					    "multirt dst %08x, ipif %p\n",
8777 					    htonl(dst), (void *)ipif));
8778 					if (ipif != NULL) {
8779 						mp = copy_mp;
8780 						copy_mp = NULL;
8781 						multirt_resolve_next = B_TRUE;
8782 						continue;
8783 					} else {
8784 						freemsg(copy_mp);
8785 					}
8786 				}
8787 			}
8788 			if (ipif != NULL)
8789 				ipif_refrele(ipif);
8790 			ill_refrele(dst_ill);
8791 			ipif_refrele(src_ipif);
8792 			return;
8793 		}
8794 		case IRE_IF_RESOLVER:
8795 			/*
8796 			 * We can't build an IRE_CACHE yet, but at least
8797 			 * we found a resolver that can help.
8798 			 */
8799 			res_mp = dst_ill->ill_resolver_mp;
8800 			if (!OK_RESOLVER_MP(res_mp))
8801 				break;
8802 
8803 			/*
8804 			 * We obtain a partial IRE_CACHE which we will pass
8805 			 * along with the resolver query.  When the response
8806 			 * comes back it will be there ready for us to add.
8807 			 * The new ire inherits the IRE_OFFSUBNET flags
8808 			 * and source address, if this was requested.
8809 			 * The ire_max_frag is atomically set under the
8810 			 * irebucket lock in ire_add_v[46]. Only in the
8811 			 * case of IRE_MARK_NOADD, we set it here itself.
8812 			 */
8813 			ire = ire_create_mp(
8814 			    (uchar_t *)&dst,		/* dest address */
8815 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8816 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8817 			    NULL,			/* gateway address */
8818 			    NULL,			/* no in_src_addr */
8819 			    (ire_marks & IRE_MARK_NOADD) ?
8820 				ipif->ipif_mtu : 0,	/* max_frag */
8821 			    NULL,			/* Fast path header */
8822 			    dst_ill->ill_rq,		/* recv-from queue */
8823 			    dst_ill->ill_wq,		/* send-to queue */
8824 			    IRE_CACHE,
8825 			    res_mp,
8826 			    src_ipif,
8827 			    NULL,
8828 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8829 			    (fire != NULL) ?		/* Parent handle */
8830 				fire->ire_phandle : 0,
8831 			    ihandle,			/* Interface handle */
8832 			    (fire != NULL) ?		/* flags if any */
8833 				(fire->ire_flags &
8834 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8835 			    (save_ire == NULL ? &ire_uinfo_null :
8836 				&save_ire->ire_uinfo),
8837 			    NULL,
8838 			    NULL);
8839 
8840 			if (save_ire != NULL) {
8841 				ire_refrele(save_ire);
8842 				save_ire = NULL;
8843 			}
8844 			if (ire == NULL)
8845 				break;
8846 
8847 			ire->ire_marks |= ire_marks;
8848 			/*
8849 			 * Construct message chain for the resolver of the
8850 			 * form:
8851 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8852 			 *
8853 			 * NOTE : ire will be added later when the response
8854 			 * comes back from ARP. If the response does not
8855 			 * come back, ARP frees the packet. For this reason,
8856 			 * we can't REFHOLD the bucket of save_ire to prevent
8857 			 * deletions. We may not be able to REFRELE the
8858 			 * bucket if the response never comes back.
8859 			 * Thus, before adding the ire, ire_add_v4 will make
8860 			 * sure that the interface route does not get deleted.
8861 			 * This is the only case unlike ip_newroute_v6,
8862 			 * ip_newroute_ipif_v6 where we can always prevent
8863 			 * deletions because ire_add_then_send is called after
8864 			 * creating the IRE.
8865 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8866 			 * does not add this IRE into the IRE CACHE.
8867 			 */
8868 			ASSERT(ire->ire_mp != NULL);
8869 			ire->ire_mp->b_cont = first_mp;
8870 			/* Have saved_mp handy, for cleanup if canput fails */
8871 			saved_mp = mp;
8872 			mp = ire->ire_dlureq_mp;
8873 			ASSERT(mp != NULL);
8874 			ire->ire_dlureq_mp = NULL;
8875 			linkb(mp, ire->ire_mp);
8876 
8877 			/*
8878 			 * Fill in the source and dest addrs for the resolver.
8879 			 * NOTE: this depends on memory layouts imposed by
8880 			 * ill_init().
8881 			 */
8882 			areq = (areq_t *)mp->b_rptr;
8883 			addrp = (ipaddr_t *)((char *)areq +
8884 			    areq->areq_sender_addr_offset);
8885 			*addrp = ire->ire_src_addr;
8886 			addrp = (ipaddr_t *)((char *)areq +
8887 			    areq->areq_target_addr_offset);
8888 			*addrp = dst;
8889 			/* Up to the resolver. */
8890 			if (canputnext(dst_ill->ill_rq)) {
8891 				putnext(dst_ill->ill_rq, mp);
8892 				/*
8893 				 * The response will come back in ip_wput
8894 				 * with db_type IRE_DB_TYPE.
8895 				 */
8896 			} else {
8897 				ire->ire_dlureq_mp = mp;
8898 				mp->b_cont = NULL;
8899 				ire_delete(ire);
8900 				saved_mp->b_next = NULL;
8901 				saved_mp->b_prev = NULL;
8902 				freemsg(first_mp);
8903 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8904 			}
8905 
8906 			if (fire != NULL) {
8907 				ire_refrele(fire);
8908 				fire = NULL;
8909 			}
8910 
8911 
8912 			/*
8913 			 * The resolution loop is re-entered if this was
8914 			 * requested through flags and we actually are
8915 			 * in a multirouting case.
8916 			 */
8917 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8918 				boolean_t need_resolve =
8919 				    ire_multirt_need_resolve(ipha_dst,
8920 					MBLK_GETLABEL(copy_mp));
8921 				if (!need_resolve) {
8922 					MULTIRT_DEBUG_UNTAG(copy_mp);
8923 					freemsg(copy_mp);
8924 					copy_mp = NULL;
8925 				} else {
8926 					/*
8927 					 * ipif_lookup_group() calls
8928 					 * ire_lookup_multi() that uses
8929 					 * ire_ftable_lookup() to find
8930 					 * an IRE_INTERFACE for the group.
8931 					 * In the multirt case,
8932 					 * ire_lookup_multi() then invokes
8933 					 * ire_multirt_lookup() to find
8934 					 * the next resolvable ire.
8935 					 * As a result, we obtain an new
8936 					 * interface, derived from the
8937 					 * next ire.
8938 					 */
8939 					ipif_refrele(ipif);
8940 					ipif = ipif_lookup_group(ipha_dst,
8941 					    zoneid);
8942 					if (ipif != NULL) {
8943 						mp = copy_mp;
8944 						copy_mp = NULL;
8945 						multirt_resolve_next = B_TRUE;
8946 						continue;
8947 					} else {
8948 						freemsg(copy_mp);
8949 					}
8950 				}
8951 			}
8952 			if (ipif != NULL)
8953 				ipif_refrele(ipif);
8954 			ill_refrele(dst_ill);
8955 			ipif_refrele(src_ipif);
8956 			return;
8957 		default:
8958 			break;
8959 		}
8960 	} while (multirt_resolve_next);
8961 
8962 err_ret:
8963 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8964 	if (fire != NULL)
8965 		ire_refrele(fire);
8966 	ipif_refrele(ipif);
8967 	/* Did this packet originate externally? */
8968 	if (dst_ill != NULL)
8969 		ill_refrele(dst_ill);
8970 	if (src_ipif != NULL)
8971 		ipif_refrele(src_ipif);
8972 	if (mp->b_prev || mp->b_next) {
8973 		mp->b_next = NULL;
8974 		mp->b_prev = NULL;
8975 	} else {
8976 		/*
8977 		 * Since ip_wput() isn't close to finished, we fill
8978 		 * in enough of the header for credible error reporting.
8979 		 */
8980 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8981 			/* Failed */
8982 			freemsg(first_mp);
8983 			if (ire != NULL)
8984 				ire_refrele(ire);
8985 			return;
8986 		}
8987 	}
8988 	/*
8989 	 * At this point we will have ire only if RTF_BLACKHOLE
8990 	 * or RTF_REJECT flags are set on the IRE. It will not
8991 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8992 	 */
8993 	if (ire != NULL) {
8994 		if (ire->ire_flags & RTF_BLACKHOLE) {
8995 			ire_refrele(ire);
8996 			freemsg(first_mp);
8997 			return;
8998 		}
8999 		ire_refrele(ire);
9000 	}
9001 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
9002 }
9003 
9004 /* Name/Value Table Lookup Routine */
9005 char *
9006 ip_nv_lookup(nv_t *nv, int value)
9007 {
9008 	if (!nv)
9009 		return (NULL);
9010 	for (; nv->nv_name; nv++) {
9011 		if (nv->nv_value == value)
9012 			return (nv->nv_name);
9013 	}
9014 	return ("unknown");
9015 }
9016 
9017 /*
9018  * one day it can be patched to 1 from /etc/system for machines that have few
9019  * fast network interfaces feeding multiple cpus.
9020  */
9021 int ill_stream_putlocks = 0;
9022 
9023 /*
9024  * This is a module open, i.e. this is a control stream for access
9025  * to a DLPI device.  We allocate an ill_t as the instance data in
9026  * this case.
9027  */
9028 int
9029 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9030 {
9031 	uint32_t mem_cnt;
9032 	uint32_t cpu_cnt;
9033 	uint32_t min_cnt;
9034 	pgcnt_t mem_avail;
9035 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
9036 	ill_t	*ill;
9037 	int	err;
9038 
9039 	/*
9040 	 * Prevent unprivileged processes from pushing IP so that
9041 	 * they can't send raw IP.
9042 	 */
9043 	if (secpolicy_net_rawaccess(credp) != 0)
9044 		return (EPERM);
9045 
9046 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9047 	q->q_ptr = WR(q)->q_ptr = ill;
9048 
9049 	/*
9050 	 * ill_init initializes the ill fields and then sends down
9051 	 * down a DL_INFO_REQ after calling qprocson.
9052 	 */
9053 	err = ill_init(q, ill);
9054 	if (err != 0) {
9055 		mi_free(ill);
9056 		q->q_ptr = NULL;
9057 		WR(q)->q_ptr = NULL;
9058 		return (err);
9059 	}
9060 
9061 	/* ill_init initializes the ipsq marking this thread as writer */
9062 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9063 	/* Wait for the DL_INFO_ACK */
9064 	mutex_enter(&ill->ill_lock);
9065 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9066 		/*
9067 		 * Return value of 0 indicates a pending signal.
9068 		 */
9069 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9070 		if (err == 0) {
9071 			mutex_exit(&ill->ill_lock);
9072 			(void) ip_close(q, 0);
9073 			return (EINTR);
9074 		}
9075 	}
9076 	mutex_exit(&ill->ill_lock);
9077 
9078 	/*
9079 	 * ip_rput_other could have set an error  in ill_error on
9080 	 * receipt of M_ERROR.
9081 	 */
9082 
9083 	err = ill->ill_error;
9084 	if (err != 0) {
9085 		(void) ip_close(q, 0);
9086 		return (err);
9087 	}
9088 
9089 	/*
9090 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9091 	 * size and the cpu speed of the machine. This is upper
9092 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9093 	 * and is lower bounded by the compile time value of
9094 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9095 	 * ip6_ire_max_bucket_cnt.
9096 	 */
9097 	mem_avail = kmem_avail();
9098 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9099 	    ip_cache_table_size / sizeof (ire_t);
9100 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9101 
9102 	min_cnt = MIN(cpu_cnt, mem_cnt);
9103 	if (min_cnt < ip_ire_min_bucket_cnt)
9104 		min_cnt = ip_ire_min_bucket_cnt;
9105 	if (ip_ire_max_bucket_cnt > min_cnt) {
9106 		ip_ire_max_bucket_cnt = min_cnt;
9107 	}
9108 
9109 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9110 	    ip6_cache_table_size / sizeof (ire_t);
9111 	min_cnt = MIN(cpu_cnt, mem_cnt);
9112 	if (min_cnt < ip6_ire_min_bucket_cnt)
9113 		min_cnt = ip6_ire_min_bucket_cnt;
9114 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9115 		ip6_ire_max_bucket_cnt = min_cnt;
9116 	}
9117 
9118 	ill->ill_credp = credp;
9119 	crhold(credp);
9120 
9121 	mutex_enter(&ip_mi_lock);
9122 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9123 	mutex_exit(&ip_mi_lock);
9124 	if (err) {
9125 		(void) ip_close(q, 0);
9126 		return (err);
9127 	}
9128 	return (0);
9129 }
9130 
9131 /* IP open routine. */
9132 int
9133 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9134 {
9135 	conn_t 		*connp;
9136 	major_t		maj;
9137 
9138 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9139 
9140 	/* Allow reopen. */
9141 	if (q->q_ptr != NULL)
9142 		return (0);
9143 
9144 	if (sflag & MODOPEN) {
9145 		/* This is a module open */
9146 		return (ip_modopen(q, devp, flag, sflag, credp));
9147 	}
9148 
9149 	/*
9150 	 * We are opening as a device. This is an IP client stream, and we
9151 	 * allocate an conn_t as the instance data.
9152 	 */
9153 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9154 	connp->conn_upq = q;
9155 	q->q_ptr = WR(q)->q_ptr = connp;
9156 
9157 	if (flag & SO_SOCKSTR)
9158 		connp->conn_flags |= IPCL_SOCKET;
9159 
9160 	/* Minor tells us which /dev entry was opened */
9161 	if (geteminor(*devp) == IPV6_MINOR) {
9162 		connp->conn_flags |= IPCL_ISV6;
9163 		connp->conn_af_isv6 = B_TRUE;
9164 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9165 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9166 	} else {
9167 		connp->conn_af_isv6 = B_FALSE;
9168 		connp->conn_pkt_isv6 = B_FALSE;
9169 	}
9170 
9171 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9172 		q->q_ptr = WR(q)->q_ptr = NULL;
9173 		CONN_DEC_REF(connp);
9174 		return (EBUSY);
9175 	}
9176 
9177 	maj = getemajor(*devp);
9178 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9179 
9180 	/*
9181 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9182 	 */
9183 	connp->conn_cred = credp;
9184 	crhold(connp->conn_cred);
9185 
9186 	/*
9187 	 * If the caller has the process-wide flag set, then default to MAC
9188 	 * exempt mode.  This allows read-down to unlabeled hosts.
9189 	 */
9190 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9191 		connp->conn_mac_exempt = B_TRUE;
9192 
9193 	connp->conn_zoneid = getzoneid();
9194 
9195 	/*
9196 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9197 	 * administrative ops.  In these cases, we just need a normal conn_t
9198 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9199 	 * an error will be returned.
9200 	 */
9201 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9202 		connp->conn_rq = q;
9203 		connp->conn_wq = WR(q);
9204 	} else {
9205 		connp->conn_ulp = IPPROTO_SCTP;
9206 		connp->conn_rq = connp->conn_wq = NULL;
9207 	}
9208 	/* Non-zero default values */
9209 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9210 
9211 	/*
9212 	 * Make the conn globally visible to walkers
9213 	 */
9214 	mutex_enter(&connp->conn_lock);
9215 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9216 	mutex_exit(&connp->conn_lock);
9217 	ASSERT(connp->conn_ref == 1);
9218 
9219 	qprocson(q);
9220 
9221 	return (0);
9222 }
9223 
9224 /*
9225  * Change q_qinfo based on the value of isv6.
9226  * This can not called on an ill queue.
9227  * Note that there is no race since either q_qinfo works for conn queues - it
9228  * is just an optimization to enter the best wput routine directly.
9229  */
9230 void
9231 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9232 {
9233 	ASSERT(q->q_flag & QREADR);
9234 	ASSERT(WR(q)->q_next == NULL);
9235 	ASSERT(q->q_ptr != NULL);
9236 
9237 	if (minor == IPV6_MINOR)  {
9238 		if (bump_mib)
9239 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9240 		q->q_qinfo = &rinit_ipv6;
9241 		WR(q)->q_qinfo = &winit_ipv6;
9242 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9243 	} else {
9244 		if (bump_mib)
9245 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9246 		q->q_qinfo = &rinit;
9247 		WR(q)->q_qinfo = &winit;
9248 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9249 	}
9250 
9251 }
9252 
9253 /*
9254  * See if IPsec needs loading because of the options in mp.
9255  */
9256 static boolean_t
9257 ipsec_opt_present(mblk_t *mp)
9258 {
9259 	uint8_t *optcp, *next_optcp, *opt_endcp;
9260 	struct opthdr *opt;
9261 	struct T_opthdr *topt;
9262 	int opthdr_len;
9263 	t_uscalar_t optname, optlevel;
9264 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9265 	ipsec_req_t *ipsr;
9266 
9267 	/*
9268 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9269 	 * return TRUE.
9270 	 */
9271 
9272 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9273 	opt_endcp = optcp + tor->OPT_length;
9274 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9275 		opthdr_len = sizeof (struct T_opthdr);
9276 	} else {		/* O_OPTMGMT_REQ */
9277 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9278 		opthdr_len = sizeof (struct opthdr);
9279 	}
9280 	for (; optcp < opt_endcp; optcp = next_optcp) {
9281 		if (optcp + opthdr_len > opt_endcp)
9282 			return (B_FALSE);	/* Not enough option header. */
9283 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9284 			topt = (struct T_opthdr *)optcp;
9285 			optlevel = topt->level;
9286 			optname = topt->name;
9287 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9288 		} else {
9289 			opt = (struct opthdr *)optcp;
9290 			optlevel = opt->level;
9291 			optname = opt->name;
9292 			next_optcp = optcp + opthdr_len +
9293 			    _TPI_ALIGN_OPT(opt->len);
9294 		}
9295 		if ((next_optcp < optcp) || /* wraparound pointer space */
9296 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9297 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9298 			return (B_FALSE); /* bad option buffer */
9299 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9300 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9301 			/*
9302 			 * Check to see if it's an all-bypass or all-zeroes
9303 			 * IPsec request.  Don't bother loading IPsec if
9304 			 * the socket doesn't want to use it.  (A good example
9305 			 * is a bypass request.)
9306 			 *
9307 			 * Basically, if any of the non-NEVER bits are set,
9308 			 * load IPsec.
9309 			 */
9310 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9311 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9312 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9313 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9314 			    != 0)
9315 				return (B_TRUE);
9316 		}
9317 	}
9318 	return (B_FALSE);
9319 }
9320 
9321 /*
9322  * If conn is is waiting for ipsec to finish loading, kick it.
9323  */
9324 /* ARGSUSED */
9325 static void
9326 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9327 {
9328 	t_scalar_t	optreq_prim;
9329 	mblk_t		*mp;
9330 	cred_t		*cr;
9331 	int		err = 0;
9332 
9333 	/*
9334 	 * This function is called, after ipsec loading is complete.
9335 	 * Since IP checks exclusively and atomically (i.e it prevents
9336 	 * ipsec load from completing until ip_optcom_req completes)
9337 	 * whether ipsec load is complete, there cannot be a race with IP
9338 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9339 	 */
9340 	mutex_enter(&connp->conn_lock);
9341 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9342 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9343 		mp = connp->conn_ipsec_opt_mp;
9344 		connp->conn_ipsec_opt_mp = NULL;
9345 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9346 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9347 		mutex_exit(&connp->conn_lock);
9348 
9349 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9350 
9351 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9352 		if (optreq_prim == T_OPTMGMT_REQ) {
9353 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9354 			    &ip_opt_obj);
9355 		} else {
9356 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9357 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9358 			    &ip_opt_obj);
9359 		}
9360 		if (err != EINPROGRESS)
9361 			CONN_OPER_PENDING_DONE(connp);
9362 		return;
9363 	}
9364 	mutex_exit(&connp->conn_lock);
9365 }
9366 
9367 /*
9368  * Called from the ipsec_loader thread, outside any perimeter, to tell
9369  * ip qenable any of the queues waiting for the ipsec loader to
9370  * complete.
9371  *
9372  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9373  * are done with this lock held, so it's guaranteed that none of the
9374  * links will change along the way.
9375  */
9376 void
9377 ip_ipsec_load_complete()
9378 {
9379 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9380 }
9381 
9382 /*
9383  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9384  * determines the grp on which it has to become exclusive, queues the mp
9385  * and sq draining restarts the optmgmt
9386  */
9387 static boolean_t
9388 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9389 {
9390 	conn_t *connp;
9391 
9392 	/*
9393 	 * Take IPsec requests and treat them special.
9394 	 */
9395 	if (ipsec_opt_present(mp)) {
9396 		/* First check if IPsec is loaded. */
9397 		mutex_enter(&ipsec_loader_lock);
9398 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9399 			mutex_exit(&ipsec_loader_lock);
9400 			return (B_FALSE);
9401 		}
9402 		connp = Q_TO_CONN(q);
9403 		mutex_enter(&connp->conn_lock);
9404 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9405 
9406 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9407 		connp->conn_ipsec_opt_mp = mp;
9408 		mutex_exit(&connp->conn_lock);
9409 		mutex_exit(&ipsec_loader_lock);
9410 
9411 		ipsec_loader_loadnow();
9412 		return (B_TRUE);
9413 	}
9414 	return (B_FALSE);
9415 }
9416 
9417 /*
9418  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9419  * all of them are copied to the conn_t. If the req is "zero", the policy is
9420  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9421  * fields.
9422  * We keep only the latest setting of the policy and thus policy setting
9423  * is not incremental/cumulative.
9424  *
9425  * Requests to set policies with multiple alternative actions will
9426  * go through a different API.
9427  */
9428 int
9429 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9430 {
9431 	uint_t ah_req = 0;
9432 	uint_t esp_req = 0;
9433 	uint_t se_req = 0;
9434 	ipsec_selkey_t sel;
9435 	ipsec_act_t *actp = NULL;
9436 	uint_t nact;
9437 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9438 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9439 	ipsec_policy_root_t *pr;
9440 	ipsec_policy_head_t *ph;
9441 	int fam;
9442 	boolean_t is_pol_reset;
9443 	int error = 0;
9444 
9445 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9446 
9447 	/*
9448 	 * The IP_SEC_OPT option does not allow variable length parameters,
9449 	 * hence a request cannot be NULL.
9450 	 */
9451 	if (req == NULL)
9452 		return (EINVAL);
9453 
9454 	ah_req = req->ipsr_ah_req;
9455 	esp_req = req->ipsr_esp_req;
9456 	se_req = req->ipsr_self_encap_req;
9457 
9458 	/*
9459 	 * Are we dealing with a request to reset the policy (i.e.
9460 	 * zero requests).
9461 	 */
9462 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9463 	    (esp_req & REQ_MASK) == 0 &&
9464 	    (se_req & REQ_MASK) == 0);
9465 
9466 	if (!is_pol_reset) {
9467 		/*
9468 		 * If we couldn't load IPsec, fail with "protocol
9469 		 * not supported".
9470 		 * IPsec may not have been loaded for a request with zero
9471 		 * policies, so we don't fail in this case.
9472 		 */
9473 		mutex_enter(&ipsec_loader_lock);
9474 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9475 			mutex_exit(&ipsec_loader_lock);
9476 			return (EPROTONOSUPPORT);
9477 		}
9478 		mutex_exit(&ipsec_loader_lock);
9479 
9480 		/*
9481 		 * Test for valid requests. Invalid algorithms
9482 		 * need to be tested by IPSEC code because new
9483 		 * algorithms can be added dynamically.
9484 		 */
9485 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9486 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9487 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9488 			return (EINVAL);
9489 		}
9490 
9491 		/*
9492 		 * Only privileged users can issue these
9493 		 * requests.
9494 		 */
9495 		if (((ah_req & IPSEC_PREF_NEVER) ||
9496 		    (esp_req & IPSEC_PREF_NEVER) ||
9497 		    (se_req & IPSEC_PREF_NEVER)) &&
9498 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9499 			return (EPERM);
9500 		}
9501 
9502 		/*
9503 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9504 		 * are mutually exclusive.
9505 		 */
9506 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9507 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9508 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9509 			/* Both of them are set */
9510 			return (EINVAL);
9511 		}
9512 	}
9513 
9514 	mutex_enter(&connp->conn_lock);
9515 
9516 	/*
9517 	 * If we have already cached policies in ip_bind_connected*(), don't
9518 	 * let them change now. We cache policies for connections
9519 	 * whose src,dst [addr, port] is known.  The exception to this is
9520 	 * tunnels.  Tunnels are allowed to change policies after having
9521 	 * become fully bound.
9522 	 */
9523 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9524 		mutex_exit(&connp->conn_lock);
9525 		return (EINVAL);
9526 	}
9527 
9528 	/*
9529 	 * We have a zero policies, reset the connection policy if already
9530 	 * set. This will cause the connection to inherit the
9531 	 * global policy, if any.
9532 	 */
9533 	if (is_pol_reset) {
9534 		if (connp->conn_policy != NULL) {
9535 			IPPH_REFRELE(connp->conn_policy);
9536 			connp->conn_policy = NULL;
9537 		}
9538 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9539 		connp->conn_in_enforce_policy = B_FALSE;
9540 		connp->conn_out_enforce_policy = B_FALSE;
9541 		mutex_exit(&connp->conn_lock);
9542 		return (0);
9543 	}
9544 
9545 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9546 	if (ph == NULL)
9547 		goto enomem;
9548 
9549 	ipsec_actvec_from_req(req, &actp, &nact);
9550 	if (actp == NULL)
9551 		goto enomem;
9552 
9553 	/*
9554 	 * Always allocate IPv4 policy entries, since they can also
9555 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9556 	 */
9557 	bzero(&sel, sizeof (sel));
9558 	sel.ipsl_valid = IPSL_IPV4;
9559 
9560 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9561 	if (pin4 == NULL)
9562 		goto enomem;
9563 
9564 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9565 	if (pout4 == NULL)
9566 		goto enomem;
9567 
9568 	if (connp->conn_pkt_isv6) {
9569 		/*
9570 		 * We're looking at a v6 socket, also allocate the
9571 		 * v6-specific entries...
9572 		 */
9573 		sel.ipsl_valid = IPSL_IPV6;
9574 		pin6 = ipsec_policy_create(&sel, actp, nact,
9575 		    IPSEC_PRIO_SOCKET);
9576 		if (pin6 == NULL)
9577 			goto enomem;
9578 
9579 		pout6 = ipsec_policy_create(&sel, actp, nact,
9580 		    IPSEC_PRIO_SOCKET);
9581 		if (pout6 == NULL)
9582 			goto enomem;
9583 
9584 		/*
9585 		 * .. and file them away in the right place.
9586 		 */
9587 		fam = IPSEC_AF_V6;
9588 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9589 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9590 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9591 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9592 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9593 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9594 	}
9595 
9596 	ipsec_actvec_free(actp, nact);
9597 
9598 	/*
9599 	 * File the v4 policies.
9600 	 */
9601 	fam = IPSEC_AF_V4;
9602 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9603 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9604 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9605 
9606 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9607 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9608 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9609 
9610 	/*
9611 	 * If the requests need security, set enforce_policy.
9612 	 * If the requests are IPSEC_PREF_NEVER, one should
9613 	 * still set conn_out_enforce_policy so that an ipsec_out
9614 	 * gets attached in ip_wput. This is needed so that
9615 	 * for connections that we don't cache policy in ip_bind,
9616 	 * if global policy matches in ip_wput_attach_policy, we
9617 	 * don't wrongly inherit global policy. Similarly, we need
9618 	 * to set conn_in_enforce_policy also so that we don't verify
9619 	 * policy wrongly.
9620 	 */
9621 	if ((ah_req & REQ_MASK) != 0 ||
9622 	    (esp_req & REQ_MASK) != 0 ||
9623 	    (se_req & REQ_MASK) != 0) {
9624 		connp->conn_in_enforce_policy = B_TRUE;
9625 		connp->conn_out_enforce_policy = B_TRUE;
9626 		connp->conn_flags |= IPCL_CHECK_POLICY;
9627 	}
9628 
9629 	/*
9630 	 * Tunnels are allowed to set policy after having been fully bound.
9631 	 * If that's the case, cache policy here.
9632 	 */
9633 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9634 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9635 
9636 	mutex_exit(&connp->conn_lock);
9637 	return (error);
9638 #undef REQ_MASK
9639 
9640 	/*
9641 	 * Common memory-allocation-failure exit path.
9642 	 */
9643 enomem:
9644 	mutex_exit(&connp->conn_lock);
9645 	if (actp != NULL)
9646 		ipsec_actvec_free(actp, nact);
9647 	if (pin4 != NULL)
9648 		IPPOL_REFRELE(pin4);
9649 	if (pout4 != NULL)
9650 		IPPOL_REFRELE(pout4);
9651 	if (pin6 != NULL)
9652 		IPPOL_REFRELE(pin6);
9653 	if (pout6 != NULL)
9654 		IPPOL_REFRELE(pout6);
9655 	return (ENOMEM);
9656 }
9657 
9658 /*
9659  * Only for options that pass in an IP addr. Currently only V4 options
9660  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9661  * So this function assumes level is IPPROTO_IP
9662  */
9663 int
9664 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9665     mblk_t *first_mp)
9666 {
9667 	ipif_t *ipif = NULL;
9668 	int error;
9669 	ill_t *ill;
9670 	int zoneid;
9671 
9672 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9673 
9674 	if (addr != INADDR_ANY || checkonly) {
9675 		ASSERT(connp != NULL);
9676 		zoneid = IPCL_ZONEID(connp);
9677 		if (option == IP_NEXTHOP) {
9678 			ipif = ipif_lookup_onlink_addr(addr, zoneid);
9679 		} else {
9680 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
9681 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9682 			    &error);
9683 		}
9684 		if (ipif == NULL) {
9685 			if (error == EINPROGRESS)
9686 				return (error);
9687 			else if ((option == IP_MULTICAST_IF) ||
9688 			    (option == IP_NEXTHOP))
9689 				return (EHOSTUNREACH);
9690 			else
9691 				return (EINVAL);
9692 		} else if (checkonly) {
9693 			if (option == IP_MULTICAST_IF) {
9694 				ill = ipif->ipif_ill;
9695 				/* not supported by the virtual network iface */
9696 				if (IS_VNI(ill)) {
9697 					ipif_refrele(ipif);
9698 					return (EINVAL);
9699 				}
9700 			}
9701 			ipif_refrele(ipif);
9702 			return (0);
9703 		}
9704 		ill = ipif->ipif_ill;
9705 		mutex_enter(&connp->conn_lock);
9706 		mutex_enter(&ill->ill_lock);
9707 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9708 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9709 			mutex_exit(&ill->ill_lock);
9710 			mutex_exit(&connp->conn_lock);
9711 			ipif_refrele(ipif);
9712 			return (option == IP_MULTICAST_IF ?
9713 			    EHOSTUNREACH : EINVAL);
9714 		}
9715 	} else {
9716 		mutex_enter(&connp->conn_lock);
9717 	}
9718 
9719 	/* None of the options below are supported on the VNI */
9720 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9721 		mutex_exit(&ill->ill_lock);
9722 		mutex_exit(&connp->conn_lock);
9723 		ipif_refrele(ipif);
9724 		return (EINVAL);
9725 	}
9726 
9727 	switch (option) {
9728 	case IP_DONTFAILOVER_IF:
9729 		/*
9730 		 * This option is used by in.mpathd to ensure
9731 		 * that IPMP probe packets only go out on the
9732 		 * test interfaces. in.mpathd sets this option
9733 		 * on the non-failover interfaces.
9734 		 * For backward compatibility, this option
9735 		 * implicitly sets IP_MULTICAST_IF, as used
9736 		 * be done in bind(), so that ip_wput gets
9737 		 * this ipif to send mcast packets.
9738 		 */
9739 		if (ipif != NULL) {
9740 			ASSERT(addr != INADDR_ANY);
9741 			connp->conn_nofailover_ill = ipif->ipif_ill;
9742 			connp->conn_multicast_ipif = ipif;
9743 		} else {
9744 			ASSERT(addr == INADDR_ANY);
9745 			connp->conn_nofailover_ill = NULL;
9746 			connp->conn_multicast_ipif = NULL;
9747 		}
9748 		break;
9749 
9750 	case IP_MULTICAST_IF:
9751 		connp->conn_multicast_ipif = ipif;
9752 		break;
9753 	case IP_NEXTHOP:
9754 		connp->conn_nexthop_v4 = addr;
9755 		connp->conn_nexthop_set = B_TRUE;
9756 		break;
9757 	}
9758 
9759 	if (ipif != NULL) {
9760 		mutex_exit(&ill->ill_lock);
9761 		mutex_exit(&connp->conn_lock);
9762 		ipif_refrele(ipif);
9763 		return (0);
9764 	}
9765 	mutex_exit(&connp->conn_lock);
9766 	/* We succeded in cleared the option */
9767 	return (0);
9768 }
9769 
9770 /*
9771  * For options that pass in an ifindex specifying the ill. V6 options always
9772  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9773  */
9774 int
9775 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9776     int level, int option, mblk_t *first_mp)
9777 {
9778 	ill_t *ill = NULL;
9779 	int error = 0;
9780 
9781 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9782 	if (ifindex != 0) {
9783 		ASSERT(connp != NULL);
9784 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9785 		    first_mp, ip_restart_optmgmt, &error);
9786 		if (ill != NULL) {
9787 			if (checkonly) {
9788 				/* not supported by the virtual network iface */
9789 				if (IS_VNI(ill)) {
9790 					ill_refrele(ill);
9791 					return (EINVAL);
9792 				}
9793 				ill_refrele(ill);
9794 				return (0);
9795 			}
9796 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9797 			    0, NULL)) {
9798 				ill_refrele(ill);
9799 				ill = NULL;
9800 				mutex_enter(&connp->conn_lock);
9801 				goto setit;
9802 			}
9803 			mutex_enter(&connp->conn_lock);
9804 			mutex_enter(&ill->ill_lock);
9805 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9806 				mutex_exit(&ill->ill_lock);
9807 				mutex_exit(&connp->conn_lock);
9808 				ill_refrele(ill);
9809 				ill = NULL;
9810 				mutex_enter(&connp->conn_lock);
9811 			}
9812 			goto setit;
9813 		} else if (error == EINPROGRESS) {
9814 			return (error);
9815 		} else {
9816 			error = 0;
9817 		}
9818 	}
9819 	mutex_enter(&connp->conn_lock);
9820 setit:
9821 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9822 
9823 	/*
9824 	 * The options below assume that the ILL (if any) transmits and/or
9825 	 * receives traffic. Neither of which is true for the virtual network
9826 	 * interface, so fail setting these on a VNI.
9827 	 */
9828 	if (IS_VNI(ill)) {
9829 		ASSERT(ill != NULL);
9830 		mutex_exit(&ill->ill_lock);
9831 		mutex_exit(&connp->conn_lock);
9832 		ill_refrele(ill);
9833 		return (EINVAL);
9834 	}
9835 
9836 	if (level == IPPROTO_IP) {
9837 		switch (option) {
9838 		case IP_BOUND_IF:
9839 			connp->conn_incoming_ill = ill;
9840 			connp->conn_outgoing_ill = ill;
9841 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9842 			    0 : ifindex;
9843 			break;
9844 
9845 		case IP_XMIT_IF:
9846 			/*
9847 			 * Similar to IP_BOUND_IF, but this only
9848 			 * determines the outgoing interface for
9849 			 * unicast packets. Also no IRE_CACHE entry
9850 			 * is added for the destination of the
9851 			 * outgoing packets. This feature is needed
9852 			 * for mobile IP.
9853 			 */
9854 			connp->conn_xmit_if_ill = ill;
9855 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9856 			    0 : ifindex;
9857 			break;
9858 
9859 		case IP_MULTICAST_IF:
9860 			/*
9861 			 * This option is an internal special. The socket
9862 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9863 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9864 			 * specifies an ifindex and we try first on V6 ill's.
9865 			 * If we don't find one, we they try using on v4 ill's
9866 			 * intenally and we come here.
9867 			 */
9868 			if (!checkonly && ill != NULL) {
9869 				ipif_t	*ipif;
9870 				ipif = ill->ill_ipif;
9871 
9872 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9873 					mutex_exit(&ill->ill_lock);
9874 					mutex_exit(&connp->conn_lock);
9875 					ill_refrele(ill);
9876 					ill = NULL;
9877 					mutex_enter(&connp->conn_lock);
9878 				} else {
9879 					connp->conn_multicast_ipif = ipif;
9880 				}
9881 			}
9882 			break;
9883 		}
9884 	} else {
9885 		switch (option) {
9886 		case IPV6_BOUND_IF:
9887 			connp->conn_incoming_ill = ill;
9888 			connp->conn_outgoing_ill = ill;
9889 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9890 			    0 : ifindex;
9891 			break;
9892 
9893 		case IPV6_BOUND_PIF:
9894 			/*
9895 			 * Limit all transmit to this ill.
9896 			 * Unlike IPV6_BOUND_IF, using this option
9897 			 * prevents load spreading and failover from
9898 			 * happening when the interface is part of the
9899 			 * group. That's why we don't need to remember
9900 			 * the ifindex in orig_bound_ifindex as in
9901 			 * IPV6_BOUND_IF.
9902 			 */
9903 			connp->conn_outgoing_pill = ill;
9904 			break;
9905 
9906 		case IPV6_DONTFAILOVER_IF:
9907 			/*
9908 			 * This option is used by in.mpathd to ensure
9909 			 * that IPMP probe packets only go out on the
9910 			 * test interfaces. in.mpathd sets this option
9911 			 * on the non-failover interfaces.
9912 			 */
9913 			connp->conn_nofailover_ill = ill;
9914 			/*
9915 			 * For backward compatibility, this option
9916 			 * implicitly sets ip_multicast_ill as used in
9917 			 * IP_MULTICAST_IF so that ip_wput gets
9918 			 * this ipif to send mcast packets.
9919 			 */
9920 			connp->conn_multicast_ill = ill;
9921 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9922 			    0 : ifindex;
9923 			break;
9924 
9925 		case IPV6_MULTICAST_IF:
9926 			/*
9927 			 * Set conn_multicast_ill to be the IPv6 ill.
9928 			 * Set conn_multicast_ipif to be an IPv4 ipif
9929 			 * for ifindex to make IPv4 mapped addresses
9930 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9931 			 * Even if no IPv6 ill exists for the ifindex
9932 			 * we need to check for an IPv4 ifindex in order
9933 			 * for this to work with mapped addresses. In that
9934 			 * case only set conn_multicast_ipif.
9935 			 */
9936 			if (!checkonly) {
9937 				if (ifindex == 0) {
9938 					connp->conn_multicast_ill = NULL;
9939 					connp->conn_orig_multicast_ifindex = 0;
9940 					connp->conn_multicast_ipif = NULL;
9941 				} else if (ill != NULL) {
9942 					connp->conn_multicast_ill = ill;
9943 					connp->conn_orig_multicast_ifindex =
9944 					    ifindex;
9945 				}
9946 			}
9947 			break;
9948 		}
9949 	}
9950 
9951 	if (ill != NULL) {
9952 		mutex_exit(&ill->ill_lock);
9953 		mutex_exit(&connp->conn_lock);
9954 		ill_refrele(ill);
9955 		return (0);
9956 	}
9957 	mutex_exit(&connp->conn_lock);
9958 	/*
9959 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9960 	 * locate the ill and could not set the option (ifindex != 0)
9961 	 */
9962 	return (ifindex == 0 ? 0 : EINVAL);
9963 }
9964 
9965 /* This routine sets socket options. */
9966 /* ARGSUSED */
9967 int
9968 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9969     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9970     void *dummy, cred_t *cr, mblk_t *first_mp)
9971 {
9972 	int		*i1 = (int *)invalp;
9973 	conn_t		*connp = Q_TO_CONN(q);
9974 	int		error = 0;
9975 	boolean_t	checkonly;
9976 	ire_t		*ire;
9977 	boolean_t	found;
9978 
9979 	switch (optset_context) {
9980 
9981 	case SETFN_OPTCOM_CHECKONLY:
9982 		checkonly = B_TRUE;
9983 		/*
9984 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9985 		 * inlen != 0 implies value supplied and
9986 		 * 	we have to "pretend" to set it.
9987 		 * inlen == 0 implies that there is no
9988 		 * 	value part in T_CHECK request and just validation
9989 		 * done elsewhere should be enough, we just return here.
9990 		 */
9991 		if (inlen == 0) {
9992 			*outlenp = 0;
9993 			return (0);
9994 		}
9995 		break;
9996 	case SETFN_OPTCOM_NEGOTIATE:
9997 	case SETFN_UD_NEGOTIATE:
9998 	case SETFN_CONN_NEGOTIATE:
9999 		checkonly = B_FALSE;
10000 		break;
10001 	default:
10002 		/*
10003 		 * We should never get here
10004 		 */
10005 		*outlenp = 0;
10006 		return (EINVAL);
10007 	}
10008 
10009 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10010 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10011 
10012 	/*
10013 	 * For fixed length options, no sanity check
10014 	 * of passed in length is done. It is assumed *_optcom_req()
10015 	 * routines do the right thing.
10016 	 */
10017 
10018 	switch (level) {
10019 	case SOL_SOCKET:
10020 		/*
10021 		 * conn_lock protects the bitfields, and is used to
10022 		 * set the fields atomically.
10023 		 */
10024 		switch (name) {
10025 		case SO_BROADCAST:
10026 			if (!checkonly) {
10027 				/* TODO: use value someplace? */
10028 				mutex_enter(&connp->conn_lock);
10029 				connp->conn_broadcast = *i1 ? 1 : 0;
10030 				mutex_exit(&connp->conn_lock);
10031 			}
10032 			break;	/* goto sizeof (int) option return */
10033 		case SO_USELOOPBACK:
10034 			if (!checkonly) {
10035 				/* TODO: use value someplace? */
10036 				mutex_enter(&connp->conn_lock);
10037 				connp->conn_loopback = *i1 ? 1 : 0;
10038 				mutex_exit(&connp->conn_lock);
10039 			}
10040 			break;	/* goto sizeof (int) option return */
10041 		case SO_DONTROUTE:
10042 			if (!checkonly) {
10043 				mutex_enter(&connp->conn_lock);
10044 				connp->conn_dontroute = *i1 ? 1 : 0;
10045 				mutex_exit(&connp->conn_lock);
10046 			}
10047 			break;	/* goto sizeof (int) option return */
10048 		case SO_REUSEADDR:
10049 			if (!checkonly) {
10050 				mutex_enter(&connp->conn_lock);
10051 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10052 				mutex_exit(&connp->conn_lock);
10053 			}
10054 			break;	/* goto sizeof (int) option return */
10055 		case SO_PROTOTYPE:
10056 			if (!checkonly) {
10057 				mutex_enter(&connp->conn_lock);
10058 				connp->conn_proto = *i1;
10059 				mutex_exit(&connp->conn_lock);
10060 			}
10061 			break;	/* goto sizeof (int) option return */
10062 		case SO_ALLZONES:
10063 			if (!checkonly) {
10064 				mutex_enter(&connp->conn_lock);
10065 				if (IPCL_IS_BOUND(connp)) {
10066 					mutex_exit(&connp->conn_lock);
10067 					return (EINVAL);
10068 				}
10069 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10070 				mutex_exit(&connp->conn_lock);
10071 			}
10072 			break;	/* goto sizeof (int) option return */
10073 		case SO_ANON_MLP:
10074 			if (!checkonly) {
10075 				mutex_enter(&connp->conn_lock);
10076 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10077 				mutex_exit(&connp->conn_lock);
10078 			}
10079 			break;	/* goto sizeof (int) option return */
10080 		case SO_MAC_EXEMPT:
10081 			if (secpolicy_net_mac_aware(cr) != 0 ||
10082 			    IPCL_IS_BOUND(connp))
10083 				return (EACCES);
10084 			if (!checkonly) {
10085 				mutex_enter(&connp->conn_lock);
10086 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10087 				mutex_exit(&connp->conn_lock);
10088 			}
10089 			break;	/* goto sizeof (int) option return */
10090 		default:
10091 			/*
10092 			 * "soft" error (negative)
10093 			 * option not handled at this level
10094 			 * Note: Do not modify *outlenp
10095 			 */
10096 			return (-EINVAL);
10097 		}
10098 		break;
10099 	case IPPROTO_IP:
10100 		switch (name) {
10101 		case IP_NEXTHOP:
10102 		case IP_MULTICAST_IF:
10103 		case IP_DONTFAILOVER_IF: {
10104 			ipaddr_t addr = *i1;
10105 
10106 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10107 			    first_mp);
10108 			if (error != 0)
10109 				return (error);
10110 			break;	/* goto sizeof (int) option return */
10111 		}
10112 
10113 		case IP_MULTICAST_TTL:
10114 			/* Recorded in transport above IP */
10115 			*outvalp = *invalp;
10116 			*outlenp = sizeof (uchar_t);
10117 			return (0);
10118 		case IP_MULTICAST_LOOP:
10119 			if (!checkonly) {
10120 				mutex_enter(&connp->conn_lock);
10121 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10122 				mutex_exit(&connp->conn_lock);
10123 			}
10124 			*outvalp = *invalp;
10125 			*outlenp = sizeof (uchar_t);
10126 			return (0);
10127 		case IP_ADD_MEMBERSHIP:
10128 		case MCAST_JOIN_GROUP:
10129 		case IP_DROP_MEMBERSHIP:
10130 		case MCAST_LEAVE_GROUP: {
10131 			struct ip_mreq *mreqp;
10132 			struct group_req *greqp;
10133 			ire_t *ire;
10134 			boolean_t done = B_FALSE;
10135 			ipaddr_t group, ifaddr;
10136 			struct sockaddr_in *sin;
10137 			uint32_t *ifindexp;
10138 			boolean_t mcast_opt = B_TRUE;
10139 			mcast_record_t fmode;
10140 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10141 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10142 
10143 			switch (name) {
10144 			case IP_ADD_MEMBERSHIP:
10145 				mcast_opt = B_FALSE;
10146 				/* FALLTHRU */
10147 			case MCAST_JOIN_GROUP:
10148 				fmode = MODE_IS_EXCLUDE;
10149 				optfn = ip_opt_add_group;
10150 				break;
10151 
10152 			case IP_DROP_MEMBERSHIP:
10153 				mcast_opt = B_FALSE;
10154 				/* FALLTHRU */
10155 			case MCAST_LEAVE_GROUP:
10156 				fmode = MODE_IS_INCLUDE;
10157 				optfn = ip_opt_delete_group;
10158 				break;
10159 			}
10160 
10161 			if (mcast_opt) {
10162 				greqp = (struct group_req *)i1;
10163 				sin = (struct sockaddr_in *)&greqp->gr_group;
10164 				if (sin->sin_family != AF_INET) {
10165 					*outlenp = 0;
10166 					return (ENOPROTOOPT);
10167 				}
10168 				group = (ipaddr_t)sin->sin_addr.s_addr;
10169 				ifaddr = INADDR_ANY;
10170 				ifindexp = &greqp->gr_interface;
10171 			} else {
10172 				mreqp = (struct ip_mreq *)i1;
10173 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10174 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10175 				ifindexp = NULL;
10176 			}
10177 
10178 			/*
10179 			 * In the multirouting case, we need to replicate
10180 			 * the request on all interfaces that will take part
10181 			 * in replication.  We do so because multirouting is
10182 			 * reflective, thus we will probably receive multi-
10183 			 * casts on those interfaces.
10184 			 * The ip_multirt_apply_membership() succeeds if the
10185 			 * operation succeeds on at least one interface.
10186 			 */
10187 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10188 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10189 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10190 			if (ire != NULL) {
10191 				if (ire->ire_flags & RTF_MULTIRT) {
10192 					error = ip_multirt_apply_membership(
10193 					    optfn, ire, connp, checkonly, group,
10194 					    fmode, INADDR_ANY, first_mp);
10195 					done = B_TRUE;
10196 				}
10197 				ire_refrele(ire);
10198 			}
10199 			if (!done) {
10200 				error = optfn(connp, checkonly, group, ifaddr,
10201 				    ifindexp, fmode, INADDR_ANY, first_mp);
10202 			}
10203 			if (error) {
10204 				/*
10205 				 * EINPROGRESS is a soft error, needs retry
10206 				 * so don't make *outlenp zero.
10207 				 */
10208 				if (error != EINPROGRESS)
10209 					*outlenp = 0;
10210 				return (error);
10211 			}
10212 			/* OK return - copy input buffer into output buffer */
10213 			if (invalp != outvalp) {
10214 				/* don't trust bcopy for identical src/dst */
10215 				bcopy(invalp, outvalp, inlen);
10216 			}
10217 			*outlenp = inlen;
10218 			return (0);
10219 		}
10220 		case IP_BLOCK_SOURCE:
10221 		case IP_UNBLOCK_SOURCE:
10222 		case IP_ADD_SOURCE_MEMBERSHIP:
10223 		case IP_DROP_SOURCE_MEMBERSHIP:
10224 		case MCAST_BLOCK_SOURCE:
10225 		case MCAST_UNBLOCK_SOURCE:
10226 		case MCAST_JOIN_SOURCE_GROUP:
10227 		case MCAST_LEAVE_SOURCE_GROUP: {
10228 			struct ip_mreq_source *imreqp;
10229 			struct group_source_req *gsreqp;
10230 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10231 			uint32_t ifindex = 0;
10232 			mcast_record_t fmode;
10233 			struct sockaddr_in *sin;
10234 			ire_t *ire;
10235 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10236 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10237 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10238 
10239 			switch (name) {
10240 			case IP_BLOCK_SOURCE:
10241 				mcast_opt = B_FALSE;
10242 				/* FALLTHRU */
10243 			case MCAST_BLOCK_SOURCE:
10244 				fmode = MODE_IS_EXCLUDE;
10245 				optfn = ip_opt_add_group;
10246 				break;
10247 
10248 			case IP_UNBLOCK_SOURCE:
10249 				mcast_opt = B_FALSE;
10250 				/* FALLTHRU */
10251 			case MCAST_UNBLOCK_SOURCE:
10252 				fmode = MODE_IS_EXCLUDE;
10253 				optfn = ip_opt_delete_group;
10254 				break;
10255 
10256 			case IP_ADD_SOURCE_MEMBERSHIP:
10257 				mcast_opt = B_FALSE;
10258 				/* FALLTHRU */
10259 			case MCAST_JOIN_SOURCE_GROUP:
10260 				fmode = MODE_IS_INCLUDE;
10261 				optfn = ip_opt_add_group;
10262 				break;
10263 
10264 			case IP_DROP_SOURCE_MEMBERSHIP:
10265 				mcast_opt = B_FALSE;
10266 				/* FALLTHRU */
10267 			case MCAST_LEAVE_SOURCE_GROUP:
10268 				fmode = MODE_IS_INCLUDE;
10269 				optfn = ip_opt_delete_group;
10270 				break;
10271 			}
10272 
10273 			if (mcast_opt) {
10274 				gsreqp = (struct group_source_req *)i1;
10275 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10276 					*outlenp = 0;
10277 					return (ENOPROTOOPT);
10278 				}
10279 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10280 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10281 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10282 				src = (ipaddr_t)sin->sin_addr.s_addr;
10283 				ifindex = gsreqp->gsr_interface;
10284 			} else {
10285 				imreqp = (struct ip_mreq_source *)i1;
10286 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10287 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10288 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10289 			}
10290 
10291 			/*
10292 			 * In the multirouting case, we need to replicate
10293 			 * the request as noted in the mcast cases above.
10294 			 */
10295 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10296 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10297 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10298 			if (ire != NULL) {
10299 				if (ire->ire_flags & RTF_MULTIRT) {
10300 					error = ip_multirt_apply_membership(
10301 					    optfn, ire, connp, checkonly, grp,
10302 					    fmode, src, first_mp);
10303 					done = B_TRUE;
10304 				}
10305 				ire_refrele(ire);
10306 			}
10307 			if (!done) {
10308 				error = optfn(connp, checkonly, grp, ifaddr,
10309 				    &ifindex, fmode, src, first_mp);
10310 			}
10311 			if (error != 0) {
10312 				/*
10313 				 * EINPROGRESS is a soft error, needs retry
10314 				 * so don't make *outlenp zero.
10315 				 */
10316 				if (error != EINPROGRESS)
10317 					*outlenp = 0;
10318 				return (error);
10319 			}
10320 			/* OK return - copy input buffer into output buffer */
10321 			if (invalp != outvalp) {
10322 				bcopy(invalp, outvalp, inlen);
10323 			}
10324 			*outlenp = inlen;
10325 			return (0);
10326 		}
10327 		case IP_SEC_OPT:
10328 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10329 			if (error != 0) {
10330 				*outlenp = 0;
10331 				return (error);
10332 			}
10333 			break;
10334 		case IP_HDRINCL:
10335 		case IP_OPTIONS:
10336 		case T_IP_OPTIONS:
10337 		case IP_TOS:
10338 		case T_IP_TOS:
10339 		case IP_TTL:
10340 		case IP_RECVDSTADDR:
10341 		case IP_RECVOPTS:
10342 			/* OK return - copy input buffer into output buffer */
10343 			if (invalp != outvalp) {
10344 				/* don't trust bcopy for identical src/dst */
10345 				bcopy(invalp, outvalp, inlen);
10346 			}
10347 			*outlenp = inlen;
10348 			return (0);
10349 		case IP_RECVIF:
10350 			/* Retrieve the inbound interface index */
10351 			if (!checkonly) {
10352 				mutex_enter(&connp->conn_lock);
10353 				connp->conn_recvif = *i1 ? 1 : 0;
10354 				mutex_exit(&connp->conn_lock);
10355 			}
10356 			break;	/* goto sizeof (int) option return */
10357 		case IP_RECVSLLA:
10358 			/* Retrieve the source link layer address */
10359 			if (!checkonly) {
10360 				mutex_enter(&connp->conn_lock);
10361 				connp->conn_recvslla = *i1 ? 1 : 0;
10362 				mutex_exit(&connp->conn_lock);
10363 			}
10364 			break;	/* goto sizeof (int) option return */
10365 		case MRT_INIT:
10366 		case MRT_DONE:
10367 		case MRT_ADD_VIF:
10368 		case MRT_DEL_VIF:
10369 		case MRT_ADD_MFC:
10370 		case MRT_DEL_MFC:
10371 		case MRT_ASSERT:
10372 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10373 				*outlenp = 0;
10374 				return (error);
10375 			}
10376 			error = ip_mrouter_set((int)name, q, checkonly,
10377 			    (uchar_t *)invalp, inlen, first_mp);
10378 			if (error) {
10379 				*outlenp = 0;
10380 				return (error);
10381 			}
10382 			/* OK return - copy input buffer into output buffer */
10383 			if (invalp != outvalp) {
10384 				/* don't trust bcopy for identical src/dst */
10385 				bcopy(invalp, outvalp, inlen);
10386 			}
10387 			*outlenp = inlen;
10388 			return (0);
10389 		case IP_BOUND_IF:
10390 		case IP_XMIT_IF:
10391 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10392 			    level, name, first_mp);
10393 			if (error != 0)
10394 				return (error);
10395 			break; 		/* goto sizeof (int) option return */
10396 
10397 		case IP_UNSPEC_SRC:
10398 			/* Allow sending with a zero source address */
10399 			if (!checkonly) {
10400 				mutex_enter(&connp->conn_lock);
10401 				connp->conn_unspec_src = *i1 ? 1 : 0;
10402 				mutex_exit(&connp->conn_lock);
10403 			}
10404 			break;	/* goto sizeof (int) option return */
10405 		default:
10406 			/*
10407 			 * "soft" error (negative)
10408 			 * option not handled at this level
10409 			 * Note: Do not modify *outlenp
10410 			 */
10411 			return (-EINVAL);
10412 		}
10413 		break;
10414 	case IPPROTO_IPV6:
10415 		switch (name) {
10416 		case IPV6_BOUND_IF:
10417 		case IPV6_BOUND_PIF:
10418 		case IPV6_DONTFAILOVER_IF:
10419 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10420 			    level, name, first_mp);
10421 			if (error != 0)
10422 				return (error);
10423 			break; 		/* goto sizeof (int) option return */
10424 
10425 		case IPV6_MULTICAST_IF:
10426 			/*
10427 			 * The only possible errors are EINPROGRESS and
10428 			 * EINVAL. EINPROGRESS will be restarted and is not
10429 			 * a hard error. We call this option on both V4 and V6
10430 			 * If both return EINVAL, then this call returns
10431 			 * EINVAL. If at least one of them succeeds we
10432 			 * return success.
10433 			 */
10434 			found = B_FALSE;
10435 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10436 			    level, name, first_mp);
10437 			if (error == EINPROGRESS)
10438 				return (error);
10439 			if (error == 0)
10440 				found = B_TRUE;
10441 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10442 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10443 			if (error == 0)
10444 				found = B_TRUE;
10445 			if (!found)
10446 				return (error);
10447 			break; 		/* goto sizeof (int) option return */
10448 
10449 		case IPV6_MULTICAST_HOPS:
10450 			/* Recorded in transport above IP */
10451 			break;	/* goto sizeof (int) option return */
10452 		case IPV6_MULTICAST_LOOP:
10453 			if (!checkonly) {
10454 				mutex_enter(&connp->conn_lock);
10455 				connp->conn_multicast_loop = *i1;
10456 				mutex_exit(&connp->conn_lock);
10457 			}
10458 			break;	/* goto sizeof (int) option return */
10459 		case IPV6_JOIN_GROUP:
10460 		case MCAST_JOIN_GROUP:
10461 		case IPV6_LEAVE_GROUP:
10462 		case MCAST_LEAVE_GROUP: {
10463 			struct ipv6_mreq *ip_mreqp;
10464 			struct group_req *greqp;
10465 			ire_t *ire;
10466 			boolean_t done = B_FALSE;
10467 			in6_addr_t groupv6;
10468 			uint32_t ifindex;
10469 			boolean_t mcast_opt = B_TRUE;
10470 			mcast_record_t fmode;
10471 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10472 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10473 
10474 			switch (name) {
10475 			case IPV6_JOIN_GROUP:
10476 				mcast_opt = B_FALSE;
10477 				/* FALLTHRU */
10478 			case MCAST_JOIN_GROUP:
10479 				fmode = MODE_IS_EXCLUDE;
10480 				optfn = ip_opt_add_group_v6;
10481 				break;
10482 
10483 			case IPV6_LEAVE_GROUP:
10484 				mcast_opt = B_FALSE;
10485 				/* FALLTHRU */
10486 			case MCAST_LEAVE_GROUP:
10487 				fmode = MODE_IS_INCLUDE;
10488 				optfn = ip_opt_delete_group_v6;
10489 				break;
10490 			}
10491 
10492 			if (mcast_opt) {
10493 				struct sockaddr_in *sin;
10494 				struct sockaddr_in6 *sin6;
10495 				greqp = (struct group_req *)i1;
10496 				if (greqp->gr_group.ss_family == AF_INET) {
10497 					sin = (struct sockaddr_in *)
10498 					    &(greqp->gr_group);
10499 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10500 					    &groupv6);
10501 				} else {
10502 					sin6 = (struct sockaddr_in6 *)
10503 					    &(greqp->gr_group);
10504 					groupv6 = sin6->sin6_addr;
10505 				}
10506 				ifindex = greqp->gr_interface;
10507 			} else {
10508 				ip_mreqp = (struct ipv6_mreq *)i1;
10509 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10510 				ifindex = ip_mreqp->ipv6mr_interface;
10511 			}
10512 			/*
10513 			 * In the multirouting case, we need to replicate
10514 			 * the request on all interfaces that will take part
10515 			 * in replication.  We do so because multirouting is
10516 			 * reflective, thus we will probably receive multi-
10517 			 * casts on those interfaces.
10518 			 * The ip_multirt_apply_membership_v6() succeeds if
10519 			 * the operation succeeds on at least one interface.
10520 			 */
10521 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10522 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10523 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10524 			if (ire != NULL) {
10525 				if (ire->ire_flags & RTF_MULTIRT) {
10526 					error = ip_multirt_apply_membership_v6(
10527 					    optfn, ire, connp, checkonly,
10528 					    &groupv6, fmode, &ipv6_all_zeros,
10529 					    first_mp);
10530 					done = B_TRUE;
10531 				}
10532 				ire_refrele(ire);
10533 			}
10534 			if (!done) {
10535 				error = optfn(connp, checkonly, &groupv6,
10536 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10537 			}
10538 			if (error) {
10539 				/*
10540 				 * EINPROGRESS is a soft error, needs retry
10541 				 * so don't make *outlenp zero.
10542 				 */
10543 				if (error != EINPROGRESS)
10544 					*outlenp = 0;
10545 				return (error);
10546 			}
10547 			/* OK return - copy input buffer into output buffer */
10548 			if (invalp != outvalp) {
10549 				/* don't trust bcopy for identical src/dst */
10550 				bcopy(invalp, outvalp, inlen);
10551 			}
10552 			*outlenp = inlen;
10553 			return (0);
10554 		}
10555 		case MCAST_BLOCK_SOURCE:
10556 		case MCAST_UNBLOCK_SOURCE:
10557 		case MCAST_JOIN_SOURCE_GROUP:
10558 		case MCAST_LEAVE_SOURCE_GROUP: {
10559 			struct group_source_req *gsreqp;
10560 			in6_addr_t v6grp, v6src;
10561 			uint32_t ifindex;
10562 			mcast_record_t fmode;
10563 			ire_t *ire;
10564 			boolean_t done = B_FALSE;
10565 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10566 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10567 
10568 			switch (name) {
10569 			case MCAST_BLOCK_SOURCE:
10570 				fmode = MODE_IS_EXCLUDE;
10571 				optfn = ip_opt_add_group_v6;
10572 				break;
10573 			case MCAST_UNBLOCK_SOURCE:
10574 				fmode = MODE_IS_EXCLUDE;
10575 				optfn = ip_opt_delete_group_v6;
10576 				break;
10577 			case MCAST_JOIN_SOURCE_GROUP:
10578 				fmode = MODE_IS_INCLUDE;
10579 				optfn = ip_opt_add_group_v6;
10580 				break;
10581 			case MCAST_LEAVE_SOURCE_GROUP:
10582 				fmode = MODE_IS_INCLUDE;
10583 				optfn = ip_opt_delete_group_v6;
10584 				break;
10585 			}
10586 
10587 			gsreqp = (struct group_source_req *)i1;
10588 			ifindex = gsreqp->gsr_interface;
10589 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10590 				struct sockaddr_in *s;
10591 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10592 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10593 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10594 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10595 			} else {
10596 				struct sockaddr_in6 *s6;
10597 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10598 				v6grp = s6->sin6_addr;
10599 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10600 				v6src = s6->sin6_addr;
10601 			}
10602 
10603 			/*
10604 			 * In the multirouting case, we need to replicate
10605 			 * the request as noted in the mcast cases above.
10606 			 */
10607 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10608 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10609 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10610 			if (ire != NULL) {
10611 				if (ire->ire_flags & RTF_MULTIRT) {
10612 					error = ip_multirt_apply_membership_v6(
10613 					    optfn, ire, connp, checkonly,
10614 					    &v6grp, fmode, &v6src, first_mp);
10615 					done = B_TRUE;
10616 				}
10617 				ire_refrele(ire);
10618 			}
10619 			if (!done) {
10620 				error = optfn(connp, checkonly, &v6grp,
10621 				    ifindex, fmode, &v6src, first_mp);
10622 			}
10623 			if (error != 0) {
10624 				/*
10625 				 * EINPROGRESS is a soft error, needs retry
10626 				 * so don't make *outlenp zero.
10627 				 */
10628 				if (error != EINPROGRESS)
10629 					*outlenp = 0;
10630 				return (error);
10631 			}
10632 			/* OK return - copy input buffer into output buffer */
10633 			if (invalp != outvalp) {
10634 				bcopy(invalp, outvalp, inlen);
10635 			}
10636 			*outlenp = inlen;
10637 			return (0);
10638 		}
10639 		case IPV6_UNICAST_HOPS:
10640 			/* Recorded in transport above IP */
10641 			break;	/* goto sizeof (int) option return */
10642 		case IPV6_UNSPEC_SRC:
10643 			/* Allow sending with a zero source address */
10644 			if (!checkonly) {
10645 				mutex_enter(&connp->conn_lock);
10646 				connp->conn_unspec_src = *i1 ? 1 : 0;
10647 				mutex_exit(&connp->conn_lock);
10648 			}
10649 			break;	/* goto sizeof (int) option return */
10650 		case IPV6_RECVPKTINFO:
10651 			if (!checkonly) {
10652 				mutex_enter(&connp->conn_lock);
10653 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10654 				mutex_exit(&connp->conn_lock);
10655 			}
10656 			break;	/* goto sizeof (int) option return */
10657 		case IPV6_RECVTCLASS:
10658 			if (!checkonly) {
10659 				if (*i1 < 0 || *i1 > 1) {
10660 					return (EINVAL);
10661 				}
10662 				mutex_enter(&connp->conn_lock);
10663 				connp->conn_ipv6_recvtclass = *i1;
10664 				mutex_exit(&connp->conn_lock);
10665 			}
10666 			break;
10667 		case IPV6_RECVPATHMTU:
10668 			if (!checkonly) {
10669 				if (*i1 < 0 || *i1 > 1) {
10670 					return (EINVAL);
10671 				}
10672 				mutex_enter(&connp->conn_lock);
10673 				connp->conn_ipv6_recvpathmtu = *i1;
10674 				mutex_exit(&connp->conn_lock);
10675 			}
10676 			break;
10677 		case IPV6_RECVHOPLIMIT:
10678 			if (!checkonly) {
10679 				mutex_enter(&connp->conn_lock);
10680 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10681 				mutex_exit(&connp->conn_lock);
10682 			}
10683 			break;	/* goto sizeof (int) option return */
10684 		case IPV6_RECVHOPOPTS:
10685 			if (!checkonly) {
10686 				mutex_enter(&connp->conn_lock);
10687 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10688 				mutex_exit(&connp->conn_lock);
10689 			}
10690 			break;	/* goto sizeof (int) option return */
10691 		case IPV6_RECVDSTOPTS:
10692 			if (!checkonly) {
10693 				mutex_enter(&connp->conn_lock);
10694 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10695 				mutex_exit(&connp->conn_lock);
10696 			}
10697 			break;	/* goto sizeof (int) option return */
10698 		case IPV6_RECVRTHDR:
10699 			if (!checkonly) {
10700 				mutex_enter(&connp->conn_lock);
10701 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10702 				mutex_exit(&connp->conn_lock);
10703 			}
10704 			break;	/* goto sizeof (int) option return */
10705 		case IPV6_RECVRTHDRDSTOPTS:
10706 			if (!checkonly) {
10707 				mutex_enter(&connp->conn_lock);
10708 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10709 				mutex_exit(&connp->conn_lock);
10710 			}
10711 			break;	/* goto sizeof (int) option return */
10712 		case IPV6_PKTINFO:
10713 			if (inlen == 0)
10714 				return (-EINVAL);	/* clearing option */
10715 			error = ip6_set_pktinfo(cr, connp,
10716 			    (struct in6_pktinfo *)invalp, first_mp);
10717 			if (error != 0)
10718 				*outlenp = 0;
10719 			else
10720 				*outlenp = inlen;
10721 			return (error);
10722 		case IPV6_NEXTHOP: {
10723 			struct sockaddr_in6 *sin6;
10724 
10725 			/* Verify that the nexthop is reachable */
10726 			if (inlen == 0)
10727 				return (-EINVAL);	/* clearing option */
10728 
10729 			sin6 = (struct sockaddr_in6 *)invalp;
10730 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10731 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10732 			    NULL, MATCH_IRE_DEFAULT);
10733 
10734 			if (ire == NULL) {
10735 				*outlenp = 0;
10736 				return (EHOSTUNREACH);
10737 			}
10738 			ire_refrele(ire);
10739 			return (-EINVAL);
10740 		}
10741 		case IPV6_SEC_OPT:
10742 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10743 			if (error != 0) {
10744 				*outlenp = 0;
10745 				return (error);
10746 			}
10747 			break;
10748 		case IPV6_SRC_PREFERENCES: {
10749 			/*
10750 			 * This is implemented strictly in the ip module
10751 			 * (here and in tcp_opt_*() to accomodate tcp
10752 			 * sockets).  Modules above ip pass this option
10753 			 * down here since ip is the only one that needs to
10754 			 * be aware of source address preferences.
10755 			 *
10756 			 * This socket option only affects connected
10757 			 * sockets that haven't already bound to a specific
10758 			 * IPv6 address.  In other words, sockets that
10759 			 * don't call bind() with an address other than the
10760 			 * unspecified address and that call connect().
10761 			 * ip_bind_connected_v6() passes these preferences
10762 			 * to the ipif_select_source_v6() function.
10763 			 */
10764 			if (inlen != sizeof (uint32_t))
10765 				return (EINVAL);
10766 			error = ip6_set_src_preferences(connp,
10767 			    *(uint32_t *)invalp);
10768 			if (error != 0) {
10769 				*outlenp = 0;
10770 				return (error);
10771 			} else {
10772 				*outlenp = sizeof (uint32_t);
10773 			}
10774 			break;
10775 		}
10776 		case IPV6_V6ONLY:
10777 			if (*i1 < 0 || *i1 > 1) {
10778 				return (EINVAL);
10779 			}
10780 			mutex_enter(&connp->conn_lock);
10781 			connp->conn_ipv6_v6only = *i1;
10782 			mutex_exit(&connp->conn_lock);
10783 			break;
10784 		default:
10785 			return (-EINVAL);
10786 		}
10787 		break;
10788 	default:
10789 		/*
10790 		 * "soft" error (negative)
10791 		 * option not handled at this level
10792 		 * Note: Do not modify *outlenp
10793 		 */
10794 		return (-EINVAL);
10795 	}
10796 	/*
10797 	 * Common case of return from an option that is sizeof (int)
10798 	 */
10799 	*(int *)outvalp = *i1;
10800 	*outlenp = sizeof (int);
10801 	return (0);
10802 }
10803 
10804 /*
10805  * This routine gets default values of certain options whose default
10806  * values are maintained by protocol specific code
10807  */
10808 /* ARGSUSED */
10809 int
10810 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10811 {
10812 	int *i1 = (int *)ptr;
10813 
10814 	switch (level) {
10815 	case IPPROTO_IP:
10816 		switch (name) {
10817 		case IP_MULTICAST_TTL:
10818 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10819 			return (sizeof (uchar_t));
10820 		case IP_MULTICAST_LOOP:
10821 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10822 			return (sizeof (uchar_t));
10823 		default:
10824 			return (-1);
10825 		}
10826 	case IPPROTO_IPV6:
10827 		switch (name) {
10828 		case IPV6_UNICAST_HOPS:
10829 			*i1 = ipv6_def_hops;
10830 			return (sizeof (int));
10831 		case IPV6_MULTICAST_HOPS:
10832 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10833 			return (sizeof (int));
10834 		case IPV6_MULTICAST_LOOP:
10835 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10836 			return (sizeof (int));
10837 		case IPV6_V6ONLY:
10838 			*i1 = 1;
10839 			return (sizeof (int));
10840 		default:
10841 			return (-1);
10842 		}
10843 	default:
10844 		return (-1);
10845 	}
10846 	/* NOTREACHED */
10847 }
10848 
10849 /*
10850  * Given a destination address and a pointer to where to put the information
10851  * this routine fills in the mtuinfo.
10852  */
10853 int
10854 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10855     struct ip6_mtuinfo *mtuinfo)
10856 {
10857 	ire_t *ire;
10858 
10859 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10860 		return (-1);
10861 
10862 	bzero(mtuinfo, sizeof (*mtuinfo));
10863 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10864 	mtuinfo->ip6m_addr.sin6_port = port;
10865 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10866 
10867 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
10868 	if (ire != NULL) {
10869 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10870 		ire_refrele(ire);
10871 	} else {
10872 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10873 	}
10874 	return (sizeof (struct ip6_mtuinfo));
10875 }
10876 
10877 /*
10878  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10879  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10880  * isn't.  This doesn't matter as the error checking is done properly for the
10881  * other MRT options coming in through ip_opt_set.
10882  */
10883 int
10884 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10885 {
10886 	conn_t		*connp = Q_TO_CONN(q);
10887 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10888 
10889 	switch (level) {
10890 	case IPPROTO_IP:
10891 		switch (name) {
10892 		case MRT_VERSION:
10893 		case MRT_ASSERT:
10894 			(void) ip_mrouter_get(name, q, ptr);
10895 			return (sizeof (int));
10896 		case IP_SEC_OPT:
10897 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10898 		case IP_NEXTHOP:
10899 			if (connp->conn_nexthop_set) {
10900 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10901 				return (sizeof (ipaddr_t));
10902 			} else
10903 				return (0);
10904 		default:
10905 			break;
10906 		}
10907 		break;
10908 	case IPPROTO_IPV6:
10909 		switch (name) {
10910 		case IPV6_SEC_OPT:
10911 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10912 		case IPV6_SRC_PREFERENCES: {
10913 			return (ip6_get_src_preferences(connp,
10914 			    (uint32_t *)ptr));
10915 		}
10916 		case IPV6_V6ONLY:
10917 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10918 			return (sizeof (int));
10919 		case IPV6_PATHMTU:
10920 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10921 				(struct ip6_mtuinfo *)ptr));
10922 		default:
10923 			break;
10924 		}
10925 		break;
10926 	default:
10927 		break;
10928 	}
10929 	return (-1);
10930 }
10931 
10932 /* Named Dispatch routine to get a current value out of our parameter table. */
10933 /* ARGSUSED */
10934 static int
10935 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10936 {
10937 	ipparam_t *ippa = (ipparam_t *)cp;
10938 
10939 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10940 	return (0);
10941 }
10942 
10943 /* ARGSUSED */
10944 static int
10945 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10946 {
10947 
10948 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10949 	return (0);
10950 }
10951 
10952 /*
10953  * Set ip{,6}_forwarding values.  This means walking through all of the
10954  * ill's and toggling their forwarding values.
10955  */
10956 /* ARGSUSED */
10957 static int
10958 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10959 {
10960 	long new_value;
10961 	int *forwarding_value = (int *)cp;
10962 	ill_t *walker;
10963 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10964 	ill_walk_context_t ctx;
10965 
10966 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10967 	    new_value < 0 || new_value > 1) {
10968 		return (EINVAL);
10969 	}
10970 
10971 	*forwarding_value = new_value;
10972 
10973 	/*
10974 	 * Regardless of the current value of ip_forwarding, set all per-ill
10975 	 * values of ip_forwarding to the value being set.
10976 	 *
10977 	 * Bring all the ill's up to date with the new global value.
10978 	 */
10979 	rw_enter(&ill_g_lock, RW_READER);
10980 
10981 	if (isv6)
10982 		walker = ILL_START_WALK_V6(&ctx);
10983 	else
10984 		walker = ILL_START_WALK_V4(&ctx);
10985 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10986 		(void) ill_forward_set(q, mp, (new_value != 0),
10987 		    (caddr_t)walker);
10988 	}
10989 	rw_exit(&ill_g_lock);
10990 
10991 	return (0);
10992 }
10993 
10994 /*
10995  * Walk through the param array specified registering each element with the
10996  * Named Dispatch handler. This is called only during init. So it is ok
10997  * not to acquire any locks
10998  */
10999 static boolean_t
11000 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11001     ipndp_t *ipnd, size_t ipnd_cnt)
11002 {
11003 	for (; ippa_cnt-- > 0; ippa++) {
11004 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11005 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11006 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11007 				nd_free(&ip_g_nd);
11008 				return (B_FALSE);
11009 			}
11010 		}
11011 	}
11012 
11013 	for (; ipnd_cnt-- > 0; ipnd++) {
11014 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11015 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11016 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11017 			    ipnd->ip_ndp_data)) {
11018 				nd_free(&ip_g_nd);
11019 				return (B_FALSE);
11020 			}
11021 		}
11022 	}
11023 
11024 	return (B_TRUE);
11025 }
11026 
11027 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11028 /* ARGSUSED */
11029 static int
11030 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11031 {
11032 	long		new_value;
11033 	ipparam_t	*ippa = (ipparam_t *)cp;
11034 
11035 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11036 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11037 		return (EINVAL);
11038 	}
11039 	ippa->ip_param_value = new_value;
11040 	return (0);
11041 }
11042 
11043 /*
11044  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11045  * When an ipf is passed here for the first time, if
11046  * we already have in-order fragments on the queue, we convert from the fast-
11047  * path reassembly scheme to the hard-case scheme.  From then on, additional
11048  * fragments are reassembled here.  We keep track of the start and end offsets
11049  * of each piece, and the number of holes in the chain.  When the hole count
11050  * goes to zero, we are done!
11051  *
11052  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11053  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11054  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11055  * after the call to ip_reassemble().
11056  */
11057 int
11058 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11059     size_t msg_len)
11060 {
11061 	uint_t	end;
11062 	mblk_t	*next_mp;
11063 	mblk_t	*mp1;
11064 	uint_t	offset;
11065 	boolean_t incr_dups = B_TRUE;
11066 	boolean_t offset_zero_seen = B_FALSE;
11067 	boolean_t pkt_boundary_checked = B_FALSE;
11068 
11069 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11070 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11071 
11072 	/* Add in byte count */
11073 	ipf->ipf_count += msg_len;
11074 	if (ipf->ipf_end) {
11075 		/*
11076 		 * We were part way through in-order reassembly, but now there
11077 		 * is a hole.  We walk through messages already queued, and
11078 		 * mark them for hard case reassembly.  We know that up till
11079 		 * now they were in order starting from offset zero.
11080 		 */
11081 		offset = 0;
11082 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11083 			IP_REASS_SET_START(mp1, offset);
11084 			if (offset == 0) {
11085 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11086 				offset = -ipf->ipf_nf_hdr_len;
11087 			}
11088 			offset += mp1->b_wptr - mp1->b_rptr;
11089 			IP_REASS_SET_END(mp1, offset);
11090 		}
11091 		/* One hole at the end. */
11092 		ipf->ipf_hole_cnt = 1;
11093 		/* Brand it as a hard case, forever. */
11094 		ipf->ipf_end = 0;
11095 	}
11096 	/* Walk through all the new pieces. */
11097 	do {
11098 		end = start + (mp->b_wptr - mp->b_rptr);
11099 		/*
11100 		 * If start is 0, decrease 'end' only for the first mblk of
11101 		 * the fragment. Otherwise 'end' can get wrong value in the
11102 		 * second pass of the loop if first mblk is exactly the
11103 		 * size of ipf_nf_hdr_len.
11104 		 */
11105 		if (start == 0 && !offset_zero_seen) {
11106 			/* First segment */
11107 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11108 			end -= ipf->ipf_nf_hdr_len;
11109 			offset_zero_seen = B_TRUE;
11110 		}
11111 		next_mp = mp->b_cont;
11112 		/*
11113 		 * We are checking to see if there is any interesing data
11114 		 * to process.  If there isn't and the mblk isn't the
11115 		 * one which carries the unfragmentable header then we
11116 		 * drop it.  It's possible to have just the unfragmentable
11117 		 * header come through without any data.  That needs to be
11118 		 * saved.
11119 		 *
11120 		 * If the assert at the top of this function holds then the
11121 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11122 		 * is infrequently traveled enough that the test is left in
11123 		 * to protect against future code changes which break that
11124 		 * invariant.
11125 		 */
11126 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11127 			/* Empty.  Blast it. */
11128 			IP_REASS_SET_START(mp, 0);
11129 			IP_REASS_SET_END(mp, 0);
11130 			/*
11131 			 * If the ipf points to the mblk we are about to free,
11132 			 * update ipf to point to the next mblk (or NULL
11133 			 * if none).
11134 			 */
11135 			if (ipf->ipf_mp->b_cont == mp)
11136 				ipf->ipf_mp->b_cont = next_mp;
11137 			freeb(mp);
11138 			continue;
11139 		}
11140 		mp->b_cont = NULL;
11141 		IP_REASS_SET_START(mp, start);
11142 		IP_REASS_SET_END(mp, end);
11143 		if (!ipf->ipf_tail_mp) {
11144 			ipf->ipf_tail_mp = mp;
11145 			ipf->ipf_mp->b_cont = mp;
11146 			if (start == 0 || !more) {
11147 				ipf->ipf_hole_cnt = 1;
11148 				/*
11149 				 * if the first fragment comes in more than one
11150 				 * mblk, this loop will be executed for each
11151 				 * mblk. Need to adjust hole count so exiting
11152 				 * this routine will leave hole count at 1.
11153 				 */
11154 				if (next_mp)
11155 					ipf->ipf_hole_cnt++;
11156 			} else
11157 				ipf->ipf_hole_cnt = 2;
11158 			continue;
11159 		} else if (ipf->ipf_last_frag_seen && !more &&
11160 			    !pkt_boundary_checked) {
11161 			/*
11162 			 * We check datagram boundary only if this fragment
11163 			 * claims to be the last fragment and we have seen a
11164 			 * last fragment in the past too. We do this only
11165 			 * once for a given fragment.
11166 			 *
11167 			 * start cannot be 0 here as fragments with start=0
11168 			 * and MF=0 gets handled as a complete packet. These
11169 			 * fragments should not reach here.
11170 			 */
11171 
11172 			if (start + msgdsize(mp) !=
11173 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11174 				/*
11175 				 * We have two fragments both of which claim
11176 				 * to be the last fragment but gives conflicting
11177 				 * information about the whole datagram size.
11178 				 * Something fishy is going on. Drop the
11179 				 * fragment and free up the reassembly list.
11180 				 */
11181 				return (IP_REASS_FAILED);
11182 			}
11183 
11184 			/*
11185 			 * We shouldn't come to this code block again for this
11186 			 * particular fragment.
11187 			 */
11188 			pkt_boundary_checked = B_TRUE;
11189 		}
11190 
11191 		/* New stuff at or beyond tail? */
11192 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11193 		if (start >= offset) {
11194 			if (ipf->ipf_last_frag_seen) {
11195 				/* current fragment is beyond last fragment */
11196 				return (IP_REASS_FAILED);
11197 			}
11198 			/* Link it on end. */
11199 			ipf->ipf_tail_mp->b_cont = mp;
11200 			ipf->ipf_tail_mp = mp;
11201 			if (more) {
11202 				if (start != offset)
11203 					ipf->ipf_hole_cnt++;
11204 			} else if (start == offset && next_mp == NULL)
11205 					ipf->ipf_hole_cnt--;
11206 			continue;
11207 		}
11208 		mp1 = ipf->ipf_mp->b_cont;
11209 		offset = IP_REASS_START(mp1);
11210 		/* New stuff at the front? */
11211 		if (start < offset) {
11212 			if (start == 0) {
11213 				if (end >= offset) {
11214 					/* Nailed the hole at the begining. */
11215 					ipf->ipf_hole_cnt--;
11216 				}
11217 			} else if (end < offset) {
11218 				/*
11219 				 * A hole, stuff, and a hole where there used
11220 				 * to be just a hole.
11221 				 */
11222 				ipf->ipf_hole_cnt++;
11223 			}
11224 			mp->b_cont = mp1;
11225 			/* Check for overlap. */
11226 			while (end > offset) {
11227 				if (end < IP_REASS_END(mp1)) {
11228 					mp->b_wptr -= end - offset;
11229 					IP_REASS_SET_END(mp, offset);
11230 					if (ill->ill_isv6) {
11231 						BUMP_MIB(ill->ill_ip6_mib,
11232 						    ipv6ReasmPartDups);
11233 					} else {
11234 						BUMP_MIB(&ip_mib,
11235 						    ipReasmPartDups);
11236 					}
11237 					break;
11238 				}
11239 				/* Did we cover another hole? */
11240 				if ((mp1->b_cont &&
11241 				    IP_REASS_END(mp1) !=
11242 				    IP_REASS_START(mp1->b_cont) &&
11243 				    end >= IP_REASS_START(mp1->b_cont)) ||
11244 				    (!ipf->ipf_last_frag_seen && !more)) {
11245 					ipf->ipf_hole_cnt--;
11246 				}
11247 				/* Clip out mp1. */
11248 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11249 					/*
11250 					 * After clipping out mp1, this guy
11251 					 * is now hanging off the end.
11252 					 */
11253 					ipf->ipf_tail_mp = mp;
11254 				}
11255 				IP_REASS_SET_START(mp1, 0);
11256 				IP_REASS_SET_END(mp1, 0);
11257 				/* Subtract byte count */
11258 				ipf->ipf_count -= mp1->b_datap->db_lim -
11259 				    mp1->b_datap->db_base;
11260 				freeb(mp1);
11261 				if (ill->ill_isv6) {
11262 					BUMP_MIB(ill->ill_ip6_mib,
11263 					    ipv6ReasmPartDups);
11264 				} else {
11265 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11266 				}
11267 				mp1 = mp->b_cont;
11268 				if (!mp1)
11269 					break;
11270 				offset = IP_REASS_START(mp1);
11271 			}
11272 			ipf->ipf_mp->b_cont = mp;
11273 			continue;
11274 		}
11275 		/*
11276 		 * The new piece starts somewhere between the start of the head
11277 		 * and before the end of the tail.
11278 		 */
11279 		for (; mp1; mp1 = mp1->b_cont) {
11280 			offset = IP_REASS_END(mp1);
11281 			if (start < offset) {
11282 				if (end <= offset) {
11283 					/* Nothing new. */
11284 					IP_REASS_SET_START(mp, 0);
11285 					IP_REASS_SET_END(mp, 0);
11286 					/* Subtract byte count */
11287 					ipf->ipf_count -= mp->b_datap->db_lim -
11288 					    mp->b_datap->db_base;
11289 					if (incr_dups) {
11290 						ipf->ipf_num_dups++;
11291 						incr_dups = B_FALSE;
11292 					}
11293 					freeb(mp);
11294 					if (ill->ill_isv6) {
11295 						BUMP_MIB(ill->ill_ip6_mib,
11296 						    ipv6ReasmDuplicates);
11297 					} else {
11298 						BUMP_MIB(&ip_mib,
11299 						    ipReasmDuplicates);
11300 					}
11301 					break;
11302 				}
11303 				/*
11304 				 * Trim redundant stuff off beginning of new
11305 				 * piece.
11306 				 */
11307 				IP_REASS_SET_START(mp, offset);
11308 				mp->b_rptr += offset - start;
11309 				if (ill->ill_isv6) {
11310 					BUMP_MIB(ill->ill_ip6_mib,
11311 					    ipv6ReasmPartDups);
11312 				} else {
11313 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11314 				}
11315 				start = offset;
11316 				if (!mp1->b_cont) {
11317 					/*
11318 					 * After trimming, this guy is now
11319 					 * hanging off the end.
11320 					 */
11321 					mp1->b_cont = mp;
11322 					ipf->ipf_tail_mp = mp;
11323 					if (!more) {
11324 						ipf->ipf_hole_cnt--;
11325 					}
11326 					break;
11327 				}
11328 			}
11329 			if (start >= IP_REASS_START(mp1->b_cont))
11330 				continue;
11331 			/* Fill a hole */
11332 			if (start > offset)
11333 				ipf->ipf_hole_cnt++;
11334 			mp->b_cont = mp1->b_cont;
11335 			mp1->b_cont = mp;
11336 			mp1 = mp->b_cont;
11337 			offset = IP_REASS_START(mp1);
11338 			if (end >= offset) {
11339 				ipf->ipf_hole_cnt--;
11340 				/* Check for overlap. */
11341 				while (end > offset) {
11342 					if (end < IP_REASS_END(mp1)) {
11343 						mp->b_wptr -= end - offset;
11344 						IP_REASS_SET_END(mp, offset);
11345 						/*
11346 						 * TODO we might bump
11347 						 * this up twice if there is
11348 						 * overlap at both ends.
11349 						 */
11350 						if (ill->ill_isv6) {
11351 							BUMP_MIB(
11352 							    ill->ill_ip6_mib,
11353 							    ipv6ReasmPartDups);
11354 						} else {
11355 							BUMP_MIB(&ip_mib,
11356 							    ipReasmPartDups);
11357 						}
11358 						break;
11359 					}
11360 					/* Did we cover another hole? */
11361 					if ((mp1->b_cont &&
11362 					    IP_REASS_END(mp1)
11363 					    != IP_REASS_START(mp1->b_cont) &&
11364 					    end >=
11365 					    IP_REASS_START(mp1->b_cont)) ||
11366 					    (!ipf->ipf_last_frag_seen &&
11367 					    !more)) {
11368 						ipf->ipf_hole_cnt--;
11369 					}
11370 					/* Clip out mp1. */
11371 					if ((mp->b_cont = mp1->b_cont) ==
11372 					    NULL) {
11373 						/*
11374 						 * After clipping out mp1,
11375 						 * this guy is now hanging
11376 						 * off the end.
11377 						 */
11378 						ipf->ipf_tail_mp = mp;
11379 					}
11380 					IP_REASS_SET_START(mp1, 0);
11381 					IP_REASS_SET_END(mp1, 0);
11382 					/* Subtract byte count */
11383 					ipf->ipf_count -=
11384 					    mp1->b_datap->db_lim -
11385 					    mp1->b_datap->db_base;
11386 					freeb(mp1);
11387 					if (ill->ill_isv6) {
11388 						BUMP_MIB(ill->ill_ip6_mib,
11389 						    ipv6ReasmPartDups);
11390 					} else {
11391 						BUMP_MIB(&ip_mib,
11392 						    ipReasmPartDups);
11393 					}
11394 					mp1 = mp->b_cont;
11395 					if (!mp1)
11396 						break;
11397 					offset = IP_REASS_START(mp1);
11398 				}
11399 			}
11400 			break;
11401 		}
11402 	} while (start = end, mp = next_mp);
11403 
11404 	/* Fragment just processed could be the last one. Remember this fact */
11405 	if (!more)
11406 		ipf->ipf_last_frag_seen = B_TRUE;
11407 
11408 	/* Still got holes? */
11409 	if (ipf->ipf_hole_cnt)
11410 		return (IP_REASS_PARTIAL);
11411 	/* Clean up overloaded fields to avoid upstream disasters. */
11412 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11413 		IP_REASS_SET_START(mp1, 0);
11414 		IP_REASS_SET_END(mp1, 0);
11415 	}
11416 	return (IP_REASS_COMPLETE);
11417 }
11418 
11419 /*
11420  * ipsec processing for the fast path, used for input UDP Packets
11421  */
11422 static boolean_t
11423 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11424     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11425 {
11426 	uint32_t	ill_index;
11427 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11428 
11429 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11430 	/* The ill_index of the incoming ILL */
11431 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11432 
11433 	/* pass packet up to the transport */
11434 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11435 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11436 		    NULL, mctl_present);
11437 		if (*first_mpp == NULL) {
11438 			return (B_FALSE);
11439 		}
11440 	}
11441 
11442 	/* Initiate IPPF processing for fastpath UDP */
11443 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11444 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11445 		if (*mpp == NULL) {
11446 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11447 			    "deferred/dropped during IPPF processing\n"));
11448 			return (B_FALSE);
11449 		}
11450 	}
11451 	/*
11452 	 * We make the checks as below since we are in the fast path
11453 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11454 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11455 	 */
11456 	if (connp->conn_recvif || connp->conn_recvslla ||
11457 	    connp->conn_ipv6_recvpktinfo) {
11458 		if (connp->conn_recvif ||
11459 		    connp->conn_ipv6_recvpktinfo) {
11460 			in_flags = IPF_RECVIF;
11461 		}
11462 		if (connp->conn_recvslla) {
11463 			in_flags |= IPF_RECVSLLA;
11464 		}
11465 		/*
11466 		 * since in_flags are being set ill will be
11467 		 * referenced in ip_add_info, so it better not
11468 		 * be NULL.
11469 		 */
11470 		/*
11471 		 * the actual data will be contained in b_cont
11472 		 * upon successful return of the following call.
11473 		 * If the call fails then the original mblk is
11474 		 * returned.
11475 		 */
11476 		*mpp = ip_add_info(*mpp, ill, in_flags);
11477 	}
11478 
11479 	return (B_TRUE);
11480 }
11481 
11482 /*
11483  * Fragmentation reassembly.  Each ILL has a hash table for
11484  * queuing packets undergoing reassembly for all IPIFs
11485  * associated with the ILL.  The hash is based on the packet
11486  * IP ident field.  The ILL frag hash table was allocated
11487  * as a timer block at the time the ILL was created.  Whenever
11488  * there is anything on the reassembly queue, the timer will
11489  * be running.  Returns B_TRUE if successful else B_FALSE;
11490  * frees mp on failure.
11491  */
11492 static boolean_t
11493 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11494     uint32_t *cksum_val, uint16_t *cksum_flags)
11495 {
11496 	uint32_t	frag_offset_flags;
11497 	ill_t		*ill = (ill_t *)q->q_ptr;
11498 	mblk_t		*mp = *mpp;
11499 	mblk_t		*t_mp;
11500 	ipaddr_t	dst;
11501 	uint8_t		proto = ipha->ipha_protocol;
11502 	uint32_t	sum_val;
11503 	uint16_t	sum_flags;
11504 	ipf_t		*ipf;
11505 	ipf_t		**ipfp;
11506 	ipfb_t		*ipfb;
11507 	uint16_t	ident;
11508 	uint32_t	offset;
11509 	ipaddr_t	src;
11510 	uint_t		hdr_length;
11511 	uint32_t	end;
11512 	mblk_t		*mp1;
11513 	mblk_t		*tail_mp;
11514 	size_t		count;
11515 	size_t		msg_len;
11516 	uint8_t		ecn_info = 0;
11517 	uint32_t	packet_size;
11518 	boolean_t	pruned = B_FALSE;
11519 
11520 	if (cksum_val != NULL)
11521 		*cksum_val = 0;
11522 	if (cksum_flags != NULL)
11523 		*cksum_flags = 0;
11524 
11525 	/*
11526 	 * Drop the fragmented as early as possible, if
11527 	 * we don't have resource(s) to re-assemble.
11528 	 */
11529 	if (ip_reass_queue_bytes == 0) {
11530 		freemsg(mp);
11531 		return (B_FALSE);
11532 	}
11533 
11534 	/* Check for fragmentation offset; return if there's none */
11535 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11536 	    (IPH_MF | IPH_OFFSET)) == 0)
11537 		return (B_TRUE);
11538 
11539 	/*
11540 	 * We utilize hardware computed checksum info only for UDP since
11541 	 * IP fragmentation is a normal occurence for the protocol.  In
11542 	 * addition, checksum offload support for IP fragments carrying
11543 	 * UDP payload is commonly implemented across network adapters.
11544 	 */
11545 	ASSERT(ill != NULL);
11546 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11547 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11548 		mblk_t *mp1 = mp->b_cont;
11549 		int32_t len;
11550 
11551 		/* Record checksum information from the packet */
11552 		sum_val = (uint32_t)DB_CKSUM16(mp);
11553 		sum_flags = DB_CKSUMFLAGS(mp);
11554 
11555 		/* IP payload offset from beginning of mblk */
11556 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11557 
11558 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11559 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11560 		    offset >= DB_CKSUMSTART(mp) &&
11561 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11562 			uint32_t adj;
11563 			/*
11564 			 * Partial checksum has been calculated by hardware
11565 			 * and attached to the packet; in addition, any
11566 			 * prepended extraneous data is even byte aligned.
11567 			 * If any such data exists, we adjust the checksum;
11568 			 * this would also handle any postpended data.
11569 			 */
11570 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11571 			    mp, mp1, len, adj);
11572 
11573 			/* One's complement subtract extraneous checksum */
11574 			if (adj >= sum_val)
11575 				sum_val = ~(adj - sum_val) & 0xFFFF;
11576 			else
11577 				sum_val -= adj;
11578 		}
11579 	} else {
11580 		sum_val = 0;
11581 		sum_flags = 0;
11582 	}
11583 
11584 	/* Clear hardware checksumming flag */
11585 	DB_CKSUMFLAGS(mp) = 0;
11586 
11587 	ident = ipha->ipha_ident;
11588 	offset = (frag_offset_flags << 3) & 0xFFFF;
11589 	src = ipha->ipha_src;
11590 	dst = ipha->ipha_dst;
11591 	hdr_length = IPH_HDR_LENGTH(ipha);
11592 	end = ntohs(ipha->ipha_length) - hdr_length;
11593 
11594 	/* If end == 0 then we have a packet with no data, so just free it */
11595 	if (end == 0) {
11596 		freemsg(mp);
11597 		return (B_FALSE);
11598 	}
11599 
11600 	/* Record the ECN field info. */
11601 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11602 	if (offset != 0) {
11603 		/*
11604 		 * If this isn't the first piece, strip the header, and
11605 		 * add the offset to the end value.
11606 		 */
11607 		mp->b_rptr += hdr_length;
11608 		end += offset;
11609 	}
11610 
11611 	msg_len = MBLKSIZE(mp);
11612 	tail_mp = mp;
11613 	while (tail_mp->b_cont != NULL) {
11614 		tail_mp = tail_mp->b_cont;
11615 		msg_len += MBLKSIZE(tail_mp);
11616 	}
11617 
11618 	/* If the reassembly list for this ILL will get too big, prune it */
11619 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11620 	    ip_reass_queue_bytes) {
11621 		ill_frag_prune(ill,
11622 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11623 		    (ip_reass_queue_bytes - msg_len));
11624 		pruned = B_TRUE;
11625 	}
11626 
11627 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11628 	mutex_enter(&ipfb->ipfb_lock);
11629 
11630 	ipfp = &ipfb->ipfb_ipf;
11631 	/* Try to find an existing fragment queue for this packet. */
11632 	for (;;) {
11633 		ipf = ipfp[0];
11634 		if (ipf != NULL) {
11635 			/*
11636 			 * It has to match on ident and src/dst address.
11637 			 */
11638 			if (ipf->ipf_ident == ident &&
11639 			    ipf->ipf_src == src &&
11640 			    ipf->ipf_dst == dst &&
11641 			    ipf->ipf_protocol == proto) {
11642 				/*
11643 				 * If we have received too many
11644 				 * duplicate fragments for this packet
11645 				 * free it.
11646 				 */
11647 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11648 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11649 					freemsg(mp);
11650 					mutex_exit(&ipfb->ipfb_lock);
11651 					return (B_FALSE);
11652 				}
11653 				/* Found it. */
11654 				break;
11655 			}
11656 			ipfp = &ipf->ipf_hash_next;
11657 			continue;
11658 		}
11659 
11660 		/*
11661 		 * If we pruned the list, do we want to store this new
11662 		 * fragment?. We apply an optimization here based on the
11663 		 * fact that most fragments will be received in order.
11664 		 * So if the offset of this incoming fragment is zero,
11665 		 * it is the first fragment of a new packet. We will
11666 		 * keep it.  Otherwise drop the fragment, as we have
11667 		 * probably pruned the packet already (since the
11668 		 * packet cannot be found).
11669 		 */
11670 		if (pruned && offset != 0) {
11671 			mutex_exit(&ipfb->ipfb_lock);
11672 			freemsg(mp);
11673 			return (B_FALSE);
11674 		}
11675 
11676 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11677 			/*
11678 			 * Too many fragmented packets in this hash
11679 			 * bucket. Free the oldest.
11680 			 */
11681 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11682 		}
11683 
11684 		/* New guy.  Allocate a frag message. */
11685 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11686 		if (mp1 == NULL) {
11687 			BUMP_MIB(&ip_mib, ipInDiscards);
11688 			freemsg(mp);
11689 reass_done:
11690 			mutex_exit(&ipfb->ipfb_lock);
11691 			return (B_FALSE);
11692 		}
11693 
11694 
11695 		BUMP_MIB(&ip_mib, ipReasmReqds);
11696 		mp1->b_cont = mp;
11697 
11698 		/* Initialize the fragment header. */
11699 		ipf = (ipf_t *)mp1->b_rptr;
11700 		ipf->ipf_mp = mp1;
11701 		ipf->ipf_ptphn = ipfp;
11702 		ipfp[0] = ipf;
11703 		ipf->ipf_hash_next = NULL;
11704 		ipf->ipf_ident = ident;
11705 		ipf->ipf_protocol = proto;
11706 		ipf->ipf_src = src;
11707 		ipf->ipf_dst = dst;
11708 		ipf->ipf_nf_hdr_len = 0;
11709 		/* Record reassembly start time. */
11710 		ipf->ipf_timestamp = gethrestime_sec();
11711 		/* Record ipf generation and account for frag header */
11712 		ipf->ipf_gen = ill->ill_ipf_gen++;
11713 		ipf->ipf_count = MBLKSIZE(mp1);
11714 		ipf->ipf_last_frag_seen = B_FALSE;
11715 		ipf->ipf_ecn = ecn_info;
11716 		ipf->ipf_num_dups = 0;
11717 		ipfb->ipfb_frag_pkts++;
11718 		ipf->ipf_checksum = 0;
11719 		ipf->ipf_checksum_flags = 0;
11720 
11721 		/* Store checksum value in fragment header */
11722 		if (sum_flags != 0) {
11723 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11724 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11725 			ipf->ipf_checksum = sum_val;
11726 			ipf->ipf_checksum_flags = sum_flags;
11727 		}
11728 
11729 		/*
11730 		 * We handle reassembly two ways.  In the easy case,
11731 		 * where all the fragments show up in order, we do
11732 		 * minimal bookkeeping, and just clip new pieces on
11733 		 * the end.  If we ever see a hole, then we go off
11734 		 * to ip_reassemble which has to mark the pieces and
11735 		 * keep track of the number of holes, etc.  Obviously,
11736 		 * the point of having both mechanisms is so we can
11737 		 * handle the easy case as efficiently as possible.
11738 		 */
11739 		if (offset == 0) {
11740 			/* Easy case, in-order reassembly so far. */
11741 			ipf->ipf_count += msg_len;
11742 			ipf->ipf_tail_mp = tail_mp;
11743 			/*
11744 			 * Keep track of next expected offset in
11745 			 * ipf_end.
11746 			 */
11747 			ipf->ipf_end = end;
11748 			ipf->ipf_nf_hdr_len = hdr_length;
11749 		} else {
11750 			/* Hard case, hole at the beginning. */
11751 			ipf->ipf_tail_mp = NULL;
11752 			/*
11753 			 * ipf_end == 0 means that we have given up
11754 			 * on easy reassembly.
11755 			 */
11756 			ipf->ipf_end = 0;
11757 
11758 			/* Forget checksum offload from now on */
11759 			ipf->ipf_checksum_flags = 0;
11760 
11761 			/*
11762 			 * ipf_hole_cnt is set by ip_reassemble.
11763 			 * ipf_count is updated by ip_reassemble.
11764 			 * No need to check for return value here
11765 			 * as we don't expect reassembly to complete
11766 			 * or fail for the first fragment itself.
11767 			 */
11768 			(void) ip_reassemble(mp, ipf,
11769 			    (frag_offset_flags & IPH_OFFSET) << 3,
11770 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11771 		}
11772 		/* Update per ipfb and ill byte counts */
11773 		ipfb->ipfb_count += ipf->ipf_count;
11774 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11775 		ill->ill_frag_count += ipf->ipf_count;
11776 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11777 		/* If the frag timer wasn't already going, start it. */
11778 		mutex_enter(&ill->ill_lock);
11779 		ill_frag_timer_start(ill);
11780 		mutex_exit(&ill->ill_lock);
11781 		goto reass_done;
11782 	}
11783 
11784 	/*
11785 	 * If the packet's flag has changed (it could be coming up
11786 	 * from an interface different than the previous, therefore
11787 	 * possibly different checksum capability), then forget about
11788 	 * any stored checksum states.  Otherwise add the value to
11789 	 * the existing one stored in the fragment header.
11790 	 */
11791 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11792 		sum_val += ipf->ipf_checksum;
11793 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11794 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11795 		ipf->ipf_checksum = sum_val;
11796 	} else if (ipf->ipf_checksum_flags != 0) {
11797 		/* Forget checksum offload from now on */
11798 		ipf->ipf_checksum_flags = 0;
11799 	}
11800 
11801 	/*
11802 	 * We have a new piece of a datagram which is already being
11803 	 * reassembled.  Update the ECN info if all IP fragments
11804 	 * are ECN capable.  If there is one which is not, clear
11805 	 * all the info.  If there is at least one which has CE
11806 	 * code point, IP needs to report that up to transport.
11807 	 */
11808 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11809 		if (ecn_info == IPH_ECN_CE)
11810 			ipf->ipf_ecn = IPH_ECN_CE;
11811 	} else {
11812 		ipf->ipf_ecn = IPH_ECN_NECT;
11813 	}
11814 	if (offset && ipf->ipf_end == offset) {
11815 		/* The new fragment fits at the end */
11816 		ipf->ipf_tail_mp->b_cont = mp;
11817 		/* Update the byte count */
11818 		ipf->ipf_count += msg_len;
11819 		/* Update per ipfb and ill byte counts */
11820 		ipfb->ipfb_count += msg_len;
11821 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11822 		ill->ill_frag_count += msg_len;
11823 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11824 		if (frag_offset_flags & IPH_MF) {
11825 			/* More to come. */
11826 			ipf->ipf_end = end;
11827 			ipf->ipf_tail_mp = tail_mp;
11828 			goto reass_done;
11829 		}
11830 	} else {
11831 		/* Go do the hard cases. */
11832 		int ret;
11833 
11834 		if (offset == 0)
11835 			ipf->ipf_nf_hdr_len = hdr_length;
11836 
11837 		/* Save current byte count */
11838 		count = ipf->ipf_count;
11839 		ret = ip_reassemble(mp, ipf,
11840 		    (frag_offset_flags & IPH_OFFSET) << 3,
11841 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11842 		/* Count of bytes added and subtracted (freeb()ed) */
11843 		count = ipf->ipf_count - count;
11844 		if (count) {
11845 			/* Update per ipfb and ill byte counts */
11846 			ipfb->ipfb_count += count;
11847 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11848 			ill->ill_frag_count += count;
11849 			ASSERT(ill->ill_frag_count > 0);
11850 		}
11851 		if (ret == IP_REASS_PARTIAL) {
11852 			goto reass_done;
11853 		} else if (ret == IP_REASS_FAILED) {
11854 			/* Reassembly failed. Free up all resources */
11855 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11856 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11857 				IP_REASS_SET_START(t_mp, 0);
11858 				IP_REASS_SET_END(t_mp, 0);
11859 			}
11860 			freemsg(mp);
11861 			goto reass_done;
11862 		}
11863 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11864 	}
11865 	/*
11866 	 * We have completed reassembly.  Unhook the frag header from
11867 	 * the reassembly list.
11868 	 *
11869 	 * Before we free the frag header, record the ECN info
11870 	 * to report back to the transport.
11871 	 */
11872 	ecn_info = ipf->ipf_ecn;
11873 	BUMP_MIB(&ip_mib, ipReasmOKs);
11874 	ipfp = ipf->ipf_ptphn;
11875 
11876 	/* We need to supply these to caller */
11877 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11878 		sum_val = ipf->ipf_checksum;
11879 	else
11880 		sum_val = 0;
11881 
11882 	mp1 = ipf->ipf_mp;
11883 	count = ipf->ipf_count;
11884 	ipf = ipf->ipf_hash_next;
11885 	if (ipf != NULL)
11886 		ipf->ipf_ptphn = ipfp;
11887 	ipfp[0] = ipf;
11888 	ill->ill_frag_count -= count;
11889 	ASSERT(ipfb->ipfb_count >= count);
11890 	ipfb->ipfb_count -= count;
11891 	ipfb->ipfb_frag_pkts--;
11892 	mutex_exit(&ipfb->ipfb_lock);
11893 	/* Ditch the frag header. */
11894 	mp = mp1->b_cont;
11895 
11896 	freeb(mp1);
11897 
11898 	/* Restore original IP length in header. */
11899 	packet_size = (uint32_t)msgdsize(mp);
11900 	if (packet_size > IP_MAXPACKET) {
11901 		freemsg(mp);
11902 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11903 		return (B_FALSE);
11904 	}
11905 
11906 	if (DB_REF(mp) > 1) {
11907 		mblk_t *mp2 = copymsg(mp);
11908 
11909 		freemsg(mp);
11910 		if (mp2 == NULL) {
11911 			BUMP_MIB(&ip_mib, ipInDiscards);
11912 			return (B_FALSE);
11913 		}
11914 		mp = mp2;
11915 	}
11916 	ipha = (ipha_t *)mp->b_rptr;
11917 
11918 	ipha->ipha_length = htons((uint16_t)packet_size);
11919 	/* We're now complete, zip the frag state */
11920 	ipha->ipha_fragment_offset_and_flags = 0;
11921 	/* Record the ECN info. */
11922 	ipha->ipha_type_of_service &= 0xFC;
11923 	ipha->ipha_type_of_service |= ecn_info;
11924 	*mpp = mp;
11925 
11926 	/* Reassembly is successful; return checksum information if needed */
11927 	if (cksum_val != NULL)
11928 		*cksum_val = sum_val;
11929 	if (cksum_flags != NULL)
11930 		*cksum_flags = sum_flags;
11931 
11932 	return (B_TRUE);
11933 }
11934 
11935 /*
11936  * Perform ip header check sum update local options.
11937  * return B_TRUE if all is well, else return B_FALSE and release
11938  * the mp. caller is responsible for decrementing ire ref cnt.
11939  */
11940 static boolean_t
11941 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11942 {
11943 	mblk_t		*first_mp;
11944 	boolean_t	mctl_present;
11945 	uint16_t	sum;
11946 
11947 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11948 	/*
11949 	 * Don't do the checksum if it has gone through AH/ESP
11950 	 * processing.
11951 	 */
11952 	if (!mctl_present) {
11953 		sum = ip_csum_hdr(ipha);
11954 		if (sum != 0) {
11955 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11956 			freemsg(first_mp);
11957 			return (B_FALSE);
11958 		}
11959 	}
11960 
11961 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11962 		if (mctl_present)
11963 			freeb(first_mp);
11964 		return (B_FALSE);
11965 	}
11966 
11967 	return (B_TRUE);
11968 }
11969 
11970 /*
11971  * All udp packet are delivered to the local host via this routine.
11972  */
11973 void
11974 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11975     ill_t *recv_ill)
11976 {
11977 	uint32_t	sum;
11978 	uint32_t	u1;
11979 	boolean_t	mctl_present;
11980 	conn_t		*connp;
11981 	mblk_t		*first_mp;
11982 	uint16_t	*up;
11983 	ill_t		*ill = (ill_t *)q->q_ptr;
11984 	uint16_t	reass_hck_flags = 0;
11985 
11986 #define	rptr    ((uchar_t *)ipha)
11987 
11988 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11989 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11990 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11991 
11992 	/*
11993 	 * FAST PATH for udp packets
11994 	 */
11995 
11996 	/* u1 is # words of IP options */
11997 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11998 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11999 
12000 	/* IP options present */
12001 	if (u1 != 0)
12002 		goto ipoptions;
12003 
12004 	/* Check the IP header checksum.  */
12005 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12006 		/* Clear the IP header h/w cksum flag */
12007 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12008 	} else {
12009 #define	uph	((uint16_t *)ipha)
12010 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12011 		    uph[6] + uph[7] + uph[8] + uph[9];
12012 #undef	uph
12013 		/* finish doing IP checksum */
12014 		sum = (sum & 0xFFFF) + (sum >> 16);
12015 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12016 		/*
12017 		 * Don't verify header checksum if this packet is coming
12018 		 * back from AH/ESP as we already did it.
12019 		 */
12020 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12021 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12022 			freemsg(first_mp);
12023 			return;
12024 		}
12025 	}
12026 
12027 	/*
12028 	 * Count for SNMP of inbound packets for ire.
12029 	 * if mctl is present this might be a secure packet and
12030 	 * has already been counted for in ip_proto_input().
12031 	 */
12032 	if (!mctl_present) {
12033 		UPDATE_IB_PKT_COUNT(ire);
12034 		ire->ire_last_used_time = lbolt;
12035 	}
12036 
12037 	/* packet part of fragmented IP packet? */
12038 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12039 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12040 		goto fragmented;
12041 	}
12042 
12043 	/* u1 = IP header length (20 bytes) */
12044 	u1 = IP_SIMPLE_HDR_LENGTH;
12045 
12046 	/* packet does not contain complete IP & UDP headers */
12047 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12048 		goto udppullup;
12049 
12050 	/* up points to UDP header */
12051 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12052 #define	iphs    ((uint16_t *)ipha)
12053 
12054 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12055 	if (up[3] != 0) {
12056 		mblk_t *mp1 = mp->b_cont;
12057 		boolean_t cksum_err;
12058 		uint16_t hck_flags = 0;
12059 
12060 		/* Pseudo-header checksum */
12061 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12062 		    iphs[9] + up[2];
12063 
12064 		/*
12065 		 * Revert to software checksum calculation if the interface
12066 		 * isn't capable of checksum offload or if IPsec is present.
12067 		 */
12068 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12069 			hck_flags = DB_CKSUMFLAGS(mp);
12070 
12071 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12072 			IP_STAT(ip_in_sw_cksum);
12073 
12074 		IP_CKSUM_RECV(hck_flags, u1,
12075 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12076 		    (int32_t)((uchar_t *)up - rptr),
12077 		    mp, mp1, cksum_err);
12078 
12079 		if (cksum_err) {
12080 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12081 
12082 			if (hck_flags & HCK_FULLCKSUM)
12083 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12084 			else if (hck_flags & HCK_PARTIALCKSUM)
12085 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12086 			else
12087 				IP_STAT(ip_udp_in_sw_cksum_err);
12088 
12089 			freemsg(first_mp);
12090 			return;
12091 		}
12092 	}
12093 
12094 	/* Non-fragmented broadcast or multicast packet? */
12095 	if (ire->ire_type == IRE_BROADCAST)
12096 		goto udpslowpath;
12097 
12098 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12099 	    ire->ire_zoneid)) != NULL) {
12100 		ASSERT(connp->conn_upq != NULL);
12101 		IP_STAT(ip_udp_fast_path);
12102 
12103 		if (CONN_UDP_FLOWCTLD(connp)) {
12104 			freemsg(mp);
12105 			BUMP_MIB(&ip_mib, udpInOverflows);
12106 		} else {
12107 			if (!mctl_present) {
12108 				BUMP_MIB(&ip_mib, ipInDelivers);
12109 			}
12110 			/*
12111 			 * mp and first_mp can change.
12112 			 */
12113 			if (ip_udp_check(q, connp, recv_ill,
12114 			    ipha, &mp, &first_mp, mctl_present)) {
12115 				/* Send it upstream */
12116 				CONN_UDP_RECV(connp, mp);
12117 			}
12118 		}
12119 		/*
12120 		 * freeb() cannot deal with null mblk being passed
12121 		 * in and first_mp can be set to null in the call
12122 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12123 		 */
12124 		if (mctl_present && first_mp != NULL) {
12125 			freeb(first_mp);
12126 		}
12127 		CONN_DEC_REF(connp);
12128 		return;
12129 	}
12130 
12131 	/*
12132 	 * if we got here we know the packet is not fragmented and
12133 	 * has no options. The classifier could not find a conn_t and
12134 	 * most likely its an icmp packet so send it through slow path.
12135 	 */
12136 
12137 	goto udpslowpath;
12138 
12139 ipoptions:
12140 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12141 		goto slow_done;
12142 	}
12143 
12144 	UPDATE_IB_PKT_COUNT(ire);
12145 	ire->ire_last_used_time = lbolt;
12146 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12147 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12148 fragmented:
12149 		/*
12150 		 * "sum" and "reass_hck_flags" are non-zero if the
12151 		 * reassembled packet has a valid hardware computed
12152 		 * checksum information associated with it.
12153 		 */
12154 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12155 			goto slow_done;
12156 		/*
12157 		 * Make sure that first_mp points back to mp as
12158 		 * the mp we came in with could have changed in
12159 		 * ip_rput_fragment().
12160 		 */
12161 		ASSERT(!mctl_present);
12162 		ipha = (ipha_t *)mp->b_rptr;
12163 		first_mp = mp;
12164 	}
12165 
12166 	/* Now we have a complete datagram, destined for this machine. */
12167 	u1 = IPH_HDR_LENGTH(ipha);
12168 	/* Pull up the UDP header, if necessary. */
12169 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12170 udppullup:
12171 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12172 			BUMP_MIB(&ip_mib, ipInDiscards);
12173 			freemsg(first_mp);
12174 			goto slow_done;
12175 		}
12176 		ipha = (ipha_t *)mp->b_rptr;
12177 	}
12178 
12179 	/*
12180 	 * Validate the checksum for the reassembled packet; for the
12181 	 * pullup case we calculate the payload checksum in software.
12182 	 */
12183 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12184 	if (up[3] != 0) {
12185 		boolean_t cksum_err;
12186 
12187 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12188 			IP_STAT(ip_in_sw_cksum);
12189 
12190 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12191 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12192 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12193 		    iphs[9] + up[2], sum, cksum_err);
12194 
12195 		if (cksum_err) {
12196 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12197 
12198 			if (reass_hck_flags & HCK_FULLCKSUM)
12199 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12200 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12201 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12202 			else
12203 				IP_STAT(ip_udp_in_sw_cksum_err);
12204 
12205 			freemsg(first_mp);
12206 			goto slow_done;
12207 		}
12208 	}
12209 udpslowpath:
12210 
12211 	/* Clear hardware checksum flag to be safe */
12212 	DB_CKSUMFLAGS(mp) = 0;
12213 
12214 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12215 	    (ire->ire_type == IRE_BROADCAST),
12216 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12217 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12218 
12219 slow_done:
12220 	IP_STAT(ip_udp_slow_path);
12221 	return;
12222 
12223 #undef  iphs
12224 #undef  rptr
12225 }
12226 
12227 /* ARGSUSED */
12228 static mblk_t *
12229 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12230     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12231     ill_rx_ring_t *ill_ring)
12232 {
12233 	conn_t		*connp;
12234 	uint32_t	sum;
12235 	uint32_t	u1;
12236 	uint16_t	*up;
12237 	int		offset;
12238 	ssize_t		len;
12239 	mblk_t		*mp1;
12240 	boolean_t	syn_present = B_FALSE;
12241 	tcph_t		*tcph;
12242 	uint_t		ip_hdr_len;
12243 	ill_t		*ill = (ill_t *)q->q_ptr;
12244 	zoneid_t	zoneid = ire->ire_zoneid;
12245 	boolean_t	cksum_err;
12246 	uint16_t	hck_flags = 0;
12247 
12248 #define	rptr	((uchar_t *)ipha)
12249 
12250 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12251 
12252 	/*
12253 	 * FAST PATH for tcp packets
12254 	 */
12255 
12256 	/* u1 is # words of IP options */
12257 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12258 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12259 
12260 	/* IP options present */
12261 	if (u1) {
12262 		goto ipoptions;
12263 	} else {
12264 		/* Check the IP header checksum.  */
12265 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12266 			/* Clear the IP header h/w cksum flag */
12267 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12268 		} else {
12269 #define	uph	((uint16_t *)ipha)
12270 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12271 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12272 #undef	uph
12273 			/* finish doing IP checksum */
12274 			sum = (sum & 0xFFFF) + (sum >> 16);
12275 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12276 			/*
12277 			 * Don't verify header checksum if this packet
12278 			 * is coming back from AH/ESP as we already did it.
12279 			 */
12280 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12281 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12282 				goto error;
12283 			}
12284 		}
12285 	}
12286 
12287 	if (!mctl_present) {
12288 		UPDATE_IB_PKT_COUNT(ire);
12289 		ire->ire_last_used_time = lbolt;
12290 	}
12291 
12292 	/* packet part of fragmented IP packet? */
12293 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12294 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12295 		goto fragmented;
12296 	}
12297 
12298 	/* u1 = IP header length (20 bytes) */
12299 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12300 
12301 	/* does packet contain IP+TCP headers? */
12302 	len = mp->b_wptr - rptr;
12303 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12304 		IP_STAT(ip_tcppullup);
12305 		goto tcppullup;
12306 	}
12307 
12308 	/* TCP options present? */
12309 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12310 
12311 	/*
12312 	 * If options need to be pulled up, then goto tcpoptions.
12313 	 * otherwise we are still in the fast path
12314 	 */
12315 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12316 		IP_STAT(ip_tcpoptions);
12317 		goto tcpoptions;
12318 	}
12319 
12320 	/* multiple mblks of tcp data? */
12321 	if ((mp1 = mp->b_cont) != NULL) {
12322 		/* more then two? */
12323 		if (mp1->b_cont != NULL) {
12324 			IP_STAT(ip_multipkttcp);
12325 			goto multipkttcp;
12326 		}
12327 		len += mp1->b_wptr - mp1->b_rptr;
12328 	}
12329 
12330 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12331 
12332 	/* part of pseudo checksum */
12333 
12334 	/* TCP datagram length */
12335 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12336 
12337 #define	iphs    ((uint16_t *)ipha)
12338 
12339 #ifdef	_BIG_ENDIAN
12340 	u1 += IPPROTO_TCP;
12341 #else
12342 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12343 #endif
12344 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12345 
12346 	/*
12347 	 * Revert to software checksum calculation if the interface
12348 	 * isn't capable of checksum offload or if IPsec is present.
12349 	 */
12350 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12351 		hck_flags = DB_CKSUMFLAGS(mp);
12352 
12353 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12354 		IP_STAT(ip_in_sw_cksum);
12355 
12356 	IP_CKSUM_RECV(hck_flags, u1,
12357 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12358 	    (int32_t)((uchar_t *)up - rptr),
12359 	    mp, mp1, cksum_err);
12360 
12361 	if (cksum_err) {
12362 		BUMP_MIB(&ip_mib, tcpInErrs);
12363 
12364 		if (hck_flags & HCK_FULLCKSUM)
12365 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12366 		else if (hck_flags & HCK_PARTIALCKSUM)
12367 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12368 		else
12369 			IP_STAT(ip_tcp_in_sw_cksum_err);
12370 
12371 		goto error;
12372 	}
12373 
12374 try_again:
12375 
12376 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12377 	    NULL) {
12378 		/* Send the TH_RST */
12379 		goto no_conn;
12380 	}
12381 
12382 	/*
12383 	 * TCP FAST PATH for AF_INET socket.
12384 	 *
12385 	 * TCP fast path to avoid extra work. An AF_INET socket type
12386 	 * does not have facility to receive extra information via
12387 	 * ip_process or ip_add_info. Also, when the connection was
12388 	 * established, we made a check if this connection is impacted
12389 	 * by any global IPSec policy or per connection policy (a
12390 	 * policy that comes in effect later will not apply to this
12391 	 * connection). Since all this can be determined at the
12392 	 * connection establishment time, a quick check of flags
12393 	 * can avoid extra work.
12394 	 */
12395 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12396 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12397 		ASSERT(first_mp == mp);
12398 		SET_SQUEUE(mp, tcp_rput_data, connp);
12399 		return (mp);
12400 	}
12401 
12402 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12403 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12404 		if (IPCL_IS_TCP(connp)) {
12405 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12406 			DB_CKSUMSTART(mp) =
12407 			    (intptr_t)ip_squeue_get(ill_ring);
12408 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12409 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12410 				SET_SQUEUE(mp, connp->conn_recv, connp);
12411 				return (mp);
12412 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12413 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12414 				ip_squeue_enter_unbound++;
12415 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12416 				    connp);
12417 				return (mp);
12418 			}
12419 			syn_present = B_TRUE;
12420 		}
12421 
12422 	}
12423 
12424 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12425 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12426 
12427 		/* No need to send this packet to TCP */
12428 		if ((flags & TH_RST) || (flags & TH_URG)) {
12429 			CONN_DEC_REF(connp);
12430 			freemsg(first_mp);
12431 			return (NULL);
12432 		}
12433 		if (flags & TH_ACK) {
12434 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
12435 			CONN_DEC_REF(connp);
12436 			return (NULL);
12437 		}
12438 
12439 		CONN_DEC_REF(connp);
12440 		freemsg(first_mp);
12441 		return (NULL);
12442 	}
12443 
12444 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12445 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12446 		    ipha, NULL, mctl_present);
12447 		if (first_mp == NULL) {
12448 			CONN_DEC_REF(connp);
12449 			return (NULL);
12450 		}
12451 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12452 			ASSERT(syn_present);
12453 			if (mctl_present) {
12454 				ASSERT(first_mp != mp);
12455 				first_mp->b_datap->db_struioflag |=
12456 				    STRUIO_POLICY;
12457 			} else {
12458 				ASSERT(first_mp == mp);
12459 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12460 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12461 			}
12462 		} else {
12463 			/*
12464 			 * Discard first_mp early since we're dealing with a
12465 			 * fully-connected conn_t and tcp doesn't do policy in
12466 			 * this case.
12467 			 */
12468 			if (mctl_present) {
12469 				freeb(first_mp);
12470 				mctl_present = B_FALSE;
12471 			}
12472 			first_mp = mp;
12473 		}
12474 	}
12475 
12476 	/* Initiate IPPF processing for fastpath */
12477 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12478 		uint32_t	ill_index;
12479 
12480 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12481 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12482 		if (mp == NULL) {
12483 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12484 			    "deferred/dropped during IPPF processing\n"));
12485 			CONN_DEC_REF(connp);
12486 			if (mctl_present)
12487 				freeb(first_mp);
12488 			return (NULL);
12489 		} else if (mctl_present) {
12490 			/*
12491 			 * ip_process might return a new mp.
12492 			 */
12493 			ASSERT(first_mp != mp);
12494 			first_mp->b_cont = mp;
12495 		} else {
12496 			first_mp = mp;
12497 		}
12498 
12499 	}
12500 
12501 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12502 		mp = ip_add_info(mp, recv_ill, flags);
12503 		if (mp == NULL) {
12504 			CONN_DEC_REF(connp);
12505 			if (mctl_present)
12506 				freeb(first_mp);
12507 			return (NULL);
12508 		} else if (mctl_present) {
12509 			/*
12510 			 * ip_add_info might return a new mp.
12511 			 */
12512 			ASSERT(first_mp != mp);
12513 			first_mp->b_cont = mp;
12514 		} else {
12515 			first_mp = mp;
12516 		}
12517 	}
12518 
12519 	if (IPCL_IS_TCP(connp)) {
12520 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12521 		return (first_mp);
12522 	} else {
12523 		putnext(connp->conn_rq, first_mp);
12524 		CONN_DEC_REF(connp);
12525 		return (NULL);
12526 	}
12527 
12528 no_conn:
12529 	/* Initiate IPPf processing, if needed. */
12530 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12531 		uint32_t ill_index;
12532 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12533 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12534 		if (first_mp == NULL) {
12535 			return (NULL);
12536 		}
12537 	}
12538 	BUMP_MIB(&ip_mib, ipInDelivers);
12539 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12540 	return (NULL);
12541 ipoptions:
12542 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12543 		goto slow_done;
12544 	}
12545 
12546 	UPDATE_IB_PKT_COUNT(ire);
12547 	ire->ire_last_used_time = lbolt;
12548 
12549 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12550 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12551 fragmented:
12552 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12553 			if (mctl_present)
12554 				freeb(first_mp);
12555 			goto slow_done;
12556 		}
12557 		/*
12558 		 * Make sure that first_mp points back to mp as
12559 		 * the mp we came in with could have changed in
12560 		 * ip_rput_fragment().
12561 		 */
12562 		ASSERT(!mctl_present);
12563 		ipha = (ipha_t *)mp->b_rptr;
12564 		first_mp = mp;
12565 	}
12566 
12567 	/* Now we have a complete datagram, destined for this machine. */
12568 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12569 
12570 	len = mp->b_wptr - mp->b_rptr;
12571 	/* Pull up a minimal TCP header, if necessary. */
12572 	if (len < (u1 + 20)) {
12573 tcppullup:
12574 		if (!pullupmsg(mp, u1 + 20)) {
12575 			BUMP_MIB(&ip_mib, ipInDiscards);
12576 			goto error;
12577 		}
12578 		ipha = (ipha_t *)mp->b_rptr;
12579 		len = mp->b_wptr - mp->b_rptr;
12580 	}
12581 
12582 	/*
12583 	 * Extract the offset field from the TCP header.  As usual, we
12584 	 * try to help the compiler more than the reader.
12585 	 */
12586 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12587 	if (offset != 5) {
12588 tcpoptions:
12589 		if (offset < 5) {
12590 			BUMP_MIB(&ip_mib, ipInDiscards);
12591 			goto error;
12592 		}
12593 		/*
12594 		 * There must be TCP options.
12595 		 * Make sure we can grab them.
12596 		 */
12597 		offset <<= 2;
12598 		offset += u1;
12599 		if (len < offset) {
12600 			if (!pullupmsg(mp, offset)) {
12601 				BUMP_MIB(&ip_mib, ipInDiscards);
12602 				goto error;
12603 			}
12604 			ipha = (ipha_t *)mp->b_rptr;
12605 			len = mp->b_wptr - rptr;
12606 		}
12607 	}
12608 
12609 	/* Get the total packet length in len, including headers. */
12610 	if (mp->b_cont) {
12611 multipkttcp:
12612 		len = msgdsize(mp);
12613 	}
12614 
12615 	/*
12616 	 * Check the TCP checksum by pulling together the pseudo-
12617 	 * header checksum, and passing it to ip_csum to be added in
12618 	 * with the TCP datagram.
12619 	 *
12620 	 * Since we are not using the hwcksum if available we must
12621 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12622 	 * If either of these fails along the way the mblk is freed.
12623 	 * If this logic ever changes and mblk is reused to say send
12624 	 * ICMP's back, then this flag may need to be cleared in
12625 	 * other places as well.
12626 	 */
12627 	DB_CKSUMFLAGS(mp) = 0;
12628 
12629 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12630 
12631 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12632 #ifdef	_BIG_ENDIAN
12633 	u1 += IPPROTO_TCP;
12634 #else
12635 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12636 #endif
12637 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12638 	/*
12639 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12640 	 */
12641 	IP_STAT(ip_in_sw_cksum);
12642 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12643 		BUMP_MIB(&ip_mib, tcpInErrs);
12644 		goto error;
12645 	}
12646 
12647 	IP_STAT(ip_tcp_slow_path);
12648 	goto try_again;
12649 #undef  iphs
12650 #undef  rptr
12651 
12652 error:
12653 	freemsg(first_mp);
12654 slow_done:
12655 	return (NULL);
12656 }
12657 
12658 /* ARGSUSED */
12659 static void
12660 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12661     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12662 {
12663 	conn_t		*connp;
12664 	uint32_t	sum;
12665 	uint32_t	u1;
12666 	ssize_t		len;
12667 	sctp_hdr_t	*sctph;
12668 	zoneid_t	zoneid = ire->ire_zoneid;
12669 	uint32_t	pktsum;
12670 	uint32_t	calcsum;
12671 	uint32_t	ports;
12672 	uint_t		ipif_seqid;
12673 	in6_addr_t	map_src, map_dst;
12674 	ill_t		*ill = (ill_t *)q->q_ptr;
12675 
12676 #define	rptr	((uchar_t *)ipha)
12677 
12678 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12679 
12680 	/* u1 is # words of IP options */
12681 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12682 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12683 
12684 	/* IP options present */
12685 	if (u1 > 0) {
12686 		goto ipoptions;
12687 	} else {
12688 		/* Check the IP header checksum.  */
12689 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12690 #define	uph	((uint16_t *)ipha)
12691 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12692 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12693 #undef	uph
12694 			/* finish doing IP checksum */
12695 			sum = (sum & 0xFFFF) + (sum >> 16);
12696 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12697 			/*
12698 			 * Don't verify header checksum if this packet
12699 			 * is coming back from AH/ESP as we already did it.
12700 			 */
12701 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12702 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12703 				goto error;
12704 			}
12705 		}
12706 		/*
12707 		 * Since there is no SCTP h/w cksum support yet, just
12708 		 * clear the flag.
12709 		 */
12710 		DB_CKSUMFLAGS(mp) = 0;
12711 	}
12712 
12713 	/*
12714 	 * Don't verify header checksum if this packet is coming
12715 	 * back from AH/ESP as we already did it.
12716 	 */
12717 	if (!mctl_present) {
12718 		UPDATE_IB_PKT_COUNT(ire);
12719 		ire->ire_last_used_time = lbolt;
12720 	}
12721 
12722 	/* packet part of fragmented IP packet? */
12723 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12724 	if (u1 & (IPH_MF | IPH_OFFSET))
12725 		goto fragmented;
12726 
12727 	/* u1 = IP header length (20 bytes) */
12728 	u1 = IP_SIMPLE_HDR_LENGTH;
12729 
12730 find_sctp_client:
12731 	/* Pullup if we don't have the sctp common header. */
12732 	len = MBLKL(mp);
12733 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12734 		if (mp->b_cont == NULL ||
12735 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12736 			BUMP_MIB(&ip_mib, ipInDiscards);
12737 			goto error;
12738 		}
12739 		ipha = (ipha_t *)mp->b_rptr;
12740 		len = MBLKL(mp);
12741 	}
12742 
12743 	sctph = (sctp_hdr_t *)(rptr + u1);
12744 #ifdef	DEBUG
12745 	if (!skip_sctp_cksum) {
12746 #endif
12747 		pktsum = sctph->sh_chksum;
12748 		sctph->sh_chksum = 0;
12749 		calcsum = sctp_cksum(mp, u1);
12750 		if (calcsum != pktsum) {
12751 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12752 			goto error;
12753 		}
12754 		sctph->sh_chksum = pktsum;
12755 #ifdef	DEBUG	/* skip_sctp_cksum */
12756 	}
12757 #endif
12758 	/* get the ports */
12759 	ports = *(uint32_t *)&sctph->sh_sport;
12760 
12761 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12762 	IRE_REFRELE(ire);
12763 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12764 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12765 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
12766 	    mp)) == NULL) {
12767 		/* Check for raw socket or OOTB handling */
12768 		goto no_conn;
12769 	}
12770 
12771 	/* Found a client; up it goes */
12772 	BUMP_MIB(&ip_mib, ipInDelivers);
12773 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12774 	return;
12775 
12776 no_conn:
12777 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12778 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12779 	return;
12780 
12781 ipoptions:
12782 	DB_CKSUMFLAGS(mp) = 0;
12783 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12784 		goto slow_done;
12785 
12786 	UPDATE_IB_PKT_COUNT(ire);
12787 	ire->ire_last_used_time = lbolt;
12788 
12789 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12790 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12791 fragmented:
12792 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12793 			goto slow_done;
12794 		/*
12795 		 * Make sure that first_mp points back to mp as
12796 		 * the mp we came in with could have changed in
12797 		 * ip_rput_fragment().
12798 		 */
12799 		ASSERT(!mctl_present);
12800 		ipha = (ipha_t *)mp->b_rptr;
12801 		first_mp = mp;
12802 	}
12803 
12804 	/* Now we have a complete datagram, destined for this machine. */
12805 	u1 = IPH_HDR_LENGTH(ipha);
12806 	goto find_sctp_client;
12807 #undef  iphs
12808 #undef  rptr
12809 
12810 error:
12811 	freemsg(first_mp);
12812 slow_done:
12813 	IRE_REFRELE(ire);
12814 }
12815 
12816 #define	VER_BITS	0xF0
12817 #define	VERSION_6	0x60
12818 
12819 static boolean_t
12820 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12821     ipaddr_t *dstp)
12822 {
12823 	uint_t	opt_len;
12824 	ipha_t *ipha;
12825 	ssize_t len;
12826 	uint_t	pkt_len;
12827 
12828 	IP_STAT(ip_ipoptions);
12829 	ipha = *iphapp;
12830 
12831 #define	rptr    ((uchar_t *)ipha)
12832 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12833 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12834 		BUMP_MIB(&ip_mib, ipInIPv6);
12835 		freemsg(mp);
12836 		return (B_FALSE);
12837 	}
12838 
12839 	/* multiple mblk or too short */
12840 	pkt_len = ntohs(ipha->ipha_length);
12841 
12842 	/* Get the number of words of IP options in the IP header. */
12843 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12844 	if (opt_len) {
12845 		/* IP Options present!  Validate and process. */
12846 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12847 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12848 			goto done;
12849 		}
12850 		/*
12851 		 * Recompute complete header length and make sure we
12852 		 * have access to all of it.
12853 		 */
12854 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12855 		if (len > (mp->b_wptr - rptr)) {
12856 			if (len > pkt_len) {
12857 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12858 				goto done;
12859 			}
12860 			if (!pullupmsg(mp, len)) {
12861 				BUMP_MIB(&ip_mib, ipInDiscards);
12862 				goto done;
12863 			}
12864 			ipha = (ipha_t *)mp->b_rptr;
12865 		}
12866 		/*
12867 		 * Go off to ip_rput_options which returns the next hop
12868 		 * destination address, which may have been affected
12869 		 * by source routing.
12870 		 */
12871 		IP_STAT(ip_opt);
12872 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12873 			return (B_FALSE);
12874 		}
12875 	}
12876 	*iphapp = ipha;
12877 	return (B_TRUE);
12878 done:
12879 	/* clear b_prev - used by ip_mroute_decap */
12880 	mp->b_prev = NULL;
12881 	freemsg(mp);
12882 	return (B_FALSE);
12883 #undef  rptr
12884 }
12885 
12886 /*
12887  * Deal with the fact that there is no ire for the destination.
12888  * The incoming ill (in_ill) is passed in to ip_newroute only
12889  * in the case of packets coming from mobile ip forward tunnel.
12890  * It must be null otherwise.
12891  */
12892 static void
12893 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12894     ipaddr_t dst)
12895 {
12896 	ipha_t	*ipha;
12897 	ill_t	*ill;
12898 
12899 	ipha = (ipha_t *)mp->b_rptr;
12900 	ill = (ill_t *)q->q_ptr;
12901 
12902 	ASSERT(ill != NULL);
12903 	/*
12904 	 * No IRE for this destination, so it can't be for us.
12905 	 * Unless we are forwarding, drop the packet.
12906 	 * We have to let source routed packets through
12907 	 * since we don't yet know if they are 'ping -l'
12908 	 * packets i.e. if they will go out over the
12909 	 * same interface as they came in on.
12910 	 */
12911 	if (ll_multicast) {
12912 		freemsg(mp);
12913 		return;
12914 	}
12915 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12916 		BUMP_MIB(&ip_mib, ipForwProhibits);
12917 		freemsg(mp);
12918 		return;
12919 	}
12920 
12921 	/* Check for Martian addresses */
12922 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12923 		freemsg(mp);
12924 		return;
12925 	}
12926 
12927 	/* Mark this packet as having originated externally */
12928 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12929 
12930 	/*
12931 	 * Clear the indication that this may have a hardware checksum
12932 	 * as we are not using it
12933 	 */
12934 	DB_CKSUMFLAGS(mp) = 0;
12935 
12936 	/*
12937 	 * Now hand the packet to ip_newroute.
12938 	 */
12939 	ip_newroute(q, mp, dst, in_ill, NULL);
12940 }
12941 
12942 /*
12943  * check ip header length and align it.
12944  */
12945 static boolean_t
12946 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12947 {
12948 	ssize_t len;
12949 	ill_t *ill;
12950 	ipha_t	*ipha;
12951 
12952 	len = MBLKL(mp);
12953 
12954 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12955 		if (!OK_32PTR(mp->b_rptr))
12956 			IP_STAT(ip_notaligned1);
12957 		else
12958 			IP_STAT(ip_notaligned2);
12959 		/* Guard against bogus device drivers */
12960 		if (len < 0) {
12961 			/* clear b_prev - used by ip_mroute_decap */
12962 			mp->b_prev = NULL;
12963 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12964 			freemsg(mp);
12965 			return (B_FALSE);
12966 		}
12967 
12968 		if (ip_rput_pullups++ == 0) {
12969 			ill = (ill_t *)q->q_ptr;
12970 			ipha = (ipha_t *)mp->b_rptr;
12971 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12972 			    "ip_check_and_align_header: %s forced us to "
12973 			    " pullup pkt, hdr len %ld, hdr addr %p",
12974 			    ill->ill_name, len, ipha);
12975 		}
12976 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12977 			/* clear b_prev - used by ip_mroute_decap */
12978 			mp->b_prev = NULL;
12979 			BUMP_MIB(&ip_mib, ipInDiscards);
12980 			freemsg(mp);
12981 			return (B_FALSE);
12982 		}
12983 	}
12984 	return (B_TRUE);
12985 }
12986 
12987 static boolean_t
12988 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12989 {
12990 	ill_group_t	*ill_group;
12991 	ill_group_t	*ire_group;
12992 	queue_t 	*q;
12993 	ill_t		*ire_ill;
12994 	uint_t		ill_ifindex;
12995 
12996 	q = *qp;
12997 	/*
12998 	 * We need to check to make sure the packet came in
12999 	 * on the queue associated with the destination IRE.
13000 	 * Note that for multicast packets and broadcast packets sent to
13001 	 * a broadcast address which is shared between multiple interfaces
13002 	 * we should not do this since we just got a random broadcast ire.
13003 	 */
13004 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13005 		boolean_t check_multi = B_TRUE;
13006 
13007 		/*
13008 		 * This packet came in on an interface other than the
13009 		 * one associated with the destination address.
13010 		 * "Gateway" it to the appropriate interface here.
13011 		 * As long as the ills belong to the same group,
13012 		 * we don't consider them to arriving on the wrong
13013 		 * interface. Thus, when the switch is doing inbound
13014 		 * load spreading, we won't drop packets when we
13015 		 * are doing strict multihoming checks. Note, the
13016 		 * same holds true for 'usesrc groups' where the
13017 		 * destination address may belong to another interface
13018 		 * to allow multipathing to happen
13019 		 */
13020 		ill_group = ill->ill_group;
13021 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13022 		ill_ifindex = ill->ill_usesrc_ifindex;
13023 		ire_group = ire_ill->ill_group;
13024 
13025 		/*
13026 		 * If it's part of the same IPMP group, or if it's a legal
13027 		 * address on the 'usesrc' interface, then bypass strict
13028 		 * checks.
13029 		 */
13030 		if (ill_group != NULL && ill_group == ire_group) {
13031 			check_multi = B_FALSE;
13032 		} else if (ill_ifindex != 0 &&
13033 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13034 			check_multi = B_FALSE;
13035 		}
13036 
13037 		if (check_multi &&
13038 		    ip_strict_dst_multihoming &&
13039 		    ((ill->ill_flags &
13040 		    ire->ire_ipif->ipif_ill->ill_flags &
13041 		    ILLF_ROUTER) == 0)) {
13042 			/* Drop packet */
13043 			BUMP_MIB(&ip_mib, ipForwProhibits);
13044 			freemsg(mp);
13045 			ire_refrele(ire);
13046 			return (B_TRUE);
13047 		}
13048 
13049 		/*
13050 		 * Change the queue (for non-virtual destination network
13051 		 * interfaces) and ip_rput_local will be called with the right
13052 		 * queue
13053 		 */
13054 		q = ire->ire_rfq;
13055 	}
13056 	/* Must be broadcast.  We'll take it. */
13057 	*qp = q;
13058 	return (B_FALSE);
13059 }
13060 
13061 static void
13062 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13063     ill_t *ill, int ll_multicast)
13064 {
13065 	ill_group_t	*ill_group;
13066 	ill_group_t	*ire_group;
13067 	queue_t	*dev_q;
13068 
13069 	ASSERT(ire->ire_stq != NULL);
13070 	if (ll_multicast != 0)
13071 		goto drop_pkt;
13072 
13073 	if (ip_no_forward(ipha, ill))
13074 		goto drop_pkt;
13075 
13076 	ill_group = ill->ill_group;
13077 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13078 	/*
13079 	 * Check if we want to forward this one at this time.
13080 	 * We allow source routed packets on a host provided that
13081 	 * they go out the same interface or same interface group
13082 	 * as they came in on.
13083 	 *
13084 	 * XXX To be quicker, we may wish to not chase pointers to
13085 	 * get the ILLF_ROUTER flag and instead store the
13086 	 * forwarding policy in the ire.  An unfortunate
13087 	 * side-effect of that would be requiring an ire flush
13088 	 * whenever the ILLF_ROUTER flag changes.
13089 	 */
13090 	if (((ill->ill_flags &
13091 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13092 	    ILLF_ROUTER) == 0) &&
13093 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13094 	    (ill_group != NULL && ill_group == ire_group)))) {
13095 		BUMP_MIB(&ip_mib, ipForwProhibits);
13096 		if (ip_source_routed(ipha)) {
13097 			q = WR(q);
13098 			/*
13099 			 * Clear the indication that this may have
13100 			 * hardware checksum as we are not using it.
13101 			 */
13102 			DB_CKSUMFLAGS(mp) = 0;
13103 			icmp_unreachable(q, mp,
13104 			    ICMP_SOURCE_ROUTE_FAILED);
13105 			ire_refrele(ire);
13106 			return;
13107 		}
13108 		goto drop_pkt;
13109 	}
13110 
13111 	/* Packet is being forwarded. Turning off hwcksum flag. */
13112 	DB_CKSUMFLAGS(mp) = 0;
13113 	if (ip_g_send_redirects) {
13114 		/*
13115 		 * Check whether the incoming interface and outgoing
13116 		 * interface is part of the same group. If so,
13117 		 * send redirects.
13118 		 *
13119 		 * Check the source address to see if it originated
13120 		 * on the same logical subnet it is going back out on.
13121 		 * If so, we should be able to send it a redirect.
13122 		 * Avoid sending a redirect if the destination
13123 		 * is directly connected (gw_addr == 0),
13124 		 * or if the packet was source routed out this
13125 		 * interface.
13126 		 */
13127 		ipaddr_t src;
13128 		mblk_t	*mp1;
13129 		ire_t	*src_ire = NULL;
13130 
13131 		/*
13132 		 * Check whether ire_rfq and q are from the same ill
13133 		 * or if they are not same, they at least belong
13134 		 * to the same group. If so, send redirects.
13135 		 */
13136 		if ((ire->ire_rfq == q ||
13137 		    (ill_group != NULL && ill_group == ire_group)) &&
13138 		    (ire->ire_gateway_addr != 0) &&
13139 		    !ip_source_routed(ipha)) {
13140 
13141 			src = ipha->ipha_src;
13142 			src_ire = ire_ftable_lookup(src, 0, 0,
13143 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13144 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13145 
13146 			if (src_ire != NULL) {
13147 				/*
13148 				 * The source is directly connected.
13149 				 * Just copy the ip header (which is
13150 				 * in the first mblk)
13151 				 */
13152 				mp1 = copyb(mp);
13153 				if (mp1 != NULL) {
13154 					icmp_send_redirect(WR(q), mp1,
13155 					    ire->ire_gateway_addr);
13156 				}
13157 				ire_refrele(src_ire);
13158 			}
13159 		}
13160 	}
13161 
13162 	dev_q = ire->ire_stq->q_next;
13163 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13164 		BUMP_MIB(&ip_mib, ipInDiscards);
13165 		freemsg(mp);
13166 		ire_refrele(ire);
13167 		return;
13168 	}
13169 
13170 	ip_rput_forward(ire, ipha, mp, ill);
13171 	IRE_REFRELE(ire);
13172 	return;
13173 
13174 drop_pkt:
13175 	ire_refrele(ire);
13176 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13177 	freemsg(mp);
13178 }
13179 
13180 static boolean_t
13181 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
13182     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13183 {
13184 	queue_t		*q;
13185 	ire_t		*ire;
13186 	uint16_t	hcksumflags;
13187 
13188 	q = *qp;
13189 	ire = *irep;
13190 
13191 	/*
13192 	 * Clear the indication that this may have hardware
13193 	 * checksum as we are not using it for forwarding.
13194 	 */
13195 	hcksumflags = DB_CKSUMFLAGS(mp);
13196 	DB_CKSUMFLAGS(mp) = 0;
13197 
13198 	/*
13199 	 * Directed broadcast forwarding: if the packet came in over a
13200 	 * different interface then it is routed out over we can forward it.
13201 	 */
13202 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13203 		ire_refrele(ire);
13204 		freemsg(mp);
13205 		BUMP_MIB(&ip_mib, ipInDiscards);
13206 		return (B_TRUE);
13207 	}
13208 	/*
13209 	 * For multicast we have set dst to be INADDR_BROADCAST
13210 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13211 	 * only for broadcast packets.
13212 	 */
13213 	if (!CLASSD(ipha->ipha_dst)) {
13214 		ire_t *new_ire;
13215 		ipif_t *ipif;
13216 		/*
13217 		 * For ill groups, as the switch duplicates broadcasts
13218 		 * across all the ports, we need to filter out and
13219 		 * send up only one copy. There is one copy for every
13220 		 * broadcast address on each ill. Thus, we look for a
13221 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13222 		 * later to see whether this ill is eligible to receive
13223 		 * them or not. ill_nominate_bcast_rcv() nominates only
13224 		 * one set of IREs for receiving.
13225 		 */
13226 
13227 		ipif = ipif_get_next_ipif(NULL, ill);
13228 		if (ipif == NULL) {
13229 			ire_refrele(ire);
13230 			freemsg(mp);
13231 			BUMP_MIB(&ip_mib, ipInDiscards);
13232 			return (B_TRUE);
13233 		}
13234 		new_ire = ire_ctable_lookup(dst, 0, 0,
13235 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13236 		ipif_refrele(ipif);
13237 
13238 		if (new_ire != NULL) {
13239 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13240 				ire_refrele(ire);
13241 				ire_refrele(new_ire);
13242 				freemsg(mp);
13243 				BUMP_MIB(&ip_mib, ipInDiscards);
13244 				return (B_TRUE);
13245 			}
13246 			/*
13247 			 * In the special case of multirouted broadcast
13248 			 * packets, we unconditionally need to "gateway"
13249 			 * them to the appropriate interface here.
13250 			 * In the normal case, this cannot happen, because
13251 			 * there is no broadcast IRE tagged with the
13252 			 * RTF_MULTIRT flag.
13253 			 */
13254 			if (new_ire->ire_flags & RTF_MULTIRT) {
13255 				ire_refrele(new_ire);
13256 				if (ire->ire_rfq != NULL) {
13257 					q = ire->ire_rfq;
13258 					*qp = q;
13259 				}
13260 			} else {
13261 				ire_refrele(ire);
13262 				ire = new_ire;
13263 			}
13264 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13265 			if (!ip_g_forward_directed_bcast) {
13266 				/*
13267 				 * Free the message if
13268 				 * ip_g_forward_directed_bcast is turned
13269 				 * off for non-local broadcast.
13270 				 */
13271 				ire_refrele(ire);
13272 				freemsg(mp);
13273 				BUMP_MIB(&ip_mib, ipInDiscards);
13274 				return (B_TRUE);
13275 			}
13276 		} else {
13277 			/*
13278 			 * This CGTP packet successfully passed the
13279 			 * CGTP filter, but the related CGTP
13280 			 * broadcast IRE has not been found,
13281 			 * meaning that the redundant ipif is
13282 			 * probably down. However, if we discarded
13283 			 * this packet, its duplicate would be
13284 			 * filtered out by the CGTP filter so none
13285 			 * of them would get through. So we keep
13286 			 * going with this one.
13287 			 */
13288 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13289 			if (ire->ire_rfq != NULL) {
13290 				q = ire->ire_rfq;
13291 				*qp = q;
13292 			}
13293 		}
13294 	}
13295 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13296 		/*
13297 		 * Verify that there are not more then one
13298 		 * IRE_BROADCAST with this broadcast address which
13299 		 * has ire_stq set.
13300 		 * TODO: simplify, loop over all IRE's
13301 		 */
13302 		ire_t	*ire1;
13303 		int	num_stq = 0;
13304 		mblk_t	*mp1;
13305 
13306 		/* Find the first one with ire_stq set */
13307 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13308 		for (ire1 = ire; ire1 &&
13309 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13310 		    ire1 = ire1->ire_next)
13311 			;
13312 		if (ire1) {
13313 			ire_refrele(ire);
13314 			ire = ire1;
13315 			IRE_REFHOLD(ire);
13316 		}
13317 
13318 		/* Check if there are additional ones with stq set */
13319 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13320 			if (ire->ire_addr != ire1->ire_addr)
13321 				break;
13322 			if (ire1->ire_stq) {
13323 				num_stq++;
13324 				break;
13325 			}
13326 		}
13327 		rw_exit(&ire->ire_bucket->irb_lock);
13328 		if (num_stq == 1 && ire->ire_stq != NULL) {
13329 			ip1dbg(("ip_rput_process_broadcast: directed "
13330 			    "broadcast to 0x%x\n",
13331 			    ntohl(ire->ire_addr)));
13332 			mp1 = copymsg(mp);
13333 			if (mp1) {
13334 				switch (ipha->ipha_protocol) {
13335 				case IPPROTO_UDP:
13336 					ip_udp_input(q, mp1, ipha, ire, ill);
13337 					break;
13338 				default:
13339 					ip_proto_input(q, mp1, ipha, ire, ill);
13340 					break;
13341 				}
13342 			}
13343 			/*
13344 			 * Adjust ttl to 2 (1+1 - the forward engine
13345 			 * will decrement it by one.
13346 			 */
13347 			if (ip_csum_hdr(ipha)) {
13348 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13349 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13350 				freemsg(mp);
13351 				ire_refrele(ire);
13352 				return (B_TRUE);
13353 			}
13354 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13355 			ipha->ipha_hdr_checksum = 0;
13356 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13357 			ip_rput_process_forward(q, mp, ire, ipha,
13358 			    ill, ll_multicast);
13359 			return (B_TRUE);
13360 		}
13361 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13362 		    ntohl(ire->ire_addr)));
13363 	}
13364 
13365 	*irep = ire;
13366 
13367 	/* Restore any hardware checksum flags */
13368 	DB_CKSUMFLAGS(mp) = hcksumflags;
13369 	return (B_FALSE);
13370 }
13371 
13372 /* ARGSUSED */
13373 static boolean_t
13374 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13375     int *ll_multicast, ipaddr_t *dstp)
13376 {
13377 	/*
13378 	 * Forward packets only if we have joined the allmulti
13379 	 * group on this interface.
13380 	 */
13381 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13382 		int retval;
13383 
13384 		/*
13385 		 * Clear the indication that this may have hardware
13386 		 * checksum as we are not using it.
13387 		 */
13388 		DB_CKSUMFLAGS(mp) = 0;
13389 		retval = ip_mforward(ill, ipha, mp);
13390 		/* ip_mforward updates mib variables if needed */
13391 		/* clear b_prev - used by ip_mroute_decap */
13392 		mp->b_prev = NULL;
13393 
13394 		switch (retval) {
13395 		case 0:
13396 			/*
13397 			 * pkt is okay and arrived on phyint.
13398 			 *
13399 			 * If we are running as a multicast router
13400 			 * we need to see all IGMP and/or PIM packets.
13401 			 */
13402 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13403 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13404 				goto done;
13405 			}
13406 			break;
13407 		case -1:
13408 			/* pkt is mal-formed, toss it */
13409 			goto drop_pkt;
13410 		case 1:
13411 			/* pkt is okay and arrived on a tunnel */
13412 			/*
13413 			 * If we are running a multicast router
13414 			 *  we need to see all igmp packets.
13415 			 */
13416 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13417 				*dstp = INADDR_BROADCAST;
13418 				*ll_multicast = 1;
13419 				return (B_FALSE);
13420 			}
13421 
13422 			goto drop_pkt;
13423 		}
13424 	}
13425 
13426 	ILM_WALKER_HOLD(ill);
13427 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
13428 		/*
13429 		 * This might just be caused by the fact that
13430 		 * multiple IP Multicast addresses map to the same
13431 		 * link layer multicast - no need to increment counter!
13432 		 */
13433 		ILM_WALKER_RELE(ill);
13434 		freemsg(mp);
13435 		return (B_TRUE);
13436 	}
13437 	ILM_WALKER_RELE(ill);
13438 done:
13439 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
13440 	/*
13441 	 * This assumes the we deliver to all streams for multicast
13442 	 * and broadcast packets.
13443 	 */
13444 	*dstp = INADDR_BROADCAST;
13445 	*ll_multicast = 1;
13446 	return (B_FALSE);
13447 drop_pkt:
13448 	ip2dbg(("ip_rput: drop pkt\n"));
13449 	freemsg(mp);
13450 	return (B_TRUE);
13451 }
13452 
13453 static boolean_t
13454 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
13455     int *ll_multicast, mblk_t **mpp)
13456 {
13457 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
13458 	boolean_t must_copy = B_FALSE;
13459 	struct iocblk   *iocp;
13460 	ipha_t		*ipha;
13461 
13462 #define	rptr    ((uchar_t *)ipha)
13463 
13464 	first_mp = *first_mpp;
13465 	mp = *mpp;
13466 
13467 	ASSERT(first_mp == mp);
13468 
13469 	/*
13470 	 * if db_ref > 1 then copymsg and free original. Packet may be
13471 	 * changed and do not want other entity who has a reference to this
13472 	 * message to trip over the changes. This is a blind change because
13473 	 * trying to catch all places that might change packet is too
13474 	 * difficult (since it may be a module above this one)
13475 	 *
13476 	 * This corresponds to the non-fast path case. We walk down the full
13477 	 * chain in this case, and check the db_ref count of all the dblks,
13478 	 * and do a copymsg if required. It is possible that the db_ref counts
13479 	 * of the data blocks in the mblk chain can be different.
13480 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
13481 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
13482 	 * 'snoop' is running.
13483 	 */
13484 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
13485 		if (mp1->b_datap->db_ref > 1) {
13486 			must_copy = B_TRUE;
13487 			break;
13488 		}
13489 	}
13490 
13491 	if (must_copy) {
13492 		mp1 = copymsg(mp);
13493 		if (mp1 == NULL) {
13494 			for (mp1 = mp; mp1 != NULL;
13495 			    mp1 = mp1->b_cont) {
13496 				mp1->b_next = NULL;
13497 				mp1->b_prev = NULL;
13498 			}
13499 			freemsg(mp);
13500 			BUMP_MIB(&ip_mib, ipInDiscards);
13501 			return (B_TRUE);
13502 		}
13503 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
13504 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
13505 			/* Copy b_next - used in M_BREAK messages */
13506 			to_mp->b_next = from_mp->b_next;
13507 			from_mp->b_next = NULL;
13508 			/* Copy b_prev - used by ip_mroute_decap */
13509 			to_mp->b_prev = from_mp->b_prev;
13510 			from_mp->b_prev = NULL;
13511 		}
13512 		*first_mpp = first_mp = mp1;
13513 		freemsg(mp);
13514 		mp = mp1;
13515 		*mpp = mp1;
13516 	}
13517 
13518 	ipha = (ipha_t *)mp->b_rptr;
13519 
13520 	/*
13521 	 * previous code has a case for M_DATA.
13522 	 * We want to check how that happens.
13523 	 */
13524 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13525 	switch (first_mp->b_datap->db_type) {
13526 	case M_PROTO:
13527 	case M_PCPROTO:
13528 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13529 		    DL_UNITDATA_IND) {
13530 			/* Go handle anything other than data elsewhere. */
13531 			ip_rput_dlpi(q, mp);
13532 			return (B_TRUE);
13533 		}
13534 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13535 		/* Ditch the DLPI header. */
13536 		mp1 = mp->b_cont;
13537 		ASSERT(first_mp == mp);
13538 		*first_mpp = mp1;
13539 		freeb(mp);
13540 		*mpp = mp1;
13541 		return (B_FALSE);
13542 	case M_BREAK:
13543 		/*
13544 		 * A packet arrives as M_BREAK following a cycle through
13545 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13546 		 * This is an IP datagram sans lower level header.
13547 		 * M_BREAK are also used to pass back in multicast packets
13548 		 * that are encapsulated with a source route.
13549 		 */
13550 		/* Ditch the M_BREAK mblk */
13551 		mp1 = mp->b_cont;
13552 		ASSERT(first_mp == mp);
13553 		*first_mpp = mp1;
13554 		freeb(mp);
13555 		mp = mp1;
13556 		mp->b_next = NULL;
13557 		*mpp = mp;
13558 		*ll_multicast = 0;
13559 		return (B_FALSE);
13560 	case M_IOCACK:
13561 		ip1dbg(("got iocack "));
13562 		iocp = (struct iocblk *)mp->b_rptr;
13563 		switch (iocp->ioc_cmd) {
13564 		case DL_IOC_HDR_INFO:
13565 			ill = (ill_t *)q->q_ptr;
13566 			ill_fastpath_ack(ill, mp);
13567 			return (B_TRUE);
13568 		case SIOCSTUNPARAM:
13569 		case OSIOCSTUNPARAM:
13570 			/* Go through qwriter_ip */
13571 			break;
13572 		case SIOCGTUNPARAM:
13573 		case OSIOCGTUNPARAM:
13574 			ip_rput_other(NULL, q, mp, NULL);
13575 			return (B_TRUE);
13576 		default:
13577 			putnext(q, mp);
13578 			return (B_TRUE);
13579 		}
13580 		/* FALLTHRU */
13581 	case M_ERROR:
13582 	case M_HANGUP:
13583 		/*
13584 		 * Since this is on the ill stream we unconditionally
13585 		 * bump up the refcount
13586 		 */
13587 		ill_refhold(ill);
13588 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13589 		    B_FALSE);
13590 		return (B_TRUE);
13591 	case M_CTL:
13592 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13593 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13594 			IPHADA_M_CTL)) {
13595 			/*
13596 			 * It's an IPsec accelerated packet.
13597 			 * Make sure that the ill from which we received the
13598 			 * packet has enabled IPsec hardware acceleration.
13599 			 */
13600 			if (!(ill->ill_capabilities &
13601 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13602 				/* IPsec kstats: bean counter */
13603 				freemsg(mp);
13604 				return (B_TRUE);
13605 			}
13606 
13607 			/*
13608 			 * Make mp point to the mblk following the M_CTL,
13609 			 * then process according to type of mp.
13610 			 * After this processing, first_mp will point to
13611 			 * the data-attributes and mp to the pkt following
13612 			 * the M_CTL.
13613 			 */
13614 			mp = first_mp->b_cont;
13615 			if (mp == NULL) {
13616 				freemsg(first_mp);
13617 				return (B_TRUE);
13618 			}
13619 			/*
13620 			 * A Hardware Accelerated packet can only be M_DATA
13621 			 * ESP or AH packet.
13622 			 */
13623 			if (mp->b_datap->db_type != M_DATA) {
13624 				/* non-M_DATA IPsec accelerated packet */
13625 				IPSECHW_DEBUG(IPSECHW_PKT,
13626 				    ("non-M_DATA IPsec accelerated pkt\n"));
13627 				freemsg(first_mp);
13628 				return (B_TRUE);
13629 			}
13630 			ipha = (ipha_t *)mp->b_rptr;
13631 			if (ipha->ipha_protocol != IPPROTO_AH &&
13632 			    ipha->ipha_protocol != IPPROTO_ESP) {
13633 				IPSECHW_DEBUG(IPSECHW_PKT,
13634 				    ("non-M_DATA IPsec accelerated pkt\n"));
13635 				freemsg(first_mp);
13636 				return (B_TRUE);
13637 			}
13638 			*mpp = mp;
13639 			return (B_FALSE);
13640 		}
13641 		putnext(q, mp);
13642 		return (B_TRUE);
13643 	case M_FLUSH:
13644 		if (*mp->b_rptr & FLUSHW) {
13645 			*mp->b_rptr &= ~FLUSHR;
13646 			qreply(q, mp);
13647 			return (B_TRUE);
13648 		}
13649 		freemsg(mp);
13650 		return (B_TRUE);
13651 	case M_IOCNAK:
13652 		ip1dbg(("got iocnak "));
13653 		iocp = (struct iocblk *)mp->b_rptr;
13654 		switch (iocp->ioc_cmd) {
13655 		case DL_IOC_HDR_INFO:
13656 		case SIOCSTUNPARAM:
13657 		case OSIOCSTUNPARAM:
13658 			/*
13659 			 * Since this is on the ill stream we unconditionally
13660 			 * bump up the refcount
13661 			 */
13662 			ill_refhold(ill);
13663 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13664 			    CUR_OP, B_FALSE);
13665 			return (B_TRUE);
13666 		case SIOCGTUNPARAM:
13667 		case OSIOCGTUNPARAM:
13668 			ip_rput_other(NULL, q, mp, NULL);
13669 			return (B_TRUE);
13670 		default:
13671 			break;
13672 		}
13673 		/* FALLTHRU */
13674 	default:
13675 		putnext(q, mp);
13676 		return (B_TRUE);
13677 	}
13678 }
13679 
13680 /* Read side put procedure.  Packets coming from the wire arrive here. */
13681 void
13682 ip_rput(queue_t *q, mblk_t *mp)
13683 {
13684 	ill_t		*ill;
13685 
13686 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13687 
13688 	ill = (ill_t *)q->q_ptr;
13689 
13690 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13691 		union DL_primitives *dl;
13692 
13693 		/*
13694 		 * Things are opening or closing. Only accept DLPI control
13695 		 * messages. In the open case, the ill->ill_ipif has not yet
13696 		 * been created. In the close case, things hanging off the
13697 		 * ill could have been freed already. In either case it
13698 		 * may not be safe to proceed further.
13699 		 */
13700 
13701 		dl = (union DL_primitives *)mp->b_rptr;
13702 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13703 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13704 			/*
13705 			 * Also SIOC[GS]TUN* ioctls can come here.
13706 			 */
13707 			inet_freemsg(mp);
13708 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13709 			    "ip_input_end: q %p (%S)", q, "uninit");
13710 			return;
13711 		}
13712 	}
13713 
13714 	/*
13715 	 * if db_ref > 1 then copymsg and free original. Packet may be
13716 	 * changed and we do not want the other entity who has a reference to
13717 	 * this message to trip over the changes. This is a blind change because
13718 	 * trying to catch all places that might change the packet is too
13719 	 * difficult.
13720 	 *
13721 	 * This corresponds to the fast path case, where we have a chain of
13722 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13723 	 * in the mblk chain. There doesn't seem to be a reason why a device
13724 	 * driver would send up data with varying db_ref counts in the mblk
13725 	 * chain. In any case the Fast path is a private interface, and our
13726 	 * drivers don't do such a thing. Given the above assumption, there is
13727 	 * no need to walk down the entire mblk chain (which could have a
13728 	 * potential performance problem)
13729 	 */
13730 	if (mp->b_datap->db_ref > 1) {
13731 		mblk_t  *mp1;
13732 		boolean_t adjusted = B_FALSE;
13733 		IP_STAT(ip_db_ref);
13734 
13735 		/*
13736 		 * The IP_RECVSLLA option depends on having the link layer
13737 		 * header. First check that:
13738 		 * a> the underlying device is of type ether, since this
13739 		 * option is currently supported only over ethernet.
13740 		 * b> there is enough room to copy over the link layer header.
13741 		 *
13742 		 * Once the checks are done, adjust rptr so that the link layer
13743 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13744 		 * be returned by some non-ethernet drivers but in this case the
13745 		 * second check will fail.
13746 		 */
13747 		if (ill->ill_type == IFT_ETHER &&
13748 		    (mp->b_rptr - mp->b_datap->db_base) >=
13749 		    sizeof (struct ether_header)) {
13750 			mp->b_rptr -= sizeof (struct ether_header);
13751 			adjusted = B_TRUE;
13752 		}
13753 		mp1 = copymsg(mp);
13754 		if (mp1 == NULL) {
13755 			/* Clear b_next - used in M_BREAK messages */
13756 			mp->b_next = NULL;
13757 			/* clear b_prev - used by ip_mroute_decap */
13758 			mp->b_prev = NULL;
13759 			freemsg(mp);
13760 			BUMP_MIB(&ip_mib, ipInDiscards);
13761 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13762 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13763 			return;
13764 		}
13765 		if (adjusted) {
13766 			/*
13767 			 * Copy is done. Restore the pointer in the _new_ mblk
13768 			 */
13769 			mp1->b_rptr += sizeof (struct ether_header);
13770 		}
13771 		/* Copy b_next - used in M_BREAK messages */
13772 		mp1->b_next = mp->b_next;
13773 		mp->b_next = NULL;
13774 		/* Copy b_prev - used by ip_mroute_decap */
13775 		mp1->b_prev = mp->b_prev;
13776 		mp->b_prev = NULL;
13777 		freemsg(mp);
13778 		mp = mp1;
13779 	}
13780 
13781 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13782 	    "ip_rput_end: q %p (%S)", q, "end");
13783 
13784 	ip_input(ill, NULL, mp, 0);
13785 }
13786 
13787 /*
13788  * Direct read side procedure capable of dealing with chains. GLDv3 based
13789  * drivers call this function directly with mblk chains while STREAMS
13790  * read side procedure ip_rput() calls this for single packet with ip_ring
13791  * set to NULL to process one packet at a time.
13792  *
13793  * The ill will always be valid if this function is called directly from
13794  * the driver.
13795  */
13796 /*ARGSUSED*/
13797 void
13798 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13799 {
13800 	ipaddr_t		dst;
13801 	ire_t			*ire;
13802 	ipha_t			*ipha;
13803 	uint_t			pkt_len;
13804 	ssize_t			len;
13805 	uint_t			opt_len;
13806 	int			ll_multicast;
13807 	int			cgtp_flt_pkt;
13808 	queue_t			*q = ill->ill_rq;
13809 	squeue_t		*curr_sqp = NULL;
13810 	mblk_t 			*head = NULL;
13811 	mblk_t			*tail = NULL;
13812 	mblk_t			*first_mp;
13813 	mblk_t 			*mp;
13814 	int			cnt = 0;
13815 
13816 	ASSERT(mp_chain != NULL);
13817 	ASSERT(ill != NULL);
13818 
13819 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13820 
13821 #define	rptr	((uchar_t *)ipha)
13822 
13823 	while (mp_chain != NULL) {
13824 		first_mp = mp = mp_chain;
13825 		mp_chain = mp_chain->b_next;
13826 		mp->b_next = NULL;
13827 		ll_multicast = 0;
13828 		ire = NULL;
13829 
13830 		/*
13831 		 * ip_input fast path
13832 		 */
13833 
13834 		/* mblk type is not M_DATA */
13835 		if (mp->b_datap->db_type != M_DATA) {
13836 			if (ip_rput_process_notdata(q, &first_mp, ill,
13837 			    &ll_multicast, &mp))
13838 				continue;
13839 		}
13840 
13841 		ASSERT(mp->b_datap->db_type == M_DATA);
13842 		ASSERT(mp->b_datap->db_ref == 1);
13843 
13844 
13845 		ipha = (ipha_t *)mp->b_rptr;
13846 		len = mp->b_wptr - rptr;
13847 
13848 		BUMP_MIB(&ip_mib, ipInReceives);
13849 
13850 		/*
13851 		 * IP header ptr not aligned?
13852 		 * OR IP header not complete in first mblk
13853 		 */
13854 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13855 			if (!ip_check_and_align_header(q, mp))
13856 				continue;
13857 			ipha = (ipha_t *)mp->b_rptr;
13858 			len = mp->b_wptr - rptr;
13859 		}
13860 
13861 		/* multiple mblk or too short */
13862 		pkt_len = ntohs(ipha->ipha_length);
13863 		len -= pkt_len;
13864 		if (len != 0) {
13865 			/*
13866 			 * Make sure we have data length consistent
13867 			 * with the IP header.
13868 			 */
13869 			if (mp->b_cont == NULL) {
13870 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13871 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13872 					ip2dbg(("ip_input: drop pkt\n"));
13873 					freemsg(mp);
13874 					continue;
13875 				}
13876 				mp->b_wptr = rptr + pkt_len;
13877 			} else if (len += msgdsize(mp->b_cont)) {
13878 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13879 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13880 					ip2dbg(("ip_input: drop pkt\n"));
13881 					freemsg(mp);
13882 					continue;
13883 				}
13884 				(void) adjmsg(mp, -len);
13885 				IP_STAT(ip_multimblk3);
13886 			}
13887 		}
13888 
13889 		if (ip_loopback_src_or_dst(ipha, ill)) {
13890 			ip2dbg(("ip_input: drop pkt\n"));
13891 			freemsg(mp);
13892 			continue;
13893 		}
13894 
13895 		/*
13896 		 * Attach any necessary label information to this packet.
13897 		 */
13898 		if (is_system_labeled() &&
13899 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
13900 			BUMP_MIB(&ip_mib, ipInDiscards);
13901 			freemsg(mp);
13902 			continue;
13903 		}
13904 
13905 		opt_len = ipha->ipha_version_and_hdr_length -
13906 		    IP_SIMPLE_HDR_VERSION;
13907 		/* IP version bad or there are IP options */
13908 		if (opt_len) {
13909 			if (len != 0)
13910 				IP_STAT(ip_multimblk4);
13911 			else
13912 				IP_STAT(ip_ipoptions);
13913 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13914 				continue;
13915 		} else {
13916 			dst = ipha->ipha_dst;
13917 		}
13918 
13919 		/*
13920 		 * Invoke the CGTP (multirouting) filtering module to process
13921 		 * the incoming packet. Packets identified as duplicates
13922 		 * must be discarded. Filtering is active only if the
13923 		 * the ip_cgtp_filter ndd variable is non-zero.
13924 		 */
13925 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13926 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13927 			cgtp_flt_pkt =
13928 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
13929 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13930 				freemsg(first_mp);
13931 				continue;
13932 			}
13933 		}
13934 
13935 		/*
13936 		 * If rsvpd is running, let RSVP daemon handle its processing
13937 		 * and forwarding of RSVP multicast/unicast packets.
13938 		 * If rsvpd is not running but mrouted is running, RSVP
13939 		 * multicast packets are forwarded as multicast traffic
13940 		 * and RSVP unicast packets are forwarded by unicast router.
13941 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13942 		 * packets are not forwarded, but the unicast packets are
13943 		 * forwarded like unicast traffic.
13944 		 */
13945 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13946 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13947 			/* RSVP packet and rsvpd running. Treat as ours */
13948 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13949 			/*
13950 			 * This assumes that we deliver to all streams for
13951 			 * multicast and broadcast packets.
13952 			 * We have to force ll_multicast to 1 to handle the
13953 			 * M_DATA messages passed in from ip_mroute_decap.
13954 			 */
13955 			dst = INADDR_BROADCAST;
13956 			ll_multicast = 1;
13957 		} else if (CLASSD(dst)) {
13958 			/* packet is multicast */
13959 			mp->b_next = NULL;
13960 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13961 			    &ll_multicast, &dst))
13962 				continue;
13963 		}
13964 
13965 
13966 		/*
13967 		 * Check if the packet is coming from the Mobile IP
13968 		 * forward tunnel interface
13969 		 */
13970 		if (ill->ill_srcif_refcnt > 0) {
13971 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13972 			    NULL, ill, MATCH_IRE_TYPE);
13973 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13974 			    ire->ire_ipif->ipif_net_type ==
13975 			    IRE_IF_RESOLVER) {
13976 				/* We need to resolve the link layer info */
13977 				ire_refrele(ire);
13978 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13979 				    ll_multicast, dst);
13980 				continue;
13981 			}
13982 		}
13983 
13984 		if (ire == NULL) {
13985 			ire = ire_cache_lookup(dst, ALL_ZONES,
13986 			    MBLK_GETLABEL(mp));
13987 		}
13988 
13989 		/*
13990 		 * If mipagent is running and reverse tunnel is created as per
13991 		 * mobile node request, then any packet coming through the
13992 		 * incoming interface from the mobile-node, should be reverse
13993 		 * tunneled to it's home agent except those that are destined
13994 		 * to foreign agent only.
13995 		 * This needs source address based ire lookup. The routing
13996 		 * entries for source address based lookup are only created by
13997 		 * mipagent program only when a reverse tunnel is created.
13998 		 * Reference : RFC2002, RFC2344
13999 		 */
14000 		if (ill->ill_mrtun_refcnt > 0) {
14001 			ipaddr_t	srcaddr;
14002 			ire_t		*tmp_ire;
14003 
14004 			tmp_ire = ire;	/* Save, we might need it later */
14005 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14006 			    ire->ire_type != IRE_BROADCAST)) {
14007 				srcaddr = ipha->ipha_src;
14008 				ire = ire_mrtun_lookup(srcaddr, ill);
14009 				if (ire != NULL) {
14010 					/*
14011 					 * Should not be getting iphada packet
14012 					 * here. we should only get those for
14013 					 * IRE_LOCAL traffic, excluded above.
14014 					 * Fail-safe (drop packet) in the event
14015 					 * hardware is misbehaving.
14016 					 */
14017 					if (first_mp != mp) {
14018 						/* IPsec KSTATS: beancount me */
14019 						freemsg(first_mp);
14020 					} else {
14021 						/*
14022 						 * This packet must be forwarded
14023 						 * to Reverse Tunnel
14024 						 */
14025 						ip_mrtun_forward(ire, ill, mp);
14026 					}
14027 					ire_refrele(ire);
14028 					if (tmp_ire != NULL)
14029 						ire_refrele(tmp_ire);
14030 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14031 					    "ip_input_end: q %p (%S)",
14032 					    q, "uninit");
14033 					continue;
14034 				}
14035 			}
14036 			/*
14037 			 * If this packet is from a non-mobilenode  or a
14038 			 * mobile-node which does not request reverse
14039 			 * tunnel service
14040 			 */
14041 			ire = tmp_ire;
14042 		}
14043 
14044 
14045 		/*
14046 		 * If we reach here that means the incoming packet satisfies
14047 		 * one of the following conditions:
14048 		 *   - packet is from a mobile node which does not request
14049 		 *	reverse tunnel
14050 		 *   - packet is from a non-mobile node, which is the most
14051 		 *	common case
14052 		 *   - packet is from a reverse tunnel enabled mobile node
14053 		 *	and destined to foreign agent only
14054 		 */
14055 
14056 		if (ire == NULL) {
14057 			/*
14058 			 * No IRE for this destination, so it can't be for us.
14059 			 * Unless we are forwarding, drop the packet.
14060 			 * We have to let source routed packets through
14061 			 * since we don't yet know if they are 'ping -l'
14062 			 * packets i.e. if they will go out over the
14063 			 * same interface as they came in on.
14064 			 */
14065 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14066 			continue;
14067 		}
14068 
14069 		/*
14070 		 * Broadcast IRE may indicate either broadcast or
14071 		 * multicast packet
14072 		 */
14073 		if (ire->ire_type == IRE_BROADCAST) {
14074 			/*
14075 			 * Skip broadcast checks if packet is UDP multicast;
14076 			 * we'd rather not enter ip_rput_process_broadcast()
14077 			 * unless the packet is broadcast for real, since
14078 			 * that routine is a no-op for multicast.
14079 			 */
14080 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
14081 			    !CLASSD(ipha->ipha_dst)) &&
14082 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
14083 			    dst, cgtp_flt_pkt, ll_multicast)) {
14084 				continue;
14085 			}
14086 		} else if (ire->ire_stq != NULL) {
14087 			/* fowarding? */
14088 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14089 			    ll_multicast);
14090 			continue;
14091 		}
14092 
14093 		/* packet not for us */
14094 		if (ire->ire_rfq != q) {
14095 			if (ip_rput_notforus(&q, mp, ire, ill)) {
14096 				continue;
14097 			}
14098 		}
14099 
14100 		switch (ipha->ipha_protocol) {
14101 		case IPPROTO_TCP:
14102 			ASSERT(first_mp == mp);
14103 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14104 				mp, 0, q, ip_ring)) != NULL) {
14105 				if (curr_sqp == NULL) {
14106 					curr_sqp = GET_SQUEUE(mp);
14107 					ASSERT(cnt == 0);
14108 					cnt++;
14109 					head = tail = mp;
14110 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14111 					ASSERT(tail != NULL);
14112 					cnt++;
14113 					tail->b_next = mp;
14114 					tail = mp;
14115 				} else {
14116 					/*
14117 					 * A different squeue. Send the
14118 					 * chain for the previous squeue on
14119 					 * its way. This shouldn't happen
14120 					 * often unless interrupt binding
14121 					 * changes.
14122 					 */
14123 					IP_STAT(ip_input_multi_squeue);
14124 					squeue_enter_chain(curr_sqp, head,
14125 					    tail, cnt, SQTAG_IP_INPUT);
14126 					curr_sqp = GET_SQUEUE(mp);
14127 					head = mp;
14128 					tail = mp;
14129 					cnt = 1;
14130 				}
14131 			}
14132 			IRE_REFRELE(ire);
14133 			continue;
14134 		case IPPROTO_UDP:
14135 			ASSERT(first_mp == mp);
14136 			ip_udp_input(q, mp, ipha, ire, ill);
14137 			IRE_REFRELE(ire);
14138 			continue;
14139 		case IPPROTO_SCTP:
14140 			ASSERT(first_mp == mp);
14141 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14142 			    q, dst);
14143 			continue;
14144 		default:
14145 			ip_proto_input(q, first_mp, ipha, ire, ill);
14146 			IRE_REFRELE(ire);
14147 			continue;
14148 		}
14149 	}
14150 
14151 	if (head != NULL)
14152 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14153 
14154 	/*
14155 	 * This code is there just to make netperf/ttcp look good.
14156 	 *
14157 	 * Its possible that after being in polling mode (and having cleared
14158 	 * the backlog), squeues have turned the interrupt frequency higher
14159 	 * to improve latency at the expense of more CPU utilization (less
14160 	 * packets per interrupts or more number of interrupts). Workloads
14161 	 * like ttcp/netperf do manage to tickle polling once in a while
14162 	 * but for the remaining time, stay in higher interrupt mode since
14163 	 * their packet arrival rate is pretty uniform and this shows up
14164 	 * as higher CPU utilization. Since people care about CPU utilization
14165 	 * while running netperf/ttcp, turn the interrupt frequency back to
14166 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14167 	 */
14168 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14169 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14170 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14171 			ip_ring->rr_blank(ip_ring->rr_handle,
14172 			    ip_ring->rr_normal_blank_time,
14173 			    ip_ring->rr_normal_pkt_cnt);
14174 		}
14175 	}
14176 
14177 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14178 	    "ip_input_end: q %p (%S)", q, "end");
14179 #undef	rptr
14180 }
14181 
14182 static void
14183 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14184     t_uscalar_t err)
14185 {
14186 	if (dl_err == DL_SYSERR) {
14187 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14188 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14189 		    ill->ill_name, dlpi_prim_str(prim), err);
14190 		return;
14191 	}
14192 
14193 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14194 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14195 	    dlpi_err_str(dl_err));
14196 }
14197 
14198 /*
14199  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14200  * than DL_UNITDATA_IND messages. If we need to process this message
14201  * exclusively, we call qwriter_ip, in which case we also need to call
14202  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14203  */
14204 void
14205 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14206 {
14207 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14208 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14209 	ill_t		*ill;
14210 
14211 	ip1dbg(("ip_rput_dlpi"));
14212 	ill = (ill_t *)q->q_ptr;
14213 	switch (dloa->dl_primitive) {
14214 	case DL_ERROR_ACK:
14215 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14216 		    "%s (0x%x), unix %u\n", ill->ill_name,
14217 		    dlpi_prim_str(dlea->dl_error_primitive),
14218 		    dlea->dl_error_primitive,
14219 		    dlpi_err_str(dlea->dl_errno),
14220 		    dlea->dl_errno,
14221 		    dlea->dl_unix_errno));
14222 		switch (dlea->dl_error_primitive) {
14223 		case DL_UNBIND_REQ:
14224 			mutex_enter(&ill->ill_lock);
14225 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14226 			cv_signal(&ill->ill_cv);
14227 			mutex_exit(&ill->ill_lock);
14228 			/* FALLTHRU */
14229 		case DL_NOTIFY_REQ:
14230 		case DL_ATTACH_REQ:
14231 		case DL_DETACH_REQ:
14232 		case DL_INFO_REQ:
14233 		case DL_BIND_REQ:
14234 		case DL_ENABMULTI_REQ:
14235 		case DL_PHYS_ADDR_REQ:
14236 		case DL_CAPABILITY_REQ:
14237 		case DL_CONTROL_REQ:
14238 			/*
14239 			 * Refhold the ill to match qwriter_ip which does a
14240 			 * refrele. Since this is on the ill stream we
14241 			 * unconditionally bump up the refcount without
14242 			 * checking for ILL_CAN_LOOKUP
14243 			 */
14244 			ill_refhold(ill);
14245 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14246 			    CUR_OP, B_FALSE);
14247 			return;
14248 		case DL_DISABMULTI_REQ:
14249 			freemsg(mp);	/* Don't want to pass this up */
14250 			return;
14251 		default:
14252 			break;
14253 		}
14254 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14255 		    dlea->dl_errno, dlea->dl_unix_errno);
14256 		freemsg(mp);
14257 		return;
14258 	case DL_INFO_ACK:
14259 	case DL_BIND_ACK:
14260 	case DL_PHYS_ADDR_ACK:
14261 	case DL_NOTIFY_ACK:
14262 	case DL_CAPABILITY_ACK:
14263 	case DL_CONTROL_ACK:
14264 		/*
14265 		 * Refhold the ill to match qwriter_ip which does a refrele
14266 		 * Since this is on the ill stream we unconditionally
14267 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14268 		 */
14269 		ill_refhold(ill);
14270 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14271 		    CUR_OP, B_FALSE);
14272 		return;
14273 	case DL_NOTIFY_IND:
14274 		ill_refhold(ill);
14275 		/*
14276 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14277 		 * relation to the current ioctl in progress (if any). Hence we
14278 		 * pass in NEW_OP in this case.
14279 		 */
14280 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14281 		    NEW_OP, B_FALSE);
14282 		return;
14283 	case DL_OK_ACK:
14284 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14285 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14286 		switch (dloa->dl_correct_primitive) {
14287 		case DL_UNBIND_REQ:
14288 			mutex_enter(&ill->ill_lock);
14289 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14290 			cv_signal(&ill->ill_cv);
14291 			mutex_exit(&ill->ill_lock);
14292 			/* FALLTHRU */
14293 		case DL_ATTACH_REQ:
14294 		case DL_DETACH_REQ:
14295 			/*
14296 			 * Refhold the ill to match qwriter_ip which does a
14297 			 * refrele. Since this is on the ill stream we
14298 			 * unconditionally bump up the refcount
14299 			 */
14300 			ill_refhold(ill);
14301 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14302 			    CUR_OP, B_FALSE);
14303 			return;
14304 		case DL_ENABMULTI_REQ:
14305 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14306 				ill->ill_dlpi_multicast_state = IDMS_OK;
14307 			break;
14308 
14309 		}
14310 		break;
14311 	default:
14312 		break;
14313 	}
14314 	freemsg(mp);
14315 }
14316 
14317 /*
14318  * Handling of DLPI messages that require exclusive access to the ipsq.
14319  *
14320  * Need to do ill_pending_mp_release on ioctl completion, which could
14321  * happen here. (along with mi_copy_done)
14322  */
14323 /* ARGSUSED */
14324 static void
14325 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14326 {
14327 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14328 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14329 	int		err = 0;
14330 	ill_t		*ill;
14331 	ipif_t		*ipif = NULL;
14332 	mblk_t		*mp1 = NULL;
14333 	conn_t		*connp = NULL;
14334 	t_uscalar_t	physaddr_req;
14335 	mblk_t		*mp_hw;
14336 	union DL_primitives *dlp;
14337 	boolean_t	success;
14338 	boolean_t	ioctl_aborted = B_FALSE;
14339 	boolean_t	log = B_TRUE;
14340 
14341 	ip1dbg(("ip_rput_dlpi_writer .."));
14342 	ill = (ill_t *)q->q_ptr;
14343 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14344 
14345 	ASSERT(IAM_WRITER_ILL(ill));
14346 
14347 	/*
14348 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14349 	 * both are null or non-null. However we can assert that only
14350 	 * after grabbing the ipsq_lock. So we don't make any assertion
14351 	 * here and in other places in the code.
14352 	 */
14353 	ipif = ipsq->ipsq_pending_ipif;
14354 	/*
14355 	 * The current ioctl could have been aborted by the user and a new
14356 	 * ioctl to bring up another ill could have started. We could still
14357 	 * get a response from the driver later.
14358 	 */
14359 	if (ipif != NULL && ipif->ipif_ill != ill)
14360 		ioctl_aborted = B_TRUE;
14361 
14362 	switch (dloa->dl_primitive) {
14363 	case DL_ERROR_ACK:
14364 		switch (dlea->dl_error_primitive) {
14365 		case DL_UNBIND_REQ:
14366 		case DL_ATTACH_REQ:
14367 		case DL_DETACH_REQ:
14368 		case DL_INFO_REQ:
14369 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14370 			break;
14371 		case DL_NOTIFY_REQ:
14372 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
14373 			log = B_FALSE;
14374 			break;
14375 		case DL_PHYS_ADDR_REQ:
14376 			/*
14377 			 * For IPv6 only, there are two additional
14378 			 * phys_addr_req's sent to the driver to get the
14379 			 * IPv6 token and lla. This allows IP to acquire
14380 			 * the hardware address format for a given interface
14381 			 * without having built in knowledge of the hardware
14382 			 * address. ill_phys_addr_pend keeps track of the last
14383 			 * DL_PAR sent so we know which response we are
14384 			 * dealing with. ill_dlpi_done will update
14385 			 * ill_phys_addr_pend when it sends the next req.
14386 			 * We don't complete the IOCTL until all three DL_PARs
14387 			 * have been attempted, so set *_len to 0 and break.
14388 			 */
14389 			physaddr_req = ill->ill_phys_addr_pend;
14390 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14391 			if (physaddr_req == DL_IPV6_TOKEN) {
14392 				ill->ill_token_length = 0;
14393 				log = B_FALSE;
14394 				break;
14395 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14396 				ill->ill_nd_lla_len = 0;
14397 				log = B_FALSE;
14398 				break;
14399 			}
14400 			/*
14401 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
14402 			 * We presumably have an IOCTL hanging out waiting
14403 			 * for completion. Find it and complete the IOCTL
14404 			 * with the error noted.
14405 			 * However, ill_dl_phys was called on an ill queue
14406 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
14407 			 * set. But the ioctl is known to be pending on ill_wq.
14408 			 */
14409 			if (!ill->ill_ifname_pending)
14410 				break;
14411 			ill->ill_ifname_pending = 0;
14412 			if (!ioctl_aborted)
14413 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14414 			if (mp1 != NULL) {
14415 				/*
14416 				 * This operation (SIOCSLIFNAME) must have
14417 				 * happened on the ill. Assert there is no conn
14418 				 */
14419 				ASSERT(connp == NULL);
14420 				q = ill->ill_wq;
14421 			}
14422 			break;
14423 		case DL_BIND_REQ:
14424 			ill_dlpi_done(ill, DL_BIND_REQ);
14425 			if (ill->ill_ifname_pending)
14426 				break;
14427 			/*
14428 			 * Something went wrong with the bind.  We presumably
14429 			 * have an IOCTL hanging out waiting for completion.
14430 			 * Find it, take down the interface that was coming
14431 			 * up, and complete the IOCTL with the error noted.
14432 			 */
14433 			if (!ioctl_aborted)
14434 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14435 			if (mp1 != NULL) {
14436 				/*
14437 				 * This operation (SIOCSLIFFLAGS) must have
14438 				 * happened from a conn.
14439 				 */
14440 				ASSERT(connp != NULL);
14441 				q = CONNP_TO_WQ(connp);
14442 				if (ill->ill_move_in_progress) {
14443 					ILL_CLEAR_MOVE(ill);
14444 				}
14445 				(void) ipif_down(ipif, NULL, NULL);
14446 				/* error is set below the switch */
14447 			}
14448 			break;
14449 		case DL_ENABMULTI_REQ:
14450 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
14451 
14452 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14453 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
14454 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
14455 				ipif_t *ipif;
14456 
14457 				log = B_FALSE;
14458 				printf("ip: joining multicasts failed (%d)"
14459 				    " on %s - will use link layer "
14460 				    "broadcasts for multicast\n",
14461 				    dlea->dl_errno, ill->ill_name);
14462 
14463 				/*
14464 				 * Set up the multicast mapping alone.
14465 				 * writer, so ok to access ill->ill_ipif
14466 				 * without any lock.
14467 				 */
14468 				ipif = ill->ill_ipif;
14469 				mutex_enter(&ill->ill_phyint->phyint_lock);
14470 				ill->ill_phyint->phyint_flags |=
14471 				    PHYI_MULTI_BCAST;
14472 				mutex_exit(&ill->ill_phyint->phyint_lock);
14473 
14474 				if (!ill->ill_isv6) {
14475 					(void) ipif_arp_setup_multicast(ipif,
14476 					    NULL);
14477 				} else {
14478 					(void) ipif_ndp_setup_multicast(ipif,
14479 					    NULL);
14480 				}
14481 			}
14482 			freemsg(mp);	/* Don't want to pass this up */
14483 			return;
14484 		case DL_CAPABILITY_REQ:
14485 		case DL_CONTROL_REQ:
14486 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
14487 			    "DL_CAPABILITY/CONTROL REQ\n"));
14488 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14489 			ill->ill_capab_state = IDMS_FAILED;
14490 			freemsg(mp);
14491 			return;
14492 		}
14493 		/*
14494 		 * Note the error for IOCTL completion (mp1 is set when
14495 		 * ready to complete ioctl). If ill_ifname_pending_err is
14496 		 * set, an error occured during plumbing (ill_ifname_pending),
14497 		 * so we want to report that error.
14498 		 *
14499 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
14500 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
14501 		 * expected to get errack'd if the driver doesn't support
14502 		 * these flags (e.g. ethernet). log will be set to B_FALSE
14503 		 * if these error conditions are encountered.
14504 		 */
14505 		if (mp1 != NULL) {
14506 			if (ill->ill_ifname_pending_err != 0)  {
14507 				err = ill->ill_ifname_pending_err;
14508 				ill->ill_ifname_pending_err = 0;
14509 			} else {
14510 				err = dlea->dl_unix_errno ?
14511 				    dlea->dl_unix_errno : ENXIO;
14512 			}
14513 		/*
14514 		 * If we're plumbing an interface and an error hasn't already
14515 		 * been saved, set ill_ifname_pending_err to the error passed
14516 		 * up. Ignore the error if log is B_FALSE (see comment above).
14517 		 */
14518 		} else if (log && ill->ill_ifname_pending &&
14519 		    ill->ill_ifname_pending_err == 0) {
14520 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
14521 			dlea->dl_unix_errno : ENXIO;
14522 		}
14523 
14524 		if (log)
14525 			ip_dlpi_error(ill, dlea->dl_error_primitive,
14526 			    dlea->dl_errno, dlea->dl_unix_errno);
14527 		break;
14528 	case DL_CAPABILITY_ACK: {
14529 		boolean_t reneg_flag = B_FALSE;
14530 		/* Call a routine to handle this one. */
14531 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
14532 		/*
14533 		 * Check if the ACK is due to renegotiation case since we
14534 		 * will need to send a new CAPABILITY_REQ later.
14535 		 */
14536 		if (ill->ill_capab_state == IDMS_RENEG) {
14537 			/* This is the ack for a renogiation case */
14538 			reneg_flag = B_TRUE;
14539 			ill->ill_capab_state = IDMS_UNKNOWN;
14540 		}
14541 		ill_capability_ack(ill, mp);
14542 		if (reneg_flag)
14543 			ill_capability_probe(ill);
14544 		break;
14545 	}
14546 	case DL_CONTROL_ACK:
14547 		/* We treat all of these as "fire and forget" */
14548 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14549 		break;
14550 	case DL_INFO_ACK:
14551 		/* Call a routine to handle this one. */
14552 		ill_dlpi_done(ill, DL_INFO_REQ);
14553 		ip_ll_subnet_defaults(ill, mp);
14554 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14555 		return;
14556 	case DL_BIND_ACK:
14557 		/*
14558 		 * We should have an IOCTL waiting on this unless
14559 		 * sent by ill_dl_phys, in which case just return
14560 		 */
14561 		ill_dlpi_done(ill, DL_BIND_REQ);
14562 		if (ill->ill_ifname_pending)
14563 			break;
14564 
14565 		if (!ioctl_aborted)
14566 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14567 		if (mp1 == NULL)
14568 			break;
14569 		ASSERT(connp != NULL);
14570 		q = CONNP_TO_WQ(connp);
14571 
14572 		/*
14573 		 * We are exclusive. So nothing can change even after
14574 		 * we get the pending mp. If need be we can put it back
14575 		 * and restart, as in calling ipif_arp_up()  below.
14576 		 */
14577 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14578 
14579 		mutex_enter(&ill->ill_lock);
14580 		ill->ill_dl_up = 1;
14581 		mutex_exit(&ill->ill_lock);
14582 
14583 		/*
14584 		 * Now bring up the resolver, when that is
14585 		 * done we'll create IREs and we are done.
14586 		 */
14587 		if (ill->ill_isv6) {
14588 			/*
14589 			 * v6 interfaces.
14590 			 * Unlike ARP which has to do another bind
14591 			 * and attach, once we get here we are
14592 			 * done withh NDP. Except in the case of
14593 			 * ILLF_XRESOLV, in which case we send an
14594 			 * AR_INTERFACE_UP to the external resolver.
14595 			 * If all goes well, the ioctl will complete
14596 			 * in ip_rput(). If there's an error, we
14597 			 * complete it here.
14598 			 */
14599 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14600 			    B_FALSE);
14601 			if (err == 0) {
14602 				if (ill->ill_flags & ILLF_XRESOLV) {
14603 					mutex_enter(&connp->conn_lock);
14604 					mutex_enter(&ill->ill_lock);
14605 					success = ipsq_pending_mp_add(
14606 					    connp, ipif, q, mp1, 0);
14607 					mutex_exit(&ill->ill_lock);
14608 					mutex_exit(&connp->conn_lock);
14609 					if (success) {
14610 						err = ipif_resolver_up(ipif,
14611 						    B_FALSE);
14612 						if (err == EINPROGRESS) {
14613 							freemsg(mp);
14614 							return;
14615 						}
14616 						ASSERT(err != 0);
14617 						mp1 = ipsq_pending_mp_get(ipsq,
14618 						    &connp);
14619 						ASSERT(mp1 != NULL);
14620 					} else {
14621 						/* conn has started closing */
14622 						err = EINTR;
14623 					}
14624 				} else { /* Non XRESOLV interface */
14625 					err = ipif_up_done_v6(ipif);
14626 				}
14627 			}
14628 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14629 			/*
14630 			 * ARP and other v4 external resolvers.
14631 			 * Leave the pending mblk intact so that
14632 			 * the ioctl completes in ip_rput().
14633 			 */
14634 			mutex_enter(&connp->conn_lock);
14635 			mutex_enter(&ill->ill_lock);
14636 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14637 			mutex_exit(&ill->ill_lock);
14638 			mutex_exit(&connp->conn_lock);
14639 			if (success) {
14640 				err = ipif_resolver_up(ipif, B_FALSE);
14641 				if (err == EINPROGRESS) {
14642 					freemsg(mp);
14643 					return;
14644 				}
14645 				ASSERT(err != 0);
14646 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14647 			} else {
14648 				/* The conn has started closing */
14649 				err = EINTR;
14650 			}
14651 		} else {
14652 			/*
14653 			 * This one is complete. Reply to pending ioctl.
14654 			 */
14655 			err = ipif_up_done(ipif);
14656 		}
14657 
14658 		if ((err == 0) && (ill->ill_up_ipifs)) {
14659 			err = ill_up_ipifs(ill, q, mp1);
14660 			if (err == EINPROGRESS) {
14661 				freemsg(mp);
14662 				return;
14663 			}
14664 		}
14665 
14666 		if (ill->ill_up_ipifs) {
14667 			ill_group_cleanup(ill);
14668 		}
14669 
14670 		break;
14671 	case DL_NOTIFY_IND: {
14672 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14673 		ire_t *ire;
14674 		boolean_t need_ire_walk_v4 = B_FALSE;
14675 		boolean_t need_ire_walk_v6 = B_FALSE;
14676 
14677 		/*
14678 		 * Change the address everywhere we need to.
14679 		 * What we're getting here is a link-level addr or phys addr.
14680 		 * The new addr is at notify + notify->dl_addr_offset
14681 		 * The address length is notify->dl_addr_length;
14682 		 */
14683 		switch (notify->dl_notification) {
14684 		case DL_NOTE_PHYS_ADDR:
14685 			mp_hw = copyb(mp);
14686 			if (mp_hw == NULL) {
14687 				err = ENOMEM;
14688 				break;
14689 			}
14690 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14691 			/*
14692 			 * We currently don't support changing
14693 			 * the token via DL_NOTIFY_IND.
14694 			 * When we do support it, we have to consider
14695 			 * what the implications are with respect to
14696 			 * the token and the link local address.
14697 			 */
14698 			mutex_enter(&ill->ill_lock);
14699 			if (dlp->notify_ind.dl_data ==
14700 			    DL_IPV6_LINK_LAYER_ADDR) {
14701 				if (ill->ill_nd_lla_mp != NULL)
14702 					freemsg(ill->ill_nd_lla_mp);
14703 				ill->ill_nd_lla_mp = mp_hw;
14704 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14705 				    dlp->notify_ind.dl_addr_offset;
14706 				ill->ill_nd_lla_len =
14707 				    dlp->notify_ind.dl_addr_length -
14708 				    ABS(ill->ill_sap_length);
14709 				mutex_exit(&ill->ill_lock);
14710 				break;
14711 			} else if (dlp->notify_ind.dl_data ==
14712 			    DL_CURR_PHYS_ADDR) {
14713 				if (ill->ill_phys_addr_mp != NULL)
14714 					freemsg(ill->ill_phys_addr_mp);
14715 				ill->ill_phys_addr_mp = mp_hw;
14716 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14717 				    dlp->notify_ind.dl_addr_offset;
14718 				ill->ill_phys_addr_length =
14719 				    dlp->notify_ind.dl_addr_length -
14720 				    ABS(ill->ill_sap_length);
14721 				if (ill->ill_isv6 &&
14722 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14723 					if (ill->ill_nd_lla_mp != NULL)
14724 						freemsg(ill->ill_nd_lla_mp);
14725 					ill->ill_nd_lla_mp = copyb(mp_hw);
14726 					ill->ill_nd_lla = (uchar_t *)
14727 					    ill->ill_nd_lla_mp->b_rptr +
14728 					    dlp->notify_ind.dl_addr_offset;
14729 					ill->ill_nd_lla_len =
14730 					    ill->ill_phys_addr_length;
14731 				}
14732 			}
14733 			mutex_exit(&ill->ill_lock);
14734 			/*
14735 			 * Send out gratuitous arp request for our new
14736 			 * hardware address.
14737 			 */
14738 			for (ipif = ill->ill_ipif; ipif != NULL;
14739 			    ipif = ipif->ipif_next) {
14740 				if (!(ipif->ipif_flags & IPIF_UP))
14741 					continue;
14742 				if (ill->ill_isv6) {
14743 					ipif_ndp_down(ipif);
14744 					/*
14745 					 * Set B_TRUE to enable
14746 					 * ipif_ndp_up() to send out
14747 					 * unsolicited advertisements.
14748 					 */
14749 					err = ipif_ndp_up(ipif,
14750 					    &ipif->ipif_v6lcl_addr,
14751 					    B_TRUE);
14752 					if (err) {
14753 						ip1dbg((
14754 						    "ip_rput_dlpi_writer: "
14755 						    "Failed to update ndp "
14756 						    "err %d\n", err));
14757 					}
14758 				} else {
14759 					/*
14760 					 * IPv4 ARP case
14761 					 *
14762 					 * Set B_TRUE, as we only want
14763 					 * ipif_resolver_up to send an
14764 					 * AR_ENTRY_ADD request up to
14765 					 * ARP.
14766 					 */
14767 					err = ipif_resolver_up(ipif,
14768 					    B_TRUE);
14769 					if (err) {
14770 						ip1dbg((
14771 						    "ip_rput_dlpi_writer: "
14772 						    "Failed to update arp "
14773 						    "err %d\n", err));
14774 					}
14775 				}
14776 			}
14777 			/*
14778 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14779 			 * case so that all old fastpath information can be
14780 			 * purged from IRE caches.
14781 			 */
14782 		/* FALLTHRU */
14783 		case DL_NOTE_FASTPATH_FLUSH:
14784 			/*
14785 			 * Any fastpath probe sent henceforth will get the
14786 			 * new fp mp. So we first delete any ires that are
14787 			 * waiting for the fastpath. Then walk all ires and
14788 			 * delete the ire or delete the fp mp. In the case of
14789 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14790 			 * recreate the ire's without going through a complex
14791 			 * ipif up/down dance. So we don't delete the ire
14792 			 * itself, but just the ire_fp_mp for these 2 ire's
14793 			 * In the case of the other ire's we delete the ire's
14794 			 * themselves. Access to ire_fp_mp is completely
14795 			 * protected by ire_lock for IRE_MIPRTUN and
14796 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14797 			 * other cases for performance.
14798 			 */
14799 			if (ill->ill_isv6) {
14800 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14801 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14802 				    NULL);
14803 			} else {
14804 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14805 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14806 				    IRE_CACHE | IRE_BROADCAST,
14807 				    ire_fastpath_flush, NULL, ill);
14808 				mutex_enter(&ire_mrtun_lock);
14809 				if (ire_mrtun_count != 0) {
14810 					mutex_exit(&ire_mrtun_lock);
14811 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14812 					    IRE_MIPRTUN, ire_fastpath_flush,
14813 					    NULL, ill);
14814 				} else {
14815 					mutex_exit(&ire_mrtun_lock);
14816 				}
14817 			}
14818 			break;
14819 		case DL_NOTE_SDU_SIZE:
14820 			/*
14821 			 * Change the MTU size of the interface, of all
14822 			 * attached ipif's, and of all relevant ire's.  The
14823 			 * new value's a uint32_t at notify->dl_data.
14824 			 * Mtu change Vs. new ire creation - protocol below.
14825 			 *
14826 			 * a Mark the ipif as IPIF_CHANGING.
14827 			 * b Set the new mtu in the ipif.
14828 			 * c Change the ire_max_frag on all affected ires
14829 			 * d Unmark the IPIF_CHANGING
14830 			 *
14831 			 * To see how the protocol works, assume an interface
14832 			 * route is also being added simultaneously by
14833 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14834 			 * the ire. If the ire is created before step a,
14835 			 * it will be cleaned up by step c. If the ire is
14836 			 * created after step d, it will see the new value of
14837 			 * ipif_mtu. Any attempt to create the ire between
14838 			 * steps a to d will fail because of the IPIF_CHANGING
14839 			 * flag. Note that ire_create() is passed a pointer to
14840 			 * the ipif_mtu, and not the value. During ire_add
14841 			 * under the bucket lock, the ire_max_frag of the
14842 			 * new ire being created is set from the ipif/ire from
14843 			 * which it is being derived.
14844 			 */
14845 			mutex_enter(&ill->ill_lock);
14846 			ill->ill_max_frag = (uint_t)notify->dl_data;
14847 
14848 			/*
14849 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14850 			 * leave it alone
14851 			 */
14852 			if (ill->ill_mtu_userspecified) {
14853 				mutex_exit(&ill->ill_lock);
14854 				break;
14855 			}
14856 			ill->ill_max_mtu = ill->ill_max_frag;
14857 			if (ill->ill_isv6) {
14858 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14859 					ill->ill_max_mtu = IPV6_MIN_MTU;
14860 			} else {
14861 				if (ill->ill_max_mtu < IP_MIN_MTU)
14862 					ill->ill_max_mtu = IP_MIN_MTU;
14863 			}
14864 			for (ipif = ill->ill_ipif; ipif != NULL;
14865 			    ipif = ipif->ipif_next) {
14866 				/*
14867 				 * Don't override the mtu if the user
14868 				 * has explicitly set it.
14869 				 */
14870 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14871 					continue;
14872 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14873 				if (ipif->ipif_isv6)
14874 					ire = ipif_to_ire_v6(ipif);
14875 				else
14876 					ire = ipif_to_ire(ipif);
14877 				if (ire != NULL) {
14878 					ire->ire_max_frag = ipif->ipif_mtu;
14879 					ire_refrele(ire);
14880 				}
14881 				if (ipif->ipif_flags & IPIF_UP) {
14882 					if (ill->ill_isv6)
14883 						need_ire_walk_v6 = B_TRUE;
14884 					else
14885 						need_ire_walk_v4 = B_TRUE;
14886 				}
14887 			}
14888 			mutex_exit(&ill->ill_lock);
14889 			if (need_ire_walk_v4)
14890 				ire_walk_v4(ill_mtu_change, (char *)ill,
14891 				    ALL_ZONES);
14892 			if (need_ire_walk_v6)
14893 				ire_walk_v6(ill_mtu_change, (char *)ill,
14894 				    ALL_ZONES);
14895 			break;
14896 		case DL_NOTE_LINK_UP:
14897 		case DL_NOTE_LINK_DOWN: {
14898 			/*
14899 			 * We are writer. ill / phyint / ipsq assocs stable.
14900 			 * The RUNNING flag reflects the state of the link.
14901 			 */
14902 			phyint_t *phyint = ill->ill_phyint;
14903 			uint64_t new_phyint_flags;
14904 			boolean_t changed = B_FALSE;
14905 
14906 			mutex_enter(&phyint->phyint_lock);
14907 			new_phyint_flags =
14908 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14909 			    phyint->phyint_flags | PHYI_RUNNING :
14910 			    phyint->phyint_flags & ~PHYI_RUNNING;
14911 			if (new_phyint_flags != phyint->phyint_flags) {
14912 				phyint->phyint_flags = new_phyint_flags;
14913 				changed = B_TRUE;
14914 			}
14915 			mutex_exit(&phyint->phyint_lock);
14916 			/*
14917 			 * If the flags have changed, send a message to
14918 			 * the routing socket.
14919 			 */
14920 			if (changed) {
14921 				if (phyint->phyint_illv4 != NULL) {
14922 					ip_rts_ifmsg(
14923 					    phyint->phyint_illv4->ill_ipif);
14924 				}
14925 				if (phyint->phyint_illv6 != NULL) {
14926 					ip_rts_ifmsg(
14927 					    phyint->phyint_illv6->ill_ipif);
14928 				}
14929 			}
14930 			break;
14931 		}
14932 		case DL_NOTE_PROMISC_ON_PHYS:
14933 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14934 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14935 			mutex_enter(&ill->ill_lock);
14936 			ill->ill_promisc_on_phys = B_TRUE;
14937 			mutex_exit(&ill->ill_lock);
14938 			break;
14939 		case DL_NOTE_PROMISC_OFF_PHYS:
14940 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14941 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14942 			mutex_enter(&ill->ill_lock);
14943 			ill->ill_promisc_on_phys = B_FALSE;
14944 			mutex_exit(&ill->ill_lock);
14945 			break;
14946 		case DL_NOTE_CAPAB_RENEG:
14947 			/*
14948 			 * Something changed on the driver side.
14949 			 * It wants us to renegotiate the capabilities
14950 			 * on this ill. The most likely cause is the
14951 			 * aggregation interface under us where a
14952 			 * port got added or went away.
14953 			 *
14954 			 * We reset the capabilities and set the
14955 			 * state to IDMS_RENG so that when the ack
14956 			 * comes back, we can start the
14957 			 * renegotiation process.
14958 			 */
14959 			ill_capability_reset(ill);
14960 			ill->ill_capab_state = IDMS_RENEG;
14961 			break;
14962 		default:
14963 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14964 			    "type 0x%x for DL_NOTIFY_IND\n",
14965 			    notify->dl_notification));
14966 			break;
14967 		}
14968 
14969 		/*
14970 		 * As this is an asynchronous operation, we
14971 		 * should not call ill_dlpi_done
14972 		 */
14973 		break;
14974 	}
14975 	case DL_NOTIFY_ACK:
14976 		/*
14977 		 * Don't really need to check for what notifications
14978 		 * are supported; we'll process what gets sent upstream,
14979 		 * and we know it'll be something we support changing
14980 		 * based on our DL_NOTIFY_REQ.
14981 		 */
14982 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14983 		break;
14984 	case DL_PHYS_ADDR_ACK: {
14985 		/*
14986 		 * We should have an IOCTL waiting on this when request
14987 		 * sent by ill_dl_phys.
14988 		 * However, ill_dl_phys was called on an ill queue (from
14989 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14990 		 * ioctl is known to be pending on ill_wq.
14991 		 * There are two additional phys_addr_req's sent to the
14992 		 * driver to get the token and lla. ill_phys_addr_pend
14993 		 * keeps track of the last one sent so we know which
14994 		 * response we are dealing with. ill_dlpi_done will
14995 		 * update ill_phys_addr_pend when it sends the next req.
14996 		 * We don't complete the IOCTL until all three DL_PARs
14997 		 * have been attempted.
14998 		 *
14999 		 * We don't need any lock to update ill_nd_lla* fields,
15000 		 * since the ill is not yet up, We grab the lock just
15001 		 * for uniformity with other code that accesses ill_nd_lla.
15002 		 */
15003 		physaddr_req = ill->ill_phys_addr_pend;
15004 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15005 		if (physaddr_req == DL_IPV6_TOKEN ||
15006 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15007 			if (physaddr_req == DL_IPV6_TOKEN) {
15008 				/*
15009 				 * bcopy to low-order bits of ill_token
15010 				 *
15011 				 * XXX Temporary hack - currently,
15012 				 * all known tokens are 64 bits,
15013 				 * so I'll cheat for the moment.
15014 				 */
15015 				dlp = (union DL_primitives *)mp->b_rptr;
15016 
15017 				mutex_enter(&ill->ill_lock);
15018 				bcopy((uchar_t *)(mp->b_rptr +
15019 				dlp->physaddr_ack.dl_addr_offset),
15020 				(void *)&ill->ill_token.s6_addr32[2],
15021 				dlp->physaddr_ack.dl_addr_length);
15022 				ill->ill_token_length =
15023 					dlp->physaddr_ack.dl_addr_length;
15024 				mutex_exit(&ill->ill_lock);
15025 			} else {
15026 				ASSERT(ill->ill_nd_lla_mp == NULL);
15027 				mp_hw = copyb(mp);
15028 				if (mp_hw == NULL) {
15029 					err = ENOMEM;
15030 					break;
15031 				}
15032 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15033 				mutex_enter(&ill->ill_lock);
15034 				ill->ill_nd_lla_mp = mp_hw;
15035 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15036 				dlp->physaddr_ack.dl_addr_offset;
15037 				ill->ill_nd_lla_len =
15038 					dlp->physaddr_ack.dl_addr_length;
15039 				mutex_exit(&ill->ill_lock);
15040 			}
15041 			break;
15042 		}
15043 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15044 		ASSERT(ill->ill_phys_addr_mp == NULL);
15045 		if (!ill->ill_ifname_pending)
15046 			break;
15047 		ill->ill_ifname_pending = 0;
15048 		if (!ioctl_aborted)
15049 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15050 		if (mp1 != NULL) {
15051 			ASSERT(connp == NULL);
15052 			q = ill->ill_wq;
15053 		}
15054 		/*
15055 		 * If any error acks received during the plumbing sequence,
15056 		 * ill_ifname_pending_err will be set. Break out and send up
15057 		 * the error to the pending ioctl.
15058 		 */
15059 		if (ill->ill_ifname_pending_err != 0) {
15060 			err = ill->ill_ifname_pending_err;
15061 			ill->ill_ifname_pending_err = 0;
15062 			break;
15063 		}
15064 		/*
15065 		 * Get the interface token.  If the zeroth interface
15066 		 * address is zero then set the address to the link local
15067 		 * address
15068 		 */
15069 		mp_hw = copyb(mp);
15070 		if (mp_hw == NULL) {
15071 			err = ENOMEM;
15072 			break;
15073 		}
15074 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15075 		ill->ill_phys_addr_mp = mp_hw;
15076 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15077 				dlp->physaddr_ack.dl_addr_offset;
15078 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15079 		    ill->ill_phys_addr_length == 0 ||
15080 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15081 			/*
15082 			 * Compatibility: atun driver returns a length of 0.
15083 			 * ipdptp has an ill_phys_addr_length of zero(from
15084 			 * DL_BIND_ACK) but a non-zero length here.
15085 			 * ipd has an ill_phys_addr_length of 4(from
15086 			 * DL_BIND_ACK) but a non-zero length here.
15087 			 */
15088 			ill->ill_phys_addr = NULL;
15089 		} else if (dlp->physaddr_ack.dl_addr_length !=
15090 		    ill->ill_phys_addr_length) {
15091 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15092 			    "Address length mismatch %d %d\n",
15093 			    dlp->physaddr_ack.dl_addr_length,
15094 			    ill->ill_phys_addr_length));
15095 			err = EINVAL;
15096 			break;
15097 		}
15098 		mutex_enter(&ill->ill_lock);
15099 		if (ill->ill_nd_lla_mp == NULL) {
15100 			ill->ill_nd_lla_mp = copyb(mp_hw);
15101 			if (ill->ill_nd_lla_mp == NULL) {
15102 				err = ENOMEM;
15103 				mutex_exit(&ill->ill_lock);
15104 				break;
15105 			}
15106 			ill->ill_nd_lla =
15107 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15108 			    dlp->physaddr_ack.dl_addr_offset;
15109 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15110 		}
15111 		mutex_exit(&ill->ill_lock);
15112 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15113 			(void) ill_setdefaulttoken(ill);
15114 
15115 		/*
15116 		 * If the ill zero interface has a zero address assign
15117 		 * it the proper link local address.
15118 		 */
15119 		ASSERT(ill->ill_ipif->ipif_id == 0);
15120 		if (ipif != NULL &&
15121 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15122 			(void) ipif_setlinklocal(ipif);
15123 		break;
15124 	}
15125 	case DL_OK_ACK:
15126 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15127 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15128 		    dloa->dl_correct_primitive));
15129 		switch (dloa->dl_correct_primitive) {
15130 		case DL_UNBIND_REQ:
15131 		case DL_ATTACH_REQ:
15132 		case DL_DETACH_REQ:
15133 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15134 			break;
15135 		}
15136 		break;
15137 	default:
15138 		break;
15139 	}
15140 
15141 	freemsg(mp);
15142 	if (mp1) {
15143 		struct iocblk *iocp;
15144 		int mode;
15145 
15146 		/*
15147 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15148 		 * SIOCSLIFNAME do a copyout.
15149 		 */
15150 		iocp = (struct iocblk *)mp1->b_rptr;
15151 
15152 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15153 		    iocp->ioc_cmd == SIOCSLIFNAME)
15154 			mode = COPYOUT;
15155 		else
15156 			mode = NO_COPYOUT;
15157 		/*
15158 		 * The ioctl must complete now without EINPROGRESS
15159 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15160 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15161 		 * stuck for ever in the ipsq.
15162 		 */
15163 		ASSERT(err != EINPROGRESS);
15164 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15165 
15166 	}
15167 }
15168 
15169 /*
15170  * ip_rput_other is called by ip_rput to handle messages modifying the global
15171  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15172  */
15173 /* ARGSUSED */
15174 void
15175 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15176 {
15177 	ill_t		*ill;
15178 	struct iocblk	*iocp;
15179 	mblk_t		*mp1;
15180 	conn_t		*connp = NULL;
15181 
15182 	ip1dbg(("ip_rput_other "));
15183 	ill = (ill_t *)q->q_ptr;
15184 	/*
15185 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15186 	 * in which case ipsq is NULL.
15187 	 */
15188 	if (ipsq != NULL) {
15189 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15190 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15191 	}
15192 
15193 	switch (mp->b_datap->db_type) {
15194 	case M_ERROR:
15195 	case M_HANGUP:
15196 		/*
15197 		 * The device has a problem.  We force the ILL down.  It can
15198 		 * be brought up again manually using SIOCSIFFLAGS (via
15199 		 * ifconfig or equivalent).
15200 		 */
15201 		ASSERT(ipsq != NULL);
15202 		if (mp->b_rptr < mp->b_wptr)
15203 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15204 		if (ill->ill_error == 0)
15205 			ill->ill_error = ENXIO;
15206 		if (!ill_down_start(q, mp))
15207 			return;
15208 		ipif_all_down_tail(ipsq, q, mp, NULL);
15209 		break;
15210 	case M_IOCACK:
15211 		iocp = (struct iocblk *)mp->b_rptr;
15212 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15213 		switch (iocp->ioc_cmd) {
15214 		case SIOCSTUNPARAM:
15215 		case OSIOCSTUNPARAM:
15216 			ASSERT(ipsq != NULL);
15217 			/*
15218 			 * Finish socket ioctl passed through to tun.
15219 			 * We should have an IOCTL waiting on this.
15220 			 */
15221 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15222 			if (ill->ill_isv6) {
15223 				struct iftun_req *ta;
15224 
15225 				/*
15226 				 * if a source or destination is
15227 				 * being set, try and set the link
15228 				 * local address for the tunnel
15229 				 */
15230 				ta = (struct iftun_req *)mp->b_cont->
15231 				    b_cont->b_rptr;
15232 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15233 					ipif_set_tun_llink(ill, ta);
15234 				}
15235 
15236 			}
15237 			if (mp1 != NULL) {
15238 				/*
15239 				 * Now copy back the b_next/b_prev used by
15240 				 * mi code for the mi_copy* functions.
15241 				 * See ip_sioctl_tunparam() for the reason.
15242 				 * Also protect against missing b_cont.
15243 				 */
15244 				if (mp->b_cont != NULL) {
15245 					mp->b_cont->b_next =
15246 					    mp1->b_cont->b_next;
15247 					mp->b_cont->b_prev =
15248 					    mp1->b_cont->b_prev;
15249 				}
15250 				inet_freemsg(mp1);
15251 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15252 				ASSERT(connp != NULL);
15253 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15254 				    iocp->ioc_error, NO_COPYOUT,
15255 				    ipsq->ipsq_current_ipif, ipsq);
15256 			} else {
15257 				ASSERT(connp == NULL);
15258 				putnext(q, mp);
15259 			}
15260 			break;
15261 		case SIOCGTUNPARAM:
15262 		case OSIOCGTUNPARAM:
15263 			/*
15264 			 * This is really M_IOCDATA from the tunnel driver.
15265 			 * convert back and complete the ioctl.
15266 			 * We should have an IOCTL waiting on this.
15267 			 */
15268 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15269 			if (mp1) {
15270 				/*
15271 				 * Now copy back the b_next/b_prev used by
15272 				 * mi code for the mi_copy* functions.
15273 				 * See ip_sioctl_tunparam() for the reason.
15274 				 * Also protect against missing b_cont.
15275 				 */
15276 				if (mp->b_cont != NULL) {
15277 					mp->b_cont->b_next =
15278 					    mp1->b_cont->b_next;
15279 					mp->b_cont->b_prev =
15280 					    mp1->b_cont->b_prev;
15281 				}
15282 				inet_freemsg(mp1);
15283 				if (iocp->ioc_error == 0)
15284 					mp->b_datap->db_type = M_IOCDATA;
15285 				ASSERT(connp != NULL);
15286 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15287 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15288 			} else {
15289 				ASSERT(connp == NULL);
15290 				putnext(q, mp);
15291 			}
15292 			break;
15293 		default:
15294 			break;
15295 		}
15296 		break;
15297 	case M_IOCNAK:
15298 		iocp = (struct iocblk *)mp->b_rptr;
15299 
15300 		switch (iocp->ioc_cmd) {
15301 		int mode;
15302 		ipif_t	*ipif;
15303 
15304 		case DL_IOC_HDR_INFO:
15305 			/*
15306 			 * If this was the first attempt turn of the
15307 			 * fastpath probing.
15308 			 */
15309 			mutex_enter(&ill->ill_lock);
15310 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15311 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15312 				mutex_exit(&ill->ill_lock);
15313 				ill_fastpath_nack(ill);
15314 				ip1dbg(("ip_rput: DLPI fastpath off on "
15315 				    "interface %s\n",
15316 				    ill->ill_name));
15317 			} else {
15318 				mutex_exit(&ill->ill_lock);
15319 			}
15320 			freemsg(mp);
15321 			break;
15322 		case SIOCSTUNPARAM:
15323 		case OSIOCSTUNPARAM:
15324 			ASSERT(ipsq != NULL);
15325 			/*
15326 			 * Finish socket ioctl passed through to tun
15327 			 * We should have an IOCTL waiting on this.
15328 			 */
15329 			/* FALLTHRU */
15330 		case SIOCGTUNPARAM:
15331 		case OSIOCGTUNPARAM:
15332 			/*
15333 			 * This is really M_IOCDATA from the tunnel driver.
15334 			 * convert back and complete the ioctl.
15335 			 * We should have an IOCTL waiting on this.
15336 			 */
15337 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15338 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15339 				mp1 = ill_pending_mp_get(ill, &connp,
15340 				    iocp->ioc_id);
15341 				mode = COPYOUT;
15342 				ipsq = NULL;
15343 				ipif = NULL;
15344 			} else {
15345 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15346 				mode = NO_COPYOUT;
15347 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15348 				ipif = ipsq->ipsq_current_ipif;
15349 			}
15350 			if (mp1 != NULL) {
15351 				/*
15352 				 * Now copy back the b_next/b_prev used by
15353 				 * mi code for the mi_copy* functions.
15354 				 * See ip_sioctl_tunparam() for the reason.
15355 				 * Also protect against missing b_cont.
15356 				 */
15357 				if (mp->b_cont != NULL) {
15358 					mp->b_cont->b_next =
15359 					    mp1->b_cont->b_next;
15360 					mp->b_cont->b_prev =
15361 					    mp1->b_cont->b_prev;
15362 				}
15363 				inet_freemsg(mp1);
15364 				if (iocp->ioc_error == 0)
15365 					iocp->ioc_error = EINVAL;
15366 				ASSERT(connp != NULL);
15367 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15368 				    iocp->ioc_error, mode, ipif, ipsq);
15369 			} else {
15370 				ASSERT(connp == NULL);
15371 				putnext(q, mp);
15372 			}
15373 			break;
15374 		default:
15375 			break;
15376 		}
15377 	default:
15378 		break;
15379 	}
15380 }
15381 
15382 /*
15383  * NOTE : This function does not ire_refrele the ire argument passed in.
15384  *
15385  * IPQoS notes
15386  * IP policy is invoked twice for a forwarded packet, once on the read side
15387  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15388  * enabled. An additional parameter, in_ill, has been added for this purpose.
15389  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15390  * because ip_mroute drops this information.
15391  *
15392  */
15393 void
15394 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15395 {
15396 	uint32_t	pkt_len;
15397 	queue_t	*q;
15398 	uint32_t	sum;
15399 #define	rptr	((uchar_t *)ipha)
15400 	uint32_t	max_frag;
15401 	uint32_t	ill_index;
15402 
15403 	/* Get the ill_index of the incoming ILL */
15404 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15405 
15406 	/* Initiate Read side IPPF processing */
15407 	if (IPP_ENABLED(IPP_FWD_IN)) {
15408 		ip_process(IPP_FWD_IN, &mp, ill_index);
15409 		if (mp == NULL) {
15410 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15411 			    "during IPPF processing\n"));
15412 			return;
15413 		}
15414 	}
15415 	pkt_len = ntohs(ipha->ipha_length);
15416 
15417 	/* Adjust the checksum to reflect the ttl decrement. */
15418 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
15419 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
15420 
15421 	if (ipha->ipha_ttl-- <= 1) {
15422 		if (ip_csum_hdr(ipha)) {
15423 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15424 			goto drop_pkt;
15425 		}
15426 		/*
15427 		 * Note: ire_stq this will be NULL for multicast
15428 		 * datagrams using the long path through arp (the IRE
15429 		 * is not an IRE_CACHE). This should not cause
15430 		 * problems since we don't generate ICMP errors for
15431 		 * multicast packets.
15432 		 */
15433 		q = ire->ire_stq;
15434 		if (q)
15435 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
15436 		else
15437 			freemsg(mp);
15438 		return;
15439 	}
15440 
15441 	/*
15442 	 * Don't forward if the interface is down
15443 	 */
15444 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
15445 		BUMP_MIB(&ip_mib, ipInDiscards);
15446 		goto drop_pkt;
15447 	}
15448 
15449 	/* Get the ill_index of the outgoing ILL */
15450 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
15451 
15452 	if (is_system_labeled()) {
15453 		mblk_t *mp1;
15454 
15455 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
15456 			BUMP_MIB(&ip_mib, ipForwProhibits);
15457 			goto drop_pkt;
15458 		}
15459 		/* Size may have changed */
15460 		mp = mp1;
15461 		ipha = (ipha_t *)mp->b_rptr;
15462 		pkt_len = ntohs(ipha->ipha_length);
15463 	}
15464 
15465 	/* Check if there are options to update */
15466 	if (!IS_SIMPLE_IPH(ipha)) {
15467 		if (ip_csum_hdr(ipha)) {
15468 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15469 			goto drop_pkt;
15470 		}
15471 		if (ip_rput_forward_options(mp, ipha, ire)) {
15472 			return;
15473 		}
15474 
15475 		ipha->ipha_hdr_checksum = 0;
15476 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
15477 	}
15478 	max_frag = ire->ire_max_frag;
15479 	if (pkt_len > max_frag) {
15480 		/*
15481 		 * It needs fragging on its way out.  We haven't
15482 		 * verified the header checksum yet.  Since we
15483 		 * are going to put a surely good checksum in the
15484 		 * outgoing header, we have to make sure that it
15485 		 * was good coming in.
15486 		 */
15487 		if (ip_csum_hdr(ipha)) {
15488 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15489 			goto drop_pkt;
15490 		}
15491 		/* Initiate Write side IPPF processing */
15492 		if (IPP_ENABLED(IPP_FWD_OUT)) {
15493 			ip_process(IPP_FWD_OUT, &mp, ill_index);
15494 			if (mp == NULL) {
15495 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
15496 				    " during IPPF processing\n"));
15497 				return;
15498 			}
15499 		}
15500 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
15501 		return;
15502 	}
15503 
15504 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
15505 	if (mp == NULL) {
15506 		BUMP_MIB(&ip_mib, ipInDiscards);
15507 		return;
15508 	}
15509 
15510 	q = ire->ire_stq;
15511 	UPDATE_IB_PKT_COUNT(ire);
15512 	ire->ire_last_used_time = lbolt;
15513 	BUMP_MIB(&ip_mib, ipForwDatagrams);
15514 	putnext(q, mp);
15515 	return;
15516 
15517 drop_pkt:;
15518 	ip1dbg(("ip_rput_forward: drop pkt\n"));
15519 	freemsg(mp);
15520 #undef	rptr
15521 }
15522 
15523 void
15524 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
15525 {
15526 	ire_t	*ire;
15527 
15528 	ASSERT(!ipif->ipif_isv6);
15529 	/*
15530 	 * Find an IRE which matches the destination and the outgoing
15531 	 * queue in the cache table. All we need is an IRE_CACHE which
15532 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
15533 	 * then it is enough to have some IRE_CACHE in the group.
15534 	 */
15535 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
15536 		dst = ipif->ipif_pp_dst_addr;
15537 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
15538 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
15539 	if (ire == NULL) {
15540 		/*
15541 		 * Mark this packet to make it be delivered to
15542 		 * ip_rput_forward after the new ire has been
15543 		 * created.
15544 		 */
15545 		mp->b_prev = NULL;
15546 		mp->b_next = mp;
15547 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
15548 		    NULL, 0);
15549 	} else {
15550 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
15551 		IRE_REFRELE(ire);
15552 	}
15553 }
15554 
15555 /* Update any source route, record route or timestamp options */
15556 static int
15557 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15558 {
15559 	ipoptp_t	opts;
15560 	uchar_t		*opt;
15561 	uint8_t		optval;
15562 	uint8_t		optlen;
15563 	ipaddr_t	dst;
15564 	uint32_t	ts;
15565 	ire_t		*dst_ire = NULL;
15566 	ire_t		*tmp_ire = NULL;
15567 	timestruc_t	now;
15568 
15569 	ip2dbg(("ip_rput_forward_options\n"));
15570 	dst = ipha->ipha_dst;
15571 	for (optval = ipoptp_first(&opts, ipha);
15572 	    optval != IPOPT_EOL;
15573 	    optval = ipoptp_next(&opts)) {
15574 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15575 		opt = opts.ipoptp_cur;
15576 		optlen = opts.ipoptp_len;
15577 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15578 		    optval, opts.ipoptp_len));
15579 		switch (optval) {
15580 			uint32_t off;
15581 		case IPOPT_SSRR:
15582 		case IPOPT_LSRR:
15583 			/* Check if adminstratively disabled */
15584 			if (!ip_forward_src_routed) {
15585 				BUMP_MIB(&ip_mib, ipForwProhibits);
15586 				if (ire->ire_stq)
15587 					icmp_unreachable(ire->ire_stq, mp,
15588 					    ICMP_SOURCE_ROUTE_FAILED);
15589 				else {
15590 					ip0dbg(("ip_rput_forward_options: "
15591 					    "unable to send unreach\n"));
15592 					freemsg(mp);
15593 				}
15594 				return (-1);
15595 			}
15596 
15597 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15598 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15599 			if (dst_ire == NULL) {
15600 				/*
15601 				 * Must be partial since ip_rput_options
15602 				 * checked for strict.
15603 				 */
15604 				break;
15605 			}
15606 			off = opt[IPOPT_OFFSET];
15607 			off--;
15608 		redo_srr:
15609 			if (optlen < IP_ADDR_LEN ||
15610 			    off > optlen - IP_ADDR_LEN) {
15611 				/* End of source route */
15612 				ip1dbg((
15613 				    "ip_rput_forward_options: end of SR\n"));
15614 				ire_refrele(dst_ire);
15615 				break;
15616 			}
15617 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15618 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15619 			    IP_ADDR_LEN);
15620 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15621 			    ntohl(dst)));
15622 
15623 			/*
15624 			 * Check if our address is present more than
15625 			 * once as consecutive hops in source route.
15626 			 */
15627 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15628 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15629 			if (tmp_ire != NULL) {
15630 				ire_refrele(tmp_ire);
15631 				off += IP_ADDR_LEN;
15632 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15633 				goto redo_srr;
15634 			}
15635 			ipha->ipha_dst = dst;
15636 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15637 			ire_refrele(dst_ire);
15638 			break;
15639 		case IPOPT_RR:
15640 			off = opt[IPOPT_OFFSET];
15641 			off--;
15642 			if (optlen < IP_ADDR_LEN ||
15643 			    off > optlen - IP_ADDR_LEN) {
15644 				/* No more room - ignore */
15645 				ip1dbg((
15646 				    "ip_rput_forward_options: end of RR\n"));
15647 				break;
15648 			}
15649 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15650 			    IP_ADDR_LEN);
15651 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15652 			break;
15653 		case IPOPT_TS:
15654 			/* Insert timestamp if there is room */
15655 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15656 			case IPOPT_TS_TSONLY:
15657 				off = IPOPT_TS_TIMELEN;
15658 				break;
15659 			case IPOPT_TS_PRESPEC:
15660 			case IPOPT_TS_PRESPEC_RFC791:
15661 				/* Verify that the address matched */
15662 				off = opt[IPOPT_OFFSET] - 1;
15663 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15664 				dst_ire = ire_ctable_lookup(dst, 0,
15665 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
15666 				    MATCH_IRE_TYPE);
15667 
15668 				if (dst_ire == NULL) {
15669 					/* Not for us */
15670 					break;
15671 				}
15672 				ire_refrele(dst_ire);
15673 				/* FALLTHRU */
15674 			case IPOPT_TS_TSANDADDR:
15675 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15676 				break;
15677 			default:
15678 				/*
15679 				 * ip_*put_options should have already
15680 				 * dropped this packet.
15681 				 */
15682 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15683 				    "unknown IT - bug in ip_rput_options?\n");
15684 				return (0);	/* Keep "lint" happy */
15685 			}
15686 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15687 				/* Increase overflow counter */
15688 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15689 				opt[IPOPT_POS_OV_FLG] =
15690 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15691 				    (off << 4));
15692 				break;
15693 			}
15694 			off = opt[IPOPT_OFFSET] - 1;
15695 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15696 			case IPOPT_TS_PRESPEC:
15697 			case IPOPT_TS_PRESPEC_RFC791:
15698 			case IPOPT_TS_TSANDADDR:
15699 				bcopy(&ire->ire_src_addr,
15700 				    (char *)opt + off, IP_ADDR_LEN);
15701 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15702 				/* FALLTHRU */
15703 			case IPOPT_TS_TSONLY:
15704 				off = opt[IPOPT_OFFSET] - 1;
15705 				/* Compute # of milliseconds since midnight */
15706 				gethrestime(&now);
15707 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15708 				    now.tv_nsec / (NANOSEC / MILLISEC);
15709 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15710 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15711 				break;
15712 			}
15713 			break;
15714 		}
15715 	}
15716 	return (0);
15717 }
15718 
15719 /*
15720  * This is called after processing at least one of AH/ESP headers.
15721  *
15722  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15723  * the actual, physical interface on which the packet was received,
15724  * but, when ip_strict_dst_multihoming is set to 1, could be the
15725  * interface which had the ipha_dst configured when the packet went
15726  * through ip_rput. The ill_index corresponding to the recv_ill
15727  * is saved in ipsec_in_rill_index
15728  */
15729 void
15730 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15731 {
15732 	mblk_t *mp;
15733 	ipaddr_t dst;
15734 	in6_addr_t *v6dstp;
15735 	ipha_t *ipha;
15736 	ip6_t *ip6h;
15737 	ipsec_in_t *ii;
15738 	boolean_t ill_need_rele = B_FALSE;
15739 	boolean_t rill_need_rele = B_FALSE;
15740 	boolean_t ire_need_rele = B_FALSE;
15741 
15742 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15743 	ASSERT(ii->ipsec_in_ill_index != 0);
15744 
15745 	mp = ipsec_mp->b_cont;
15746 	ASSERT(mp != NULL);
15747 
15748 
15749 	if (ill == NULL) {
15750 		ASSERT(recv_ill == NULL);
15751 		/*
15752 		 * We need to get the original queue on which ip_rput_local
15753 		 * or ip_rput_data_v6 was called.
15754 		 */
15755 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15756 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15757 		ill_need_rele = B_TRUE;
15758 
15759 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15760 			recv_ill = ill_lookup_on_ifindex(
15761 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15762 			    NULL, NULL, NULL, NULL);
15763 			rill_need_rele = B_TRUE;
15764 		} else {
15765 			recv_ill = ill;
15766 		}
15767 
15768 		if ((ill == NULL) || (recv_ill == NULL)) {
15769 			ip0dbg(("ip_fanout_proto_again: interface "
15770 			    "disappeared\n"));
15771 			if (ill != NULL)
15772 				ill_refrele(ill);
15773 			if (recv_ill != NULL)
15774 				ill_refrele(recv_ill);
15775 			freemsg(ipsec_mp);
15776 			return;
15777 		}
15778 	}
15779 
15780 	ASSERT(ill != NULL && recv_ill != NULL);
15781 
15782 	if (mp->b_datap->db_type == M_CTL) {
15783 		/*
15784 		 * AH/ESP is returning the ICMP message after
15785 		 * removing their headers. Fanout again till
15786 		 * it gets to the right protocol.
15787 		 */
15788 		if (ii->ipsec_in_v4) {
15789 			icmph_t *icmph;
15790 			int iph_hdr_length;
15791 			int hdr_length;
15792 
15793 			ipha = (ipha_t *)mp->b_rptr;
15794 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15795 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15796 			ipha = (ipha_t *)&icmph[1];
15797 			hdr_length = IPH_HDR_LENGTH(ipha);
15798 			/*
15799 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15800 			 * Reset the type to M_DATA.
15801 			 */
15802 			mp->b_datap->db_type = M_DATA;
15803 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15804 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15805 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15806 		} else {
15807 			icmp6_t *icmp6;
15808 			int hdr_length;
15809 
15810 			ip6h = (ip6_t *)mp->b_rptr;
15811 			/* Don't call hdr_length_v6() unless you have to. */
15812 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15813 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15814 			else
15815 				hdr_length = IPV6_HDR_LEN;
15816 
15817 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15818 			/*
15819 			 * icmp_inbound_error_fanout_v6 may need to do
15820 			 * pullupmsg.  Reset the type to M_DATA.
15821 			 */
15822 			mp->b_datap->db_type = M_DATA;
15823 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15824 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15825 		}
15826 		if (ill_need_rele)
15827 			ill_refrele(ill);
15828 		if (rill_need_rele)
15829 			ill_refrele(recv_ill);
15830 		return;
15831 	}
15832 
15833 	if (ii->ipsec_in_v4) {
15834 		ipha = (ipha_t *)mp->b_rptr;
15835 		dst = ipha->ipha_dst;
15836 		if (CLASSD(dst)) {
15837 			/*
15838 			 * Multicast has to be delivered to all streams.
15839 			 */
15840 			dst = INADDR_BROADCAST;
15841 		}
15842 
15843 		if (ire == NULL) {
15844 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
15845 			    MBLK_GETLABEL(mp));
15846 			if (ire == NULL) {
15847 				if (ill_need_rele)
15848 					ill_refrele(ill);
15849 				if (rill_need_rele)
15850 					ill_refrele(recv_ill);
15851 				ip1dbg(("ip_fanout_proto_again: "
15852 				    "IRE not found"));
15853 				freemsg(ipsec_mp);
15854 				return;
15855 			}
15856 			ire_need_rele = B_TRUE;
15857 		}
15858 
15859 		switch (ipha->ipha_protocol) {
15860 			case IPPROTO_UDP:
15861 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15862 				    recv_ill);
15863 				if (ire_need_rele)
15864 					ire_refrele(ire);
15865 				break;
15866 			case IPPROTO_TCP:
15867 				if (!ire_need_rele)
15868 					IRE_REFHOLD(ire);
15869 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15870 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15871 				IRE_REFRELE(ire);
15872 				if (mp != NULL)
15873 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15874 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15875 				break;
15876 			case IPPROTO_SCTP:
15877 				if (!ire_need_rele)
15878 					IRE_REFHOLD(ire);
15879 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15880 				    ipsec_mp, 0, ill->ill_rq, dst);
15881 				break;
15882 			default:
15883 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15884 				    recv_ill);
15885 				if (ire_need_rele)
15886 					ire_refrele(ire);
15887 				break;
15888 		}
15889 	} else {
15890 		uint32_t rput_flags = 0;
15891 
15892 		ip6h = (ip6_t *)mp->b_rptr;
15893 		v6dstp = &ip6h->ip6_dst;
15894 		/*
15895 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15896 		 * address.
15897 		 *
15898 		 * Currently, we don't store that state in the IPSEC_IN
15899 		 * message, and we may need to.
15900 		 */
15901 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15902 		    IP6_IN_LLMCAST : 0);
15903 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15904 		    NULL);
15905 	}
15906 	if (ill_need_rele)
15907 		ill_refrele(ill);
15908 	if (rill_need_rele)
15909 		ill_refrele(recv_ill);
15910 }
15911 
15912 /*
15913  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15914  * returns 'true' if there are still fragments left on the queue, in
15915  * which case we restart the timer.
15916  */
15917 void
15918 ill_frag_timer(void *arg)
15919 {
15920 	ill_t	*ill = (ill_t *)arg;
15921 	boolean_t frag_pending;
15922 
15923 	mutex_enter(&ill->ill_lock);
15924 	ASSERT(!ill->ill_fragtimer_executing);
15925 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15926 		ill->ill_frag_timer_id = 0;
15927 		mutex_exit(&ill->ill_lock);
15928 		return;
15929 	}
15930 	ill->ill_fragtimer_executing = 1;
15931 	mutex_exit(&ill->ill_lock);
15932 
15933 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15934 
15935 	/*
15936 	 * Restart the timer, if we have fragments pending or if someone
15937 	 * wanted us to be scheduled again.
15938 	 */
15939 	mutex_enter(&ill->ill_lock);
15940 	ill->ill_fragtimer_executing = 0;
15941 	ill->ill_frag_timer_id = 0;
15942 	if (frag_pending || ill->ill_fragtimer_needrestart)
15943 		ill_frag_timer_start(ill);
15944 	mutex_exit(&ill->ill_lock);
15945 }
15946 
15947 void
15948 ill_frag_timer_start(ill_t *ill)
15949 {
15950 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15951 
15952 	/* If the ill is closing or opening don't proceed */
15953 	if (ill->ill_state_flags & ILL_CONDEMNED)
15954 		return;
15955 
15956 	if (ill->ill_fragtimer_executing) {
15957 		/*
15958 		 * ill_frag_timer is currently executing. Just record the
15959 		 * the fact that we want the timer to be restarted.
15960 		 * ill_frag_timer will post a timeout before it returns,
15961 		 * ensuring it will be called again.
15962 		 */
15963 		ill->ill_fragtimer_needrestart = 1;
15964 		return;
15965 	}
15966 
15967 	if (ill->ill_frag_timer_id == 0) {
15968 		/*
15969 		 * The timer is neither running nor is the timeout handler
15970 		 * executing. Post a timeout so that ill_frag_timer will be
15971 		 * called
15972 		 */
15973 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15974 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15975 		ill->ill_fragtimer_needrestart = 0;
15976 	}
15977 }
15978 
15979 /*
15980  * This routine is needed for loopback when forwarding multicasts.
15981  *
15982  * IPQoS Notes:
15983  * IPPF processing is done in fanout routines.
15984  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15985  * processing for IPSec packets is done when it comes back in clear.
15986  * NOTE : The callers of this function need to do the ire_refrele for the
15987  *	  ire that is being passed in.
15988  */
15989 void
15990 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15991     ill_t *recv_ill)
15992 {
15993 	ill_t	*ill = (ill_t *)q->q_ptr;
15994 	uint32_t	sum;
15995 	uint32_t	u1;
15996 	uint32_t	u2;
15997 	int		hdr_length;
15998 	boolean_t	mctl_present;
15999 	mblk_t		*first_mp = mp;
16000 	mblk_t		*hada_mp = NULL;
16001 	ipha_t		*inner_ipha;
16002 
16003 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16004 	    "ip_rput_locl_start: q %p", q);
16005 
16006 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16007 
16008 
16009 #define	rptr	((uchar_t *)ipha)
16010 #define	iphs	((uint16_t *)ipha)
16011 
16012 	/*
16013 	 * no UDP or TCP packet should come here anymore.
16014 	 */
16015 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16016 	    (ipha->ipha_protocol != IPPROTO_UDP));
16017 
16018 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16019 	if (mctl_present &&
16020 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16021 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16022 
16023 		/*
16024 		 * It's an IPsec accelerated packet.
16025 		 * Keep a pointer to the data attributes around until
16026 		 * we allocate the ipsec_info_t.
16027 		 */
16028 		IPSECHW_DEBUG(IPSECHW_PKT,
16029 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16030 		hada_mp = first_mp;
16031 		hada_mp->b_cont = NULL;
16032 		/*
16033 		 * Since it is accelerated, it comes directly from
16034 		 * the ill and the data attributes is followed by
16035 		 * the packet data.
16036 		 */
16037 		ASSERT(mp->b_datap->db_type != M_CTL);
16038 		first_mp = mp;
16039 		mctl_present = B_FALSE;
16040 	}
16041 
16042 	/*
16043 	 * IF M_CTL is not present, then ipsec_in_is_secure
16044 	 * should return B_TRUE. There is a case where loopback
16045 	 * packets has an M_CTL in the front with all the
16046 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16047 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16048 	 * packets never comes here, it is safe to ASSERT the
16049 	 * following.
16050 	 */
16051 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16052 
16053 
16054 	/* u1 is # words of IP options */
16055 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16056 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16057 
16058 	if (u1) {
16059 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16060 			if (hada_mp != NULL)
16061 				freemsg(hada_mp);
16062 			return;
16063 		}
16064 	} else {
16065 		/* Check the IP header checksum.  */
16066 #define	uph	((uint16_t *)ipha)
16067 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16068 		    uph[6] + uph[7] + uph[8] + uph[9];
16069 #undef  uph
16070 		/* finish doing IP checksum */
16071 		sum = (sum & 0xFFFF) + (sum >> 16);
16072 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16073 		/*
16074 		 * Don't verify header checksum if this packet is coming
16075 		 * back from AH/ESP as we already did it.
16076 		 */
16077 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16078 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16079 			goto drop_pkt;
16080 		}
16081 	}
16082 
16083 	/*
16084 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16085 	 * might be called more than once for secure packets, count only
16086 	 * the first time.
16087 	 */
16088 	if (!mctl_present) {
16089 		UPDATE_IB_PKT_COUNT(ire);
16090 		ire->ire_last_used_time = lbolt;
16091 	}
16092 
16093 	/* Check for fragmentation offset. */
16094 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16095 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16096 	if (u1) {
16097 		/*
16098 		 * We re-assemble fragments before we do the AH/ESP
16099 		 * processing. Thus, M_CTL should not be present
16100 		 * while we are re-assembling.
16101 		 */
16102 		ASSERT(!mctl_present);
16103 		ASSERT(first_mp == mp);
16104 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16105 			return;
16106 		}
16107 		/*
16108 		 * Make sure that first_mp points back to mp as
16109 		 * the mp we came in with could have changed in
16110 		 * ip_rput_fragment().
16111 		 */
16112 		ipha = (ipha_t *)mp->b_rptr;
16113 		first_mp = mp;
16114 	}
16115 
16116 	/*
16117 	 * Clear hardware checksumming flag as it is currently only
16118 	 * used by TCP and UDP.
16119 	 */
16120 	DB_CKSUMFLAGS(mp) = 0;
16121 
16122 	/* Now we have a complete datagram, destined for this machine. */
16123 	u1 = IPH_HDR_LENGTH(ipha);
16124 	switch (ipha->ipha_protocol) {
16125 	case IPPROTO_ICMP: {
16126 		ire_t		*ire_zone;
16127 		ilm_t		*ilm;
16128 		mblk_t		*mp1;
16129 		zoneid_t	last_zoneid;
16130 
16131 		if (CLASSD(ipha->ipha_dst) &&
16132 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16133 			ASSERT(ire->ire_type == IRE_BROADCAST);
16134 			/*
16135 			 * In the multicast case, applications may have joined
16136 			 * the group from different zones, so we need to deliver
16137 			 * the packet to each of them. Loop through the
16138 			 * multicast memberships structures (ilm) on the receive
16139 			 * ill and send a copy of the packet up each matching
16140 			 * one. However, we don't do this for multicasts sent on
16141 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16142 			 * they must stay in the sender's zone.
16143 			 *
16144 			 * ilm_add_v6() ensures that ilms in the same zone are
16145 			 * contiguous in the ill_ilm list. We use this property
16146 			 * to avoid sending duplicates needed when two
16147 			 * applications in the same zone join the same group on
16148 			 * different logical interfaces: we ignore the ilm if
16149 			 * its zoneid is the same as the last matching one.
16150 			 * In addition, the sending of the packet for
16151 			 * ire_zoneid is delayed until all of the other ilms
16152 			 * have been exhausted.
16153 			 */
16154 			last_zoneid = -1;
16155 			ILM_WALKER_HOLD(recv_ill);
16156 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16157 			    ilm = ilm->ilm_next) {
16158 				if ((ilm->ilm_flags & ILM_DELETED) ||
16159 				    ipha->ipha_dst != ilm->ilm_addr ||
16160 				    ilm->ilm_zoneid == last_zoneid ||
16161 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16162 				    ilm->ilm_zoneid == ALL_ZONES ||
16163 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16164 					continue;
16165 				mp1 = ip_copymsg(first_mp);
16166 				if (mp1 == NULL)
16167 					continue;
16168 				icmp_inbound(q, mp1, B_TRUE, ill,
16169 				    0, sum, mctl_present, B_TRUE,
16170 				    recv_ill, ilm->ilm_zoneid);
16171 				last_zoneid = ilm->ilm_zoneid;
16172 			}
16173 			ILM_WALKER_RELE(recv_ill);
16174 		} else if (ire->ire_type == IRE_BROADCAST) {
16175 			/*
16176 			 * In the broadcast case, there may be many zones
16177 			 * which need a copy of the packet delivered to them.
16178 			 * There is one IRE_BROADCAST per broadcast address
16179 			 * and per zone; we walk those using a helper function.
16180 			 * In addition, the sending of the packet for ire is
16181 			 * delayed until all of the other ires have been
16182 			 * processed.
16183 			 */
16184 			IRB_REFHOLD(ire->ire_bucket);
16185 			ire_zone = NULL;
16186 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16187 			    ire)) != NULL) {
16188 				mp1 = ip_copymsg(first_mp);
16189 				if (mp1 == NULL)
16190 					continue;
16191 
16192 				UPDATE_IB_PKT_COUNT(ire_zone);
16193 				ire_zone->ire_last_used_time = lbolt;
16194 				icmp_inbound(q, mp1, B_TRUE, ill,
16195 				    0, sum, mctl_present, B_TRUE,
16196 				    recv_ill, ire_zone->ire_zoneid);
16197 			}
16198 			IRB_REFRELE(ire->ire_bucket);
16199 		}
16200 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16201 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16202 		    ire->ire_zoneid);
16203 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16204 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16205 		return;
16206 	}
16207 	case IPPROTO_IGMP:
16208 		/*
16209 		 * If we are not willing to accept IGMP packets in clear,
16210 		 * then check with global policy.
16211 		 */
16212 		if (igmp_accept_clear_messages == 0) {
16213 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16214 			    ipha, NULL, mctl_present);
16215 			if (first_mp == NULL)
16216 				return;
16217 		}
16218 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16219 			freemsg(first_mp);
16220 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16221 			BUMP_MIB(&ip_mib, ipInDiscards);
16222 			return;
16223 		}
16224 		if (igmp_input(q, mp, ill)) {
16225 			/* Bad packet - discarded by igmp_input */
16226 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16227 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16228 			if (mctl_present)
16229 				freeb(first_mp);
16230 			return;
16231 		}
16232 		/*
16233 		 * igmp_input() may have pulled up the message so ipha needs to
16234 		 * be reinitialized.
16235 		 */
16236 		ipha = (ipha_t *)mp->b_rptr;
16237 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16238 			/* No user-level listener for IGMP packets */
16239 			goto drop_pkt;
16240 		}
16241 		/* deliver to local raw users */
16242 		break;
16243 	case IPPROTO_PIM:
16244 		/*
16245 		 * If we are not willing to accept PIM packets in clear,
16246 		 * then check with global policy.
16247 		 */
16248 		if (pim_accept_clear_messages == 0) {
16249 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16250 			    ipha, NULL, mctl_present);
16251 			if (first_mp == NULL)
16252 				return;
16253 		}
16254 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16255 			freemsg(first_mp);
16256 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16257 			BUMP_MIB(&ip_mib, ipInDiscards);
16258 			return;
16259 		}
16260 		if (pim_input(q, mp) != 0) {
16261 			/* Bad packet - discarded by pim_input */
16262 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16263 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16264 			if (mctl_present)
16265 				freeb(first_mp);
16266 			return;
16267 		}
16268 
16269 		/*
16270 		 * pim_input() may have pulled up the message so ipha needs to
16271 		 * be reinitialized.
16272 		 */
16273 		ipha = (ipha_t *)mp->b_rptr;
16274 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16275 			/* No user-level listener for PIM packets */
16276 			goto drop_pkt;
16277 		}
16278 		/* deliver to local raw users */
16279 		break;
16280 	case IPPROTO_ENCAP:
16281 		/*
16282 		 * Handle self-encapsulated packets (IP-in-IP where
16283 		 * the inner addresses == the outer addresses).
16284 		 */
16285 		hdr_length = IPH_HDR_LENGTH(ipha);
16286 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16287 		    mp->b_wptr) {
16288 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16289 			    sizeof (ipha_t) - mp->b_rptr)) {
16290 				BUMP_MIB(&ip_mib, ipInDiscards);
16291 				freemsg(first_mp);
16292 				return;
16293 			}
16294 			ipha = (ipha_t *)mp->b_rptr;
16295 		}
16296 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16297 		/*
16298 		 * Check the sanity of the inner IP header.
16299 		 */
16300 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16301 			BUMP_MIB(&ip_mib, ipInDiscards);
16302 			freemsg(first_mp);
16303 			return;
16304 		}
16305 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16306 			BUMP_MIB(&ip_mib, ipInDiscards);
16307 			freemsg(first_mp);
16308 			return;
16309 		}
16310 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16311 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16312 			ipsec_in_t *ii;
16313 
16314 			/*
16315 			 * Self-encapsulated tunnel packet. Remove
16316 			 * the outer IP header and fanout again.
16317 			 * We also need to make sure that the inner
16318 			 * header is pulled up until options.
16319 			 */
16320 			mp->b_rptr = (uchar_t *)inner_ipha;
16321 			ipha = inner_ipha;
16322 			hdr_length = IPH_HDR_LENGTH(ipha);
16323 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16324 				if (!pullupmsg(mp, (uchar_t *)ipha +
16325 				    + hdr_length - mp->b_rptr)) {
16326 					freemsg(first_mp);
16327 					return;
16328 				}
16329 				ipha = (ipha_t *)mp->b_rptr;
16330 			}
16331 			if (!mctl_present) {
16332 				ASSERT(first_mp == mp);
16333 				/*
16334 				 * This means that somebody is sending
16335 				 * Self-encapsualted packets without AH/ESP.
16336 				 * If AH/ESP was present, we would have already
16337 				 * allocated the first_mp.
16338 				 */
16339 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16340 				    NULL) {
16341 					ip1dbg(("ip_proto_input: IPSEC_IN "
16342 					    "allocation failure.\n"));
16343 					BUMP_MIB(&ip_mib, ipInDiscards);
16344 					freemsg(mp);
16345 					return;
16346 				}
16347 				first_mp->b_cont = mp;
16348 			}
16349 			/*
16350 			 * We generally store the ill_index if we need to
16351 			 * do IPSEC processing as we lose the ill queue when
16352 			 * we come back. But in this case, we never should
16353 			 * have to store the ill_index here as it should have
16354 			 * been stored previously when we processed the
16355 			 * AH/ESP header in this routine or for non-ipsec
16356 			 * cases, we still have the queue. But for some bad
16357 			 * packets from the wire, we can get to IPSEC after
16358 			 * this and we better store the index for that case.
16359 			 */
16360 			ill = (ill_t *)q->q_ptr;
16361 			ii = (ipsec_in_t *)first_mp->b_rptr;
16362 			ii->ipsec_in_ill_index =
16363 			    ill->ill_phyint->phyint_ifindex;
16364 			ii->ipsec_in_rill_index =
16365 			    recv_ill->ill_phyint->phyint_ifindex;
16366 			if (ii->ipsec_in_decaps) {
16367 				/*
16368 				 * This packet is self-encapsulated multiple
16369 				 * times. We don't want to recurse infinitely.
16370 				 * To keep it simple, drop the packet.
16371 				 */
16372 				BUMP_MIB(&ip_mib, ipInDiscards);
16373 				freemsg(first_mp);
16374 				return;
16375 			}
16376 			ii->ipsec_in_decaps = B_TRUE;
16377 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16378 			return;
16379 		}
16380 		break;
16381 	case IPPROTO_AH:
16382 	case IPPROTO_ESP: {
16383 		/*
16384 		 * Fast path for AH/ESP. If this is the first time
16385 		 * we are sending a datagram to AH/ESP, allocate
16386 		 * a IPSEC_IN message and prepend it. Otherwise,
16387 		 * just fanout.
16388 		 */
16389 
16390 		int ipsec_rc;
16391 		ipsec_in_t *ii;
16392 
16393 		IP_STAT(ipsec_proto_ahesp);
16394 		if (!mctl_present) {
16395 			ASSERT(first_mp == mp);
16396 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16397 				ip1dbg(("ip_proto_input: IPSEC_IN "
16398 				    "allocation failure.\n"));
16399 				freemsg(hada_mp); /* okay ifnull */
16400 				BUMP_MIB(&ip_mib, ipInDiscards);
16401 				freemsg(mp);
16402 				return;
16403 			}
16404 			/*
16405 			 * Store the ill_index so that when we come back
16406 			 * from IPSEC we ride on the same queue.
16407 			 */
16408 			ill = (ill_t *)q->q_ptr;
16409 			ii = (ipsec_in_t *)first_mp->b_rptr;
16410 			ii->ipsec_in_ill_index =
16411 			    ill->ill_phyint->phyint_ifindex;
16412 			ii->ipsec_in_rill_index =
16413 			    recv_ill->ill_phyint->phyint_ifindex;
16414 			first_mp->b_cont = mp;
16415 			/*
16416 			 * Cache hardware acceleration info.
16417 			 */
16418 			if (hada_mp != NULL) {
16419 				IPSECHW_DEBUG(IPSECHW_PKT,
16420 				    ("ip_rput_local: caching data attr.\n"));
16421 				ii->ipsec_in_accelerated = B_TRUE;
16422 				ii->ipsec_in_da = hada_mp;
16423 				hada_mp = NULL;
16424 			}
16425 		} else {
16426 			ii = (ipsec_in_t *)first_mp->b_rptr;
16427 		}
16428 
16429 		if (!ipsec_loaded()) {
16430 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
16431 			    ire->ire_zoneid);
16432 			return;
16433 		}
16434 
16435 		/* select inbound SA and have IPsec process the pkt */
16436 		if (ipha->ipha_protocol == IPPROTO_ESP) {
16437 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
16438 			if (esph == NULL)
16439 				return;
16440 			ASSERT(ii->ipsec_in_esp_sa != NULL);
16441 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
16442 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
16443 			    first_mp, esph);
16444 		} else {
16445 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
16446 			if (ah == NULL)
16447 				return;
16448 			ASSERT(ii->ipsec_in_ah_sa != NULL);
16449 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
16450 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
16451 			    first_mp, ah);
16452 		}
16453 
16454 		switch (ipsec_rc) {
16455 		case IPSEC_STATUS_SUCCESS:
16456 			break;
16457 		case IPSEC_STATUS_FAILED:
16458 			BUMP_MIB(&ip_mib, ipInDiscards);
16459 			/* FALLTHRU */
16460 		case IPSEC_STATUS_PENDING:
16461 			return;
16462 		}
16463 		/* we're done with IPsec processing, send it up */
16464 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
16465 		return;
16466 	}
16467 	default:
16468 		break;
16469 	}
16470 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
16471 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
16472 		    ire->ire_zoneid));
16473 		goto drop_pkt;
16474 	}
16475 	/*
16476 	 * Handle protocols with which IP is less intimate.  There
16477 	 * can be more than one stream bound to a particular
16478 	 * protocol.  When this is the case, each one gets a copy
16479 	 * of any incoming packets.
16480 	 */
16481 	ip_fanout_proto(q, first_mp, ill, ipha,
16482 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
16483 	    B_TRUE, recv_ill, ire->ire_zoneid);
16484 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16485 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
16486 	return;
16487 
16488 drop_pkt:
16489 	freemsg(first_mp);
16490 	if (hada_mp != NULL)
16491 		freeb(hada_mp);
16492 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16493 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
16494 #undef	rptr
16495 #undef  iphs
16496 
16497 }
16498 
16499 /*
16500  * Update any source route, record route or timestamp options.
16501  * Check that we are at end of strict source route.
16502  * The options have already been checked for sanity in ip_rput_options().
16503  */
16504 static boolean_t
16505 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
16506 {
16507 	ipoptp_t	opts;
16508 	uchar_t		*opt;
16509 	uint8_t		optval;
16510 	uint8_t		optlen;
16511 	ipaddr_t	dst;
16512 	uint32_t	ts;
16513 	ire_t		*dst_ire;
16514 	timestruc_t	now;
16515 
16516 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16517 
16518 	ip2dbg(("ip_rput_local_options\n"));
16519 
16520 	for (optval = ipoptp_first(&opts, ipha);
16521 	    optval != IPOPT_EOL;
16522 	    optval = ipoptp_next(&opts)) {
16523 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16524 		opt = opts.ipoptp_cur;
16525 		optlen = opts.ipoptp_len;
16526 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
16527 		    optval, optlen));
16528 		switch (optval) {
16529 			uint32_t off;
16530 		case IPOPT_SSRR:
16531 		case IPOPT_LSRR:
16532 			off = opt[IPOPT_OFFSET];
16533 			off--;
16534 			if (optlen < IP_ADDR_LEN ||
16535 			    off > optlen - IP_ADDR_LEN) {
16536 				/* End of source route */
16537 				ip1dbg(("ip_rput_local_options: end of SR\n"));
16538 				break;
16539 			}
16540 			/*
16541 			 * This will only happen if two consecutive entries
16542 			 * in the source route contains our address or if
16543 			 * it is a packet with a loose source route which
16544 			 * reaches us before consuming the whole source route
16545 			 */
16546 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
16547 			if (optval == IPOPT_SSRR) {
16548 				goto bad_src_route;
16549 			}
16550 			/*
16551 			 * Hack: instead of dropping the packet truncate the
16552 			 * source route to what has been used by filling the
16553 			 * rest with IPOPT_NOP.
16554 			 */
16555 			opt[IPOPT_OLEN] = (uint8_t)off;
16556 			while (off < optlen) {
16557 				opt[off++] = IPOPT_NOP;
16558 			}
16559 			break;
16560 		case IPOPT_RR:
16561 			off = opt[IPOPT_OFFSET];
16562 			off--;
16563 			if (optlen < IP_ADDR_LEN ||
16564 			    off > optlen - IP_ADDR_LEN) {
16565 				/* No more room - ignore */
16566 				ip1dbg((
16567 				    "ip_rput_local_options: end of RR\n"));
16568 				break;
16569 			}
16570 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16571 			    IP_ADDR_LEN);
16572 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16573 			break;
16574 		case IPOPT_TS:
16575 			/* Insert timestamp if there is romm */
16576 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16577 			case IPOPT_TS_TSONLY:
16578 				off = IPOPT_TS_TIMELEN;
16579 				break;
16580 			case IPOPT_TS_PRESPEC:
16581 			case IPOPT_TS_PRESPEC_RFC791:
16582 				/* Verify that the address matched */
16583 				off = opt[IPOPT_OFFSET] - 1;
16584 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16585 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16586 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16587 				if (dst_ire == NULL) {
16588 					/* Not for us */
16589 					break;
16590 				}
16591 				ire_refrele(dst_ire);
16592 				/* FALLTHRU */
16593 			case IPOPT_TS_TSANDADDR:
16594 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16595 				break;
16596 			default:
16597 				/*
16598 				 * ip_*put_options should have already
16599 				 * dropped this packet.
16600 				 */
16601 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16602 				    "unknown IT - bug in ip_rput_options?\n");
16603 				return (B_TRUE);	/* Keep "lint" happy */
16604 			}
16605 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16606 				/* Increase overflow counter */
16607 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16608 				opt[IPOPT_POS_OV_FLG] =
16609 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16610 				    (off << 4));
16611 				break;
16612 			}
16613 			off = opt[IPOPT_OFFSET] - 1;
16614 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16615 			case IPOPT_TS_PRESPEC:
16616 			case IPOPT_TS_PRESPEC_RFC791:
16617 			case IPOPT_TS_TSANDADDR:
16618 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16619 				    IP_ADDR_LEN);
16620 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16621 				/* FALLTHRU */
16622 			case IPOPT_TS_TSONLY:
16623 				off = opt[IPOPT_OFFSET] - 1;
16624 				/* Compute # of milliseconds since midnight */
16625 				gethrestime(&now);
16626 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16627 				    now.tv_nsec / (NANOSEC / MILLISEC);
16628 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16629 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16630 				break;
16631 			}
16632 			break;
16633 		}
16634 	}
16635 	return (B_TRUE);
16636 
16637 bad_src_route:
16638 	q = WR(q);
16639 	/* make sure we clear any indication of a hardware checksum */
16640 	DB_CKSUMFLAGS(mp) = 0;
16641 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16642 	return (B_FALSE);
16643 
16644 }
16645 
16646 /*
16647  * Process IP options in an inbound packet.  If an option affects the
16648  * effective destination address, return the next hop address via dstp.
16649  * Returns -1 if something fails in which case an ICMP error has been sent
16650  * and mp freed.
16651  */
16652 static int
16653 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16654 {
16655 	ipoptp_t	opts;
16656 	uchar_t		*opt;
16657 	uint8_t		optval;
16658 	uint8_t		optlen;
16659 	ipaddr_t	dst;
16660 	intptr_t	code = 0;
16661 	ire_t		*ire = NULL;
16662 
16663 	ip2dbg(("ip_rput_options\n"));
16664 	dst = ipha->ipha_dst;
16665 	for (optval = ipoptp_first(&opts, ipha);
16666 	    optval != IPOPT_EOL;
16667 	    optval = ipoptp_next(&opts)) {
16668 		opt = opts.ipoptp_cur;
16669 		optlen = opts.ipoptp_len;
16670 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16671 		    optval, optlen));
16672 		/*
16673 		 * Note: we need to verify the checksum before we
16674 		 * modify anything thus this routine only extracts the next
16675 		 * hop dst from any source route.
16676 		 */
16677 		switch (optval) {
16678 			uint32_t off;
16679 		case IPOPT_SSRR:
16680 		case IPOPT_LSRR:
16681 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16682 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16683 			if (ire == NULL) {
16684 				if (optval == IPOPT_SSRR) {
16685 					ip1dbg(("ip_rput_options: not next"
16686 					    " strict source route 0x%x\n",
16687 					    ntohl(dst)));
16688 					code = (char *)&ipha->ipha_dst -
16689 					    (char *)ipha;
16690 					goto param_prob; /* RouterReq's */
16691 				}
16692 				ip2dbg(("ip_rput_options: "
16693 				    "not next source route 0x%x\n",
16694 				    ntohl(dst)));
16695 				break;
16696 			}
16697 			ire_refrele(ire);
16698 
16699 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16700 				ip1dbg((
16701 				    "ip_rput_options: bad option offset\n"));
16702 				code = (char *)&opt[IPOPT_OLEN] -
16703 				    (char *)ipha;
16704 				goto param_prob;
16705 			}
16706 			off = opt[IPOPT_OFFSET];
16707 			off--;
16708 		redo_srr:
16709 			if (optlen < IP_ADDR_LEN ||
16710 			    off > optlen - IP_ADDR_LEN) {
16711 				/* End of source route */
16712 				ip1dbg(("ip_rput_options: end of SR\n"));
16713 				break;
16714 			}
16715 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16716 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16717 			    ntohl(dst)));
16718 
16719 			/*
16720 			 * Check if our address is present more than
16721 			 * once as consecutive hops in source route.
16722 			 * XXX verify per-interface ip_forwarding
16723 			 * for source route?
16724 			 */
16725 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16726 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16727 
16728 			if (ire != NULL) {
16729 				ire_refrele(ire);
16730 				off += IP_ADDR_LEN;
16731 				goto redo_srr;
16732 			}
16733 
16734 			if (dst == htonl(INADDR_LOOPBACK)) {
16735 				ip1dbg(("ip_rput_options: loopback addr in "
16736 				    "source route!\n"));
16737 				goto bad_src_route;
16738 			}
16739 			/*
16740 			 * For strict: verify that dst is directly
16741 			 * reachable.
16742 			 */
16743 			if (optval == IPOPT_SSRR) {
16744 				ire = ire_ftable_lookup(dst, 0, 0,
16745 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16746 				    MBLK_GETLABEL(mp),
16747 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
16748 				if (ire == NULL) {
16749 					ip1dbg(("ip_rput_options: SSRR not "
16750 					    "directly reachable: 0x%x\n",
16751 					    ntohl(dst)));
16752 					goto bad_src_route;
16753 				}
16754 				ire_refrele(ire);
16755 			}
16756 			/*
16757 			 * Defer update of the offset and the record route
16758 			 * until the packet is forwarded.
16759 			 */
16760 			break;
16761 		case IPOPT_RR:
16762 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16763 				ip1dbg((
16764 				    "ip_rput_options: bad option offset\n"));
16765 				code = (char *)&opt[IPOPT_OLEN] -
16766 				    (char *)ipha;
16767 				goto param_prob;
16768 			}
16769 			break;
16770 		case IPOPT_TS:
16771 			/*
16772 			 * Verify that length >= 5 and that there is either
16773 			 * room for another timestamp or that the overflow
16774 			 * counter is not maxed out.
16775 			 */
16776 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16777 			if (optlen < IPOPT_MINLEN_IT) {
16778 				goto param_prob;
16779 			}
16780 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16781 				ip1dbg((
16782 				    "ip_rput_options: bad option offset\n"));
16783 				code = (char *)&opt[IPOPT_OFFSET] -
16784 				    (char *)ipha;
16785 				goto param_prob;
16786 			}
16787 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16788 			case IPOPT_TS_TSONLY:
16789 				off = IPOPT_TS_TIMELEN;
16790 				break;
16791 			case IPOPT_TS_TSANDADDR:
16792 			case IPOPT_TS_PRESPEC:
16793 			case IPOPT_TS_PRESPEC_RFC791:
16794 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16795 				break;
16796 			default:
16797 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16798 				    (char *)ipha;
16799 				goto param_prob;
16800 			}
16801 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16802 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16803 				/*
16804 				 * No room and the overflow counter is 15
16805 				 * already.
16806 				 */
16807 				goto param_prob;
16808 			}
16809 			break;
16810 		}
16811 	}
16812 
16813 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16814 		*dstp = dst;
16815 		return (0);
16816 	}
16817 
16818 	ip1dbg(("ip_rput_options: error processing IP options."));
16819 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16820 
16821 param_prob:
16822 	q = WR(q);
16823 	/* make sure we clear any indication of a hardware checksum */
16824 	DB_CKSUMFLAGS(mp) = 0;
16825 	icmp_param_problem(q, mp, (uint8_t)code);
16826 	return (-1);
16827 
16828 bad_src_route:
16829 	q = WR(q);
16830 	/* make sure we clear any indication of a hardware checksum */
16831 	DB_CKSUMFLAGS(mp) = 0;
16832 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16833 	return (-1);
16834 }
16835 
16836 /*
16837  * IP & ICMP info in >=14 msg's ...
16838  *  - ip fixed part (mib2_ip_t)
16839  *  - icmp fixed part (mib2_icmp_t)
16840  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16841  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16842  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16843  *  - ipRouteAttributeTable (ip 102)	labeled routes
16844  *  - ip multicast membership (ip_member_t)
16845  *  - ip multicast source filtering (ip_grpsrc_t)
16846  *  - igmp fixed part (struct igmpstat)
16847  *  - multicast routing stats (struct mrtstat)
16848  *  - multicast routing vifs (array of struct vifctl)
16849  *  - multicast routing routes (array of struct mfcctl)
16850  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16851  *					One per ill plus one generic
16852  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16853  *					One per ill plus one generic
16854  *  - ipv6RouteEntry			all IPv6 IREs
16855  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
16856  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16857  *  - ipv6AddrEntry			all IPv6 ipifs
16858  *  - ipv6 multicast membership (ipv6_member_t)
16859  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16860  *
16861  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16862  * already present.
16863  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
16864  * already filled in by the caller.
16865  * Return value of 0 indicates that no messages were sent and caller
16866  * should free mpctl.
16867  */
16868 int
16869 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16870 {
16871 
16872 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16873 		return (0);
16874 	}
16875 
16876 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16877 		return (1);
16878 	}
16879 
16880 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16881 		return (1);
16882 	}
16883 
16884 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16885 		return (1);
16886 	}
16887 
16888 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16889 		return (1);
16890 	}
16891 
16892 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16893 		return (1);
16894 	}
16895 
16896 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16897 		return (1);
16898 	}
16899 
16900 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16901 		return (1);
16902 	}
16903 
16904 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16905 		return (1);
16906 	}
16907 
16908 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16909 		return (1);
16910 	}
16911 
16912 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16913 		return (1);
16914 	}
16915 
16916 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16917 		return (1);
16918 	}
16919 
16920 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16921 		return (1);
16922 	}
16923 
16924 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16925 		return (1);
16926 	}
16927 
16928 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16929 		return (1);
16930 	}
16931 
16932 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16933 		return (1);
16934 	}
16935 
16936 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16937 		return (1);
16938 	}
16939 
16940 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16941 		return (1);
16942 	}
16943 	freemsg(mpctl);
16944 	return (1);
16945 }
16946 
16947 
16948 /* Get global IPv4 statistics */
16949 static mblk_t *
16950 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16951 {
16952 	struct opthdr		*optp;
16953 	mblk_t			*mp2ctl;
16954 
16955 	/*
16956 	 * make a copy of the original message
16957 	 */
16958 	mp2ctl = copymsg(mpctl);
16959 
16960 	/* fixed length IP structure... */
16961 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16962 	optp->level = MIB2_IP;
16963 	optp->name = 0;
16964 	SET_MIB(ip_mib.ipForwarding,
16965 	    (WE_ARE_FORWARDING ? 1 : 2));
16966 	SET_MIB(ip_mib.ipDefaultTTL,
16967 	    (uint32_t)ip_def_ttl);
16968 	SET_MIB(ip_mib.ipReasmTimeout,
16969 	    ip_g_frag_timeout);
16970 	SET_MIB(ip_mib.ipAddrEntrySize,
16971 	    sizeof (mib2_ipAddrEntry_t));
16972 	SET_MIB(ip_mib.ipRouteEntrySize,
16973 	    sizeof (mib2_ipRouteEntry_t));
16974 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16975 	    sizeof (mib2_ipNetToMediaEntry_t));
16976 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16977 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16978 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
16979 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
16980 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16981 	    (int)sizeof (ip_mib))) {
16982 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16983 		    (uint_t)sizeof (ip_mib)));
16984 	}
16985 
16986 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16987 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16988 	    (int)optp->level, (int)optp->name, (int)optp->len));
16989 	qreply(q, mpctl);
16990 	return (mp2ctl);
16991 }
16992 
16993 /* Global IPv4 ICMP statistics */
16994 static mblk_t *
16995 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16996 {
16997 	struct opthdr		*optp;
16998 	mblk_t			*mp2ctl;
16999 
17000 	/*
17001 	 * Make a copy of the original message
17002 	 */
17003 	mp2ctl = copymsg(mpctl);
17004 
17005 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17006 	optp->level = MIB2_ICMP;
17007 	optp->name = 0;
17008 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17009 	    (int)sizeof (icmp_mib))) {
17010 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17011 		    (uint_t)sizeof (icmp_mib)));
17012 	}
17013 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17014 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17015 	    (int)optp->level, (int)optp->name, (int)optp->len));
17016 	qreply(q, mpctl);
17017 	return (mp2ctl);
17018 }
17019 
17020 /* Global IPv4 IGMP statistics */
17021 static mblk_t *
17022 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17023 {
17024 	struct opthdr		*optp;
17025 	mblk_t			*mp2ctl;
17026 
17027 	/*
17028 	 * make a copy of the original message
17029 	 */
17030 	mp2ctl = copymsg(mpctl);
17031 
17032 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17033 	optp->level = EXPER_IGMP;
17034 	optp->name = 0;
17035 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17036 	    (int)sizeof (igmpstat))) {
17037 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17038 		    (uint_t)sizeof (igmpstat)));
17039 	}
17040 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17041 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17042 	    (int)optp->level, (int)optp->name, (int)optp->len));
17043 	qreply(q, mpctl);
17044 	return (mp2ctl);
17045 }
17046 
17047 /* Global IPv4 Multicast Routing statistics */
17048 static mblk_t *
17049 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17050 {
17051 	struct opthdr		*optp;
17052 	mblk_t			*mp2ctl;
17053 
17054 	/*
17055 	 * make a copy of the original message
17056 	 */
17057 	mp2ctl = copymsg(mpctl);
17058 
17059 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17060 	optp->level = EXPER_DVMRP;
17061 	optp->name = 0;
17062 	if (!ip_mroute_stats(mpctl->b_cont)) {
17063 		ip0dbg(("ip_mroute_stats: failed\n"));
17064 	}
17065 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17066 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17067 	    (int)optp->level, (int)optp->name, (int)optp->len));
17068 	qreply(q, mpctl);
17069 	return (mp2ctl);
17070 }
17071 
17072 /* IPv4 address information */
17073 static mblk_t *
17074 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17075 {
17076 	struct opthdr		*optp;
17077 	mblk_t			*mp2ctl;
17078 	mblk_t			*mp_tail = NULL;
17079 	ill_t			*ill;
17080 	ipif_t			*ipif;
17081 	uint_t			bitval;
17082 	mib2_ipAddrEntry_t	mae;
17083 	zoneid_t		zoneid;
17084 	ill_walk_context_t ctx;
17085 
17086 	/*
17087 	 * make a copy of the original message
17088 	 */
17089 	mp2ctl = copymsg(mpctl);
17090 
17091 	/* ipAddrEntryTable */
17092 
17093 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17094 	optp->level = MIB2_IP;
17095 	optp->name = MIB2_IP_ADDR;
17096 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17097 
17098 	rw_enter(&ill_g_lock, RW_READER);
17099 	ill = ILL_START_WALK_V4(&ctx);
17100 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17101 		for (ipif = ill->ill_ipif; ipif != NULL;
17102 		    ipif = ipif->ipif_next) {
17103 			if (ipif->ipif_zoneid != zoneid &&
17104 			    ipif->ipif_zoneid != ALL_ZONES)
17105 				continue;
17106 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17107 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17108 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17109 
17110 			(void) ipif_get_name(ipif,
17111 			    mae.ipAdEntIfIndex.o_bytes,
17112 			    OCTET_LENGTH);
17113 			mae.ipAdEntIfIndex.o_length =
17114 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17115 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17116 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17117 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17118 			mae.ipAdEntInfo.ae_subnet_len =
17119 			    ip_mask_to_plen(ipif->ipif_net_mask);
17120 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17121 			for (bitval = 1;
17122 			    bitval &&
17123 			    !(bitval & ipif->ipif_brd_addr);
17124 			    bitval <<= 1)
17125 				noop;
17126 			mae.ipAdEntBcastAddr = bitval;
17127 			mae.ipAdEntReasmMaxSize = 65535;
17128 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17129 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17130 			mae.ipAdEntInfo.ae_broadcast_addr =
17131 			    ipif->ipif_brd_addr;
17132 			mae.ipAdEntInfo.ae_pp_dst_addr =
17133 			    ipif->ipif_pp_dst_addr;
17134 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17135 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17136 
17137 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17138 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17139 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17140 				    "allocate %u bytes\n",
17141 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17142 			}
17143 		}
17144 	}
17145 	rw_exit(&ill_g_lock);
17146 
17147 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17148 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17149 	    (int)optp->level, (int)optp->name, (int)optp->len));
17150 	qreply(q, mpctl);
17151 	return (mp2ctl);
17152 }
17153 
17154 /* IPv6 address information */
17155 static mblk_t *
17156 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17157 {
17158 	struct opthdr		*optp;
17159 	mblk_t			*mp2ctl;
17160 	mblk_t			*mp_tail = NULL;
17161 	ill_t			*ill;
17162 	ipif_t			*ipif;
17163 	mib2_ipv6AddrEntry_t	mae6;
17164 	zoneid_t		zoneid;
17165 	ill_walk_context_t	ctx;
17166 
17167 	/*
17168 	 * make a copy of the original message
17169 	 */
17170 	mp2ctl = copymsg(mpctl);
17171 
17172 	/* ipv6AddrEntryTable */
17173 
17174 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17175 	optp->level = MIB2_IP6;
17176 	optp->name = MIB2_IP6_ADDR;
17177 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17178 
17179 	rw_enter(&ill_g_lock, RW_READER);
17180 	ill = ILL_START_WALK_V6(&ctx);
17181 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17182 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17183 			if (ipif->ipif_zoneid != zoneid &&
17184 			    ipif->ipif_zoneid != ALL_ZONES)
17185 				continue;
17186 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17187 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17188 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17189 
17190 			(void) ipif_get_name(ipif,
17191 			    mae6.ipv6AddrIfIndex.o_bytes,
17192 			    OCTET_LENGTH);
17193 			mae6.ipv6AddrIfIndex.o_length =
17194 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17195 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17196 			mae6.ipv6AddrPfxLength =
17197 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17198 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17199 			mae6.ipv6AddrInfo.ae_subnet_len =
17200 			    mae6.ipv6AddrPfxLength;
17201 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17202 
17203 			/* Type: stateless(1), stateful(2), unknown(3) */
17204 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17205 				mae6.ipv6AddrType = 1;
17206 			else
17207 				mae6.ipv6AddrType = 2;
17208 			/* Anycast: true(1), false(2) */
17209 			if (ipif->ipif_flags & IPIF_ANYCAST)
17210 				mae6.ipv6AddrAnycastFlag = 1;
17211 			else
17212 				mae6.ipv6AddrAnycastFlag = 2;
17213 
17214 			/*
17215 			 * Address status: preferred(1), deprecated(2),
17216 			 * invalid(3), inaccessible(4), unknown(5)
17217 			 */
17218 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17219 				mae6.ipv6AddrStatus = 3;
17220 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17221 				mae6.ipv6AddrStatus = 2;
17222 			else
17223 				mae6.ipv6AddrStatus = 1;
17224 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17225 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17226 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17227 						ipif->ipif_v6pp_dst_addr;
17228 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17229 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17230 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17231 				(char *)&mae6,
17232 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17233 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17234 				    "allocate %u bytes\n",
17235 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17236 			}
17237 		}
17238 	}
17239 	rw_exit(&ill_g_lock);
17240 
17241 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17242 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17243 	    (int)optp->level, (int)optp->name, (int)optp->len));
17244 	qreply(q, mpctl);
17245 	return (mp2ctl);
17246 }
17247 
17248 /* IPv4 multicast group membership. */
17249 static mblk_t *
17250 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17251 {
17252 	struct opthdr		*optp;
17253 	mblk_t			*mp2ctl;
17254 	ill_t			*ill;
17255 	ipif_t			*ipif;
17256 	ilm_t			*ilm;
17257 	ip_member_t		ipm;
17258 	mblk_t			*mp_tail = NULL;
17259 	ill_walk_context_t	ctx;
17260 	zoneid_t		zoneid;
17261 
17262 	/*
17263 	 * make a copy of the original message
17264 	 */
17265 	mp2ctl = copymsg(mpctl);
17266 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17267 
17268 	/* ipGroupMember table */
17269 	optp = (struct opthdr *)&mpctl->b_rptr[
17270 	    sizeof (struct T_optmgmt_ack)];
17271 	optp->level = MIB2_IP;
17272 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17273 
17274 	rw_enter(&ill_g_lock, RW_READER);
17275 	ill = ILL_START_WALK_V4(&ctx);
17276 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17277 		ILM_WALKER_HOLD(ill);
17278 		for (ipif = ill->ill_ipif; ipif != NULL;
17279 		    ipif = ipif->ipif_next) {
17280 			if (ipif->ipif_zoneid != zoneid &&
17281 			    ipif->ipif_zoneid != ALL_ZONES)
17282 				continue;	/* not this zone */
17283 			(void) ipif_get_name(ipif,
17284 			    ipm.ipGroupMemberIfIndex.o_bytes,
17285 			    OCTET_LENGTH);
17286 			ipm.ipGroupMemberIfIndex.o_length =
17287 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17288 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17289 				ASSERT(ilm->ilm_ipif != NULL);
17290 				ASSERT(ilm->ilm_ill == NULL);
17291 				if (ilm->ilm_ipif != ipif)
17292 					continue;
17293 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17294 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17295 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17296 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17297 				    (char *)&ipm, (int)sizeof (ipm))) {
17298 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17299 					    "failed to allocate %u bytes\n",
17300 						(uint_t)sizeof (ipm)));
17301 				}
17302 			}
17303 		}
17304 		ILM_WALKER_RELE(ill);
17305 	}
17306 	rw_exit(&ill_g_lock);
17307 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17308 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17309 	    (int)optp->level, (int)optp->name, (int)optp->len));
17310 	qreply(q, mpctl);
17311 	return (mp2ctl);
17312 }
17313 
17314 /* IPv6 multicast group membership. */
17315 static mblk_t *
17316 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17317 {
17318 	struct opthdr		*optp;
17319 	mblk_t			*mp2ctl;
17320 	ill_t			*ill;
17321 	ilm_t			*ilm;
17322 	ipv6_member_t		ipm6;
17323 	mblk_t			*mp_tail = NULL;
17324 	ill_walk_context_t	ctx;
17325 	zoneid_t		zoneid;
17326 
17327 	/*
17328 	 * make a copy of the original message
17329 	 */
17330 	mp2ctl = copymsg(mpctl);
17331 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17332 
17333 	/* ip6GroupMember table */
17334 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17335 	optp->level = MIB2_IP6;
17336 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17337 
17338 	rw_enter(&ill_g_lock, RW_READER);
17339 	ill = ILL_START_WALK_V6(&ctx);
17340 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17341 		ILM_WALKER_HOLD(ill);
17342 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17343 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17344 			ASSERT(ilm->ilm_ipif == NULL);
17345 			ASSERT(ilm->ilm_ill != NULL);
17346 			if (ilm->ilm_zoneid != zoneid)
17347 				continue;	/* not this zone */
17348 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17349 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17350 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17351 			if (!snmp_append_data2(mpctl->b_cont,
17352 			    &mp_tail,
17353 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17354 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17355 				    "failed to allocate %u bytes\n",
17356 				    (uint_t)sizeof (ipm6)));
17357 			}
17358 		}
17359 		ILM_WALKER_RELE(ill);
17360 	}
17361 	rw_exit(&ill_g_lock);
17362 
17363 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17364 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17365 	    (int)optp->level, (int)optp->name, (int)optp->len));
17366 	qreply(q, mpctl);
17367 	return (mp2ctl);
17368 }
17369 
17370 /* IP multicast filtered sources */
17371 static mblk_t *
17372 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17373 {
17374 	struct opthdr		*optp;
17375 	mblk_t			*mp2ctl;
17376 	ill_t			*ill;
17377 	ipif_t			*ipif;
17378 	ilm_t			*ilm;
17379 	ip_grpsrc_t		ips;
17380 	mblk_t			*mp_tail = NULL;
17381 	ill_walk_context_t	ctx;
17382 	zoneid_t		zoneid;
17383 	int			i;
17384 	slist_t			*sl;
17385 
17386 	/*
17387 	 * make a copy of the original message
17388 	 */
17389 	mp2ctl = copymsg(mpctl);
17390 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17391 
17392 	/* ipGroupSource table */
17393 	optp = (struct opthdr *)&mpctl->b_rptr[
17394 	    sizeof (struct T_optmgmt_ack)];
17395 	optp->level = MIB2_IP;
17396 	optp->name = EXPER_IP_GROUP_SOURCES;
17397 
17398 	rw_enter(&ill_g_lock, RW_READER);
17399 	ill = ILL_START_WALK_V4(&ctx);
17400 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17401 		ILM_WALKER_HOLD(ill);
17402 		for (ipif = ill->ill_ipif; ipif != NULL;
17403 		    ipif = ipif->ipif_next) {
17404 			if (ipif->ipif_zoneid != zoneid)
17405 				continue;	/* not this zone */
17406 			(void) ipif_get_name(ipif,
17407 			    ips.ipGroupSourceIfIndex.o_bytes,
17408 			    OCTET_LENGTH);
17409 			ips.ipGroupSourceIfIndex.o_length =
17410 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17411 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17412 				ASSERT(ilm->ilm_ipif != NULL);
17413 				ASSERT(ilm->ilm_ill == NULL);
17414 				sl = ilm->ilm_filter;
17415 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17416 					continue;
17417 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17418 				for (i = 0; i < sl->sl_numsrc; i++) {
17419 					if (!IN6_IS_ADDR_V4MAPPED(
17420 					    &sl->sl_addr[i]))
17421 						continue;
17422 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
17423 					    ips.ipGroupSourceAddress);
17424 					if (snmp_append_data2(mpctl->b_cont,
17425 					    &mp_tail, (char *)&ips,
17426 					    (int)sizeof (ips)) == 0) {
17427 						ip1dbg(("ip_snmp_get_mib2_"
17428 						    "ip_group_src: failed to "
17429 						    "allocate %u bytes\n",
17430 						    (uint_t)sizeof (ips)));
17431 					}
17432 				}
17433 			}
17434 		}
17435 		ILM_WALKER_RELE(ill);
17436 	}
17437 	rw_exit(&ill_g_lock);
17438 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17439 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17440 	    (int)optp->level, (int)optp->name, (int)optp->len));
17441 	qreply(q, mpctl);
17442 	return (mp2ctl);
17443 }
17444 
17445 /* IPv6 multicast filtered sources. */
17446 static mblk_t *
17447 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
17448 {
17449 	struct opthdr		*optp;
17450 	mblk_t			*mp2ctl;
17451 	ill_t			*ill;
17452 	ilm_t			*ilm;
17453 	ipv6_grpsrc_t		ips6;
17454 	mblk_t			*mp_tail = NULL;
17455 	ill_walk_context_t	ctx;
17456 	zoneid_t		zoneid;
17457 	int			i;
17458 	slist_t			*sl;
17459 
17460 	/*
17461 	 * make a copy of the original message
17462 	 */
17463 	mp2ctl = copymsg(mpctl);
17464 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17465 
17466 	/* ip6GroupMember table */
17467 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17468 	optp->level = MIB2_IP6;
17469 	optp->name = EXPER_IP6_GROUP_SOURCES;
17470 
17471 	rw_enter(&ill_g_lock, RW_READER);
17472 	ill = ILL_START_WALK_V6(&ctx);
17473 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17474 		ILM_WALKER_HOLD(ill);
17475 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
17476 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17477 			ASSERT(ilm->ilm_ipif == NULL);
17478 			ASSERT(ilm->ilm_ill != NULL);
17479 			sl = ilm->ilm_filter;
17480 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
17481 				continue;
17482 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
17483 			for (i = 0; i < sl->sl_numsrc; i++) {
17484 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
17485 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17486 				    (char *)&ips6, (int)sizeof (ips6))) {
17487 					ip1dbg(("ip_snmp_get_mib2_ip6_"
17488 					    "group_src: failed to allocate "
17489 					    "%u bytes\n",
17490 					    (uint_t)sizeof (ips6)));
17491 				}
17492 			}
17493 		}
17494 		ILM_WALKER_RELE(ill);
17495 	}
17496 	rw_exit(&ill_g_lock);
17497 
17498 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17499 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17500 	    (int)optp->level, (int)optp->name, (int)optp->len));
17501 	qreply(q, mpctl);
17502 	return (mp2ctl);
17503 }
17504 
17505 /* Multicast routing virtual interface table. */
17506 static mblk_t *
17507 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
17508 {
17509 	struct opthdr		*optp;
17510 	mblk_t			*mp2ctl;
17511 
17512 	/*
17513 	 * make a copy of the original message
17514 	 */
17515 	mp2ctl = copymsg(mpctl);
17516 
17517 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17518 	optp->level = EXPER_DVMRP;
17519 	optp->name = EXPER_DVMRP_VIF;
17520 	if (!ip_mroute_vif(mpctl->b_cont)) {
17521 		ip0dbg(("ip_mroute_vif: failed\n"));
17522 	}
17523 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17524 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
17525 	    (int)optp->level, (int)optp->name, (int)optp->len));
17526 	qreply(q, mpctl);
17527 	return (mp2ctl);
17528 }
17529 
17530 /* Multicast routing table. */
17531 static mblk_t *
17532 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
17533 {
17534 	struct opthdr		*optp;
17535 	mblk_t			*mp2ctl;
17536 
17537 	/*
17538 	 * make a copy of the original message
17539 	 */
17540 	mp2ctl = copymsg(mpctl);
17541 
17542 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17543 	optp->level = EXPER_DVMRP;
17544 	optp->name = EXPER_DVMRP_MRT;
17545 	if (!ip_mroute_mrt(mpctl->b_cont)) {
17546 		ip0dbg(("ip_mroute_mrt: failed\n"));
17547 	}
17548 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17549 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
17550 	    (int)optp->level, (int)optp->name, (int)optp->len));
17551 	qreply(q, mpctl);
17552 	return (mp2ctl);
17553 }
17554 
17555 /*
17556  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
17557  * in one IRE walk.
17558  */
17559 static mblk_t *
17560 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
17561 {
17562 	struct opthdr	*optp;
17563 	mblk_t		*mp2ctl;	/* Returned */
17564 	mblk_t		*mp3ctl;	/* nettomedia */
17565 	mblk_t		*mp4ctl;	/* routeattrs */
17566 	iproutedata_t	ird;
17567 	zoneid_t	zoneid;
17568 
17569 	/*
17570 	 * make copies of the original message
17571 	 *	- mp2ctl is returned unchanged to the caller for his use
17572 	 *	- mpctl is sent upstream as ipRouteEntryTable
17573 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
17574 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
17575 	 */
17576 	mp2ctl = copymsg(mpctl);
17577 	mp3ctl = copymsg(mpctl);
17578 	mp4ctl = copymsg(mpctl);
17579 	if (mp3ctl == NULL || mp4ctl == NULL) {
17580 		freemsg(mp4ctl);
17581 		freemsg(mp3ctl);
17582 		freemsg(mp2ctl);
17583 		freemsg(mpctl);
17584 		return (NULL);
17585 	}
17586 
17587 	bzero(&ird, sizeof (ird));
17588 
17589 	ird.ird_route.lp_head = mpctl->b_cont;
17590 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17591 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17592 
17593 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17594 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
17595 	if (zoneid == GLOBAL_ZONEID) {
17596 		/*
17597 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17598 		 * the sys_net_config privilege, it can only run in the global
17599 		 * zone, so we don't display these IREs in the other zones.
17600 		 */
17601 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
17602 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
17603 	}
17604 
17605 	/* ipRouteEntryTable in mpctl */
17606 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17607 	optp->level = MIB2_IP;
17608 	optp->name = MIB2_IP_ROUTE;
17609 	optp->len = msgdsize(ird.ird_route.lp_head);
17610 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17611 	    (int)optp->level, (int)optp->name, (int)optp->len));
17612 	qreply(q, mpctl);
17613 
17614 	/* ipNetToMediaEntryTable in mp3ctl */
17615 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17616 	optp->level = MIB2_IP;
17617 	optp->name = MIB2_IP_MEDIA;
17618 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17619 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17620 	    (int)optp->level, (int)optp->name, (int)optp->len));
17621 	qreply(q, mp3ctl);
17622 
17623 	/* ipRouteAttributeTable in mp4ctl */
17624 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17625 	optp->level = MIB2_IP;
17626 	optp->name = EXPER_IP_RTATTR;
17627 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17628 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17629 	    (int)optp->level, (int)optp->name, (int)optp->len));
17630 	if (optp->len == 0)
17631 		freemsg(mp4ctl);
17632 	else
17633 		qreply(q, mp4ctl);
17634 
17635 	return (mp2ctl);
17636 }
17637 
17638 /*
17639  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
17640  * ipv6NetToMediaEntryTable in an NDP walk.
17641  */
17642 static mblk_t *
17643 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17644 {
17645 	struct opthdr	*optp;
17646 	mblk_t		*mp2ctl;	/* Returned */
17647 	mblk_t		*mp3ctl;	/* nettomedia */
17648 	mblk_t		*mp4ctl;	/* routeattrs */
17649 	iproutedata_t	ird;
17650 	zoneid_t	zoneid;
17651 
17652 	/*
17653 	 * make copies of the original message
17654 	 *	- mp2ctl is returned unchanged to the caller for his use
17655 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
17656 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
17657 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
17658 	 */
17659 	mp2ctl = copymsg(mpctl);
17660 	mp3ctl = copymsg(mpctl);
17661 	mp4ctl = copymsg(mpctl);
17662 	if (mp3ctl == NULL || mp4ctl == NULL) {
17663 		freemsg(mp4ctl);
17664 		freemsg(mp3ctl);
17665 		freemsg(mp2ctl);
17666 		freemsg(mpctl);
17667 		return (NULL);
17668 	}
17669 
17670 	bzero(&ird, sizeof (ird));
17671 
17672 	ird.ird_route.lp_head = mpctl->b_cont;
17673 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17674 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17675 
17676 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17677 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
17678 
17679 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17680 	optp->level = MIB2_IP6;
17681 	optp->name = MIB2_IP6_ROUTE;
17682 	optp->len = msgdsize(ird.ird_route.lp_head);
17683 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17684 	    (int)optp->level, (int)optp->name, (int)optp->len));
17685 	qreply(q, mpctl);
17686 
17687 	/* ipv6NetToMediaEntryTable in mp3ctl */
17688 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
17689 
17690 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17691 	optp->level = MIB2_IP6;
17692 	optp->name = MIB2_IP6_MEDIA;
17693 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17694 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17695 	    (int)optp->level, (int)optp->name, (int)optp->len));
17696 	qreply(q, mp3ctl);
17697 
17698 	/* ipv6RouteAttributeTable in mp4ctl */
17699 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17700 	optp->level = MIB2_IP6;
17701 	optp->name = EXPER_IP_RTATTR;
17702 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17703 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17704 	    (int)optp->level, (int)optp->name, (int)optp->len));
17705 	if (optp->len == 0)
17706 		freemsg(mp4ctl);
17707 	else
17708 		qreply(q, mp4ctl);
17709 
17710 	return (mp2ctl);
17711 }
17712 
17713 /*
17714  * ICMPv6 mib: One per ill
17715  */
17716 static mblk_t *
17717 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17718 {
17719 	struct opthdr		*optp;
17720 	mblk_t			*mp2ctl;
17721 	ill_t			*ill;
17722 	ill_walk_context_t	ctx;
17723 	mblk_t			*mp_tail = NULL;
17724 
17725 	/*
17726 	 * Make a copy of the original message
17727 	 */
17728 	mp2ctl = copymsg(mpctl);
17729 
17730 	/* fixed length IPv6 structure ... */
17731 
17732 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17733 	optp->level = MIB2_IP6;
17734 	optp->name = 0;
17735 	/* Include "unknown interface" ip6_mib */
17736 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17737 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17738 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17739 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17740 	    sizeof (mib2_ipv6IfStatsEntry_t));
17741 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17742 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17743 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17744 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17745 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17746 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17747 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17748 	    (int)sizeof (ip6_mib))) {
17749 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17750 		    (uint_t)sizeof (ip6_mib)));
17751 	}
17752 
17753 	rw_enter(&ill_g_lock, RW_READER);
17754 	ill = ILL_START_WALK_V6(&ctx);
17755 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17756 		ill->ill_ip6_mib->ipv6IfIndex =
17757 		    ill->ill_phyint->phyint_ifindex;
17758 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17759 		    ipv6_forward ? 1 : 2);
17760 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17761 		    ill->ill_max_hops);
17762 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17763 		    sizeof (mib2_ipv6IfStatsEntry_t));
17764 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17765 		    sizeof (mib2_ipv6AddrEntry_t));
17766 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17767 		    sizeof (mib2_ipv6RouteEntry_t));
17768 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17769 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17770 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17771 		    sizeof (ipv6_member_t));
17772 
17773 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17774 		    (char *)ill->ill_ip6_mib,
17775 		    (int)sizeof (*ill->ill_ip6_mib))) {
17776 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17777 				"%u bytes\n",
17778 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17779 		}
17780 	}
17781 	rw_exit(&ill_g_lock);
17782 
17783 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17784 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17785 	    (int)optp->level, (int)optp->name, (int)optp->len));
17786 	qreply(q, mpctl);
17787 	return (mp2ctl);
17788 }
17789 
17790 /*
17791  * ICMPv6 mib: One per ill
17792  */
17793 static mblk_t *
17794 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17795 {
17796 	struct opthdr		*optp;
17797 	mblk_t			*mp2ctl;
17798 	ill_t			*ill;
17799 	ill_walk_context_t	ctx;
17800 	mblk_t			*mp_tail = NULL;
17801 	/*
17802 	 * Make a copy of the original message
17803 	 */
17804 	mp2ctl = copymsg(mpctl);
17805 
17806 	/* fixed length ICMPv6 structure ... */
17807 
17808 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17809 	optp->level = MIB2_ICMP6;
17810 	optp->name = 0;
17811 	/* Include "unknown interface" icmp6_mib */
17812 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17813 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17814 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17815 	    (int)sizeof (icmp6_mib))) {
17816 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17817 		    (uint_t)sizeof (icmp6_mib)));
17818 	}
17819 
17820 	rw_enter(&ill_g_lock, RW_READER);
17821 	ill = ILL_START_WALK_V6(&ctx);
17822 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17823 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17824 		    ill->ill_phyint->phyint_ifindex;
17825 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17826 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17827 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17828 		    (char *)ill->ill_icmp6_mib,
17829 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17830 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17831 			    "%u bytes\n",
17832 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17833 		}
17834 	}
17835 	rw_exit(&ill_g_lock);
17836 
17837 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17838 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17839 	    (int)optp->level, (int)optp->name, (int)optp->len));
17840 	qreply(q, mpctl);
17841 	return (mp2ctl);
17842 }
17843 
17844 /*
17845  * ire_walk routine to create both ipRouteEntryTable and
17846  * ipNetToMediaEntryTable in one IRE walk
17847  */
17848 static void
17849 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
17850 {
17851 	ill_t				*ill;
17852 	ipif_t				*ipif;
17853 	mblk_t				*llmp;
17854 	dl_unitdata_req_t		*dlup;
17855 	mib2_ipRouteEntry_t		*re;
17856 	mib2_ipNetToMediaEntry_t	ntme;
17857 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
17858 	ipaddr_t			gw_addr;
17859 	tsol_ire_gw_secattr_t		*attrp;
17860 	tsol_gc_t			*gc = NULL;
17861 	tsol_gcgrp_t			*gcgrp = NULL;
17862 	uint_t				sacnt = 0;
17863 	int				i;
17864 
17865 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17866 
17867 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
17868 		return;
17869 
17870 	if ((attrp = ire->ire_gw_secattr) != NULL) {
17871 		mutex_enter(&attrp->igsa_lock);
17872 		if ((gc = attrp->igsa_gc) != NULL) {
17873 			gcgrp = gc->gc_grp;
17874 			ASSERT(gcgrp != NULL);
17875 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17876 			sacnt = 1;
17877 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
17878 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17879 			gc = gcgrp->gcgrp_head;
17880 			sacnt = gcgrp->gcgrp_count;
17881 		}
17882 		mutex_exit(&attrp->igsa_lock);
17883 
17884 		/* do nothing if there's no gc to report */
17885 		if (gc == NULL) {
17886 			ASSERT(sacnt == 0);
17887 			if (gcgrp != NULL) {
17888 				/* we might as well drop the lock now */
17889 				rw_exit(&gcgrp->gcgrp_rwlock);
17890 				gcgrp = NULL;
17891 			}
17892 			attrp = NULL;
17893 		}
17894 
17895 		ASSERT(gc == NULL || (gcgrp != NULL &&
17896 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
17897 	}
17898 	ASSERT(sacnt == 0 || gc != NULL);
17899 
17900 	if (sacnt != 0 &&
17901 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
17902 		kmem_free(re, sizeof (*re));
17903 		rw_exit(&gcgrp->gcgrp_rwlock);
17904 		return;
17905 	}
17906 
17907 	/*
17908 	 * Return all IRE types for route table... let caller pick and choose
17909 	 */
17910 	re->ipRouteDest = ire->ire_addr;
17911 	ipif = ire->ire_ipif;
17912 	re->ipRouteIfIndex.o_length = 0;
17913 	if (ire->ire_type == IRE_CACHE) {
17914 		ill = (ill_t *)ire->ire_stq->q_ptr;
17915 		re->ipRouteIfIndex.o_length =
17916 		    ill->ill_name_length == 0 ? 0 :
17917 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17918 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
17919 		    re->ipRouteIfIndex.o_length);
17920 	} else if (ipif != NULL) {
17921 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
17922 		    OCTET_LENGTH);
17923 		re->ipRouteIfIndex.o_length =
17924 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
17925 	}
17926 	re->ipRouteMetric1 = -1;
17927 	re->ipRouteMetric2 = -1;
17928 	re->ipRouteMetric3 = -1;
17929 	re->ipRouteMetric4 = -1;
17930 
17931 	gw_addr = ire->ire_gateway_addr;
17932 
17933 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17934 		re->ipRouteNextHop = ire->ire_src_addr;
17935 	else
17936 		re->ipRouteNextHop = gw_addr;
17937 	/* indirect(4), direct(3), or invalid(2) */
17938 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17939 		re->ipRouteType = 2;
17940 	else
17941 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
17942 	re->ipRouteProto = -1;
17943 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17944 	re->ipRouteMask = ire->ire_mask;
17945 	re->ipRouteMetric5 = -1;
17946 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
17947 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
17948 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17949 	llmp = ire->ire_dlureq_mp;
17950 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
17951 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
17952 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
17953 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17954 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17955 	re->ipRouteInfo.re_flags	= ire->ire_flags;
17956 	re->ipRouteInfo.re_in_ill.o_length = 0;
17957 	if (ire->ire_in_ill != NULL) {
17958 		re->ipRouteInfo.re_in_ill.o_length =
17959 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17960 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17961 		bcopy(ire->ire_in_ill->ill_name,
17962 		    re->ipRouteInfo.re_in_ill.o_bytes,
17963 		    re->ipRouteInfo.re_in_ill.o_length);
17964 	}
17965 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17966 
17967 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
17968 	    (char *)re, (int)sizeof (*re))) {
17969 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17970 		    (uint_t)sizeof (*re)));
17971 	}
17972 
17973 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
17974 		iaeptr->iae_routeidx = ird->ird_idx;
17975 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
17976 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
17977 	}
17978 
17979 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
17980 	    (char *)iae, sacnt * sizeof (*iae))) {
17981 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17982 		    (unsigned)(sacnt * sizeof (*iae))));
17983 	}
17984 
17985 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17986 		goto done;
17987 	/*
17988 	 * only IRE_CACHE entries that are for a directly connected subnet
17989 	 * get appended to net -> phys addr table
17990 	 * (others in arp)
17991 	 */
17992 	ntme.ipNetToMediaIfIndex.o_length = 0;
17993 	ill = ire_to_ill(ire);
17994 	ASSERT(ill != NULL);
17995 	ntme.ipNetToMediaIfIndex.o_length =
17996 	    ill->ill_name_length == 0 ? 0 :
17997 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17998 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17999 		    ntme.ipNetToMediaIfIndex.o_length);
18000 
18001 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18002 	if (llmp) {
18003 		uchar_t *addr;
18004 
18005 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18006 		/* Remove sap from  address */
18007 		if (ill->ill_sap_length < 0)
18008 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18009 		else
18010 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18011 			    ill->ill_sap_length;
18012 
18013 		ntme.ipNetToMediaPhysAddress.o_length =
18014 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18015 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18016 		    ntme.ipNetToMediaPhysAddress.o_length);
18017 	}
18018 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18019 	/* assume dynamic (may be changed in arp) */
18020 	ntme.ipNetToMediaType = 3;
18021 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18022 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18023 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18024 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18025 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18026 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18027 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18028 		    (uint_t)sizeof (ntme)));
18029 	}
18030 done:
18031 	/* bump route index for next pass */
18032 	ird->ird_idx++;
18033 
18034 	kmem_free(re, sizeof (*re));
18035 	if (sacnt != 0)
18036 		kmem_free(iae, sacnt * sizeof (*iae));
18037 
18038 	if (gcgrp != NULL)
18039 		rw_exit(&gcgrp->gcgrp_rwlock);
18040 }
18041 
18042 /*
18043  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18044  */
18045 static void
18046 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18047 {
18048 	ill_t				*ill;
18049 	ipif_t				*ipif;
18050 	mib2_ipv6RouteEntry_t		*re;
18051 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18052 	in6_addr_t			gw_addr_v6;
18053 	tsol_ire_gw_secattr_t		*attrp;
18054 	tsol_gc_t			*gc = NULL;
18055 	tsol_gcgrp_t			*gcgrp = NULL;
18056 	uint_t				sacnt = 0;
18057 	int				i;
18058 
18059 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18060 
18061 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18062 		return;
18063 
18064 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18065 		mutex_enter(&attrp->igsa_lock);
18066 		if ((gc = attrp->igsa_gc) != NULL) {
18067 			gcgrp = gc->gc_grp;
18068 			ASSERT(gcgrp != NULL);
18069 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18070 			sacnt = 1;
18071 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18072 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18073 			gc = gcgrp->gcgrp_head;
18074 			sacnt = gcgrp->gcgrp_count;
18075 		}
18076 		mutex_exit(&attrp->igsa_lock);
18077 
18078 		/* do nothing if there's no gc to report */
18079 		if (gc == NULL) {
18080 			ASSERT(sacnt == 0);
18081 			if (gcgrp != NULL) {
18082 				/* we might as well drop the lock now */
18083 				rw_exit(&gcgrp->gcgrp_rwlock);
18084 				gcgrp = NULL;
18085 			}
18086 			attrp = NULL;
18087 		}
18088 
18089 		ASSERT(gc == NULL || (gcgrp != NULL &&
18090 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18091 	}
18092 	ASSERT(sacnt == 0 || gc != NULL);
18093 
18094 	if (sacnt != 0 &&
18095 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18096 		kmem_free(re, sizeof (*re));
18097 		rw_exit(&gcgrp->gcgrp_rwlock);
18098 		return;
18099 	}
18100 
18101 	/*
18102 	 * Return all IRE types for route table... let caller pick and choose
18103 	 */
18104 	re->ipv6RouteDest = ire->ire_addr_v6;
18105 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18106 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18107 	re->ipv6RouteIfIndex.o_length = 0;
18108 	ipif = ire->ire_ipif;
18109 	if (ire->ire_type == IRE_CACHE) {
18110 		ill = (ill_t *)ire->ire_stq->q_ptr;
18111 		re->ipv6RouteIfIndex.o_length =
18112 		    ill->ill_name_length == 0 ? 0 :
18113 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18114 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18115 		    re->ipv6RouteIfIndex.o_length);
18116 	} else if (ipif != NULL) {
18117 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18118 		    OCTET_LENGTH);
18119 		re->ipv6RouteIfIndex.o_length =
18120 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18121 	}
18122 
18123 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18124 
18125 	mutex_enter(&ire->ire_lock);
18126 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18127 	mutex_exit(&ire->ire_lock);
18128 
18129 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18130 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18131 	else
18132 		re->ipv6RouteNextHop = gw_addr_v6;
18133 
18134 	/* remote(4), local(3), or discard(2) */
18135 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18136 		re->ipv6RouteType = 2;
18137 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18138 		re->ipv6RouteType = 3;
18139 	else
18140 		re->ipv6RouteType = 4;
18141 
18142 	re->ipv6RouteProtocol	= -1;
18143 	re->ipv6RoutePolicy	= 0;
18144 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18145 	re->ipv6RouteNextHopRDI	= 0;
18146 	re->ipv6RouteWeight	= 0;
18147 	re->ipv6RouteMetric	= 0;
18148 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18149 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18150 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18151 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18152 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18153 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18154 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18155 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18156 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18157 
18158 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18159 	    (char *)re, (int)sizeof (*re))) {
18160 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18161 		    (uint_t)sizeof (*re)));
18162 	}
18163 
18164 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18165 		iaeptr->iae_routeidx = ird->ird_idx;
18166 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18167 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18168 	}
18169 
18170 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18171 	    (char *)iae, sacnt * sizeof (*iae))) {
18172 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18173 		    (unsigned)(sacnt * sizeof (*iae))));
18174 	}
18175 
18176 	/* bump route index for next pass */
18177 	ird->ird_idx++;
18178 
18179 	kmem_free(re, sizeof (*re));
18180 	if (sacnt != 0)
18181 		kmem_free(iae, sacnt * sizeof (*iae));
18182 
18183 	if (gcgrp != NULL)
18184 		rw_exit(&gcgrp->gcgrp_rwlock);
18185 }
18186 
18187 /*
18188  * ndp_walk routine to create ipv6NetToMediaEntryTable
18189  */
18190 static int
18191 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18192 {
18193 	ill_t				*ill;
18194 	mib2_ipv6NetToMediaEntry_t	ntme;
18195 	dl_unitdata_req_t		*dl;
18196 
18197 	ill = nce->nce_ill;
18198 	ASSERT(ill->ill_isv6);
18199 
18200 	/*
18201 	 * Neighbor cache entry attached to IRE with on-link
18202 	 * destination.
18203 	 */
18204 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18205 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18206 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18207 	    (nce->nce_res_mp != NULL)) {
18208 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18209 		ntme.ipv6NetToMediaPhysAddress.o_length =
18210 		    dl->dl_dest_addr_length;
18211 	} else {
18212 		ntme.ipv6NetToMediaPhysAddress.o_length =
18213 		    ill->ill_phys_addr_length;
18214 	}
18215 	if (nce->nce_res_mp != NULL) {
18216 		bcopy((char *)nce->nce_res_mp->b_rptr +
18217 		    NCE_LL_ADDR_OFFSET(ill),
18218 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18219 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18220 	} else {
18221 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18222 		    ill->ill_phys_addr_length);
18223 	}
18224 	/*
18225 	 * Note: Returns ND_* states. Should be:
18226 	 * reachable(1), stale(2), delay(3), probe(4),
18227 	 * invalid(5), unknown(6)
18228 	 */
18229 	ntme.ipv6NetToMediaState = nce->nce_state;
18230 	ntme.ipv6NetToMediaLastUpdated = 0;
18231 
18232 	/* other(1), dynamic(2), static(3), local(4) */
18233 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18234 		ntme.ipv6NetToMediaType = 4;
18235 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18236 		ntme.ipv6NetToMediaType = 1;
18237 	} else {
18238 		ntme.ipv6NetToMediaType = 2;
18239 	}
18240 
18241 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18242 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18243 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18244 		    (uint_t)sizeof (ntme)));
18245 	}
18246 	return (0);
18247 }
18248 
18249 /*
18250  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18251  */
18252 /* ARGSUSED */
18253 int
18254 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18255 {
18256 	switch (level) {
18257 	case MIB2_IP:
18258 	case MIB2_ICMP:
18259 		switch (name) {
18260 		default:
18261 			break;
18262 		}
18263 		return (1);
18264 	default:
18265 		return (1);
18266 	}
18267 }
18268 
18269 /*
18270  * Called before the options are updated to check if this packet will
18271  * be source routed from here.
18272  * This routine assumes that the options are well formed i.e. that they
18273  * have already been checked.
18274  */
18275 static boolean_t
18276 ip_source_routed(ipha_t *ipha)
18277 {
18278 	ipoptp_t	opts;
18279 	uchar_t		*opt;
18280 	uint8_t		optval;
18281 	uint8_t		optlen;
18282 	ipaddr_t	dst;
18283 	ire_t		*ire;
18284 
18285 	if (IS_SIMPLE_IPH(ipha)) {
18286 		ip2dbg(("not source routed\n"));
18287 		return (B_FALSE);
18288 	}
18289 	dst = ipha->ipha_dst;
18290 	for (optval = ipoptp_first(&opts, ipha);
18291 	    optval != IPOPT_EOL;
18292 	    optval = ipoptp_next(&opts)) {
18293 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18294 		opt = opts.ipoptp_cur;
18295 		optlen = opts.ipoptp_len;
18296 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18297 		    optval, optlen));
18298 		switch (optval) {
18299 			uint32_t off;
18300 		case IPOPT_SSRR:
18301 		case IPOPT_LSRR:
18302 			/*
18303 			 * If dst is one of our addresses and there are some
18304 			 * entries left in the source route return (true).
18305 			 */
18306 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18307 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18308 			if (ire == NULL) {
18309 				ip2dbg(("ip_source_routed: not next"
18310 				    " source route 0x%x\n",
18311 				    ntohl(dst)));
18312 				return (B_FALSE);
18313 			}
18314 			ire_refrele(ire);
18315 			off = opt[IPOPT_OFFSET];
18316 			off--;
18317 			if (optlen < IP_ADDR_LEN ||
18318 			    off > optlen - IP_ADDR_LEN) {
18319 				/* End of source route */
18320 				ip1dbg(("ip_source_routed: end of SR\n"));
18321 				return (B_FALSE);
18322 			}
18323 			return (B_TRUE);
18324 		}
18325 	}
18326 	ip2dbg(("not source routed\n"));
18327 	return (B_FALSE);
18328 }
18329 
18330 /*
18331  * Check if the packet contains any source route.
18332  */
18333 static boolean_t
18334 ip_source_route_included(ipha_t *ipha)
18335 {
18336 	ipoptp_t	opts;
18337 	uint8_t		optval;
18338 
18339 	if (IS_SIMPLE_IPH(ipha))
18340 		return (B_FALSE);
18341 	for (optval = ipoptp_first(&opts, ipha);
18342 	    optval != IPOPT_EOL;
18343 	    optval = ipoptp_next(&opts)) {
18344 		switch (optval) {
18345 		case IPOPT_SSRR:
18346 		case IPOPT_LSRR:
18347 			return (B_TRUE);
18348 		}
18349 	}
18350 	return (B_FALSE);
18351 }
18352 
18353 /*
18354  * Called when the IRE expiration timer fires.
18355  */
18356 /* ARGSUSED */
18357 void
18358 ip_trash_timer_expire(void *args)
18359 {
18360 	int	flush_flag = 0;
18361 
18362 	/*
18363 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18364 	 * This lock makes sure that a new invocation of this function
18365 	 * that occurs due to an almost immediate timer firing will not
18366 	 * progress beyond this point until the current invocation is done
18367 	 */
18368 	mutex_enter(&ip_trash_timer_lock);
18369 	ip_ire_expire_id = 0;
18370 	mutex_exit(&ip_trash_timer_lock);
18371 
18372 	/* Periodic timer */
18373 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18374 		/*
18375 		 * Remove all IRE_CACHE entries since they might
18376 		 * contain arp information.
18377 		 */
18378 		flush_flag |= FLUSH_ARP_TIME;
18379 		ip_ire_arp_time_elapsed = 0;
18380 		IP_STAT(ip_ire_arp_timer_expired);
18381 	}
18382 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18383 		/* Remove all redirects */
18384 		flush_flag |= FLUSH_REDIRECT_TIME;
18385 		ip_ire_rd_time_elapsed = 0;
18386 		IP_STAT(ip_ire_redirect_timer_expired);
18387 	}
18388 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18389 		/* Increase path mtu */
18390 		flush_flag |= FLUSH_MTU_TIME;
18391 		ip_ire_pmtu_time_elapsed = 0;
18392 		IP_STAT(ip_ire_pmtu_timer_expired);
18393 	}
18394 	if (flush_flag != 0) {
18395 		/* Walk all IPv4 IRE's and update them */
18396 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
18397 		    ALL_ZONES);
18398 	}
18399 	if (flush_flag & FLUSH_MTU_TIME) {
18400 		/*
18401 		 * Walk all IPv6 IRE's and update them
18402 		 * Note that ARP and redirect timers are not
18403 		 * needed since NUD handles stale entries.
18404 		 */
18405 		flush_flag = FLUSH_MTU_TIME;
18406 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18407 		    ALL_ZONES);
18408 	}
18409 
18410 	ip_ire_arp_time_elapsed += ip_timer_interval;
18411 	ip_ire_rd_time_elapsed += ip_timer_interval;
18412 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
18413 
18414 	/*
18415 	 * Hold the lock to serialize timeout calls and prevent
18416 	 * stale values in ip_ire_expire_id. Otherwise it is possible
18417 	 * for the timer to fire and a new invocation of this function
18418 	 * to start before the return value of timeout has been stored
18419 	 * in ip_ire_expire_id by the current invocation.
18420 	 */
18421 	mutex_enter(&ip_trash_timer_lock);
18422 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
18423 	    MSEC_TO_TICK(ip_timer_interval));
18424 	mutex_exit(&ip_trash_timer_lock);
18425 }
18426 
18427 /*
18428  * Called by the memory allocator subsystem directly, when the system
18429  * is running low on memory.
18430  */
18431 /* ARGSUSED */
18432 void
18433 ip_trash_ire_reclaim(void *args)
18434 {
18435 	ire_cache_count_t icc;
18436 	ire_cache_reclaim_t icr;
18437 	ncc_cache_count_t ncc;
18438 	nce_cache_reclaim_t ncr;
18439 	uint_t delete_cnt;
18440 	/*
18441 	 * Memory reclaim call back.
18442 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
18443 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
18444 	 * entries, determine what fraction to free for
18445 	 * each category of IRE_CACHE entries giving absolute priority
18446 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
18447 	 * entry will be freed unless all offlink entries are freed).
18448 	 */
18449 	icc.icc_total = 0;
18450 	icc.icc_unused = 0;
18451 	icc.icc_offlink = 0;
18452 	icc.icc_pmtu = 0;
18453 	icc.icc_onlink = 0;
18454 	ire_walk(ire_cache_count, (char *)&icc);
18455 
18456 	/*
18457 	 * Free NCEs for IPv6 like the onlink ires.
18458 	 */
18459 	ncc.ncc_total = 0;
18460 	ncc.ncc_host = 0;
18461 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
18462 
18463 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
18464 	    icc.icc_pmtu + icc.icc_onlink);
18465 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
18466 	IP_STAT(ip_trash_ire_reclaim_calls);
18467 	if (delete_cnt == 0)
18468 		return;
18469 	IP_STAT(ip_trash_ire_reclaim_success);
18470 	/* Always delete all unused offlink entries */
18471 	icr.icr_unused = 1;
18472 	if (delete_cnt <= icc.icc_unused) {
18473 		/*
18474 		 * Only need to free unused entries.  In other words,
18475 		 * there are enough unused entries to free to meet our
18476 		 * target number of freed ire cache entries.
18477 		 */
18478 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
18479 		ncr.ncr_host = 0;
18480 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
18481 		/*
18482 		 * Only need to free unused entries, plus a fraction of offlink
18483 		 * entries.  It follows from the first if statement that
18484 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
18485 		 */
18486 		delete_cnt -= icc.icc_unused;
18487 		/* Round up # deleted by truncating fraction */
18488 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
18489 		icr.icr_pmtu = icr.icr_onlink = 0;
18490 		ncr.ncr_host = 0;
18491 	} else if (delete_cnt <=
18492 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
18493 		/*
18494 		 * Free all unused and offlink entries, plus a fraction of
18495 		 * pmtu entries.  It follows from the previous if statement
18496 		 * that icc_pmtu is non-zero, and that
18497 		 * delete_cnt != icc_unused + icc_offlink.
18498 		 */
18499 		icr.icr_offlink = 1;
18500 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
18501 		/* Round up # deleted by truncating fraction */
18502 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
18503 		icr.icr_onlink = 0;
18504 		ncr.ncr_host = 0;
18505 	} else {
18506 		/*
18507 		 * Free all unused, offlink, and pmtu entries, plus a fraction
18508 		 * of onlink entries.  If we're here, then we know that
18509 		 * icc_onlink is non-zero, and that
18510 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
18511 		 */
18512 		icr.icr_offlink = icr.icr_pmtu = 1;
18513 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
18514 		    icc.icc_pmtu;
18515 		/* Round up # deleted by truncating fraction */
18516 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
18517 		/* Using the same delete fraction as for onlink IREs */
18518 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
18519 	}
18520 #ifdef DEBUG
18521 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
18522 	    "fractions %d/%d/%d/%d\n",
18523 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
18524 	    icc.icc_unused, icc.icc_offlink,
18525 	    icc.icc_pmtu, icc.icc_onlink,
18526 	    icr.icr_unused, icr.icr_offlink,
18527 	    icr.icr_pmtu, icr.icr_onlink));
18528 #endif
18529 	ire_walk(ire_cache_reclaim, (char *)&icr);
18530 	if (ncr.ncr_host != 0)
18531 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
18532 		    (uchar_t *)&ncr);
18533 #ifdef DEBUG
18534 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
18535 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
18536 	ire_walk(ire_cache_count, (char *)&icc);
18537 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
18538 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
18539 	    icc.icc_pmtu, icc.icc_onlink));
18540 #endif
18541 }
18542 
18543 /*
18544  * ip_unbind is called when a copy of an unbind request is received from the
18545  * upper level protocol.  We remove this conn from any fanout hash list it is
18546  * on, and zero out the bind information.  No reply is expected up above.
18547  */
18548 mblk_t *
18549 ip_unbind(queue_t *q, mblk_t *mp)
18550 {
18551 	conn_t	*connp = Q_TO_CONN(q);
18552 
18553 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
18554 
18555 	if (is_system_labeled() && connp->conn_anon_port) {
18556 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
18557 		    connp->conn_mlp_type, connp->conn_ulp,
18558 		    ntohs(connp->conn_lport), B_FALSE);
18559 		connp->conn_anon_port = 0;
18560 	}
18561 	connp->conn_mlp_type = mlptSingle;
18562 
18563 	ipcl_hash_remove(connp);
18564 
18565 	ASSERT(mp->b_cont == NULL);
18566 	/*
18567 	 * Convert mp into a T_OK_ACK
18568 	 */
18569 	mp = mi_tpi_ok_ack_alloc(mp);
18570 
18571 	/*
18572 	 * should not happen in practice... T_OK_ACK is smaller than the
18573 	 * original message.
18574 	 */
18575 	if (mp == NULL)
18576 		return (NULL);
18577 
18578 	/*
18579 	 * Don't bzero the ports if its TCP since TCP still needs the
18580 	 * lport to remove it from its own bind hash. TCP will do the
18581 	 * cleanup.
18582 	 */
18583 	if (!IPCL_IS_TCP(connp))
18584 		bzero(&connp->u_port, sizeof (connp->u_port));
18585 
18586 	return (mp);
18587 }
18588 
18589 /*
18590  * Write side put procedure.  Outbound data, IOCTLs, responses from
18591  * resolvers, etc, come down through here.
18592  */
18593 void
18594 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
18595 {
18596 	conn_t		*connp = NULL;
18597 	queue_t		*q = (queue_t *)arg2;
18598 	ipha_t		*ipha;
18599 #define	rptr	((uchar_t *)ipha)
18600 	ire_t		*ire = NULL;
18601 	ire_t		*sctp_ire = NULL;
18602 	uint32_t	v_hlen_tos_len;
18603 	ipaddr_t	dst;
18604 	mblk_t		*first_mp = NULL;
18605 	boolean_t	mctl_present;
18606 	ipsec_out_t	*io;
18607 	int		match_flags;
18608 	ill_t		*attach_ill = NULL;
18609 					/* Bind to IPIF_NOFAILOVER ill etc. */
18610 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
18611 	ipif_t		*dst_ipif;
18612 	boolean_t	multirt_need_resolve = B_FALSE;
18613 	mblk_t		*copy_mp = NULL;
18614 	int		err;
18615 	zoneid_t	zoneid;
18616 	int	adjust;
18617 	uint16_t iplen;
18618 	boolean_t	need_decref = B_FALSE;
18619 	boolean_t	ignore_dontroute = B_FALSE;
18620 	boolean_t	ignore_nexthop = B_FALSE;
18621 	boolean_t	ip_nexthop = B_FALSE;
18622 	ipaddr_t	nexthop_addr;
18623 
18624 #ifdef	_BIG_ENDIAN
18625 #define	V_HLEN	(v_hlen_tos_len >> 24)
18626 #else
18627 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
18628 #endif
18629 
18630 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
18631 	    "ip_wput_start: q %p", q);
18632 
18633 	/*
18634 	 * ip_wput fast path
18635 	 */
18636 
18637 	/* is packet from ARP ? */
18638 	if (q->q_next != NULL)
18639 		goto qnext;
18640 
18641 	connp = (conn_t *)arg;
18642 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
18643 
18644 	/* is queue flow controlled? */
18645 	if ((q->q_first != NULL || connp->conn_draining) &&
18646 	    (caller == IP_WPUT)) {
18647 		ASSERT(!need_decref);
18648 		(void) putq(q, mp);
18649 		return;
18650 	}
18651 
18652 	/* Multidata transmit? */
18653 	if (DB_TYPE(mp) == M_MULTIDATA) {
18654 		/*
18655 		 * We should never get here, since all Multidata messages
18656 		 * originating from tcp should have been directed over to
18657 		 * tcp_multisend() in the first place.
18658 		 */
18659 		BUMP_MIB(&ip_mib, ipOutDiscards);
18660 		freemsg(mp);
18661 		return;
18662 	} else if (DB_TYPE(mp) != M_DATA)
18663 		goto notdata;
18664 
18665 	if (mp->b_flag & MSGHASREF) {
18666 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18667 		mp->b_flag &= ~MSGHASREF;
18668 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
18669 		need_decref = B_TRUE;
18670 	}
18671 	ipha = (ipha_t *)mp->b_rptr;
18672 
18673 	/* is IP header non-aligned or mblk smaller than basic IP header */
18674 #ifndef SAFETY_BEFORE_SPEED
18675 	if (!OK_32PTR(rptr) ||
18676 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
18677 		goto hdrtoosmall;
18678 #endif
18679 
18680 	ASSERT(OK_32PTR(ipha));
18681 
18682 	/*
18683 	 * This function assumes that mp points to an IPv4 packet.  If it's the
18684 	 * wrong version, we'll catch it again in ip_output_v6.
18685 	 *
18686 	 * Note that this is *only* locally-generated output here, and never
18687 	 * forwarded data, and that we need to deal only with transports that
18688 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
18689 	 * label.)
18690 	 */
18691 	if (is_system_labeled() &&
18692 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
18693 	    !connp->conn_ulp_labeled) {
18694 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
18695 		    connp->conn_mac_exempt);
18696 		ipha = (ipha_t *)mp->b_rptr;
18697 		if (err != 0) {
18698 			first_mp = mp;
18699 			if (err == EINVAL)
18700 				goto icmp_parameter_problem;
18701 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
18702 			goto drop_pkt;
18703 		}
18704 		iplen = ntohs(ipha->ipha_length) + adjust;
18705 		ipha->ipha_length = htons(iplen);
18706 	}
18707 
18708 	/*
18709 	 * If there is a policy, try to attach an ipsec_out in
18710 	 * the front. At the end, first_mp either points to a
18711 	 * M_DATA message or IPSEC_OUT message linked to a
18712 	 * M_DATA message. We have to do it now as we might
18713 	 * lose the "conn" if we go through ip_newroute.
18714 	 */
18715 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
18716 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
18717 		    ipha->ipha_protocol)) == NULL)) {
18718 			if (need_decref)
18719 				CONN_DEC_REF(connp);
18720 			return;
18721 		} else {
18722 			ASSERT(mp->b_datap->db_type == M_CTL);
18723 			first_mp = mp;
18724 			mp = mp->b_cont;
18725 			mctl_present = B_TRUE;
18726 		}
18727 	} else {
18728 		first_mp = mp;
18729 		mctl_present = B_FALSE;
18730 	}
18731 
18732 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18733 
18734 	/* is wrong version or IP options present */
18735 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
18736 		goto version_hdrlen_check;
18737 	dst = ipha->ipha_dst;
18738 
18739 	if (connp->conn_nofailover_ill != NULL) {
18740 		attach_ill = conn_get_held_ill(connp,
18741 		    &connp->conn_nofailover_ill, &err);
18742 		if (err == ILL_LOOKUP_FAILED) {
18743 			if (need_decref)
18744 				CONN_DEC_REF(connp);
18745 			freemsg(first_mp);
18746 			return;
18747 		}
18748 	}
18749 
18750 	/* is packet multicast? */
18751 	if (CLASSD(dst))
18752 		goto multicast;
18753 
18754 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
18755 	    (connp->conn_nexthop_set)) {
18756 		/*
18757 		 * If the destination is a broadcast or a loopback
18758 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
18759 		 * through the standard path. But in the case of local
18760 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
18761 		 * the standard path not IP_XMIT_IF.
18762 		 */
18763 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18764 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
18765 		    (ire->ire_type != IRE_LOOPBACK))) {
18766 			if ((connp->conn_dontroute ||
18767 			    connp->conn_nexthop_set) && (ire != NULL) &&
18768 			    (ire->ire_type == IRE_LOCAL))
18769 				goto standard_path;
18770 
18771 			if (ire != NULL) {
18772 				ire_refrele(ire);
18773 				/* No more access to ire */
18774 				ire = NULL;
18775 			}
18776 			/*
18777 			 * bypass routing checks and go directly to
18778 			 * interface.
18779 			 */
18780 			if (connp->conn_dontroute) {
18781 				goto dontroute;
18782 			} else if (connp->conn_nexthop_set) {
18783 				ip_nexthop = B_TRUE;
18784 				nexthop_addr = connp->conn_nexthop_v4;
18785 				goto send_from_ill;
18786 			}
18787 
18788 			/*
18789 			 * If IP_XMIT_IF socket option is set,
18790 			 * then we allow unicast and multicast
18791 			 * packets to go through the ill. It is
18792 			 * quite possible that the destination
18793 			 * is not in the ire cache table and we
18794 			 * do not want to go to ip_newroute()
18795 			 * instead we call ip_newroute_ipif.
18796 			 */
18797 			xmit_ill = conn_get_held_ill(connp,
18798 			    &connp->conn_xmit_if_ill, &err);
18799 			if (err == ILL_LOOKUP_FAILED) {
18800 				if (attach_ill != NULL)
18801 					ill_refrele(attach_ill);
18802 				if (need_decref)
18803 					CONN_DEC_REF(connp);
18804 				freemsg(first_mp);
18805 				return;
18806 			}
18807 			goto send_from_ill;
18808 		}
18809 standard_path:
18810 		/* Must be a broadcast, a loopback or a local ire */
18811 		if (ire != NULL) {
18812 			ire_refrele(ire);
18813 			/* No more access to ire */
18814 			ire = NULL;
18815 		}
18816 	}
18817 
18818 	if (attach_ill != NULL)
18819 		goto send_from_ill;
18820 
18821 	/*
18822 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18823 	 * this for the tcp global queue and listen end point
18824 	 * as it does not really have a real destination to
18825 	 * talk to.  This is also true for SCTP.
18826 	 */
18827 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18828 	    !connp->conn_fully_bound) {
18829 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18830 		if (ire == NULL)
18831 			goto noirefound;
18832 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18833 		    "ip_wput_end: q %p (%S)", q, "end");
18834 
18835 		/*
18836 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18837 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18838 		 */
18839 		if (ire->ire_flags & RTF_MULTIRT) {
18840 
18841 			/*
18842 			 * Force the TTL of multirouted packets if required.
18843 			 * The TTL of such packets is bounded by the
18844 			 * ip_multirt_ttl ndd variable.
18845 			 */
18846 			if ((ip_multirt_ttl > 0) &&
18847 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18848 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18849 				    "(was %d), dst 0x%08x\n",
18850 				    ip_multirt_ttl, ipha->ipha_ttl,
18851 				    ntohl(ire->ire_addr)));
18852 				ipha->ipha_ttl = ip_multirt_ttl;
18853 			}
18854 			/*
18855 			 * We look at this point if there are pending
18856 			 * unresolved routes. ire_multirt_resolvable()
18857 			 * checks in O(n) that all IRE_OFFSUBNET ire
18858 			 * entries for the packet's destination and
18859 			 * flagged RTF_MULTIRT are currently resolved.
18860 			 * If some remain unresolved, we make a copy
18861 			 * of the current message. It will be used
18862 			 * to initiate additional route resolutions.
18863 			 */
18864 			multirt_need_resolve =
18865 			    ire_multirt_need_resolve(ire->ire_addr,
18866 			    MBLK_GETLABEL(first_mp));
18867 			ip2dbg(("ip_wput[TCP]: ire %p, "
18868 			    "multirt_need_resolve %d, first_mp %p\n",
18869 			    (void *)ire, multirt_need_resolve,
18870 			    (void *)first_mp));
18871 			if (multirt_need_resolve) {
18872 				copy_mp = copymsg(first_mp);
18873 				if (copy_mp != NULL) {
18874 					MULTIRT_DEBUG_TAG(copy_mp);
18875 				}
18876 			}
18877 		}
18878 
18879 		ip_wput_ire(q, first_mp, ire, connp, caller);
18880 
18881 		/*
18882 		 * Try to resolve another multiroute if
18883 		 * ire_multirt_need_resolve() deemed it necessary.
18884 		 */
18885 		if (copy_mp != NULL) {
18886 			ip_newroute(q, copy_mp, dst, NULL, connp);
18887 		}
18888 		if (need_decref)
18889 			CONN_DEC_REF(connp);
18890 		return;
18891 	}
18892 
18893 	/*
18894 	 * Access to conn_ire_cache. (protected by conn_lock)
18895 	 *
18896 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18897 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18898 	 * send a packet or two with the IRE_CACHE that is going away.
18899 	 * Access to the ire requires an ire refhold on the ire prior to
18900 	 * its use since an interface unplumb thread may delete the cached
18901 	 * ire and release the refhold at any time.
18902 	 *
18903 	 * Caching an ire in the conn_ire_cache
18904 	 *
18905 	 * o Caching an ire pointer in the conn requires a strict check for
18906 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18907 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18908 	 * in the conn is done after making sure under the bucket lock that the
18909 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18910 	 * caching an ire after the unplumb thread has cleaned up the conn.
18911 	 * If the conn does not send a packet subsequently the unplumb thread
18912 	 * will be hanging waiting for the ire count to drop to zero.
18913 	 *
18914 	 * o We also need to atomically test for a null conn_ire_cache and
18915 	 * set the conn_ire_cache under the the protection of the conn_lock
18916 	 * to avoid races among concurrent threads trying to simultaneously
18917 	 * cache an ire in the conn_ire_cache.
18918 	 */
18919 	mutex_enter(&connp->conn_lock);
18920 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18921 
18922 	if (ire != NULL && ire->ire_addr == dst &&
18923 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18924 
18925 		IRE_REFHOLD(ire);
18926 		mutex_exit(&connp->conn_lock);
18927 
18928 	} else {
18929 		boolean_t cached = B_FALSE;
18930 		connp->conn_ire_cache = NULL;
18931 		mutex_exit(&connp->conn_lock);
18932 		/* Release the old ire */
18933 		if (ire != NULL && sctp_ire == NULL)
18934 			IRE_REFRELE_NOTR(ire);
18935 
18936 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18937 		if (ire == NULL)
18938 			goto noirefound;
18939 		IRE_REFHOLD_NOTR(ire);
18940 
18941 		mutex_enter(&connp->conn_lock);
18942 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18943 		    connp->conn_ire_cache == NULL) {
18944 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18945 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18946 				connp->conn_ire_cache = ire;
18947 				cached = B_TRUE;
18948 			}
18949 			rw_exit(&ire->ire_bucket->irb_lock);
18950 		}
18951 		mutex_exit(&connp->conn_lock);
18952 
18953 		/*
18954 		 * We can continue to use the ire but since it was
18955 		 * not cached, we should drop the extra reference.
18956 		 */
18957 		if (!cached)
18958 			IRE_REFRELE_NOTR(ire);
18959 	}
18960 
18961 
18962 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18963 	    "ip_wput_end: q %p (%S)", q, "end");
18964 
18965 	/*
18966 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18967 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18968 	 */
18969 	if (ire->ire_flags & RTF_MULTIRT) {
18970 
18971 		/*
18972 		 * Force the TTL of multirouted packets if required.
18973 		 * The TTL of such packets is bounded by the
18974 		 * ip_multirt_ttl ndd variable.
18975 		 */
18976 		if ((ip_multirt_ttl > 0) &&
18977 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18978 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18979 			    "(was %d), dst 0x%08x\n",
18980 			    ip_multirt_ttl, ipha->ipha_ttl,
18981 			    ntohl(ire->ire_addr)));
18982 			ipha->ipha_ttl = ip_multirt_ttl;
18983 		}
18984 
18985 		/*
18986 		 * At this point, we check to see if there are any pending
18987 		 * unresolved routes. ire_multirt_resolvable()
18988 		 * checks in O(n) that all IRE_OFFSUBNET ire
18989 		 * entries for the packet's destination and
18990 		 * flagged RTF_MULTIRT are currently resolved.
18991 		 * If some remain unresolved, we make a copy
18992 		 * of the current message. It will be used
18993 		 * to initiate additional route resolutions.
18994 		 */
18995 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
18996 		    MBLK_GETLABEL(first_mp));
18997 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18998 		    "multirt_need_resolve %d, first_mp %p\n",
18999 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19000 		if (multirt_need_resolve) {
19001 			copy_mp = copymsg(first_mp);
19002 			if (copy_mp != NULL) {
19003 				MULTIRT_DEBUG_TAG(copy_mp);
19004 			}
19005 		}
19006 	}
19007 
19008 	ip_wput_ire(q, first_mp, ire, connp, caller);
19009 
19010 	/*
19011 	 * Try to resolve another multiroute if
19012 	 * ire_multirt_resolvable() deemed it necessary
19013 	 */
19014 	if (copy_mp != NULL) {
19015 		ip_newroute(q, copy_mp, dst, NULL, connp);
19016 	}
19017 	if (need_decref)
19018 		CONN_DEC_REF(connp);
19019 	return;
19020 
19021 qnext:
19022 	/*
19023 	 * Upper Level Protocols pass down complete IP datagrams
19024 	 * as M_DATA messages.	Everything else is a sideshow.
19025 	 *
19026 	 * 1) We could be re-entering ip_wput because of ip_neworute
19027 	 *    in which case we could have a IPSEC_OUT message. We
19028 	 *    need to pass through ip_wput like other datagrams and
19029 	 *    hence cannot branch to ip_wput_nondata.
19030 	 *
19031 	 * 2) ARP, AH, ESP, and other clients who are on the module
19032 	 *    instance of IP stream, give us something to deal with.
19033 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19034 	 *
19035 	 * 3) ICMP replies also could come here.
19036 	 */
19037 	if (DB_TYPE(mp) != M_DATA) {
19038 	    notdata:
19039 		if (DB_TYPE(mp) == M_CTL) {
19040 			/*
19041 			 * M_CTL messages are used by ARP, AH and ESP to
19042 			 * communicate with IP. We deal with IPSEC_IN and
19043 			 * IPSEC_OUT here. ip_wput_nondata handles other
19044 			 * cases.
19045 			 */
19046 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19047 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19048 				first_mp = mp->b_cont;
19049 				first_mp->b_flag &= ~MSGHASREF;
19050 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19051 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19052 				CONN_DEC_REF(connp);
19053 				connp = NULL;
19054 			}
19055 			if (ii->ipsec_info_type == IPSEC_IN) {
19056 				/*
19057 				 * Either this message goes back to
19058 				 * IPSEC for further processing or to
19059 				 * ULP after policy checks.
19060 				 */
19061 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19062 				return;
19063 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19064 				io = (ipsec_out_t *)ii;
19065 				if (io->ipsec_out_proc_begin) {
19066 					/*
19067 					 * IPSEC processing has already started.
19068 					 * Complete it.
19069 					 * IPQoS notes: We don't care what is
19070 					 * in ipsec_out_ill_index since this
19071 					 * won't be processed for IPQoS policies
19072 					 * in ipsec_out_process.
19073 					 */
19074 					ipsec_out_process(q, mp, NULL,
19075 					    io->ipsec_out_ill_index);
19076 					return;
19077 				} else {
19078 					connp = (q->q_next != NULL) ?
19079 					    NULL : Q_TO_CONN(q);
19080 					first_mp = mp;
19081 					mp = mp->b_cont;
19082 					mctl_present = B_TRUE;
19083 				}
19084 				zoneid = io->ipsec_out_zoneid;
19085 				ASSERT(zoneid != ALL_ZONES);
19086 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19087 				/*
19088 				 * It's an IPsec control message requesting
19089 				 * an SADB update to be sent to the IPsec
19090 				 * hardware acceleration capable ills.
19091 				 */
19092 				ipsec_ctl_t *ipsec_ctl =
19093 				    (ipsec_ctl_t *)mp->b_rptr;
19094 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19095 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19096 				mblk_t *cmp = mp->b_cont;
19097 
19098 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19099 				ASSERT(cmp != NULL);
19100 
19101 				freeb(mp);
19102 				ill_ipsec_capab_send_all(satype, cmp, sa);
19103 				return;
19104 			} else {
19105 				/*
19106 				 * This must be ARP or special TSOL signaling.
19107 				 */
19108 				ip_wput_nondata(NULL, q, mp, NULL);
19109 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19110 				    "ip_wput_end: q %p (%S)", q, "nondata");
19111 				return;
19112 			}
19113 		} else {
19114 			/*
19115 			 * This must be non-(ARP/AH/ESP) messages.
19116 			 */
19117 			ASSERT(!need_decref);
19118 			ip_wput_nondata(NULL, q, mp, NULL);
19119 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19120 			    "ip_wput_end: q %p (%S)", q, "nondata");
19121 			return;
19122 		}
19123 	} else {
19124 		first_mp = mp;
19125 		mctl_present = B_FALSE;
19126 	}
19127 
19128 	ASSERT(first_mp != NULL);
19129 	/*
19130 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19131 	 * to make sure that this packet goes out on the same interface it
19132 	 * came in. We handle that here.
19133 	 */
19134 	if (mctl_present) {
19135 		uint_t ifindex;
19136 
19137 		io = (ipsec_out_t *)first_mp->b_rptr;
19138 		if (io->ipsec_out_attach_if ||
19139 		    io->ipsec_out_xmit_if ||
19140 		    io->ipsec_out_ip_nexthop) {
19141 			ill_t	*ill;
19142 
19143 			/*
19144 			 * We may have lost the conn context if we are
19145 			 * coming here from ip_newroute(). Copy the
19146 			 * nexthop information.
19147 			 */
19148 			if (io->ipsec_out_ip_nexthop) {
19149 				ip_nexthop = B_TRUE;
19150 				nexthop_addr = io->ipsec_out_nexthop_addr;
19151 
19152 				ipha = (ipha_t *)mp->b_rptr;
19153 				dst = ipha->ipha_dst;
19154 				goto send_from_ill;
19155 			} else {
19156 				ASSERT(io->ipsec_out_ill_index != 0);
19157 				ifindex = io->ipsec_out_ill_index;
19158 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19159 				    NULL, NULL, NULL, NULL);
19160 				/*
19161 				 * ipsec_out_xmit_if bit is used to tell
19162 				 * ip_wput to use the ill to send outgoing data
19163 				 * as we have no conn when data comes from ICMP
19164 				 * error msg routines. Currently this feature is
19165 				 * only used by ip_mrtun_forward routine.
19166 				 */
19167 				if (io->ipsec_out_xmit_if) {
19168 					xmit_ill = ill;
19169 					if (xmit_ill == NULL) {
19170 						ip1dbg(("ip_output:bad ifindex "
19171 						    "for xmit_ill %d\n",
19172 						    ifindex));
19173 						freemsg(first_mp);
19174 						BUMP_MIB(&ip_mib,
19175 						    ipOutDiscards);
19176 						ASSERT(!need_decref);
19177 						return;
19178 					}
19179 					/* Free up the ipsec_out_t mblk */
19180 					ASSERT(first_mp->b_cont == mp);
19181 					first_mp->b_cont = NULL;
19182 					freeb(first_mp);
19183 					/* Just send the IP header+ICMP+data */
19184 					first_mp = mp;
19185 					ipha = (ipha_t *)mp->b_rptr;
19186 					dst = ipha->ipha_dst;
19187 					goto send_from_ill;
19188 				} else {
19189 					attach_ill = ill;
19190 				}
19191 
19192 				if (attach_ill == NULL) {
19193 					ASSERT(xmit_ill == NULL);
19194 					ip1dbg(("ip_output: bad ifindex for "
19195 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19196 					    ifindex));
19197 					freemsg(first_mp);
19198 					BUMP_MIB(&ip_mib, ipOutDiscards);
19199 					ASSERT(!need_decref);
19200 					return;
19201 				}
19202 			}
19203 		}
19204 	}
19205 
19206 	ASSERT(xmit_ill == NULL);
19207 
19208 	/* We have a complete IP datagram heading outbound. */
19209 	ipha = (ipha_t *)mp->b_rptr;
19210 
19211 #ifndef SPEED_BEFORE_SAFETY
19212 	/*
19213 	 * Make sure we have a full-word aligned message and that at least
19214 	 * a simple IP header is accessible in the first message.  If not,
19215 	 * try a pullup.
19216 	 */
19217 	if (!OK_32PTR(rptr) ||
19218 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19219 	    hdrtoosmall:
19220 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19221 			BUMP_MIB(&ip_mib, ipOutDiscards);
19222 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19223 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19224 			if (first_mp == NULL)
19225 				first_mp = mp;
19226 			goto drop_pkt;
19227 		}
19228 
19229 		/* This function assumes that mp points to an IPv4 packet. */
19230 		if (is_system_labeled() && q->q_next == NULL &&
19231 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19232 		    !connp->conn_ulp_labeled) {
19233 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19234 			    &adjust, connp->conn_mac_exempt);
19235 			ipha = (ipha_t *)mp->b_rptr;
19236 			if (first_mp != NULL)
19237 				first_mp->b_cont = mp;
19238 			if (err != 0) {
19239 				if (first_mp == NULL)
19240 					first_mp = mp;
19241 				if (err == EINVAL)
19242 					goto icmp_parameter_problem;
19243 				ip2dbg(("ip_wput: label check failed (%d)\n",
19244 				    err));
19245 				goto drop_pkt;
19246 			}
19247 			iplen = ntohs(ipha->ipha_length) + adjust;
19248 			ipha->ipha_length = htons(iplen);
19249 		}
19250 
19251 		ipha = (ipha_t *)mp->b_rptr;
19252 		if (first_mp == NULL) {
19253 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19254 			/*
19255 			 * If we got here because of "goto hdrtoosmall"
19256 			 * We need to attach a IPSEC_OUT.
19257 			 */
19258 			if (connp->conn_out_enforce_policy) {
19259 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19260 				    NULL, ipha->ipha_protocol)) == NULL)) {
19261 					if (need_decref)
19262 						CONN_DEC_REF(connp);
19263 					return;
19264 				} else {
19265 					ASSERT(mp->b_datap->db_type == M_CTL);
19266 					first_mp = mp;
19267 					mp = mp->b_cont;
19268 					mctl_present = B_TRUE;
19269 				}
19270 			} else {
19271 				first_mp = mp;
19272 				mctl_present = B_FALSE;
19273 			}
19274 		}
19275 	}
19276 #endif
19277 
19278 	/* Most of the code below is written for speed, not readability */
19279 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19280 
19281 	/*
19282 	 * If ip_newroute() fails, we're going to need a full
19283 	 * header for the icmp wraparound.
19284 	 */
19285 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19286 		uint_t	v_hlen;
19287 	    version_hdrlen_check:
19288 		ASSERT(first_mp != NULL);
19289 		v_hlen = V_HLEN;
19290 		/*
19291 		 * siphon off IPv6 packets coming down from transport
19292 		 * layer modules here.
19293 		 * Note: high-order bit carries NUD reachability confirmation
19294 		 */
19295 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19296 			/*
19297 			 * XXX implement a IPv4 and IPv6 packet counter per
19298 			 * conn and switch when ratio exceeds e.g. 10:1
19299 			 */
19300 #ifdef notyet
19301 			if (q->q_next == NULL) /* Avoid ill queue */
19302 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19303 #endif
19304 			BUMP_MIB(&ip_mib, ipOutIPv6);
19305 			ASSERT(xmit_ill == NULL);
19306 			if (attach_ill != NULL)
19307 				ill_refrele(attach_ill);
19308 			if (need_decref)
19309 				mp->b_flag |= MSGHASREF;
19310 			(void) ip_output_v6(connp, first_mp, q, caller);
19311 			return;
19312 		}
19313 
19314 		if ((v_hlen >> 4) != IP_VERSION) {
19315 			BUMP_MIB(&ip_mib, ipOutDiscards);
19316 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19317 			    "ip_wput_end: q %p (%S)", q, "badvers");
19318 			goto drop_pkt;
19319 		}
19320 		/*
19321 		 * Is the header length at least 20 bytes?
19322 		 *
19323 		 * Are there enough bytes accessible in the header?  If
19324 		 * not, try a pullup.
19325 		 */
19326 		v_hlen &= 0xF;
19327 		v_hlen <<= 2;
19328 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19329 			BUMP_MIB(&ip_mib, ipOutDiscards);
19330 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19331 			    "ip_wput_end: q %p (%S)", q, "badlen");
19332 			goto drop_pkt;
19333 		}
19334 		if (v_hlen > (mp->b_wptr - rptr)) {
19335 			if (!pullupmsg(mp, v_hlen)) {
19336 				BUMP_MIB(&ip_mib, ipOutDiscards);
19337 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19338 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19339 				goto drop_pkt;
19340 			}
19341 			ipha = (ipha_t *)mp->b_rptr;
19342 		}
19343 		/*
19344 		 * Move first entry from any source route into ipha_dst and
19345 		 * verify the options
19346 		 */
19347 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19348 			ASSERT(xmit_ill == NULL);
19349 			if (attach_ill != NULL)
19350 				ill_refrele(attach_ill);
19351 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19352 			    "ip_wput_end: q %p (%S)", q, "badopts");
19353 			if (need_decref)
19354 				CONN_DEC_REF(connp);
19355 			return;
19356 		}
19357 	}
19358 	dst = ipha->ipha_dst;
19359 
19360 	/*
19361 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19362 	 * we have to run the packet through ip_newroute which will take
19363 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19364 	 * a resolver, or assigning a default gateway, etc.
19365 	 */
19366 	if (CLASSD(dst)) {
19367 		ipif_t	*ipif;
19368 		uint32_t setsrc = 0;
19369 
19370 	    multicast:
19371 		ASSERT(first_mp != NULL);
19372 		ASSERT(xmit_ill == NULL);
19373 		ip2dbg(("ip_wput: CLASSD\n"));
19374 		if (connp == NULL) {
19375 			/*
19376 			 * Use the first good ipif on the ill.
19377 			 * XXX Should this ever happen? (Appears
19378 			 * to show up with just ppp and no ethernet due
19379 			 * to in.rdisc.)
19380 			 * However, ire_send should be able to
19381 			 * call ip_wput_ire directly.
19382 			 *
19383 			 * XXX Also, this can happen for ICMP and other packets
19384 			 * with multicast source addresses.  Perhaps we should
19385 			 * fix things so that we drop the packet in question,
19386 			 * but for now, just run with it.
19387 			 */
19388 			ill_t *ill = (ill_t *)q->q_ptr;
19389 
19390 			/*
19391 			 * Don't honor attach_if for this case. If ill
19392 			 * is part of the group, ipif could belong to
19393 			 * any ill and we cannot maintain attach_ill
19394 			 * and ipif_ill same anymore and the assert
19395 			 * below would fail.
19396 			 */
19397 			if (mctl_present) {
19398 				io->ipsec_out_ill_index = 0;
19399 				io->ipsec_out_attach_if = B_FALSE;
19400 				ASSERT(attach_ill != NULL);
19401 				ill_refrele(attach_ill);
19402 				attach_ill = NULL;
19403 			}
19404 
19405 			ASSERT(attach_ill == NULL);
19406 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19407 			if (ipif == NULL) {
19408 				if (need_decref)
19409 					CONN_DEC_REF(connp);
19410 				freemsg(first_mp);
19411 				return;
19412 			}
19413 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
19414 			    ntohl(dst), ill->ill_name));
19415 		} else {
19416 			/*
19417 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
19418 			 * IP_XMIT_IF is honoured.
19419 			 * Block comment above this function explains the
19420 			 * locking mechanism used here
19421 			 */
19422 			xmit_ill = conn_get_held_ill(connp,
19423 			    &connp->conn_xmit_if_ill, &err);
19424 			if (err == ILL_LOOKUP_FAILED) {
19425 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
19426 				goto drop_pkt;
19427 			}
19428 			if (xmit_ill == NULL) {
19429 				ipif = conn_get_held_ipif(connp,
19430 				    &connp->conn_multicast_ipif, &err);
19431 				if (err == IPIF_LOOKUP_FAILED) {
19432 					ip1dbg(("ip_wput: No ipif for "
19433 					    "multicast\n"));
19434 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19435 					goto drop_pkt;
19436 				}
19437 			}
19438 			if (xmit_ill != NULL) {
19439 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19440 				if (ipif == NULL) {
19441 					ip1dbg(("ip_wput: No ipif for "
19442 					    "IP_XMIT_IF\n"));
19443 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19444 					goto drop_pkt;
19445 				}
19446 			} else if (ipif == NULL || ipif->ipif_isv6) {
19447 				/*
19448 				 * We must do this ipif determination here
19449 				 * else we could pass through ip_newroute
19450 				 * and come back here without the conn context.
19451 				 *
19452 				 * Note: we do late binding i.e. we bind to
19453 				 * the interface when the first packet is sent.
19454 				 * For performance reasons we do not rebind on
19455 				 * each packet but keep the binding until the
19456 				 * next IP_MULTICAST_IF option.
19457 				 *
19458 				 * conn_multicast_{ipif,ill} are shared between
19459 				 * IPv4 and IPv6 and AF_INET6 sockets can
19460 				 * send both IPv4 and IPv6 packets. Hence
19461 				 * we have to check that "isv6" matches above.
19462 				 */
19463 				if (ipif != NULL)
19464 					ipif_refrele(ipif);
19465 				ipif = ipif_lookup_group(dst, zoneid);
19466 				if (ipif == NULL) {
19467 					ip1dbg(("ip_wput: No ipif for "
19468 					    "multicast\n"));
19469 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19470 					goto drop_pkt;
19471 				}
19472 				err = conn_set_held_ipif(connp,
19473 				    &connp->conn_multicast_ipif, ipif);
19474 				if (err == IPIF_LOOKUP_FAILED) {
19475 					ipif_refrele(ipif);
19476 					ip1dbg(("ip_wput: No ipif for "
19477 					    "multicast\n"));
19478 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19479 					goto drop_pkt;
19480 				}
19481 			}
19482 		}
19483 		ASSERT(!ipif->ipif_isv6);
19484 		/*
19485 		 * As we may lose the conn by the time we reach ip_wput_ire,
19486 		 * we copy conn_multicast_loop and conn_dontroute on to an
19487 		 * ipsec_out. In case if this datagram goes out secure,
19488 		 * we need the ill_index also. Copy that also into the
19489 		 * ipsec_out.
19490 		 */
19491 		if (mctl_present) {
19492 			io = (ipsec_out_t *)first_mp->b_rptr;
19493 			ASSERT(first_mp->b_datap->db_type == M_CTL);
19494 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
19495 		} else {
19496 			ASSERT(mp == first_mp);
19497 			if ((first_mp = allocb(sizeof (ipsec_info_t),
19498 			    BPRI_HI)) == NULL) {
19499 				ipif_refrele(ipif);
19500 				first_mp = mp;
19501 				goto drop_pkt;
19502 			}
19503 			first_mp->b_datap->db_type = M_CTL;
19504 			first_mp->b_wptr += sizeof (ipsec_info_t);
19505 			/* ipsec_out_secure is B_FALSE now */
19506 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
19507 			io = (ipsec_out_t *)first_mp->b_rptr;
19508 			io->ipsec_out_type = IPSEC_OUT;
19509 			io->ipsec_out_len = sizeof (ipsec_out_t);
19510 			io->ipsec_out_use_global_policy = B_TRUE;
19511 			first_mp->b_cont = mp;
19512 			mctl_present = B_TRUE;
19513 		}
19514 		if (attach_ill != NULL) {
19515 			ASSERT(attach_ill == ipif->ipif_ill);
19516 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19517 
19518 			/*
19519 			 * Check if we need an ire that will not be
19520 			 * looked up by anybody else i.e. HIDDEN.
19521 			 */
19522 			if (ill_is_probeonly(attach_ill)) {
19523 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19524 			}
19525 			io->ipsec_out_ill_index =
19526 			    attach_ill->ill_phyint->phyint_ifindex;
19527 			io->ipsec_out_attach_if = B_TRUE;
19528 		} else {
19529 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
19530 			io->ipsec_out_ill_index =
19531 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
19532 		}
19533 		if (connp != NULL) {
19534 			io->ipsec_out_multicast_loop =
19535 			    connp->conn_multicast_loop;
19536 			io->ipsec_out_dontroute = connp->conn_dontroute;
19537 			io->ipsec_out_zoneid = connp->conn_zoneid;
19538 		}
19539 		/*
19540 		 * If the application uses IP_MULTICAST_IF with
19541 		 * different logical addresses of the same ILL, we
19542 		 * need to make sure that the soruce address of
19543 		 * the packet matches the logical IP address used
19544 		 * in the option. We do it by initializing ipha_src
19545 		 * here. This should keep IPSEC also happy as
19546 		 * when we return from IPSEC processing, we don't
19547 		 * have to worry about getting the right address on
19548 		 * the packet. Thus it is sufficient to look for
19549 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
19550 		 * MATCH_IRE_IPIF.
19551 		 *
19552 		 * NOTE : We need to do it for non-secure case also as
19553 		 * this might go out secure if there is a global policy
19554 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
19555 		 * address, the source should be initialized already and
19556 		 * hence we won't be initializing here.
19557 		 *
19558 		 * As we do not have the ire yet, it is possible that
19559 		 * we set the source address here and then later discover
19560 		 * that the ire implies the source address to be assigned
19561 		 * through the RTF_SETSRC flag.
19562 		 * In that case, the setsrc variable will remind us
19563 		 * that overwritting the source address by the one
19564 		 * of the RTF_SETSRC-flagged ire is allowed.
19565 		 */
19566 		if (ipha->ipha_src == INADDR_ANY &&
19567 		    (connp == NULL || !connp->conn_unspec_src)) {
19568 			ipha->ipha_src = ipif->ipif_src_addr;
19569 			setsrc = RTF_SETSRC;
19570 		}
19571 		/*
19572 		 * Find an IRE which matches the destination and the outgoing
19573 		 * queue (i.e. the outgoing interface.)
19574 		 * For loopback use a unicast IP address for
19575 		 * the ire lookup.
19576 		 */
19577 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
19578 		    PHYI_LOOPBACK) {
19579 			dst = ipif->ipif_lcl_addr;
19580 		}
19581 		/*
19582 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
19583 		 * We don't need to lookup ire in ctable as the packet
19584 		 * needs to be sent to the destination through the specified
19585 		 * ill irrespective of ires in the cache table.
19586 		 */
19587 		ire = NULL;
19588 		if (xmit_ill == NULL) {
19589 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
19590 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19591 		}
19592 
19593 		/*
19594 		 * refrele attach_ill as its not needed anymore.
19595 		 */
19596 		if (attach_ill != NULL) {
19597 			ill_refrele(attach_ill);
19598 			attach_ill = NULL;
19599 		}
19600 
19601 		if (ire == NULL) {
19602 			/*
19603 			 * Multicast loopback and multicast forwarding is
19604 			 * done in ip_wput_ire.
19605 			 *
19606 			 * Mark this packet to make it be delivered to
19607 			 * ip_wput_ire after the new ire has been
19608 			 * created.
19609 			 *
19610 			 * The call to ip_newroute_ipif takes into account
19611 			 * the setsrc reminder. In any case, we take care
19612 			 * of the RTF_MULTIRT flag.
19613 			 */
19614 			mp->b_prev = mp->b_next = NULL;
19615 			if (xmit_ill == NULL ||
19616 			    xmit_ill->ill_ipif_up_count > 0) {
19617 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
19618 				    setsrc | RTF_MULTIRT);
19619 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19620 				    "ip_wput_end: q %p (%S)", q, "noire");
19621 			} else {
19622 				freemsg(first_mp);
19623 			}
19624 			ipif_refrele(ipif);
19625 			if (xmit_ill != NULL)
19626 				ill_refrele(xmit_ill);
19627 			if (need_decref)
19628 				CONN_DEC_REF(connp);
19629 			return;
19630 		}
19631 
19632 		ipif_refrele(ipif);
19633 		ipif = NULL;
19634 		ASSERT(xmit_ill == NULL);
19635 
19636 		/*
19637 		 * Honor the RTF_SETSRC flag for multicast packets,
19638 		 * if allowed by the setsrc reminder.
19639 		 */
19640 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
19641 			ipha->ipha_src = ire->ire_src_addr;
19642 		}
19643 
19644 		/*
19645 		 * Unconditionally force the TTL to 1 for
19646 		 * multirouted multicast packets:
19647 		 * multirouted multicast should not cross
19648 		 * multicast routers.
19649 		 */
19650 		if (ire->ire_flags & RTF_MULTIRT) {
19651 			if (ipha->ipha_ttl > 1) {
19652 				ip2dbg(("ip_wput: forcing multicast "
19653 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
19654 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
19655 				ipha->ipha_ttl = 1;
19656 			}
19657 		}
19658 	} else {
19659 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19660 		if ((ire != NULL) && (ire->ire_type &
19661 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
19662 			ignore_dontroute = B_TRUE;
19663 			ignore_nexthop = B_TRUE;
19664 		}
19665 		if (ire != NULL) {
19666 			ire_refrele(ire);
19667 			ire = NULL;
19668 		}
19669 		/*
19670 		 * Guard against coming in from arp in which case conn is NULL.
19671 		 * Also guard against non M_DATA with dontroute set but
19672 		 * destined to local, loopback or broadcast addresses.
19673 		 */
19674 		if (connp != NULL && connp->conn_dontroute &&
19675 		    !ignore_dontroute) {
19676 dontroute:
19677 			/*
19678 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
19679 			 * routing protocols from seeing false direct
19680 			 * connectivity.
19681 			 */
19682 			ipha->ipha_ttl = 1;
19683 			/*
19684 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
19685 			 * along with SO_DONTROUTE, higher precedence is
19686 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
19687 			 */
19688 			if (connp->conn_xmit_if_ill == NULL) {
19689 				/* If suitable ipif not found, drop packet */
19690 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
19691 				if (dst_ipif == NULL) {
19692 					ip1dbg(("ip_wput: no route for "
19693 					    "dst using SO_DONTROUTE\n"));
19694 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19695 					mp->b_prev = mp->b_next = NULL;
19696 					if (first_mp == NULL)
19697 						first_mp = mp;
19698 					goto drop_pkt;
19699 				} else {
19700 					/*
19701 					 * If suitable ipif has been found, set
19702 					 * xmit_ill to the corresponding
19703 					 * ipif_ill because we'll be following
19704 					 * the IP_XMIT_IF logic.
19705 					 */
19706 					ASSERT(xmit_ill == NULL);
19707 					xmit_ill = dst_ipif->ipif_ill;
19708 					mutex_enter(&xmit_ill->ill_lock);
19709 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
19710 						mutex_exit(&xmit_ill->ill_lock);
19711 						xmit_ill = NULL;
19712 						ipif_refrele(dst_ipif);
19713 						ip1dbg(("ip_wput: no route for"
19714 						    " dst using"
19715 						    " SO_DONTROUTE\n"));
19716 						BUMP_MIB(&ip_mib,
19717 						    ipOutNoRoutes);
19718 						mp->b_prev = mp->b_next = NULL;
19719 						if (first_mp == NULL)
19720 							first_mp = mp;
19721 						goto drop_pkt;
19722 					}
19723 					ill_refhold_locked(xmit_ill);
19724 					mutex_exit(&xmit_ill->ill_lock);
19725 					ipif_refrele(dst_ipif);
19726 				}
19727 			}
19728 
19729 		}
19730 		/*
19731 		 * If we are bound to IPIF_NOFAILOVER address, look for
19732 		 * an IRE_CACHE matching the ill.
19733 		 */
19734 send_from_ill:
19735 		if (attach_ill != NULL) {
19736 			ipif_t	*attach_ipif;
19737 
19738 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19739 
19740 			/*
19741 			 * Check if we need an ire that will not be
19742 			 * looked up by anybody else i.e. HIDDEN.
19743 			 */
19744 			if (ill_is_probeonly(attach_ill)) {
19745 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19746 			}
19747 
19748 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
19749 			if (attach_ipif == NULL) {
19750 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
19751 				goto drop_pkt;
19752 			}
19753 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
19754 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19755 			ipif_refrele(attach_ipif);
19756 		} else if (xmit_ill != NULL || (connp != NULL &&
19757 			    connp->conn_xmit_if_ill != NULL)) {
19758 			/*
19759 			 * Mark this packet as originated locally
19760 			 */
19761 			mp->b_prev = mp->b_next = NULL;
19762 			/*
19763 			 * xmit_ill could be NULL if SO_DONTROUTE
19764 			 * is also set.
19765 			 */
19766 			if (xmit_ill == NULL) {
19767 				xmit_ill = conn_get_held_ill(connp,
19768 				    &connp->conn_xmit_if_ill, &err);
19769 				if (err == ILL_LOOKUP_FAILED) {
19770 					if (need_decref)
19771 						CONN_DEC_REF(connp);
19772 					freemsg(first_mp);
19773 					return;
19774 				}
19775 				if (xmit_ill == NULL) {
19776 					if (connp->conn_dontroute)
19777 						goto dontroute;
19778 					goto send_from_ill;
19779 				}
19780 			}
19781 			/*
19782 			 * could be SO_DONTROUTE case also.
19783 			 * check at least one interface is UP as
19784 			 * spcified by this ILL, and then call
19785 			 * ip_newroute_ipif()
19786 			 */
19787 			if (xmit_ill->ill_ipif_up_count > 0) {
19788 				ipif_t *ipif;
19789 
19790 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19791 				if (ipif != NULL) {
19792 					ip_newroute_ipif(q, first_mp, ipif,
19793 					    dst, connp, 0);
19794 					ipif_refrele(ipif);
19795 					ip1dbg(("ip_wput: ip_unicast_if\n"));
19796 				}
19797 			} else {
19798 				freemsg(first_mp);
19799 			}
19800 			ill_refrele(xmit_ill);
19801 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19802 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
19803 			if (need_decref)
19804 				CONN_DEC_REF(connp);
19805 			return;
19806 		} else if (ip_nexthop || (connp != NULL &&
19807 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
19808 			if (!ip_nexthop) {
19809 				ip_nexthop = B_TRUE;
19810 				nexthop_addr = connp->conn_nexthop_v4;
19811 			}
19812 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
19813 			    MATCH_IRE_GW;
19814 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19815 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
19816 		} else {
19817 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19818 		}
19819 		if (!ire) {
19820 			/*
19821 			 * Make sure we don't load spread if this
19822 			 * is IPIF_NOFAILOVER case.
19823 			 */
19824 			if ((attach_ill != NULL) ||
19825 			    (ip_nexthop && !ignore_nexthop)) {
19826 				if (mctl_present) {
19827 					io = (ipsec_out_t *)first_mp->b_rptr;
19828 					ASSERT(first_mp->b_datap->db_type ==
19829 					    M_CTL);
19830 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19831 				} else {
19832 					ASSERT(mp == first_mp);
19833 					first_mp = allocb(
19834 					    sizeof (ipsec_info_t), BPRI_HI);
19835 					if (first_mp == NULL) {
19836 						first_mp = mp;
19837 						goto drop_pkt;
19838 					}
19839 					first_mp->b_datap->db_type = M_CTL;
19840 					first_mp->b_wptr +=
19841 					    sizeof (ipsec_info_t);
19842 					/* ipsec_out_secure is B_FALSE now */
19843 					bzero(first_mp->b_rptr,
19844 					    sizeof (ipsec_info_t));
19845 					io = (ipsec_out_t *)first_mp->b_rptr;
19846 					io->ipsec_out_type = IPSEC_OUT;
19847 					io->ipsec_out_len =
19848 					    sizeof (ipsec_out_t);
19849 					io->ipsec_out_use_global_policy =
19850 					    B_TRUE;
19851 					first_mp->b_cont = mp;
19852 					mctl_present = B_TRUE;
19853 				}
19854 				if (attach_ill != NULL) {
19855 					io->ipsec_out_ill_index = attach_ill->
19856 					    ill_phyint->phyint_ifindex;
19857 					io->ipsec_out_attach_if = B_TRUE;
19858 				} else {
19859 					io->ipsec_out_ip_nexthop = ip_nexthop;
19860 					io->ipsec_out_nexthop_addr =
19861 					    nexthop_addr;
19862 				}
19863 			}
19864 noirefound:
19865 			/*
19866 			 * Mark this packet as having originated on
19867 			 * this machine.  This will be noted in
19868 			 * ire_add_then_send, which needs to know
19869 			 * whether to run it back through ip_wput or
19870 			 * ip_rput following successful resolution.
19871 			 */
19872 			mp->b_prev = NULL;
19873 			mp->b_next = NULL;
19874 			ip_newroute(q, first_mp, dst, NULL, connp);
19875 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19876 			    "ip_wput_end: q %p (%S)", q, "newroute");
19877 			if (attach_ill != NULL)
19878 				ill_refrele(attach_ill);
19879 			if (xmit_ill != NULL)
19880 				ill_refrele(xmit_ill);
19881 			if (need_decref)
19882 				CONN_DEC_REF(connp);
19883 			return;
19884 		}
19885 	}
19886 
19887 	/* We now know where we are going with it. */
19888 
19889 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19890 	    "ip_wput_end: q %p (%S)", q, "end");
19891 
19892 	/*
19893 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19894 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19895 	 */
19896 	if (ire->ire_flags & RTF_MULTIRT) {
19897 		/*
19898 		 * Force the TTL of multirouted packets if required.
19899 		 * The TTL of such packets is bounded by the
19900 		 * ip_multirt_ttl ndd variable.
19901 		 */
19902 		if ((ip_multirt_ttl > 0) &&
19903 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19904 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19905 			    "(was %d), dst 0x%08x\n",
19906 			    ip_multirt_ttl, ipha->ipha_ttl,
19907 			    ntohl(ire->ire_addr)));
19908 			ipha->ipha_ttl = ip_multirt_ttl;
19909 		}
19910 		/*
19911 		 * At this point, we check to see if there are any pending
19912 		 * unresolved routes. ire_multirt_resolvable()
19913 		 * checks in O(n) that all IRE_OFFSUBNET ire
19914 		 * entries for the packet's destination and
19915 		 * flagged RTF_MULTIRT are currently resolved.
19916 		 * If some remain unresolved, we make a copy
19917 		 * of the current message. It will be used
19918 		 * to initiate additional route resolutions.
19919 		 */
19920 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19921 		    MBLK_GETLABEL(first_mp));
19922 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19923 		    "multirt_need_resolve %d, first_mp %p\n",
19924 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19925 		if (multirt_need_resolve) {
19926 			copy_mp = copymsg(first_mp);
19927 			if (copy_mp != NULL) {
19928 				MULTIRT_DEBUG_TAG(copy_mp);
19929 			}
19930 		}
19931 	}
19932 
19933 	ip_wput_ire(q, first_mp, ire, connp, caller);
19934 	/*
19935 	 * Try to resolve another multiroute if
19936 	 * ire_multirt_resolvable() deemed it necessary.
19937 	 * At this point, we need to distinguish
19938 	 * multicasts from other packets. For multicasts,
19939 	 * we call ip_newroute_ipif() and request that both
19940 	 * multirouting and setsrc flags are checked.
19941 	 */
19942 	if (copy_mp != NULL) {
19943 		if (CLASSD(dst)) {
19944 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19945 			if (ipif) {
19946 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19947 				    RTF_SETSRC | RTF_MULTIRT);
19948 				ipif_refrele(ipif);
19949 			} else {
19950 				MULTIRT_DEBUG_UNTAG(copy_mp);
19951 				freemsg(copy_mp);
19952 				copy_mp = NULL;
19953 			}
19954 		} else {
19955 			ip_newroute(q, copy_mp, dst, NULL, connp);
19956 		}
19957 	}
19958 	if (attach_ill != NULL)
19959 		ill_refrele(attach_ill);
19960 	if (xmit_ill != NULL)
19961 		ill_refrele(xmit_ill);
19962 	if (need_decref)
19963 		CONN_DEC_REF(connp);
19964 	return;
19965 
19966 icmp_parameter_problem:
19967 	/* could not have originated externally */
19968 	ASSERT(mp->b_prev == NULL);
19969 	if (ip_hdr_complete(ipha, zoneid) == 0) {
19970 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
19971 		/* it's the IP header length that's in trouble */
19972 		icmp_param_problem(q, first_mp, 0);
19973 		first_mp = NULL;
19974 	}
19975 
19976 drop_pkt:
19977 	ip1dbg(("ip_wput: dropped packet\n"));
19978 	if (ire != NULL)
19979 		ire_refrele(ire);
19980 	if (need_decref)
19981 		CONN_DEC_REF(connp);
19982 	freemsg(first_mp);
19983 	if (attach_ill != NULL)
19984 		ill_refrele(attach_ill);
19985 	if (xmit_ill != NULL)
19986 		ill_refrele(xmit_ill);
19987 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19988 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19989 }
19990 
19991 void
19992 ip_wput(queue_t *q, mblk_t *mp)
19993 {
19994 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19995 }
19996 
19997 /*
19998  *
19999  * The following rules must be observed when accessing any ipif or ill
20000  * that has been cached in the conn. Typically conn_nofailover_ill,
20001  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20002  *
20003  * Access: The ipif or ill pointed to from the conn can be accessed under
20004  * the protection of the conn_lock or after it has been refheld under the
20005  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20006  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20007  * The reason for this is that a concurrent unplumb could actually be
20008  * cleaning up these cached pointers by walking the conns and might have
20009  * finished cleaning up the conn in question. The macros check that an
20010  * unplumb has not yet started on the ipif or ill.
20011  *
20012  * Caching: An ipif or ill pointer may be cached in the conn only after
20013  * making sure that an unplumb has not started. So the caching is done
20014  * while holding both the conn_lock and the ill_lock and after using the
20015  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20016  * flag before starting the cleanup of conns.
20017  *
20018  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20019  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20020  * or a reference to the ipif or a reference to an ire that references the
20021  * ipif. An ipif does not change its ill except for failover/failback. Since
20022  * failover/failback happens only after bringing down the ipif and making sure
20023  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20024  * the above holds.
20025  */
20026 ipif_t *
20027 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20028 {
20029 	ipif_t	*ipif;
20030 	ill_t	*ill;
20031 
20032 	*err = 0;
20033 	rw_enter(&ill_g_lock, RW_READER);
20034 	mutex_enter(&connp->conn_lock);
20035 	ipif = *ipifp;
20036 	if (ipif != NULL) {
20037 		ill = ipif->ipif_ill;
20038 		mutex_enter(&ill->ill_lock);
20039 		if (IPIF_CAN_LOOKUP(ipif)) {
20040 			ipif_refhold_locked(ipif);
20041 			mutex_exit(&ill->ill_lock);
20042 			mutex_exit(&connp->conn_lock);
20043 			rw_exit(&ill_g_lock);
20044 			return (ipif);
20045 		} else {
20046 			*err = IPIF_LOOKUP_FAILED;
20047 		}
20048 		mutex_exit(&ill->ill_lock);
20049 	}
20050 	mutex_exit(&connp->conn_lock);
20051 	rw_exit(&ill_g_lock);
20052 	return (NULL);
20053 }
20054 
20055 ill_t *
20056 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20057 {
20058 	ill_t	*ill;
20059 
20060 	*err = 0;
20061 	mutex_enter(&connp->conn_lock);
20062 	ill = *illp;
20063 	if (ill != NULL) {
20064 		mutex_enter(&ill->ill_lock);
20065 		if (ILL_CAN_LOOKUP(ill)) {
20066 			ill_refhold_locked(ill);
20067 			mutex_exit(&ill->ill_lock);
20068 			mutex_exit(&connp->conn_lock);
20069 			return (ill);
20070 		} else {
20071 			*err = ILL_LOOKUP_FAILED;
20072 		}
20073 		mutex_exit(&ill->ill_lock);
20074 	}
20075 	mutex_exit(&connp->conn_lock);
20076 	return (NULL);
20077 }
20078 
20079 static int
20080 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20081 {
20082 	ill_t	*ill;
20083 
20084 	ill = ipif->ipif_ill;
20085 	mutex_enter(&connp->conn_lock);
20086 	mutex_enter(&ill->ill_lock);
20087 	if (IPIF_CAN_LOOKUP(ipif)) {
20088 		*ipifp = ipif;
20089 		mutex_exit(&ill->ill_lock);
20090 		mutex_exit(&connp->conn_lock);
20091 		return (0);
20092 	}
20093 	mutex_exit(&ill->ill_lock);
20094 	mutex_exit(&connp->conn_lock);
20095 	return (IPIF_LOOKUP_FAILED);
20096 }
20097 
20098 /*
20099  * This is called if the outbound datagram needs fragmentation.
20100  *
20101  * NOTE : This function does not ire_refrele the ire argument passed in.
20102  */
20103 static void
20104 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20105 {
20106 	ipha_t		*ipha;
20107 	mblk_t		*mp;
20108 	uint32_t	v_hlen_tos_len;
20109 	uint32_t	max_frag;
20110 	uint32_t	frag_flag;
20111 	boolean_t	dont_use;
20112 
20113 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20114 		mp = ipsec_mp->b_cont;
20115 	} else {
20116 		mp = ipsec_mp;
20117 	}
20118 
20119 	ipha = (ipha_t *)mp->b_rptr;
20120 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20121 
20122 #ifdef	_BIG_ENDIAN
20123 #define	V_HLEN	(v_hlen_tos_len >> 24)
20124 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20125 #else
20126 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20127 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20128 #endif
20129 
20130 #ifndef SPEED_BEFORE_SAFETY
20131 	/*
20132 	 * Check that ipha_length is consistent with
20133 	 * the mblk length
20134 	 */
20135 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20136 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20137 		    LENGTH, msgdsize(mp)));
20138 		freemsg(ipsec_mp);
20139 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20140 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20141 		    "packet length mismatch");
20142 		return;
20143 	}
20144 #endif
20145 	/*
20146 	 * Don't use frag_flag if pre-built packet or source
20147 	 * routed or if multicast (since multicast packets do not solicit
20148 	 * ICMP "packet too big" messages). Get the values of
20149 	 * max_frag and frag_flag atomically by acquiring the
20150 	 * ire_lock.
20151 	 */
20152 	mutex_enter(&ire->ire_lock);
20153 	max_frag = ire->ire_max_frag;
20154 	frag_flag = ire->ire_frag_flag;
20155 	mutex_exit(&ire->ire_lock);
20156 
20157 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20158 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20159 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20160 
20161 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20162 	    (dont_use ? 0 : frag_flag));
20163 }
20164 
20165 /*
20166  * Used for deciding the MSS size for the upper layer. Thus
20167  * we need to check the outbound policy values in the conn.
20168  */
20169 int
20170 conn_ipsec_length(conn_t *connp)
20171 {
20172 	ipsec_latch_t *ipl;
20173 
20174 	ipl = connp->conn_latch;
20175 	if (ipl == NULL)
20176 		return (0);
20177 
20178 	if (ipl->ipl_out_policy == NULL)
20179 		return (0);
20180 
20181 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20182 }
20183 
20184 /*
20185  * Returns an estimate of the IPSEC headers size. This is used if
20186  * we don't want to call into IPSEC to get the exact size.
20187  */
20188 int
20189 ipsec_out_extra_length(mblk_t *ipsec_mp)
20190 {
20191 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20192 	ipsec_action_t *a;
20193 
20194 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20195 	if (!io->ipsec_out_secure)
20196 		return (0);
20197 
20198 	a = io->ipsec_out_act;
20199 
20200 	if (a == NULL) {
20201 		ASSERT(io->ipsec_out_policy != NULL);
20202 		a = io->ipsec_out_policy->ipsp_act;
20203 	}
20204 	ASSERT(a != NULL);
20205 
20206 	return (a->ipa_ovhd);
20207 }
20208 
20209 /*
20210  * Returns an estimate of the IPSEC headers size. This is used if
20211  * we don't want to call into IPSEC to get the exact size.
20212  */
20213 int
20214 ipsec_in_extra_length(mblk_t *ipsec_mp)
20215 {
20216 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20217 	ipsec_action_t *a;
20218 
20219 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20220 
20221 	a = ii->ipsec_in_action;
20222 	return (a == NULL ? 0 : a->ipa_ovhd);
20223 }
20224 
20225 /*
20226  * If there are any source route options, return the true final
20227  * destination. Otherwise, return the destination.
20228  */
20229 ipaddr_t
20230 ip_get_dst(ipha_t *ipha)
20231 {
20232 	ipoptp_t	opts;
20233 	uchar_t		*opt;
20234 	uint8_t		optval;
20235 	uint8_t		optlen;
20236 	ipaddr_t	dst;
20237 	uint32_t off;
20238 
20239 	dst = ipha->ipha_dst;
20240 
20241 	if (IS_SIMPLE_IPH(ipha))
20242 		return (dst);
20243 
20244 	for (optval = ipoptp_first(&opts, ipha);
20245 	    optval != IPOPT_EOL;
20246 	    optval = ipoptp_next(&opts)) {
20247 		opt = opts.ipoptp_cur;
20248 		optlen = opts.ipoptp_len;
20249 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20250 		switch (optval) {
20251 		case IPOPT_SSRR:
20252 		case IPOPT_LSRR:
20253 			off = opt[IPOPT_OFFSET];
20254 			/*
20255 			 * If one of the conditions is true, it means
20256 			 * end of options and dst already has the right
20257 			 * value.
20258 			 */
20259 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20260 				off = optlen - IP_ADDR_LEN;
20261 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20262 			}
20263 			return (dst);
20264 		default:
20265 			break;
20266 		}
20267 	}
20268 
20269 	return (dst);
20270 }
20271 
20272 mblk_t *
20273 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20274     conn_t *connp, boolean_t unspec_src)
20275 {
20276 	ipsec_out_t	*io;
20277 	mblk_t		*first_mp;
20278 	boolean_t policy_present;
20279 
20280 	first_mp = mp;
20281 	if (mp->b_datap->db_type == M_CTL) {
20282 		io = (ipsec_out_t *)first_mp->b_rptr;
20283 		/*
20284 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20285 		 *
20286 		 * 1) There is per-socket policy (including cached global
20287 		 *    policy).
20288 		 * 2) There is no per-socket policy, but it is
20289 		 *    a multicast packet that needs to go out
20290 		 *    on a specific interface. This is the case
20291 		 *    where (ip_wput and ip_wput_multicast) attaches
20292 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20293 		 *
20294 		 * In case (2) we check with global policy to
20295 		 * see if there is a match and set the ill_index
20296 		 * appropriately so that we can lookup the ire
20297 		 * properly in ip_wput_ipsec_out.
20298 		 */
20299 
20300 		/*
20301 		 * ipsec_out_use_global_policy is set to B_FALSE
20302 		 * in ipsec_in_to_out(). Refer to that function for
20303 		 * details.
20304 		 */
20305 		if ((io->ipsec_out_latch == NULL) &&
20306 		    (io->ipsec_out_use_global_policy)) {
20307 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20308 			    ire, connp, unspec_src));
20309 		}
20310 		if (!io->ipsec_out_secure) {
20311 			/*
20312 			 * If this is not a secure packet, drop
20313 			 * the IPSEC_OUT mp and treat it as a clear
20314 			 * packet. This happens when we are sending
20315 			 * a ICMP reply back to a clear packet. See
20316 			 * ipsec_in_to_out() for details.
20317 			 */
20318 			mp = first_mp->b_cont;
20319 			freeb(first_mp);
20320 		}
20321 		return (mp);
20322 	}
20323 	/*
20324 	 * See whether we need to attach a global policy here. We
20325 	 * don't depend on the conn (as it could be null) for deciding
20326 	 * what policy this datagram should go through because it
20327 	 * should have happened in ip_wput if there was some
20328 	 * policy. This normally happens for connections which are not
20329 	 * fully bound preventing us from caching policies in
20330 	 * ip_bind. Packets coming from the TCP listener/global queue
20331 	 * - which are non-hard_bound - could also be affected by
20332 	 * applying policy here.
20333 	 *
20334 	 * If this packet is coming from tcp global queue or listener,
20335 	 * we will be applying policy here.  This may not be *right*
20336 	 * if these packets are coming from the detached connection as
20337 	 * it could have gone in clear before. This happens only if a
20338 	 * TCP connection started when there is no policy and somebody
20339 	 * added policy before it became detached. Thus packets of the
20340 	 * detached connection could go out secure and the other end
20341 	 * would drop it because it will be expecting in clear. The
20342 	 * converse is not true i.e if somebody starts a TCP
20343 	 * connection and deletes the policy, all the packets will
20344 	 * still go out with the policy that existed before deleting
20345 	 * because ip_unbind sends up policy information which is used
20346 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20347 	 * TCP to attach a dummy IPSEC_OUT and set
20348 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20349 	 * affect performance for normal cases, we are not doing it.
20350 	 * Thus, set policy before starting any TCP connections.
20351 	 *
20352 	 * NOTE - We might apply policy even for a hard bound connection
20353 	 * - for which we cached policy in ip_bind - if somebody added
20354 	 * global policy after we inherited the policy in ip_bind.
20355 	 * This means that the packets that were going out in clear
20356 	 * previously would start going secure and hence get dropped
20357 	 * on the other side. To fix this, TCP attaches a dummy
20358 	 * ipsec_out and make sure that we don't apply global policy.
20359 	 */
20360 	if (ipha != NULL)
20361 		policy_present = ipsec_outbound_v4_policy_present;
20362 	else
20363 		policy_present = ipsec_outbound_v6_policy_present;
20364 	if (!policy_present)
20365 		return (mp);
20366 
20367 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20368 }
20369 
20370 ire_t *
20371 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20372 {
20373 	ipaddr_t addr;
20374 	ire_t *save_ire;
20375 	irb_t *irb;
20376 	ill_group_t *illgrp;
20377 	int	err;
20378 
20379 	save_ire = ire;
20380 	addr = ire->ire_addr;
20381 
20382 	ASSERT(ire->ire_type == IRE_BROADCAST);
20383 
20384 	illgrp = connp->conn_outgoing_ill->ill_group;
20385 	if (illgrp == NULL) {
20386 		*conn_outgoing_ill = conn_get_held_ill(connp,
20387 		    &connp->conn_outgoing_ill, &err);
20388 		if (err == ILL_LOOKUP_FAILED) {
20389 			ire_refrele(save_ire);
20390 			return (NULL);
20391 		}
20392 		return (save_ire);
20393 	}
20394 	/*
20395 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20396 	 * If it is part of the group, we need to send on the ire
20397 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20398 	 * to this group. This is okay as IP_BOUND_IF really means
20399 	 * any ill in the group. We depend on the fact that the
20400 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20401 	 * if such an ire exists. This is possible only if you have
20402 	 * at least one ill in the group that has not failed.
20403 	 *
20404 	 * First get to the ire that matches the address and group.
20405 	 *
20406 	 * We don't look for an ire with a matching zoneid because a given zone
20407 	 * won't always have broadcast ires on all ills in the group.
20408 	 */
20409 	irb = ire->ire_bucket;
20410 	rw_enter(&irb->irb_lock, RW_READER);
20411 	if (ire->ire_marks & IRE_MARK_NORECV) {
20412 		/*
20413 		 * If the current zone only has an ire broadcast for this
20414 		 * address marked NORECV, the ire we want is ahead in the
20415 		 * bucket, so we look it up deliberately ignoring the zoneid.
20416 		 */
20417 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
20418 			if (ire->ire_addr != addr)
20419 				continue;
20420 			/* skip over deleted ires */
20421 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
20422 				continue;
20423 		}
20424 	}
20425 	while (ire != NULL) {
20426 		/*
20427 		 * If a new interface is coming up, we could end up
20428 		 * seeing the loopback ire and the non-loopback ire
20429 		 * may not have been added yet. So check for ire_stq
20430 		 */
20431 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
20432 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
20433 			break;
20434 		}
20435 		ire = ire->ire_next;
20436 	}
20437 	if (ire != NULL && ire->ire_addr == addr &&
20438 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
20439 		IRE_REFHOLD(ire);
20440 		rw_exit(&irb->irb_lock);
20441 		ire_refrele(save_ire);
20442 		*conn_outgoing_ill = ire_to_ill(ire);
20443 		/*
20444 		 * Refhold the ill to make the conn_outgoing_ill
20445 		 * independent of the ire. ip_wput_ire goes in a loop
20446 		 * and may refrele the ire. Since we have an ire at this
20447 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
20448 		 */
20449 		ill_refhold(*conn_outgoing_ill);
20450 		return (ire);
20451 	}
20452 	rw_exit(&irb->irb_lock);
20453 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
20454 	/*
20455 	 * If we can't find a suitable ire, return the original ire.
20456 	 */
20457 	return (save_ire);
20458 }
20459 
20460 /*
20461  * This function does the ire_refrele of the ire passed in as the
20462  * argument. As this function looks up more ires i.e broadcast ires,
20463  * it needs to REFRELE them. Currently, for simplicity we don't
20464  * differentiate the one passed in and looked up here. We always
20465  * REFRELE.
20466  * IPQoS Notes:
20467  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
20468  * IPSec packets are done in ipsec_out_process.
20469  *
20470  */
20471 void
20472 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
20473 {
20474 	ipha_t		*ipha;
20475 #define	rptr	((uchar_t *)ipha)
20476 	mblk_t		*mp1;
20477 	queue_t		*stq;
20478 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
20479 	uint32_t	v_hlen_tos_len;
20480 	uint32_t	ttl_protocol;
20481 	ipaddr_t	src;
20482 	ipaddr_t	dst;
20483 	uint32_t	cksum;
20484 	ipaddr_t	orig_src;
20485 	ire_t		*ire1;
20486 	mblk_t		*next_mp;
20487 	uint_t		hlen;
20488 	uint16_t	*up;
20489 	uint32_t	max_frag = ire->ire_max_frag;
20490 	ill_t		*ill = ire_to_ill(ire);
20491 	int		clusterwide;
20492 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
20493 	int		ipsec_len;
20494 	mblk_t		*first_mp;
20495 	ipsec_out_t	*io;
20496 	boolean_t	conn_dontroute;		/* conn value for multicast */
20497 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
20498 	boolean_t	multicast_forward;	/* Should we forward ? */
20499 	boolean_t	unspec_src;
20500 	ill_t		*conn_outgoing_ill = NULL;
20501 	ill_t		*ire_ill;
20502 	ill_t		*ire1_ill;
20503 	uint32_t 	ill_index = 0;
20504 	boolean_t	multirt_send = B_FALSE;
20505 	int		err;
20506 	zoneid_t	zoneid;
20507 
20508 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
20509 	    "ip_wput_ire_start: q %p", q);
20510 
20511 	multicast_forward = B_FALSE;
20512 	unspec_src = (connp != NULL && connp->conn_unspec_src);
20513 
20514 	if (ire->ire_flags & RTF_MULTIRT) {
20515 		/*
20516 		 * Multirouting case. The bucket where ire is stored
20517 		 * probably holds other RTF_MULTIRT flagged ire
20518 		 * to the destination. In this call to ip_wput_ire,
20519 		 * we attempt to send the packet through all
20520 		 * those ires. Thus, we first ensure that ire is the
20521 		 * first RTF_MULTIRT ire in the bucket,
20522 		 * before walking the ire list.
20523 		 */
20524 		ire_t *first_ire;
20525 		irb_t *irb = ire->ire_bucket;
20526 		ASSERT(irb != NULL);
20527 
20528 		/* Make sure we do not omit any multiroute ire. */
20529 		IRB_REFHOLD(irb);
20530 		for (first_ire = irb->irb_ire;
20531 		    first_ire != NULL;
20532 		    first_ire = first_ire->ire_next) {
20533 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
20534 			    (first_ire->ire_addr == ire->ire_addr) &&
20535 			    !(first_ire->ire_marks &
20536 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
20537 				break;
20538 		}
20539 
20540 		if ((first_ire != NULL) && (first_ire != ire)) {
20541 			IRE_REFHOLD(first_ire);
20542 			ire_refrele(ire);
20543 			ire = first_ire;
20544 			ill = ire_to_ill(ire);
20545 		}
20546 		IRB_REFRELE(irb);
20547 	}
20548 
20549 	/*
20550 	 * conn_outgoing_ill is used only in the broadcast loop.
20551 	 * for performance we don't grab the mutexs in the fastpath
20552 	 */
20553 	if ((connp != NULL) &&
20554 	    (connp->conn_xmit_if_ill == NULL) &&
20555 	    (ire->ire_type == IRE_BROADCAST) &&
20556 	    ((connp->conn_nofailover_ill != NULL) ||
20557 	    (connp->conn_outgoing_ill != NULL))) {
20558 		/*
20559 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
20560 		 * option. So, see if this endpoint is bound to a
20561 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
20562 		 * that if the interface is failed, we will still send
20563 		 * the packet on the same ill which is what we want.
20564 		 */
20565 		conn_outgoing_ill = conn_get_held_ill(connp,
20566 		    &connp->conn_nofailover_ill, &err);
20567 		if (err == ILL_LOOKUP_FAILED) {
20568 			ire_refrele(ire);
20569 			freemsg(mp);
20570 			return;
20571 		}
20572 		if (conn_outgoing_ill == NULL) {
20573 			/*
20574 			 * Choose a good ill in the group to send the
20575 			 * packets on.
20576 			 */
20577 			ire = conn_set_outgoing_ill(connp, ire,
20578 			    &conn_outgoing_ill);
20579 			if (ire == NULL) {
20580 				freemsg(mp);
20581 				return;
20582 			}
20583 		}
20584 	}
20585 
20586 	if (mp->b_datap->db_type != M_CTL) {
20587 		ipha = (ipha_t *)mp->b_rptr;
20588 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
20589 	} else {
20590 		io = (ipsec_out_t *)mp->b_rptr;
20591 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20592 		zoneid = io->ipsec_out_zoneid;
20593 		ASSERT(zoneid != ALL_ZONES);
20594 		ipha = (ipha_t *)mp->b_cont->b_rptr;
20595 		dst = ipha->ipha_dst;
20596 		/*
20597 		 * For the multicast case, ipsec_out carries conn_dontroute and
20598 		 * conn_multicast_loop as conn may not be available here. We
20599 		 * need this for multicast loopback and forwarding which is done
20600 		 * later in the code.
20601 		 */
20602 		if (CLASSD(dst)) {
20603 			conn_dontroute = io->ipsec_out_dontroute;
20604 			conn_multicast_loop = io->ipsec_out_multicast_loop;
20605 			/*
20606 			 * If conn_dontroute is not set or conn_multicast_loop
20607 			 * is set, we need to do forwarding/loopback. For
20608 			 * datagrams from ip_wput_multicast, conn_dontroute is
20609 			 * set to B_TRUE and conn_multicast_loop is set to
20610 			 * B_FALSE so that we neither do forwarding nor
20611 			 * loopback.
20612 			 */
20613 			if (!conn_dontroute || conn_multicast_loop)
20614 				multicast_forward = B_TRUE;
20615 		}
20616 	}
20617 
20618 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
20619 	    ire->ire_zoneid != ALL_ZONES) {
20620 		/*
20621 		 * When a zone sends a packet to another zone, we try to deliver
20622 		 * the packet under the same conditions as if the destination
20623 		 * was a real node on the network. To do so, we look for a
20624 		 * matching route in the forwarding table.
20625 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
20626 		 * ip_newroute() does.
20627 		 */
20628 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
20629 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
20630 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
20631 		if (src_ire != NULL &&
20632 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
20633 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
20634 				ipha->ipha_src = src_ire->ire_src_addr;
20635 			ire_refrele(src_ire);
20636 		} else {
20637 			ire_refrele(ire);
20638 			if (conn_outgoing_ill != NULL)
20639 				ill_refrele(conn_outgoing_ill);
20640 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
20641 			if (src_ire != NULL) {
20642 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
20643 					ire_refrele(src_ire);
20644 					freemsg(mp);
20645 					return;
20646 				}
20647 				ire_refrele(src_ire);
20648 			}
20649 			if (ip_hdr_complete(ipha, zoneid)) {
20650 				/* Failed */
20651 				freemsg(mp);
20652 				return;
20653 			}
20654 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
20655 			return;
20656 		}
20657 	}
20658 
20659 	if (mp->b_datap->db_type == M_CTL ||
20660 	    ipsec_outbound_v4_policy_present) {
20661 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
20662 		    unspec_src);
20663 		if (mp == NULL) {
20664 			ire_refrele(ire);
20665 			if (conn_outgoing_ill != NULL)
20666 				ill_refrele(conn_outgoing_ill);
20667 			return;
20668 		}
20669 	}
20670 
20671 	first_mp = mp;
20672 	ipsec_len = 0;
20673 
20674 	if (first_mp->b_datap->db_type == M_CTL) {
20675 		io = (ipsec_out_t *)first_mp->b_rptr;
20676 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20677 		mp = first_mp->b_cont;
20678 		ipsec_len = ipsec_out_extra_length(first_mp);
20679 		ASSERT(ipsec_len >= 0);
20680 		zoneid = io->ipsec_out_zoneid;
20681 		ASSERT(zoneid != ALL_ZONES);
20682 
20683 		/*
20684 		 * Drop M_CTL here if IPsec processing is not needed.
20685 		 * (Non-IPsec use of M_CTL extracted any information it
20686 		 * needed above).
20687 		 */
20688 		if (ipsec_len == 0) {
20689 			freeb(first_mp);
20690 			first_mp = mp;
20691 		}
20692 	}
20693 
20694 	/*
20695 	 * Fast path for ip_wput_ire
20696 	 */
20697 
20698 	ipha = (ipha_t *)mp->b_rptr;
20699 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20700 	dst = ipha->ipha_dst;
20701 
20702 	/*
20703 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
20704 	 * if the socket is a SOCK_RAW type. The transport checksum should
20705 	 * be provided in the pre-built packet, so we don't need to compute it.
20706 	 * Also, other application set flags, like DF, should not be altered.
20707 	 * Other transport MUST pass down zero.
20708 	 */
20709 	ip_hdr_included = ipha->ipha_ident;
20710 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20711 
20712 	if (CLASSD(dst)) {
20713 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
20714 		    ntohl(dst),
20715 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
20716 		    ntohl(ire->ire_addr)));
20717 	}
20718 
20719 /* Macros to extract header fields from data already in registers */
20720 #ifdef	_BIG_ENDIAN
20721 #define	V_HLEN	(v_hlen_tos_len >> 24)
20722 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20723 #define	PROTO	(ttl_protocol & 0xFF)
20724 #else
20725 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20726 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20727 #define	PROTO	(ttl_protocol >> 8)
20728 #endif
20729 
20730 
20731 	orig_src = src = ipha->ipha_src;
20732 	/* (The loop back to "another" is explained down below.) */
20733 another:;
20734 	/*
20735 	 * Assign an ident value for this packet.  We assign idents on
20736 	 * a per destination basis out of the IRE.  There could be
20737 	 * other threads targeting the same destination, so we have to
20738 	 * arrange for a atomic increment.  Note that we use a 32-bit
20739 	 * atomic add because it has better performance than its
20740 	 * 16-bit sibling.
20741 	 *
20742 	 * If running in cluster mode and if the source address
20743 	 * belongs to a replicated service then vector through
20744 	 * cl_inet_ipident vector to allocate ip identifier
20745 	 * NOTE: This is a contract private interface with the
20746 	 * clustering group.
20747 	 */
20748 	clusterwide = 0;
20749 	if (cl_inet_ipident) {
20750 		ASSERT(cl_inet_isclusterwide);
20751 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20752 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
20753 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
20754 			    AF_INET, (uint8_t *)(uintptr_t)src,
20755 			    (uint8_t *)(uintptr_t)dst);
20756 			clusterwide = 1;
20757 		}
20758 	}
20759 	if (!clusterwide) {
20760 		ipha->ipha_ident =
20761 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
20762 	}
20763 
20764 #ifndef _BIG_ENDIAN
20765 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20766 #endif
20767 
20768 	/*
20769 	 * Set source address unless sent on an ill or conn_unspec_src is set.
20770 	 * This is needed to obey conn_unspec_src when packets go through
20771 	 * ip_newroute + arp.
20772 	 * Assumes ip_newroute{,_multi} sets the source address as well.
20773 	 */
20774 	if (src == INADDR_ANY && !unspec_src) {
20775 		/*
20776 		 * Assign the appropriate source address from the IRE if none
20777 		 * was specified.
20778 		 */
20779 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
20780 
20781 		/*
20782 		 * With IP multipathing, broadcast packets are sent on the ire
20783 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
20784 		 * the group. However, this ire might not be in the same zone so
20785 		 * we can't always use its source address. We look for a
20786 		 * broadcast ire in the same group and in the right zone.
20787 		 */
20788 		if (ire->ire_type == IRE_BROADCAST &&
20789 		    ire->ire_zoneid != zoneid) {
20790 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
20791 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
20792 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
20793 			if (src_ire != NULL) {
20794 				src = src_ire->ire_src_addr;
20795 				ire_refrele(src_ire);
20796 			} else {
20797 				ire_refrele(ire);
20798 				if (conn_outgoing_ill != NULL)
20799 					ill_refrele(conn_outgoing_ill);
20800 				freemsg(first_mp);
20801 				BUMP_MIB(&ip_mib, ipOutDiscards);
20802 				return;
20803 			}
20804 		} else {
20805 			src = ire->ire_src_addr;
20806 		}
20807 
20808 		if (connp == NULL) {
20809 			ip1dbg(("ip_wput_ire: no connp and no src "
20810 			    "address for dst 0x%x, using src 0x%x\n",
20811 			    ntohl(dst),
20812 			    ntohl(src)));
20813 		}
20814 		ipha->ipha_src = src;
20815 	}
20816 	stq = ire->ire_stq;
20817 
20818 	/*
20819 	 * We only allow ire chains for broadcasts since there will
20820 	 * be multiple IRE_CACHE entries for the same multicast
20821 	 * address (one per ipif).
20822 	 */
20823 	next_mp = NULL;
20824 
20825 	/* broadcast packet */
20826 	if (ire->ire_type == IRE_BROADCAST)
20827 		goto broadcast;
20828 
20829 	/* loopback ? */
20830 	if (stq == NULL)
20831 		goto nullstq;
20832 
20833 	/* The ill_index for outbound ILL */
20834 	ill_index = Q_TO_INDEX(stq);
20835 
20836 	BUMP_MIB(&ip_mib, ipOutRequests);
20837 	ttl_protocol = ((uint16_t *)ipha)[4];
20838 
20839 	/* pseudo checksum (do it in parts for IP header checksum) */
20840 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20841 
20842 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20843 		queue_t *dev_q = stq->q_next;
20844 
20845 		/* flow controlled */
20846 		if ((dev_q->q_next || dev_q->q_first) &&
20847 		    !canput(dev_q))
20848 			goto blocked;
20849 		if ((PROTO == IPPROTO_UDP) &&
20850 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20851 			hlen = (V_HLEN & 0xF) << 2;
20852 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20853 			if (*up != 0) {
20854 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20855 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20856 				/* Software checksum? */
20857 				if (DB_CKSUMFLAGS(mp) == 0) {
20858 					IP_STAT(ip_out_sw_cksum);
20859 					IP_STAT_UPDATE(
20860 					    ip_udp_out_sw_cksum_bytes,
20861 					    LENGTH - hlen);
20862 				}
20863 			}
20864 		}
20865 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20866 		hlen = (V_HLEN & 0xF) << 2;
20867 		if (PROTO == IPPROTO_TCP) {
20868 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20869 			/*
20870 			 * The packet header is processed once and for all, even
20871 			 * in the multirouting case. We disable hardware
20872 			 * checksum if the packet is multirouted, as it will be
20873 			 * replicated via several interfaces, and not all of
20874 			 * them may have this capability.
20875 			 */
20876 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20877 			    LENGTH, max_frag, ipsec_len, cksum);
20878 			/* Software checksum? */
20879 			if (DB_CKSUMFLAGS(mp) == 0) {
20880 				IP_STAT(ip_out_sw_cksum);
20881 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20882 				    LENGTH - hlen);
20883 			}
20884 		} else {
20885 			sctp_hdr_t	*sctph;
20886 
20887 			ASSERT(PROTO == IPPROTO_SCTP);
20888 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20889 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20890 			/*
20891 			 * Zero out the checksum field to ensure proper
20892 			 * checksum calculation.
20893 			 */
20894 			sctph->sh_chksum = 0;
20895 #ifdef	DEBUG
20896 			if (!skip_sctp_cksum)
20897 #endif
20898 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20899 		}
20900 	}
20901 
20902 	/*
20903 	 * If this is a multicast packet and originated from ip_wput
20904 	 * we need to do loopback and forwarding checks. If it comes
20905 	 * from ip_wput_multicast, we SHOULD not do this.
20906 	 */
20907 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20908 
20909 	/* checksum */
20910 	cksum += ttl_protocol;
20911 
20912 	/* fragment the packet */
20913 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20914 		goto fragmentit;
20915 	/*
20916 	 * Don't use frag_flag if packet is pre-built or source
20917 	 * routed or if multicast (since multicast packets do
20918 	 * not solicit ICMP "packet too big" messages).
20919 	 */
20920 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20921 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20922 	    !ip_source_route_included(ipha)) &&
20923 	    !CLASSD(ipha->ipha_dst))
20924 		ipha->ipha_fragment_offset_and_flags |=
20925 		    htons(ire->ire_frag_flag);
20926 
20927 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20928 		/* calculate IP header checksum */
20929 		cksum += ipha->ipha_ident;
20930 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20931 		cksum += ipha->ipha_fragment_offset_and_flags;
20932 
20933 		/* IP options present */
20934 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20935 		if (hlen)
20936 			goto checksumoptions;
20937 
20938 		/* calculate hdr checksum */
20939 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20940 		cksum = ~(cksum + (cksum >> 16));
20941 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20942 	}
20943 	if (ipsec_len != 0) {
20944 		/*
20945 		 * We will do the rest of the processing after
20946 		 * we come back from IPSEC in ip_wput_ipsec_out().
20947 		 */
20948 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20949 
20950 		io = (ipsec_out_t *)first_mp->b_rptr;
20951 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20952 				ill_phyint->phyint_ifindex;
20953 
20954 		ipsec_out_process(q, first_mp, ire, ill_index);
20955 		ire_refrele(ire);
20956 		if (conn_outgoing_ill != NULL)
20957 			ill_refrele(conn_outgoing_ill);
20958 		return;
20959 	}
20960 
20961 	/*
20962 	 * In most cases, the emission loop below is entered only
20963 	 * once. Only in the case where the ire holds the
20964 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20965 	 * flagged ires in the bucket, and send the packet
20966 	 * through all crossed RTF_MULTIRT routes.
20967 	 */
20968 	if (ire->ire_flags & RTF_MULTIRT) {
20969 		multirt_send = B_TRUE;
20970 	}
20971 	do {
20972 		if (multirt_send) {
20973 			irb_t *irb;
20974 			/*
20975 			 * We are in a multiple send case, need to get
20976 			 * the next ire and make a duplicate of the packet.
20977 			 * ire1 holds here the next ire to process in the
20978 			 * bucket. If multirouting is expected,
20979 			 * any non-RTF_MULTIRT ire that has the
20980 			 * right destination address is ignored.
20981 			 */
20982 			irb = ire->ire_bucket;
20983 			ASSERT(irb != NULL);
20984 
20985 			IRB_REFHOLD(irb);
20986 			for (ire1 = ire->ire_next;
20987 			    ire1 != NULL;
20988 			    ire1 = ire1->ire_next) {
20989 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20990 					continue;
20991 				if (ire1->ire_addr != ire->ire_addr)
20992 					continue;
20993 				if (ire1->ire_marks &
20994 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20995 					continue;
20996 
20997 				/* Got one */
20998 				IRE_REFHOLD(ire1);
20999 				break;
21000 			}
21001 			IRB_REFRELE(irb);
21002 
21003 			if (ire1 != NULL) {
21004 				next_mp = copyb(mp);
21005 				if ((next_mp == NULL) ||
21006 				    ((mp->b_cont != NULL) &&
21007 				    ((next_mp->b_cont =
21008 				    dupmsg(mp->b_cont)) == NULL))) {
21009 					freemsg(next_mp);
21010 					next_mp = NULL;
21011 					ire_refrele(ire1);
21012 					ire1 = NULL;
21013 				}
21014 			}
21015 
21016 			/* Last multiroute ire; don't loop anymore. */
21017 			if (ire1 == NULL) {
21018 				multirt_send = B_FALSE;
21019 			}
21020 		}
21021 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
21022 		if (mp == NULL) {
21023 			BUMP_MIB(&ip_mib, ipOutDiscards);
21024 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
21025 			    "during IPPF processing\n"));
21026 			ire_refrele(ire);
21027 			if (next_mp != NULL) {
21028 				freemsg(next_mp);
21029 				ire_refrele(ire1);
21030 			}
21031 			if (conn_outgoing_ill != NULL)
21032 				ill_refrele(conn_outgoing_ill);
21033 			return;
21034 		}
21035 		UPDATE_OB_PKT_COUNT(ire);
21036 		ire->ire_last_used_time = lbolt;
21037 
21038 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21039 		    "ip_wput_ire_end: q %p (%S)",
21040 		    q, "last copy out");
21041 		putnext(stq, mp);
21042 		IRE_REFRELE(ire);
21043 
21044 		if (multirt_send) {
21045 			ASSERT(ire1);
21046 			/*
21047 			 * Proceed with the next RTF_MULTIRT ire,
21048 			 * Also set up the send-to queue accordingly.
21049 			 */
21050 			ire = ire1;
21051 			ire1 = NULL;
21052 			stq = ire->ire_stq;
21053 			mp = next_mp;
21054 			next_mp = NULL;
21055 			ipha = (ipha_t *)mp->b_rptr;
21056 			ill_index = Q_TO_INDEX(stq);
21057 		}
21058 	} while (multirt_send);
21059 	if (conn_outgoing_ill != NULL)
21060 		ill_refrele(conn_outgoing_ill);
21061 	return;
21062 
21063 	/*
21064 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21065 	 */
21066 broadcast:
21067 	{
21068 		/*
21069 		 * Avoid broadcast storms by setting the ttl to 1
21070 		 * for broadcasts. This parameter can be set
21071 		 * via ndd, so make sure that for the SO_DONTROUTE
21072 		 * case that ipha_ttl is always set to 1.
21073 		 * In the event that we are replying to incoming
21074 		 * ICMP packets, conn could be NULL.
21075 		 */
21076 		if ((connp != NULL) && connp->conn_dontroute)
21077 			ipha->ipha_ttl = 1;
21078 		else
21079 			ipha->ipha_ttl = ip_broadcast_ttl;
21080 
21081 		/*
21082 		 * Note that we are not doing a IRB_REFHOLD here.
21083 		 * Actually we don't care if the list changes i.e
21084 		 * if somebody deletes an IRE from the list while
21085 		 * we drop the lock, the next time we come around
21086 		 * ire_next will be NULL and hence we won't send
21087 		 * out multiple copies which is fine.
21088 		 */
21089 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21090 		ire1 = ire->ire_next;
21091 		if (conn_outgoing_ill != NULL) {
21092 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21093 				ASSERT(ire1 == ire->ire_next);
21094 				if (ire1 != NULL && ire1->ire_addr == dst) {
21095 					ire_refrele(ire);
21096 					ire = ire1;
21097 					IRE_REFHOLD(ire);
21098 					ire1 = ire->ire_next;
21099 					continue;
21100 				}
21101 				rw_exit(&ire->ire_bucket->irb_lock);
21102 				/* Did not find a matching ill */
21103 				ip1dbg(("ip_wput_ire: broadcast with no "
21104 				    "matching IP_BOUND_IF ill %s\n",
21105 				    conn_outgoing_ill->ill_name));
21106 				freemsg(first_mp);
21107 				if (ire != NULL)
21108 					ire_refrele(ire);
21109 				ill_refrele(conn_outgoing_ill);
21110 				return;
21111 			}
21112 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21113 			/*
21114 			 * If the next IRE has the same address and is not one
21115 			 * of the two copies that we need to send, try to see
21116 			 * whether this copy should be sent at all. This
21117 			 * assumes that we insert loopbacks first and then
21118 			 * non-loopbacks. This is acheived by inserting the
21119 			 * loopback always before non-loopback.
21120 			 * This is used to send a single copy of a broadcast
21121 			 * packet out all physical interfaces that have an
21122 			 * matching IRE_BROADCAST while also looping
21123 			 * back one copy (to ip_wput_local) for each
21124 			 * matching physical interface. However, we avoid
21125 			 * sending packets out different logical that match by
21126 			 * having ipif_up/ipif_down supress duplicate
21127 			 * IRE_BROADCASTS.
21128 			 *
21129 			 * This feature is currently used to get broadcasts
21130 			 * sent to multiple interfaces, when the broadcast
21131 			 * address being used applies to multiple interfaces.
21132 			 * For example, a whole net broadcast will be
21133 			 * replicated on every connected subnet of
21134 			 * the target net.
21135 			 *
21136 			 * Each zone has its own set of IRE_BROADCASTs, so that
21137 			 * we're able to distribute inbound packets to multiple
21138 			 * zones who share a broadcast address. We avoid looping
21139 			 * back outbound packets in different zones but on the
21140 			 * same ill, as the application would see duplicates.
21141 			 *
21142 			 * If the interfaces are part of the same group,
21143 			 * we would want to send only one copy out for
21144 			 * whole group.
21145 			 *
21146 			 * This logic assumes that ire_add_v4() groups the
21147 			 * IRE_BROADCAST entries so that those with the same
21148 			 * ire_addr and ill_group are kept together.
21149 			 */
21150 			ire_ill = ire->ire_ipif->ipif_ill;
21151 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21152 				if (ire_ill->ill_group != NULL &&
21153 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21154 					/*
21155 					 * If the current zone only has an ire
21156 					 * broadcast for this address marked
21157 					 * NORECV, the ire we want is ahead in
21158 					 * the bucket, so we look it up
21159 					 * deliberately ignoring the zoneid.
21160 					 */
21161 					for (ire1 = ire->ire_bucket->irb_ire;
21162 					    ire1 != NULL;
21163 					    ire1 = ire1->ire_next) {
21164 						ire1_ill =
21165 						    ire1->ire_ipif->ipif_ill;
21166 						if (ire1->ire_addr != dst)
21167 							continue;
21168 						/* skip over the current ire */
21169 						if (ire1 == ire)
21170 							continue;
21171 						/* skip over deleted ires */
21172 						if (ire1->ire_marks &
21173 						    IRE_MARK_CONDEMNED)
21174 							continue;
21175 						/*
21176 						 * non-loopback ire in our
21177 						 * group: use it for the next
21178 						 * pass in the loop
21179 						 */
21180 						if (ire1->ire_stq != NULL &&
21181 						    ire1_ill->ill_group ==
21182 						    ire_ill->ill_group)
21183 							break;
21184 					}
21185 				}
21186 			} else {
21187 				while (ire1 != NULL && ire1->ire_addr == dst) {
21188 					ire1_ill = ire1->ire_ipif->ipif_ill;
21189 					/*
21190 					 * We can have two broadcast ires on the
21191 					 * same ill in different zones; here
21192 					 * we'll send a copy of the packet on
21193 					 * each ill and the fanout code will
21194 					 * call conn_wantpacket() to check that
21195 					 * the zone has the broadcast address
21196 					 * configured on the ill. If the two
21197 					 * ires are in the same group we only
21198 					 * send one copy up.
21199 					 */
21200 					if (ire1_ill != ire_ill &&
21201 					    (ire1_ill->ill_group == NULL ||
21202 					    ire_ill->ill_group == NULL ||
21203 					    ire1_ill->ill_group !=
21204 					    ire_ill->ill_group)) {
21205 						break;
21206 					}
21207 					ire1 = ire1->ire_next;
21208 				}
21209 			}
21210 		}
21211 		ASSERT(multirt_send == B_FALSE);
21212 		if (ire1 != NULL && ire1->ire_addr == dst) {
21213 			if ((ire->ire_flags & RTF_MULTIRT) &&
21214 			    (ire1->ire_flags & RTF_MULTIRT)) {
21215 				/*
21216 				 * We are in the multirouting case.
21217 				 * The message must be sent at least
21218 				 * on both ires. These ires have been
21219 				 * inserted AFTER the standard ones
21220 				 * in ip_rt_add(). There are thus no
21221 				 * other ire entries for the destination
21222 				 * address in the rest of the bucket
21223 				 * that do not have the RTF_MULTIRT
21224 				 * flag. We don't process a copy
21225 				 * of the message here. This will be
21226 				 * done in the final sending loop.
21227 				 */
21228 				multirt_send = B_TRUE;
21229 			} else {
21230 				next_mp = ip_copymsg(first_mp);
21231 				if (next_mp != NULL)
21232 					IRE_REFHOLD(ire1);
21233 			}
21234 		}
21235 		rw_exit(&ire->ire_bucket->irb_lock);
21236 	}
21237 
21238 	if (stq) {
21239 		/*
21240 		 * A non-NULL send-to queue means this packet is going
21241 		 * out of this machine.
21242 		 */
21243 
21244 		BUMP_MIB(&ip_mib, ipOutRequests);
21245 		ttl_protocol = ((uint16_t *)ipha)[4];
21246 		/*
21247 		 * We accumulate the pseudo header checksum in cksum.
21248 		 * This is pretty hairy code, so watch close.  One
21249 		 * thing to keep in mind is that UDP and TCP have
21250 		 * stored their respective datagram lengths in their
21251 		 * checksum fields.  This lines things up real nice.
21252 		 */
21253 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21254 		    (src >> 16) + (src & 0xFFFF);
21255 		/*
21256 		 * We assume the udp checksum field contains the
21257 		 * length, so to compute the pseudo header checksum,
21258 		 * all we need is the protocol number and src/dst.
21259 		 */
21260 		/* Provide the checksums for UDP and TCP. */
21261 		if ((PROTO == IPPROTO_TCP) &&
21262 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21263 			/* hlen gets the number of uchar_ts in the IP header */
21264 			hlen = (V_HLEN & 0xF) << 2;
21265 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21266 			IP_STAT(ip_out_sw_cksum);
21267 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21268 			    LENGTH - hlen);
21269 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21270 			if (*up == 0)
21271 				*up = 0xFFFF;
21272 		} else if (PROTO == IPPROTO_SCTP &&
21273 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21274 			sctp_hdr_t	*sctph;
21275 
21276 			hlen = (V_HLEN & 0xF) << 2;
21277 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21278 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21279 			sctph->sh_chksum = 0;
21280 #ifdef	DEBUG
21281 			if (!skip_sctp_cksum)
21282 #endif
21283 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21284 		} else {
21285 			queue_t *dev_q = stq->q_next;
21286 
21287 			if ((dev_q->q_next || dev_q->q_first) &&
21288 			    !canput(dev_q)) {
21289 			    blocked:
21290 				ipha->ipha_ident = ip_hdr_included;
21291 				/*
21292 				 * If we don't have a conn to apply
21293 				 * backpressure, free the message.
21294 				 * In the ire_send path, we don't know
21295 				 * the position to requeue the packet. Rather
21296 				 * than reorder packets, we just drop this
21297 				 * packet.
21298 				 */
21299 				if (ip_output_queue && connp != NULL &&
21300 				    caller != IRE_SEND) {
21301 					if (caller == IP_WSRV) {
21302 						connp->conn_did_putbq = 1;
21303 						(void) putbq(connp->conn_wq,
21304 						    first_mp);
21305 						conn_drain_insert(connp);
21306 						/*
21307 						 * This is the service thread,
21308 						 * and the queue is already
21309 						 * noenabled. The check for
21310 						 * canput and the putbq is not
21311 						 * atomic. So we need to check
21312 						 * again.
21313 						 */
21314 						if (canput(stq->q_next))
21315 							connp->conn_did_putbq
21316 							    = 0;
21317 						IP_STAT(ip_conn_flputbq);
21318 					} else {
21319 						/*
21320 						 * We are not the service proc.
21321 						 * ip_wsrv will be scheduled or
21322 						 * is already running.
21323 						 */
21324 						(void) putq(connp->conn_wq,
21325 						    first_mp);
21326 					}
21327 				} else {
21328 					BUMP_MIB(&ip_mib, ipOutDiscards);
21329 					freemsg(first_mp);
21330 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21331 					    "ip_wput_ire_end: q %p (%S)",
21332 					    q, "discard");
21333 				}
21334 				ire_refrele(ire);
21335 				if (next_mp) {
21336 					ire_refrele(ire1);
21337 					freemsg(next_mp);
21338 				}
21339 				if (conn_outgoing_ill != NULL)
21340 					ill_refrele(conn_outgoing_ill);
21341 				return;
21342 			}
21343 			if ((PROTO == IPPROTO_UDP) &&
21344 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21345 				/*
21346 				 * hlen gets the number of uchar_ts in the
21347 				 * IP header
21348 				 */
21349 				hlen = (V_HLEN & 0xF) << 2;
21350 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21351 				max_frag = ire->ire_max_frag;
21352 				if (*up != 0) {
21353 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21354 					    up, PROTO, hlen, LENGTH, max_frag,
21355 					    ipsec_len, cksum);
21356 					/* Software checksum? */
21357 					if (DB_CKSUMFLAGS(mp) == 0) {
21358 						IP_STAT(ip_out_sw_cksum);
21359 						IP_STAT_UPDATE(
21360 						    ip_udp_out_sw_cksum_bytes,
21361 						    LENGTH - hlen);
21362 					}
21363 				}
21364 			}
21365 		}
21366 		/*
21367 		 * Need to do this even when fragmenting. The local
21368 		 * loopback can be done without computing checksums
21369 		 * but forwarding out other interface must be done
21370 		 * after the IP checksum (and ULP checksums) have been
21371 		 * computed.
21372 		 *
21373 		 * NOTE : multicast_forward is set only if this packet
21374 		 * originated from ip_wput. For packets originating from
21375 		 * ip_wput_multicast, it is not set.
21376 		 */
21377 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21378 		    multi_loopback:
21379 			ip2dbg(("ip_wput: multicast, loop %d\n",
21380 			    conn_multicast_loop));
21381 
21382 			/*  Forget header checksum offload */
21383 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21384 
21385 			/*
21386 			 * Local loopback of multicasts?  Check the
21387 			 * ill.
21388 			 *
21389 			 * Note that the loopback function will not come
21390 			 * in through ip_rput - it will only do the
21391 			 * client fanout thus we need to do an mforward
21392 			 * as well.  The is different from the BSD
21393 			 * logic.
21394 			 */
21395 			if (ill != NULL) {
21396 				ilm_t	*ilm;
21397 
21398 				ILM_WALKER_HOLD(ill);
21399 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21400 				    ALL_ZONES);
21401 				ILM_WALKER_RELE(ill);
21402 				if (ilm != NULL) {
21403 					/*
21404 					 * Pass along the virtual output q.
21405 					 * ip_wput_local() will distribute the
21406 					 * packet to all the matching zones,
21407 					 * except the sending zone when
21408 					 * IP_MULTICAST_LOOP is false.
21409 					 */
21410 					ip_multicast_loopback(q, ill, first_mp,
21411 					    conn_multicast_loop ? 0 :
21412 					    IP_FF_NO_MCAST_LOOP, zoneid);
21413 				}
21414 			}
21415 			if (ipha->ipha_ttl == 0) {
21416 				/*
21417 				 * 0 => only to this host i.e. we are
21418 				 * done. We are also done if this was the
21419 				 * loopback interface since it is sufficient
21420 				 * to loopback one copy of a multicast packet.
21421 				 */
21422 				freemsg(first_mp);
21423 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21424 				    "ip_wput_ire_end: q %p (%S)",
21425 				    q, "loopback");
21426 				ire_refrele(ire);
21427 				if (conn_outgoing_ill != NULL)
21428 					ill_refrele(conn_outgoing_ill);
21429 				return;
21430 			}
21431 			/*
21432 			 * ILLF_MULTICAST is checked in ip_newroute
21433 			 * i.e. we don't need to check it here since
21434 			 * all IRE_CACHEs come from ip_newroute.
21435 			 * For multicast traffic, SO_DONTROUTE is interpreted
21436 			 * to mean only send the packet out the interface
21437 			 * (optionally specified with IP_MULTICAST_IF)
21438 			 * and do not forward it out additional interfaces.
21439 			 * RSVP and the rsvp daemon is an example of a
21440 			 * protocol and user level process that
21441 			 * handles it's own routing. Hence, it uses the
21442 			 * SO_DONTROUTE option to accomplish this.
21443 			 */
21444 
21445 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
21446 				/* Unconditionally redo the checksum */
21447 				ipha->ipha_hdr_checksum = 0;
21448 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21449 
21450 				/*
21451 				 * If this needs to go out secure, we need
21452 				 * to wait till we finish the IPSEC
21453 				 * processing.
21454 				 */
21455 				if (ipsec_len == 0 &&
21456 				    ip_mforward(ill, ipha, mp)) {
21457 					freemsg(first_mp);
21458 					ip1dbg(("ip_wput: mforward failed\n"));
21459 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21460 					    "ip_wput_ire_end: q %p (%S)",
21461 					    q, "mforward failed");
21462 					ire_refrele(ire);
21463 					if (conn_outgoing_ill != NULL)
21464 						ill_refrele(conn_outgoing_ill);
21465 					return;
21466 				}
21467 			}
21468 		}
21469 		max_frag = ire->ire_max_frag;
21470 		cksum += ttl_protocol;
21471 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
21472 			/* No fragmentation required for this one. */
21473 			/*
21474 			 * Don't use frag_flag if packet is pre-built or source
21475 			 * routed or if multicast (since multicast packets do
21476 			 * not solicit ICMP "packet too big" messages).
21477 			 */
21478 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21479 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21480 			    !ip_source_route_included(ipha)) &&
21481 			    !CLASSD(ipha->ipha_dst))
21482 				ipha->ipha_fragment_offset_and_flags |=
21483 				    htons(ire->ire_frag_flag);
21484 
21485 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21486 				/* Complete the IP header checksum. */
21487 				cksum += ipha->ipha_ident;
21488 				cksum += (v_hlen_tos_len >> 16)+
21489 				    (v_hlen_tos_len & 0xFFFF);
21490 				cksum += ipha->ipha_fragment_offset_and_flags;
21491 				hlen = (V_HLEN & 0xF) -
21492 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21493 				if (hlen) {
21494 				    checksumoptions:
21495 					/*
21496 					 * Account for the IP Options in the IP
21497 					 * header checksum.
21498 					 */
21499 					up = (uint16_t *)(rptr+
21500 					    IP_SIMPLE_HDR_LENGTH);
21501 					do {
21502 						cksum += up[0];
21503 						cksum += up[1];
21504 						up += 2;
21505 					} while (--hlen);
21506 				}
21507 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21508 				cksum = ~(cksum + (cksum >> 16));
21509 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
21510 			}
21511 			if (ipsec_len != 0) {
21512 				ipsec_out_process(q, first_mp, ire, ill_index);
21513 				if (!next_mp) {
21514 					ire_refrele(ire);
21515 					if (conn_outgoing_ill != NULL)
21516 						ill_refrele(conn_outgoing_ill);
21517 					return;
21518 				}
21519 				goto next;
21520 			}
21521 
21522 			/*
21523 			 * multirt_send has already been handled
21524 			 * for broadcast, but not yet for multicast
21525 			 * or IP options.
21526 			 */
21527 			if (next_mp == NULL) {
21528 				if (ire->ire_flags & RTF_MULTIRT) {
21529 					multirt_send = B_TRUE;
21530 				}
21531 			}
21532 
21533 			/*
21534 			 * In most cases, the emission loop below is
21535 			 * entered only once. Only in the case where
21536 			 * the ire holds the RTF_MULTIRT flag, do we loop
21537 			 * to process all RTF_MULTIRT ires in the bucket,
21538 			 * and send the packet through all crossed
21539 			 * RTF_MULTIRT routes.
21540 			 */
21541 			do {
21542 				if (multirt_send) {
21543 					irb_t *irb;
21544 
21545 					irb = ire->ire_bucket;
21546 					ASSERT(irb != NULL);
21547 					/*
21548 					 * We are in a multiple send case,
21549 					 * need to get the next IRE and make
21550 					 * a duplicate of the packet.
21551 					 */
21552 					IRB_REFHOLD(irb);
21553 					for (ire1 = ire->ire_next;
21554 					    ire1 != NULL;
21555 					    ire1 = ire1->ire_next) {
21556 						if (!(ire1->ire_flags &
21557 						    RTF_MULTIRT))
21558 							continue;
21559 						if (ire1->ire_addr !=
21560 						    ire->ire_addr)
21561 							continue;
21562 						if (ire1->ire_marks &
21563 						    (IRE_MARK_CONDEMNED|
21564 							IRE_MARK_HIDDEN))
21565 							continue;
21566 
21567 						/* Got one */
21568 						IRE_REFHOLD(ire1);
21569 						break;
21570 					}
21571 					IRB_REFRELE(irb);
21572 
21573 					if (ire1 != NULL) {
21574 						next_mp = copyb(mp);
21575 						if ((next_mp == NULL) ||
21576 						    ((mp->b_cont != NULL) &&
21577 						    ((next_mp->b_cont =
21578 						    dupmsg(mp->b_cont))
21579 						    == NULL))) {
21580 							freemsg(next_mp);
21581 							next_mp = NULL;
21582 							ire_refrele(ire1);
21583 							ire1 = NULL;
21584 						}
21585 					}
21586 
21587 					/*
21588 					 * Last multiroute ire; don't loop
21589 					 * anymore. The emission is over
21590 					 * and next_mp is NULL.
21591 					 */
21592 					if (ire1 == NULL) {
21593 						multirt_send = B_FALSE;
21594 					}
21595 				}
21596 
21597 				ASSERT(ipsec_len == 0);
21598 				mp1 = ip_wput_attach_llhdr(mp, ire,
21599 				    IPP_LOCAL_OUT, ill_index);
21600 				if (mp1 == NULL) {
21601 					BUMP_MIB(&ip_mib, ipOutDiscards);
21602 					if (next_mp) {
21603 						freemsg(next_mp);
21604 						ire_refrele(ire1);
21605 					}
21606 					ire_refrele(ire);
21607 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21608 					    "ip_wput_ire_end: q %p (%S)",
21609 					    q, "discard MDATA");
21610 					if (conn_outgoing_ill != NULL)
21611 						ill_refrele(conn_outgoing_ill);
21612 					return;
21613 				}
21614 				UPDATE_OB_PKT_COUNT(ire);
21615 				ire->ire_last_used_time = lbolt;
21616 
21617 				if (multirt_send) {
21618 					/*
21619 					 * We are in a multiple send case,
21620 					 * need to re-enter the sending loop
21621 					 * using the next ire.
21622 					 */
21623 					putnext(stq, mp1);
21624 					ire_refrele(ire);
21625 					ire = ire1;
21626 					stq = ire->ire_stq;
21627 					mp = next_mp;
21628 					next_mp = NULL;
21629 					ipha = (ipha_t *)mp->b_rptr;
21630 					ill_index = Q_TO_INDEX(stq);
21631 				}
21632 			} while (multirt_send);
21633 
21634 			if (!next_mp) {
21635 				/*
21636 				 * Last copy going out (the ultra-common
21637 				 * case).  Note that we intentionally replicate
21638 				 * the putnext rather than calling it before
21639 				 * the next_mp check in hopes of a little
21640 				 * tail-call action out of the compiler.
21641 				 */
21642 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21643 				    "ip_wput_ire_end: q %p (%S)",
21644 				    q, "last copy out(1)");
21645 				putnext(stq, mp1);
21646 				ire_refrele(ire);
21647 				if (conn_outgoing_ill != NULL)
21648 					ill_refrele(conn_outgoing_ill);
21649 				return;
21650 			}
21651 			/* More copies going out below. */
21652 			putnext(stq, mp1);
21653 		} else {
21654 			int offset;
21655 		    fragmentit:
21656 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21657 			/*
21658 			 * If this would generate a icmp_frag_needed message,
21659 			 * we need to handle it before we do the IPSEC
21660 			 * processing. Otherwise, we need to strip the IPSEC
21661 			 * headers before we send up the message to the ULPs
21662 			 * which becomes messy and difficult.
21663 			 */
21664 			if (ipsec_len != 0) {
21665 				if ((max_frag < (unsigned int)(LENGTH +
21666 				    ipsec_len)) && (offset & IPH_DF)) {
21667 
21668 					BUMP_MIB(&ip_mib, ipFragFails);
21669 					ipha->ipha_hdr_checksum = 0;
21670 					ipha->ipha_hdr_checksum =
21671 					    (uint16_t)ip_csum_hdr(ipha);
21672 					icmp_frag_needed(ire->ire_stq, first_mp,
21673 					    max_frag);
21674 					if (!next_mp) {
21675 						ire_refrele(ire);
21676 						if (conn_outgoing_ill != NULL) {
21677 							ill_refrele(
21678 							    conn_outgoing_ill);
21679 						}
21680 						return;
21681 					}
21682 				} else {
21683 					/*
21684 					 * This won't cause a icmp_frag_needed
21685 					 * message. to be gnerated. Send it on
21686 					 * the wire. Note that this could still
21687 					 * cause fragmentation and all we
21688 					 * do is the generation of the message
21689 					 * to the ULP if needed before IPSEC.
21690 					 */
21691 					if (!next_mp) {
21692 						ipsec_out_process(q, first_mp,
21693 						    ire, ill_index);
21694 						TRACE_2(TR_FAC_IP,
21695 						    TR_IP_WPUT_IRE_END,
21696 						    "ip_wput_ire_end: q %p "
21697 						    "(%S)", q,
21698 						    "last ipsec_out_process");
21699 						ire_refrele(ire);
21700 						if (conn_outgoing_ill != NULL) {
21701 							ill_refrele(
21702 							    conn_outgoing_ill);
21703 						}
21704 						return;
21705 					}
21706 					ipsec_out_process(q, first_mp,
21707 					    ire, ill_index);
21708 				}
21709 			} else {
21710 				/* Initiate IPPF processing */
21711 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21712 					ip_process(IPP_LOCAL_OUT, &mp,
21713 					    ill_index);
21714 					if (mp == NULL) {
21715 						BUMP_MIB(&ip_mib,
21716 						    ipOutDiscards);
21717 						if (next_mp != NULL) {
21718 							freemsg(next_mp);
21719 							ire_refrele(ire1);
21720 						}
21721 						ire_refrele(ire);
21722 						TRACE_2(TR_FAC_IP,
21723 						    TR_IP_WPUT_IRE_END,
21724 						    "ip_wput_ire: q %p (%S)",
21725 						    q, "discard MDATA");
21726 						if (conn_outgoing_ill != NULL) {
21727 							ill_refrele(
21728 							    conn_outgoing_ill);
21729 						}
21730 						return;
21731 					}
21732 				}
21733 				if (!next_mp) {
21734 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21735 					    "ip_wput_ire_end: q %p (%S)",
21736 					    q, "last fragmentation");
21737 					ip_wput_ire_fragmentit(mp, ire);
21738 					ire_refrele(ire);
21739 					if (conn_outgoing_ill != NULL)
21740 						ill_refrele(conn_outgoing_ill);
21741 					return;
21742 				}
21743 				ip_wput_ire_fragmentit(mp, ire);
21744 			}
21745 		}
21746 	} else {
21747 	    nullstq:
21748 		/* A NULL stq means the destination address is local. */
21749 		UPDATE_OB_PKT_COUNT(ire);
21750 		ire->ire_last_used_time = lbolt;
21751 		ASSERT(ire->ire_ipif != NULL);
21752 		if (!next_mp) {
21753 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21754 			    "ip_wput_ire_end: q %p (%S)",
21755 			    q, "local address");
21756 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
21757 			    first_mp, ire, 0, ire->ire_zoneid);
21758 			ire_refrele(ire);
21759 			if (conn_outgoing_ill != NULL)
21760 				ill_refrele(conn_outgoing_ill);
21761 			return;
21762 		}
21763 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
21764 		    ire, 0, ire->ire_zoneid);
21765 	}
21766 next:
21767 	/*
21768 	 * More copies going out to additional interfaces.
21769 	 * ire1 has already been held. We don't need the
21770 	 * "ire" anymore.
21771 	 */
21772 	ire_refrele(ire);
21773 	ire = ire1;
21774 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
21775 	mp = next_mp;
21776 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
21777 	ill = ire_to_ill(ire);
21778 	first_mp = mp;
21779 	if (ipsec_len != 0) {
21780 		ASSERT(first_mp->b_datap->db_type == M_CTL);
21781 		mp = mp->b_cont;
21782 	}
21783 	dst = ire->ire_addr;
21784 	ipha = (ipha_t *)mp->b_rptr;
21785 	/*
21786 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
21787 	 * Restore ipha_ident "no checksum" flag.
21788 	 */
21789 	src = orig_src;
21790 	ipha->ipha_ident = ip_hdr_included;
21791 	goto another;
21792 
21793 #undef	rptr
21794 #undef	Q_TO_INDEX
21795 }
21796 
21797 /*
21798  * Routine to allocate a message that is used to notify the ULP about MDT.
21799  * The caller may provide a pointer to the link-layer MDT capabilities,
21800  * or NULL if MDT is to be disabled on the stream.
21801  */
21802 mblk_t *
21803 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
21804 {
21805 	mblk_t *mp;
21806 	ip_mdt_info_t *mdti;
21807 	ill_mdt_capab_t *idst;
21808 
21809 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
21810 		DB_TYPE(mp) = M_CTL;
21811 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
21812 		mdti = (ip_mdt_info_t *)mp->b_rptr;
21813 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
21814 		idst = &(mdti->mdt_capab);
21815 
21816 		/*
21817 		 * If the caller provides us with the capability, copy
21818 		 * it over into our notification message; otherwise
21819 		 * we zero out the capability portion.
21820 		 */
21821 		if (isrc != NULL)
21822 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
21823 		else
21824 			bzero((caddr_t)idst, sizeof (*idst));
21825 	}
21826 	return (mp);
21827 }
21828 
21829 /*
21830  * Routine which determines whether MDT can be enabled on the destination
21831  * IRE and IPC combination, and if so, allocates and returns the MDT
21832  * notification mblk that may be used by ULP.  We also check if we need to
21833  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21834  * MDT usage in the past have been lifted.  This gets called during IP
21835  * and ULP binding.
21836  */
21837 mblk_t *
21838 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21839     ill_mdt_capab_t *mdt_cap)
21840 {
21841 	mblk_t *mp;
21842 	boolean_t rc = B_FALSE;
21843 
21844 	ASSERT(dst_ire != NULL);
21845 	ASSERT(connp != NULL);
21846 	ASSERT(mdt_cap != NULL);
21847 
21848 	/*
21849 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21850 	 * Multidata, which is handled in tcp_multisend().  This
21851 	 * is the reason why we do all these checks here, to ensure
21852 	 * that we don't enable Multidata for the cases which we
21853 	 * can't handle at the moment.
21854 	 */
21855 	do {
21856 		/* Only do TCP at the moment */
21857 		if (connp->conn_ulp != IPPROTO_TCP)
21858 			break;
21859 
21860 		/*
21861 		 * IPSEC outbound policy present?  Note that we get here
21862 		 * after calling ipsec_conn_cache_policy() where the global
21863 		 * policy checking is performed.  conn_latch will be
21864 		 * non-NULL as long as there's a policy defined,
21865 		 * i.e. conn_out_enforce_policy may be NULL in such case
21866 		 * when the connection is non-secure, and hence we check
21867 		 * further if the latch refers to an outbound policy.
21868 		 */
21869 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21870 			break;
21871 
21872 		/* CGTP (multiroute) is enabled? */
21873 		if (dst_ire->ire_flags & RTF_MULTIRT)
21874 			break;
21875 
21876 		/* Outbound IPQoS enabled? */
21877 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21878 			/*
21879 			 * In this case, we disable MDT for this and all
21880 			 * future connections going over the interface.
21881 			 */
21882 			mdt_cap->ill_mdt_on = 0;
21883 			break;
21884 		}
21885 
21886 		/* socket option(s) present? */
21887 		if (!CONN_IS_MD_FASTPATH(connp))
21888 			break;
21889 
21890 		rc = B_TRUE;
21891 	/* CONSTCOND */
21892 	} while (0);
21893 
21894 	/* Remember the result */
21895 	connp->conn_mdt_ok = rc;
21896 
21897 	if (!rc)
21898 		return (NULL);
21899 	else if (!mdt_cap->ill_mdt_on) {
21900 		/*
21901 		 * If MDT has been previously turned off in the past, and we
21902 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21903 		 * then enable it for this interface.
21904 		 */
21905 		mdt_cap->ill_mdt_on = 1;
21906 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21907 		    "interface %s\n", ill_name));
21908 	}
21909 
21910 	/* Allocate the MDT info mblk */
21911 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21912 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21913 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21914 		return (NULL);
21915 	}
21916 	return (mp);
21917 }
21918 
21919 /*
21920  * Create destination address attribute, and fill it with the physical
21921  * destination address and SAP taken from the template DL_UNITDATA_REQ
21922  * message block.
21923  */
21924 boolean_t
21925 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21926 {
21927 	dl_unitdata_req_t *dlurp;
21928 	pattr_t *pa;
21929 	pattrinfo_t pa_info;
21930 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21931 	uint_t das_len, das_off;
21932 
21933 	ASSERT(dlmp != NULL);
21934 
21935 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21936 	das_len = dlurp->dl_dest_addr_length;
21937 	das_off = dlurp->dl_dest_addr_offset;
21938 
21939 	pa_info.type = PATTR_DSTADDRSAP;
21940 	pa_info.len = sizeof (**das) + das_len - 1;
21941 
21942 	/* create and associate the attribute */
21943 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21944 	if (pa != NULL) {
21945 		ASSERT(*das != NULL);
21946 		(*das)->addr_is_group = 0;
21947 		(*das)->addr_len = (uint8_t)das_len;
21948 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21949 	}
21950 
21951 	return (pa != NULL);
21952 }
21953 
21954 /*
21955  * Create hardware checksum attribute and fill it with the values passed.
21956  */
21957 boolean_t
21958 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21959     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21960 {
21961 	pattr_t *pa;
21962 	pattrinfo_t pa_info;
21963 
21964 	ASSERT(mmd != NULL);
21965 
21966 	pa_info.type = PATTR_HCKSUM;
21967 	pa_info.len = sizeof (pattr_hcksum_t);
21968 
21969 	/* create and associate the attribute */
21970 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21971 	if (pa != NULL) {
21972 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21973 
21974 		hck->hcksum_start_offset = start_offset;
21975 		hck->hcksum_stuff_offset = stuff_offset;
21976 		hck->hcksum_end_offset = end_offset;
21977 		hck->hcksum_flags = flags;
21978 	}
21979 	return (pa != NULL);
21980 }
21981 
21982 /*
21983  * Create zerocopy attribute and fill it with the specified flags
21984  */
21985 boolean_t
21986 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21987 {
21988 	pattr_t *pa;
21989 	pattrinfo_t pa_info;
21990 
21991 	ASSERT(mmd != NULL);
21992 	pa_info.type = PATTR_ZCOPY;
21993 	pa_info.len = sizeof (pattr_zcopy_t);
21994 
21995 	/* create and associate the attribute */
21996 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21997 	if (pa != NULL) {
21998 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21999 
22000 		zcopy->zcopy_flags = flags;
22001 	}
22002 	return (pa != NULL);
22003 }
22004 
22005 /*
22006  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22007  * block chain. We could rewrite to handle arbitrary message block chains but
22008  * that would make the code complicated and slow. Right now there three
22009  * restrictions:
22010  *
22011  *   1. The first message block must contain the complete IP header and
22012  *	at least 1 byte of payload data.
22013  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22014  *	so that we can use a single Multidata message.
22015  *   3. No frag must be distributed over two or more message blocks so
22016  *	that we don't need more than two packet descriptors per frag.
22017  *
22018  * The above restrictions allow us to support userland applications (which
22019  * will send down a single message block) and NFS over UDP (which will
22020  * send down a chain of at most three message blocks).
22021  *
22022  * We also don't use MDT for payloads with less than or equal to
22023  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22024  */
22025 boolean_t
22026 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22027 {
22028 	int	blocks;
22029 	ssize_t	total, missing, size;
22030 
22031 	ASSERT(mp != NULL);
22032 	ASSERT(hdr_len > 0);
22033 
22034 	size = MBLKL(mp) - hdr_len;
22035 	if (size <= 0)
22036 		return (B_FALSE);
22037 
22038 	/* The first mblk contains the header and some payload. */
22039 	blocks = 1;
22040 	total = size;
22041 	size %= len;
22042 	missing = (size == 0) ? 0 : (len - size);
22043 	mp = mp->b_cont;
22044 
22045 	while (mp != NULL) {
22046 		/*
22047 		 * Give up if we encounter a zero length message block.
22048 		 * In practice, this should rarely happen and therefore
22049 		 * not worth the trouble of freeing and re-linking the
22050 		 * mblk from the chain to handle such case.
22051 		 */
22052 		if ((size = MBLKL(mp)) == 0)
22053 			return (B_FALSE);
22054 
22055 		/* Too many payload buffers for a single Multidata message? */
22056 		if (++blocks > MULTIDATA_MAX_PBUFS)
22057 			return (B_FALSE);
22058 
22059 		total += size;
22060 		/* Is a frag distributed over two or more message blocks? */
22061 		if (missing > size)
22062 			return (B_FALSE);
22063 		size -= missing;
22064 
22065 		size %= len;
22066 		missing = (size == 0) ? 0 : (len - size);
22067 
22068 		mp = mp->b_cont;
22069 	}
22070 
22071 	return (total > ip_wput_frag_mdt_min);
22072 }
22073 
22074 /*
22075  * Outbound IPv4 fragmentation routine using MDT.
22076  */
22077 static void
22078 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22079     uint32_t frag_flag, int offset)
22080 {
22081 	ipha_t		*ipha_orig;
22082 	int		i1, ip_data_end;
22083 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22084 	mblk_t		*hdr_mp, *md_mp = NULL;
22085 	unsigned char	*hdr_ptr, *pld_ptr;
22086 	multidata_t	*mmd;
22087 	ip_pdescinfo_t	pdi;
22088 
22089 	ASSERT(DB_TYPE(mp) == M_DATA);
22090 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22091 
22092 	ipha_orig = (ipha_t *)mp->b_rptr;
22093 	mp->b_rptr += sizeof (ipha_t);
22094 
22095 	/* Calculate how many packets we will send out */
22096 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22097 	pkts = (i1 + len - 1) / len;
22098 	ASSERT(pkts > 1);
22099 
22100 	/* Allocate a message block which will hold all the IP Headers. */
22101 	wroff = ip_wroff_extra;
22102 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22103 
22104 	i1 = pkts * hdr_chunk_len;
22105 	/*
22106 	 * Create the header buffer, Multidata and destination address
22107 	 * and SAP attribute that should be associated with it.
22108 	 */
22109 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22110 	    ((hdr_mp->b_wptr += i1),
22111 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22112 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
22113 		freemsg(mp);
22114 		if (md_mp == NULL) {
22115 			freemsg(hdr_mp);
22116 		} else {
22117 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22118 			freemsg(md_mp);
22119 		}
22120 		IP_STAT(ip_frag_mdt_allocfail);
22121 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22122 		return;
22123 	}
22124 	IP_STAT(ip_frag_mdt_allocd);
22125 
22126 	/*
22127 	 * Add a payload buffer to the Multidata; this operation must not
22128 	 * fail, or otherwise our logic in this routine is broken.  There
22129 	 * is no memory allocation done by the routine, so any returned
22130 	 * failure simply tells us that we've done something wrong.
22131 	 *
22132 	 * A failure tells us that either we're adding the same payload
22133 	 * buffer more than once, or we're trying to add more buffers than
22134 	 * allowed.  None of the above cases should happen, and we panic
22135 	 * because either there's horrible heap corruption, and/or
22136 	 * programming mistake.
22137 	 */
22138 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22139 		goto pbuf_panic;
22140 
22141 	hdr_ptr = hdr_mp->b_rptr;
22142 	pld_ptr = mp->b_rptr;
22143 
22144 	/* Establish the ending byte offset, based on the starting offset. */
22145 	offset <<= 3;
22146 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22147 	    IP_SIMPLE_HDR_LENGTH;
22148 
22149 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22150 
22151 	while (pld_ptr < mp->b_wptr) {
22152 		ipha_t		*ipha;
22153 		uint16_t	offset_and_flags;
22154 		uint16_t	ip_len;
22155 		int		error;
22156 
22157 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22158 		ipha = (ipha_t *)(hdr_ptr + wroff);
22159 		ASSERT(OK_32PTR(ipha));
22160 		*ipha = *ipha_orig;
22161 
22162 		if (ip_data_end - offset > len) {
22163 			offset_and_flags = IPH_MF;
22164 		} else {
22165 			/*
22166 			 * Last frag. Set len to the length of this last piece.
22167 			 */
22168 			len = ip_data_end - offset;
22169 			/* A frag of a frag might have IPH_MF non-zero */
22170 			offset_and_flags =
22171 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22172 			    IPH_MF;
22173 		}
22174 		offset_and_flags |= (uint16_t)(offset >> 3);
22175 		offset_and_flags |= (uint16_t)frag_flag;
22176 		/* Store the offset and flags in the IP header. */
22177 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22178 
22179 		/* Store the length in the IP header. */
22180 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22181 		ipha->ipha_length = htons(ip_len);
22182 
22183 		/*
22184 		 * Set the IP header checksum.  Note that mp is just
22185 		 * the header, so this is easy to pass to ip_csum.
22186 		 */
22187 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22188 
22189 		/*
22190 		 * Record offset and size of header and data of the next packet
22191 		 * in the multidata message.
22192 		 */
22193 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22194 		PDESC_PLD_INIT(&pdi);
22195 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22196 		ASSERT(i1 > 0);
22197 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22198 		if (i1 == len) {
22199 			pld_ptr += len;
22200 		} else {
22201 			i1 = len - i1;
22202 			mp = mp->b_cont;
22203 			ASSERT(mp != NULL);
22204 			ASSERT(MBLKL(mp) >= i1);
22205 			/*
22206 			 * Attach the next payload message block to the
22207 			 * multidata message.
22208 			 */
22209 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22210 				goto pbuf_panic;
22211 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22212 			pld_ptr = mp->b_rptr + i1;
22213 		}
22214 
22215 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22216 		    KM_NOSLEEP)) == NULL) {
22217 			/*
22218 			 * Any failure other than ENOMEM indicates that we
22219 			 * have passed in invalid pdesc info or parameters
22220 			 * to mmd_addpdesc, which must not happen.
22221 			 *
22222 			 * EINVAL is a result of failure on boundary checks
22223 			 * against the pdesc info contents.  It should not
22224 			 * happen, and we panic because either there's
22225 			 * horrible heap corruption, and/or programming
22226 			 * mistake.
22227 			 */
22228 			if (error != ENOMEM) {
22229 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22230 				    "pdesc logic error detected for "
22231 				    "mmd %p pinfo %p (%d)\n",
22232 				    (void *)mmd, (void *)&pdi, error);
22233 				/* NOTREACHED */
22234 			}
22235 			IP_STAT(ip_frag_mdt_addpdescfail);
22236 			/* Free unattached payload message blocks as well */
22237 			md_mp->b_cont = mp->b_cont;
22238 			goto free_mmd;
22239 		}
22240 
22241 		/* Advance fragment offset. */
22242 		offset += len;
22243 
22244 		/* Advance to location for next header in the buffer. */
22245 		hdr_ptr += hdr_chunk_len;
22246 
22247 		/* Did we reach the next payload message block? */
22248 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22249 			mp = mp->b_cont;
22250 			/*
22251 			 * Attach the next message block with payload
22252 			 * data to the multidata message.
22253 			 */
22254 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22255 				goto pbuf_panic;
22256 			pld_ptr = mp->b_rptr;
22257 		}
22258 	}
22259 
22260 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22261 	ASSERT(mp->b_wptr == pld_ptr);
22262 
22263 	/* Update IP statistics */
22264 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22265 	BUMP_MIB(&ip_mib, ipFragOKs);
22266 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22267 
22268 	if (pkt_type == OB_PKT) {
22269 		ire->ire_ob_pkt_count += pkts;
22270 		if (ire->ire_ipif != NULL)
22271 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22272 	} else {
22273 		/*
22274 		 * The type is IB_PKT in the forwarding path and in
22275 		 * the mobile IP case when the packet is being reverse-
22276 		 * tunneled to the home agent.
22277 		 */
22278 		ire->ire_ib_pkt_count += pkts;
22279 		ASSERT(!IRE_IS_LOCAL(ire));
22280 		if (ire->ire_type & IRE_BROADCAST)
22281 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22282 		else
22283 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22284 	}
22285 	ire->ire_last_used_time = lbolt;
22286 	/* Send it down */
22287 	putnext(ire->ire_stq, md_mp);
22288 	return;
22289 
22290 pbuf_panic:
22291 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22292 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22293 	    pbuf_idx);
22294 	/* NOTREACHED */
22295 }
22296 
22297 /*
22298  * Outbound IP fragmentation routine.
22299  *
22300  * NOTE : This routine does not ire_refrele the ire that is passed in
22301  * as the argument.
22302  */
22303 static void
22304 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22305     uint32_t frag_flag)
22306 {
22307 	int		i1;
22308 	mblk_t		*ll_hdr_mp;
22309 	int 		ll_hdr_len;
22310 	int		hdr_len;
22311 	mblk_t		*hdr_mp;
22312 	ipha_t		*ipha;
22313 	int		ip_data_end;
22314 	int		len;
22315 	mblk_t		*mp = mp_orig;
22316 	int		offset;
22317 	queue_t		*q;
22318 	uint32_t	v_hlen_tos_len;
22319 	mblk_t		*first_mp;
22320 	boolean_t	mctl_present;
22321 	ill_t		*ill;
22322 	mblk_t		*xmit_mp;
22323 	mblk_t		*carve_mp;
22324 	ire_t		*ire1 = NULL;
22325 	ire_t		*save_ire = NULL;
22326 	mblk_t  	*next_mp = NULL;
22327 	boolean_t	last_frag = B_FALSE;
22328 	boolean_t	multirt_send = B_FALSE;
22329 	ire_t		*first_ire = NULL;
22330 	irb_t		*irb = NULL;
22331 
22332 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22333 	    "ip_wput_frag_start:");
22334 
22335 	if (mp->b_datap->db_type == M_CTL) {
22336 		first_mp = mp;
22337 		mp_orig = mp = mp->b_cont;
22338 		mctl_present = B_TRUE;
22339 	} else {
22340 		first_mp = mp;
22341 		mctl_present = B_FALSE;
22342 	}
22343 
22344 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22345 	ipha = (ipha_t *)mp->b_rptr;
22346 
22347 	/*
22348 	 * If the Don't Fragment flag is on, generate an ICMP destination
22349 	 * unreachable, fragmentation needed.
22350 	 */
22351 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22352 	if (offset & IPH_DF) {
22353 		BUMP_MIB(&ip_mib, ipFragFails);
22354 		/*
22355 		 * Need to compute hdr checksum if called from ip_wput_ire.
22356 		 * Note that ip_rput_forward verifies the checksum before
22357 		 * calling this routine so in that case this is a noop.
22358 		 */
22359 		ipha->ipha_hdr_checksum = 0;
22360 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22361 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22362 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22363 		    "ip_wput_frag_end:(%S)",
22364 		    "don't fragment");
22365 		return;
22366 	}
22367 	if (mctl_present)
22368 		freeb(first_mp);
22369 	/*
22370 	 * Establish the starting offset.  May not be zero if we are fragging
22371 	 * a fragment that is being forwarded.
22372 	 */
22373 	offset = offset & IPH_OFFSET;
22374 
22375 	/* TODO why is this test needed? */
22376 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22377 	if (((max_frag - LENGTH) & ~7) < 8) {
22378 		/* TODO: notify ulp somehow */
22379 		BUMP_MIB(&ip_mib, ipFragFails);
22380 		freemsg(mp);
22381 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22382 		    "ip_wput_frag_end:(%S)",
22383 		    "len < 8");
22384 		return;
22385 	}
22386 
22387 	hdr_len = (V_HLEN & 0xF) << 2;
22388 
22389 	ipha->ipha_hdr_checksum = 0;
22390 
22391 	/*
22392 	 * Establish the number of bytes maximum per frag, after putting
22393 	 * in the header.
22394 	 */
22395 	len = (max_frag - hdr_len) & ~7;
22396 
22397 	/* Check if we can use MDT to send out the frags. */
22398 	ASSERT(!IRE_IS_LOCAL(ire));
22399 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
22400 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
22401 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
22402 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
22403 		ASSERT(ill->ill_mdt_capab != NULL);
22404 		if (!ill->ill_mdt_capab->ill_mdt_on) {
22405 			/*
22406 			 * If MDT has been previously turned off in the past,
22407 			 * and we currently can do MDT (due to IPQoS policy
22408 			 * removal, etc.) then enable it for this interface.
22409 			 */
22410 			ill->ill_mdt_capab->ill_mdt_on = 1;
22411 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
22412 			    ill->ill_name));
22413 		}
22414 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
22415 		    offset);
22416 		return;
22417 	}
22418 
22419 	/* Get a copy of the header for the trailing frags */
22420 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
22421 	if (!hdr_mp) {
22422 		BUMP_MIB(&ip_mib, ipOutDiscards);
22423 		freemsg(mp);
22424 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22425 		    "ip_wput_frag_end:(%S)",
22426 		    "couldn't copy hdr");
22427 		return;
22428 	}
22429 	if (DB_CRED(mp) != NULL)
22430 		mblk_setcred(hdr_mp, DB_CRED(mp));
22431 
22432 	/* Store the starting offset, with the MoreFrags flag. */
22433 	i1 = offset | IPH_MF | frag_flag;
22434 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
22435 
22436 	/* Establish the ending byte offset, based on the starting offset. */
22437 	offset <<= 3;
22438 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
22439 
22440 	/* Store the length of the first fragment in the IP header. */
22441 	i1 = len + hdr_len;
22442 	ASSERT(i1 <= IP_MAXPACKET);
22443 	ipha->ipha_length = htons((uint16_t)i1);
22444 
22445 	/*
22446 	 * Compute the IP header checksum for the first frag.  We have to
22447 	 * watch out that we stop at the end of the header.
22448 	 */
22449 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22450 
22451 	/*
22452 	 * Now carve off the first frag.  Note that this will include the
22453 	 * original IP header.
22454 	 */
22455 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
22456 		BUMP_MIB(&ip_mib, ipOutDiscards);
22457 		freeb(hdr_mp);
22458 		freemsg(mp_orig);
22459 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22460 		    "ip_wput_frag_end:(%S)",
22461 		    "couldn't carve first");
22462 		return;
22463 	}
22464 
22465 	/*
22466 	 * Multirouting case. Each fragment is replicated
22467 	 * via all non-condemned RTF_MULTIRT routes
22468 	 * currently resolved.
22469 	 * We ensure that first_ire is the first RTF_MULTIRT
22470 	 * ire in the bucket.
22471 	 */
22472 	if (ire->ire_flags & RTF_MULTIRT) {
22473 		irb = ire->ire_bucket;
22474 		ASSERT(irb != NULL);
22475 
22476 		multirt_send = B_TRUE;
22477 
22478 		/* Make sure we do not omit any multiroute ire. */
22479 		IRB_REFHOLD(irb);
22480 		for (first_ire = irb->irb_ire;
22481 		    first_ire != NULL;
22482 		    first_ire = first_ire->ire_next) {
22483 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22484 			    (first_ire->ire_addr == ire->ire_addr) &&
22485 			    !(first_ire->ire_marks &
22486 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22487 				break;
22488 		}
22489 
22490 		if (first_ire != NULL) {
22491 			if (first_ire != ire) {
22492 				IRE_REFHOLD(first_ire);
22493 				/*
22494 				 * Do not release the ire passed in
22495 				 * as the argument.
22496 				 */
22497 				ire = first_ire;
22498 			} else {
22499 				first_ire = NULL;
22500 			}
22501 		}
22502 		IRB_REFRELE(irb);
22503 
22504 		/*
22505 		 * Save the first ire; we will need to restore it
22506 		 * for the trailing frags.
22507 		 * We REFHOLD save_ire, as each iterated ire will be
22508 		 * REFRELEd.
22509 		 */
22510 		save_ire = ire;
22511 		IRE_REFHOLD(save_ire);
22512 	}
22513 
22514 	/*
22515 	 * First fragment emission loop.
22516 	 * In most cases, the emission loop below is entered only
22517 	 * once. Only in the case where the ire holds the RTF_MULTIRT
22518 	 * flag, do we loop to process all RTF_MULTIRT ires in the
22519 	 * bucket, and send the fragment through all crossed
22520 	 * RTF_MULTIRT routes.
22521 	 */
22522 	do {
22523 		if (ire->ire_flags & RTF_MULTIRT) {
22524 			/*
22525 			 * We are in a multiple send case, need to get
22526 			 * the next ire and make a copy of the packet.
22527 			 * ire1 holds here the next ire to process in the
22528 			 * bucket. If multirouting is expected,
22529 			 * any non-RTF_MULTIRT ire that has the
22530 			 * right destination address is ignored.
22531 			 *
22532 			 * We have to take into account the MTU of
22533 			 * each walked ire. max_frag is set by the
22534 			 * the caller and generally refers to
22535 			 * the primary ire entry. Here we ensure that
22536 			 * no route with a lower MTU will be used, as
22537 			 * fragments are carved once for all ires,
22538 			 * then replicated.
22539 			 */
22540 			ASSERT(irb != NULL);
22541 			IRB_REFHOLD(irb);
22542 			for (ire1 = ire->ire_next;
22543 			    ire1 != NULL;
22544 			    ire1 = ire1->ire_next) {
22545 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22546 					continue;
22547 				if (ire1->ire_addr != ire->ire_addr)
22548 					continue;
22549 				if (ire1->ire_marks &
22550 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22551 					continue;
22552 				/*
22553 				 * Ensure we do not exceed the MTU
22554 				 * of the next route.
22555 				 */
22556 				if (ire1->ire_max_frag < max_frag) {
22557 					ip_multirt_bad_mtu(ire1, max_frag);
22558 					continue;
22559 				}
22560 
22561 				/* Got one. */
22562 				IRE_REFHOLD(ire1);
22563 				break;
22564 			}
22565 			IRB_REFRELE(irb);
22566 
22567 			if (ire1 != NULL) {
22568 				next_mp = copyb(mp);
22569 				if ((next_mp == NULL) ||
22570 				    ((mp->b_cont != NULL) &&
22571 				    ((next_mp->b_cont =
22572 				    dupmsg(mp->b_cont)) == NULL))) {
22573 					freemsg(next_mp);
22574 					next_mp = NULL;
22575 					ire_refrele(ire1);
22576 					ire1 = NULL;
22577 				}
22578 			}
22579 
22580 			/* Last multiroute ire; don't loop anymore. */
22581 			if (ire1 == NULL) {
22582 				multirt_send = B_FALSE;
22583 			}
22584 		}
22585 
22586 		ll_hdr_len = 0;
22587 		LOCK_IRE_FP_MP(ire);
22588 		ll_hdr_mp = ire->ire_fp_mp;
22589 		if (ll_hdr_mp != NULL) {
22590 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22591 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
22592 		} else {
22593 			ll_hdr_mp = ire->ire_dlureq_mp;
22594 		}
22595 
22596 		/* If there is a transmit header, get a copy for this frag. */
22597 		/*
22598 		 * TODO: should check db_ref before calling ip_carve_mp since
22599 		 * it might give us a dup.
22600 		 */
22601 		if (!ll_hdr_mp) {
22602 			/* No xmit header. */
22603 			xmit_mp = mp;
22604 		} else if (mp->b_datap->db_ref == 1 &&
22605 		    ll_hdr_len != 0 &&
22606 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22607 			/* M_DATA fastpath */
22608 			mp->b_rptr -= ll_hdr_len;
22609 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
22610 			xmit_mp = mp;
22611 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
22612 			UNLOCK_IRE_FP_MP(ire);
22613 			BUMP_MIB(&ip_mib, ipOutDiscards);
22614 			freeb(hdr_mp);
22615 			freemsg(mp);
22616 			freemsg(mp_orig);
22617 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22618 			    "ip_wput_frag_end:(%S)",
22619 			    "discard");
22620 
22621 			if (multirt_send) {
22622 				ASSERT(ire1);
22623 				ASSERT(next_mp);
22624 
22625 				freemsg(next_mp);
22626 				ire_refrele(ire1);
22627 			}
22628 			if (save_ire != NULL)
22629 				IRE_REFRELE(save_ire);
22630 
22631 			if (first_ire != NULL)
22632 				ire_refrele(first_ire);
22633 			return;
22634 		} else {
22635 			xmit_mp->b_cont = mp;
22636 			if (DB_CRED(mp) != NULL)
22637 				mblk_setcred(xmit_mp, DB_CRED(mp));
22638 			/* Get priority marking, if any. */
22639 			if (DB_TYPE(xmit_mp) == M_DATA)
22640 				xmit_mp->b_band = mp->b_band;
22641 		}
22642 		UNLOCK_IRE_FP_MP(ire);
22643 		q = ire->ire_stq;
22644 		BUMP_MIB(&ip_mib, ipFragCreates);
22645 		putnext(q, xmit_mp);
22646 		if (pkt_type != OB_PKT) {
22647 			/*
22648 			 * Update the packet count of trailing
22649 			 * RTF_MULTIRT ires.
22650 			 */
22651 			UPDATE_OB_PKT_COUNT(ire);
22652 		}
22653 
22654 		if (multirt_send) {
22655 			/*
22656 			 * We are in a multiple send case; look for
22657 			 * the next ire and re-enter the loop.
22658 			 */
22659 			ASSERT(ire1);
22660 			ASSERT(next_mp);
22661 			/* REFRELE the current ire before looping */
22662 			ire_refrele(ire);
22663 			ire = ire1;
22664 			ire1 = NULL;
22665 			mp = next_mp;
22666 			next_mp = NULL;
22667 		}
22668 	} while (multirt_send);
22669 
22670 	ASSERT(ire1 == NULL);
22671 
22672 	/* Restore the original ire; we need it for the trailing frags */
22673 	if (save_ire != NULL) {
22674 		/* REFRELE the last iterated ire */
22675 		ire_refrele(ire);
22676 		/* save_ire has been REFHOLDed */
22677 		ire = save_ire;
22678 		save_ire = NULL;
22679 		q = ire->ire_stq;
22680 	}
22681 
22682 	if (pkt_type == OB_PKT) {
22683 		UPDATE_OB_PKT_COUNT(ire);
22684 	} else {
22685 		UPDATE_IB_PKT_COUNT(ire);
22686 	}
22687 
22688 	/* Advance the offset to the second frag starting point. */
22689 	offset += len;
22690 	/*
22691 	 * Update hdr_len from the copied header - there might be less options
22692 	 * in the later fragments.
22693 	 */
22694 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
22695 	/* Loop until done. */
22696 	for (;;) {
22697 		uint16_t	offset_and_flags;
22698 		uint16_t	ip_len;
22699 
22700 		if (ip_data_end - offset > len) {
22701 			/*
22702 			 * Carve off the appropriate amount from the original
22703 			 * datagram.
22704 			 */
22705 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22706 				mp = NULL;
22707 				break;
22708 			}
22709 			/*
22710 			 * More frags after this one.  Get another copy
22711 			 * of the header.
22712 			 */
22713 			if (carve_mp->b_datap->db_ref == 1 &&
22714 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22715 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22716 				/* Inline IP header */
22717 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22718 				    hdr_mp->b_rptr;
22719 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22720 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22721 				mp = carve_mp;
22722 			} else {
22723 				if (!(mp = copyb(hdr_mp))) {
22724 					freemsg(carve_mp);
22725 					break;
22726 				}
22727 				/* Get priority marking, if any. */
22728 				mp->b_band = carve_mp->b_band;
22729 				mp->b_cont = carve_mp;
22730 			}
22731 			ipha = (ipha_t *)mp->b_rptr;
22732 			offset_and_flags = IPH_MF;
22733 		} else {
22734 			/*
22735 			 * Last frag.  Consume the header. Set len to
22736 			 * the length of this last piece.
22737 			 */
22738 			len = ip_data_end - offset;
22739 
22740 			/*
22741 			 * Carve off the appropriate amount from the original
22742 			 * datagram.
22743 			 */
22744 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22745 				mp = NULL;
22746 				break;
22747 			}
22748 			if (carve_mp->b_datap->db_ref == 1 &&
22749 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22750 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22751 				/* Inline IP header */
22752 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22753 				    hdr_mp->b_rptr;
22754 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22755 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22756 				mp = carve_mp;
22757 				freeb(hdr_mp);
22758 				hdr_mp = mp;
22759 			} else {
22760 				mp = hdr_mp;
22761 				/* Get priority marking, if any. */
22762 				mp->b_band = carve_mp->b_band;
22763 				mp->b_cont = carve_mp;
22764 			}
22765 			ipha = (ipha_t *)mp->b_rptr;
22766 			/* A frag of a frag might have IPH_MF non-zero */
22767 			offset_and_flags =
22768 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22769 			    IPH_MF;
22770 		}
22771 		offset_and_flags |= (uint16_t)(offset >> 3);
22772 		offset_and_flags |= (uint16_t)frag_flag;
22773 		/* Store the offset and flags in the IP header. */
22774 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22775 
22776 		/* Store the length in the IP header. */
22777 		ip_len = (uint16_t)(len + hdr_len);
22778 		ipha->ipha_length = htons(ip_len);
22779 
22780 		/*
22781 		 * Set the IP header checksum.	Note that mp is just
22782 		 * the header, so this is easy to pass to ip_csum.
22783 		 */
22784 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22785 
22786 		/* Attach a transmit header, if any, and ship it. */
22787 		if (pkt_type == OB_PKT) {
22788 			UPDATE_OB_PKT_COUNT(ire);
22789 		} else {
22790 			UPDATE_IB_PKT_COUNT(ire);
22791 		}
22792 
22793 		if (ire->ire_flags & RTF_MULTIRT) {
22794 			irb = ire->ire_bucket;
22795 			ASSERT(irb != NULL);
22796 
22797 			multirt_send = B_TRUE;
22798 
22799 			/*
22800 			 * Save the original ire; we will need to restore it
22801 			 * for the tailing frags.
22802 			 */
22803 			save_ire = ire;
22804 			IRE_REFHOLD(save_ire);
22805 		}
22806 		/*
22807 		 * Emission loop for this fragment, similar
22808 		 * to what is done for the first fragment.
22809 		 */
22810 		do {
22811 			if (multirt_send) {
22812 				/*
22813 				 * We are in a multiple send case, need to get
22814 				 * the next ire and make a copy of the packet.
22815 				 */
22816 				ASSERT(irb != NULL);
22817 				IRB_REFHOLD(irb);
22818 				for (ire1 = ire->ire_next;
22819 				    ire1 != NULL;
22820 				    ire1 = ire1->ire_next) {
22821 					if (!(ire1->ire_flags & RTF_MULTIRT))
22822 						continue;
22823 					if (ire1->ire_addr != ire->ire_addr)
22824 						continue;
22825 					if (ire1->ire_marks &
22826 					    (IRE_MARK_CONDEMNED|
22827 						IRE_MARK_HIDDEN))
22828 						continue;
22829 					/*
22830 					 * Ensure we do not exceed the MTU
22831 					 * of the next route.
22832 					 */
22833 					if (ire1->ire_max_frag < max_frag) {
22834 						ip_multirt_bad_mtu(ire1,
22835 						    max_frag);
22836 						continue;
22837 					}
22838 
22839 					/* Got one. */
22840 					IRE_REFHOLD(ire1);
22841 					break;
22842 				}
22843 				IRB_REFRELE(irb);
22844 
22845 				if (ire1 != NULL) {
22846 					next_mp = copyb(mp);
22847 					if ((next_mp == NULL) ||
22848 					    ((mp->b_cont != NULL) &&
22849 					    ((next_mp->b_cont =
22850 					    dupmsg(mp->b_cont)) == NULL))) {
22851 						freemsg(next_mp);
22852 						next_mp = NULL;
22853 						ire_refrele(ire1);
22854 						ire1 = NULL;
22855 					}
22856 				}
22857 
22858 				/* Last multiroute ire; don't loop anymore. */
22859 				if (ire1 == NULL) {
22860 					multirt_send = B_FALSE;
22861 				}
22862 			}
22863 
22864 			/* Update transmit header */
22865 			ll_hdr_len = 0;
22866 			LOCK_IRE_FP_MP(ire);
22867 			ll_hdr_mp = ire->ire_fp_mp;
22868 			if (ll_hdr_mp != NULL) {
22869 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22870 				ll_hdr_len = MBLKL(ll_hdr_mp);
22871 			} else {
22872 				ll_hdr_mp = ire->ire_dlureq_mp;
22873 			}
22874 
22875 			if (!ll_hdr_mp) {
22876 				xmit_mp = mp;
22877 			} else if (mp->b_datap->db_ref == 1 &&
22878 			    ll_hdr_len != 0 &&
22879 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22880 				/* M_DATA fastpath */
22881 				mp->b_rptr -= ll_hdr_len;
22882 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22883 				    ll_hdr_len);
22884 				xmit_mp = mp;
22885 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22886 				xmit_mp->b_cont = mp;
22887 				if (DB_CRED(mp) != NULL)
22888 					mblk_setcred(xmit_mp, DB_CRED(mp));
22889 				/* Get priority marking, if any. */
22890 				if (DB_TYPE(xmit_mp) == M_DATA)
22891 					xmit_mp->b_band = mp->b_band;
22892 			} else {
22893 				/*
22894 				 * Exit both the replication and
22895 				 * fragmentation loops.
22896 				 */
22897 				UNLOCK_IRE_FP_MP(ire);
22898 				goto drop_pkt;
22899 			}
22900 			UNLOCK_IRE_FP_MP(ire);
22901 			BUMP_MIB(&ip_mib, ipFragCreates);
22902 			putnext(q, xmit_mp);
22903 
22904 			if (pkt_type != OB_PKT) {
22905 				/*
22906 				 * Update the packet count of trailing
22907 				 * RTF_MULTIRT ires.
22908 				 */
22909 				UPDATE_OB_PKT_COUNT(ire);
22910 			}
22911 
22912 			/* All done if we just consumed the hdr_mp. */
22913 			if (mp == hdr_mp) {
22914 				last_frag = B_TRUE;
22915 			}
22916 
22917 			if (multirt_send) {
22918 				/*
22919 				 * We are in a multiple send case; look for
22920 				 * the next ire and re-enter the loop.
22921 				 */
22922 				ASSERT(ire1);
22923 				ASSERT(next_mp);
22924 				/* REFRELE the current ire before looping */
22925 				ire_refrele(ire);
22926 				ire = ire1;
22927 				ire1 = NULL;
22928 				q = ire->ire_stq;
22929 				mp = next_mp;
22930 				next_mp = NULL;
22931 			}
22932 		} while (multirt_send);
22933 		/*
22934 		 * Restore the original ire; we need it for the
22935 		 * trailing frags
22936 		 */
22937 		if (save_ire != NULL) {
22938 			ASSERT(ire1 == NULL);
22939 			/* REFRELE the last iterated ire */
22940 			ire_refrele(ire);
22941 			/* save_ire has been REFHOLDed */
22942 			ire = save_ire;
22943 			q = ire->ire_stq;
22944 			save_ire = NULL;
22945 		}
22946 
22947 		if (last_frag) {
22948 			BUMP_MIB(&ip_mib, ipFragOKs);
22949 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22950 			    "ip_wput_frag_end:(%S)",
22951 			    "consumed hdr_mp");
22952 
22953 			if (first_ire != NULL)
22954 				ire_refrele(first_ire);
22955 			return;
22956 		}
22957 		/* Otherwise, advance and loop. */
22958 		offset += len;
22959 	}
22960 
22961 drop_pkt:
22962 	/* Clean up following allocation failure. */
22963 	BUMP_MIB(&ip_mib, ipOutDiscards);
22964 	freemsg(mp);
22965 	if (mp != hdr_mp)
22966 		freeb(hdr_mp);
22967 	if (mp != mp_orig)
22968 		freemsg(mp_orig);
22969 
22970 	if (save_ire != NULL)
22971 		IRE_REFRELE(save_ire);
22972 	if (first_ire != NULL)
22973 		ire_refrele(first_ire);
22974 
22975 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22976 	    "ip_wput_frag_end:(%S)",
22977 	    "end--alloc failure");
22978 }
22979 
22980 /*
22981  * Copy the header plus those options which have the copy bit set
22982  */
22983 static mblk_t *
22984 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22985 {
22986 	mblk_t	*mp;
22987 	uchar_t	*up;
22988 
22989 	/*
22990 	 * Quick check if we need to look for options without the copy bit
22991 	 * set
22992 	 */
22993 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22994 	if (!mp)
22995 		return (mp);
22996 	mp->b_rptr += ip_wroff_extra;
22997 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22998 		bcopy(rptr, mp->b_rptr, hdr_len);
22999 		mp->b_wptr += hdr_len + ip_wroff_extra;
23000 		return (mp);
23001 	}
23002 	up  = mp->b_rptr;
23003 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23004 	up += IP_SIMPLE_HDR_LENGTH;
23005 	rptr += IP_SIMPLE_HDR_LENGTH;
23006 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23007 	while (hdr_len > 0) {
23008 		uint32_t optval;
23009 		uint32_t optlen;
23010 
23011 		optval = *rptr;
23012 		if (optval == IPOPT_EOL)
23013 			break;
23014 		if (optval == IPOPT_NOP)
23015 			optlen = 1;
23016 		else
23017 			optlen = rptr[1];
23018 		if (optval & IPOPT_COPY) {
23019 			bcopy(rptr, up, optlen);
23020 			up += optlen;
23021 		}
23022 		rptr += optlen;
23023 		hdr_len -= optlen;
23024 	}
23025 	/*
23026 	 * Make sure that we drop an even number of words by filling
23027 	 * with EOL to the next word boundary.
23028 	 */
23029 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23030 	    hdr_len & 0x3; hdr_len++)
23031 		*up++ = IPOPT_EOL;
23032 	mp->b_wptr = up;
23033 	/* Update header length */
23034 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23035 	return (mp);
23036 }
23037 
23038 /*
23039  * Delivery to local recipients including fanout to multiple recipients.
23040  * Does not do checksumming of UDP/TCP.
23041  * Note: q should be the read side queue for either the ill or conn.
23042  * Note: rq should be the read side q for the lower (ill) stream.
23043  * We don't send packets to IPPF processing, thus the last argument
23044  * to all the fanout calls are B_FALSE.
23045  */
23046 void
23047 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23048     int fanout_flags, zoneid_t zoneid)
23049 {
23050 	uint32_t	protocol;
23051 	mblk_t		*first_mp;
23052 	boolean_t	mctl_present;
23053 	int		ire_type;
23054 #define	rptr	((uchar_t *)ipha)
23055 
23056 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23057 	    "ip_wput_local_start: q %p", q);
23058 
23059 	if (ire != NULL) {
23060 		ire_type = ire->ire_type;
23061 	} else {
23062 		/*
23063 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23064 		 * packet is not multicast, we can't tell the ire type.
23065 		 */
23066 		ASSERT(CLASSD(ipha->ipha_dst));
23067 		ire_type = IRE_BROADCAST;
23068 	}
23069 
23070 	first_mp = mp;
23071 	if (first_mp->b_datap->db_type == M_CTL) {
23072 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23073 		if (!io->ipsec_out_secure) {
23074 			/*
23075 			 * This ipsec_out_t was allocated in ip_wput
23076 			 * for multicast packets to store the ill_index.
23077 			 * As this is being delivered locally, we don't
23078 			 * need this anymore.
23079 			 */
23080 			mp = first_mp->b_cont;
23081 			freeb(first_mp);
23082 			first_mp = mp;
23083 			mctl_present = B_FALSE;
23084 		} else {
23085 			mctl_present = B_TRUE;
23086 			mp = first_mp->b_cont;
23087 			ASSERT(mp != NULL);
23088 			ipsec_out_to_in(first_mp);
23089 		}
23090 	} else {
23091 		mctl_present = B_FALSE;
23092 	}
23093 
23094 	loopback_packets++;
23095 
23096 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23097 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23098 	if (!IS_SIMPLE_IPH(ipha)) {
23099 		ip_wput_local_options(ipha);
23100 	}
23101 
23102 	protocol = ipha->ipha_protocol;
23103 	switch (protocol) {
23104 	case IPPROTO_ICMP: {
23105 		ire_t		*ire_zone;
23106 		ilm_t		*ilm;
23107 		mblk_t		*mp1;
23108 		zoneid_t	last_zoneid;
23109 
23110 		if (CLASSD(ipha->ipha_dst) &&
23111 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23112 			ASSERT(ire_type == IRE_BROADCAST);
23113 			/*
23114 			 * In the multicast case, applications may have joined
23115 			 * the group from different zones, so we need to deliver
23116 			 * the packet to each of them. Loop through the
23117 			 * multicast memberships structures (ilm) on the receive
23118 			 * ill and send a copy of the packet up each matching
23119 			 * one. However, we don't do this for multicasts sent on
23120 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23121 			 * they must stay in the sender's zone.
23122 			 *
23123 			 * ilm_add_v6() ensures that ilms in the same zone are
23124 			 * contiguous in the ill_ilm list. We use this property
23125 			 * to avoid sending duplicates needed when two
23126 			 * applications in the same zone join the same group on
23127 			 * different logical interfaces: we ignore the ilm if
23128 			 * its zoneid is the same as the last matching one.
23129 			 * In addition, the sending of the packet for
23130 			 * ire_zoneid is delayed until all of the other ilms
23131 			 * have been exhausted.
23132 			 */
23133 			last_zoneid = -1;
23134 			ILM_WALKER_HOLD(ill);
23135 			for (ilm = ill->ill_ilm; ilm != NULL;
23136 			    ilm = ilm->ilm_next) {
23137 				if ((ilm->ilm_flags & ILM_DELETED) ||
23138 				    ipha->ipha_dst != ilm->ilm_addr ||
23139 				    ilm->ilm_zoneid == last_zoneid ||
23140 				    ilm->ilm_zoneid == zoneid ||
23141 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23142 					continue;
23143 				mp1 = ip_copymsg(first_mp);
23144 				if (mp1 == NULL)
23145 					continue;
23146 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23147 				    mctl_present, B_FALSE, ill,
23148 				    ilm->ilm_zoneid);
23149 				last_zoneid = ilm->ilm_zoneid;
23150 			}
23151 			ILM_WALKER_RELE(ill);
23152 			/*
23153 			 * Loopback case: the sending endpoint has
23154 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23155 			 * dispatch the multicast packet to the sending zone.
23156 			 */
23157 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23158 				freemsg(first_mp);
23159 				return;
23160 			}
23161 		} else if (ire_type == IRE_BROADCAST) {
23162 			/*
23163 			 * In the broadcast case, there may be many zones
23164 			 * which need a copy of the packet delivered to them.
23165 			 * There is one IRE_BROADCAST per broadcast address
23166 			 * and per zone; we walk those using a helper function.
23167 			 * In addition, the sending of the packet for zoneid is
23168 			 * delayed until all of the other ires have been
23169 			 * processed.
23170 			 */
23171 			IRB_REFHOLD(ire->ire_bucket);
23172 			ire_zone = NULL;
23173 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23174 			    ire)) != NULL) {
23175 				mp1 = ip_copymsg(first_mp);
23176 				if (mp1 == NULL)
23177 					continue;
23178 
23179 				UPDATE_IB_PKT_COUNT(ire_zone);
23180 				ire_zone->ire_last_used_time = lbolt;
23181 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23182 				    mctl_present, B_FALSE, ill,
23183 				    ire_zone->ire_zoneid);
23184 			}
23185 			IRB_REFRELE(ire->ire_bucket);
23186 		}
23187 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23188 		    0, mctl_present, B_FALSE, ill, zoneid);
23189 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23190 		    "ip_wput_local_end: q %p (%S)",
23191 		    q, "icmp");
23192 		return;
23193 	}
23194 	case IPPROTO_IGMP:
23195 		if (igmp_input(q, mp, ill)) {
23196 			/* Bad packet - discarded by igmp_input */
23197 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23198 			    "ip_wput_local_end: q %p (%S)",
23199 			    q, "igmp_input--bad packet");
23200 			if (mctl_present)
23201 				freeb(first_mp);
23202 			return;
23203 		}
23204 		/*
23205 		 * igmp_input() may have pulled up the message so ipha needs to
23206 		 * be reinitialized.
23207 		 */
23208 		ipha = (ipha_t *)mp->b_rptr;
23209 		/* deliver to local raw users */
23210 		break;
23211 	case IPPROTO_ENCAP:
23212 		/*
23213 		 * This case is covered by either ip_fanout_proto, or by
23214 		 * the above security processing for self-tunneled packets.
23215 		 */
23216 		break;
23217 	case IPPROTO_UDP: {
23218 		uint16_t	*up;
23219 		uint32_t	ports;
23220 
23221 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23222 		    UDP_PORTS_OFFSET);
23223 		/* Force a 'valid' checksum. */
23224 		up[3] = 0;
23225 
23226 		ports = *(uint32_t *)up;
23227 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23228 		    (ire_type == IRE_BROADCAST),
23229 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23230 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23231 		    ill, zoneid);
23232 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23233 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23234 		return;
23235 	}
23236 	case IPPROTO_TCP: {
23237 
23238 		/*
23239 		 * For TCP, discard broadcast packets.
23240 		 */
23241 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23242 			freemsg(first_mp);
23243 			BUMP_MIB(&ip_mib, ipInDiscards);
23244 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23245 			return;
23246 		}
23247 
23248 		if (mp->b_datap->db_type == M_DATA) {
23249 			/*
23250 			 * M_DATA mblk, so init mblk (chain) for no struio().
23251 			 */
23252 			mblk_t	*mp1 = mp;
23253 
23254 			do
23255 				mp1->b_datap->db_struioflag = 0;
23256 			while ((mp1 = mp1->b_cont) != NULL);
23257 		}
23258 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23259 		    <= mp->b_wptr);
23260 		ip_fanout_tcp(q, first_mp, ill, ipha,
23261 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23262 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23263 		    mctl_present, B_FALSE, zoneid);
23264 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23265 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23266 		return;
23267 	}
23268 	case IPPROTO_SCTP:
23269 	{
23270 		uint32_t	ports;
23271 
23272 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23273 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23274 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23275 		    IP_FF_IP6INFO,
23276 		    mctl_present, B_FALSE, 0, zoneid);
23277 		return;
23278 	}
23279 
23280 	default:
23281 		break;
23282 	}
23283 	/*
23284 	 * Find a client for some other protocol.  We give
23285 	 * copies to multiple clients, if more than one is
23286 	 * bound.
23287 	 */
23288 	ip_fanout_proto(q, first_mp, ill, ipha,
23289 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23290 	    mctl_present, B_FALSE, ill, zoneid);
23291 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23292 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23293 #undef	rptr
23294 }
23295 
23296 /*
23297  * Update any source route, record route, or timestamp options.
23298  * Check that we are at end of strict source route.
23299  * The options have been sanity checked by ip_wput_options().
23300  */
23301 static void
23302 ip_wput_local_options(ipha_t *ipha)
23303 {
23304 	ipoptp_t	opts;
23305 	uchar_t		*opt;
23306 	uint8_t		optval;
23307 	uint8_t		optlen;
23308 	ipaddr_t	dst;
23309 	uint32_t	ts;
23310 	ire_t		*ire;
23311 	timestruc_t	now;
23312 
23313 	ip2dbg(("ip_wput_local_options\n"));
23314 	for (optval = ipoptp_first(&opts, ipha);
23315 	    optval != IPOPT_EOL;
23316 	    optval = ipoptp_next(&opts)) {
23317 		opt = opts.ipoptp_cur;
23318 		optlen = opts.ipoptp_len;
23319 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23320 		switch (optval) {
23321 			uint32_t off;
23322 		case IPOPT_SSRR:
23323 		case IPOPT_LSRR:
23324 			off = opt[IPOPT_OFFSET];
23325 			off--;
23326 			if (optlen < IP_ADDR_LEN ||
23327 			    off > optlen - IP_ADDR_LEN) {
23328 				/* End of source route */
23329 				break;
23330 			}
23331 			/*
23332 			 * This will only happen if two consecutive entries
23333 			 * in the source route contains our address or if
23334 			 * it is a packet with a loose source route which
23335 			 * reaches us before consuming the whole source route
23336 			 */
23337 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23338 			if (optval == IPOPT_SSRR) {
23339 				return;
23340 			}
23341 			/*
23342 			 * Hack: instead of dropping the packet truncate the
23343 			 * source route to what has been used by filling the
23344 			 * rest with IPOPT_NOP.
23345 			 */
23346 			opt[IPOPT_OLEN] = (uint8_t)off;
23347 			while (off < optlen) {
23348 				opt[off++] = IPOPT_NOP;
23349 			}
23350 			break;
23351 		case IPOPT_RR:
23352 			off = opt[IPOPT_OFFSET];
23353 			off--;
23354 			if (optlen < IP_ADDR_LEN ||
23355 			    off > optlen - IP_ADDR_LEN) {
23356 				/* No more room - ignore */
23357 				ip1dbg((
23358 				    "ip_wput_forward_options: end of RR\n"));
23359 				break;
23360 			}
23361 			dst = htonl(INADDR_LOOPBACK);
23362 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23363 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23364 			break;
23365 		case IPOPT_TS:
23366 			/* Insert timestamp if there is romm */
23367 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23368 			case IPOPT_TS_TSONLY:
23369 				off = IPOPT_TS_TIMELEN;
23370 				break;
23371 			case IPOPT_TS_PRESPEC:
23372 			case IPOPT_TS_PRESPEC_RFC791:
23373 				/* Verify that the address matched */
23374 				off = opt[IPOPT_OFFSET] - 1;
23375 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
23376 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
23377 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
23378 				if (ire == NULL) {
23379 					/* Not for us */
23380 					break;
23381 				}
23382 				ire_refrele(ire);
23383 				/* FALLTHRU */
23384 			case IPOPT_TS_TSANDADDR:
23385 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
23386 				break;
23387 			default:
23388 				/*
23389 				 * ip_*put_options should have already
23390 				 * dropped this packet.
23391 				 */
23392 				cmn_err(CE_PANIC, "ip_wput_local_options: "
23393 				    "unknown IT - bug in ip_wput_options?\n");
23394 				return;	/* Keep "lint" happy */
23395 			}
23396 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
23397 				/* Increase overflow counter */
23398 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
23399 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
23400 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
23401 				    (off << 4);
23402 				break;
23403 			}
23404 			off = opt[IPOPT_OFFSET] - 1;
23405 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23406 			case IPOPT_TS_PRESPEC:
23407 			case IPOPT_TS_PRESPEC_RFC791:
23408 			case IPOPT_TS_TSANDADDR:
23409 				dst = htonl(INADDR_LOOPBACK);
23410 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23411 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23412 				/* FALLTHRU */
23413 			case IPOPT_TS_TSONLY:
23414 				off = opt[IPOPT_OFFSET] - 1;
23415 				/* Compute # of milliseconds since midnight */
23416 				gethrestime(&now);
23417 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
23418 				    now.tv_nsec / (NANOSEC / MILLISEC);
23419 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
23420 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
23421 				break;
23422 			}
23423 			break;
23424 		}
23425 	}
23426 }
23427 
23428 /*
23429  * Send out a multicast packet on interface ipif.
23430  * The sender does not have an conn.
23431  * Caller verifies that this isn't a PHYI_LOOPBACK.
23432  */
23433 void
23434 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
23435 {
23436 	ipha_t	*ipha;
23437 	ire_t	*ire;
23438 	ipaddr_t	dst;
23439 	mblk_t		*first_mp;
23440 
23441 	/* igmp_sendpkt always allocates a ipsec_out_t */
23442 	ASSERT(mp->b_datap->db_type == M_CTL);
23443 	ASSERT(!ipif->ipif_isv6);
23444 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
23445 
23446 	first_mp = mp;
23447 	mp = first_mp->b_cont;
23448 	ASSERT(mp->b_datap->db_type == M_DATA);
23449 	ipha = (ipha_t *)mp->b_rptr;
23450 
23451 	/*
23452 	 * Find an IRE which matches the destination and the outgoing
23453 	 * queue (i.e. the outgoing interface.)
23454 	 */
23455 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
23456 		dst = ipif->ipif_pp_dst_addr;
23457 	else
23458 		dst = ipha->ipha_dst;
23459 	/*
23460 	 * The source address has already been initialized by the
23461 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
23462 	 * be sufficient rather than MATCH_IRE_IPIF.
23463 	 *
23464 	 * This function is used for sending IGMP packets. We need
23465 	 * to make sure that we send the packet out of the interface
23466 	 * (ipif->ipif_ill) where we joined the group. This is to
23467 	 * prevent from switches doing IGMP snooping to send us multicast
23468 	 * packets for a given group on the interface we have joined.
23469 	 * If we can't find an ire, igmp_sendpkt has already initialized
23470 	 * ipsec_out_attach_if so that this will not be load spread in
23471 	 * ip_newroute_ipif.
23472 	 */
23473 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
23474 	    MATCH_IRE_ILL);
23475 	if (!ire) {
23476 		/*
23477 		 * Mark this packet to make it be delivered to
23478 		 * ip_wput_ire after the new ire has been
23479 		 * created.
23480 		 */
23481 		mp->b_prev = NULL;
23482 		mp->b_next = NULL;
23483 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
23484 		return;
23485 	}
23486 
23487 	/*
23488 	 * Honor the RTF_SETSRC flag; this is the only case
23489 	 * where we force this addr whatever the current src addr is,
23490 	 * because this address is set by igmp_sendpkt(), and
23491 	 * cannot be specified by any user.
23492 	 */
23493 	if (ire->ire_flags & RTF_SETSRC) {
23494 		ipha->ipha_src = ire->ire_src_addr;
23495 	}
23496 
23497 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
23498 }
23499 
23500 /*
23501  * NOTE : This function does not ire_refrele the ire argument passed in.
23502  *
23503  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
23504  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
23505  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
23506  * the ire_lock to access the ire_fp_mp in this case.
23507  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
23508  * prepending a fastpath message IPQoS processing must precede it, we also set
23509  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
23510  * (IPQoS might have set the b_band for CoS marking).
23511  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
23512  * must follow it so that IPQoS can mark the dl_priority field for CoS
23513  * marking, if needed.
23514  */
23515 static mblk_t *
23516 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
23517 {
23518 	uint_t	hlen;
23519 	ipha_t *ipha;
23520 	mblk_t *mp1;
23521 	boolean_t qos_done = B_FALSE;
23522 	uchar_t	*ll_hdr;
23523 
23524 #define	rptr	((uchar_t *)ipha)
23525 
23526 	ipha = (ipha_t *)mp->b_rptr;
23527 	hlen = 0;
23528 	LOCK_IRE_FP_MP(ire);
23529 	if ((mp1 = ire->ire_fp_mp) != NULL) {
23530 		ASSERT(DB_TYPE(mp1) == M_DATA);
23531 		/* Initiate IPPF processing */
23532 		if ((proc != 0) && IPP_ENABLED(proc)) {
23533 			UNLOCK_IRE_FP_MP(ire);
23534 			ip_process(proc, &mp, ill_index);
23535 			if (mp == NULL)
23536 				return (NULL);
23537 
23538 			ipha = (ipha_t *)mp->b_rptr;
23539 			LOCK_IRE_FP_MP(ire);
23540 			if ((mp1 = ire->ire_fp_mp) == NULL) {
23541 				qos_done = B_TRUE;
23542 				goto no_fp_mp;
23543 			}
23544 			ASSERT(DB_TYPE(mp1) == M_DATA);
23545 		}
23546 		hlen = MBLKL(mp1);
23547 		/*
23548 		 * Check if we have enough room to prepend fastpath
23549 		 * header
23550 		 */
23551 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
23552 			ll_hdr = rptr - hlen;
23553 			bcopy(mp1->b_rptr, ll_hdr, hlen);
23554 			/* XXX ipha is not aligned here */
23555 			ipha = (ipha_t *)(rptr - hlen);
23556 			/*
23557 			 * Set the b_rptr to the start of the link layer
23558 			 * header
23559 			 */
23560 			mp->b_rptr = rptr;
23561 			mp1 = mp;
23562 		} else {
23563 			mp1 = copyb(mp1);
23564 			if (mp1 == NULL)
23565 				goto unlock_err;
23566 			mp1->b_band = mp->b_band;
23567 			mp1->b_cont = mp;
23568 			/*
23569 			 * certain system generated traffic may not
23570 			 * have cred/label in ip header block. This
23571 			 * is true even for a labeled system. But for
23572 			 * labeled traffic, inherit the label in the
23573 			 * new header.
23574 			 */
23575 			if (DB_CRED(mp) != NULL)
23576 				mblk_setcred(mp1, DB_CRED(mp));
23577 			/*
23578 			 * XXX disable ICK_VALID and compute checksum
23579 			 * here; can happen if ire_fp_mp changes and
23580 			 * it can't be copied now due to insufficient
23581 			 * space. (unlikely, fp mp can change, but it
23582 			 * does not increase in length)
23583 			 */
23584 		}
23585 		UNLOCK_IRE_FP_MP(ire);
23586 	} else {
23587 no_fp_mp:
23588 		mp1 = copyb(ire->ire_dlureq_mp);
23589 		if (mp1 == NULL) {
23590 unlock_err:
23591 			UNLOCK_IRE_FP_MP(ire);
23592 			freemsg(mp);
23593 			return (NULL);
23594 		}
23595 		UNLOCK_IRE_FP_MP(ire);
23596 		mp1->b_cont = mp;
23597 		/*
23598 		 * certain system generated traffic may not
23599 		 * have cred/label in ip header block. This
23600 		 * is true even for a labeled system. But for
23601 		 * labeled traffic, inherit the label in the
23602 		 * new header.
23603 		 */
23604 		if (DB_CRED(mp) != NULL)
23605 			mblk_setcred(mp1, DB_CRED(mp));
23606 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
23607 			ip_process(proc, &mp1, ill_index);
23608 			if (mp1 == NULL)
23609 				return (NULL);
23610 		}
23611 	}
23612 	return (mp1);
23613 #undef rptr
23614 }
23615 
23616 /*
23617  * Finish the outbound IPsec processing for an IPv6 packet. This function
23618  * is called from ipsec_out_process() if the IPsec packet was processed
23619  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23620  * asynchronously.
23621  */
23622 void
23623 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
23624     ire_t *ire_arg)
23625 {
23626 	in6_addr_t *v6dstp;
23627 	ire_t *ire;
23628 	mblk_t *mp;
23629 	uint_t	ill_index;
23630 	ipsec_out_t *io;
23631 	boolean_t attach_if, hwaccel;
23632 	uint32_t flags = IP6_NO_IPPOLICY;
23633 	int match_flags;
23634 	zoneid_t zoneid;
23635 	boolean_t ill_need_rele = B_FALSE;
23636 	boolean_t ire_need_rele = B_FALSE;
23637 
23638 	mp = ipsec_mp->b_cont;
23639 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23640 	ill_index = io->ipsec_out_ill_index;
23641 	if (io->ipsec_out_reachable) {
23642 		flags |= IPV6_REACHABILITY_CONFIRMATION;
23643 	}
23644 	attach_if = io->ipsec_out_attach_if;
23645 	hwaccel = io->ipsec_out_accelerated;
23646 	zoneid = io->ipsec_out_zoneid;
23647 	ASSERT(zoneid != ALL_ZONES);
23648 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23649 	/* Multicast addresses should have non-zero ill_index. */
23650 	v6dstp = &ip6h->ip6_dst;
23651 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
23652 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
23653 	ASSERT(!attach_if || ill_index != 0);
23654 	if (ill_index != 0) {
23655 		if (ill == NULL) {
23656 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
23657 			    B_TRUE);
23658 
23659 			/* Failure case frees things for us. */
23660 			if (ill == NULL)
23661 				return;
23662 
23663 			ill_need_rele = B_TRUE;
23664 		}
23665 		/*
23666 		 * If this packet needs to go out on a particular interface
23667 		 * honor it.
23668 		 */
23669 		if (attach_if) {
23670 			match_flags = MATCH_IRE_ILL;
23671 
23672 			/*
23673 			 * Check if we need an ire that will not be
23674 			 * looked up by anybody else i.e. HIDDEN.
23675 			 */
23676 			if (ill_is_probeonly(ill)) {
23677 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23678 			}
23679 		}
23680 	}
23681 	ASSERT(mp != NULL);
23682 
23683 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
23684 		boolean_t unspec_src;
23685 		ipif_t	*ipif;
23686 
23687 		/*
23688 		 * Use the ill_index to get the right ill.
23689 		 */
23690 		unspec_src = io->ipsec_out_unspec_src;
23691 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23692 		if (ipif == NULL) {
23693 			if (ill_need_rele)
23694 				ill_refrele(ill);
23695 			freemsg(ipsec_mp);
23696 			return;
23697 		}
23698 
23699 		if (ire_arg != NULL) {
23700 			ire = ire_arg;
23701 		} else {
23702 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23703 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23704 			ire_need_rele = B_TRUE;
23705 		}
23706 		if (ire != NULL) {
23707 			ipif_refrele(ipif);
23708 			/*
23709 			 * XXX Do the multicast forwarding now, as the IPSEC
23710 			 * processing has been done.
23711 			 */
23712 			goto send;
23713 		}
23714 
23715 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
23716 		mp->b_prev = NULL;
23717 		mp->b_next = NULL;
23718 
23719 		/*
23720 		 * If the IPsec packet was processed asynchronously,
23721 		 * drop it now.
23722 		 */
23723 		if (q == NULL) {
23724 			if (ill_need_rele)
23725 				ill_refrele(ill);
23726 			freemsg(ipsec_mp);
23727 			return;
23728 		}
23729 
23730 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
23731 		    unspec_src, zoneid);
23732 		ipif_refrele(ipif);
23733 	} else {
23734 		if (attach_if) {
23735 			ipif_t	*ipif;
23736 
23737 			ipif = ipif_get_next_ipif(NULL, ill);
23738 			if (ipif == NULL) {
23739 				if (ill_need_rele)
23740 					ill_refrele(ill);
23741 				freemsg(ipsec_mp);
23742 				return;
23743 			}
23744 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23745 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23746 			ire_need_rele = B_TRUE;
23747 			ipif_refrele(ipif);
23748 		} else {
23749 			if (ire_arg != NULL) {
23750 				ire = ire_arg;
23751 			} else {
23752 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
23753 				ire_need_rele = B_TRUE;
23754 			}
23755 		}
23756 		if (ire != NULL)
23757 			goto send;
23758 		/*
23759 		 * ire disappeared underneath.
23760 		 *
23761 		 * What we need to do here is the ip_newroute
23762 		 * logic to get the ire without doing the IPSEC
23763 		 * processing. Follow the same old path. But this
23764 		 * time, ip_wput or ire_add_then_send will call us
23765 		 * directly as all the IPSEC operations are done.
23766 		 */
23767 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
23768 		mp->b_prev = NULL;
23769 		mp->b_next = NULL;
23770 
23771 		/*
23772 		 * If the IPsec packet was processed asynchronously,
23773 		 * drop it now.
23774 		 */
23775 		if (q == NULL) {
23776 			if (ill_need_rele)
23777 				ill_refrele(ill);
23778 			freemsg(ipsec_mp);
23779 			return;
23780 		}
23781 
23782 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
23783 		    zoneid);
23784 	}
23785 	if (ill != NULL && ill_need_rele)
23786 		ill_refrele(ill);
23787 	return;
23788 send:
23789 	if (ill != NULL && ill_need_rele)
23790 		ill_refrele(ill);
23791 
23792 	/* Local delivery */
23793 	if (ire->ire_stq == NULL) {
23794 		ASSERT(q != NULL);
23795 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
23796 		    ire, 0);
23797 		if (ire_need_rele)
23798 			ire_refrele(ire);
23799 		return;
23800 	}
23801 	/*
23802 	 * Everything is done. Send it out on the wire.
23803 	 * We force the insertion of a fragment header using the
23804 	 * IPH_FRAG_HDR flag in two cases:
23805 	 * - after reception of an ICMPv6 "packet too big" message
23806 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
23807 	 * - for multirouted IPv6 packets, so that the receiver can
23808 	 *   discard duplicates according to their fragment identifier
23809 	 */
23810 	/* XXX fix flow control problems. */
23811 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
23812 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
23813 		if (hwaccel) {
23814 			/*
23815 			 * hardware acceleration does not handle these
23816 			 * "slow path" cases.
23817 			 */
23818 			/* IPsec KSTATS: should bump bean counter here. */
23819 			if (ire_need_rele)
23820 				ire_refrele(ire);
23821 			freemsg(ipsec_mp);
23822 			return;
23823 		}
23824 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
23825 		    (mp->b_cont ? msgdsize(mp) :
23826 		    mp->b_wptr - (uchar_t *)ip6h)) {
23827 			/* IPsec KSTATS: should bump bean counter here. */
23828 			ip0dbg(("Packet length mismatch: %d, %ld\n",
23829 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
23830 			    msgdsize(mp)));
23831 			if (ire_need_rele)
23832 				ire_refrele(ire);
23833 			freemsg(ipsec_mp);
23834 			return;
23835 		}
23836 		ASSERT(mp->b_prev == NULL);
23837 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
23838 		    ntohs(ip6h->ip6_plen) +
23839 		    IPV6_HDR_LEN, ire->ire_max_frag));
23840 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
23841 		    ire->ire_max_frag);
23842 	} else {
23843 		UPDATE_OB_PKT_COUNT(ire);
23844 		ire->ire_last_used_time = lbolt;
23845 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
23846 	}
23847 	if (ire_need_rele)
23848 		ire_refrele(ire);
23849 	freeb(ipsec_mp);
23850 }
23851 
23852 void
23853 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23854 {
23855 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23856 	da_ipsec_t *hada;	/* data attributes */
23857 	ill_t *ill = (ill_t *)q->q_ptr;
23858 
23859 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23860 
23861 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23862 		/* IPsec KSTATS: Bump lose counter here! */
23863 		freemsg(mp);
23864 		return;
23865 	}
23866 
23867 	/*
23868 	 * It's an IPsec packet that must be
23869 	 * accelerated by the Provider, and the
23870 	 * outbound ill is IPsec acceleration capable.
23871 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23872 	 * to the ill.
23873 	 * IPsec KSTATS: should bump packet counter here.
23874 	 */
23875 
23876 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23877 	if (hada_mp == NULL) {
23878 		/* IPsec KSTATS: should bump packet counter here. */
23879 		freemsg(mp);
23880 		return;
23881 	}
23882 
23883 	hada_mp->b_datap->db_type = M_CTL;
23884 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23885 	hada_mp->b_cont = mp;
23886 
23887 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23888 	bzero(hada, sizeof (da_ipsec_t));
23889 	hada->da_type = IPHADA_M_CTL;
23890 
23891 	putnext(q, hada_mp);
23892 }
23893 
23894 /*
23895  * Finish the outbound IPsec processing. This function is called from
23896  * ipsec_out_process() if the IPsec packet was processed
23897  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23898  * asynchronously.
23899  */
23900 void
23901 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23902     ire_t *ire_arg)
23903 {
23904 	uint32_t v_hlen_tos_len;
23905 	ipaddr_t	dst;
23906 	ipif_t	*ipif = NULL;
23907 	ire_t *ire;
23908 	ire_t *ire1 = NULL;
23909 	mblk_t *next_mp = NULL;
23910 	uint32_t max_frag;
23911 	boolean_t multirt_send = B_FALSE;
23912 	mblk_t *mp;
23913 	mblk_t *mp1;
23914 	uint_t	ill_index;
23915 	ipsec_out_t *io;
23916 	boolean_t attach_if;
23917 	int match_flags, offset;
23918 	irb_t *irb = NULL;
23919 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23920 	zoneid_t zoneid;
23921 	uint32_t cksum;
23922 	uint16_t *up;
23923 #ifdef	_BIG_ENDIAN
23924 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23925 #else
23926 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23927 #endif
23928 
23929 	mp = ipsec_mp->b_cont;
23930 	ASSERT(mp != NULL);
23931 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23932 	dst = ipha->ipha_dst;
23933 
23934 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23935 	ill_index = io->ipsec_out_ill_index;
23936 	attach_if = io->ipsec_out_attach_if;
23937 	zoneid = io->ipsec_out_zoneid;
23938 	ASSERT(zoneid != ALL_ZONES);
23939 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23940 	if (ill_index != 0) {
23941 		if (ill == NULL) {
23942 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23943 			    ill_index, B_FALSE);
23944 
23945 			/* Failure case frees things for us. */
23946 			if (ill == NULL)
23947 				return;
23948 
23949 			ill_need_rele = B_TRUE;
23950 		}
23951 		/*
23952 		 * If this packet needs to go out on a particular interface
23953 		 * honor it.
23954 		 */
23955 		if (attach_if) {
23956 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
23957 
23958 			/*
23959 			 * Check if we need an ire that will not be
23960 			 * looked up by anybody else i.e. HIDDEN.
23961 			 */
23962 			if (ill_is_probeonly(ill)) {
23963 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23964 			}
23965 		}
23966 	}
23967 
23968 	if (CLASSD(dst)) {
23969 		boolean_t conn_dontroute;
23970 		/*
23971 		 * Use the ill_index to get the right ipif.
23972 		 */
23973 		conn_dontroute = io->ipsec_out_dontroute;
23974 		if (ill_index == 0)
23975 			ipif = ipif_lookup_group(dst, zoneid);
23976 		else
23977 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23978 		if (ipif == NULL) {
23979 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23980 			    " multicast\n"));
23981 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23982 			freemsg(ipsec_mp);
23983 			goto done;
23984 		}
23985 		/*
23986 		 * ipha_src has already been intialized with the
23987 		 * value of the ipif in ip_wput. All we need now is
23988 		 * an ire to send this downstream.
23989 		 */
23990 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
23991 		    MBLK_GETLABEL(mp), match_flags);
23992 		if (ire != NULL) {
23993 			ill_t *ill1;
23994 			/*
23995 			 * Do the multicast forwarding now, as the IPSEC
23996 			 * processing has been done.
23997 			 */
23998 			if (ip_g_mrouter && !conn_dontroute &&
23999 			    (ill1 = ire_to_ill(ire))) {
24000 				if (ip_mforward(ill1, ipha, mp)) {
24001 					freemsg(ipsec_mp);
24002 					ip1dbg(("ip_wput_ipsec_out: mforward "
24003 					    "failed\n"));
24004 					ire_refrele(ire);
24005 					goto done;
24006 				}
24007 			}
24008 			goto send;
24009 		}
24010 
24011 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24012 		mp->b_prev = NULL;
24013 		mp->b_next = NULL;
24014 
24015 		/*
24016 		 * If the IPsec packet was processed asynchronously,
24017 		 * drop it now.
24018 		 */
24019 		if (q == NULL) {
24020 			freemsg(ipsec_mp);
24021 			goto done;
24022 		}
24023 
24024 		/*
24025 		 * We may be using a wrong ipif to create the ire.
24026 		 * But it is okay as the source address is assigned
24027 		 * for the packet already. Next outbound packet would
24028 		 * create the IRE with the right IPIF in ip_wput.
24029 		 *
24030 		 * Also handle RTF_MULTIRT routes.
24031 		 */
24032 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24033 	} else {
24034 		if (attach_if) {
24035 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24036 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24037 		} else {
24038 			if (ire_arg != NULL) {
24039 				ire = ire_arg;
24040 				ire_need_rele = B_FALSE;
24041 			} else {
24042 				ire = ire_cache_lookup(dst, zoneid,
24043 				    MBLK_GETLABEL(mp));
24044 			}
24045 		}
24046 		if (ire != NULL) {
24047 			goto send;
24048 		}
24049 
24050 		/*
24051 		 * ire disappeared underneath.
24052 		 *
24053 		 * What we need to do here is the ip_newroute
24054 		 * logic to get the ire without doing the IPSEC
24055 		 * processing. Follow the same old path. But this
24056 		 * time, ip_wput or ire_add_then_put will call us
24057 		 * directly as all the IPSEC operations are done.
24058 		 */
24059 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24060 		mp->b_prev = NULL;
24061 		mp->b_next = NULL;
24062 
24063 		/*
24064 		 * If the IPsec packet was processed asynchronously,
24065 		 * drop it now.
24066 		 */
24067 		if (q == NULL) {
24068 			freemsg(ipsec_mp);
24069 			goto done;
24070 		}
24071 
24072 		/*
24073 		 * Since we're going through ip_newroute() again, we
24074 		 * need to make sure we don't:
24075 		 *
24076 		 *	1.) Trigger the ASSERT() with the ipha_ident
24077 		 *	    overloading.
24078 		 *	2.) Redo transport-layer checksumming, since we've
24079 		 *	    already done all that to get this far.
24080 		 *
24081 		 * The easiest way not do either of the above is to set
24082 		 * the ipha_ident field to IP_HDR_INCLUDED.
24083 		 */
24084 		ipha->ipha_ident = IP_HDR_INCLUDED;
24085 		ip_newroute(q, ipsec_mp, dst, NULL,
24086 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24087 	}
24088 	goto done;
24089 send:
24090 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24091 		/*
24092 		 * ESP NAT-Traversal packet.
24093 		 *
24094 		 * Just do software checksum for now.
24095 		 */
24096 
24097 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24098 		IP_STAT(ip_out_sw_cksum);
24099 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24100 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24101 #define	iphs	((uint16_t *)ipha)
24102 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24103 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24104 		    IP_SIMPLE_HDR_LENGTH);
24105 #undef iphs
24106 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24107 			cksum = 0xFFFF;
24108 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24109 			if (mp1->b_wptr - mp1->b_rptr >=
24110 			    offset + sizeof (uint16_t)) {
24111 				up = (uint16_t *)(mp1->b_rptr + offset);
24112 				*up = cksum;
24113 				break;	/* out of for loop */
24114 			} else {
24115 				offset -= (mp->b_wptr - mp->b_rptr);
24116 			}
24117 	} /* Otherwise, just keep the all-zero checksum. */
24118 
24119 	if (ire->ire_stq == NULL) {
24120 		/*
24121 		 * Loopbacks go through ip_wput_local except for one case.
24122 		 * We come here if we generate a icmp_frag_needed message
24123 		 * after IPSEC processing is over. When this function calls
24124 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24125 		 * icmp_frag_needed. The message generated comes back here
24126 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24127 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24128 		 * source address as it is usually set in ip_wput_ire. As
24129 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24130 		 * and we end up here. We can't enter ip_wput_ire once the
24131 		 * IPSEC processing is over and hence we need to do it here.
24132 		 */
24133 		ASSERT(q != NULL);
24134 		UPDATE_OB_PKT_COUNT(ire);
24135 		ire->ire_last_used_time = lbolt;
24136 		if (ipha->ipha_src == 0)
24137 			ipha->ipha_src = ire->ire_src_addr;
24138 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24139 		    ire, 0, zoneid);
24140 		if (ire_need_rele)
24141 			ire_refrele(ire);
24142 		goto done;
24143 	}
24144 
24145 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24146 		/*
24147 		 * We are through with IPSEC processing.
24148 		 * Fragment this and send it on the wire.
24149 		 */
24150 		if (io->ipsec_out_accelerated) {
24151 			/*
24152 			 * The packet has been accelerated but must
24153 			 * be fragmented. This should not happen
24154 			 * since AH and ESP must not accelerate
24155 			 * packets that need fragmentation, however
24156 			 * the configuration could have changed
24157 			 * since the AH or ESP processing.
24158 			 * Drop packet.
24159 			 * IPsec KSTATS: bump bean counter here.
24160 			 */
24161 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24162 			    "fragmented accelerated packet!\n"));
24163 			freemsg(ipsec_mp);
24164 		} else {
24165 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24166 		}
24167 		if (ire_need_rele)
24168 			ire_refrele(ire);
24169 		goto done;
24170 	}
24171 
24172 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24173 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24174 	    (void *)ire->ire_ipif, (void *)ipif));
24175 
24176 	/*
24177 	 * Multiroute the secured packet, unless IPsec really
24178 	 * requires the packet to go out only through a particular
24179 	 * interface.
24180 	 */
24181 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24182 		ire_t *first_ire;
24183 		irb = ire->ire_bucket;
24184 		ASSERT(irb != NULL);
24185 		/*
24186 		 * This ire has been looked up as the one that
24187 		 * goes through the given ipif;
24188 		 * make sure we do not omit any other multiroute ire
24189 		 * that may be present in the bucket before this one.
24190 		 */
24191 		IRB_REFHOLD(irb);
24192 		for (first_ire = irb->irb_ire;
24193 		    first_ire != NULL;
24194 		    first_ire = first_ire->ire_next) {
24195 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24196 			    (first_ire->ire_addr == ire->ire_addr) &&
24197 			    !(first_ire->ire_marks &
24198 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24199 				break;
24200 		}
24201 
24202 		if ((first_ire != NULL) && (first_ire != ire)) {
24203 			/*
24204 			 * Don't change the ire if the packet must
24205 			 * be fragmented if sent via this new one.
24206 			 */
24207 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24208 				IRE_REFHOLD(first_ire);
24209 				if (ire_need_rele)
24210 					ire_refrele(ire);
24211 				else
24212 					ire_need_rele = B_TRUE;
24213 				ire = first_ire;
24214 			}
24215 		}
24216 		IRB_REFRELE(irb);
24217 
24218 		multirt_send = B_TRUE;
24219 		max_frag = ire->ire_max_frag;
24220 	} else {
24221 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24222 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24223 			    "flag, attach_if %d\n", attach_if));
24224 		}
24225 	}
24226 
24227 	/*
24228 	 * In most cases, the emission loop below is entered only once.
24229 	 * Only in the case where the ire holds the RTF_MULTIRT
24230 	 * flag, we loop to process all RTF_MULTIRT ires in the
24231 	 * bucket, and send the packet through all crossed
24232 	 * RTF_MULTIRT routes.
24233 	 */
24234 	do {
24235 		if (multirt_send) {
24236 			/*
24237 			 * ire1 holds here the next ire to process in the
24238 			 * bucket. If multirouting is expected,
24239 			 * any non-RTF_MULTIRT ire that has the
24240 			 * right destination address is ignored.
24241 			 */
24242 			ASSERT(irb != NULL);
24243 			IRB_REFHOLD(irb);
24244 			for (ire1 = ire->ire_next;
24245 			    ire1 != NULL;
24246 			    ire1 = ire1->ire_next) {
24247 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24248 					continue;
24249 				if (ire1->ire_addr != ire->ire_addr)
24250 					continue;
24251 				if (ire1->ire_marks &
24252 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24253 					continue;
24254 				/* No loopback here */
24255 				if (ire1->ire_stq == NULL)
24256 					continue;
24257 				/*
24258 				 * Ensure we do not exceed the MTU
24259 				 * of the next route.
24260 				 */
24261 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24262 					ip_multirt_bad_mtu(ire1, max_frag);
24263 					continue;
24264 				}
24265 
24266 				IRE_REFHOLD(ire1);
24267 				break;
24268 			}
24269 			IRB_REFRELE(irb);
24270 			if (ire1 != NULL) {
24271 				/*
24272 				 * We are in a multiple send case, need to
24273 				 * make a copy of the packet.
24274 				 */
24275 				next_mp = copymsg(ipsec_mp);
24276 				if (next_mp == NULL) {
24277 					ire_refrele(ire1);
24278 					ire1 = NULL;
24279 				}
24280 			}
24281 		}
24282 
24283 		/* Everything is done. Send it out on the wire */
24284 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
24285 		if (mp1 == NULL) {
24286 			BUMP_MIB(&ip_mib, ipOutDiscards);
24287 			freemsg(ipsec_mp);
24288 			if (ire_need_rele)
24289 				ire_refrele(ire);
24290 			if (ire1 != NULL) {
24291 				ire_refrele(ire1);
24292 				freemsg(next_mp);
24293 			}
24294 			goto done;
24295 		}
24296 		UPDATE_OB_PKT_COUNT(ire);
24297 		ire->ire_last_used_time = lbolt;
24298 		if (!io->ipsec_out_accelerated) {
24299 			putnext(ire->ire_stq, mp1);
24300 		} else {
24301 			/*
24302 			 * Safety Pup says: make sure this is going to
24303 			 * the right interface!
24304 			 */
24305 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
24306 			int ifindex = ill1->ill_phyint->phyint_ifindex;
24307 
24308 			if (ifindex != io->ipsec_out_capab_ill_index) {
24309 				/* IPsec kstats: bump lose counter */
24310 				freemsg(mp1);
24311 			} else {
24312 				ipsec_hw_putnext(ire->ire_stq, mp1);
24313 			}
24314 		}
24315 
24316 		freeb(ipsec_mp);
24317 		if (ire_need_rele)
24318 			ire_refrele(ire);
24319 
24320 		if (ire1 != NULL) {
24321 			ire = ire1;
24322 			ire_need_rele = B_TRUE;
24323 			ASSERT(next_mp);
24324 			ipsec_mp = next_mp;
24325 			mp = ipsec_mp->b_cont;
24326 			ire1 = NULL;
24327 			next_mp = NULL;
24328 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
24329 		} else {
24330 			multirt_send = B_FALSE;
24331 		}
24332 	} while (multirt_send);
24333 done:
24334 	if (ill != NULL && ill_need_rele)
24335 		ill_refrele(ill);
24336 	if (ipif != NULL)
24337 		ipif_refrele(ipif);
24338 }
24339 
24340 /*
24341  * Get the ill corresponding to the specified ire, and compare its
24342  * capabilities with the protocol and algorithms specified by the
24343  * the SA obtained from ipsec_out. If they match, annotate the
24344  * ipsec_out structure to indicate that the packet needs acceleration.
24345  *
24346  *
24347  * A packet is eligible for outbound hardware acceleration if the
24348  * following conditions are satisfied:
24349  *
24350  * 1. the packet will not be fragmented
24351  * 2. the provider supports the algorithm
24352  * 3. there is no pending control message being exchanged
24353  * 4. snoop is not attached
24354  * 5. the destination address is not a broadcast or multicast address.
24355  *
24356  * Rationale:
24357  *	- Hardware drivers do not support fragmentation with
24358  *	  the current interface.
24359  *	- snoop, multicast, and broadcast may result in exposure of
24360  *	  a cleartext datagram.
24361  * We check all five of these conditions here.
24362  *
24363  * XXX would like to nuke "ire_t *" parameter here; problem is that
24364  * IRE is only way to figure out if a v4 address is a broadcast and
24365  * thus ineligible for acceleration...
24366  */
24367 static void
24368 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
24369 {
24370 	ipsec_out_t *io;
24371 	mblk_t *data_mp;
24372 	uint_t plen, overhead;
24373 
24374 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
24375 		return;
24376 
24377 	if (ill == NULL)
24378 		return;
24379 
24380 	/*
24381 	 * Destination address is a broadcast or multicast.  Punt.
24382 	 */
24383 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
24384 	    IRE_LOCAL)))
24385 		return;
24386 
24387 	data_mp = ipsec_mp->b_cont;
24388 
24389 	if (ill->ill_isv6) {
24390 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
24391 
24392 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
24393 			return;
24394 
24395 		plen = ip6h->ip6_plen;
24396 	} else {
24397 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
24398 
24399 		if (CLASSD(ipha->ipha_dst))
24400 			return;
24401 
24402 		plen = ipha->ipha_length;
24403 	}
24404 	/*
24405 	 * Is there a pending DLPI control message being exchanged
24406 	 * between IP/IPsec and the DLS Provider? If there is, it
24407 	 * could be a SADB update, and the state of the DLS Provider
24408 	 * SADB might not be in sync with the SADB maintained by
24409 	 * IPsec. To avoid dropping packets or using the wrong keying
24410 	 * material, we do not accelerate this packet.
24411 	 */
24412 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
24413 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24414 		    "ill_dlpi_pending! don't accelerate packet\n"));
24415 		return;
24416 	}
24417 
24418 	/*
24419 	 * Is the Provider in promiscous mode? If it does, we don't
24420 	 * accelerate the packet since it will bounce back up to the
24421 	 * listeners in the clear.
24422 	 */
24423 	if (ill->ill_promisc_on_phys) {
24424 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24425 		    "ill in promiscous mode, don't accelerate packet\n"));
24426 		return;
24427 	}
24428 
24429 	/*
24430 	 * Will the packet require fragmentation?
24431 	 */
24432 
24433 	/*
24434 	 * IPsec ESP note: this is a pessimistic estimate, but the same
24435 	 * as is used elsewhere.
24436 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
24437 	 *	+ 2-byte trailer
24438 	 */
24439 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
24440 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
24441 
24442 	if ((plen + overhead) > ill->ill_max_mtu)
24443 		return;
24444 
24445 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24446 
24447 	/*
24448 	 * Can the ill accelerate this IPsec protocol and algorithm
24449 	 * specified by the SA?
24450 	 */
24451 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
24452 	    ill->ill_isv6, sa)) {
24453 		return;
24454 	}
24455 
24456 	/*
24457 	 * Tell AH or ESP that the outbound ill is capable of
24458 	 * accelerating this packet.
24459 	 */
24460 	io->ipsec_out_is_capab_ill = B_TRUE;
24461 }
24462 
24463 /*
24464  * Select which AH & ESP SA's to use (if any) for the outbound packet.
24465  *
24466  * If this function returns B_TRUE, the requested SA's have been filled
24467  * into the ipsec_out_*_sa pointers.
24468  *
24469  * If the function returns B_FALSE, the packet has been "consumed", most
24470  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
24471  *
24472  * The SA references created by the protocol-specific "select"
24473  * function will be released when the ipsec_mp is freed, thanks to the
24474  * ipsec_out_free destructor -- see spd.c.
24475  */
24476 static boolean_t
24477 ipsec_out_select_sa(mblk_t *ipsec_mp)
24478 {
24479 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
24480 	ipsec_out_t *io;
24481 	ipsec_policy_t *pp;
24482 	ipsec_action_t *ap;
24483 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24484 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24485 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24486 
24487 	if (!io->ipsec_out_secure) {
24488 		/*
24489 		 * We came here by mistake.
24490 		 * Don't bother with ipsec processing
24491 		 * We should "discourage" this path in the future.
24492 		 */
24493 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24494 		return (B_FALSE);
24495 	}
24496 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24497 	ASSERT((io->ipsec_out_policy != NULL) ||
24498 	    (io->ipsec_out_act != NULL));
24499 
24500 	ASSERT(io->ipsec_out_failed == B_FALSE);
24501 
24502 	/*
24503 	 * IPSEC processing has started.
24504 	 */
24505 	io->ipsec_out_proc_begin = B_TRUE;
24506 	ap = io->ipsec_out_act;
24507 	if (ap == NULL) {
24508 		pp = io->ipsec_out_policy;
24509 		ASSERT(pp != NULL);
24510 		ap = pp->ipsp_act;
24511 		ASSERT(ap != NULL);
24512 	}
24513 
24514 	/*
24515 	 * We have an action.  now, let's select SA's.
24516 	 * (In the future, we can cache this in the conn_t..)
24517 	 */
24518 	if (ap->ipa_want_esp) {
24519 		if (io->ipsec_out_esp_sa == NULL) {
24520 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
24521 			    IPPROTO_ESP);
24522 		}
24523 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
24524 	}
24525 
24526 	if (ap->ipa_want_ah) {
24527 		if (io->ipsec_out_ah_sa == NULL) {
24528 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
24529 			    IPPROTO_AH);
24530 		}
24531 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
24532 		/*
24533 		 * The ESP and AH processing order needs to be preserved
24534 		 * when both protocols are required (ESP should be applied
24535 		 * before AH for an outbound packet). Force an ESP ACQUIRE
24536 		 * when both ESP and AH are required, and an AH ACQUIRE
24537 		 * is needed.
24538 		 */
24539 		if (ap->ipa_want_esp && need_ah_acquire)
24540 			need_esp_acquire = B_TRUE;
24541 	}
24542 
24543 	/*
24544 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
24545 	 * Release SAs that got referenced, but will not be used until we
24546 	 * acquire _all_ of the SAs we need.
24547 	 */
24548 	if (need_ah_acquire || need_esp_acquire) {
24549 		if (io->ipsec_out_ah_sa != NULL) {
24550 			IPSA_REFRELE(io->ipsec_out_ah_sa);
24551 			io->ipsec_out_ah_sa = NULL;
24552 		}
24553 		if (io->ipsec_out_esp_sa != NULL) {
24554 			IPSA_REFRELE(io->ipsec_out_esp_sa);
24555 			io->ipsec_out_esp_sa = NULL;
24556 		}
24557 
24558 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
24559 		return (B_FALSE);
24560 	}
24561 
24562 	return (B_TRUE);
24563 }
24564 
24565 /*
24566  * Process an IPSEC_OUT message and see what you can
24567  * do with it.
24568  * IPQoS Notes:
24569  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
24570  * IPSec.
24571  * XXX would like to nuke ire_t.
24572  * XXX ill_index better be "real"
24573  */
24574 void
24575 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
24576 {
24577 	ipsec_out_t *io;
24578 	ipsec_policy_t *pp;
24579 	ipsec_action_t *ap;
24580 	ipha_t *ipha;
24581 	ip6_t *ip6h;
24582 	mblk_t *mp;
24583 	ill_t *ill;
24584 	zoneid_t zoneid;
24585 	ipsec_status_t ipsec_rc;
24586 	boolean_t ill_need_rele = B_FALSE;
24587 
24588 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24589 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24590 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24591 	mp = ipsec_mp->b_cont;
24592 
24593 	/*
24594 	 * Initiate IPPF processing. We do it here to account for packets
24595 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
24596 	 * We can check for ipsec_out_proc_begin even for such packets, as
24597 	 * they will always be false (asserted below).
24598 	 */
24599 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
24600 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
24601 		    io->ipsec_out_ill_index : ill_index);
24602 		if (mp == NULL) {
24603 			ip2dbg(("ipsec_out_process: packet dropped "\
24604 			    "during IPPF processing\n"));
24605 			freeb(ipsec_mp);
24606 			BUMP_MIB(&ip_mib, ipOutDiscards);
24607 			return;
24608 		}
24609 	}
24610 
24611 	if (!io->ipsec_out_secure) {
24612 		/*
24613 		 * We came here by mistake.
24614 		 * Don't bother with ipsec processing
24615 		 * Should "discourage" this path in the future.
24616 		 */
24617 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24618 		goto done;
24619 	}
24620 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24621 	ASSERT((io->ipsec_out_policy != NULL) ||
24622 	    (io->ipsec_out_act != NULL));
24623 	ASSERT(io->ipsec_out_failed == B_FALSE);
24624 
24625 	if (!ipsec_loaded()) {
24626 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
24627 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24628 			BUMP_MIB(&ip_mib, ipOutDiscards);
24629 		} else {
24630 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
24631 		}
24632 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
24633 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
24634 		return;
24635 	}
24636 
24637 	/*
24638 	 * IPSEC processing has started.
24639 	 */
24640 	io->ipsec_out_proc_begin = B_TRUE;
24641 	ap = io->ipsec_out_act;
24642 	if (ap == NULL) {
24643 		pp = io->ipsec_out_policy;
24644 		ASSERT(pp != NULL);
24645 		ap = pp->ipsp_act;
24646 		ASSERT(ap != NULL);
24647 	}
24648 
24649 	/*
24650 	 * Save the outbound ill index. When the packet comes back
24651 	 * from IPsec, we make sure the ill hasn't changed or disappeared
24652 	 * before sending it the accelerated packet.
24653 	 */
24654 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
24655 		int ifindex;
24656 		ill = ire_to_ill(ire);
24657 		ifindex = ill->ill_phyint->phyint_ifindex;
24658 		io->ipsec_out_capab_ill_index = ifindex;
24659 	}
24660 
24661 	/*
24662 	 * The order of processing is first insert a IP header if needed.
24663 	 * Then insert the ESP header and then the AH header.
24664 	 */
24665 	if ((io->ipsec_out_se_done == B_FALSE) &&
24666 	    (ap->ipa_want_se)) {
24667 		/*
24668 		 * First get the outer IP header before sending
24669 		 * it to ESP.
24670 		 */
24671 		ipha_t *oipha, *iipha;
24672 		mblk_t *outer_mp, *inner_mp;
24673 
24674 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
24675 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
24676 			    "ipsec_out_process: "
24677 			    "Self-Encapsulation failed: Out of memory\n");
24678 			freemsg(ipsec_mp);
24679 			BUMP_MIB(&ip_mib, ipOutDiscards);
24680 			return;
24681 		}
24682 		inner_mp = ipsec_mp->b_cont;
24683 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
24684 		oipha = (ipha_t *)outer_mp->b_rptr;
24685 		iipha = (ipha_t *)inner_mp->b_rptr;
24686 		*oipha = *iipha;
24687 		outer_mp->b_wptr += sizeof (ipha_t);
24688 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
24689 		    sizeof (ipha_t));
24690 		oipha->ipha_protocol = IPPROTO_ENCAP;
24691 		oipha->ipha_version_and_hdr_length =
24692 		    IP_SIMPLE_HDR_VERSION;
24693 		oipha->ipha_hdr_checksum = 0;
24694 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
24695 		outer_mp->b_cont = inner_mp;
24696 		ipsec_mp->b_cont = outer_mp;
24697 
24698 		io->ipsec_out_se_done = B_TRUE;
24699 		io->ipsec_out_encaps = B_TRUE;
24700 	}
24701 
24702 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
24703 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
24704 	    !ipsec_out_select_sa(ipsec_mp))
24705 		return;
24706 
24707 	/*
24708 	 * By now, we know what SA's to use.  Toss over to ESP & AH
24709 	 * to do the heavy lifting.
24710 	 */
24711 	zoneid = io->ipsec_out_zoneid;
24712 	ASSERT(zoneid != ALL_ZONES);
24713 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
24714 		ASSERT(io->ipsec_out_esp_sa != NULL);
24715 		io->ipsec_out_esp_done = B_TRUE;
24716 		/*
24717 		 * Note that since hw accel can only apply one transform,
24718 		 * not two, we skip hw accel for ESP if we also have AH
24719 		 * This is an design limitation of the interface
24720 		 * which should be revisited.
24721 		 */
24722 		ASSERT(ire != NULL);
24723 		if (io->ipsec_out_ah_sa == NULL) {
24724 			ill = (ill_t *)ire->ire_stq->q_ptr;
24725 			ipsec_out_is_accelerated(ipsec_mp,
24726 			    io->ipsec_out_esp_sa, ill, ire);
24727 		}
24728 
24729 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
24730 		switch (ipsec_rc) {
24731 		case IPSEC_STATUS_SUCCESS:
24732 			break;
24733 		case IPSEC_STATUS_FAILED:
24734 			BUMP_MIB(&ip_mib, ipOutDiscards);
24735 			/* FALLTHRU */
24736 		case IPSEC_STATUS_PENDING:
24737 			return;
24738 		}
24739 	}
24740 
24741 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
24742 		ASSERT(io->ipsec_out_ah_sa != NULL);
24743 		io->ipsec_out_ah_done = B_TRUE;
24744 		if (ire == NULL) {
24745 			int idx = io->ipsec_out_capab_ill_index;
24746 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
24747 			    NULL, NULL, NULL, NULL);
24748 			ill_need_rele = B_TRUE;
24749 		} else {
24750 			ill = (ill_t *)ire->ire_stq->q_ptr;
24751 		}
24752 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
24753 		    ire);
24754 
24755 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
24756 		switch (ipsec_rc) {
24757 		case IPSEC_STATUS_SUCCESS:
24758 			break;
24759 		case IPSEC_STATUS_FAILED:
24760 			BUMP_MIB(&ip_mib, ipOutDiscards);
24761 			/* FALLTHRU */
24762 		case IPSEC_STATUS_PENDING:
24763 			if (ill != NULL && ill_need_rele)
24764 				ill_refrele(ill);
24765 			return;
24766 		}
24767 	}
24768 	/*
24769 	 * We are done with IPSEC processing. Send it over
24770 	 * the wire.
24771 	 */
24772 done:
24773 	mp = ipsec_mp->b_cont;
24774 	ipha = (ipha_t *)mp->b_rptr;
24775 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24776 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
24777 	} else {
24778 		ip6h = (ip6_t *)ipha;
24779 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
24780 	}
24781 	if (ill != NULL && ill_need_rele)
24782 		ill_refrele(ill);
24783 }
24784 
24785 /* ARGSUSED */
24786 void
24787 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
24788 {
24789 	opt_restart_t	*or;
24790 	int	err;
24791 	conn_t	*connp;
24792 
24793 	ASSERT(CONN_Q(q));
24794 	connp = Q_TO_CONN(q);
24795 
24796 	ASSERT(first_mp->b_datap->db_type == M_CTL);
24797 	or = (opt_restart_t *)first_mp->b_rptr;
24798 	/*
24799 	 * We don't need to pass any credentials here since this is just
24800 	 * a restart. The credentials are passed in when svr4_optcom_req
24801 	 * is called the first time (from ip_wput_nondata).
24802 	 */
24803 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
24804 		err = svr4_optcom_req(q, first_mp, NULL,
24805 		    &ip_opt_obj);
24806 	} else {
24807 		ASSERT(or->or_type == T_OPTMGMT_REQ);
24808 		err = tpi_optcom_req(q, first_mp, NULL,
24809 		    &ip_opt_obj);
24810 	}
24811 	if (err != EINPROGRESS) {
24812 		/* operation is done */
24813 		CONN_OPER_PENDING_DONE(connp);
24814 	}
24815 }
24816 
24817 /*
24818  * ioctls that go through a down/up sequence may need to wait for the down
24819  * to complete. This involves waiting for the ire and ipif refcnts to go down
24820  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
24821  */
24822 /* ARGSUSED */
24823 void
24824 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24825 {
24826 	struct iocblk *iocp;
24827 	mblk_t *mp1;
24828 	ipif_t	*ipif;
24829 	ip_ioctl_cmd_t *ipip;
24830 	int err;
24831 	sin_t	*sin;
24832 	struct lifreq *lifr;
24833 	struct ifreq *ifr;
24834 
24835 	iocp = (struct iocblk *)mp->b_rptr;
24836 	ASSERT(ipsq != NULL);
24837 	/* Existence of mp1 verified in ip_wput_nondata */
24838 	mp1 = mp->b_cont->b_cont;
24839 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24840 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
24841 		ill_t *ill;
24842 		/*
24843 		 * Special case where ipsq_current_ipif may not be set.
24844 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
24845 		 * ill could also have become part of a ipmp group in the
24846 		 * process, we are here as were not able to complete the
24847 		 * operation in ipif_set_values because we could not become
24848 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
24849 		 * will not be set so we need to set it.
24850 		 */
24851 		ill = (ill_t *)q->q_ptr;
24852 		ipsq->ipsq_current_ipif = ill->ill_ipif;
24853 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24854 	}
24855 
24856 	ipif = ipsq->ipsq_current_ipif;
24857 	ASSERT(ipif != NULL);
24858 	if (ipip->ipi_cmd_type == IF_CMD) {
24859 		/* This a old style SIOC[GS]IF* command */
24860 		ifr = (struct ifreq *)mp1->b_rptr;
24861 		sin = (sin_t *)&ifr->ifr_addr;
24862 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24863 		/* This a new style SIOC[GS]LIF* command */
24864 		lifr = (struct lifreq *)mp1->b_rptr;
24865 		sin = (sin_t *)&lifr->lifr_addr;
24866 	} else {
24867 		sin = NULL;
24868 	}
24869 
24870 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24871 	    (void *)mp1->b_rptr);
24872 
24873 	/* SIOCLIFREMOVEIF could have removed the ipif */
24874 	ip_ioctl_finish(q, mp, err,
24875 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24876 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24877 }
24878 
24879 /*
24880  * ioctl processing
24881  *
24882  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24883  * the ioctl command in the ioctl tables and determines the copyin data size
24884  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24885  * size.
24886  *
24887  * ioctl processing then continues when the M_IOCDATA makes its way down.
24888  * Now the ioctl is looked up again in the ioctl table, and its properties are
24889  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24890  * and the general ioctl processing function ip_process_ioctl is called.
24891  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24892  * so goes thru the serialization primitive ipsq_try_enter. Then the
24893  * appropriate function to handle the ioctl is called based on the entry in
24894  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24895  * which also refreleases the 'conn' that was refheld at the start of the
24896  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24897  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24898  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24899  *
24900  * Many exclusive ioctls go thru an internal down up sequence as part of
24901  * the operation. For example an attempt to change the IP address of an
24902  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24903  * does all the cleanup such as deleting all ires that use this address.
24904  * Then we need to wait till all references to the interface go away.
24905  */
24906 void
24907 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24908 {
24909 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24910 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24911 	cmd_info_t ci;
24912 	int err;
24913 	boolean_t entered_ipsq = B_FALSE;
24914 
24915 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24916 
24917 	if (ipip == NULL)
24918 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24919 
24920 	/*
24921 	 * SIOCLIFADDIF needs to go thru a special path since the
24922 	 * ill may not exist yet. This happens in the case of lo0
24923 	 * which is created using this ioctl.
24924 	 */
24925 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24926 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24927 		ip_ioctl_finish(q, mp, err,
24928 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24929 		    NULL, NULL);
24930 		return;
24931 	}
24932 
24933 	ci.ci_ipif = NULL;
24934 	switch (ipip->ipi_cmd_type) {
24935 	case IF_CMD:
24936 	case LIF_CMD:
24937 		/*
24938 		 * ioctls that pass in a [l]ifreq appear here.
24939 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24940 		 * ci.ci_ipif
24941 		 */
24942 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24943 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24944 		if (err != 0) {
24945 			ip_ioctl_finish(q, mp, err,
24946 			    ipip->ipi_flags & IPI_GET_CMD ?
24947 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24948 			return;
24949 		}
24950 		ASSERT(ci.ci_ipif != NULL);
24951 		break;
24952 
24953 	case TUN_CMD:
24954 		/*
24955 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24956 		 * a refheld ipif in ci.ci_ipif
24957 		 */
24958 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24959 		if (err != 0) {
24960 			ip_ioctl_finish(q, mp, err,
24961 			    ipip->ipi_flags & IPI_GET_CMD ?
24962 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24963 			return;
24964 		}
24965 		ASSERT(ci.ci_ipif != NULL);
24966 		break;
24967 
24968 	case MISC_CMD:
24969 		/*
24970 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24971 		 * For eg. SIOCGLIFCONF will appear here.
24972 		 */
24973 		switch (ipip->ipi_cmd) {
24974 		case IF_UNITSEL:
24975 			/* ioctl comes down the ill */
24976 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24977 			ipif_refhold(ci.ci_ipif);
24978 			break;
24979 		case SIOCGMSFILTER:
24980 		case SIOCSMSFILTER:
24981 		case SIOCGIPMSFILTER:
24982 		case SIOCSIPMSFILTER:
24983 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24984 			    ip_process_ioctl);
24985 			if (err != 0) {
24986 				ip_ioctl_finish(q, mp, err,
24987 				    ipip->ipi_flags & IPI_GET_CMD ?
24988 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24989 				return;
24990 			}
24991 			break;
24992 		}
24993 		err = 0;
24994 		ci.ci_sin = NULL;
24995 		ci.ci_sin6 = NULL;
24996 		ci.ci_lifr = NULL;
24997 		break;
24998 	}
24999 
25000 	/*
25001 	 * If ipsq is non-null, we are already being called exclusively
25002 	 */
25003 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25004 	if (!(ipip->ipi_flags & IPI_WR)) {
25005 		/*
25006 		 * A return value of EINPROGRESS means the ioctl is
25007 		 * either queued and waiting for some reason or has
25008 		 * already completed.
25009 		 */
25010 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25011 		    ci.ci_lifr);
25012 		if (ci.ci_ipif != NULL)
25013 			ipif_refrele(ci.ci_ipif);
25014 		ip_ioctl_finish(q, mp, err,
25015 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25016 		    NULL, NULL);
25017 		return;
25018 	}
25019 
25020 	ASSERT(ci.ci_ipif != NULL);
25021 
25022 	if (ipsq == NULL) {
25023 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25024 		    ip_process_ioctl, NEW_OP, B_TRUE);
25025 		entered_ipsq = B_TRUE;
25026 	}
25027 	/*
25028 	 * Release the ipif so that ipif_down and friends that wait for
25029 	 * references to go away are not misled about the current ipif_refcnt
25030 	 * values. We are writer so we can access the ipif even after releasing
25031 	 * the ipif.
25032 	 */
25033 	ipif_refrele(ci.ci_ipif);
25034 	if (ipsq == NULL)
25035 		return;
25036 
25037 	mutex_enter(&ipsq->ipsq_lock);
25038 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25039 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25040 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25041 	mutex_exit(&ipsq->ipsq_lock);
25042 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25043 	/*
25044 	 * For most set ioctls that come here, this serves as a single point
25045 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25046 	 * be any new references to the ipif. This helps functions that go
25047 	 * through this path and end up trying to wait for the refcnts
25048 	 * associated with the ipif to go down to zero. Some exceptions are
25049 	 * Failover, Failback, and Groupname commands that operate on more than
25050 	 * just the ci.ci_ipif. These commands internally determine the
25051 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25052 	 * flags on that set. Another exception is the Removeif command that
25053 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25054 	 * ipif to operate on.
25055 	 */
25056 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25057 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25058 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25059 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25060 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25061 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25062 
25063 	/*
25064 	 * A return value of EINPROGRESS means the ioctl is
25065 	 * either queued and waiting for some reason or has
25066 	 * already completed.
25067 	 */
25068 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25069 	    ci.ci_lifr);
25070 
25071 	/* SIOCLIFREMOVEIF could have removed the ipif */
25072 	ip_ioctl_finish(q, mp, err,
25073 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25074 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25075 
25076 	if (entered_ipsq)
25077 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25078 }
25079 
25080 /*
25081  * Complete the ioctl. Typically ioctls use the mi package and need to
25082  * do mi_copyout/mi_copy_done.
25083  */
25084 void
25085 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25086     ipif_t *ipif, ipsq_t *ipsq)
25087 {
25088 	conn_t	*connp = NULL;
25089 
25090 	if (err == EINPROGRESS)
25091 		return;
25092 
25093 	if (CONN_Q(q)) {
25094 		connp = Q_TO_CONN(q);
25095 		ASSERT(connp->conn_ref >= 2);
25096 	}
25097 
25098 	switch (mode) {
25099 	case COPYOUT:
25100 		if (err == 0)
25101 			mi_copyout(q, mp);
25102 		else
25103 			mi_copy_done(q, mp, err);
25104 		break;
25105 
25106 	case NO_COPYOUT:
25107 		mi_copy_done(q, mp, err);
25108 		break;
25109 
25110 	default:
25111 		/* An ioctl aborted through a conn close would take this path */
25112 		break;
25113 	}
25114 
25115 	/*
25116 	 * The refhold placed at the start of the ioctl is released here.
25117 	 */
25118 	if (connp != NULL)
25119 		CONN_OPER_PENDING_DONE(connp);
25120 
25121 	/*
25122 	 * If the ioctl were an exclusive ioctl it would have set
25123 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25124 	 */
25125 	if (ipif != NULL) {
25126 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25127 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25128 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25129 	}
25130 
25131 	/*
25132 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25133 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25134 	 * entering the ipsq
25135 	 */
25136 	if (ipsq != NULL) {
25137 		mutex_enter(&ipsq->ipsq_lock);
25138 		ipsq->ipsq_current_ipif = NULL;
25139 		mutex_exit(&ipsq->ipsq_lock);
25140 	}
25141 }
25142 
25143 /*
25144  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25145  */
25146 /* ARGSUSED */
25147 void
25148 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25149 {
25150 	conn_t *connp = arg;
25151 	tcp_t	*tcp;
25152 
25153 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25154 	tcp = connp->conn_tcp;
25155 
25156 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25157 		freemsg(mp);
25158 	else
25159 		tcp_rput_other(tcp, mp);
25160 	CONN_OPER_PENDING_DONE(connp);
25161 }
25162 
25163 /* Called from ip_wput for all non data messages */
25164 /* ARGSUSED */
25165 void
25166 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25167 {
25168 	mblk_t		*mp1;
25169 	ire_t		*ire;
25170 	ill_t		*ill;
25171 	struct iocblk	*iocp;
25172 	ip_ioctl_cmd_t	*ipip;
25173 	cred_t		*cr;
25174 	conn_t		*connp = NULL;
25175 	int		cmd, err;
25176 
25177 	if (CONN_Q(q))
25178 		connp = Q_TO_CONN(q);
25179 
25180 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25181 
25182 	/* Check if it is a queue to /dev/sctp. */
25183 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25184 	    connp->conn_rq == NULL) {
25185 		sctp_wput(q, mp);
25186 		return;
25187 	}
25188 
25189 	switch (DB_TYPE(mp)) {
25190 	case M_IOCTL:
25191 		/*
25192 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25193 		 * will arrange to copy in associated control structures.
25194 		 */
25195 		ip_sioctl_copyin_setup(q, mp);
25196 		return;
25197 	case M_IOCDATA:
25198 		/*
25199 		 * Ensure that this is associated with one of our trans-
25200 		 * parent ioctls.  If it's not ours, discard it if we're
25201 		 * running as a driver, or pass it on if we're a module.
25202 		 */
25203 		iocp = (struct iocblk *)mp->b_rptr;
25204 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25205 		if (ipip == NULL) {
25206 			if (q->q_next == NULL) {
25207 				goto nak;
25208 			} else {
25209 				putnext(q, mp);
25210 			}
25211 			return;
25212 		} else if ((q->q_next != NULL) &&
25213 		    !(ipip->ipi_flags & IPI_MODOK)) {
25214 			/*
25215 			 * the ioctl is one we recognise, but is not
25216 			 * consumed by IP as a module, pass M_IOCDATA
25217 			 * for processing downstream, but only for
25218 			 * common Streams ioctls.
25219 			 */
25220 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25221 				putnext(q, mp);
25222 				return;
25223 			} else {
25224 				goto nak;
25225 			}
25226 		}
25227 
25228 		/* IOCTL continuation following copyin or copyout. */
25229 		if (mi_copy_state(q, mp, NULL) == -1) {
25230 			/*
25231 			 * The copy operation failed.  mi_copy_state already
25232 			 * cleaned up, so we're out of here.
25233 			 */
25234 			return;
25235 		}
25236 		/*
25237 		 * If we just completed a copy in, we become writer and
25238 		 * continue processing in ip_sioctl_copyin_done.  If it
25239 		 * was a copy out, we call mi_copyout again.  If there is
25240 		 * nothing more to copy out, it will complete the IOCTL.
25241 		 */
25242 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25243 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25244 				mi_copy_done(q, mp, EPROTO);
25245 				return;
25246 			}
25247 			/*
25248 			 * Check for cases that need more copying.  A return
25249 			 * value of 0 means a second copyin has been started,
25250 			 * so we return; a return value of 1 means no more
25251 			 * copying is needed, so we continue.
25252 			 */
25253 			cmd = iocp->ioc_cmd;
25254 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25255 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25256 			    MI_COPY_COUNT(mp) == 1) {
25257 				if (ip_copyin_msfilter(q, mp) == 0)
25258 					return;
25259 			}
25260 			/*
25261 			 * Refhold the conn, till the ioctl completes. This is
25262 			 * needed in case the ioctl ends up in the pending mp
25263 			 * list. Every mp in the ill_pending_mp list and
25264 			 * the ipsq_pending_mp must have a refhold on the conn
25265 			 * to resume processing. The refhold is released when
25266 			 * the ioctl completes. (normally or abnormally)
25267 			 * In all cases ip_ioctl_finish is called to finish
25268 			 * the ioctl.
25269 			 */
25270 			if (connp != NULL) {
25271 				/* This is not a reentry */
25272 				ASSERT(ipsq == NULL);
25273 				CONN_INC_REF(connp);
25274 			} else {
25275 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25276 					mi_copy_done(q, mp, EINVAL);
25277 					return;
25278 				}
25279 			}
25280 
25281 			ip_process_ioctl(ipsq, q, mp, ipip);
25282 
25283 		} else {
25284 			mi_copyout(q, mp);
25285 		}
25286 		return;
25287 nak:
25288 		iocp->ioc_error = EINVAL;
25289 		mp->b_datap->db_type = M_IOCNAK;
25290 		iocp->ioc_count = 0;
25291 		qreply(q, mp);
25292 		return;
25293 
25294 	case M_IOCNAK:
25295 		/*
25296 		 * The only way we could get here is if a resolver didn't like
25297 		 * an IOCTL we sent it.	 This shouldn't happen.
25298 		 */
25299 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25300 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25301 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25302 		freemsg(mp);
25303 		return;
25304 	case M_IOCACK:
25305 		/* Finish socket ioctls passed through to ARP. */
25306 		ip_sioctl_iocack(q, mp);
25307 		return;
25308 	case M_FLUSH:
25309 		if (*mp->b_rptr & FLUSHW)
25310 			flushq(q, FLUSHALL);
25311 		if (q->q_next) {
25312 			/*
25313 			 * M_FLUSH is sent up to IP by some drivers during
25314 			 * unbind. ip_rput has already replied to it. We are
25315 			 * here for the M_FLUSH that we originated in IP
25316 			 * before sending the unbind request to the driver.
25317 			 * Just free it as we don't queue packets in IP
25318 			 * on the write side of the device instance.
25319 			 */
25320 			freemsg(mp);
25321 			return;
25322 		}
25323 		if (*mp->b_rptr & FLUSHR) {
25324 			*mp->b_rptr &= ~FLUSHW;
25325 			qreply(q, mp);
25326 			return;
25327 		}
25328 		freemsg(mp);
25329 		return;
25330 	case IRE_DB_REQ_TYPE:
25331 		/* An Upper Level Protocol wants a copy of an IRE. */
25332 		ip_ire_req(q, mp);
25333 		return;
25334 	case M_CTL:
25335 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
25336 			break;
25337 
25338 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
25339 		    IP_ULP_OUT_LABELED) {
25340 			out_labeled_t *olp;
25341 
25342 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
25343 				break;
25344 			olp = (out_labeled_t *)mp->b_rptr;
25345 			connp->conn_ulp_labeled = olp->out_qnext == q;
25346 			freemsg(mp);
25347 			return;
25348 		}
25349 
25350 		/* M_CTL messages are used by ARP to tell us things. */
25351 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
25352 			break;
25353 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
25354 		case AR_ENTRY_SQUERY:
25355 			ip_wput_ctl(q, mp);
25356 			return;
25357 		case AR_CLIENT_NOTIFY:
25358 			ip_arp_news(q, mp);
25359 			return;
25360 		case AR_DLPIOP_DONE:
25361 			ASSERT(q->q_next != NULL);
25362 			ill = (ill_t *)q->q_ptr;
25363 			/* qwriter_ip releases the refhold */
25364 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
25365 			ill_refhold(ill);
25366 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
25367 			    CUR_OP, B_FALSE);
25368 			return;
25369 		case AR_ARP_CLOSING:
25370 			/*
25371 			 * ARP (above us) is closing. If no ARP bringup is
25372 			 * currently pending, ack the message so that ARP
25373 			 * can complete its close. Also mark ill_arp_closing
25374 			 * so that new ARP bringups will fail. If any
25375 			 * ARP bringup is currently in progress, we will
25376 			 * ack this when the current ARP bringup completes.
25377 			 */
25378 			ASSERT(q->q_next != NULL);
25379 			ill = (ill_t *)q->q_ptr;
25380 			mutex_enter(&ill->ill_lock);
25381 			ill->ill_arp_closing = 1;
25382 			if (!ill->ill_arp_bringup_pending) {
25383 				mutex_exit(&ill->ill_lock);
25384 				qreply(q, mp);
25385 			} else {
25386 				mutex_exit(&ill->ill_lock);
25387 				freemsg(mp);
25388 			}
25389 			return;
25390 		default:
25391 			break;
25392 		}
25393 		break;
25394 	case M_PROTO:
25395 	case M_PCPROTO:
25396 		/*
25397 		 * The only PROTO messages we expect are ULP binds and
25398 		 * copies of option negotiation acknowledgements.
25399 		 */
25400 		switch (((union T_primitives *)mp->b_rptr)->type) {
25401 		case O_T_BIND_REQ:
25402 		case T_BIND_REQ: {
25403 			/* Request can get queued in bind */
25404 			ASSERT(connp != NULL);
25405 			/*
25406 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
25407 			 * instead of going through this path.  We only get
25408 			 * here in the following cases:
25409 			 *
25410 			 * a. Bind retries, where ipsq is non-NULL.
25411 			 * b. T_BIND_REQ is issued from non TCP/UDP
25412 			 *    transport, e.g. icmp for raw socket,
25413 			 *    in which case ipsq will be NULL.
25414 			 */
25415 			ASSERT(ipsq != NULL ||
25416 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
25417 
25418 			/* Don't increment refcnt if this is a re-entry */
25419 			if (ipsq == NULL)
25420 				CONN_INC_REF(connp);
25421 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
25422 			    connp, NULL) : ip_bind_v4(q, mp, connp);
25423 			if (mp == NULL)
25424 				return;
25425 			if (IPCL_IS_TCP(connp)) {
25426 				/*
25427 				 * In the case of TCP endpoint we
25428 				 * come here only for bind retries
25429 				 */
25430 				ASSERT(ipsq != NULL);
25431 				CONN_INC_REF(connp);
25432 				squeue_fill(connp->conn_sqp, mp,
25433 				    ip_resume_tcp_bind, connp,
25434 				    SQTAG_BIND_RETRY);
25435 				return;
25436 			} else if (IPCL_IS_UDP(connp)) {
25437 				/*
25438 				 * In the case of UDP endpoint we
25439 				 * come here only for bind retries
25440 				 */
25441 				ASSERT(ipsq != NULL);
25442 				udp_resume_bind(connp, mp);
25443 				return;
25444 			}
25445 			qreply(q, mp);
25446 			CONN_OPER_PENDING_DONE(connp);
25447 			return;
25448 		}
25449 		case T_SVR4_OPTMGMT_REQ:
25450 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
25451 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
25452 
25453 			ASSERT(connp != NULL);
25454 			if (!snmpcom_req(q, mp, ip_snmp_set,
25455 			    ip_snmp_get, cr)) {
25456 				/*
25457 				 * Call svr4_optcom_req so that it can
25458 				 * generate the ack. We don't come here
25459 				 * if this operation is being restarted.
25460 				 * ip_restart_optmgmt will drop the conn ref.
25461 				 * In the case of ipsec option after the ipsec
25462 				 * load is complete conn_restart_ipsec_waiter
25463 				 * drops the conn ref.
25464 				 */
25465 				ASSERT(ipsq == NULL);
25466 				CONN_INC_REF(connp);
25467 				if (ip_check_for_ipsec_opt(q, mp))
25468 					return;
25469 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
25470 				if (err != EINPROGRESS) {
25471 					/* Operation is done */
25472 					CONN_OPER_PENDING_DONE(connp);
25473 				}
25474 			}
25475 			return;
25476 		case T_OPTMGMT_REQ:
25477 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
25478 			/*
25479 			 * Note: No snmpcom_req support through new
25480 			 * T_OPTMGMT_REQ.
25481 			 * Call tpi_optcom_req so that it can
25482 			 * generate the ack.
25483 			 */
25484 			ASSERT(connp != NULL);
25485 			ASSERT(ipsq == NULL);
25486 			/*
25487 			 * We don't come here for restart. ip_restart_optmgmt
25488 			 * will drop the conn ref. In the case of ipsec option
25489 			 * after the ipsec load is complete
25490 			 * conn_restart_ipsec_waiter drops the conn ref.
25491 			 */
25492 			CONN_INC_REF(connp);
25493 			if (ip_check_for_ipsec_opt(q, mp))
25494 				return;
25495 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
25496 			if (err != EINPROGRESS) {
25497 				/* Operation is done */
25498 				CONN_OPER_PENDING_DONE(connp);
25499 			}
25500 			return;
25501 		case T_UNBIND_REQ:
25502 			mp = ip_unbind(q, mp);
25503 			qreply(q, mp);
25504 			return;
25505 		default:
25506 			/*
25507 			 * Have to drop any DLPI messages coming down from
25508 			 * arp (such as an info_req which would cause ip
25509 			 * to receive an extra info_ack if it was passed
25510 			 * through.
25511 			 */
25512 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
25513 			    (int)*(uint_t *)mp->b_rptr));
25514 			freemsg(mp);
25515 			return;
25516 		}
25517 		/* NOTREACHED */
25518 	case IRE_DB_TYPE: {
25519 		nce_t		*nce;
25520 		ill_t		*ill;
25521 		in6_addr_t	gw_addr_v6;
25522 
25523 
25524 		/*
25525 		 * This is a response back from a resolver.  It
25526 		 * consists of a message chain containing:
25527 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
25528 		 * The IRE_MBLK is the one we allocated in ip_newroute.
25529 		 * The LL_HDR_MBLK is the DLPI header to use to get
25530 		 * the attached packet, and subsequent ones for the
25531 		 * same destination, transmitted.
25532 		 */
25533 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
25534 			break;
25535 		/*
25536 		 * First, check to make sure the resolution succeeded.
25537 		 * If it failed, the second mblk will be empty.
25538 		 * If it is, free the chain, dropping the packet.
25539 		 * (We must ire_delete the ire; that frees the ire mblk)
25540 		 * We're doing this now to support PVCs for ATM; it's
25541 		 * a partial xresolv implementation. When we fully implement
25542 		 * xresolv interfaces, instead of freeing everything here
25543 		 * we'll initiate neighbor discovery.
25544 		 *
25545 		 * For v4 (ARP and other external resolvers) the resolver
25546 		 * frees the message, so no check is needed. This check
25547 		 * is required, though, for a full xresolve implementation.
25548 		 * Including this code here now both shows how external
25549 		 * resolvers can NACK a resolution request using an
25550 		 * existing design that has no specific provisions for NACKs,
25551 		 * and also takes into account that the current non-ARP
25552 		 * external resolver has been coded to use this method of
25553 		 * NACKing for all IPv6 (xresolv) cases,
25554 		 * whether our xresolv implementation is complete or not.
25555 		 *
25556 		 */
25557 		ire = (ire_t *)mp->b_rptr;
25558 		ill = ire_to_ill(ire);
25559 		mp1 = mp->b_cont;		/* dl_unitdata_req */
25560 		if (mp1->b_rptr == mp1->b_wptr) {
25561 			if (ire->ire_ipversion == IPV6_VERSION) {
25562 				/*
25563 				 * XRESOLV interface.
25564 				 */
25565 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
25566 				mutex_enter(&ire->ire_lock);
25567 				gw_addr_v6 = ire->ire_gateway_addr_v6;
25568 				mutex_exit(&ire->ire_lock);
25569 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25570 					nce = ndp_lookup(ill,
25571 					    &ire->ire_addr_v6, B_FALSE);
25572 				} else {
25573 					nce = ndp_lookup(ill, &gw_addr_v6,
25574 					    B_FALSE);
25575 				}
25576 				if (nce != NULL) {
25577 					nce_resolv_failed(nce);
25578 					ndp_delete(nce);
25579 					NCE_REFRELE(nce);
25580 				}
25581 			}
25582 			mp->b_cont = NULL;
25583 			freemsg(mp1);		/* frees the pkt as well */
25584 			ire_delete((ire_t *)mp->b_rptr);
25585 			return;
25586 		}
25587 		/*
25588 		 * Split them into IRE_MBLK and pkt and feed it into
25589 		 * ire_add_then_send. Then in ire_add_then_send
25590 		 * the IRE will be added, and then the packet will be
25591 		 * run back through ip_wput. This time it will make
25592 		 * it to the wire.
25593 		 */
25594 		mp->b_cont = NULL;
25595 		mp = mp1->b_cont;		/* now, mp points to pkt */
25596 		mp1->b_cont = NULL;
25597 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
25598 		if (ire->ire_ipversion == IPV6_VERSION) {
25599 			/*
25600 			 * XRESOLV interface. Find the nce and put a copy
25601 			 * of the dl_unitdata_req in nce_res_mp
25602 			 */
25603 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
25604 			mutex_enter(&ire->ire_lock);
25605 			gw_addr_v6 = ire->ire_gateway_addr_v6;
25606 			mutex_exit(&ire->ire_lock);
25607 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25608 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
25609 				    B_FALSE);
25610 			} else {
25611 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
25612 			}
25613 			if (nce != NULL) {
25614 				/*
25615 				 * We have to protect nce_res_mp here
25616 				 * from being accessed by other threads
25617 				 * while we change the mblk pointer.
25618 				 * Other functions will also lock the nce when
25619 				 * accessing nce_res_mp.
25620 				 *
25621 				 * The reason we change the mblk pointer
25622 				 * here rather than copying the resolved address
25623 				 * into the template is that, unlike with
25624 				 * ethernet, we have no guarantee that the
25625 				 * resolved address length will be
25626 				 * smaller than or equal to the lla length
25627 				 * with which the template was allocated,
25628 				 * (for ethernet, they're equal)
25629 				 * so we have to use the actual resolved
25630 				 * address mblk - which holds the real
25631 				 * dl_unitdata_req with the resolved address.
25632 				 *
25633 				 * Doing this is the same behavior as was
25634 				 * previously used in the v4 ARP case.
25635 				 */
25636 				mutex_enter(&nce->nce_lock);
25637 				if (nce->nce_res_mp != NULL)
25638 					freemsg(nce->nce_res_mp);
25639 				nce->nce_res_mp = mp1;
25640 				mutex_exit(&nce->nce_lock);
25641 				/*
25642 				 * We do a fastpath probe here because
25643 				 * we have resolved the address without
25644 				 * using Neighbor Discovery.
25645 				 * In the non-XRESOLV v6 case, the fastpath
25646 				 * probe is done right after neighbor
25647 				 * discovery completes.
25648 				 */
25649 				if (nce->nce_res_mp != NULL) {
25650 					int res;
25651 					nce_fastpath_list_add(nce);
25652 					res = ill_fastpath_probe(ill,
25653 					    nce->nce_res_mp);
25654 					if (res != 0 && res != EAGAIN)
25655 						nce_fastpath_list_delete(nce);
25656 				}
25657 
25658 				ire_add_then_send(q, ire, mp);
25659 				/*
25660 				 * Now we have to clean out any packets
25661 				 * that may have been queued on the nce
25662 				 * while it was waiting for address resolution
25663 				 * to complete.
25664 				 */
25665 				mutex_enter(&nce->nce_lock);
25666 				mp1 = nce->nce_qd_mp;
25667 				nce->nce_qd_mp = NULL;
25668 				mutex_exit(&nce->nce_lock);
25669 				while (mp1 != NULL) {
25670 					mblk_t *nxt_mp;
25671 					queue_t *fwdq = NULL;
25672 					ill_t   *inbound_ill;
25673 					uint_t ifindex;
25674 
25675 					nxt_mp = mp1->b_next;
25676 					mp1->b_next = NULL;
25677 					/*
25678 					 * Retrieve ifindex stored in
25679 					 * ip_rput_data_v6()
25680 					 */
25681 					ifindex =
25682 					    (uint_t)(uintptr_t)mp1->b_prev;
25683 					inbound_ill =
25684 						ill_lookup_on_ifindex(ifindex,
25685 						    B_TRUE, NULL, NULL, NULL,
25686 						    NULL);
25687 					mp1->b_prev = NULL;
25688 					if (inbound_ill != NULL)
25689 						fwdq = inbound_ill->ill_rq;
25690 
25691 					if (fwdq != NULL) {
25692 						put(fwdq, mp1);
25693 						ill_refrele(inbound_ill);
25694 					} else
25695 						put(WR(ill->ill_rq), mp1);
25696 					mp1 = nxt_mp;
25697 				}
25698 				NCE_REFRELE(nce);
25699 			} else {	/* nce is NULL; clean up */
25700 				ire_delete(ire);
25701 				freemsg(mp);
25702 				freemsg(mp1);
25703 				return;
25704 			}
25705 		} else {
25706 			ire->ire_dlureq_mp = mp1;
25707 			ire_add_then_send(q, ire, mp);
25708 		}
25709 		return;	/* All is well, the packet has been sent. */
25710 	}
25711 	default:
25712 		break;
25713 	}
25714 	if (q->q_next) {
25715 		putnext(q, mp);
25716 	} else
25717 		freemsg(mp);
25718 }
25719 
25720 /*
25721  * Process IP options in an outbound packet.  Modify the destination if there
25722  * is a source route option.
25723  * Returns non-zero if something fails in which case an ICMP error has been
25724  * sent and mp freed.
25725  */
25726 static int
25727 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
25728     boolean_t mctl_present, zoneid_t zoneid)
25729 {
25730 	ipoptp_t	opts;
25731 	uchar_t		*opt;
25732 	uint8_t		optval;
25733 	uint8_t		optlen;
25734 	ipaddr_t	dst;
25735 	intptr_t	code = 0;
25736 	mblk_t		*mp;
25737 	ire_t		*ire = NULL;
25738 
25739 	ip2dbg(("ip_wput_options\n"));
25740 	mp = ipsec_mp;
25741 	if (mctl_present) {
25742 		mp = ipsec_mp->b_cont;
25743 	}
25744 
25745 	dst = ipha->ipha_dst;
25746 	for (optval = ipoptp_first(&opts, ipha);
25747 	    optval != IPOPT_EOL;
25748 	    optval = ipoptp_next(&opts)) {
25749 		opt = opts.ipoptp_cur;
25750 		optlen = opts.ipoptp_len;
25751 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
25752 		    optval, optlen));
25753 		switch (optval) {
25754 			uint32_t off;
25755 		case IPOPT_SSRR:
25756 		case IPOPT_LSRR:
25757 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25758 				ip1dbg((
25759 				    "ip_wput_options: bad option offset\n"));
25760 				code = (char *)&opt[IPOPT_OLEN] -
25761 				    (char *)ipha;
25762 				goto param_prob;
25763 			}
25764 			off = opt[IPOPT_OFFSET];
25765 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
25766 			    ntohl(dst)));
25767 			/*
25768 			 * For strict: verify that dst is directly
25769 			 * reachable.
25770 			 */
25771 			if (optval == IPOPT_SSRR) {
25772 				ire = ire_ftable_lookup(dst, 0, 0,
25773 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25774 				    MBLK_GETLABEL(mp),
25775 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
25776 				if (ire == NULL) {
25777 					ip1dbg(("ip_wput_options: SSRR not"
25778 					    " directly reachable: 0x%x\n",
25779 					    ntohl(dst)));
25780 					goto bad_src_route;
25781 				}
25782 				ire_refrele(ire);
25783 			}
25784 			break;
25785 		case IPOPT_RR:
25786 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25787 				ip1dbg((
25788 				    "ip_wput_options: bad option offset\n"));
25789 				code = (char *)&opt[IPOPT_OLEN] -
25790 				    (char *)ipha;
25791 				goto param_prob;
25792 			}
25793 			break;
25794 		case IPOPT_TS:
25795 			/*
25796 			 * Verify that length >=5 and that there is either
25797 			 * room for another timestamp or that the overflow
25798 			 * counter is not maxed out.
25799 			 */
25800 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
25801 			if (optlen < IPOPT_MINLEN_IT) {
25802 				goto param_prob;
25803 			}
25804 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25805 				ip1dbg((
25806 				    "ip_wput_options: bad option offset\n"));
25807 				code = (char *)&opt[IPOPT_OFFSET] -
25808 				    (char *)ipha;
25809 				goto param_prob;
25810 			}
25811 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25812 			case IPOPT_TS_TSONLY:
25813 				off = IPOPT_TS_TIMELEN;
25814 				break;
25815 			case IPOPT_TS_TSANDADDR:
25816 			case IPOPT_TS_PRESPEC:
25817 			case IPOPT_TS_PRESPEC_RFC791:
25818 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25819 				break;
25820 			default:
25821 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
25822 				    (char *)ipha;
25823 				goto param_prob;
25824 			}
25825 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
25826 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
25827 				/*
25828 				 * No room and the overflow counter is 15
25829 				 * already.
25830 				 */
25831 				goto param_prob;
25832 			}
25833 			break;
25834 		}
25835 	}
25836 
25837 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
25838 		return (0);
25839 
25840 	ip1dbg(("ip_wput_options: error processing IP options."));
25841 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
25842 
25843 param_prob:
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_param_problem(q, ipsec_mp, (uint8_t)code);
25854 	return (-1);
25855 
25856 bad_src_route:
25857 	/*
25858 	 * Since ip_wput() isn't close to finished, we fill
25859 	 * in enough of the header for credible error reporting.
25860 	 */
25861 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25862 		/* Failed */
25863 		freemsg(ipsec_mp);
25864 		return (-1);
25865 	}
25866 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
25867 	return (-1);
25868 }
25869 
25870 /*
25871  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25872  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25873  * thru /etc/system.
25874  */
25875 #define	CONN_MAXDRAINCNT	64
25876 
25877 static void
25878 conn_drain_init(void)
25879 {
25880 	int i;
25881 
25882 	conn_drain_list_cnt = conn_drain_nthreads;
25883 
25884 	if ((conn_drain_list_cnt == 0) ||
25885 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25886 		/*
25887 		 * Default value of the number of drainers is the
25888 		 * number of cpus, subject to maximum of 8 drainers.
25889 		 */
25890 		if (boot_max_ncpus != -1)
25891 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25892 		else
25893 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25894 	}
25895 
25896 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25897 	    KM_SLEEP);
25898 
25899 	for (i = 0; i < conn_drain_list_cnt; i++) {
25900 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25901 		    MUTEX_DEFAULT, NULL);
25902 	}
25903 }
25904 
25905 static void
25906 conn_drain_fini(void)
25907 {
25908 	int i;
25909 
25910 	for (i = 0; i < conn_drain_list_cnt; i++)
25911 		mutex_destroy(&conn_drain_list[i].idl_lock);
25912 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25913 	conn_drain_list = NULL;
25914 }
25915 
25916 /*
25917  * Note: For an overview of how flowcontrol is handled in IP please see the
25918  * IP Flowcontrol notes at the top of this file.
25919  *
25920  * Flow control has blocked us from proceeding. Insert the given conn in one
25921  * of the conn drain lists. These conn wq's will be qenabled later on when
25922  * STREAMS flow control does a backenable. conn_walk_drain will enable
25923  * the first conn in each of these drain lists. Each of these qenabled conns
25924  * in turn enables the next in the list, after it runs, or when it closes,
25925  * thus sustaining the drain process.
25926  *
25927  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25928  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25929  * running at any time, on a given conn, since there can be only 1 service proc
25930  * running on a queue at any time.
25931  */
25932 void
25933 conn_drain_insert(conn_t *connp)
25934 {
25935 	idl_t	*idl;
25936 	uint_t	index;
25937 
25938 	mutex_enter(&connp->conn_lock);
25939 	if (connp->conn_state_flags & CONN_CLOSING) {
25940 		/*
25941 		 * The conn is closing as a result of which CONN_CLOSING
25942 		 * is set. Return.
25943 		 */
25944 		mutex_exit(&connp->conn_lock);
25945 		return;
25946 	} else if (connp->conn_idl == NULL) {
25947 		/*
25948 		 * Assign the next drain list round robin. We dont' use
25949 		 * a lock, and thus it may not be strictly round robin.
25950 		 * Atomicity of load/stores is enough to make sure that
25951 		 * conn_drain_list_index is always within bounds.
25952 		 */
25953 		index = conn_drain_list_index;
25954 		ASSERT(index < conn_drain_list_cnt);
25955 		connp->conn_idl = &conn_drain_list[index];
25956 		index++;
25957 		if (index == conn_drain_list_cnt)
25958 			index = 0;
25959 		conn_drain_list_index = index;
25960 	}
25961 	mutex_exit(&connp->conn_lock);
25962 
25963 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25964 	if ((connp->conn_drain_prev != NULL) ||
25965 	    (connp->conn_state_flags & CONN_CLOSING)) {
25966 		/*
25967 		 * The conn is already in the drain list, OR
25968 		 * the conn is closing. We need to check again for
25969 		 * the closing case again since close can happen
25970 		 * after we drop the conn_lock, and before we
25971 		 * acquire the CONN_DRAIN_LIST_LOCK.
25972 		 */
25973 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25974 		return;
25975 	} else {
25976 		idl = connp->conn_idl;
25977 	}
25978 
25979 	/*
25980 	 * The conn is not in the drain list. Insert it at the
25981 	 * tail of the drain list. The drain list is circular
25982 	 * and doubly linked. idl_conn points to the 1st element
25983 	 * in the list.
25984 	 */
25985 	if (idl->idl_conn == NULL) {
25986 		idl->idl_conn = connp;
25987 		connp->conn_drain_next = connp;
25988 		connp->conn_drain_prev = connp;
25989 	} else {
25990 		conn_t *head = idl->idl_conn;
25991 
25992 		connp->conn_drain_next = head;
25993 		connp->conn_drain_prev = head->conn_drain_prev;
25994 		head->conn_drain_prev->conn_drain_next = connp;
25995 		head->conn_drain_prev = connp;
25996 	}
25997 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25998 }
25999 
26000 /*
26001  * This conn is closing, and we are called from ip_close. OR
26002  * This conn has been serviced by ip_wsrv, and we need to do the tail
26003  * processing.
26004  * If this conn is part of the drain list, we may need to sustain the drain
26005  * process by qenabling the next conn in the drain list. We may also need to
26006  * remove this conn from the list, if it is done.
26007  */
26008 static void
26009 conn_drain_tail(conn_t *connp, boolean_t closing)
26010 {
26011 	idl_t *idl;
26012 
26013 	/*
26014 	 * connp->conn_idl is stable at this point, and no lock is needed
26015 	 * to check it. If we are called from ip_close, close has already
26016 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26017 	 * called us only because conn_idl is non-null. If we are called thru
26018 	 * service, conn_idl could be null, but it cannot change because
26019 	 * service is single-threaded per queue, and there cannot be another
26020 	 * instance of service trying to call conn_drain_insert on this conn
26021 	 * now.
26022 	 */
26023 	ASSERT(!closing || (connp->conn_idl != NULL));
26024 
26025 	/*
26026 	 * If connp->conn_idl is null, the conn has not been inserted into any
26027 	 * drain list even once since creation of the conn. Just return.
26028 	 */
26029 	if (connp->conn_idl == NULL)
26030 		return;
26031 
26032 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26033 
26034 	if (connp->conn_drain_prev == NULL) {
26035 		/* This conn is currently not in the drain list.  */
26036 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26037 		return;
26038 	}
26039 	idl = connp->conn_idl;
26040 	if (idl->idl_conn_draining == connp) {
26041 		/*
26042 		 * This conn is the current drainer. If this is the last conn
26043 		 * in the drain list, we need to do more checks, in the 'if'
26044 		 * below. Otherwwise we need to just qenable the next conn,
26045 		 * to sustain the draining, and is handled in the 'else'
26046 		 * below.
26047 		 */
26048 		if (connp->conn_drain_next == idl->idl_conn) {
26049 			/*
26050 			 * This conn is the last in this list. This round
26051 			 * of draining is complete. If idl_repeat is set,
26052 			 * it means another flow enabling has happened from
26053 			 * the driver/streams and we need to another round
26054 			 * of draining.
26055 			 * If there are more than 2 conns in the drain list,
26056 			 * do a left rotate by 1, so that all conns except the
26057 			 * conn at the head move towards the head by 1, and the
26058 			 * the conn at the head goes to the tail. This attempts
26059 			 * a more even share for all queues that are being
26060 			 * drained.
26061 			 */
26062 			if ((connp->conn_drain_next != connp) &&
26063 			    (idl->idl_conn->conn_drain_next != connp)) {
26064 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26065 			}
26066 			if (idl->idl_repeat) {
26067 				qenable(idl->idl_conn->conn_wq);
26068 				idl->idl_conn_draining = idl->idl_conn;
26069 				idl->idl_repeat = 0;
26070 			} else {
26071 				idl->idl_conn_draining = NULL;
26072 			}
26073 		} else {
26074 			/*
26075 			 * If the next queue that we are now qenable'ing,
26076 			 * is closing, it will remove itself from this list
26077 			 * and qenable the subsequent queue in ip_close().
26078 			 * Serialization is acheived thru idl_lock.
26079 			 */
26080 			qenable(connp->conn_drain_next->conn_wq);
26081 			idl->idl_conn_draining = connp->conn_drain_next;
26082 		}
26083 	}
26084 	if (!connp->conn_did_putbq || closing) {
26085 		/*
26086 		 * Remove ourself from the drain list, if we did not do
26087 		 * a putbq, or if the conn is closing.
26088 		 * Note: It is possible that q->q_first is non-null. It means
26089 		 * that these messages landed after we did a enableok() in
26090 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26091 		 * service them.
26092 		 */
26093 		if (connp->conn_drain_next == connp) {
26094 			/* Singleton in the list */
26095 			ASSERT(connp->conn_drain_prev == connp);
26096 			idl->idl_conn = NULL;
26097 			idl->idl_conn_draining = NULL;
26098 		} else {
26099 			connp->conn_drain_prev->conn_drain_next =
26100 			    connp->conn_drain_next;
26101 			connp->conn_drain_next->conn_drain_prev =
26102 			    connp->conn_drain_prev;
26103 			if (idl->idl_conn == connp)
26104 				idl->idl_conn = connp->conn_drain_next;
26105 			ASSERT(idl->idl_conn_draining != connp);
26106 
26107 		}
26108 		connp->conn_drain_next = NULL;
26109 		connp->conn_drain_prev = NULL;
26110 	}
26111 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26112 }
26113 
26114 /*
26115  * Write service routine. Shared perimeter entry point.
26116  * ip_wsrv can be called in any of the following ways.
26117  * 1. The device queue's messages has fallen below the low water mark
26118  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26119  *    the drain lists and backenable the first conn in each list.
26120  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
26121  *    qenabled non-tcp upper layers. We start dequeing messages and call
26122  *    ip_wput for each message.
26123  */
26124 
26125 void
26126 ip_wsrv(queue_t *q)
26127 {
26128 	conn_t	*connp;
26129 	ill_t	*ill;
26130 	mblk_t	*mp;
26131 
26132 	if (q->q_next) {
26133 		ill = (ill_t *)q->q_ptr;
26134 		if (ill->ill_state_flags == 0) {
26135 			/*
26136 			 * The device flow control has opened up.
26137 			 * Walk through conn drain lists and qenable the
26138 			 * first conn in each list. This makes sense only
26139 			 * if the stream is fully plumbed and setup.
26140 			 * Hence the if check above.
26141 			 */
26142 			ip1dbg(("ip_wsrv: walking\n"));
26143 			conn_walk_drain();
26144 		}
26145 		return;
26146 	}
26147 
26148 	connp = Q_TO_CONN(q);
26149 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
26150 
26151 	/*
26152 	 * 1. Set conn_draining flag to signal that service is active.
26153 	 *
26154 	 * 2. ip_output determines whether it has been called from service,
26155 	 *    based on the last parameter. If it is IP_WSRV it concludes it
26156 	 *    has been called from service.
26157 	 *
26158 	 * 3. Message ordering is preserved by the following logic.
26159 	 *    i. A directly called ip_output (i.e. not thru service) will queue
26160 	 *    the message at the tail, if conn_draining is set (i.e. service
26161 	 *    is running) or if q->q_first is non-null.
26162 	 *
26163 	 *    ii. If ip_output is called from service, and if ip_output cannot
26164 	 *    putnext due to flow control, it does a putbq.
26165 	 *
26166 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
26167 	 *    (causing an infinite loop).
26168 	 */
26169 	ASSERT(!connp->conn_did_putbq);
26170 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
26171 		connp->conn_draining = 1;
26172 		noenable(q);
26173 		while ((mp = getq(q)) != NULL) {
26174 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
26175 			if (connp->conn_did_putbq) {
26176 				/* ip_wput did a putbq */
26177 				break;
26178 			}
26179 		}
26180 		/*
26181 		 * At this point, a thread coming down from top, calling
26182 		 * ip_wput, may end up queueing the message. We have not yet
26183 		 * enabled the queue, so ip_wsrv won't be called again.
26184 		 * To avoid this race, check q->q_first again (in the loop)
26185 		 * If the other thread queued the message before we call
26186 		 * enableok(), we will catch it in the q->q_first check.
26187 		 * If the other thread queues the message after we call
26188 		 * enableok(), ip_wsrv will be called again by STREAMS.
26189 		 */
26190 		connp->conn_draining = 0;
26191 		enableok(q);
26192 	}
26193 
26194 	/* Enable the next conn for draining */
26195 	conn_drain_tail(connp, B_FALSE);
26196 
26197 	connp->conn_did_putbq = 0;
26198 }
26199 
26200 /*
26201  * Walk the list of all conn's calling the function provided with the
26202  * specified argument for each.	 Note that this only walks conn's that
26203  * have been bound.
26204  * Applies to both IPv4 and IPv6.
26205  */
26206 static void
26207 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
26208 {
26209 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
26210 	    func, arg, zoneid);
26211 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
26212 	    func, arg, zoneid);
26213 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
26214 	    func, arg, zoneid);
26215 	conn_walk_fanout_table(ipcl_proto_fanout,
26216 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
26217 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
26218 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
26219 }
26220 
26221 /*
26222  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
26223  * of conns that need to be drained, check if drain is already in progress.
26224  * If so set the idl_repeat bit, indicating that the last conn in the list
26225  * needs to reinitiate the drain once again, for the list. If drain is not
26226  * in progress for the list, initiate the draining, by qenabling the 1st
26227  * conn in the list. The drain is self-sustaining, each qenabled conn will
26228  * in turn qenable the next conn, when it is done/blocked/closing.
26229  */
26230 static void
26231 conn_walk_drain(void)
26232 {
26233 	int i;
26234 	idl_t *idl;
26235 
26236 	IP_STAT(ip_conn_walk_drain);
26237 
26238 	for (i = 0; i < conn_drain_list_cnt; i++) {
26239 		idl = &conn_drain_list[i];
26240 		mutex_enter(&idl->idl_lock);
26241 		if (idl->idl_conn == NULL) {
26242 			mutex_exit(&idl->idl_lock);
26243 			continue;
26244 		}
26245 		/*
26246 		 * If this list is not being drained currently by
26247 		 * an ip_wsrv thread, start the process.
26248 		 */
26249 		if (idl->idl_conn_draining == NULL) {
26250 			ASSERT(idl->idl_repeat == 0);
26251 			qenable(idl->idl_conn->conn_wq);
26252 			idl->idl_conn_draining = idl->idl_conn;
26253 		} else {
26254 			idl->idl_repeat = 1;
26255 		}
26256 		mutex_exit(&idl->idl_lock);
26257 	}
26258 }
26259 
26260 /*
26261  * Walk an conn hash table of `count' buckets, calling func for each entry.
26262  */
26263 static void
26264 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
26265     zoneid_t zoneid)
26266 {
26267 	conn_t	*connp;
26268 
26269 	while (count-- > 0) {
26270 		mutex_enter(&connfp->connf_lock);
26271 		for (connp = connfp->connf_head; connp != NULL;
26272 		    connp = connp->conn_next) {
26273 			if (zoneid == GLOBAL_ZONEID ||
26274 			    zoneid == connp->conn_zoneid) {
26275 				CONN_INC_REF(connp);
26276 				mutex_exit(&connfp->connf_lock);
26277 				(*func)(connp, arg);
26278 				mutex_enter(&connfp->connf_lock);
26279 				CONN_DEC_REF(connp);
26280 			}
26281 		}
26282 		mutex_exit(&connfp->connf_lock);
26283 		connfp++;
26284 	}
26285 }
26286 
26287 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
26288 static void
26289 conn_report1(conn_t *connp, void *mp)
26290 {
26291 	char	buf1[INET6_ADDRSTRLEN];
26292 	char	buf2[INET6_ADDRSTRLEN];
26293 	uint_t	print_len, buf_len;
26294 
26295 	ASSERT(connp != NULL);
26296 
26297 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
26298 	if (buf_len <= 0)
26299 		return;
26300 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
26301 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
26302 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
26303 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
26304 	    "%5d %s/%05d %s/%05d\n",
26305 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
26306 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
26307 	    buf1, connp->conn_lport,
26308 	    buf2, connp->conn_fport);
26309 	if (print_len < buf_len) {
26310 		((mblk_t *)mp)->b_wptr += print_len;
26311 	} else {
26312 		((mblk_t *)mp)->b_wptr += buf_len;
26313 	}
26314 }
26315 
26316 /*
26317  * Named Dispatch routine to produce a formatted report on all conns
26318  * that are listed in one of the fanout tables.
26319  * This report is accessed by using the ndd utility to "get" ND variable
26320  * "ip_conn_status".
26321  */
26322 /* ARGSUSED */
26323 static int
26324 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
26325 {
26326 	(void) mi_mpprintf(mp,
26327 	    "CONN      " MI_COL_HDRPAD_STR
26328 	    "rfq      " MI_COL_HDRPAD_STR
26329 	    "stq      " MI_COL_HDRPAD_STR
26330 	    " zone local                 remote");
26331 
26332 	/*
26333 	 * Because of the ndd constraint, at most we can have 64K buffer
26334 	 * to put in all conn info.  So to be more efficient, just
26335 	 * allocate a 64K buffer here, assuming we need that large buffer.
26336 	 * This should be OK as only privileged processes can do ndd /dev/ip.
26337 	 */
26338 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
26339 		/* The following may work even if we cannot get a large buf. */
26340 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
26341 		return (0);
26342 	}
26343 
26344 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
26345 	return (0);
26346 }
26347 
26348 /*
26349  * Determine if the ill and multicast aspects of that packets
26350  * "matches" the conn.
26351  */
26352 boolean_t
26353 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
26354     zoneid_t zoneid)
26355 {
26356 	ill_t *in_ill;
26357 	boolean_t found;
26358 	ipif_t *ipif;
26359 	ire_t *ire;
26360 	ipaddr_t dst, src;
26361 
26362 	dst = ipha->ipha_dst;
26363 	src = ipha->ipha_src;
26364 
26365 	/*
26366 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
26367 	 * unicast, broadcast and multicast reception to
26368 	 * conn_incoming_ill. conn_wantpacket itself is called
26369 	 * only for BROADCAST and multicast.
26370 	 *
26371 	 * 1) ip_rput supresses duplicate broadcasts if the ill
26372 	 *    is part of a group. Hence, we should be receiving
26373 	 *    just one copy of broadcast for the whole group.
26374 	 *    Thus, if it is part of the group the packet could
26375 	 *    come on any ill of the group and hence we need a
26376 	 *    match on the group. Otherwise, match on ill should
26377 	 *    be sufficient.
26378 	 *
26379 	 * 2) ip_rput does not suppress duplicate multicast packets.
26380 	 *    If there are two interfaces in a ill group and we have
26381 	 *    2 applications (conns) joined a multicast group G on
26382 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
26383 	 *    will give us two packets because we join G on both the
26384 	 *    interfaces rather than nominating just one interface
26385 	 *    for receiving multicast like broadcast above. So,
26386 	 *    we have to call ilg_lookup_ill to filter out duplicate
26387 	 *    copies, if ill is part of a group.
26388 	 */
26389 	in_ill = connp->conn_incoming_ill;
26390 	if (in_ill != NULL) {
26391 		if (in_ill->ill_group == NULL) {
26392 			if (in_ill != ill)
26393 				return (B_FALSE);
26394 		} else if (in_ill->ill_group != ill->ill_group) {
26395 			return (B_FALSE);
26396 		}
26397 	}
26398 
26399 	if (!CLASSD(dst)) {
26400 		if (IPCL_ZONE_MATCH(connp, zoneid))
26401 			return (B_TRUE);
26402 		/*
26403 		 * The conn is in a different zone; we need to check that this
26404 		 * broadcast address is configured in the application's zone and
26405 		 * on one ill in the group.
26406 		 */
26407 		ipif = ipif_get_next_ipif(NULL, ill);
26408 		if (ipif == NULL)
26409 			return (B_FALSE);
26410 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
26411 		    connp->conn_zoneid, NULL,
26412 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
26413 		ipif_refrele(ipif);
26414 		if (ire != NULL) {
26415 			ire_refrele(ire);
26416 			return (B_TRUE);
26417 		} else {
26418 			return (B_FALSE);
26419 		}
26420 	}
26421 
26422 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
26423 	    connp->conn_zoneid == zoneid) {
26424 		/*
26425 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
26426 		 * disabled, therefore we don't dispatch the multicast packet to
26427 		 * the sending zone.
26428 		 */
26429 		return (B_FALSE);
26430 	}
26431 
26432 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
26433 	    connp->conn_zoneid != zoneid) {
26434 		/*
26435 		 * Multicast packet on the loopback interface: we only match
26436 		 * conns who joined the group in the specified zone.
26437 		 */
26438 		return (B_FALSE);
26439 	}
26440 
26441 	if (connp->conn_multi_router) {
26442 		/* multicast packet and multicast router socket: send up */
26443 		return (B_TRUE);
26444 	}
26445 
26446 	mutex_enter(&connp->conn_lock);
26447 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
26448 	mutex_exit(&connp->conn_lock);
26449 	return (found);
26450 }
26451 
26452 /*
26453  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
26454  */
26455 /* ARGSUSED */
26456 static void
26457 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
26458 {
26459 	ill_t *ill = (ill_t *)q->q_ptr;
26460 	mblk_t	*mp1, *mp2;
26461 	ipif_t  *ipif;
26462 	int err = 0;
26463 	conn_t *connp = NULL;
26464 	ipsq_t	*ipsq;
26465 	arc_t	*arc;
26466 
26467 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
26468 
26469 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
26470 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
26471 
26472 	ASSERT(IAM_WRITER_ILL(ill));
26473 	mp2 = mp->b_cont;
26474 	mp->b_cont = NULL;
26475 
26476 	/*
26477 	 * We have now received the arp bringup completion message
26478 	 * from ARP. Mark the arp bringup as done. Also if the arp
26479 	 * stream has already started closing, send up the AR_ARP_CLOSING
26480 	 * ack now since ARP is waiting in close for this ack.
26481 	 */
26482 	mutex_enter(&ill->ill_lock);
26483 	ill->ill_arp_bringup_pending = 0;
26484 	if (ill->ill_arp_closing) {
26485 		mutex_exit(&ill->ill_lock);
26486 		/* Let's reuse the mp for sending the ack */
26487 		arc = (arc_t *)mp->b_rptr;
26488 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
26489 		arc->arc_cmd = AR_ARP_CLOSING;
26490 		qreply(q, mp);
26491 	} else {
26492 		mutex_exit(&ill->ill_lock);
26493 		freeb(mp);
26494 	}
26495 
26496 	/* We should have an IOCTL waiting on this. */
26497 	ipsq = ill->ill_phyint->phyint_ipsq;
26498 	ipif = ipsq->ipsq_pending_ipif;
26499 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
26500 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
26501 	if (mp1 == NULL) {
26502 		/* bringup was aborted by the user */
26503 		freemsg(mp2);
26504 		return;
26505 	}
26506 	ASSERT(connp != NULL);
26507 	q = CONNP_TO_WQ(connp);
26508 	/*
26509 	 * If the DL_BIND_REQ fails, it is noted
26510 	 * in arc_name_offset.
26511 	 */
26512 	err = *((int *)mp2->b_rptr);
26513 	if (err == 0) {
26514 		if (ipif->ipif_isv6) {
26515 			if ((err = ipif_up_done_v6(ipif)) != 0)
26516 				ip0dbg(("ip_arp_done: init failed\n"));
26517 		} else {
26518 			if ((err = ipif_up_done(ipif)) != 0)
26519 				ip0dbg(("ip_arp_done: init failed\n"));
26520 		}
26521 	} else {
26522 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
26523 	}
26524 
26525 	freemsg(mp2);
26526 
26527 	if ((err == 0) && (ill->ill_up_ipifs)) {
26528 		err = ill_up_ipifs(ill, q, mp1);
26529 		if (err == EINPROGRESS)
26530 			return;
26531 	}
26532 
26533 	if (ill->ill_up_ipifs) {
26534 		ill_group_cleanup(ill);
26535 	}
26536 
26537 	/*
26538 	 * The ioctl must complete now without EINPROGRESS
26539 	 * since ipsq_pending_mp_get has removed the ioctl mblk
26540 	 * from ipsq_pending_mp. Otherwise the ioctl will be
26541 	 * stuck for ever in the ipsq.
26542 	 */
26543 	ASSERT(err != EINPROGRESS);
26544 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
26545 }
26546 
26547 /* Allocate the private structure */
26548 static int
26549 ip_priv_alloc(void **bufp)
26550 {
26551 	void	*buf;
26552 
26553 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
26554 		return (ENOMEM);
26555 
26556 	*bufp = buf;
26557 	return (0);
26558 }
26559 
26560 /* Function to delete the private structure */
26561 void
26562 ip_priv_free(void *buf)
26563 {
26564 	ASSERT(buf != NULL);
26565 	kmem_free(buf, sizeof (ip_priv_t));
26566 }
26567 
26568 /*
26569  * The entry point for IPPF processing.
26570  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
26571  * routine just returns.
26572  *
26573  * When called, ip_process generates an ipp_packet_t structure
26574  * which holds the state information for this packet and invokes the
26575  * the classifier (via ipp_packet_process). The classification, depending on
26576  * configured filters, results in a list of actions for this packet. Invoking
26577  * an action may cause the packet to be dropped, in which case the resulting
26578  * mblk (*mpp) is NULL. proc indicates the callout position for
26579  * this packet and ill_index is the interface this packet on or will leave
26580  * on (inbound and outbound resp.).
26581  */
26582 void
26583 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
26584 {
26585 	mblk_t		*mp;
26586 	ip_priv_t	*priv;
26587 	ipp_action_id_t	aid;
26588 	int		rc = 0;
26589 	ipp_packet_t	*pp;
26590 #define	IP_CLASS	"ip"
26591 
26592 	/* If the classifier is not loaded, return  */
26593 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
26594 		return;
26595 	}
26596 
26597 	mp = *mpp;
26598 	ASSERT(mp != NULL);
26599 
26600 	/* Allocate the packet structure */
26601 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
26602 	if (rc != 0) {
26603 		*mpp = NULL;
26604 		freemsg(mp);
26605 		return;
26606 	}
26607 
26608 	/* Allocate the private structure */
26609 	rc = ip_priv_alloc((void **)&priv);
26610 	if (rc != 0) {
26611 		*mpp = NULL;
26612 		freemsg(mp);
26613 		ipp_packet_free(pp);
26614 		return;
26615 	}
26616 	priv->proc = proc;
26617 	priv->ill_index = ill_index;
26618 	ipp_packet_set_private(pp, priv, ip_priv_free);
26619 	ipp_packet_set_data(pp, mp);
26620 
26621 	/* Invoke the classifier */
26622 	rc = ipp_packet_process(&pp);
26623 	if (pp != NULL) {
26624 		mp = ipp_packet_get_data(pp);
26625 		ipp_packet_free(pp);
26626 		if (rc != 0) {
26627 			freemsg(mp);
26628 			*mpp = NULL;
26629 		}
26630 	} else {
26631 		*mpp = NULL;
26632 	}
26633 #undef	IP_CLASS
26634 }
26635 
26636 /*
26637  * Propagate a multicast group membership operation (add/drop) on
26638  * all the interfaces crossed by the related multirt routes.
26639  * The call is considered successful if the operation succeeds
26640  * on at least one interface.
26641  */
26642 static int
26643 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
26644     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
26645     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
26646     mblk_t *first_mp)
26647 {
26648 	ire_t		*ire_gw;
26649 	irb_t		*irb;
26650 	int		error = 0;
26651 	opt_restart_t	*or;
26652 
26653 	irb = ire->ire_bucket;
26654 	ASSERT(irb != NULL);
26655 
26656 	ASSERT(DB_TYPE(first_mp) == M_CTL);
26657 
26658 	or = (opt_restart_t *)first_mp->b_rptr;
26659 	IRB_REFHOLD(irb);
26660 	for (; ire != NULL; ire = ire->ire_next) {
26661 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
26662 			continue;
26663 		if (ire->ire_addr != group)
26664 			continue;
26665 
26666 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
26667 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
26668 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
26669 		/* No resolver exists for the gateway; skip this ire. */
26670 		if (ire_gw == NULL)
26671 			continue;
26672 
26673 		/*
26674 		 * This function can return EINPROGRESS. If so the operation
26675 		 * will be restarted from ip_restart_optmgmt which will
26676 		 * call ip_opt_set and option processing will restart for
26677 		 * this option. So we may end up calling 'fn' more than once.
26678 		 * This requires that 'fn' is idempotent except for the
26679 		 * return value. The operation is considered a success if
26680 		 * it succeeds at least once on any one interface.
26681 		 */
26682 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
26683 		    NULL, fmode, src, first_mp);
26684 		if (error == 0)
26685 			or->or_private = CGTP_MCAST_SUCCESS;
26686 
26687 		if (ip_debug > 0) {
26688 			ulong_t	off;
26689 			char	*ksym;
26690 			ksym = kobj_getsymname((uintptr_t)fn, &off);
26691 			ip2dbg(("ip_multirt_apply_membership: "
26692 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
26693 			    "error %d [success %u]\n",
26694 			    ksym ? ksym : "?",
26695 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
26696 			    error, or->or_private));
26697 		}
26698 
26699 		ire_refrele(ire_gw);
26700 		if (error == EINPROGRESS) {
26701 			IRB_REFRELE(irb);
26702 			return (error);
26703 		}
26704 	}
26705 	IRB_REFRELE(irb);
26706 	/*
26707 	 * Consider the call as successful if we succeeded on at least
26708 	 * one interface. Otherwise, return the last encountered error.
26709 	 */
26710 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
26711 }
26712 
26713 
26714 /*
26715  * Issue a warning regarding a route crossing an interface with an
26716  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
26717  * amount of time is logged.
26718  */
26719 static void
26720 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
26721 {
26722 	hrtime_t	current = gethrtime();
26723 	char		buf[16];
26724 
26725 	/* Convert interval in ms to hrtime in ns */
26726 	if (multirt_bad_mtu_last_time +
26727 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
26728 	    current) {
26729 		cmn_err(CE_WARN, "ip: ignoring multiroute "
26730 		    "to %s, incorrect MTU %u (expected %u)\n",
26731 		    ip_dot_addr(ire->ire_addr, buf),
26732 		    ire->ire_max_frag, max_frag);
26733 
26734 		multirt_bad_mtu_last_time = current;
26735 	}
26736 }
26737 
26738 
26739 /*
26740  * Get the CGTP (multirouting) filtering status.
26741  * If 0, the CGTP hooks are transparent.
26742  */
26743 /* ARGSUSED */
26744 static int
26745 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
26746 {
26747 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26748 
26749 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
26750 	return (0);
26751 }
26752 
26753 
26754 /*
26755  * Set the CGTP (multirouting) filtering status.
26756  * If the status is changed from active to transparent
26757  * or from transparent to active, forward the new status
26758  * to the filtering module (if loaded).
26759  */
26760 /* ARGSUSED */
26761 static int
26762 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
26763     cred_t *ioc_cr)
26764 {
26765 	long		new_value;
26766 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26767 
26768 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
26769 	    new_value < 0 || new_value > 1) {
26770 		return (EINVAL);
26771 	}
26772 
26773 	/*
26774 	 * Do not enable CGTP filtering - thus preventing the hooks
26775 	 * from being invoked - if the version number of the
26776 	 * filtering module hooks does not match.
26777 	 */
26778 	if ((ip_cgtp_filter_ops != NULL) &&
26779 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
26780 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
26781 		    "(module hooks version %d, expecting %d)\n",
26782 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
26783 		return (ENOTSUP);
26784 	}
26785 
26786 	if ((!*ip_cgtp_filter_value) && new_value) {
26787 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
26788 		    ip_cgtp_filter_ops == NULL ?
26789 		    " (module not loaded)" : "");
26790 	}
26791 	if (*ip_cgtp_filter_value && (!new_value)) {
26792 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
26793 		    ip_cgtp_filter_ops == NULL ?
26794 		    " (module not loaded)" : "");
26795 	}
26796 
26797 	if (ip_cgtp_filter_ops != NULL) {
26798 		int	res;
26799 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
26800 			return (res);
26801 		}
26802 	}
26803 
26804 	*ip_cgtp_filter_value = (boolean_t)new_value;
26805 
26806 	return (0);
26807 }
26808 
26809 
26810 /*
26811  * Return the expected CGTP hooks version number.
26812  */
26813 int
26814 ip_cgtp_filter_supported(void)
26815 {
26816 	return (ip_cgtp_filter_rev);
26817 }
26818 
26819 
26820 /*
26821  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
26822  * or by invoking this function. In the first case, the version number
26823  * of the registered structure is checked at hooks activation time
26824  * in ip_cgtp_filter_set().
26825  */
26826 int
26827 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
26828 {
26829 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
26830 		return (ENOTSUP);
26831 
26832 	ip_cgtp_filter_ops = ops;
26833 	return (0);
26834 }
26835 
26836 static squeue_func_t
26837 ip_squeue_switch(int val)
26838 {
26839 	squeue_func_t rval = squeue_fill;
26840 
26841 	switch (val) {
26842 	case IP_SQUEUE_ENTER_NODRAIN:
26843 		rval = squeue_enter_nodrain;
26844 		break;
26845 	case IP_SQUEUE_ENTER:
26846 		rval = squeue_enter;
26847 		break;
26848 	default:
26849 		break;
26850 	}
26851 	return (rval);
26852 }
26853 
26854 /* ARGSUSED */
26855 static int
26856 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
26857     caddr_t addr, cred_t *cr)
26858 {
26859 	int *v = (int *)addr;
26860 	long new_value;
26861 
26862 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26863 		return (EINVAL);
26864 
26865 	ip_input_proc = ip_squeue_switch(new_value);
26866 	*v = new_value;
26867 	return (0);
26868 }
26869 
26870 /* ARGSUSED */
26871 static int
26872 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26873     caddr_t addr, cred_t *cr)
26874 {
26875 	int *v = (int *)addr;
26876 	long new_value;
26877 
26878 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26879 		return (EINVAL);
26880 
26881 	*v = new_value;
26882 	return (0);
26883 }
26884 
26885 static void
26886 ip_kstat_init(void)
26887 {
26888 	ip_named_kstat_t template = {
26889 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26890 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26891 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26892 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26893 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26894 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26895 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26896 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26897 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26898 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26899 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26900 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26901 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26902 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26903 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26904 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26905 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26906 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26907 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26908 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26909 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26910 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26911 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26912 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26913 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26914 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26915 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26916 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26917 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26918 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26919 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26920 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26921 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26922 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26923 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26924 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26925 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26926 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26927 	};
26928 
26929 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26930 					NUM_OF_FIELDS(ip_named_kstat_t),
26931 					0);
26932 	if (!ip_mibkp)
26933 		return;
26934 
26935 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26936 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26937 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26938 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26939 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26940 
26941 	template.netToMediaEntrySize.value.i32 =
26942 		sizeof (mib2_ipNetToMediaEntry_t);
26943 
26944 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26945 
26946 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26947 
26948 	ip_mibkp->ks_update = ip_kstat_update;
26949 
26950 	kstat_install(ip_mibkp);
26951 }
26952 
26953 static void
26954 ip_kstat_fini(void)
26955 {
26956 
26957 	if (ip_mibkp != NULL) {
26958 		kstat_delete(ip_mibkp);
26959 		ip_mibkp = NULL;
26960 	}
26961 }
26962 
26963 static int
26964 ip_kstat_update(kstat_t *kp, int rw)
26965 {
26966 	ip_named_kstat_t *ipkp;
26967 
26968 	if (!kp || !kp->ks_data)
26969 		return (EIO);
26970 
26971 	if (rw == KSTAT_WRITE)
26972 		return (EACCES);
26973 
26974 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26975 
26976 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26977 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26978 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26979 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26980 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26981 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26982 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26983 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26984 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26985 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26986 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26987 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26988 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26989 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26990 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26991 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26992 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26993 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26994 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26995 
26996 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26997 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26998 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26999 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
27000 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
27001 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
27002 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
27003 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
27004 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
27005 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
27006 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
27007 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
27008 
27009 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
27010 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
27011 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
27012 
27013 	return (0);
27014 }
27015 
27016 static void
27017 icmp_kstat_init(void)
27018 {
27019 	icmp_named_kstat_t template = {
27020 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27021 		{ "inErrors",		KSTAT_DATA_UINT32 },
27022 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27023 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27024 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27025 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27026 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27027 		{ "inEchos",		KSTAT_DATA_UINT32 },
27028 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27029 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27030 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27031 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27032 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27033 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27034 		{ "outErrors",		KSTAT_DATA_UINT32 },
27035 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27036 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27037 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27038 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27039 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27040 		{ "outEchos",		KSTAT_DATA_UINT32 },
27041 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27042 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27043 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27044 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27045 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27046 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27047 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27048 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27049 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27050 		{ "outDrops",		KSTAT_DATA_UINT32 },
27051 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27052 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27053 	};
27054 
27055 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27056 					NUM_OF_FIELDS(icmp_named_kstat_t),
27057 					0);
27058 	if (icmp_mibkp == NULL)
27059 		return;
27060 
27061 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27062 
27063 	icmp_mibkp->ks_update = icmp_kstat_update;
27064 
27065 	kstat_install(icmp_mibkp);
27066 }
27067 
27068 static void
27069 icmp_kstat_fini(void)
27070 {
27071 
27072 	if (icmp_mibkp != NULL) {
27073 		kstat_delete(icmp_mibkp);
27074 		icmp_mibkp = NULL;
27075 	}
27076 }
27077 
27078 static int
27079 icmp_kstat_update(kstat_t *kp, int rw)
27080 {
27081 	icmp_named_kstat_t *icmpkp;
27082 
27083 	if ((kp == NULL) || (kp->ks_data == NULL))
27084 		return (EIO);
27085 
27086 	if (rw == KSTAT_WRITE)
27087 		return (EACCES);
27088 
27089 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27090 
27091 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27092 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27093 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27094 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27095 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27096 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27097 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27098 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27099 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27100 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27101 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27102 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27103 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27104 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27105 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27106 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27107 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27108 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27109 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27110 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27111 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27112 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27113 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27114 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27115 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27116 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27117 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27118 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27119 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27120 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
27121 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
27122 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
27123 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
27124 
27125 	return (0);
27126 }
27127 
27128 /*
27129  * This is the fanout function for raw socket opened for SCTP.  Note
27130  * that it is called after SCTP checks that there is no socket which
27131  * wants a packet.  Then before SCTP handles this out of the blue packet,
27132  * this function is called to see if there is any raw socket for SCTP.
27133  * If there is and it is bound to the correct address, the packet will
27134  * be sent to that socket.  Note that only one raw socket can be bound to
27135  * a port.  This is assured in ipcl_sctp_hash_insert();
27136  */
27137 void
27138 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
27139     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
27140     uint_t ipif_seqid, zoneid_t zoneid)
27141 {
27142 	conn_t		*connp;
27143 	queue_t		*rq;
27144 	mblk_t		*first_mp;
27145 	boolean_t	secure;
27146 	ip6_t		*ip6h;
27147 
27148 	first_mp = mp;
27149 	if (mctl_present) {
27150 		mp = first_mp->b_cont;
27151 		secure = ipsec_in_is_secure(first_mp);
27152 		ASSERT(mp != NULL);
27153 	} else {
27154 		secure = B_FALSE;
27155 	}
27156 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
27157 
27158 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
27159 	if (connp == NULL) {
27160 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
27161 		    mctl_present);
27162 		return;
27163 	}
27164 	rq = connp->conn_rq;
27165 	if (!canputnext(rq)) {
27166 		CONN_DEC_REF(connp);
27167 		BUMP_MIB(&ip_mib, rawipInOverflows);
27168 		freemsg(first_mp);
27169 		return;
27170 	}
27171 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
27172 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
27173 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
27174 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
27175 		if (first_mp == NULL) {
27176 			CONN_DEC_REF(connp);
27177 			return;
27178 		}
27179 	}
27180 	/*
27181 	 * We probably should not send M_CTL message up to
27182 	 * raw socket.
27183 	 */
27184 	if (mctl_present)
27185 		freeb(first_mp);
27186 
27187 	/* Initiate IPPF processing here if needed. */
27188 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
27189 	    (!isv4 && IP6_IN_IPP(flags))) {
27190 		ip_process(IPP_LOCAL_IN, &mp,
27191 		    recv_ill->ill_phyint->phyint_ifindex);
27192 		if (mp == NULL) {
27193 			CONN_DEC_REF(connp);
27194 			return;
27195 		}
27196 	}
27197 
27198 	if (connp->conn_recvif || connp->conn_recvslla ||
27199 	    ((connp->conn_ipv6_recvpktinfo ||
27200 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
27201 	    (flags & IP_FF_IP6INFO))) {
27202 		int in_flags = 0;
27203 
27204 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
27205 			in_flags = IPF_RECVIF;
27206 		}
27207 		if (connp->conn_recvslla) {
27208 			in_flags |= IPF_RECVSLLA;
27209 		}
27210 		if (isv4) {
27211 			mp = ip_add_info(mp, recv_ill, in_flags);
27212 		} else {
27213 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
27214 			if (mp == NULL) {
27215 				CONN_DEC_REF(connp);
27216 				return;
27217 			}
27218 		}
27219 	}
27220 
27221 	BUMP_MIB(&ip_mib, ipInDelivers);
27222 	/*
27223 	 * We are sending the IPSEC_IN message also up. Refer
27224 	 * to comments above this function.
27225 	 */
27226 	putnext(rq, mp);
27227 	CONN_DEC_REF(connp);
27228 }
27229 
27230 /*
27231  * Martian Address Filtering [RFC 1812, Section 5.3.7]
27232  */
27233 static boolean_t
27234 ip_no_forward(ipha_t *ipha, ill_t *ill)
27235 {
27236 	ipaddr_t ip_src, ip_dst;
27237 	ire_t *src_ire = NULL;
27238 
27239 	ip_src = ntohl(ipha->ipha_src);
27240 	ip_dst = ntohl(ipha->ipha_dst);
27241 
27242 	if (ip_dst == INADDR_ANY)
27243 		goto dont_forward;
27244 
27245 	if (IN_CLASSD(ip_src))
27246 		goto dont_forward;
27247 
27248 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
27249 		goto dont_forward;
27250 
27251 	if (IN_BADCLASS(ip_dst))
27252 		goto dont_forward;
27253 
27254 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
27255 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
27256 	if (src_ire != NULL) {
27257 		ire_refrele(src_ire);
27258 		goto dont_forward;
27259 	}
27260 
27261 	return (B_FALSE);
27262 
27263 dont_forward:
27264 	if (ip_debug > 2) {
27265 		printf("ip_no_forward: dropping packet received on %s\n",
27266 		    ill->ill_name);
27267 		pr_addr_dbg("ip_no_forward: from src %s\n",
27268 		    AF_INET, &ipha->ipha_src);
27269 		pr_addr_dbg("ip_no_forward: to dst %s\n",
27270 		    AF_INET, &ipha->ipha_dst);
27271 	}
27272 	BUMP_MIB(&ip_mib, ipForwProhibits);
27273 	return (B_TRUE);
27274 }
27275 
27276 static boolean_t
27277 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
27278 {
27279 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
27280 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
27281 		if (ip_debug > 2) {
27282 			if (ill != NULL) {
27283 				printf("ip_loopback_src_or_dst: "
27284 				    "dropping packet received on %s\n",
27285 				    ill->ill_name);
27286 			} else {
27287 				printf("ip_loopback_src_or_dst: "
27288 				    "dropping packet\n");
27289 			}
27290 
27291 			pr_addr_dbg(
27292 			    "ip_loopback_src_or_dst: from src %s\n",
27293 			    AF_INET, &ipha->ipha_src);
27294 			pr_addr_dbg(
27295 			    "ip_loopback_src_or_dst: to dst %s\n",
27296 			    AF_INET, &ipha->ipha_dst);
27297 		}
27298 
27299 		BUMP_MIB(&ip_mib, ipInAddrErrors);
27300 		return (B_TRUE);
27301 	}
27302 	return (B_FALSE);
27303 }
27304 
27305 /*
27306  * Return B_TRUE if the buffers differ in length or content.
27307  * This is used for comparing extension header buffers.
27308  * Note that an extension header would be declared different
27309  * even if all that changed was the next header value in that header i.e.
27310  * what really changed is the next extension header.
27311  */
27312 boolean_t
27313 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
27314     uint_t blen)
27315 {
27316 	if (!b_valid)
27317 		blen = 0;
27318 
27319 	if (alen != blen)
27320 		return (B_TRUE);
27321 	if (alen == 0)
27322 		return (B_FALSE);	/* Both zero length */
27323 	return (bcmp(abuf, bbuf, alen));
27324 }
27325 
27326 /*
27327  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
27328  * Return B_FALSE if memory allocation fails - don't change any state!
27329  */
27330 boolean_t
27331 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27332     const void *src, uint_t srclen)
27333 {
27334 	void *dst;
27335 
27336 	if (!src_valid)
27337 		srclen = 0;
27338 
27339 	ASSERT(*dstlenp == 0);
27340 	if (src != NULL && srclen != 0) {
27341 		dst = mi_alloc(srclen, BPRI_MED);
27342 		if (dst == NULL)
27343 			return (B_FALSE);
27344 	} else {
27345 		dst = NULL;
27346 	}
27347 	if (*dstp != NULL)
27348 		mi_free(*dstp);
27349 	*dstp = dst;
27350 	*dstlenp = dst == NULL ? 0 : srclen;
27351 	return (B_TRUE);
27352 }
27353 
27354 /*
27355  * Replace what is in *dst, *dstlen with the source.
27356  * Assumes ip_allocbuf has already been called.
27357  */
27358 void
27359 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27360     const void *src, uint_t srclen)
27361 {
27362 	if (!src_valid)
27363 		srclen = 0;
27364 
27365 	ASSERT(*dstlenp == srclen);
27366 	if (src != NULL && srclen != 0)
27367 		bcopy(src, *dstp, srclen);
27368 }
27369 
27370 /*
27371  * Free the storage pointed to by the members of an ip6_pkt_t.
27372  */
27373 void
27374 ip6_pkt_free(ip6_pkt_t *ipp)
27375 {
27376 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
27377 
27378 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
27379 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
27380 		ipp->ipp_hopopts = NULL;
27381 		ipp->ipp_hopoptslen = 0;
27382 	}
27383 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
27384 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
27385 		ipp->ipp_rtdstopts = NULL;
27386 		ipp->ipp_rtdstoptslen = 0;
27387 	}
27388 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
27389 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
27390 		ipp->ipp_dstopts = NULL;
27391 		ipp->ipp_dstoptslen = 0;
27392 	}
27393 	if (ipp->ipp_fields & IPPF_RTHDR) {
27394 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
27395 		ipp->ipp_rthdr = NULL;
27396 		ipp->ipp_rthdrlen = 0;
27397 	}
27398 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
27399 	    IPPF_RTHDR);
27400 }
27401