xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 0b69c2f001a429251e2d38f25aca860396551214)
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 *, int);
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, iph_hdr_length)) {
1988 					freemsg(first_mp);
1989 					return;
1990 				}
1991 				/*
1992 				 * icmp_inbound_too_big() may alter mp.
1993 				 * Resynch ipha and icmph accordingly.
1994 				 */
1995 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1996 				ipha = (ipha_t *)&icmph[1];
1997 			}
1998 			/* FALLTHRU */
1999 		default :
2000 			/*
2001 			 * IPQoS notes: Since we have already done IPQoS
2002 			 * processing we don't want to do it again in
2003 			 * the fanout routines called by
2004 			 * icmp_inbound_error_fanout, hence the last
2005 			 * argument, ip_policy, is B_FALSE.
2006 			 */
2007 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2008 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2009 			    B_FALSE, recv_ill, zoneid);
2010 		}
2011 		return;
2012 	}
2013 	/* Send out an ICMP packet */
2014 	icmph->icmph_checksum = 0;
2015 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2016 	if (icmph->icmph_checksum == 0)
2017 		icmph->icmph_checksum = 0xFFFF;
2018 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2019 		ipif_t	*ipif_chosen;
2020 		/*
2021 		 * Make it look like it was directed to us, so we don't look
2022 		 * like a fool with a broadcast or multicast source address.
2023 		 */
2024 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2025 		/*
2026 		 * Make sure that we haven't grabbed an interface that's DOWN.
2027 		 */
2028 		if (ipif != NULL) {
2029 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2030 			    ipha->ipha_src, zoneid);
2031 			if (ipif_chosen != NULL) {
2032 				ipif_refrele(ipif);
2033 				ipif = ipif_chosen;
2034 			}
2035 		}
2036 		if (ipif == NULL) {
2037 			ip0dbg(("icmp_inbound: "
2038 			    "No source for broadcast/multicast:\n"
2039 			    "\tsrc 0x%x dst 0x%x ill %p "
2040 			    "ipif_lcl_addr 0x%x\n",
2041 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2042 			    (void *)ill,
2043 			    ill->ill_ipif->ipif_lcl_addr));
2044 			freemsg(first_mp);
2045 			return;
2046 		}
2047 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2048 		ipha->ipha_dst = ipif->ipif_src_addr;
2049 		ipif_refrele(ipif);
2050 	}
2051 	/* Reset time to live. */
2052 	ipha->ipha_ttl = ip_def_ttl;
2053 	{
2054 		/* Swap source and destination addresses */
2055 		ipaddr_t tmp;
2056 
2057 		tmp = ipha->ipha_src;
2058 		ipha->ipha_src = ipha->ipha_dst;
2059 		ipha->ipha_dst = tmp;
2060 	}
2061 	ipha->ipha_ident = 0;
2062 	if (!IS_SIMPLE_IPH(ipha))
2063 		icmp_options_update(ipha);
2064 
2065 	/*
2066 	 * ICMP echo replies should go out on the same interface
2067 	 * the request came on as probes used by in.mpathd for detecting
2068 	 * NIC failures are ECHO packets. We turn-off load spreading
2069 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2070 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2071 	 * function. This is in turn handled by ip_wput and ip_newroute
2072 	 * to make sure that the packet goes out on the interface it came
2073 	 * in on. If we don't turnoff load spreading, the packets might get
2074 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2075 	 * to go out and in.mpathd would wrongly detect a failure or
2076 	 * mis-detect a NIC failure for link failure. As load spreading
2077 	 * can happen only if ill_group is not NULL, we do only for
2078 	 * that case and this does not affect the normal case.
2079 	 *
2080 	 * We turn off load spreading only on echo packets that came from
2081 	 * on-link hosts. If the interface route has been deleted, this will
2082 	 * not be enforced as we can't do much. For off-link hosts, as the
2083 	 * default routes in IPv4 does not typically have an ire_ipif
2084 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2085 	 * Moreover, expecting a default route through this interface may
2086 	 * not be correct. We use ipha_dst because of the swap above.
2087 	 */
2088 	onlink = B_FALSE;
2089 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2090 		/*
2091 		 * First, we need to make sure that it is not one of our
2092 		 * local addresses. If we set onlink when it is one of
2093 		 * our local addresses, we will end up creating IRE_CACHES
2094 		 * for one of our local addresses. Then, we will never
2095 		 * accept packets for them afterwards.
2096 		 */
2097 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2098 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2099 		if (src_ire == NULL) {
2100 			ipif = ipif_get_next_ipif(NULL, ill);
2101 			if (ipif == NULL) {
2102 				BUMP_MIB(&ip_mib, ipInDiscards);
2103 				freemsg(mp);
2104 				return;
2105 			}
2106 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2107 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2108 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2109 			ipif_refrele(ipif);
2110 			if (src_ire != NULL) {
2111 				onlink = B_TRUE;
2112 				ire_refrele(src_ire);
2113 			}
2114 		} else {
2115 			ire_refrele(src_ire);
2116 		}
2117 	}
2118 	if (!mctl_present) {
2119 		/*
2120 		 * This packet should go out the same way as it
2121 		 * came in i.e in clear. To make sure that global
2122 		 * policy will not be applied to this in ip_wput_ire,
2123 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2124 		 */
2125 		ASSERT(first_mp == mp);
2126 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2127 			BUMP_MIB(&ip_mib, ipInDiscards);
2128 			freemsg(mp);
2129 			return;
2130 		}
2131 		ii = (ipsec_in_t *)first_mp->b_rptr;
2132 
2133 		/* This is not a secure packet */
2134 		ii->ipsec_in_secure = B_FALSE;
2135 		if (onlink) {
2136 			ii->ipsec_in_attach_if = B_TRUE;
2137 			ii->ipsec_in_ill_index =
2138 			    ill->ill_phyint->phyint_ifindex;
2139 			ii->ipsec_in_rill_index =
2140 			    recv_ill->ill_phyint->phyint_ifindex;
2141 		}
2142 		first_mp->b_cont = mp;
2143 	} else if (onlink) {
2144 		ii = (ipsec_in_t *)first_mp->b_rptr;
2145 		ii->ipsec_in_attach_if = B_TRUE;
2146 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2147 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2148 	} else {
2149 		ii = (ipsec_in_t *)first_mp->b_rptr;
2150 	}
2151 	ii->ipsec_in_zoneid = zoneid;
2152 	ASSERT(zoneid != ALL_ZONES);
2153 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2154 		BUMP_MIB(&ip_mib, ipInDiscards);
2155 		return;
2156 	}
2157 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2158 	put(WR(q), first_mp);
2159 }
2160 
2161 static ipaddr_t
2162 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2163 {
2164 	conn_t *connp;
2165 	connf_t *connfp;
2166 	ipaddr_t nexthop_addr = INADDR_ANY;
2167 	int hdr_length = IPH_HDR_LENGTH(ipha);
2168 	uint16_t *up;
2169 	uint32_t ports;
2170 
2171 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2172 	switch (ipha->ipha_protocol) {
2173 		case IPPROTO_TCP:
2174 		{
2175 			tcph_t *tcph;
2176 
2177 			/* do a reverse lookup */
2178 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2179 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2180 			    TCPS_LISTEN);
2181 			break;
2182 		}
2183 		case IPPROTO_UDP:
2184 		{
2185 			uint32_t dstport, srcport;
2186 
2187 			((uint16_t *)&ports)[0] = up[1];
2188 			((uint16_t *)&ports)[1] = up[0];
2189 
2190 			/* Extract ports in net byte order */
2191 			dstport = htons(ntohl(ports) & 0xFFFF);
2192 			srcport = htons(ntohl(ports) >> 16);
2193 
2194 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2195 			mutex_enter(&connfp->connf_lock);
2196 			connp = connfp->connf_head;
2197 
2198 			/* do a reverse lookup */
2199 			while ((connp != NULL) &&
2200 			    (!IPCL_UDP_MATCH(connp, dstport,
2201 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2202 			    connp->conn_zoneid != zoneid)) {
2203 				connp = connp->conn_next;
2204 			}
2205 			if (connp != NULL)
2206 				CONN_INC_REF(connp);
2207 			mutex_exit(&connfp->connf_lock);
2208 			break;
2209 		}
2210 		case IPPROTO_SCTP:
2211 		{
2212 			in6_addr_t map_src, map_dst;
2213 
2214 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2215 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2216 			((uint16_t *)&ports)[0] = up[1];
2217 			((uint16_t *)&ports)[1] = up[0];
2218 
2219 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2220 			    0, zoneid)) == NULL) {
2221 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2222 				    zoneid, ports, ipha);
2223 			} else {
2224 				CONN_INC_REF(connp);
2225 				SCTP_REFRELE(CONN2SCTP(connp));
2226 			}
2227 			break;
2228 		}
2229 		default:
2230 		{
2231 			ipha_t ripha;
2232 
2233 			ripha.ipha_src = ipha->ipha_dst;
2234 			ripha.ipha_dst = ipha->ipha_src;
2235 			ripha.ipha_protocol = ipha->ipha_protocol;
2236 
2237 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2238 			mutex_enter(&connfp->connf_lock);
2239 			connp = connfp->connf_head;
2240 			for (connp = connfp->connf_head; connp != NULL;
2241 			    connp = connp->conn_next) {
2242 				if (IPCL_PROTO_MATCH(connp,
2243 				    ipha->ipha_protocol, &ripha, ill,
2244 				    0, zoneid)) {
2245 					CONN_INC_REF(connp);
2246 					break;
2247 				}
2248 			}
2249 			mutex_exit(&connfp->connf_lock);
2250 		}
2251 	}
2252 	if (connp != NULL) {
2253 		if (connp->conn_nexthop_set)
2254 			nexthop_addr = connp->conn_nexthop_v4;
2255 		CONN_DEC_REF(connp);
2256 	}
2257 	return (nexthop_addr);
2258 }
2259 
2260 /* Table from RFC 1191 */
2261 static int icmp_frag_size_table[] =
2262 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2263 
2264 /*
2265  * Process received ICMP Packet too big.
2266  * After updating any IRE it does the fanout to any matching transport streams.
2267  * Assumes the message has been pulled up till the IP header that caused
2268  * the error.
2269  *
2270  * Returns B_FALSE on failure and B_TRUE on success.
2271  */
2272 static boolean_t
2273 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2274     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2275 {
2276 	ire_t	*ire, *first_ire;
2277 	int	mtu;
2278 	int	hdr_length;
2279 	ipaddr_t nexthop_addr;
2280 
2281 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2282 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2283 
2284 	hdr_length = IPH_HDR_LENGTH(ipha);
2285 
2286 	/* Drop if the original packet contained a source route */
2287 	if (ip_source_route_included(ipha)) {
2288 		return (B_FALSE);
2289 	}
2290 	/*
2291 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2292 	 * header.
2293 	 */
2294 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2295 	    mp->b_wptr) {
2296 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2297 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2298 			BUMP_MIB(&ip_mib, ipInDiscards);
2299 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2300 			return (B_FALSE);
2301 		}
2302 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2303 		ipha = (ipha_t *)&icmph[1];
2304 	}
2305 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2306 	if (nexthop_addr != INADDR_ANY) {
2307 		/* nexthop set */
2308 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2309 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2310 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2311 	} else {
2312 		/* nexthop not set */
2313 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2314 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2315 	}
2316 
2317 	if (!first_ire) {
2318 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2319 		    ntohl(ipha->ipha_dst)));
2320 		return (B_FALSE);
2321 	}
2322 	/* Check for MTU discovery advice as described in RFC 1191 */
2323 	mtu = ntohs(icmph->icmph_du_mtu);
2324 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2325 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2326 	    ire = ire->ire_next) {
2327 		/*
2328 		 * Look for the connection to which this ICMP message is
2329 		 * directed. If it has the IP_NEXTHOP option set, then the
2330 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2331 		 * option. Else the search is limited to regular IREs.
2332 		 */
2333 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2334 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2335 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2336 		    (nexthop_addr != INADDR_ANY)))
2337 			continue;
2338 
2339 		mutex_enter(&ire->ire_lock);
2340 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2341 			/* Reduce the IRE max frag value as advised. */
2342 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2343 			    mtu, ire->ire_max_frag));
2344 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2345 		} else {
2346 			uint32_t length;
2347 			int	i;
2348 
2349 			/*
2350 			 * Use the table from RFC 1191 to figure out
2351 			 * the next "plateau" based on the length in
2352 			 * the original IP packet.
2353 			 */
2354 			length = ntohs(ipha->ipha_length);
2355 			if (ire->ire_max_frag <= length &&
2356 			    ire->ire_max_frag >= length - hdr_length) {
2357 				/*
2358 				 * Handle broken BSD 4.2 systems that
2359 				 * return the wrong iph_length in ICMP
2360 				 * errors.
2361 				 */
2362 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2363 				    length, ire->ire_max_frag));
2364 				length -= hdr_length;
2365 			}
2366 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2367 				if (length > icmp_frag_size_table[i])
2368 					break;
2369 			}
2370 			if (i == A_CNT(icmp_frag_size_table)) {
2371 				/* Smaller than 68! */
2372 				ip1dbg(("Too big for packet size %d\n",
2373 				    length));
2374 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2375 				ire->ire_frag_flag = 0;
2376 			} else {
2377 				mtu = icmp_frag_size_table[i];
2378 				ip1dbg(("Calculated mtu %d, packet size %d, "
2379 				    "before %d", mtu, length,
2380 				    ire->ire_max_frag));
2381 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2382 				ip1dbg((", after %d\n", ire->ire_max_frag));
2383 			}
2384 			/* Record the new max frag size for the ULP. */
2385 			icmph->icmph_du_zero = 0;
2386 			icmph->icmph_du_mtu =
2387 			    htons((uint16_t)ire->ire_max_frag);
2388 		}
2389 		mutex_exit(&ire->ire_lock);
2390 	}
2391 	rw_exit(&first_ire->ire_bucket->irb_lock);
2392 	ire_refrele(first_ire);
2393 	return (B_TRUE);
2394 }
2395 
2396 /*
2397  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2398  * calls this function.
2399  */
2400 static mblk_t *
2401 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2402 {
2403 	ipha_t *ipha;
2404 	icmph_t *icmph;
2405 	ipha_t *in_ipha;
2406 	int length;
2407 
2408 	ASSERT(mp->b_datap->db_type == M_DATA);
2409 
2410 	/*
2411 	 * For Self-encapsulated packets, we added an extra IP header
2412 	 * without the options. Inner IP header is the one from which
2413 	 * the outer IP header was formed. Thus, we need to remove the
2414 	 * outer IP header. To do this, we pullup the whole message
2415 	 * and overlay whatever follows the outer IP header over the
2416 	 * outer IP header.
2417 	 */
2418 
2419 	if (!pullupmsg(mp, -1)) {
2420 		BUMP_MIB(&ip_mib, ipInDiscards);
2421 		return (NULL);
2422 	}
2423 
2424 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2425 	ipha = (ipha_t *)&icmph[1];
2426 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2427 
2428 	/*
2429 	 * The length that we want to overlay is following the inner
2430 	 * IP header. Subtracting the IP header + icmp header + outer
2431 	 * IP header's length should give us the length that we want to
2432 	 * overlay.
2433 	 */
2434 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2435 	    hdr_length;
2436 	/*
2437 	 * Overlay whatever follows the inner header over the
2438 	 * outer header.
2439 	 */
2440 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2441 
2442 	/* Set the wptr to account for the outer header */
2443 	mp->b_wptr -= hdr_length;
2444 	return (mp);
2445 }
2446 
2447 /*
2448  * Try to pass the ICMP message upstream in case the ULP cares.
2449  *
2450  * If the packet that caused the ICMP error is secure, we send
2451  * it to AH/ESP to make sure that the attached packet has a
2452  * valid association. ipha in the code below points to the
2453  * IP header of the packet that caused the error.
2454  *
2455  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2456  * in the context of IPSEC. Normally we tell the upper layer
2457  * whenever we send the ire (including ip_bind), the IPSEC header
2458  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2459  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2460  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2461  * same thing. As TCP has the IPSEC options size that needs to be
2462  * adjusted, we just pass the MTU unchanged.
2463  *
2464  * IFN could have been generated locally or by some router.
2465  *
2466  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2467  *	    This happens because IP adjusted its value of MTU on an
2468  *	    earlier IFN message and could not tell the upper layer,
2469  *	    the new adjusted value of MTU e.g. Packet was encrypted
2470  *	    or there was not enough information to fanout to upper
2471  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2472  *	    generates the IFN, where IPSEC processing has *not* been
2473  *	    done.
2474  *
2475  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2476  *	    could have generated this. This happens because ire_max_frag
2477  *	    value in IP was set to a new value, while the IPSEC processing
2478  *	    was being done and after we made the fragmentation check in
2479  *	    ip_wput_ire. Thus on return from IPSEC processing,
2480  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2481  *	    and generates the IFN. As IPSEC processing is over, we fanout
2482  *	    to AH/ESP to remove the header.
2483  *
2484  *	    In both these cases, ipsec_in_loopback will be set indicating
2485  *	    that IFN was generated locally.
2486  *
2487  * ROUTER : IFN could be secure or non-secure.
2488  *
2489  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2490  *	      packet in error has AH/ESP headers to validate the AH/ESP
2491  *	      headers. AH/ESP will verify whether there is a valid SA or
2492  *	      not and send it back. We will fanout again if we have more
2493  *	      data in the packet.
2494  *
2495  *	      If the packet in error does not have AH/ESP, we handle it
2496  *	      like any other case.
2497  *
2498  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2499  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2500  *	      for validation. AH/ESP will verify whether there is a
2501  *	      valid SA or not and send it back. We will fanout again if
2502  *	      we have more data in the packet.
2503  *
2504  *	      If the packet in error does not have AH/ESP, we handle it
2505  *	      like any other case.
2506  */
2507 static void
2508 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2509     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2510     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2511     zoneid_t zoneid)
2512 {
2513 	uint16_t *up;	/* Pointer to ports in ULP header */
2514 	uint32_t ports;	/* reversed ports for fanout */
2515 	ipha_t ripha;	/* With reversed addresses */
2516 	mblk_t *first_mp;
2517 	ipsec_in_t *ii;
2518 	tcph_t	*tcph;
2519 	conn_t	*connp;
2520 
2521 	first_mp = mp;
2522 	if (mctl_present) {
2523 		mp = first_mp->b_cont;
2524 		ASSERT(mp != NULL);
2525 
2526 		ii = (ipsec_in_t *)first_mp->b_rptr;
2527 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2528 	} else {
2529 		ii = NULL;
2530 	}
2531 
2532 	switch (ipha->ipha_protocol) {
2533 	case IPPROTO_UDP:
2534 		/*
2535 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2536 		 * transport header.
2537 		 */
2538 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2539 		    mp->b_wptr) {
2540 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2541 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2542 				BUMP_MIB(&ip_mib, ipInDiscards);
2543 				goto drop_pkt;
2544 			}
2545 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2546 			ipha = (ipha_t *)&icmph[1];
2547 		}
2548 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2549 
2550 		/*
2551 		 * Attempt to find a client stream based on port.
2552 		 * Note that we do a reverse lookup since the header is
2553 		 * in the form we sent it out.
2554 		 * The ripha header is only used for the IP_UDP_MATCH and we
2555 		 * only set the src and dst addresses and protocol.
2556 		 */
2557 		ripha.ipha_src = ipha->ipha_dst;
2558 		ripha.ipha_dst = ipha->ipha_src;
2559 		ripha.ipha_protocol = ipha->ipha_protocol;
2560 		((uint16_t *)&ports)[0] = up[1];
2561 		((uint16_t *)&ports)[1] = up[0];
2562 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2563 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2564 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2565 		    icmph->icmph_type, icmph->icmph_code));
2566 
2567 		/* Have to change db_type after any pullupmsg */
2568 		DB_TYPE(mp) = M_CTL;
2569 
2570 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2571 		    mctl_present, ip_policy, recv_ill, zoneid);
2572 		return;
2573 
2574 	case IPPROTO_TCP:
2575 		/*
2576 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2577 		 * transport header.
2578 		 */
2579 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2580 		    mp->b_wptr) {
2581 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2582 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2583 				BUMP_MIB(&ip_mib, ipInDiscards);
2584 				goto drop_pkt;
2585 			}
2586 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2587 			ipha = (ipha_t *)&icmph[1];
2588 		}
2589 		/*
2590 		 * Find a TCP client stream for this packet.
2591 		 * Note that we do a reverse lookup since the header is
2592 		 * in the form we sent it out.
2593 		 */
2594 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2595 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2596 		if (connp == NULL) {
2597 			BUMP_MIB(&ip_mib, ipInDiscards);
2598 			goto drop_pkt;
2599 		}
2600 
2601 		/* Have to change db_type after any pullupmsg */
2602 		DB_TYPE(mp) = M_CTL;
2603 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2604 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2605 		return;
2606 
2607 	case IPPROTO_SCTP:
2608 		/*
2609 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2610 		 * transport header.
2611 		 */
2612 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2613 		    mp->b_wptr) {
2614 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2615 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2616 				BUMP_MIB(&ip_mib, ipInDiscards);
2617 				goto drop_pkt;
2618 			}
2619 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2620 			ipha = (ipha_t *)&icmph[1];
2621 		}
2622 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2623 		/*
2624 		 * Find a SCTP client stream for this packet.
2625 		 * Note that we do a reverse lookup since the header is
2626 		 * in the form we sent it out.
2627 		 * The ripha header is only used for the matching and we
2628 		 * only set the src and dst addresses, protocol, and version.
2629 		 */
2630 		ripha.ipha_src = ipha->ipha_dst;
2631 		ripha.ipha_dst = ipha->ipha_src;
2632 		ripha.ipha_protocol = ipha->ipha_protocol;
2633 		ripha.ipha_version_and_hdr_length =
2634 		    ipha->ipha_version_and_hdr_length;
2635 		((uint16_t *)&ports)[0] = up[1];
2636 		((uint16_t *)&ports)[1] = up[0];
2637 
2638 		/* Have to change db_type after any pullupmsg */
2639 		DB_TYPE(mp) = M_CTL;
2640 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2641 		    mctl_present, ip_policy, 0, zoneid);
2642 		return;
2643 
2644 	case IPPROTO_ESP:
2645 	case IPPROTO_AH: {
2646 		int ipsec_rc;
2647 
2648 		/*
2649 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2650 		 * We will re-use the IPSEC_IN if it is already present as
2651 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2652 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2653 		 * one and attach it in the front.
2654 		 */
2655 		if (ii != NULL) {
2656 			/*
2657 			 * ip_fanout_proto_again converts the ICMP errors
2658 			 * that come back from AH/ESP to M_DATA so that
2659 			 * if it is non-AH/ESP and we do a pullupmsg in
2660 			 * this function, it would work. Convert it back
2661 			 * to M_CTL before we send up as this is a ICMP
2662 			 * error. This could have been generated locally or
2663 			 * by some router. Validate the inner IPSEC
2664 			 * headers.
2665 			 *
2666 			 * NOTE : ill_index is used by ip_fanout_proto_again
2667 			 * to locate the ill.
2668 			 */
2669 			ASSERT(ill != NULL);
2670 			ii->ipsec_in_ill_index =
2671 			    ill->ill_phyint->phyint_ifindex;
2672 			ii->ipsec_in_rill_index =
2673 			    recv_ill->ill_phyint->phyint_ifindex;
2674 			DB_TYPE(first_mp->b_cont) = M_CTL;
2675 		} else {
2676 			/*
2677 			 * IPSEC_IN is not present. We attach a ipsec_in
2678 			 * message and send up to IPSEC for validating
2679 			 * and removing the IPSEC headers. Clear
2680 			 * ipsec_in_secure so that when we return
2681 			 * from IPSEC, we don't mistakenly think that this
2682 			 * is a secure packet came from the network.
2683 			 *
2684 			 * NOTE : ill_index is used by ip_fanout_proto_again
2685 			 * to locate the ill.
2686 			 */
2687 			ASSERT(first_mp == mp);
2688 			first_mp = ipsec_in_alloc(B_TRUE);
2689 			if (first_mp == NULL) {
2690 				freemsg(mp);
2691 				BUMP_MIB(&ip_mib, ipInDiscards);
2692 				return;
2693 			}
2694 			ii = (ipsec_in_t *)first_mp->b_rptr;
2695 
2696 			/* This is not a secure packet */
2697 			ii->ipsec_in_secure = B_FALSE;
2698 			first_mp->b_cont = mp;
2699 			DB_TYPE(mp) = M_CTL;
2700 			ASSERT(ill != NULL);
2701 			ii->ipsec_in_ill_index =
2702 			    ill->ill_phyint->phyint_ifindex;
2703 			ii->ipsec_in_rill_index =
2704 			    recv_ill->ill_phyint->phyint_ifindex;
2705 		}
2706 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2707 
2708 		if (!ipsec_loaded()) {
2709 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2710 			return;
2711 		}
2712 
2713 		if (ipha->ipha_protocol == IPPROTO_ESP)
2714 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2715 		else
2716 			ipsec_rc = ipsecah_icmp_error(first_mp);
2717 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2718 			return;
2719 
2720 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2721 		return;
2722 	}
2723 	default:
2724 		/*
2725 		 * The ripha header is only used for the lookup and we
2726 		 * only set the src and dst addresses and protocol.
2727 		 */
2728 		ripha.ipha_src = ipha->ipha_dst;
2729 		ripha.ipha_dst = ipha->ipha_src;
2730 		ripha.ipha_protocol = ipha->ipha_protocol;
2731 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2732 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2733 		    ntohl(ipha->ipha_dst),
2734 		    icmph->icmph_type, icmph->icmph_code));
2735 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2736 			ipha_t *in_ipha;
2737 
2738 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2739 			    mp->b_wptr) {
2740 				if (!pullupmsg(mp, (uchar_t *)ipha +
2741 				    hdr_length + sizeof (ipha_t) -
2742 				    mp->b_rptr)) {
2743 
2744 					BUMP_MIB(&ip_mib, ipInDiscards);
2745 					goto drop_pkt;
2746 				}
2747 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2748 				ipha = (ipha_t *)&icmph[1];
2749 			}
2750 			/*
2751 			 * Caller has verified that length has to be
2752 			 * at least the size of IP header.
2753 			 */
2754 			ASSERT(hdr_length >= sizeof (ipha_t));
2755 			/*
2756 			 * Check the sanity of the inner IP header like
2757 			 * we did for the outer header.
2758 			 */
2759 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2760 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2761 				BUMP_MIB(&ip_mib, ipInDiscards);
2762 				goto drop_pkt;
2763 			}
2764 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2765 				BUMP_MIB(&ip_mib, ipInDiscards);
2766 				goto drop_pkt;
2767 			}
2768 			/* Check for Self-encapsulated tunnels */
2769 			if (in_ipha->ipha_src == ipha->ipha_src &&
2770 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2771 
2772 				mp = icmp_inbound_self_encap_error(mp,
2773 				    iph_hdr_length, hdr_length);
2774 				if (mp == NULL)
2775 					goto drop_pkt;
2776 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2777 				ipha = (ipha_t *)&icmph[1];
2778 				hdr_length = IPH_HDR_LENGTH(ipha);
2779 				/*
2780 				 * The packet in error is self-encapsualted.
2781 				 * And we are finding it further encapsulated
2782 				 * which we could not have possibly generated.
2783 				 */
2784 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2785 					BUMP_MIB(&ip_mib, ipInDiscards);
2786 					goto drop_pkt;
2787 				}
2788 				icmp_inbound_error_fanout(q, ill, first_mp,
2789 				    icmph, ipha, iph_hdr_length, hdr_length,
2790 				    mctl_present, ip_policy, recv_ill, zoneid);
2791 				return;
2792 			}
2793 		}
2794 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2795 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2796 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2797 		    ii != NULL &&
2798 		    ii->ipsec_in_loopback &&
2799 		    ii->ipsec_in_secure) {
2800 			/*
2801 			 * For IP tunnels that get a looped-back
2802 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2803 			 * reported new MTU to take into account the IPsec
2804 			 * headers protecting this configured tunnel.
2805 			 *
2806 			 * This allows the tunnel module (tun.c) to blindly
2807 			 * accept the MTU reported in an ICMP "too big"
2808 			 * message.
2809 			 *
2810 			 * Non-looped back ICMP messages will just be
2811 			 * handled by the security protocols (if needed),
2812 			 * and the first subsequent packet will hit this
2813 			 * path.
2814 			 */
2815 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2816 			    ipsec_in_extra_length(first_mp));
2817 		}
2818 		/* Have to change db_type after any pullupmsg */
2819 		DB_TYPE(mp) = M_CTL;
2820 
2821 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2822 		    ip_policy, recv_ill, zoneid);
2823 		return;
2824 	}
2825 	/* NOTREACHED */
2826 drop_pkt:;
2827 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2828 	freemsg(first_mp);
2829 }
2830 
2831 /*
2832  * Common IP options parser.
2833  *
2834  * Setup routine: fill in *optp with options-parsing state, then
2835  * tail-call ipoptp_next to return the first option.
2836  */
2837 uint8_t
2838 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2839 {
2840 	uint32_t totallen; /* total length of all options */
2841 
2842 	totallen = ipha->ipha_version_and_hdr_length -
2843 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2844 	totallen <<= 2;
2845 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2846 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2847 	optp->ipoptp_flags = 0;
2848 	return (ipoptp_next(optp));
2849 }
2850 
2851 /*
2852  * Common IP options parser: extract next option.
2853  */
2854 uint8_t
2855 ipoptp_next(ipoptp_t *optp)
2856 {
2857 	uint8_t *end = optp->ipoptp_end;
2858 	uint8_t *cur = optp->ipoptp_next;
2859 	uint8_t opt, len, pointer;
2860 
2861 	/*
2862 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2863 	 * has been corrupted.
2864 	 */
2865 	ASSERT(cur <= end);
2866 
2867 	if (cur == end)
2868 		return (IPOPT_EOL);
2869 
2870 	opt = cur[IPOPT_OPTVAL];
2871 
2872 	/*
2873 	 * Skip any NOP options.
2874 	 */
2875 	while (opt == IPOPT_NOP) {
2876 		cur++;
2877 		if (cur == end)
2878 			return (IPOPT_EOL);
2879 		opt = cur[IPOPT_OPTVAL];
2880 	}
2881 
2882 	if (opt == IPOPT_EOL)
2883 		return (IPOPT_EOL);
2884 
2885 	/*
2886 	 * Option requiring a length.
2887 	 */
2888 	if ((cur + 1) >= end) {
2889 		optp->ipoptp_flags |= IPOPTP_ERROR;
2890 		return (IPOPT_EOL);
2891 	}
2892 	len = cur[IPOPT_OLEN];
2893 	if (len < 2) {
2894 		optp->ipoptp_flags |= IPOPTP_ERROR;
2895 		return (IPOPT_EOL);
2896 	}
2897 	optp->ipoptp_cur = cur;
2898 	optp->ipoptp_len = len;
2899 	optp->ipoptp_next = cur + len;
2900 	if (cur + len > end) {
2901 		optp->ipoptp_flags |= IPOPTP_ERROR;
2902 		return (IPOPT_EOL);
2903 	}
2904 
2905 	/*
2906 	 * For the options which require a pointer field, make sure
2907 	 * its there, and make sure it points to either something
2908 	 * inside this option, or the end of the option.
2909 	 */
2910 	switch (opt) {
2911 	case IPOPT_RR:
2912 	case IPOPT_TS:
2913 	case IPOPT_LSRR:
2914 	case IPOPT_SSRR:
2915 		if (len <= IPOPT_OFFSET) {
2916 			optp->ipoptp_flags |= IPOPTP_ERROR;
2917 			return (opt);
2918 		}
2919 		pointer = cur[IPOPT_OFFSET];
2920 		if (pointer - 1 > len) {
2921 			optp->ipoptp_flags |= IPOPTP_ERROR;
2922 			return (opt);
2923 		}
2924 		break;
2925 	}
2926 
2927 	/*
2928 	 * Sanity check the pointer field based on the type of the
2929 	 * option.
2930 	 */
2931 	switch (opt) {
2932 	case IPOPT_RR:
2933 	case IPOPT_SSRR:
2934 	case IPOPT_LSRR:
2935 		if (pointer < IPOPT_MINOFF_SR)
2936 			optp->ipoptp_flags |= IPOPTP_ERROR;
2937 		break;
2938 	case IPOPT_TS:
2939 		if (pointer < IPOPT_MINOFF_IT)
2940 			optp->ipoptp_flags |= IPOPTP_ERROR;
2941 		/*
2942 		 * Note that the Internet Timestamp option also
2943 		 * contains two four bit fields (the Overflow field,
2944 		 * and the Flag field), which follow the pointer
2945 		 * field.  We don't need to check that these fields
2946 		 * fall within the length of the option because this
2947 		 * was implicitely done above.  We've checked that the
2948 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2949 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2950 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2951 		 */
2952 		ASSERT(len > IPOPT_POS_OV_FLG);
2953 		break;
2954 	}
2955 
2956 	return (opt);
2957 }
2958 
2959 /*
2960  * Use the outgoing IP header to create an IP_OPTIONS option the way
2961  * it was passed down from the application.
2962  */
2963 int
2964 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2965 {
2966 	ipoptp_t	opts;
2967 	const uchar_t	*opt;
2968 	uint8_t		optval;
2969 	uint8_t		optlen;
2970 	uint32_t	len = 0;
2971 	uchar_t	*buf1 = buf;
2972 
2973 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2974 	len += IP_ADDR_LEN;
2975 	bzero(buf1, IP_ADDR_LEN);
2976 
2977 	/*
2978 	 * OK to cast away const here, as we don't store through the returned
2979 	 * opts.ipoptp_cur pointer.
2980 	 */
2981 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2982 	    optval != IPOPT_EOL;
2983 	    optval = ipoptp_next(&opts)) {
2984 		int	off;
2985 
2986 		opt = opts.ipoptp_cur;
2987 		optlen = opts.ipoptp_len;
2988 		switch (optval) {
2989 		case IPOPT_SSRR:
2990 		case IPOPT_LSRR:
2991 
2992 			/*
2993 			 * Insert ipha_dst as the first entry in the source
2994 			 * route and move down the entries on step.
2995 			 * The last entry gets placed at buf1.
2996 			 */
2997 			buf[IPOPT_OPTVAL] = optval;
2998 			buf[IPOPT_OLEN] = optlen;
2999 			buf[IPOPT_OFFSET] = optlen;
3000 
3001 			off = optlen - IP_ADDR_LEN;
3002 			if (off < 0) {
3003 				/* No entries in source route */
3004 				break;
3005 			}
3006 			/* Last entry in source route */
3007 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3008 			off -= IP_ADDR_LEN;
3009 
3010 			while (off > 0) {
3011 				bcopy(opt + off,
3012 				    buf + off + IP_ADDR_LEN,
3013 				    IP_ADDR_LEN);
3014 				off -= IP_ADDR_LEN;
3015 			}
3016 			/* ipha_dst into first slot */
3017 			bcopy(&ipha->ipha_dst,
3018 			    buf + off + IP_ADDR_LEN,
3019 			    IP_ADDR_LEN);
3020 			buf += optlen;
3021 			len += optlen;
3022 			break;
3023 
3024 		case IPOPT_COMSEC:
3025 		case IPOPT_SECURITY:
3026 			/* if passing up a label is not ok, then remove */
3027 			if (is_system_labeled())
3028 				break;
3029 			/* FALLTHROUGH */
3030 		default:
3031 			bcopy(opt, buf, optlen);
3032 			buf += optlen;
3033 			len += optlen;
3034 			break;
3035 		}
3036 	}
3037 done:
3038 	/* Pad the resulting options */
3039 	while (len & 0x3) {
3040 		*buf++ = IPOPT_EOL;
3041 		len++;
3042 	}
3043 	return (len);
3044 }
3045 
3046 /*
3047  * Update any record route or timestamp options to include this host.
3048  * Reverse any source route option.
3049  * This routine assumes that the options are well formed i.e. that they
3050  * have already been checked.
3051  */
3052 static void
3053 icmp_options_update(ipha_t *ipha)
3054 {
3055 	ipoptp_t	opts;
3056 	uchar_t		*opt;
3057 	uint8_t		optval;
3058 	ipaddr_t	src;		/* Our local address */
3059 	ipaddr_t	dst;
3060 
3061 	ip2dbg(("icmp_options_update\n"));
3062 	src = ipha->ipha_src;
3063 	dst = ipha->ipha_dst;
3064 
3065 	for (optval = ipoptp_first(&opts, ipha);
3066 	    optval != IPOPT_EOL;
3067 	    optval = ipoptp_next(&opts)) {
3068 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3069 		opt = opts.ipoptp_cur;
3070 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3071 		    optval, opts.ipoptp_len));
3072 		switch (optval) {
3073 			int off1, off2;
3074 		case IPOPT_SSRR:
3075 		case IPOPT_LSRR:
3076 			/*
3077 			 * Reverse the source route.  The first entry
3078 			 * should be the next to last one in the current
3079 			 * source route (the last entry is our address).
3080 			 * The last entry should be the final destination.
3081 			 */
3082 			off1 = IPOPT_MINOFF_SR - 1;
3083 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3084 			if (off2 < 0) {
3085 				/* No entries in source route */
3086 				ip1dbg((
3087 				    "icmp_options_update: bad src route\n"));
3088 				break;
3089 			}
3090 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3091 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3092 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3093 			off2 -= IP_ADDR_LEN;
3094 
3095 			while (off1 < off2) {
3096 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3097 				bcopy((char *)opt + off2, (char *)opt + off1,
3098 				    IP_ADDR_LEN);
3099 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3100 				off1 += IP_ADDR_LEN;
3101 				off2 -= IP_ADDR_LEN;
3102 			}
3103 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3104 			break;
3105 		}
3106 	}
3107 }
3108 
3109 /*
3110  * Process received ICMP Redirect messages.
3111  */
3112 /* ARGSUSED */
3113 static void
3114 icmp_redirect(mblk_t *mp)
3115 {
3116 	ipha_t	*ipha;
3117 	int	iph_hdr_length;
3118 	icmph_t	*icmph;
3119 	ipha_t	*ipha_err;
3120 	ire_t	*ire;
3121 	ire_t	*prev_ire;
3122 	ire_t	*save_ire;
3123 	ipaddr_t  src, dst, gateway;
3124 	iulp_t	ulp_info = { 0 };
3125 	int	error;
3126 
3127 	ipha = (ipha_t *)mp->b_rptr;
3128 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3129 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3130 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3131 		BUMP_MIB(&icmp_mib, icmpInErrors);
3132 		freemsg(mp);
3133 		return;
3134 	}
3135 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3136 	ipha_err = (ipha_t *)&icmph[1];
3137 	src = ipha->ipha_src;
3138 	dst = ipha_err->ipha_dst;
3139 	gateway = icmph->icmph_rd_gateway;
3140 	/* Make sure the new gateway is reachable somehow. */
3141 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3142 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3143 	/*
3144 	 * Make sure we had a route for the dest in question and that
3145 	 * that route was pointing to the old gateway (the source of the
3146 	 * redirect packet.)
3147 	 */
3148 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3149 	    NULL, MATCH_IRE_GW);
3150 	/*
3151 	 * Check that
3152 	 *	the redirect was not from ourselves
3153 	 *	the new gateway and the old gateway are directly reachable
3154 	 */
3155 	if (!prev_ire ||
3156 	    !ire ||
3157 	    ire->ire_type == IRE_LOCAL) {
3158 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3159 		freemsg(mp);
3160 		if (ire != NULL)
3161 			ire_refrele(ire);
3162 		if (prev_ire != NULL)
3163 			ire_refrele(prev_ire);
3164 		return;
3165 	}
3166 
3167 	/*
3168 	 * Should we use the old ULP info to create the new gateway?  From
3169 	 * a user's perspective, we should inherit the info so that it
3170 	 * is a "smooth" transition.  If we do not do that, then new
3171 	 * connections going thru the new gateway will have no route metrics,
3172 	 * which is counter-intuitive to user.  From a network point of
3173 	 * view, this may or may not make sense even though the new gateway
3174 	 * is still directly connected to us so the route metrics should not
3175 	 * change much.
3176 	 *
3177 	 * But if the old ire_uinfo is not initialized, we do another
3178 	 * recursive lookup on the dest using the new gateway.  There may
3179 	 * be a route to that.  If so, use it to initialize the redirect
3180 	 * route.
3181 	 */
3182 	if (prev_ire->ire_uinfo.iulp_set) {
3183 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3184 	} else {
3185 		ire_t *tmp_ire;
3186 		ire_t *sire;
3187 
3188 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3189 		    ALL_ZONES, 0, NULL,
3190 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3191 		if (sire != NULL) {
3192 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3193 			/*
3194 			 * If sire != NULL, ire_ftable_lookup() should not
3195 			 * return a NULL value.
3196 			 */
3197 			ASSERT(tmp_ire != NULL);
3198 			ire_refrele(tmp_ire);
3199 			ire_refrele(sire);
3200 		} else if (tmp_ire != NULL) {
3201 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3202 			    sizeof (iulp_t));
3203 			ire_refrele(tmp_ire);
3204 		}
3205 	}
3206 	if (prev_ire->ire_type == IRE_CACHE)
3207 		ire_delete(prev_ire);
3208 	ire_refrele(prev_ire);
3209 	/*
3210 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3211 	 * require TOS routing
3212 	 */
3213 	switch (icmph->icmph_code) {
3214 	case 0:
3215 	case 1:
3216 		/* TODO: TOS specificity for cases 2 and 3 */
3217 	case 2:
3218 	case 3:
3219 		break;
3220 	default:
3221 		freemsg(mp);
3222 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3223 		ire_refrele(ire);
3224 		return;
3225 	}
3226 	/*
3227 	 * Create a Route Association.  This will allow us to remember that
3228 	 * someone we believe told us to use the particular gateway.
3229 	 */
3230 	save_ire = ire;
3231 	ire = ire_create(
3232 		(uchar_t *)&dst,			/* dest addr */
3233 		(uchar_t *)&ip_g_all_ones,		/* mask */
3234 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3235 		(uchar_t *)&gateway,			/* gateway addr */
3236 		NULL,					/* no in_srcaddr */
3237 		&save_ire->ire_max_frag,		/* max frag */
3238 		NULL,					/* Fast Path header */
3239 		NULL,					/* no rfq */
3240 		NULL,					/* no stq */
3241 		IRE_HOST_REDIRECT,
3242 		NULL,
3243 		NULL,
3244 		NULL,
3245 		0,
3246 		0,
3247 		0,
3248 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3249 		&ulp_info,
3250 		NULL,
3251 		NULL);
3252 
3253 	if (ire == NULL) {
3254 		freemsg(mp);
3255 		ire_refrele(save_ire);
3256 		return;
3257 	}
3258 	error = ire_add(&ire, NULL, NULL, NULL);
3259 	ire_refrele(save_ire);
3260 	if (error == 0) {
3261 		ire_refrele(ire);		/* Held in ire_add_v4 */
3262 		/* tell routing sockets that we received a redirect */
3263 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3264 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3265 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3266 	}
3267 
3268 	/*
3269 	 * Delete any existing IRE_HOST_REDIRECT for this destination.
3270 	 * This together with the added IRE has the effect of
3271 	 * modifying an existing redirect.
3272 	 */
3273 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST_REDIRECT, NULL, NULL,
3274 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3275 	if (prev_ire) {
3276 		ire_delete(prev_ire);
3277 		ire_refrele(prev_ire);
3278 	}
3279 
3280 	freemsg(mp);
3281 }
3282 
3283 /*
3284  * Generate an ICMP parameter problem message.
3285  */
3286 static void
3287 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr)
3288 {
3289 	icmph_t	icmph;
3290 	boolean_t mctl_present;
3291 	mblk_t *first_mp;
3292 
3293 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3294 
3295 	if (!(mp = icmp_pkt_err_ok(mp))) {
3296 		if (mctl_present)
3297 			freeb(first_mp);
3298 		return;
3299 	}
3300 
3301 	bzero(&icmph, sizeof (icmph_t));
3302 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3303 	icmph.icmph_pp_ptr = ptr;
3304 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3305 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3306 }
3307 
3308 /*
3309  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3310  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3311  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3312  * an icmp error packet can be sent.
3313  * Assigns an appropriate source address to the packet. If ipha_dst is
3314  * one of our addresses use it for source. Otherwise pick a source based
3315  * on a route lookup back to ipha_src.
3316  * Note that ipha_src must be set here since the
3317  * packet is likely to arrive on an ill queue in ip_wput() which will
3318  * not set a source address.
3319  */
3320 static void
3321 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3322     boolean_t mctl_present)
3323 {
3324 	ipaddr_t dst;
3325 	icmph_t	*icmph;
3326 	ipha_t	*ipha;
3327 	uint_t	len_needed;
3328 	size_t	msg_len;
3329 	mblk_t	*mp1;
3330 	ipaddr_t src;
3331 	ire_t	*ire;
3332 	mblk_t *ipsec_mp;
3333 	ipsec_out_t	*io = NULL;
3334 	boolean_t xmit_if_on = B_FALSE;
3335 	zoneid_t	zoneid;
3336 
3337 	if (mctl_present) {
3338 		/*
3339 		 * If it is :
3340 		 *
3341 		 * 1) a IPSEC_OUT, then this is caused by outbound
3342 		 *    datagram originating on this host. IPSEC processing
3343 		 *    may or may not have been done. Refer to comments above
3344 		 *    icmp_inbound_error_fanout for details.
3345 		 *
3346 		 * 2) a IPSEC_IN if we are generating a icmp_message
3347 		 *    for an incoming datagram destined for us i.e called
3348 		 *    from ip_fanout_send_icmp.
3349 		 */
3350 		ipsec_info_t *in;
3351 		ipsec_mp = mp;
3352 		mp = ipsec_mp->b_cont;
3353 
3354 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3355 		ipha = (ipha_t *)mp->b_rptr;
3356 
3357 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3358 		    in->ipsec_info_type == IPSEC_IN);
3359 
3360 		if (in->ipsec_info_type == IPSEC_IN) {
3361 			/*
3362 			 * Convert the IPSEC_IN to IPSEC_OUT.
3363 			 */
3364 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3365 				BUMP_MIB(&ip_mib, ipOutDiscards);
3366 				return;
3367 			}
3368 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3369 		} else {
3370 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3371 			io = (ipsec_out_t *)in;
3372 			if (io->ipsec_out_xmit_if)
3373 				xmit_if_on = B_TRUE;
3374 			/*
3375 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3376 			 * ire lookup.
3377 			 */
3378 			io->ipsec_out_proc_begin = B_FALSE;
3379 		}
3380 		zoneid = io->ipsec_out_zoneid;
3381 		ASSERT(zoneid != ALL_ZONES);
3382 	} else {
3383 		/*
3384 		 * This is in clear. The icmp message we are building
3385 		 * here should go out in clear.
3386 		 *
3387 		 * Pardon the convolution of it all, but it's easier to
3388 		 * allocate a "use cleartext" IPSEC_IN message and convert
3389 		 * it than it is to allocate a new one.
3390 		 */
3391 		ipsec_in_t *ii;
3392 		ASSERT(DB_TYPE(mp) == M_DATA);
3393 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3394 			freemsg(mp);
3395 			BUMP_MIB(&ip_mib, ipOutDiscards);
3396 			return;
3397 		}
3398 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3399 
3400 		/* This is not a secure packet */
3401 		ii->ipsec_in_secure = B_FALSE;
3402 		if (CONN_Q(q)) {
3403 			zoneid = Q_TO_CONN(q)->conn_zoneid;
3404 		} else {
3405 			zoneid = GLOBAL_ZONEID;
3406 		}
3407 		ii->ipsec_in_zoneid = zoneid;
3408 		ASSERT(zoneid != ALL_ZONES);
3409 		ipsec_mp->b_cont = mp;
3410 		ipha = (ipha_t *)mp->b_rptr;
3411 		/*
3412 		 * Convert the IPSEC_IN to IPSEC_OUT.
3413 		 */
3414 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3415 			BUMP_MIB(&ip_mib, ipOutDiscards);
3416 			return;
3417 		}
3418 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3419 	}
3420 
3421 	/* Remember our eventual destination */
3422 	dst = ipha->ipha_src;
3423 
3424 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3425 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3426 	if (ire != NULL &&
3427 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3428 		src = ipha->ipha_dst;
3429 	} else if (!xmit_if_on) {
3430 		if (ire != NULL)
3431 			ire_refrele(ire);
3432 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3433 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3434 		if (ire == NULL) {
3435 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3436 			freemsg(ipsec_mp);
3437 			return;
3438 		}
3439 		src = ire->ire_src_addr;
3440 	} else {
3441 		ipif_t	*ipif = NULL;
3442 		ill_t	*ill;
3443 		/*
3444 		 * This must be an ICMP error coming from
3445 		 * ip_mrtun_forward(). The src addr should
3446 		 * be equal to the IP-addr of the outgoing
3447 		 * interface.
3448 		 */
3449 		if (io == NULL) {
3450 			/* This is not a IPSEC_OUT type control msg */
3451 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3452 			freemsg(ipsec_mp);
3453 			return;
3454 		}
3455 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3456 		    NULL, NULL, NULL, NULL);
3457 		if (ill != NULL) {
3458 			ipif = ipif_get_next_ipif(NULL, ill);
3459 			ill_refrele(ill);
3460 		}
3461 		if (ipif == NULL) {
3462 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3463 			freemsg(ipsec_mp);
3464 			return;
3465 		}
3466 		src = ipif->ipif_src_addr;
3467 		ipif_refrele(ipif);
3468 	}
3469 
3470 	if (ire != NULL)
3471 		ire_refrele(ire);
3472 
3473 	/*
3474 	 * Check if we can send back more then 8 bytes in addition
3475 	 * to the IP header. We will include as much as 64 bytes.
3476 	 */
3477 	len_needed = IPH_HDR_LENGTH(ipha);
3478 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3479 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3480 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3481 	}
3482 	len_needed += ip_icmp_return;
3483 	msg_len = msgdsize(mp);
3484 	if (msg_len > len_needed) {
3485 		(void) adjmsg(mp, len_needed - msg_len);
3486 		msg_len = len_needed;
3487 	}
3488 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3489 	if (mp1 == NULL) {
3490 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3491 		freemsg(ipsec_mp);
3492 		return;
3493 	}
3494 	/*
3495 	 * On an unlabeled system, dblks don't necessarily have creds.
3496 	 */
3497 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3498 	if (DB_CRED(mp) != NULL)
3499 		mblk_setcred(mp1, DB_CRED(mp));
3500 	mp1->b_cont = mp;
3501 	mp = mp1;
3502 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3503 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3504 	    io->ipsec_out_type == IPSEC_OUT);
3505 	ipsec_mp->b_cont = mp;
3506 
3507 	/*
3508 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3509 	 * node generates be accepted in peace by all on-host destinations.
3510 	 * If we do NOT assume that all on-host destinations trust
3511 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3512 	 * (Look for ipsec_out_icmp_loopback).
3513 	 */
3514 	io->ipsec_out_icmp_loopback = B_TRUE;
3515 
3516 	ipha = (ipha_t *)mp->b_rptr;
3517 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3518 	*ipha = icmp_ipha;
3519 	ipha->ipha_src = src;
3520 	ipha->ipha_dst = dst;
3521 	ipha->ipha_ttl = ip_def_ttl;
3522 	msg_len += sizeof (icmp_ipha) + len;
3523 	if (msg_len > IP_MAXPACKET) {
3524 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3525 		msg_len = IP_MAXPACKET;
3526 	}
3527 	ipha->ipha_length = htons((uint16_t)msg_len);
3528 	icmph = (icmph_t *)&ipha[1];
3529 	bcopy(stuff, icmph, len);
3530 	icmph->icmph_checksum = 0;
3531 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3532 	if (icmph->icmph_checksum == 0)
3533 		icmph->icmph_checksum = 0xFFFF;
3534 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3535 	put(q, ipsec_mp);
3536 }
3537 
3538 /*
3539  * Determine if an ICMP error packet can be sent given the rate limit.
3540  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3541  * in milliseconds) and a burst size. Burst size number of packets can
3542  * be sent arbitrarely closely spaced.
3543  * The state is tracked using two variables to implement an approximate
3544  * token bucket filter:
3545  *	icmp_pkt_err_last - lbolt value when the last burst started
3546  *	icmp_pkt_err_sent - number of packets sent in current burst
3547  */
3548 boolean_t
3549 icmp_err_rate_limit(void)
3550 {
3551 	clock_t now = TICK_TO_MSEC(lbolt);
3552 	uint_t refilled; /* Number of packets refilled in tbf since last */
3553 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3554 
3555 	if (err_interval == 0)
3556 		return (B_FALSE);
3557 
3558 	if (icmp_pkt_err_last > now) {
3559 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3560 		icmp_pkt_err_last = 0;
3561 		icmp_pkt_err_sent = 0;
3562 	}
3563 	/*
3564 	 * If we are in a burst update the token bucket filter.
3565 	 * Update the "last" time to be close to "now" but make sure
3566 	 * we don't loose precision.
3567 	 */
3568 	if (icmp_pkt_err_sent != 0) {
3569 		refilled = (now - icmp_pkt_err_last)/err_interval;
3570 		if (refilled > icmp_pkt_err_sent) {
3571 			icmp_pkt_err_sent = 0;
3572 		} else {
3573 			icmp_pkt_err_sent -= refilled;
3574 			icmp_pkt_err_last += refilled * err_interval;
3575 		}
3576 	}
3577 	if (icmp_pkt_err_sent == 0) {
3578 		/* Start of new burst */
3579 		icmp_pkt_err_last = now;
3580 	}
3581 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3582 		icmp_pkt_err_sent++;
3583 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3584 		    icmp_pkt_err_sent));
3585 		return (B_FALSE);
3586 	}
3587 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3588 	return (B_TRUE);
3589 }
3590 
3591 /*
3592  * Check if it is ok to send an IPv4 ICMP error packet in
3593  * response to the IPv4 packet in mp.
3594  * Free the message and return null if no
3595  * ICMP error packet should be sent.
3596  */
3597 static mblk_t *
3598 icmp_pkt_err_ok(mblk_t *mp)
3599 {
3600 	icmph_t	*icmph;
3601 	ipha_t	*ipha;
3602 	uint_t	len_needed;
3603 	ire_t	*src_ire;
3604 	ire_t	*dst_ire;
3605 
3606 	if (!mp)
3607 		return (NULL);
3608 	ipha = (ipha_t *)mp->b_rptr;
3609 	if (ip_csum_hdr(ipha)) {
3610 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3611 		freemsg(mp);
3612 		return (NULL);
3613 	}
3614 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3615 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3616 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3617 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3618 	if (src_ire != NULL || dst_ire != NULL ||
3619 	    CLASSD(ipha->ipha_dst) ||
3620 	    CLASSD(ipha->ipha_src) ||
3621 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3622 		/* Note: only errors to the fragment with offset 0 */
3623 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3624 		freemsg(mp);
3625 		if (src_ire != NULL)
3626 			ire_refrele(src_ire);
3627 		if (dst_ire != NULL)
3628 			ire_refrele(dst_ire);
3629 		return (NULL);
3630 	}
3631 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3632 		/*
3633 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3634 		 * errors in response to any ICMP errors.
3635 		 */
3636 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3637 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3638 			if (!pullupmsg(mp, len_needed)) {
3639 				BUMP_MIB(&icmp_mib, icmpInErrors);
3640 				freemsg(mp);
3641 				return (NULL);
3642 			}
3643 			ipha = (ipha_t *)mp->b_rptr;
3644 		}
3645 		icmph = (icmph_t *)
3646 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3647 		switch (icmph->icmph_type) {
3648 		case ICMP_DEST_UNREACHABLE:
3649 		case ICMP_SOURCE_QUENCH:
3650 		case ICMP_TIME_EXCEEDED:
3651 		case ICMP_PARAM_PROBLEM:
3652 		case ICMP_REDIRECT:
3653 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3654 			freemsg(mp);
3655 			return (NULL);
3656 		default:
3657 			break;
3658 		}
3659 	}
3660 	/*
3661 	 * If this is a labeled system, then check to see if we're allowed to
3662 	 * send a response to this particular sender.  If not, then just drop.
3663 	 */
3664 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3665 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3666 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3667 		freemsg(mp);
3668 		return (NULL);
3669 	}
3670 	if (icmp_err_rate_limit()) {
3671 		/*
3672 		 * Only send ICMP error packets every so often.
3673 		 * This should be done on a per port/source basis,
3674 		 * but for now this will suffice.
3675 		 */
3676 		freemsg(mp);
3677 		return (NULL);
3678 	}
3679 	return (mp);
3680 }
3681 
3682 /*
3683  * Generate an ICMP redirect message.
3684  */
3685 static void
3686 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3687 {
3688 	icmph_t	icmph;
3689 
3690 	/*
3691 	 * We are called from ip_rput where we could
3692 	 * not have attached an IPSEC_IN.
3693 	 */
3694 	ASSERT(mp->b_datap->db_type == M_DATA);
3695 
3696 	if (!(mp = icmp_pkt_err_ok(mp))) {
3697 		return;
3698 	}
3699 
3700 	bzero(&icmph, sizeof (icmph_t));
3701 	icmph.icmph_type = ICMP_REDIRECT;
3702 	icmph.icmph_code = 1;
3703 	icmph.icmph_rd_gateway = gateway;
3704 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3705 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE);
3706 }
3707 
3708 /*
3709  * Generate an ICMP time exceeded message.
3710  */
3711 void
3712 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code)
3713 {
3714 	icmph_t	icmph;
3715 	boolean_t mctl_present;
3716 	mblk_t *first_mp;
3717 
3718 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3719 
3720 	if (!(mp = icmp_pkt_err_ok(mp))) {
3721 		if (mctl_present)
3722 			freeb(first_mp);
3723 		return;
3724 	}
3725 
3726 	bzero(&icmph, sizeof (icmph_t));
3727 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3728 	icmph.icmph_code = code;
3729 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3730 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present);
3731 }
3732 
3733 /*
3734  * Generate an ICMP unreachable message.
3735  */
3736 void
3737 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code)
3738 {
3739 	icmph_t	icmph;
3740 	mblk_t *first_mp;
3741 	boolean_t mctl_present;
3742 
3743 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3744 
3745 	if (!(mp = icmp_pkt_err_ok(mp))) {
3746 		if (mctl_present)
3747 			freeb(first_mp);
3748 		return;
3749 	}
3750 
3751 	bzero(&icmph, sizeof (icmph_t));
3752 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3753 	icmph.icmph_code = code;
3754 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3755 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3756 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present);
3757 }
3758 
3759 /*
3760  * News from ARP.  ARP sends notification of interesting events down
3761  * to its clients using M_CTL messages with the interesting ARP packet
3762  * attached via b_cont.
3763  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3764  * queue as opposed to ARP sending the message to all the clients, i.e. all
3765  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3766  * table if a cache IRE is found to delete all the entries for the address in
3767  * the packet.
3768  */
3769 static void
3770 ip_arp_news(queue_t *q, mblk_t *mp)
3771 {
3772 	arcn_t		*arcn;
3773 	arh_t		*arh;
3774 	char		*cp1;
3775 	uchar_t		*cp2;
3776 	ire_t		*ire = NULL;
3777 	int		i1;
3778 	char		hbuf[128];
3779 	char		sbuf[16];
3780 	ipaddr_t	src;
3781 	in6_addr_t	v6src;
3782 	boolean_t	isv6 = B_FALSE;
3783 
3784 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3785 		if (q->q_next) {
3786 			putnext(q, mp);
3787 		} else
3788 			freemsg(mp);
3789 		return;
3790 	}
3791 	arh = (arh_t *)mp->b_cont->b_rptr;
3792 	/* Is it one we are interested in? */
3793 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3794 		isv6 = B_TRUE;
3795 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3796 		    IPV6_ADDR_LEN);
3797 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3798 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3799 		    IP_ADDR_LEN);
3800 	} else {
3801 		freemsg(mp);
3802 		return;
3803 	}
3804 
3805 	arcn = (arcn_t *)mp->b_rptr;
3806 	switch (arcn->arcn_code) {
3807 	case AR_CN_BOGON:
3808 		/*
3809 		 * Someone is sending ARP packets with a source protocol
3810 		 * address which we have published.  Either they are
3811 		 * pretending to be us, or we have been asked to proxy
3812 		 * for a machine that can do fine for itself, or two
3813 		 * different machines are providing proxy service for the
3814 		 * same protocol address, or something.  We try and do
3815 		 * something appropriate here.
3816 		 */
3817 		cp2 = (uchar_t *)&arh[1];
3818 		cp1 = hbuf;
3819 		*cp1 = '\0';
3820 		for (i1 = arh->arh_hlen; i1--; cp1 += 3)
3821 			(void) sprintf(cp1, "%02x:", *cp2++ & 0xff);
3822 		if (cp1 != hbuf)
3823 			cp1[-1] = '\0';
3824 		(void) ip_dot_addr(src, sbuf);
3825 		if (isv6)
3826 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
3827 		else
3828 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
3829 
3830 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3831 			cmn_err(CE_WARN,
3832 			    "IP: Hardware address '%s' trying"
3833 			    " to be our address %s!",
3834 			    hbuf, sbuf);
3835 		} else {
3836 			cmn_err(CE_WARN,
3837 			    "IP: Proxy ARP problem?  "
3838 			    "Hardware address '%s' thinks it is %s",
3839 			    hbuf, sbuf);
3840 		}
3841 		if (ire != NULL)
3842 			ire_refrele(ire);
3843 		break;
3844 	case AR_CN_ANNOUNCE:
3845 		if (isv6) {
3846 			/*
3847 			 * For XRESOLV interfaces.
3848 			 * Delete the IRE cache entry and NCE for this
3849 			 * v6 address
3850 			 */
3851 			ip_ire_clookup_and_delete_v6(&v6src);
3852 			/*
3853 			 * If v6src is a non-zero, it's a router address
3854 			 * as below. Do the same sort of thing to clean
3855 			 * out off-net IRE_CACHE entries that go through
3856 			 * the router.
3857 			 */
3858 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
3859 				ire_walk_v6(ire_delete_cache_gw_v6,
3860 				    (char *)&v6src, ALL_ZONES);
3861 			}
3862 			break;
3863 		}
3864 		/*
3865 		 * ARP gives us a copy of any broadcast packet with identical
3866 		 * sender and receiver protocol address, in
3867 		 * case we want to intuit something from it.  Such a packet
3868 		 * usually means that a machine has just come up on the net.
3869 		 * If we have an IRE_CACHE, we blow it away.  This way we will
3870 		 * immediately pick up the rare case of a host changing
3871 		 * hardware address. ip_ire_clookup_and_delete achieves this.
3872 		 *
3873 		 * The address in "src" may be an entry for a router.
3874 		 * (Default router, or non-default router.)  If
3875 		 * that's true, then any off-net IRE_CACHE entries
3876 		 * that go through the router with address "src"
3877 		 * must be clobbered.  Use ire_walk to achieve this
3878 		 * goal.
3879 		 *
3880 		 * It should be possible to determine if the address
3881 		 * in src is or is not for a router.  This way,
3882 		 * the ire_walk() isn't called all of the time here.
3883 		 * Do not pass 'src' value of 0 to ire_delete_cache_gw,
3884 		 * as it would remove all IRE_CACHE entries for onlink
3885 		 * destinations. All onlink destinations have
3886 		 * ire_gateway_addr == 0.
3887 		 */
3888 		if ((ip_ire_clookup_and_delete(src, NULL) ||
3889 		    (ire = ire_ftable_lookup(src, 0, 0, 0, NULL, NULL, NULL,
3890 		    0, NULL, MATCH_IRE_DSTONLY)) != NULL) && src != 0) {
3891 			ire_walk_v4(ire_delete_cache_gw, (char *)&src,
3892 			    ALL_ZONES);
3893 		}
3894 		/* From ire_ftable_lookup */
3895 		if (ire != NULL)
3896 			ire_refrele(ire);
3897 		break;
3898 	default:
3899 		if (ire != NULL)
3900 			ire_refrele(ire);
3901 		break;
3902 	}
3903 	freemsg(mp);
3904 }
3905 
3906 /*
3907  * Create a mblk suitable for carrying the interface index and/or source link
3908  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
3909  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
3910  * application.
3911  */
3912 mblk_t *
3913 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
3914 {
3915 	mblk_t		*mp;
3916 	in_pktinfo_t	*pinfo;
3917 	ipha_t *ipha;
3918 	struct ether_header *pether;
3919 
3920 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
3921 	if (mp == NULL) {
3922 		ip1dbg(("ip_add_info: allocation failure.\n"));
3923 		return (data_mp);
3924 	}
3925 
3926 	ipha	= (ipha_t *)data_mp->b_rptr;
3927 	pinfo = (in_pktinfo_t *)mp->b_rptr;
3928 	bzero(pinfo, sizeof (in_pktinfo_t));
3929 	pinfo->in_pkt_flags = (uchar_t)flags;
3930 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
3931 
3932 	if (flags & IPF_RECVIF)
3933 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
3934 
3935 	pether = (struct ether_header *)((char *)ipha
3936 	    - sizeof (struct ether_header));
3937 	/*
3938 	 * Make sure the interface is an ethernet type, since this option
3939 	 * is currently supported only on this type of interface. Also make
3940 	 * sure we are pointing correctly above db_base.
3941 	 */
3942 
3943 	if ((flags & IPF_RECVSLLA) &&
3944 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
3945 	    (ill->ill_type == IFT_ETHER) &&
3946 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
3947 
3948 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
3949 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
3950 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
3951 	} else {
3952 		/*
3953 		 * Clear the bit. Indicate to upper layer that IP is not
3954 		 * sending this ancillary info.
3955 		 */
3956 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
3957 	}
3958 
3959 	mp->b_datap->db_type = M_CTL;
3960 	mp->b_wptr += sizeof (in_pktinfo_t);
3961 	mp->b_cont = data_mp;
3962 
3963 	return (mp);
3964 }
3965 
3966 /*
3967  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
3968  * part of the bind request.
3969  */
3970 
3971 boolean_t
3972 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
3973 {
3974 	ipsec_in_t *ii;
3975 
3976 	ASSERT(policy_mp != NULL);
3977 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
3978 
3979 	ii = (ipsec_in_t *)policy_mp->b_rptr;
3980 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
3981 
3982 	connp->conn_policy = ii->ipsec_in_policy;
3983 	ii->ipsec_in_policy = NULL;
3984 
3985 	if (ii->ipsec_in_action != NULL) {
3986 		if (connp->conn_latch == NULL) {
3987 			connp->conn_latch = iplatch_create();
3988 			if (connp->conn_latch == NULL)
3989 				return (B_FALSE);
3990 		}
3991 		ipsec_latch_inbound(connp->conn_latch, ii);
3992 	}
3993 	return (B_TRUE);
3994 }
3995 
3996 /*
3997  * Upper level protocols (ULP) pass through bind requests to IP for inspection
3998  * and to arrange for power-fanout assist.  The ULP is identified by
3999  * adding a single byte at the end of the original bind message.
4000  * A ULP other than UDP or TCP that wishes to be recognized passes
4001  * down a bind with a zero length address.
4002  *
4003  * The binding works as follows:
4004  * - A zero byte address means just bind to the protocol.
4005  * - A four byte address is treated as a request to validate
4006  *   that the address is a valid local address, appropriate for
4007  *   an application to bind to. This does not affect any fanout
4008  *   information in IP.
4009  * - A sizeof sin_t byte address is used to bind to only the local address
4010  *   and port.
4011  * - A sizeof ipa_conn_t byte address contains complete fanout information
4012  *   consisting of local and remote addresses and ports.  In
4013  *   this case, the addresses are both validated as appropriate
4014  *   for this operation, and, if so, the information is retained
4015  *   for use in the inbound fanout.
4016  *
4017  * The ULP (except in the zero-length bind) can append an
4018  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4019  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4020  * a copy of the source or destination IRE (source for local bind;
4021  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4022  * policy information contained should be copied on to the conn.
4023  *
4024  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4025  */
4026 mblk_t *
4027 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4028 {
4029 	ssize_t		len;
4030 	struct T_bind_req	*tbr;
4031 	sin_t		*sin;
4032 	ipa_conn_t	*ac;
4033 	uchar_t		*ucp;
4034 	mblk_t		*mp1;
4035 	boolean_t	ire_requested;
4036 	boolean_t	ipsec_policy_set = B_FALSE;
4037 	int		error = 0;
4038 	int		protocol;
4039 	ipa_conn_x_t	*acx;
4040 
4041 	ASSERT(!connp->conn_af_isv6);
4042 	connp->conn_pkt_isv6 = B_FALSE;
4043 
4044 	len = MBLKL(mp);
4045 	if (len < (sizeof (*tbr) + 1)) {
4046 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4047 		    "ip_bind: bogus msg, len %ld", len);
4048 		/* XXX: Need to return something better */
4049 		goto bad_addr;
4050 	}
4051 	/* Back up and extract the protocol identifier. */
4052 	mp->b_wptr--;
4053 	protocol = *mp->b_wptr & 0xFF;
4054 	tbr = (struct T_bind_req *)mp->b_rptr;
4055 	/* Reset the message type in preparation for shipping it back. */
4056 	DB_TYPE(mp) = M_PCPROTO;
4057 
4058 	connp->conn_ulp = (uint8_t)protocol;
4059 
4060 	/*
4061 	 * Check for a zero length address.  This is from a protocol that
4062 	 * wants to register to receive all packets of its type.
4063 	 */
4064 	if (tbr->ADDR_length == 0) {
4065 		/*
4066 		 * These protocols are now intercepted in ip_bind_v6().
4067 		 * Reject protocol-level binds here for now.
4068 		 *
4069 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4070 		 * so that the protocol type cannot be SCTP.
4071 		 */
4072 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4073 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4074 			goto bad_addr;
4075 		}
4076 
4077 		/*
4078 		 *
4079 		 * The udp module never sends down a zero-length address,
4080 		 * and allowing this on a labeled system will break MLP
4081 		 * functionality.
4082 		 */
4083 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4084 			goto bad_addr;
4085 
4086 		if (connp->conn_mac_exempt)
4087 			goto bad_addr;
4088 
4089 		/* No hash here really.  The table is big enough. */
4090 		connp->conn_srcv6 = ipv6_all_zeros;
4091 
4092 		ipcl_proto_insert(connp, protocol);
4093 
4094 		tbr->PRIM_type = T_BIND_ACK;
4095 		return (mp);
4096 	}
4097 
4098 	/* Extract the address pointer from the message. */
4099 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4100 	    tbr->ADDR_length);
4101 	if (ucp == NULL) {
4102 		ip1dbg(("ip_bind: no address\n"));
4103 		goto bad_addr;
4104 	}
4105 	if (!OK_32PTR(ucp)) {
4106 		ip1dbg(("ip_bind: unaligned address\n"));
4107 		goto bad_addr;
4108 	}
4109 	/*
4110 	 * Check for trailing mps.
4111 	 */
4112 
4113 	mp1 = mp->b_cont;
4114 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4115 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4116 
4117 	switch (tbr->ADDR_length) {
4118 	default:
4119 		ip1dbg(("ip_bind: bad address length %d\n",
4120 		    (int)tbr->ADDR_length));
4121 		goto bad_addr;
4122 
4123 	case IP_ADDR_LEN:
4124 		/* Verification of local address only */
4125 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4126 		    ire_requested, ipsec_policy_set, B_FALSE);
4127 		break;
4128 
4129 	case sizeof (sin_t):
4130 		sin = (sin_t *)ucp;
4131 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4132 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4133 		if (protocol == IPPROTO_TCP)
4134 			connp->conn_recv = tcp_conn_request;
4135 		break;
4136 
4137 	case sizeof (ipa_conn_t):
4138 		ac = (ipa_conn_t *)ucp;
4139 		/* For raw socket, the local port is not set. */
4140 		if (ac->ac_lport == 0)
4141 			ac->ac_lport = connp->conn_lport;
4142 		/* Always verify destination reachability. */
4143 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4144 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4145 		    ipsec_policy_set, B_TRUE, B_TRUE);
4146 		if (protocol == IPPROTO_TCP)
4147 			connp->conn_recv = tcp_input;
4148 		break;
4149 
4150 	case sizeof (ipa_conn_x_t):
4151 		acx = (ipa_conn_x_t *)ucp;
4152 		/*
4153 		 * Whether or not to verify destination reachability depends
4154 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4155 		 */
4156 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4157 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4158 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4159 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4160 		if (protocol == IPPROTO_TCP)
4161 			connp->conn_recv = tcp_input;
4162 		break;
4163 	}
4164 	if (error == EINPROGRESS)
4165 		return (NULL);
4166 	else if (error != 0)
4167 		goto bad_addr;
4168 	/*
4169 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4170 	 * We can't do this in ip_bind_insert_ire because the policy
4171 	 * may not have been inherited at that point in time and hence
4172 	 * conn_out_enforce_policy may not be set.
4173 	 */
4174 	mp1 = mp->b_cont;
4175 	if (ire_requested && connp->conn_out_enforce_policy &&
4176 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4177 		ire_t *ire = (ire_t *)mp1->b_rptr;
4178 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4179 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4180 	}
4181 
4182 	/* Send it home. */
4183 	mp->b_datap->db_type = M_PCPROTO;
4184 	tbr->PRIM_type = T_BIND_ACK;
4185 	return (mp);
4186 
4187 bad_addr:
4188 	/*
4189 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4190 	 * a unix errno.
4191 	 */
4192 	if (error > 0)
4193 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4194 	else
4195 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4196 	return (mp);
4197 }
4198 
4199 /*
4200  * Here address is verified to be a valid local address.
4201  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4202  * address is also considered a valid local address.
4203  * In the case of a broadcast/multicast address, however, the
4204  * upper protocol is expected to reset the src address
4205  * to 0 if it sees a IRE_BROADCAST type returned so that
4206  * no packets are emitted with broadcast/multicast address as
4207  * source address (that violates hosts requirements RFC1122)
4208  * The addresses valid for bind are:
4209  *	(1) - INADDR_ANY (0)
4210  *	(2) - IP address of an UP interface
4211  *	(3) - IP address of a DOWN interface
4212  *	(4) - valid local IP broadcast addresses. In this case
4213  *	the conn will only receive packets destined to
4214  *	the specified broadcast address.
4215  *	(5) - a multicast address. In this case
4216  *	the conn will only receive packets destined to
4217  *	the specified multicast address. Note: the
4218  *	application still has to issue an
4219  *	IP_ADD_MEMBERSHIP socket option.
4220  *
4221  * On error, return -1 for TBADADDR otherwise pass the
4222  * errno with TSYSERR reply.
4223  *
4224  * In all the above cases, the bound address must be valid in the current zone.
4225  * When the address is loopback, multicast or broadcast, there might be many
4226  * matching IREs so bind has to look up based on the zone.
4227  *
4228  * Note: lport is in network byte order.
4229  */
4230 int
4231 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4232     boolean_t ire_requested, boolean_t ipsec_policy_set,
4233     boolean_t fanout_insert)
4234 {
4235 	int		error = 0;
4236 	ire_t		*src_ire;
4237 	mblk_t		*policy_mp;
4238 	ipif_t		*ipif;
4239 	zoneid_t	zoneid;
4240 
4241 	if (ipsec_policy_set) {
4242 		policy_mp = mp->b_cont;
4243 	}
4244 
4245 	/*
4246 	 * If it was previously connected, conn_fully_bound would have
4247 	 * been set.
4248 	 */
4249 	connp->conn_fully_bound = B_FALSE;
4250 
4251 	src_ire = NULL;
4252 	ipif = NULL;
4253 
4254 	zoneid = IPCL_ZONEID(connp);
4255 
4256 	if (src_addr) {
4257 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4258 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4259 		/*
4260 		 * If an address other than 0.0.0.0 is requested,
4261 		 * we verify that it is a valid address for bind
4262 		 * Note: Following code is in if-else-if form for
4263 		 * readability compared to a condition check.
4264 		 */
4265 		/* LINTED - statement has no consequent */
4266 		if (IRE_IS_LOCAL(src_ire)) {
4267 			/*
4268 			 * (2) Bind to address of local UP interface
4269 			 */
4270 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4271 			/*
4272 			 * (4) Bind to broadcast address
4273 			 * Note: permitted only from transports that
4274 			 * request IRE
4275 			 */
4276 			if (!ire_requested)
4277 				error = EADDRNOTAVAIL;
4278 		} else {
4279 			/*
4280 			 * (3) Bind to address of local DOWN interface
4281 			 * (ipif_lookup_addr() looks up all interfaces
4282 			 * but we do not get here for UP interfaces
4283 			 * - case (2) above)
4284 			 * We put the protocol byte back into the mblk
4285 			 * since we may come back via ip_wput_nondata()
4286 			 * later with this mblk if ipif_lookup_addr chooses
4287 			 * to defer processing.
4288 			 */
4289 			*mp->b_wptr++ = (char)connp->conn_ulp;
4290 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4291 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4292 			    &error)) != NULL) {
4293 				ipif_refrele(ipif);
4294 			} else if (error == EINPROGRESS) {
4295 				if (src_ire != NULL)
4296 					ire_refrele(src_ire);
4297 				return (EINPROGRESS);
4298 			} else if (CLASSD(src_addr)) {
4299 				error = 0;
4300 				if (src_ire != NULL)
4301 					ire_refrele(src_ire);
4302 				/*
4303 				 * (5) bind to multicast address.
4304 				 * Fake out the IRE returned to upper
4305 				 * layer to be a broadcast IRE.
4306 				 */
4307 				src_ire = ire_ctable_lookup(
4308 				    INADDR_BROADCAST, INADDR_ANY,
4309 				    IRE_BROADCAST, NULL, zoneid, NULL,
4310 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4311 				if (src_ire == NULL || !ire_requested)
4312 					error = EADDRNOTAVAIL;
4313 			} else {
4314 				/*
4315 				 * Not a valid address for bind
4316 				 */
4317 				error = EADDRNOTAVAIL;
4318 			}
4319 			/*
4320 			 * Just to keep it consistent with the processing in
4321 			 * ip_bind_v4()
4322 			 */
4323 			mp->b_wptr--;
4324 		}
4325 		if (error) {
4326 			/* Red Alert!  Attempting to be a bogon! */
4327 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4328 			    ntohl(src_addr)));
4329 			goto bad_addr;
4330 		}
4331 	}
4332 
4333 	/*
4334 	 * Allow setting new policies. For example, disconnects come
4335 	 * down as ipa_t bind. As we would have set conn_policy_cached
4336 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4337 	 * can change after the disconnect.
4338 	 */
4339 	connp->conn_policy_cached = B_FALSE;
4340 
4341 	/*
4342 	 * If not fanout_insert this was just an address verification
4343 	 */
4344 	if (fanout_insert) {
4345 		/*
4346 		 * The addresses have been verified. Time to insert in
4347 		 * the correct fanout list.
4348 		 */
4349 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4350 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4351 		connp->conn_lport = lport;
4352 		connp->conn_fport = 0;
4353 		/*
4354 		 * Do we need to add a check to reject Multicast packets
4355 		 */
4356 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4357 	}
4358 
4359 	if (error == 0) {
4360 		if (ire_requested) {
4361 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4362 				error = -1;
4363 				/* Falls through to bad_addr */
4364 			}
4365 		} else if (ipsec_policy_set) {
4366 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4367 				error = -1;
4368 				/* Falls through to bad_addr */
4369 			}
4370 		}
4371 	}
4372 bad_addr:
4373 	if (error != 0) {
4374 		if (connp->conn_anon_port) {
4375 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4376 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4377 			    B_FALSE);
4378 		}
4379 		connp->conn_mlp_type = mlptSingle;
4380 	}
4381 	if (src_ire != NULL)
4382 		IRE_REFRELE(src_ire);
4383 	if (ipsec_policy_set) {
4384 		ASSERT(policy_mp == mp->b_cont);
4385 		ASSERT(policy_mp != NULL);
4386 		freeb(policy_mp);
4387 		/*
4388 		 * As of now assume that nothing else accompanies
4389 		 * IPSEC_POLICY_SET.
4390 		 */
4391 		mp->b_cont = NULL;
4392 	}
4393 	return (error);
4394 }
4395 
4396 /*
4397  * Verify that both the source and destination addresses
4398  * are valid.  If verify_dst is false, then the destination address may be
4399  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4400  * destination reachability, while tunnels do not.
4401  * Note that we allow connect to broadcast and multicast
4402  * addresses when ire_requested is set. Thus the ULP
4403  * has to check for IRE_BROADCAST and multicast.
4404  *
4405  * Returns zero if ok.
4406  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4407  * (for use with TSYSERR reply).
4408  *
4409  * Note: lport and fport are in network byte order.
4410  */
4411 int
4412 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4413     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4414     boolean_t ire_requested, boolean_t ipsec_policy_set,
4415     boolean_t fanout_insert, boolean_t verify_dst)
4416 {
4417 	ire_t		*src_ire;
4418 	ire_t		*dst_ire;
4419 	int		error = 0;
4420 	int 		protocol;
4421 	mblk_t		*policy_mp;
4422 	ire_t		*sire = NULL;
4423 	ire_t		*md_dst_ire = NULL;
4424 	ill_t		*md_ill = NULL;
4425 	zoneid_t	zoneid;
4426 	ipaddr_t	src_addr = *src_addrp;
4427 
4428 	src_ire = dst_ire = NULL;
4429 	protocol = *mp->b_wptr & 0xFF;
4430 
4431 	/*
4432 	 * If we never got a disconnect before, clear it now.
4433 	 */
4434 	connp->conn_fully_bound = B_FALSE;
4435 
4436 	if (ipsec_policy_set) {
4437 		policy_mp = mp->b_cont;
4438 	}
4439 
4440 	zoneid = IPCL_ZONEID(connp);
4441 
4442 	if (CLASSD(dst_addr)) {
4443 		/* Pick up an IRE_BROADCAST */
4444 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4445 		    NULL, zoneid, MBLK_GETLABEL(mp),
4446 		    (MATCH_IRE_RECURSIVE |
4447 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4448 		    MATCH_IRE_SECATTR));
4449 	} else {
4450 		/*
4451 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4452 		 * and onlink ipif is not found set ENETUNREACH error.
4453 		 */
4454 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4455 			ipif_t *ipif;
4456 
4457 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4458 			    dst_addr : connp->conn_nexthop_v4, zoneid);
4459 			if (ipif == NULL) {
4460 				error = ENETUNREACH;
4461 				goto bad_addr;
4462 			}
4463 			ipif_refrele(ipif);
4464 		}
4465 
4466 		if (connp->conn_nexthop_set) {
4467 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4468 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4469 			    MATCH_IRE_SECATTR);
4470 		} else {
4471 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4472 			    &sire, zoneid, MBLK_GETLABEL(mp),
4473 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4474 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4475 			    MATCH_IRE_SECATTR));
4476 		}
4477 	}
4478 	/*
4479 	 * dst_ire can't be a broadcast when not ire_requested.
4480 	 * We also prevent ire's with src address INADDR_ANY to
4481 	 * be used, which are created temporarily for
4482 	 * sending out packets from endpoints that have
4483 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4484 	 * reachable.  If verify_dst is false, the destination needn't be
4485 	 * reachable.
4486 	 *
4487 	 * If we match on a reject or black hole, then we've got a
4488 	 * local failure.  May as well fail out the connect() attempt,
4489 	 * since it's never going to succeed.
4490 	 */
4491 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4492 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4493 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4494 		/*
4495 		 * If we're verifying destination reachability, we always want
4496 		 * to complain here.
4497 		 *
4498 		 * If we're not verifying destination reachability but the
4499 		 * destination has a route, we still want to fail on the
4500 		 * temporary address and broadcast address tests.
4501 		 */
4502 		if (verify_dst || (dst_ire != NULL)) {
4503 			if (ip_debug > 2) {
4504 				pr_addr_dbg("ip_bind_connected: bad connected "
4505 				    "dst %s\n", AF_INET, &dst_addr);
4506 			}
4507 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4508 				error = ENETUNREACH;
4509 			else
4510 				error = EHOSTUNREACH;
4511 			goto bad_addr;
4512 		}
4513 	}
4514 
4515 	/*
4516 	 * We now know that routing will allow us to reach the destination.
4517 	 * Check whether Trusted Solaris policy allows communication with this
4518 	 * host, and pretend that the destination is unreachable if not.
4519 	 *
4520 	 * This is never a problem for TCP, since that transport is known to
4521 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4522 	 * handling.  If the remote is unreachable, it will be detected at that
4523 	 * point, so there's no reason to check it here.
4524 	 *
4525 	 * Note that for sendto (and other datagram-oriented friends), this
4526 	 * check is done as part of the data path label computation instead.
4527 	 * The check here is just to make non-TCP connect() report the right
4528 	 * error.
4529 	 */
4530 	if (dst_ire != NULL && is_system_labeled() &&
4531 	    !IPCL_IS_TCP(connp) &&
4532 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4533 	    connp->conn_mac_exempt) != 0) {
4534 		error = EHOSTUNREACH;
4535 		if (ip_debug > 2) {
4536 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4537 			    AF_INET, &dst_addr);
4538 		}
4539 		goto bad_addr;
4540 	}
4541 
4542 	/*
4543 	 * If the app does a connect(), it means that it will most likely
4544 	 * send more than 1 packet to the destination.  It makes sense
4545 	 * to clear the temporary flag.
4546 	 */
4547 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4548 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4549 		irb_t *irb = dst_ire->ire_bucket;
4550 
4551 		rw_enter(&irb->irb_lock, RW_WRITER);
4552 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4553 		irb->irb_tmp_ire_cnt--;
4554 		rw_exit(&irb->irb_lock);
4555 	}
4556 
4557 	/*
4558 	 * See if we should notify ULP about MDT; we do this whether or not
4559 	 * ire_requested is TRUE, in order to handle active connects; MDT
4560 	 * eligibility tests for passive connects are handled separately
4561 	 * through tcp_adapt_ire().  We do this before the source address
4562 	 * selection, because dst_ire may change after a call to
4563 	 * ipif_select_source().  This is a best-effort check, as the
4564 	 * packet for this connection may not actually go through
4565 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4566 	 * calling ip_newroute().  This is why we further check on the
4567 	 * IRE during Multidata packet transmission in tcp_multisend().
4568 	 */
4569 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4570 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4571 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4572 	    ILL_MDT_CAPABLE(md_ill)) {
4573 		md_dst_ire = dst_ire;
4574 		IRE_REFHOLD(md_dst_ire);
4575 	}
4576 
4577 	if (dst_ire != NULL &&
4578 	    dst_ire->ire_type == IRE_LOCAL &&
4579 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4580 		/*
4581 		 * If the IRE belongs to a different zone, look for a matching
4582 		 * route in the forwarding table and use the source address from
4583 		 * that route.
4584 		 */
4585 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4586 		    zoneid, 0, NULL,
4587 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4588 		    MATCH_IRE_RJ_BHOLE);
4589 		if (src_ire == NULL) {
4590 			error = EHOSTUNREACH;
4591 			goto bad_addr;
4592 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4593 			if (!(src_ire->ire_type & IRE_HOST))
4594 				error = ENETUNREACH;
4595 			else
4596 				error = EHOSTUNREACH;
4597 			goto bad_addr;
4598 		}
4599 		if (src_addr == INADDR_ANY)
4600 			src_addr = src_ire->ire_src_addr;
4601 		ire_refrele(src_ire);
4602 		src_ire = NULL;
4603 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4604 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4605 			src_addr = sire->ire_src_addr;
4606 			ire_refrele(dst_ire);
4607 			dst_ire = sire;
4608 			sire = NULL;
4609 		} else {
4610 			/*
4611 			 * Pick a source address so that a proper inbound
4612 			 * load spreading would happen.
4613 			 */
4614 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4615 			ipif_t *src_ipif = NULL;
4616 			ire_t *ipif_ire;
4617 
4618 			/*
4619 			 * Supply a local source address such that inbound
4620 			 * load spreading happens.
4621 			 *
4622 			 * Determine the best source address on this ill for
4623 			 * the destination.
4624 			 *
4625 			 * 1) For broadcast, we should return a broadcast ire
4626 			 *    found above so that upper layers know that the
4627 			 *    destination address is a broadcast address.
4628 			 *
4629 			 * 2) If this is part of a group, select a better
4630 			 *    source address so that better inbound load
4631 			 *    balancing happens. Do the same if the ipif
4632 			 *    is DEPRECATED.
4633 			 *
4634 			 * 3) If the outgoing interface is part of a usesrc
4635 			 *    group, then try selecting a source address from
4636 			 *    the usesrc ILL.
4637 			 */
4638 			if ((dst_ire->ire_zoneid != zoneid &&
4639 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4640 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4641 			    ((dst_ill->ill_group != NULL) ||
4642 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4643 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4644 				/*
4645 				 * If the destination is reachable via a
4646 				 * given gateway, the selected source address
4647 				 * should be in the same subnet as the gateway.
4648 				 * Otherwise, the destination is not reachable.
4649 				 *
4650 				 * If there are no interfaces on the same subnet
4651 				 * as the destination, ipif_select_source gives
4652 				 * first non-deprecated interface which might be
4653 				 * on a different subnet than the gateway.
4654 				 * This is not desirable. Hence pass the dst_ire
4655 				 * source address to ipif_select_source.
4656 				 * It is sure that the destination is reachable
4657 				 * with the dst_ire source address subnet.
4658 				 * So passing dst_ire source address to
4659 				 * ipif_select_source will make sure that the
4660 				 * selected source will be on the same subnet
4661 				 * as dst_ire source address.
4662 				 */
4663 				ipaddr_t saddr =
4664 				    dst_ire->ire_ipif->ipif_src_addr;
4665 				src_ipif = ipif_select_source(dst_ill,
4666 				    saddr, zoneid);
4667 				if (src_ipif != NULL) {
4668 					if (IS_VNI(src_ipif->ipif_ill)) {
4669 						/*
4670 						 * For VNI there is no
4671 						 * interface route
4672 						 */
4673 						src_addr =
4674 						    src_ipif->ipif_src_addr;
4675 					} else {
4676 						ipif_ire =
4677 						    ipif_to_ire(src_ipif);
4678 						if (ipif_ire != NULL) {
4679 							IRE_REFRELE(dst_ire);
4680 							dst_ire = ipif_ire;
4681 						}
4682 						src_addr =
4683 						    dst_ire->ire_src_addr;
4684 					}
4685 					ipif_refrele(src_ipif);
4686 				} else {
4687 					src_addr = dst_ire->ire_src_addr;
4688 				}
4689 			} else {
4690 				src_addr = dst_ire->ire_src_addr;
4691 			}
4692 		}
4693 	}
4694 
4695 	/*
4696 	 * We do ire_route_lookup() here (and not
4697 	 * interface lookup as we assert that
4698 	 * src_addr should only come from an
4699 	 * UP interface for hard binding.
4700 	 */
4701 	ASSERT(src_ire == NULL);
4702 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
4703 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4704 	/* src_ire must be a local|loopback */
4705 	if (!IRE_IS_LOCAL(src_ire)) {
4706 		if (ip_debug > 2) {
4707 			pr_addr_dbg("ip_bind_connected: bad connected "
4708 			    "src %s\n", AF_INET, &src_addr);
4709 		}
4710 		error = EADDRNOTAVAIL;
4711 		goto bad_addr;
4712 	}
4713 
4714 	/*
4715 	 * If the source address is a loopback address, the
4716 	 * destination had best be local or multicast.
4717 	 * The transports that can't handle multicast will reject
4718 	 * those addresses.
4719 	 */
4720 	if (src_ire->ire_type == IRE_LOOPBACK &&
4721 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
4722 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
4723 		error = -1;
4724 		goto bad_addr;
4725 	}
4726 
4727 	/*
4728 	 * Allow setting new policies. For example, disconnects come
4729 	 * down as ipa_t bind. As we would have set conn_policy_cached
4730 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4731 	 * can change after the disconnect.
4732 	 */
4733 	connp->conn_policy_cached = B_FALSE;
4734 
4735 	/*
4736 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
4737 	 * can handle their passed-in conn's.
4738 	 */
4739 
4740 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4741 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
4742 	connp->conn_lport = lport;
4743 	connp->conn_fport = fport;
4744 	*src_addrp = src_addr;
4745 
4746 	ASSERT(!(ipsec_policy_set && ire_requested));
4747 	if (ire_requested) {
4748 		iulp_t *ulp_info = NULL;
4749 
4750 		/*
4751 		 * Note that sire will not be NULL if this is an off-link
4752 		 * connection and there is not cache for that dest yet.
4753 		 *
4754 		 * XXX Because of an existing bug, if there are multiple
4755 		 * default routes, the IRE returned now may not be the actual
4756 		 * default route used (default routes are chosen in a
4757 		 * round robin fashion).  So if the metrics for different
4758 		 * default routes are different, we may return the wrong
4759 		 * metrics.  This will not be a problem if the existing
4760 		 * bug is fixed.
4761 		 */
4762 		if (sire != NULL) {
4763 			ulp_info = &(sire->ire_uinfo);
4764 		}
4765 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
4766 			error = -1;
4767 			goto bad_addr;
4768 		}
4769 	} else if (ipsec_policy_set) {
4770 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4771 			error = -1;
4772 			goto bad_addr;
4773 		}
4774 	}
4775 
4776 	/*
4777 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
4778 	 * we'll cache that.  If we don't, we'll inherit global policy.
4779 	 *
4780 	 * We can't insert until the conn reflects the policy. Note that
4781 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
4782 	 * connections where we don't have a policy. This is to prevent
4783 	 * global policy lookups in the inbound path.
4784 	 *
4785 	 * If we insert before we set conn_policy_cached,
4786 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
4787 	 * because global policy cound be non-empty. We normally call
4788 	 * ipsec_check_policy() for conn_policy_cached connections only if
4789 	 * ipc_in_enforce_policy is set. But in this case,
4790 	 * conn_policy_cached can get set anytime since we made the
4791 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
4792 	 * called, which will make the above assumption false.  Thus, we
4793 	 * need to insert after we set conn_policy_cached.
4794 	 */
4795 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
4796 		goto bad_addr;
4797 
4798 	if (fanout_insert) {
4799 		/*
4800 		 * The addresses have been verified. Time to insert in
4801 		 * the correct fanout list.
4802 		 */
4803 		error = ipcl_conn_insert(connp, protocol, src_addr,
4804 		    dst_addr, connp->conn_ports);
4805 	}
4806 
4807 	if (error == 0) {
4808 		connp->conn_fully_bound = B_TRUE;
4809 		/*
4810 		 * Our initial checks for MDT have passed; the IRE is not
4811 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
4812 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
4813 		 * ip_mdinfo_return(), which performs further checks
4814 		 * against them and upon success, returns the MDT info
4815 		 * mblk which we will attach to the bind acknowledgment.
4816 		 */
4817 		if (md_dst_ire != NULL) {
4818 			mblk_t *mdinfo_mp;
4819 
4820 			ASSERT(md_ill != NULL);
4821 			ASSERT(md_ill->ill_mdt_capab != NULL);
4822 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
4823 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
4824 				linkb(mp, mdinfo_mp);
4825 		}
4826 	}
4827 bad_addr:
4828 	if (ipsec_policy_set) {
4829 		ASSERT(policy_mp == mp->b_cont);
4830 		ASSERT(policy_mp != NULL);
4831 		freeb(policy_mp);
4832 		/*
4833 		 * As of now assume that nothing else accompanies
4834 		 * IPSEC_POLICY_SET.
4835 		 */
4836 		mp->b_cont = NULL;
4837 	}
4838 	if (src_ire != NULL)
4839 		IRE_REFRELE(src_ire);
4840 	if (dst_ire != NULL)
4841 		IRE_REFRELE(dst_ire);
4842 	if (sire != NULL)
4843 		IRE_REFRELE(sire);
4844 	if (md_dst_ire != NULL)
4845 		IRE_REFRELE(md_dst_ire);
4846 	return (error);
4847 }
4848 
4849 /*
4850  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
4851  * Prefers dst_ire over src_ire.
4852  */
4853 static boolean_t
4854 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
4855 {
4856 	mblk_t	*mp1;
4857 	ire_t *ret_ire = NULL;
4858 
4859 	mp1 = mp->b_cont;
4860 	ASSERT(mp1 != NULL);
4861 
4862 	if (ire != NULL) {
4863 		/*
4864 		 * mp1 initialized above to IRE_DB_REQ_TYPE
4865 		 * appended mblk. Its <upper protocol>'s
4866 		 * job to make sure there is room.
4867 		 */
4868 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
4869 			return (0);
4870 
4871 		mp1->b_datap->db_type = IRE_DB_TYPE;
4872 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
4873 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
4874 		ret_ire = (ire_t *)mp1->b_rptr;
4875 		/*
4876 		 * Pass the latest setting of the ip_path_mtu_discovery and
4877 		 * copy the ulp info if any.
4878 		 */
4879 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
4880 		    IPH_DF : 0;
4881 		if (ulp_info != NULL) {
4882 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
4883 			    sizeof (iulp_t));
4884 		}
4885 		ret_ire->ire_mp = mp1;
4886 	} else {
4887 		/*
4888 		 * No IRE was found. Remove IRE mblk.
4889 		 */
4890 		mp->b_cont = mp1->b_cont;
4891 		freeb(mp1);
4892 	}
4893 
4894 	return (1);
4895 }
4896 
4897 /*
4898  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
4899  * the final piece where we don't.  Return a pointer to the first mblk in the
4900  * result, and update the pointer to the next mblk to chew on.  If anything
4901  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
4902  * NULL pointer.
4903  */
4904 mblk_t *
4905 ip_carve_mp(mblk_t **mpp, ssize_t len)
4906 {
4907 	mblk_t	*mp0;
4908 	mblk_t	*mp1;
4909 	mblk_t	*mp2;
4910 
4911 	if (!len || !mpp || !(mp0 = *mpp))
4912 		return (NULL);
4913 	/* If we aren't going to consume the first mblk, we need a dup. */
4914 	if (mp0->b_wptr - mp0->b_rptr > len) {
4915 		mp1 = dupb(mp0);
4916 		if (mp1) {
4917 			/* Partition the data between the two mblks. */
4918 			mp1->b_wptr = mp1->b_rptr + len;
4919 			mp0->b_rptr = mp1->b_wptr;
4920 			/*
4921 			 * after adjustments if mblk not consumed is now
4922 			 * unaligned, try to align it. If this fails free
4923 			 * all messages and let upper layer recover.
4924 			 */
4925 			if (!OK_32PTR(mp0->b_rptr)) {
4926 				if (!pullupmsg(mp0, -1)) {
4927 					freemsg(mp0);
4928 					freemsg(mp1);
4929 					*mpp = NULL;
4930 					return (NULL);
4931 				}
4932 			}
4933 		}
4934 		return (mp1);
4935 	}
4936 	/* Eat through as many mblks as we need to get len bytes. */
4937 	len -= mp0->b_wptr - mp0->b_rptr;
4938 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
4939 		if (mp2->b_wptr - mp2->b_rptr > len) {
4940 			/*
4941 			 * We won't consume the entire last mblk.  Like
4942 			 * above, dup and partition it.
4943 			 */
4944 			mp1->b_cont = dupb(mp2);
4945 			mp1 = mp1->b_cont;
4946 			if (!mp1) {
4947 				/*
4948 				 * Trouble.  Rather than go to a lot of
4949 				 * trouble to clean up, we free the messages.
4950 				 * This won't be any worse than losing it on
4951 				 * the wire.
4952 				 */
4953 				freemsg(mp0);
4954 				freemsg(mp2);
4955 				*mpp = NULL;
4956 				return (NULL);
4957 			}
4958 			mp1->b_wptr = mp1->b_rptr + len;
4959 			mp2->b_rptr = mp1->b_wptr;
4960 			/*
4961 			 * after adjustments if mblk not consumed is now
4962 			 * unaligned, try to align it. If this fails free
4963 			 * all messages and let upper layer recover.
4964 			 */
4965 			if (!OK_32PTR(mp2->b_rptr)) {
4966 				if (!pullupmsg(mp2, -1)) {
4967 					freemsg(mp0);
4968 					freemsg(mp2);
4969 					*mpp = NULL;
4970 					return (NULL);
4971 				}
4972 			}
4973 			*mpp = mp2;
4974 			return (mp0);
4975 		}
4976 		/* Decrement len by the amount we just got. */
4977 		len -= mp2->b_wptr - mp2->b_rptr;
4978 	}
4979 	/*
4980 	 * len should be reduced to zero now.  If not our caller has
4981 	 * screwed up.
4982 	 */
4983 	if (len) {
4984 		/* Shouldn't happen! */
4985 		freemsg(mp0);
4986 		*mpp = NULL;
4987 		return (NULL);
4988 	}
4989 	/*
4990 	 * We consumed up to exactly the end of an mblk.  Detach the part
4991 	 * we are returning from the rest of the chain.
4992 	 */
4993 	mp1->b_cont = NULL;
4994 	*mpp = mp2;
4995 	return (mp0);
4996 }
4997 
4998 /* The ill stream is being unplumbed. Called from ip_close */
4999 int
5000 ip_modclose(ill_t *ill)
5001 {
5002 
5003 	boolean_t success;
5004 	ipsq_t	*ipsq;
5005 	ipif_t	*ipif;
5006 	queue_t	*q = ill->ill_rq;
5007 
5008 	/*
5009 	 * Forcibly enter the ipsq after some delay. This is to take
5010 	 * care of the case when some ioctl does not complete because
5011 	 * we sent a control message to the driver and it did not
5012 	 * send us a reply. We want to be able to at least unplumb
5013 	 * and replumb rather than force the user to reboot the system.
5014 	 */
5015 	success = ipsq_enter(ill, B_FALSE);
5016 
5017 	/*
5018 	 * Open/close/push/pop is guaranteed to be single threaded
5019 	 * per stream by STREAMS. FS guarantees that all references
5020 	 * from top are gone before close is called. So there can't
5021 	 * be another close thread that has set CONDEMNED on this ill.
5022 	 * and cause ipsq_enter to return failure.
5023 	 */
5024 	ASSERT(success);
5025 	ipsq = ill->ill_phyint->phyint_ipsq;
5026 
5027 	/*
5028 	 * Mark it condemned. No new reference will be made to this ill.
5029 	 * Lookup functions will return an error. Threads that try to
5030 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5031 	 * that the refcnt will drop down to zero.
5032 	 */
5033 	mutex_enter(&ill->ill_lock);
5034 	ill->ill_state_flags |= ILL_CONDEMNED;
5035 	for (ipif = ill->ill_ipif; ipif != NULL;
5036 	    ipif = ipif->ipif_next) {
5037 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5038 	}
5039 	/*
5040 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5041 	 * returns  error if ILL_CONDEMNED is set
5042 	 */
5043 	cv_broadcast(&ill->ill_cv);
5044 	mutex_exit(&ill->ill_lock);
5045 
5046 	/*
5047 	 * Shut down fragmentation reassembly.
5048 	 * ill_frag_timer won't start a timer again.
5049 	 * Now cancel any existing timer
5050 	 */
5051 	(void) untimeout(ill->ill_frag_timer_id);
5052 	(void) ill_frag_timeout(ill, 0);
5053 
5054 	/*
5055 	 * If MOVE was in progress, clear the
5056 	 * move_in_progress fields also.
5057 	 */
5058 	if (ill->ill_move_in_progress) {
5059 		ILL_CLEAR_MOVE(ill);
5060 	}
5061 
5062 	/*
5063 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5064 	 * this ill. Then wait for the refcnts to drop to zero.
5065 	 * ill_is_quiescent checks whether the ill is really quiescent.
5066 	 * Then make sure that threads that are waiting to enter the
5067 	 * ipsq have seen the error returned by ipsq_enter and have
5068 	 * gone away. Then we call ill_delete_tail which does the
5069 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5070 	 */
5071 	ill_delete(ill);
5072 	mutex_enter(&ill->ill_lock);
5073 	while (!ill_is_quiescent(ill))
5074 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5075 	while (ill->ill_waiters)
5076 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5077 
5078 	mutex_exit(&ill->ill_lock);
5079 
5080 	/* qprocsoff is called in ill_delete_tail */
5081 	ill_delete_tail(ill);
5082 
5083 	/*
5084 	 * Walk through all upper (conn) streams and qenable
5085 	 * those that have queued data.
5086 	 * close synchronization needs this to
5087 	 * be done to ensure that all upper layers blocked
5088 	 * due to flow control to the closing device
5089 	 * get unblocked.
5090 	 */
5091 	ip1dbg(("ip_wsrv: walking\n"));
5092 	conn_walk_drain();
5093 
5094 	mutex_enter(&ip_mi_lock);
5095 	mi_close_unlink(&ip_g_head, (IDP)ill);
5096 	mutex_exit(&ip_mi_lock);
5097 
5098 	/*
5099 	 * credp could be null if the open didn't succeed and ip_modopen
5100 	 * itself calls ip_close.
5101 	 */
5102 	if (ill->ill_credp != NULL)
5103 		crfree(ill->ill_credp);
5104 
5105 	mi_close_free((IDP)ill);
5106 	q->q_ptr = WR(q)->q_ptr = NULL;
5107 
5108 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5109 
5110 	return (0);
5111 }
5112 
5113 /*
5114  * This is called as part of close() for both IP and UDP
5115  * in order to quiesce the conn.
5116  */
5117 void
5118 ip_quiesce_conn(conn_t *connp)
5119 {
5120 	boolean_t	drain_cleanup_reqd = B_FALSE;
5121 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5122 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5123 
5124 	ASSERT(!IPCL_IS_TCP(connp));
5125 
5126 	/*
5127 	 * Mark the conn as closing, and this conn must not be
5128 	 * inserted in future into any list. Eg. conn_drain_insert(),
5129 	 * won't insert this conn into the conn_drain_list.
5130 	 * Similarly ill_pending_mp_add() will not add any mp to
5131 	 * the pending mp list, after this conn has started closing.
5132 	 *
5133 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5134 	 * cannot get set henceforth.
5135 	 */
5136 	mutex_enter(&connp->conn_lock);
5137 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5138 	connp->conn_state_flags |= CONN_CLOSING;
5139 	if (connp->conn_idl != NULL)
5140 		drain_cleanup_reqd = B_TRUE;
5141 	if (connp->conn_oper_pending_ill != NULL)
5142 		conn_ioctl_cleanup_reqd = B_TRUE;
5143 	if (connp->conn_ilg_inuse != 0)
5144 		ilg_cleanup_reqd = B_TRUE;
5145 	mutex_exit(&connp->conn_lock);
5146 
5147 	if (IPCL_IS_UDP(connp))
5148 		udp_quiesce_conn(connp);
5149 
5150 	if (conn_ioctl_cleanup_reqd)
5151 		conn_ioctl_cleanup(connp);
5152 
5153 	if (is_system_labeled() && connp->conn_anon_port) {
5154 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5155 		    connp->conn_mlp_type, connp->conn_ulp,
5156 		    ntohs(connp->conn_lport), B_FALSE);
5157 		connp->conn_anon_port = 0;
5158 	}
5159 	connp->conn_mlp_type = mlptSingle;
5160 
5161 	/*
5162 	 * Remove this conn from any fanout list it is on.
5163 	 * and then wait for any threads currently operating
5164 	 * on this endpoint to finish
5165 	 */
5166 	ipcl_hash_remove(connp);
5167 
5168 	/*
5169 	 * Remove this conn from the drain list, and do
5170 	 * any other cleanup that may be required.
5171 	 * (Only non-tcp streams may have a non-null conn_idl.
5172 	 * TCP streams are never flow controlled, and
5173 	 * conn_idl will be null)
5174 	 */
5175 	if (drain_cleanup_reqd)
5176 		conn_drain_tail(connp, B_TRUE);
5177 
5178 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5179 		(void) ip_mrouter_done(NULL);
5180 
5181 	if (ilg_cleanup_reqd)
5182 		ilg_delete_all(connp);
5183 
5184 	conn_delete_ire(connp, NULL);
5185 
5186 	/*
5187 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5188 	 * callers from write side can't be there now because close
5189 	 * is in progress. The only other caller is ipcl_walk
5190 	 * which checks for the condemned flag.
5191 	 */
5192 	mutex_enter(&connp->conn_lock);
5193 	connp->conn_state_flags |= CONN_CONDEMNED;
5194 	while (connp->conn_ref != 1)
5195 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5196 	connp->conn_state_flags |= CONN_QUIESCED;
5197 	mutex_exit(&connp->conn_lock);
5198 }
5199 
5200 /* ARGSUSED */
5201 int
5202 ip_close(queue_t *q, int flags)
5203 {
5204 	conn_t		*connp;
5205 
5206 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5207 
5208 	/*
5209 	 * Call the appropriate delete routine depending on whether this is
5210 	 * a module or device.
5211 	 */
5212 	if (WR(q)->q_next != NULL) {
5213 		/* This is a module close */
5214 		return (ip_modclose((ill_t *)q->q_ptr));
5215 	}
5216 
5217 	connp = q->q_ptr;
5218 	ip_quiesce_conn(connp);
5219 
5220 	qprocsoff(q);
5221 
5222 	/*
5223 	 * Now we are truly single threaded on this stream, and can
5224 	 * delete the things hanging off the connp, and finally the connp.
5225 	 * We removed this connp from the fanout list, it cannot be
5226 	 * accessed thru the fanouts, and we already waited for the
5227 	 * conn_ref to drop to 0. We are already in close, so
5228 	 * there cannot be any other thread from the top. qprocsoff
5229 	 * has completed, and service has completed or won't run in
5230 	 * future.
5231 	 */
5232 	ASSERT(connp->conn_ref == 1);
5233 
5234 	/*
5235 	 * A conn which was previously marked as IPCL_UDP cannot
5236 	 * retain the flag because it would have been cleared by
5237 	 * udp_close().
5238 	 */
5239 	ASSERT(!IPCL_IS_UDP(connp));
5240 
5241 	if (connp->conn_latch != NULL) {
5242 		IPLATCH_REFRELE(connp->conn_latch);
5243 		connp->conn_latch = NULL;
5244 	}
5245 	if (connp->conn_policy != NULL) {
5246 		IPPH_REFRELE(connp->conn_policy);
5247 		connp->conn_policy = NULL;
5248 	}
5249 	if (connp->conn_ipsec_opt_mp != NULL) {
5250 		freemsg(connp->conn_ipsec_opt_mp);
5251 		connp->conn_ipsec_opt_mp = NULL;
5252 	}
5253 
5254 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5255 
5256 	connp->conn_ref--;
5257 	ipcl_conn_destroy(connp);
5258 
5259 	q->q_ptr = WR(q)->q_ptr = NULL;
5260 	return (0);
5261 }
5262 
5263 int
5264 ip_snmpmod_close(queue_t *q)
5265 {
5266 	conn_t *connp = Q_TO_CONN(q);
5267 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5268 
5269 	qprocsoff(q);
5270 
5271 	if (connp->conn_flags & IPCL_UDPMOD)
5272 		udp_close_free(connp);
5273 
5274 	if (connp->conn_cred != NULL) {
5275 		crfree(connp->conn_cred);
5276 		connp->conn_cred = NULL;
5277 	}
5278 	CONN_DEC_REF(connp);
5279 	q->q_ptr = WR(q)->q_ptr = NULL;
5280 	return (0);
5281 }
5282 
5283 /*
5284  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5285  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5286  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5287  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5288  * queues as we never enqueue messages there and we don't handle any ioctls.
5289  * Everything else is freed.
5290  */
5291 void
5292 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5293 {
5294 	conn_t	*connp = q->q_ptr;
5295 	pfi_t	setfn;
5296 	pfi_t	getfn;
5297 
5298 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5299 
5300 	switch (DB_TYPE(mp)) {
5301 	case M_PROTO:
5302 	case M_PCPROTO:
5303 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5304 		    ((((union T_primitives *)mp->b_rptr)->type ==
5305 			T_SVR4_OPTMGMT_REQ) ||
5306 		    (((union T_primitives *)mp->b_rptr)->type ==
5307 			T_OPTMGMT_REQ))) {
5308 			/*
5309 			 * This is the only TPI primitive supported. Its
5310 			 * handling does not require tcp_t, but it does require
5311 			 * conn_t to check permissions.
5312 			 */
5313 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5314 
5315 			if (connp->conn_flags & IPCL_TCPMOD) {
5316 				setfn = tcp_snmp_set;
5317 				getfn = tcp_snmp_get;
5318 			} else {
5319 				setfn = udp_snmp_set;
5320 				getfn = udp_snmp_get;
5321 			}
5322 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5323 				freemsg(mp);
5324 				return;
5325 			}
5326 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5327 		    != NULL)
5328 			qreply(q, mp);
5329 		break;
5330 	case M_FLUSH:
5331 	case M_IOCTL:
5332 		putnext(q, mp);
5333 		break;
5334 	default:
5335 		freemsg(mp);
5336 		break;
5337 	}
5338 }
5339 
5340 /* Return the IP checksum for the IP header at "iph". */
5341 uint16_t
5342 ip_csum_hdr(ipha_t *ipha)
5343 {
5344 	uint16_t	*uph;
5345 	uint32_t	sum;
5346 	int		opt_len;
5347 
5348 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5349 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5350 	uph = (uint16_t *)ipha;
5351 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5352 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5353 	if (opt_len > 0) {
5354 		do {
5355 			sum += uph[10];
5356 			sum += uph[11];
5357 			uph += 2;
5358 		} while (--opt_len);
5359 	}
5360 	sum = (sum & 0xFFFF) + (sum >> 16);
5361 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5362 	if (sum == 0xffff)
5363 		sum = 0;
5364 	return ((uint16_t)sum);
5365 }
5366 
5367 void
5368 ip_ddi_destroy(void)
5369 {
5370 	tnet_fini();
5371 	tcp_ddi_destroy();
5372 	sctp_ddi_destroy();
5373 	ipsec_loader_destroy();
5374 	ipsec_policy_destroy();
5375 	ipsec_kstat_destroy();
5376 	nd_free(&ip_g_nd);
5377 	mutex_destroy(&igmp_timer_lock);
5378 	mutex_destroy(&mld_timer_lock);
5379 	mutex_destroy(&igmp_slowtimeout_lock);
5380 	mutex_destroy(&mld_slowtimeout_lock);
5381 	mutex_destroy(&ip_mi_lock);
5382 	mutex_destroy(&rts_clients.connf_lock);
5383 	ip_ire_fini();
5384 	ip6_asp_free();
5385 	conn_drain_fini();
5386 	ipcl_destroy();
5387 	inet_minor_destroy(ip_minor_arena);
5388 	icmp_kstat_fini();
5389 	ip_kstat_fini();
5390 	rw_destroy(&ipsec_capab_ills_lock);
5391 	rw_destroy(&ill_g_usesrc_lock);
5392 	ip_drop_unregister(&ip_dropper);
5393 }
5394 
5395 
5396 void
5397 ip_ddi_init(void)
5398 {
5399 	TCP6_MAJ = ddi_name_to_major(TCP6);
5400 	TCP_MAJ	= ddi_name_to_major(TCP);
5401 	SCTP_MAJ = ddi_name_to_major(SCTP);
5402 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5403 
5404 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5405 
5406 	/* IP's IPsec code calls the packet dropper */
5407 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5408 
5409 	if (!ip_g_nd) {
5410 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5411 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5412 			nd_free(&ip_g_nd);
5413 		}
5414 	}
5415 
5416 	ipsec_loader_init();
5417 	ipsec_policy_init();
5418 	ipsec_kstat_init();
5419 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5420 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5421 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5422 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5423 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5424 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5425 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5426 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5427 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5428 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5429 
5430 	/*
5431 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5432 	 * initial devices: ip, ip6, tcp, tcp6.
5433 	 */
5434 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5435 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5436 		cmn_err(CE_PANIC,
5437 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5438 	}
5439 
5440 	ipcl_init();
5441 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5442 	ip_ire_init();
5443 	ip6_asp_init();
5444 	ipif_init();
5445 	conn_drain_init();
5446 	tcp_ddi_init();
5447 	sctp_ddi_init();
5448 
5449 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5450 
5451 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5452 		"net", KSTAT_TYPE_NAMED,
5453 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5454 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5455 		ip_kstat->ks_data = &ip_statistics;
5456 		kstat_install(ip_kstat);
5457 	}
5458 	ip_kstat_init();
5459 	ip6_kstat_init();
5460 	icmp_kstat_init();
5461 	ipsec_loader_start();
5462 	tnet_init();
5463 }
5464 
5465 /*
5466  * Allocate and initialize a DLPI template of the specified length.  (May be
5467  * called as writer.)
5468  */
5469 mblk_t *
5470 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5471 {
5472 	mblk_t	*mp;
5473 
5474 	mp = allocb(len, BPRI_MED);
5475 	if (!mp)
5476 		return (NULL);
5477 
5478 	/*
5479 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5480 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5481 	 * that other DLPI are M_PROTO.
5482 	 */
5483 	if (prim == DL_INFO_REQ) {
5484 		mp->b_datap->db_type = M_PCPROTO;
5485 	} else {
5486 		mp->b_datap->db_type = M_PROTO;
5487 	}
5488 
5489 	mp->b_wptr = mp->b_rptr + len;
5490 	bzero(mp->b_rptr, len);
5491 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5492 	return (mp);
5493 }
5494 
5495 const char *
5496 dlpi_prim_str(int prim)
5497 {
5498 	switch (prim) {
5499 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5500 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5501 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5502 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5503 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5504 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5505 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5506 	case DL_OK_ACK:		return ("DL_OK_ACK");
5507 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5508 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5509 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5510 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5511 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5512 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5513 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5514 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5515 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5516 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5517 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5518 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5519 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5520 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5521 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5522 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5523 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5524 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5525 	default:		return ("<unknown primitive>");
5526 	}
5527 }
5528 
5529 const char *
5530 dlpi_err_str(int err)
5531 {
5532 	switch (err) {
5533 	case DL_ACCESS:		return ("DL_ACCESS");
5534 	case DL_BADADDR:	return ("DL_BADADDR");
5535 	case DL_BADCORR:	return ("DL_BADCORR");
5536 	case DL_BADDATA:	return ("DL_BADDATA");
5537 	case DL_BADPPA:		return ("DL_BADPPA");
5538 	case DL_BADPRIM:	return ("DL_BADPRIM");
5539 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5540 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5541 	case DL_BADSAP:		return ("DL_BADSAP");
5542 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5543 	case DL_BOUND:		return ("DL_BOUND");
5544 	case DL_INITFAILED:	return ("DL_INITFAILED");
5545 	case DL_NOADDR:		return ("DL_NOADDR");
5546 	case DL_NOTINIT:	return ("DL_NOTINIT");
5547 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5548 	case DL_SYSERR:		return ("DL_SYSERR");
5549 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5550 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5551 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5552 	case DL_TOOMANY:	return ("DL_TOOMANY");
5553 	case DL_NOTENAB:	return ("DL_NOTENAB");
5554 	case DL_BUSY:		return ("DL_BUSY");
5555 	case DL_NOAUTO:		return ("DL_NOAUTO");
5556 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5557 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5558 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5559 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5560 	case DL_PENDING:	return ("DL_PENDING");
5561 	default:		return ("<unknown error>");
5562 	}
5563 }
5564 
5565 /*
5566  * Debug formatting routine.  Returns a character string representation of the
5567  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5568  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5569  */
5570 char *
5571 ip_dot_addr(ipaddr_t addr, char *buf)
5572 {
5573 	return (ip_dot_saddr((uchar_t *)&addr, buf));
5574 }
5575 
5576 /*
5577  * Debug formatting routine.  Returns a character string representation of the
5578  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5579  * as a pointer.  The "xxx" parts including left zero padding so the final
5580  * string will fit easily in tables.  It would be nice to take a padding
5581  * length argument instead.
5582  */
5583 static char *
5584 ip_dot_saddr(uchar_t *addr, char *buf)
5585 {
5586 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5587 	    addr[0] & 0xFF, addr[1] & 0xFF, addr[2] & 0xFF, addr[3] & 0xFF);
5588 	return (buf);
5589 }
5590 
5591 /*
5592  * Send an ICMP error after patching up the packet appropriately.  Returns
5593  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5594  */
5595 static boolean_t
5596 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5597     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5598 {
5599 	ipha_t *ipha;
5600 	mblk_t *first_mp;
5601 	boolean_t secure;
5602 	unsigned char db_type;
5603 
5604 	first_mp = mp;
5605 	if (mctl_present) {
5606 		mp = mp->b_cont;
5607 		secure = ipsec_in_is_secure(first_mp);
5608 		ASSERT(mp != NULL);
5609 	} else {
5610 		/*
5611 		 * If this is an ICMP error being reported - which goes
5612 		 * up as M_CTLs, we need to convert them to M_DATA till
5613 		 * we finish checking with global policy because
5614 		 * ipsec_check_global_policy() assumes M_DATA as clear
5615 		 * and M_CTL as secure.
5616 		 */
5617 		db_type = DB_TYPE(mp);
5618 		DB_TYPE(mp) = M_DATA;
5619 		secure = B_FALSE;
5620 	}
5621 	/*
5622 	 * We are generating an icmp error for some inbound packet.
5623 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
5624 	 * Before we generate an error, check with global policy
5625 	 * to see whether this is allowed to enter the system. As
5626 	 * there is no "conn", we are checking with global policy.
5627 	 */
5628 	ipha = (ipha_t *)mp->b_rptr;
5629 	if (secure || ipsec_inbound_v4_policy_present) {
5630 		first_mp = ipsec_check_global_policy(first_mp, NULL,
5631 		    ipha, NULL, mctl_present);
5632 		if (first_mp == NULL)
5633 			return (B_FALSE);
5634 	}
5635 
5636 	if (!mctl_present)
5637 		DB_TYPE(mp) = db_type;
5638 
5639 	if (flags & IP_FF_SEND_ICMP) {
5640 		if (flags & IP_FF_HDR_COMPLETE) {
5641 			if (ip_hdr_complete(ipha, zoneid)) {
5642 				freemsg(first_mp);
5643 				return (B_TRUE);
5644 			}
5645 		}
5646 		if (flags & IP_FF_CKSUM) {
5647 			/*
5648 			 * Have to correct checksum since
5649 			 * the packet might have been
5650 			 * fragmented and the reassembly code in ip_rput
5651 			 * does not restore the IP checksum.
5652 			 */
5653 			ipha->ipha_hdr_checksum = 0;
5654 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
5655 		}
5656 		switch (icmp_type) {
5657 		case ICMP_DEST_UNREACHABLE:
5658 			icmp_unreachable(WR(q), first_mp, icmp_code);
5659 			break;
5660 		default:
5661 			freemsg(first_mp);
5662 			break;
5663 		}
5664 	} else {
5665 		freemsg(first_mp);
5666 		return (B_FALSE);
5667 	}
5668 
5669 	return (B_TRUE);
5670 }
5671 
5672 /*
5673  * Used to send an ICMP error message when a packet is received for
5674  * a protocol that is not supported. The mblk passed as argument
5675  * is consumed by this function.
5676  */
5677 void
5678 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
5679 {
5680 	mblk_t *mp;
5681 	ipha_t *ipha;
5682 	ill_t *ill;
5683 	ipsec_in_t *ii;
5684 
5685 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5686 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5687 
5688 	mp = ipsec_mp->b_cont;
5689 	ipsec_mp->b_cont = NULL;
5690 	ipha = (ipha_t *)mp->b_rptr;
5691 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
5692 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
5693 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
5694 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
5695 		}
5696 	} else {
5697 		/* Get ill from index in ipsec_in_t. */
5698 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
5699 		    B_TRUE, NULL, NULL, NULL, NULL);
5700 		if (ill != NULL) {
5701 			if (ip_fanout_send_icmp_v6(q, mp, flags,
5702 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
5703 			    0, B_FALSE, zoneid)) {
5704 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
5705 			}
5706 
5707 			ill_refrele(ill);
5708 		} else { /* re-link for the freemsg() below. */
5709 			ipsec_mp->b_cont = mp;
5710 		}
5711 	}
5712 
5713 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
5714 	freemsg(ipsec_mp);
5715 }
5716 
5717 /*
5718  * See if the inbound datagram has had IPsec processing applied to it.
5719  */
5720 boolean_t
5721 ipsec_in_is_secure(mblk_t *ipsec_mp)
5722 {
5723 	ipsec_in_t *ii;
5724 
5725 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
5726 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
5727 
5728 	if (ii->ipsec_in_loopback) {
5729 		return (ii->ipsec_in_secure);
5730 	} else {
5731 		return (ii->ipsec_in_ah_sa != NULL ||
5732 		    ii->ipsec_in_esp_sa != NULL ||
5733 		    ii->ipsec_in_decaps);
5734 	}
5735 }
5736 
5737 /*
5738  * Handle protocols with which IP is less intimate.  There
5739  * can be more than one stream bound to a particular
5740  * protocol.  When this is the case, normally each one gets a copy
5741  * of any incoming packets.
5742  *
5743  * IPSEC NOTE :
5744  *
5745  * Don't allow a secure packet going up a non-secure connection.
5746  * We don't allow this because
5747  *
5748  * 1) Reply might go out in clear which will be dropped at
5749  *    the sending side.
5750  * 2) If the reply goes out in clear it will give the
5751  *    adversary enough information for getting the key in
5752  *    most of the cases.
5753  *
5754  * Moreover getting a secure packet when we expect clear
5755  * implies that SA's were added without checking for
5756  * policy on both ends. This should not happen once ISAKMP
5757  * is used to negotiate SAs as SAs will be added only after
5758  * verifying the policy.
5759  *
5760  * NOTE : If the packet was tunneled and not multicast we only send
5761  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
5762  * back to delivering packets to AF_INET6 raw sockets.
5763  *
5764  * IPQoS Notes:
5765  * Once we have determined the client, invoke IPPF processing.
5766  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
5767  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
5768  * ip_policy will be false.
5769  *
5770  * Zones notes:
5771  * Currently only applications in the global zone can create raw sockets for
5772  * protocols other than ICMP. So unlike the broadcast / multicast case of
5773  * ip_fanout_udp(), we only send a copy of the packet to streams in the
5774  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
5775  */
5776 static void
5777 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
5778     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
5779     zoneid_t zoneid)
5780 {
5781 	queue_t	*rq;
5782 	mblk_t	*mp1, *first_mp1;
5783 	uint_t	protocol = ipha->ipha_protocol;
5784 	ipaddr_t dst;
5785 	boolean_t one_only;
5786 	mblk_t *first_mp = mp;
5787 	boolean_t secure;
5788 	uint32_t ill_index;
5789 	conn_t	*connp, *first_connp, *next_connp;
5790 	connf_t	*connfp;
5791 	boolean_t shared_addr;
5792 
5793 	if (mctl_present) {
5794 		mp = first_mp->b_cont;
5795 		secure = ipsec_in_is_secure(first_mp);
5796 		ASSERT(mp != NULL);
5797 	} else {
5798 		secure = B_FALSE;
5799 	}
5800 	dst = ipha->ipha_dst;
5801 	/*
5802 	 * If the packet was tunneled and not multicast we only send to it
5803 	 * the first match.
5804 	 */
5805 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
5806 	    !CLASSD(dst));
5807 
5808 	shared_addr = (zoneid == ALL_ZONES);
5809 	if (shared_addr) {
5810 		/*
5811 		 * We don't allow multilevel ports for raw IP, so no need to
5812 		 * check for that here.
5813 		 */
5814 		zoneid = tsol_packet_to_zoneid(mp);
5815 	}
5816 
5817 	connfp = &ipcl_proto_fanout[protocol];
5818 	mutex_enter(&connfp->connf_lock);
5819 	connp = connfp->connf_head;
5820 	for (connp = connfp->connf_head; connp != NULL;
5821 		connp = connp->conn_next) {
5822 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
5823 		    zoneid) &&
5824 		    (!is_system_labeled() ||
5825 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
5826 		    connp)))
5827 			break;
5828 	}
5829 
5830 	if (connp == NULL || connp->conn_upq == NULL) {
5831 		/*
5832 		 * No one bound to these addresses.  Is
5833 		 * there a client that wants all
5834 		 * unclaimed datagrams?
5835 		 */
5836 		mutex_exit(&connfp->connf_lock);
5837 		/*
5838 		 * Check for IPPROTO_ENCAP...
5839 		 */
5840 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
5841 			/*
5842 			 * XXX If an IPsec mblk is here on a multicast
5843 			 * tunnel (using ip_mroute stuff), what should
5844 			 * I do?
5845 			 *
5846 			 * For now, just free the IPsec mblk before
5847 			 * passing it up to the multicast routing
5848 			 * stuff.
5849 			 *
5850 			 * BTW,  If I match a configured IP-in-IP
5851 			 * tunnel, ip_mroute_decap will never be
5852 			 * called.
5853 			 */
5854 			if (mp != first_mp)
5855 				freeb(first_mp);
5856 			ip_mroute_decap(q, mp);
5857 		} else {
5858 			/*
5859 			 * Otherwise send an ICMP protocol unreachable.
5860 			 */
5861 			if (ip_fanout_send_icmp(q, first_mp, flags,
5862 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
5863 			    mctl_present, zoneid)) {
5864 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
5865 			}
5866 		}
5867 		return;
5868 	}
5869 	CONN_INC_REF(connp);
5870 	first_connp = connp;
5871 
5872 	/*
5873 	 * Only send message to one tunnel driver by immediately
5874 	 * terminating the loop.
5875 	 */
5876 	connp = one_only ? NULL : connp->conn_next;
5877 
5878 	for (;;) {
5879 		while (connp != NULL) {
5880 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
5881 			    flags, zoneid) &&
5882 			    (!is_system_labeled() ||
5883 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
5884 			    shared_addr, connp)))
5885 				break;
5886 			connp = connp->conn_next;
5887 		}
5888 
5889 		/*
5890 		 * Copy the packet.
5891 		 */
5892 		if (connp == NULL || connp->conn_upq == NULL ||
5893 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
5894 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
5895 			/*
5896 			 * No more interested clients or memory
5897 			 * allocation failed
5898 			 */
5899 			connp = first_connp;
5900 			break;
5901 		}
5902 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
5903 		CONN_INC_REF(connp);
5904 		mutex_exit(&connfp->connf_lock);
5905 		rq = connp->conn_rq;
5906 		if (!canputnext(rq)) {
5907 			if (flags & IP_FF_RAWIP) {
5908 				BUMP_MIB(&ip_mib, rawipInOverflows);
5909 			} else {
5910 				BUMP_MIB(&icmp_mib, icmpInOverflows);
5911 			}
5912 
5913 			freemsg(first_mp1);
5914 		} else {
5915 			if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5916 				first_mp1 = ipsec_check_inbound_policy
5917 				    (first_mp1, connp, ipha, NULL,
5918 				    mctl_present);
5919 			}
5920 			if (first_mp1 != NULL) {
5921 				/*
5922 				 * ip_fanout_proto also gets called from
5923 				 * icmp_inbound_error_fanout, in which case
5924 				 * the msg type is M_CTL.  Don't add info
5925 				 * in this case for the time being. In future
5926 				 * when there is a need for knowing the
5927 				 * inbound iface index for ICMP error msgs,
5928 				 * then this can be changed.
5929 				 */
5930 				if ((connp->conn_recvif != 0) &&
5931 				    (mp->b_datap->db_type != M_CTL)) {
5932 					/*
5933 					 * the actual data will be
5934 					 * contained in b_cont upon
5935 					 * successful return of the
5936 					 * following call else
5937 					 * original mblk is returned
5938 					 */
5939 					ASSERT(recv_ill != NULL);
5940 					mp1 = ip_add_info(mp1, recv_ill,
5941 						IPF_RECVIF);
5942 				}
5943 				BUMP_MIB(&ip_mib, ipInDelivers);
5944 				if (mctl_present)
5945 					freeb(first_mp1);
5946 				putnext(rq, mp1);
5947 			}
5948 		}
5949 		mutex_enter(&connfp->connf_lock);
5950 		/* Follow the next pointer before releasing the conn. */
5951 		next_connp = connp->conn_next;
5952 		CONN_DEC_REF(connp);
5953 		connp = next_connp;
5954 	}
5955 
5956 	/* Last one.  Send it upstream. */
5957 	mutex_exit(&connfp->connf_lock);
5958 
5959 	/*
5960 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
5961 	 * will be set to false.
5962 	 */
5963 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
5964 		ill_index = ill->ill_phyint->phyint_ifindex;
5965 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
5966 		if (mp == NULL) {
5967 			CONN_DEC_REF(connp);
5968 			if (mctl_present) {
5969 				freeb(first_mp);
5970 			}
5971 			return;
5972 		}
5973 	}
5974 
5975 	rq = connp->conn_rq;
5976 	if (!canputnext(rq)) {
5977 		if (flags & IP_FF_RAWIP) {
5978 			BUMP_MIB(&ip_mib, rawipInOverflows);
5979 		} else {
5980 			BUMP_MIB(&icmp_mib, icmpInOverflows);
5981 		}
5982 
5983 		freemsg(first_mp);
5984 	} else {
5985 		if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
5986 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
5987 			    ipha, NULL, mctl_present);
5988 		}
5989 		if (first_mp != NULL) {
5990 			/*
5991 			 * ip_fanout_proto also gets called
5992 			 * from icmp_inbound_error_fanout, in
5993 			 * which case the msg type is M_CTL.
5994 			 * Don't add info in this case for time
5995 			 * being. In future when there is a
5996 			 * need for knowing the inbound iface
5997 			 * index for ICMP error msgs, then this
5998 			 * can be changed
5999 			 */
6000 			if ((connp->conn_recvif != 0) &&
6001 			    (mp->b_datap->db_type != M_CTL)) {
6002 				/*
6003 				 * the actual data will be contained in
6004 				 * b_cont upon successful return
6005 				 * of the following call else original
6006 				 * mblk is returned
6007 				 */
6008 				ASSERT(recv_ill != NULL);
6009 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6010 			}
6011 			BUMP_MIB(&ip_mib, ipInDelivers);
6012 			putnext(rq, mp);
6013 			if (mctl_present)
6014 				freeb(first_mp);
6015 		}
6016 	}
6017 	CONN_DEC_REF(connp);
6018 }
6019 
6020 /*
6021  * Fanout for TCP packets
6022  * The caller puts <fport, lport> in the ports parameter.
6023  *
6024  * IPQoS Notes
6025  * Before sending it to the client, invoke IPPF processing.
6026  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6027  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6028  * ip_policy is false.
6029  */
6030 static void
6031 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6032     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6033 {
6034 	mblk_t  *first_mp;
6035 	boolean_t secure;
6036 	uint32_t ill_index;
6037 	int	ip_hdr_len;
6038 	tcph_t	*tcph;
6039 	boolean_t syn_present = B_FALSE;
6040 	conn_t	*connp;
6041 
6042 	first_mp = mp;
6043 	if (mctl_present) {
6044 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6045 		mp = first_mp->b_cont;
6046 		secure = ipsec_in_is_secure(first_mp);
6047 		ASSERT(mp != NULL);
6048 	} else {
6049 		secure = B_FALSE;
6050 	}
6051 
6052 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6053 
6054 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6055 	    NULL) {
6056 		/*
6057 		 * No connected connection or listener. Send a
6058 		 * TH_RST via tcp_xmit_listeners_reset.
6059 		 */
6060 
6061 		/* Initiate IPPf processing, if needed. */
6062 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6063 			uint32_t ill_index;
6064 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6065 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6066 			if (first_mp == NULL)
6067 				return;
6068 		}
6069 		BUMP_MIB(&ip_mib, ipInDelivers);
6070 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6071 		    zoneid));
6072 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6073 		return;
6074 	}
6075 
6076 	/*
6077 	 * Allocate the SYN for the TCP connection here itself
6078 	 */
6079 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6080 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6081 		if (IPCL_IS_TCP(connp)) {
6082 			squeue_t *sqp;
6083 
6084 			/*
6085 			 * For fused tcp loopback, assign the eager's
6086 			 * squeue to be that of the active connect's.
6087 			 * Note that we don't check for IP_FF_LOOPBACK
6088 			 * here since this routine gets called only
6089 			 * for loopback (unlike the IPv6 counterpart).
6090 			 */
6091 			ASSERT(Q_TO_CONN(q) != NULL);
6092 			if (do_tcp_fusion &&
6093 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6094 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6095 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6096 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6097 				sqp = Q_TO_CONN(q)->conn_sqp;
6098 			} else {
6099 				sqp = IP_SQUEUE_GET(lbolt);
6100 			}
6101 
6102 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6103 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6104 			syn_present = B_TRUE;
6105 		}
6106 	}
6107 
6108 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6109 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6110 		if ((flags & TH_RST) || (flags & TH_URG)) {
6111 			CONN_DEC_REF(connp);
6112 			freemsg(first_mp);
6113 			return;
6114 		}
6115 		if (flags & TH_ACK) {
6116 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
6117 			CONN_DEC_REF(connp);
6118 			return;
6119 		}
6120 
6121 		CONN_DEC_REF(connp);
6122 		freemsg(first_mp);
6123 		return;
6124 	}
6125 
6126 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6127 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6128 		    NULL, mctl_present);
6129 		if (first_mp == NULL) {
6130 			CONN_DEC_REF(connp);
6131 			return;
6132 		}
6133 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6134 			ASSERT(syn_present);
6135 			if (mctl_present) {
6136 				ASSERT(first_mp != mp);
6137 				first_mp->b_datap->db_struioflag |=
6138 				    STRUIO_POLICY;
6139 			} else {
6140 				ASSERT(first_mp == mp);
6141 				mp->b_datap->db_struioflag &=
6142 				    ~STRUIO_EAGER;
6143 				mp->b_datap->db_struioflag |=
6144 				    STRUIO_POLICY;
6145 			}
6146 		} else {
6147 			/*
6148 			 * Discard first_mp early since we're dealing with a
6149 			 * fully-connected conn_t and tcp doesn't do policy in
6150 			 * this case.
6151 			 */
6152 			if (mctl_present) {
6153 				freeb(first_mp);
6154 				mctl_present = B_FALSE;
6155 			}
6156 			first_mp = mp;
6157 		}
6158 	}
6159 
6160 	/*
6161 	 * Initiate policy processing here if needed. If we get here from
6162 	 * icmp_inbound_error_fanout, ip_policy is false.
6163 	 */
6164 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6165 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6166 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6167 		if (mp == NULL) {
6168 			CONN_DEC_REF(connp);
6169 			if (mctl_present)
6170 				freeb(first_mp);
6171 			return;
6172 		} else if (mctl_present) {
6173 			ASSERT(first_mp != mp);
6174 			first_mp->b_cont = mp;
6175 		} else {
6176 			first_mp = mp;
6177 		}
6178 	}
6179 
6180 
6181 
6182 	/* Handle IPv6 socket options. */
6183 	if (!syn_present &&
6184 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6185 		/* Add header */
6186 		ASSERT(recv_ill != NULL);
6187 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6188 		if (mp == NULL) {
6189 			CONN_DEC_REF(connp);
6190 			if (mctl_present)
6191 				freeb(first_mp);
6192 			return;
6193 		} else if (mctl_present) {
6194 			/*
6195 			 * ip_add_info might return a new mp.
6196 			 */
6197 			ASSERT(first_mp != mp);
6198 			first_mp->b_cont = mp;
6199 		} else {
6200 			first_mp = mp;
6201 		}
6202 	}
6203 
6204 	BUMP_MIB(&ip_mib, ipInDelivers);
6205 	if (IPCL_IS_TCP(connp)) {
6206 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6207 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6208 	} else {
6209 		putnext(connp->conn_rq, first_mp);
6210 		CONN_DEC_REF(connp);
6211 	}
6212 }
6213 
6214 /*
6215  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6216  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6217  * Caller is responsible for dropping references to the conn, and freeing
6218  * first_mp.
6219  *
6220  * IPQoS Notes
6221  * Before sending it to the client, invoke IPPF processing. Policy processing
6222  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6223  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6224  * ip_wput_local, ip_policy is false.
6225  */
6226 static void
6227 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6228     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6229     boolean_t ip_policy)
6230 {
6231 	boolean_t	mctl_present = (first_mp != NULL);
6232 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6233 	uint32_t	ill_index;
6234 
6235 	if (mctl_present)
6236 		first_mp->b_cont = mp;
6237 	else
6238 		first_mp = mp;
6239 
6240 	if (CONN_UDP_FLOWCTLD(connp)) {
6241 		BUMP_MIB(&ip_mib, udpInOverflows);
6242 		freemsg(first_mp);
6243 		return;
6244 	}
6245 
6246 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6247 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6248 		    NULL, mctl_present);
6249 		if (first_mp == NULL)
6250 			return;	/* Freed by ipsec_check_inbound_policy(). */
6251 	}
6252 	if (mctl_present)
6253 		freeb(first_mp);
6254 
6255 	if (connp->conn_recvif)
6256 		in_flags = IPF_RECVIF;
6257 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6258 		in_flags |= IPF_RECVSLLA;
6259 
6260 	/* Handle IPv6 options. */
6261 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6262 		in_flags |= IPF_RECVIF;
6263 
6264 	/*
6265 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6266 	 * freed if the packet is dropped. The caller will do so.
6267 	 */
6268 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6269 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6270 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6271 		if (mp == NULL) {
6272 			return;
6273 		}
6274 	}
6275 	if ((in_flags != 0) &&
6276 	    (mp->b_datap->db_type != M_CTL)) {
6277 		/*
6278 		 * The actual data will be contained in b_cont
6279 		 * upon successful return of the following call
6280 		 * else original mblk is returned
6281 		 */
6282 		ASSERT(recv_ill != NULL);
6283 		mp = ip_add_info(mp, recv_ill, in_flags);
6284 	}
6285 	BUMP_MIB(&ip_mib, ipInDelivers);
6286 
6287 	/* Send it upstream */
6288 	CONN_UDP_RECV(connp, mp);
6289 }
6290 
6291 /*
6292  * Fanout for UDP packets.
6293  * The caller puts <fport, lport> in the ports parameter.
6294  *
6295  * If SO_REUSEADDR is set all multicast and broadcast packets
6296  * will be delivered to all streams bound to the same port.
6297  *
6298  * Zones notes:
6299  * Multicast and broadcast packets will be distributed to streams in all zones.
6300  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6301  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6302  * packets. To maintain this behavior with multiple zones, the conns are grouped
6303  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6304  * each zone. If unset, all the following conns in the same zone are skipped.
6305  */
6306 static void
6307 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6308     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6309     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6310 {
6311 	uint32_t	dstport, srcport;
6312 	ipaddr_t	dst;
6313 	mblk_t		*first_mp;
6314 	boolean_t	secure;
6315 	in6_addr_t	v6src;
6316 	conn_t		*connp;
6317 	connf_t		*connfp;
6318 	conn_t		*first_connp;
6319 	conn_t		*next_connp;
6320 	mblk_t		*mp1, *first_mp1;
6321 	ipaddr_t	src;
6322 	zoneid_t	last_zoneid;
6323 	boolean_t	reuseaddr;
6324 	boolean_t	shared_addr;
6325 
6326 	first_mp = mp;
6327 	if (mctl_present) {
6328 		mp = first_mp->b_cont;
6329 		first_mp->b_cont = NULL;
6330 		secure = ipsec_in_is_secure(first_mp);
6331 		ASSERT(mp != NULL);
6332 	} else {
6333 		first_mp = NULL;
6334 		secure = B_FALSE;
6335 	}
6336 
6337 	/* Extract ports in net byte order */
6338 	dstport = htons(ntohl(ports) & 0xFFFF);
6339 	srcport = htons(ntohl(ports) >> 16);
6340 	dst = ipha->ipha_dst;
6341 	src = ipha->ipha_src;
6342 
6343 	shared_addr = (zoneid == ALL_ZONES);
6344 	if (shared_addr) {
6345 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6346 		if (zoneid == ALL_ZONES)
6347 			zoneid = tsol_packet_to_zoneid(mp);
6348 	}
6349 
6350 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6351 	mutex_enter(&connfp->connf_lock);
6352 	connp = connfp->connf_head;
6353 	if (!broadcast && !CLASSD(dst)) {
6354 		/*
6355 		 * Not broadcast or multicast. Send to the one (first)
6356 		 * client we find. No need to check conn_wantpacket()
6357 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6358 		 * IPv4 unicast packets.
6359 		 */
6360 		while ((connp != NULL) &&
6361 		    (!IPCL_UDP_MATCH(connp, dstport, dst,
6362 		    srcport, src) ||
6363 		    (connp->conn_zoneid != zoneid && !connp->conn_allzones))) {
6364 			connp = connp->conn_next;
6365 		}
6366 
6367 		if (connp == NULL || connp->conn_upq == NULL)
6368 			goto notfound;
6369 
6370 		if (is_system_labeled() &&
6371 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6372 		    connp))
6373 			goto notfound;
6374 
6375 		CONN_INC_REF(connp);
6376 		mutex_exit(&connfp->connf_lock);
6377 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6378 		    recv_ill, ip_policy);
6379 		IP_STAT(ip_udp_fannorm);
6380 		CONN_DEC_REF(connp);
6381 		return;
6382 	}
6383 
6384 	/*
6385 	 * Broadcast and multicast case
6386 	 *
6387 	 * Need to check conn_wantpacket().
6388 	 * If SO_REUSEADDR has been set on the first we send the
6389 	 * packet to all clients that have joined the group and
6390 	 * match the port.
6391 	 */
6392 
6393 	while (connp != NULL) {
6394 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6395 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6396 		    (!is_system_labeled() ||
6397 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6398 		    connp)))
6399 			break;
6400 		connp = connp->conn_next;
6401 	}
6402 
6403 	if (connp == NULL || connp->conn_upq == NULL)
6404 		goto notfound;
6405 
6406 	first_connp = connp;
6407 	/*
6408 	 * When SO_REUSEADDR is not set, send the packet only to the first
6409 	 * matching connection in its zone by keeping track of the zoneid.
6410 	 */
6411 	reuseaddr = first_connp->conn_reuseaddr;
6412 	last_zoneid = first_connp->conn_zoneid;
6413 
6414 	CONN_INC_REF(connp);
6415 	connp = connp->conn_next;
6416 	for (;;) {
6417 		while (connp != NULL) {
6418 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6419 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6420 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6421 			    (!is_system_labeled() ||
6422 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6423 			    shared_addr, connp)))
6424 				break;
6425 			connp = connp->conn_next;
6426 		}
6427 		/*
6428 		 * Just copy the data part alone. The mctl part is
6429 		 * needed just for verifying policy and it is never
6430 		 * sent up.
6431 		 */
6432 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6433 		    ((mp1 = copymsg(mp)) == NULL))) {
6434 			/*
6435 			 * No more interested clients or memory
6436 			 * allocation failed
6437 			 */
6438 			connp = first_connp;
6439 			break;
6440 		}
6441 		if (connp->conn_zoneid != last_zoneid) {
6442 			/*
6443 			 * Update the zoneid so that the packet isn't sent to
6444 			 * any more conns in the same zone unless SO_REUSEADDR
6445 			 * is set.
6446 			 */
6447 			reuseaddr = connp->conn_reuseaddr;
6448 			last_zoneid = connp->conn_zoneid;
6449 		}
6450 		if (first_mp != NULL) {
6451 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6452 			    ipsec_info_type == IPSEC_IN);
6453 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6454 			if (first_mp1 == NULL) {
6455 				freemsg(mp1);
6456 				connp = first_connp;
6457 				break;
6458 			}
6459 		} else {
6460 			first_mp1 = NULL;
6461 		}
6462 		CONN_INC_REF(connp);
6463 		mutex_exit(&connfp->connf_lock);
6464 		/*
6465 		 * IPQoS notes: We don't send the packet for policy
6466 		 * processing here, will do it for the last one (below).
6467 		 * i.e. we do it per-packet now, but if we do policy
6468 		 * processing per-conn, then we would need to do it
6469 		 * here too.
6470 		 */
6471 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6472 		    ipha, flags, recv_ill, B_FALSE);
6473 		mutex_enter(&connfp->connf_lock);
6474 		/* Follow the next pointer before releasing the conn. */
6475 		next_connp = connp->conn_next;
6476 		IP_STAT(ip_udp_fanmb);
6477 		CONN_DEC_REF(connp);
6478 		connp = next_connp;
6479 	}
6480 
6481 	/* Last one.  Send it upstream. */
6482 	mutex_exit(&connfp->connf_lock);
6483 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6484 	    ip_policy);
6485 	IP_STAT(ip_udp_fanmb);
6486 	CONN_DEC_REF(connp);
6487 	return;
6488 
6489 notfound:
6490 
6491 	mutex_exit(&connfp->connf_lock);
6492 	IP_STAT(ip_udp_fanothers);
6493 	/*
6494 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6495 	 * have already been matched above, since they live in the IPv4
6496 	 * fanout tables. This implies we only need to
6497 	 * check for IPv6 in6addr_any endpoints here.
6498 	 * Thus we compare using ipv6_all_zeros instead of the destination
6499 	 * address, except for the multicast group membership lookup which
6500 	 * uses the IPv4 destination.
6501 	 */
6502 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6503 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6504 	mutex_enter(&connfp->connf_lock);
6505 	connp = connfp->connf_head;
6506 	if (!broadcast && !CLASSD(dst)) {
6507 		while (connp != NULL) {
6508 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6509 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6510 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6511 			    !connp->conn_ipv6_v6only)
6512 				break;
6513 			connp = connp->conn_next;
6514 		}
6515 
6516 		if (connp != NULL && is_system_labeled() &&
6517 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6518 		    connp))
6519 			connp = NULL;
6520 
6521 		if (connp == NULL || connp->conn_upq == NULL) {
6522 			/*
6523 			 * No one bound to this port.  Is
6524 			 * there a client that wants all
6525 			 * unclaimed datagrams?
6526 			 */
6527 			mutex_exit(&connfp->connf_lock);
6528 
6529 			if (mctl_present)
6530 				first_mp->b_cont = mp;
6531 			else
6532 				first_mp = mp;
6533 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6534 				ip_fanout_proto(q, first_mp, ill, ipha,
6535 				    flags | IP_FF_RAWIP, mctl_present,
6536 				    ip_policy, recv_ill, zoneid);
6537 			} else {
6538 				if (ip_fanout_send_icmp(q, first_mp, flags,
6539 				    ICMP_DEST_UNREACHABLE,
6540 				    ICMP_PORT_UNREACHABLE,
6541 				    mctl_present, zoneid)) {
6542 					BUMP_MIB(&ip_mib, udpNoPorts);
6543 				}
6544 			}
6545 			return;
6546 		}
6547 
6548 		CONN_INC_REF(connp);
6549 		mutex_exit(&connfp->connf_lock);
6550 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6551 		    recv_ill, ip_policy);
6552 		CONN_DEC_REF(connp);
6553 		return;
6554 	}
6555 	/*
6556 	 * IPv4 multicast packet being delivered to an AF_INET6
6557 	 * in6addr_any endpoint.
6558 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6559 	 * and not conn_wantpacket_v6() since any multicast membership is
6560 	 * for an IPv4-mapped multicast address.
6561 	 * The packet is sent to all clients in all zones that have joined the
6562 	 * group and match the port.
6563 	 */
6564 	while (connp != NULL) {
6565 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6566 		    srcport, v6src) &&
6567 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6568 		    (!is_system_labeled() ||
6569 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6570 		    connp)))
6571 			break;
6572 		connp = connp->conn_next;
6573 	}
6574 
6575 	if (connp == NULL || connp->conn_upq == NULL) {
6576 		/*
6577 		 * No one bound to this port.  Is
6578 		 * there a client that wants all
6579 		 * unclaimed datagrams?
6580 		 */
6581 		mutex_exit(&connfp->connf_lock);
6582 
6583 		if (mctl_present)
6584 			first_mp->b_cont = mp;
6585 		else
6586 			first_mp = mp;
6587 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6588 			ip_fanout_proto(q, first_mp, ill, ipha,
6589 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
6590 			    recv_ill, zoneid);
6591 		} else {
6592 			/*
6593 			 * We used to attempt to send an icmp error here, but
6594 			 * since this is known to be a multicast packet
6595 			 * and we don't send icmp errors in response to
6596 			 * multicast, just drop the packet and give up sooner.
6597 			 */
6598 			BUMP_MIB(&ip_mib, udpNoPorts);
6599 			freemsg(first_mp);
6600 		}
6601 		return;
6602 	}
6603 
6604 	first_connp = connp;
6605 
6606 	CONN_INC_REF(connp);
6607 	connp = connp->conn_next;
6608 	for (;;) {
6609 		while (connp != NULL) {
6610 			if (IPCL_UDP_MATCH_V6(connp, dstport,
6611 			    ipv6_all_zeros, srcport, v6src) &&
6612 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6613 			    (!is_system_labeled() ||
6614 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6615 			    shared_addr, connp)))
6616 				break;
6617 			connp = connp->conn_next;
6618 		}
6619 		/*
6620 		 * Just copy the data part alone. The mctl part is
6621 		 * needed just for verifying policy and it is never
6622 		 * sent up.
6623 		 */
6624 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6625 		    ((mp1 = copymsg(mp)) == NULL))) {
6626 			/*
6627 			 * No more intested clients or memory
6628 			 * allocation failed
6629 			 */
6630 			connp = first_connp;
6631 			break;
6632 		}
6633 		if (first_mp != NULL) {
6634 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6635 			    ipsec_info_type == IPSEC_IN);
6636 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6637 			if (first_mp1 == NULL) {
6638 				freemsg(mp1);
6639 				connp = first_connp;
6640 				break;
6641 			}
6642 		} else {
6643 			first_mp1 = NULL;
6644 		}
6645 		CONN_INC_REF(connp);
6646 		mutex_exit(&connfp->connf_lock);
6647 		/*
6648 		 * IPQoS notes: We don't send the packet for policy
6649 		 * processing here, will do it for the last one (below).
6650 		 * i.e. we do it per-packet now, but if we do policy
6651 		 * processing per-conn, then we would need to do it
6652 		 * here too.
6653 		 */
6654 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6655 		    ipha, flags, recv_ill, B_FALSE);
6656 		mutex_enter(&connfp->connf_lock);
6657 		/* Follow the next pointer before releasing the conn. */
6658 		next_connp = connp->conn_next;
6659 		CONN_DEC_REF(connp);
6660 		connp = next_connp;
6661 	}
6662 
6663 	/* Last one.  Send it upstream. */
6664 	mutex_exit(&connfp->connf_lock);
6665 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6666 	    ip_policy);
6667 	CONN_DEC_REF(connp);
6668 }
6669 
6670 /*
6671  * Complete the ip_wput header so that it
6672  * is possible to generate ICMP
6673  * errors.
6674  */
6675 static int
6676 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
6677 {
6678 	ire_t *ire;
6679 
6680 	if (ipha->ipha_src == INADDR_ANY) {
6681 		ire = ire_lookup_local(zoneid);
6682 		if (ire == NULL) {
6683 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
6684 			return (1);
6685 		}
6686 		ipha->ipha_src = ire->ire_addr;
6687 		ire_refrele(ire);
6688 	}
6689 	ipha->ipha_ttl = ip_def_ttl;
6690 	ipha->ipha_hdr_checksum = 0;
6691 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6692 	return (0);
6693 }
6694 
6695 /*
6696  * Nobody should be sending
6697  * packets up this stream
6698  */
6699 static void
6700 ip_lrput(queue_t *q, mblk_t *mp)
6701 {
6702 	mblk_t *mp1;
6703 
6704 	switch (mp->b_datap->db_type) {
6705 	case M_FLUSH:
6706 		/* Turn around */
6707 		if (*mp->b_rptr & FLUSHW) {
6708 			*mp->b_rptr &= ~FLUSHR;
6709 			qreply(q, mp);
6710 			return;
6711 		}
6712 		break;
6713 	}
6714 	/* Could receive messages that passed through ar_rput */
6715 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
6716 		mp1->b_prev = mp1->b_next = NULL;
6717 	freemsg(mp);
6718 }
6719 
6720 /* Nobody should be sending packets down this stream */
6721 /* ARGSUSED */
6722 void
6723 ip_lwput(queue_t *q, mblk_t *mp)
6724 {
6725 	freemsg(mp);
6726 }
6727 
6728 /*
6729  * Move the first hop in any source route to ipha_dst and remove that part of
6730  * the source route.  Called by other protocols.  Errors in option formatting
6731  * are ignored - will be handled by ip_wput_options Return the final
6732  * destination (either ipha_dst or the last entry in a source route.)
6733  */
6734 ipaddr_t
6735 ip_massage_options(ipha_t *ipha)
6736 {
6737 	ipoptp_t	opts;
6738 	uchar_t		*opt;
6739 	uint8_t		optval;
6740 	uint8_t		optlen;
6741 	ipaddr_t	dst;
6742 	int		i;
6743 	ire_t		*ire;
6744 
6745 	ip2dbg(("ip_massage_options\n"));
6746 	dst = ipha->ipha_dst;
6747 	for (optval = ipoptp_first(&opts, ipha);
6748 	    optval != IPOPT_EOL;
6749 	    optval = ipoptp_next(&opts)) {
6750 		opt = opts.ipoptp_cur;
6751 		switch (optval) {
6752 			uint8_t off;
6753 		case IPOPT_SSRR:
6754 		case IPOPT_LSRR:
6755 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
6756 				ip1dbg(("ip_massage_options: bad src route\n"));
6757 				break;
6758 			}
6759 			optlen = opts.ipoptp_len;
6760 			off = opt[IPOPT_OFFSET];
6761 			off--;
6762 		redo_srr:
6763 			if (optlen < IP_ADDR_LEN ||
6764 			    off > optlen - IP_ADDR_LEN) {
6765 				/* End of source route */
6766 				ip1dbg(("ip_massage_options: end of SR\n"));
6767 				break;
6768 			}
6769 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
6770 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
6771 			    ntohl(dst)));
6772 			/*
6773 			 * Check if our address is present more than
6774 			 * once as consecutive hops in source route.
6775 			 * XXX verify per-interface ip_forwarding
6776 			 * for source route?
6777 			 */
6778 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
6779 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
6780 			if (ire != NULL) {
6781 				ire_refrele(ire);
6782 				off += IP_ADDR_LEN;
6783 				goto redo_srr;
6784 			}
6785 			if (dst == htonl(INADDR_LOOPBACK)) {
6786 				ip1dbg(("ip_massage_options: loopback addr in "
6787 				    "source route!\n"));
6788 				break;
6789 			}
6790 			/*
6791 			 * Update ipha_dst to be the first hop and remove the
6792 			 * first hop from the source route (by overwriting
6793 			 * part of the option with NOP options).
6794 			 */
6795 			ipha->ipha_dst = dst;
6796 			/* Put the last entry in dst */
6797 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
6798 			    3;
6799 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
6800 
6801 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
6802 			    ntohl(dst)));
6803 			/* Move down and overwrite */
6804 			opt[IP_ADDR_LEN] = opt[0];
6805 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
6806 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
6807 			for (i = 0; i < IP_ADDR_LEN; i++)
6808 				opt[i] = IPOPT_NOP;
6809 			break;
6810 		}
6811 	}
6812 	return (dst);
6813 }
6814 
6815 /*
6816  * This function's job is to forward data to the reverse tunnel (FA->HA)
6817  * after doing a few checks. It is assumed that the incoming interface
6818  * of the packet is always different than the outgoing interface and the
6819  * ire_type of the found ire has to be a non-resolver type.
6820  *
6821  * IPQoS notes
6822  * IP policy is invoked twice for a forwarded packet, once on the read side
6823  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
6824  * enabled.
6825  */
6826 static void
6827 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
6828 {
6829 	ipha_t		*ipha;
6830 	queue_t		*q;
6831 	uint32_t 	pkt_len;
6832 #define	rptr    ((uchar_t *)ipha)
6833 	uint32_t 	sum;
6834 	uint32_t 	max_frag;
6835 	mblk_t		*first_mp;
6836 	uint32_t	ill_index;
6837 
6838 	ASSERT(ire != NULL);
6839 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
6840 	ASSERT(ire->ire_stq != NULL);
6841 
6842 	/* Initiate read side IPPF processing */
6843 	if (IPP_ENABLED(IPP_FWD_IN)) {
6844 		ill_index = in_ill->ill_phyint->phyint_ifindex;
6845 		ip_process(IPP_FWD_IN, &mp, ill_index);
6846 		if (mp == NULL) {
6847 			ip2dbg(("ip_mrtun_forward: inbound pkt "
6848 			    "dropped during IPPF processing\n"));
6849 			return;
6850 		}
6851 	}
6852 
6853 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
6854 		ILLF_ROUTER) == 0) ||
6855 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
6856 		BUMP_MIB(&ip_mib, ipForwProhibits);
6857 		ip0dbg(("ip_mrtun_forward: Can't forward :"
6858 		    "forwarding is not turned on\n"));
6859 		goto drop_pkt;
6860 	}
6861 
6862 	/*
6863 	 * Don't forward if the interface is down
6864 	 */
6865 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
6866 		BUMP_MIB(&ip_mib, ipInDiscards);
6867 		goto drop_pkt;
6868 	}
6869 
6870 	ipha = (ipha_t *)mp->b_rptr;
6871 	pkt_len = ntohs(ipha->ipha_length);
6872 	/* Adjust the checksum to reflect the ttl decrement. */
6873 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
6874 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
6875 	if (ipha->ipha_ttl-- <= 1) {
6876 		if (ip_csum_hdr(ipha)) {
6877 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6878 			goto drop_pkt;
6879 		}
6880 		q = ire->ire_stq;
6881 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6882 		    BPRI_HI)) == NULL) {
6883 			goto drop_pkt;
6884 		}
6885 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6886 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED);
6887 
6888 		return;
6889 	}
6890 
6891 	/* Get the ill_index of the ILL */
6892 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
6893 
6894 	/*
6895 	 * ip_mrtun_forward is only used by foreign agent to reverse
6896 	 * tunnel the incoming packet. So it does not do any option
6897 	 * processing for source routing.
6898 	 */
6899 	max_frag = ire->ire_max_frag;
6900 	if (pkt_len > max_frag) {
6901 		/*
6902 		 * It needs fragging on its way out.  We haven't
6903 		 * verified the header checksum yet.  Since we
6904 		 * are going to put a surely good checksum in the
6905 		 * outgoing header, we have to make sure that it
6906 		 * was good coming in.
6907 		 */
6908 		if (ip_csum_hdr(ipha)) {
6909 			BUMP_MIB(&ip_mib, ipInCksumErrs);
6910 			goto drop_pkt;
6911 		}
6912 
6913 		/* Initiate write side IPPF processing */
6914 		if (IPP_ENABLED(IPP_FWD_OUT)) {
6915 			ip_process(IPP_FWD_OUT, &mp, ill_index);
6916 			if (mp == NULL) {
6917 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
6918 				    "dropped/deferred during ip policy "\
6919 				    "processing\n"));
6920 				return;
6921 			}
6922 		}
6923 		if ((first_mp = allocb(sizeof (ipsec_info_t),
6924 		    BPRI_HI)) == NULL) {
6925 			goto drop_pkt;
6926 		}
6927 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
6928 		mp = first_mp;
6929 
6930 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
6931 		return;
6932 	}
6933 
6934 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
6935 
6936 	ASSERT(ire->ire_ipif != NULL);
6937 
6938 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
6939 	if (mp == NULL) {
6940 		BUMP_MIB(&ip_mib, ipInDiscards);
6941 		return;
6942 	}
6943 
6944 	/* Now send the packet to the tunnel interface */
6945 	q = ire->ire_stq;
6946 	UPDATE_IB_PKT_COUNT(ire);
6947 	ire->ire_last_used_time = lbolt;
6948 	BUMP_MIB(&ip_mib, ipForwDatagrams);
6949 	putnext(q, mp);
6950 	ip2dbg(("ip_mrtun_forward: sent packet to ill %p\n", q->q_ptr));
6951 	return;
6952 
6953 drop_pkt:;
6954 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
6955 	freemsg(mp);
6956 #undef	rptr
6957 }
6958 
6959 /*
6960  * Fills the ipsec_out_t data structure with appropriate fields and
6961  * prepends it to mp which contains the IP hdr + data that was meant
6962  * to be forwarded. Please note that ipsec_out_info data structure
6963  * is used here to communicate the outgoing ill path at ip_wput()
6964  * for the ICMP error packet. This has nothing to do with ipsec IP
6965  * security. ipsec_out_t is really used to pass the info to the module
6966  * IP where this information cannot be extracted from conn.
6967  * This functions is called by ip_mrtun_forward().
6968  */
6969 void
6970 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
6971 {
6972 	ipsec_out_t	*io;
6973 
6974 	ASSERT(xmit_ill != NULL);
6975 	first_mp->b_datap->db_type = M_CTL;
6976 	first_mp->b_wptr += sizeof (ipsec_info_t);
6977 	/*
6978 	 * This is to pass info to ip_wput in absence of conn.
6979 	 * ipsec_out_secure will be B_FALSE because of this.
6980 	 * Thus ipsec_out_secure being B_FALSE indicates that
6981 	 * this is not IPSEC security related information.
6982 	 */
6983 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
6984 	io = (ipsec_out_t *)first_mp->b_rptr;
6985 	io->ipsec_out_type = IPSEC_OUT;
6986 	io->ipsec_out_len = sizeof (ipsec_out_t);
6987 	first_mp->b_cont = mp;
6988 	io->ipsec_out_ill_index =
6989 	    xmit_ill->ill_phyint->phyint_ifindex;
6990 	io->ipsec_out_xmit_if = B_TRUE;
6991 }
6992 
6993 /*
6994  * Return the network mask
6995  * associated with the specified address.
6996  */
6997 ipaddr_t
6998 ip_net_mask(ipaddr_t addr)
6999 {
7000 	uchar_t	*up = (uchar_t *)&addr;
7001 	ipaddr_t mask = 0;
7002 	uchar_t	*maskp = (uchar_t *)&mask;
7003 
7004 #if defined(__i386) || defined(__amd64)
7005 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7006 #endif
7007 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7008 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7009 #endif
7010 	if (CLASSD(addr)) {
7011 		maskp[0] = 0xF0;
7012 		return (mask);
7013 	}
7014 	if (addr == 0)
7015 		return (0);
7016 	maskp[0] = 0xFF;
7017 	if ((up[0] & 0x80) == 0)
7018 		return (mask);
7019 
7020 	maskp[1] = 0xFF;
7021 	if ((up[0] & 0xC0) == 0x80)
7022 		return (mask);
7023 
7024 	maskp[2] = 0xFF;
7025 	if ((up[0] & 0xE0) == 0xC0)
7026 		return (mask);
7027 
7028 	/* Must be experimental or multicast, indicate as much */
7029 	return ((ipaddr_t)0);
7030 }
7031 
7032 /*
7033  * Select an ill for the packet by considering load spreading across
7034  * a different ill in the group if dst_ill is part of some group.
7035  */
7036 static ill_t *
7037 ip_newroute_get_dst_ill(ill_t *dst_ill)
7038 {
7039 	ill_t *ill;
7040 
7041 	/*
7042 	 * We schedule irrespective of whether the source address is
7043 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7044 	 */
7045 	ill = illgrp_scheduler(dst_ill);
7046 	if (ill == NULL)
7047 		return (NULL);
7048 
7049 	/*
7050 	 * For groups with names ip_sioctl_groupname ensures that all
7051 	 * ills are of same type. For groups without names, ifgrp_insert
7052 	 * ensures this.
7053 	 */
7054 	ASSERT(dst_ill->ill_type == ill->ill_type);
7055 
7056 	return (ill);
7057 }
7058 
7059 /*
7060  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7061  */
7062 ill_t *
7063 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7064 {
7065 	ill_t *ret_ill;
7066 
7067 	ASSERT(ifindex != 0);
7068 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7069 	if (ret_ill == NULL ||
7070 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7071 		if (isv6) {
7072 			if (ill != NULL) {
7073 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7074 			} else {
7075 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7076 			}
7077 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7078 			    "bad ifindex %d.\n", ifindex));
7079 		} else {
7080 			BUMP_MIB(&ip_mib, ipOutDiscards);
7081 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7082 			    "bad ifindex %d.\n", ifindex));
7083 		}
7084 		if (ret_ill != NULL)
7085 			ill_refrele(ret_ill);
7086 		freemsg(first_mp);
7087 		return (NULL);
7088 	}
7089 
7090 	return (ret_ill);
7091 }
7092 
7093 /*
7094  * IPv4 -
7095  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7096  * out a packet to a destination address for which we do not have specific
7097  * (or sufficient) routing information.
7098  *
7099  * NOTE : These are the scopes of some of the variables that point at IRE,
7100  *	  which needs to be followed while making any future modifications
7101  *	  to avoid memory leaks.
7102  *
7103  *	- ire and sire are the entries looked up initially by
7104  *	  ire_ftable_lookup.
7105  *	- ipif_ire is used to hold the interface ire associated with
7106  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7107  *	  it before branching out to error paths.
7108  *	- save_ire is initialized before ire_create, so that ire returned
7109  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7110  *	  before breaking out of the switch.
7111  *
7112  *	Thus on failures, we have to REFRELE only ire and sire, if they
7113  *	are not NULL.
7114  */
7115 void
7116 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp)
7117 {
7118 	areq_t	*areq;
7119 	ipaddr_t gw = 0;
7120 	ire_t	*ire = NULL;
7121 	mblk_t	*res_mp;
7122 	ipaddr_t *addrp;
7123 	ipaddr_t nexthop_addr;
7124 	ipif_t  *src_ipif = NULL;
7125 	ill_t	*dst_ill = NULL;
7126 	ipha_t  *ipha;
7127 	ire_t	*sire = NULL;
7128 	mblk_t	*first_mp;
7129 	ire_t	*save_ire;
7130 	mblk_t	*dlureq_mp;
7131 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7132 	ushort_t ire_marks = 0;
7133 	boolean_t mctl_present;
7134 	ipsec_out_t *io;
7135 	mblk_t	*saved_mp;
7136 	ire_t	*first_sire = NULL;
7137 	mblk_t	*copy_mp = NULL;
7138 	mblk_t	*xmit_mp = NULL;
7139 	ipaddr_t save_dst;
7140 	uint32_t multirt_flags =
7141 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7142 	boolean_t multirt_is_resolvable;
7143 	boolean_t multirt_resolve_next;
7144 	boolean_t do_attach_ill = B_FALSE;
7145 	boolean_t ip_nexthop = B_FALSE;
7146 	zoneid_t zoneid;
7147 	tsol_ire_gw_secattr_t *attrp = NULL;
7148 	tsol_gcgrp_t *gcgrp = NULL;
7149 	tsol_gcgrp_addr_t ga;
7150 
7151 	if (ip_debug > 2) {
7152 		/* ip1dbg */
7153 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7154 	}
7155 
7156 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7157 	if (mctl_present) {
7158 		io = (ipsec_out_t *)first_mp->b_rptr;
7159 		zoneid = io->ipsec_out_zoneid;
7160 		ASSERT(zoneid != ALL_ZONES);
7161 	} else if (connp != NULL) {
7162 		zoneid = connp->conn_zoneid;
7163 	} else {
7164 		zoneid = GLOBAL_ZONEID;
7165 	}
7166 
7167 	ipha = (ipha_t *)mp->b_rptr;
7168 
7169 	/* All multicast lookups come through ip_newroute_ipif() */
7170 	if (CLASSD(dst)) {
7171 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7172 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7173 		freemsg(first_mp);
7174 		return;
7175 	}
7176 
7177 	if (ip_loopback_src_or_dst(ipha, NULL)) {
7178 		goto icmp_err_ret;
7179 	}
7180 
7181 	if (mctl_present && io->ipsec_out_attach_if) {
7182 		/* ip_grab_attach_ill returns a held ill */
7183 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7184 		    io->ipsec_out_ill_index, B_FALSE);
7185 
7186 		/* Failure case frees things for us. */
7187 		if (attach_ill == NULL)
7188 			return;
7189 
7190 		/*
7191 		 * Check if we need an ire that will not be
7192 		 * looked up by anybody else i.e. HIDDEN.
7193 		 */
7194 		if (ill_is_probeonly(attach_ill))
7195 			ire_marks = IRE_MARK_HIDDEN;
7196 	}
7197 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7198 		ip_nexthop = B_TRUE;
7199 		nexthop_addr = io->ipsec_out_nexthop_addr;
7200 	}
7201 	/*
7202 	 * If this IRE is created for forwarding or it is not for
7203 	 * traffic for congestion controlled protocols, mark it as temporary.
7204 	 */
7205 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7206 		ire_marks |= IRE_MARK_TEMPORARY;
7207 
7208 	/*
7209 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7210 	 * chain until it gets the most specific information available.
7211 	 * For example, we know that there is no IRE_CACHE for this dest,
7212 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7213 	 * ire_ftable_lookup will look up the gateway, etc.
7214 	 * Check if in_ill != NULL. If it is true, the packet must be
7215 	 * from an incoming interface where RTA_SRCIFP is set.
7216 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7217 	 * to the destination, of equal netmask length in the forward table,
7218 	 * will be recursively explored. If no information is available
7219 	 * for the final gateway of that route, we force the returned ire
7220 	 * to be equal to sire using MATCH_IRE_PARENT.
7221 	 * At least, in this case we have a starting point (in the buckets)
7222 	 * to look for other routes to the destination in the forward table.
7223 	 * This is actually used only for multirouting, where a list
7224 	 * of routes has to be processed in sequence.
7225 	 */
7226 	if (in_ill != NULL) {
7227 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7228 		    in_ill, MATCH_IRE_TYPE);
7229 	} else if (ip_nexthop) {
7230 		/*
7231 		 * The first time we come here, we look for an IRE_INTERFACE
7232 		 * entry for the specified nexthop, set the dst to be the
7233 		 * nexthop address and create an IRE_CACHE entry for the
7234 		 * nexthop. The next time around, we are able to find an
7235 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7236 		 * nexthop address and create an IRE_CACHE entry for the
7237 		 * destination address via the specified nexthop.
7238 		 */
7239 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7240 		    MBLK_GETLABEL(mp));
7241 		if (ire != NULL) {
7242 			gw = nexthop_addr;
7243 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7244 		} else {
7245 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7246 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7247 			    MBLK_GETLABEL(mp),
7248 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7249 			if (ire != NULL) {
7250 				dst = nexthop_addr;
7251 			}
7252 		}
7253 	} else if (attach_ill == NULL) {
7254 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7255 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7256 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7257 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7258 		    MATCH_IRE_SECATTR);
7259 	} else {
7260 		/*
7261 		 * attach_ill is set only for communicating with
7262 		 * on-link hosts. So, don't look for DEFAULT.
7263 		 */
7264 		ipif_t	*attach_ipif;
7265 
7266 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7267 		if (attach_ipif == NULL) {
7268 			ill_refrele(attach_ill);
7269 			goto icmp_err_ret;
7270 		}
7271 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7272 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7273 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7274 		    MATCH_IRE_SECATTR);
7275 		ipif_refrele(attach_ipif);
7276 	}
7277 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7278 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7279 
7280 	/*
7281 	 * This loop is run only once in most cases.
7282 	 * We loop to resolve further routes only when the destination
7283 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7284 	 */
7285 	do {
7286 		/* Clear the previous iteration's values */
7287 		if (src_ipif != NULL) {
7288 			ipif_refrele(src_ipif);
7289 			src_ipif = NULL;
7290 		}
7291 		if (dst_ill != NULL) {
7292 			ill_refrele(dst_ill);
7293 			dst_ill = NULL;
7294 		}
7295 
7296 		multirt_resolve_next = B_FALSE;
7297 		/*
7298 		 * We check if packets have to be multirouted.
7299 		 * In this case, given the current <ire, sire> couple,
7300 		 * we look for the next suitable <ire, sire>.
7301 		 * This check is done in ire_multirt_lookup(),
7302 		 * which applies various criteria to find the next route
7303 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7304 		 * unchanged if it detects it has not been tried yet.
7305 		 */
7306 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7307 			ip3dbg(("ip_newroute: starting next_resolution "
7308 			    "with first_mp %p, tag %d\n",
7309 			    (void *)first_mp,
7310 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7311 
7312 			ASSERT(sire != NULL);
7313 			multirt_is_resolvable =
7314 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7315 				MBLK_GETLABEL(mp));
7316 
7317 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7318 			    "ire %p, sire %p\n",
7319 			    multirt_is_resolvable,
7320 			    (void *)ire, (void *)sire));
7321 
7322 			if (!multirt_is_resolvable) {
7323 				/*
7324 				 * No more multirt route to resolve; give up
7325 				 * (all routes resolved or no more
7326 				 * resolvable routes).
7327 				 */
7328 				if (ire != NULL) {
7329 					ire_refrele(ire);
7330 					ire = NULL;
7331 				}
7332 			} else {
7333 				ASSERT(sire != NULL);
7334 				ASSERT(ire != NULL);
7335 				/*
7336 				 * We simply use first_sire as a flag that
7337 				 * indicates if a resolvable multirt route
7338 				 * has already been found.
7339 				 * If it is not the case, we may have to send
7340 				 * an ICMP error to report that the
7341 				 * destination is unreachable.
7342 				 * We do not IRE_REFHOLD first_sire.
7343 				 */
7344 				if (first_sire == NULL) {
7345 					first_sire = sire;
7346 				}
7347 			}
7348 		}
7349 		if (ire == NULL) {
7350 			if (ip_debug > 3) {
7351 				/* ip2dbg */
7352 				pr_addr_dbg("ip_newroute: "
7353 				    "can't resolve %s\n", AF_INET, &dst);
7354 			}
7355 			ip3dbg(("ip_newroute: "
7356 			    "ire %p, sire %p, first_sire %p\n",
7357 			    (void *)ire, (void *)sire, (void *)first_sire));
7358 
7359 			if (sire != NULL) {
7360 				ire_refrele(sire);
7361 				sire = NULL;
7362 			}
7363 
7364 			if (first_sire != NULL) {
7365 				/*
7366 				 * At least one multirt route has been found
7367 				 * in the same call to ip_newroute();
7368 				 * there is no need to report an ICMP error.
7369 				 * first_sire was not IRE_REFHOLDed.
7370 				 */
7371 				MULTIRT_DEBUG_UNTAG(first_mp);
7372 				freemsg(first_mp);
7373 				return;
7374 			}
7375 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7376 			    RTA_DST);
7377 			if (attach_ill != NULL)
7378 				ill_refrele(attach_ill);
7379 			goto icmp_err_ret;
7380 		}
7381 
7382 		/*
7383 		 * When RTA_SRCIFP is used to add a route, then an interface
7384 		 * route is added in the source interface's routing table.
7385 		 * If the outgoing interface of this route is of type
7386 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7387 		 * ire_dlureq_mp is set to NULL. Later, when this route is
7388 		 * first used for forwarding packet, ip_newroute() is called
7389 		 * to resolve the hardware address of the outgoing ipif.
7390 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7391 		 * source interface based table. We only come here if the
7392 		 * outgoing interface is a resolver interface and we don't
7393 		 * have the ire_dlureq_mp information yet.
7394 		 * If in_ill is not null that means it is called from
7395 		 * ip_rput.
7396 		 */
7397 
7398 		ASSERT(ire->ire_in_ill == NULL ||
7399 		    (ire->ire_type == IRE_IF_RESOLVER &&
7400 		    ire->ire_dlureq_mp == NULL));
7401 
7402 		/*
7403 		 * Verify that the returned IRE does not have either
7404 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7405 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7406 		 */
7407 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7408 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7409 			if (attach_ill != NULL)
7410 				ill_refrele(attach_ill);
7411 			goto icmp_err_ret;
7412 		}
7413 		/*
7414 		 * Increment the ire_ob_pkt_count field for ire if it is an
7415 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7416 		 * increment the same for the parent IRE, sire, if it is some
7417 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7418 		 * and HOST_REDIRECT).
7419 		 */
7420 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7421 			UPDATE_OB_PKT_COUNT(ire);
7422 			ire->ire_last_used_time = lbolt;
7423 		}
7424 
7425 		if (sire != NULL) {
7426 			gw = sire->ire_gateway_addr;
7427 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7428 			    IRE_INTERFACE)) == 0);
7429 			UPDATE_OB_PKT_COUNT(sire);
7430 			sire->ire_last_used_time = lbolt;
7431 		}
7432 		/*
7433 		 * We have a route to reach the destination.
7434 		 *
7435 		 * 1) If the interface is part of ill group, try to get a new
7436 		 *    ill taking load spreading into account.
7437 		 *
7438 		 * 2) After selecting the ill, get a source address that
7439 		 *    might create good inbound load spreading.
7440 		 *    ipif_select_source does this for us.
7441 		 *
7442 		 * If the application specified the ill (ifindex), we still
7443 		 * load spread. Only if the packets needs to go out
7444 		 * specifically on a given ill e.g. binding to
7445 		 * IPIF_NOFAILOVER address, then we don't try to use a
7446 		 * different ill for load spreading.
7447 		 */
7448 		if (attach_ill == NULL) {
7449 			/*
7450 			 * Don't perform outbound load spreading in the
7451 			 * case of an RTF_MULTIRT route, as we actually
7452 			 * typically want to replicate outgoing packets
7453 			 * through particular interfaces.
7454 			 */
7455 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7456 				dst_ill = ire->ire_ipif->ipif_ill;
7457 				/* for uniformity */
7458 				ill_refhold(dst_ill);
7459 			} else {
7460 				/*
7461 				 * If we are here trying to create an IRE_CACHE
7462 				 * for an offlink destination and have the
7463 				 * IRE_CACHE for the next hop and the latter is
7464 				 * using virtual IP source address selection i.e
7465 				 * it's ire->ire_ipif is pointing to a virtual
7466 				 * network interface (vni) then
7467 				 * ip_newroute_get_dst_ll() will return the vni
7468 				 * interface as the dst_ill. Since the vni is
7469 				 * virtual i.e not associated with any physical
7470 				 * interface, it cannot be the dst_ill, hence
7471 				 * in such a case call ip_newroute_get_dst_ll()
7472 				 * with the stq_ill instead of the ire_ipif ILL.
7473 				 * The function returns a refheld ill.
7474 				 */
7475 				if ((ire->ire_type == IRE_CACHE) &&
7476 				    IS_VNI(ire->ire_ipif->ipif_ill))
7477 					dst_ill = ip_newroute_get_dst_ill(
7478 						ire->ire_stq->q_ptr);
7479 				else
7480 					dst_ill = ip_newroute_get_dst_ill(
7481 						ire->ire_ipif->ipif_ill);
7482 			}
7483 			if (dst_ill == NULL) {
7484 				if (ip_debug > 2) {
7485 					pr_addr_dbg("ip_newroute: "
7486 					    "no dst ill for dst"
7487 					    " %s\n", AF_INET, &dst);
7488 				}
7489 				goto icmp_err_ret;
7490 			}
7491 		} else {
7492 			dst_ill = ire->ire_ipif->ipif_ill;
7493 			/* for uniformity */
7494 			ill_refhold(dst_ill);
7495 			/*
7496 			 * We should have found a route matching ill as we
7497 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7498 			 * Rather than asserting, when there is a mismatch,
7499 			 * we just drop the packet.
7500 			 */
7501 			if (dst_ill != attach_ill) {
7502 				ip0dbg(("ip_newroute: Packet dropped as "
7503 				    "IPIF_NOFAILOVER ill is %s, "
7504 				    "ire->ire_ipif->ipif_ill is %s\n",
7505 				    attach_ill->ill_name,
7506 				    dst_ill->ill_name));
7507 				ill_refrele(attach_ill);
7508 				goto icmp_err_ret;
7509 			}
7510 		}
7511 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7512 		if (attach_ill != NULL) {
7513 			ill_refrele(attach_ill);
7514 			attach_ill = NULL;
7515 			do_attach_ill = B_TRUE;
7516 		}
7517 		ASSERT(dst_ill != NULL);
7518 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7519 
7520 		/*
7521 		 * Pick the best source address from dst_ill.
7522 		 *
7523 		 * 1) If it is part of a multipathing group, we would
7524 		 *    like to spread the inbound packets across different
7525 		 *    interfaces. ipif_select_source picks a random source
7526 		 *    across the different ills in the group.
7527 		 *
7528 		 * 2) If it is not part of a multipathing group, we try
7529 		 *    to pick the source address from the destination
7530 		 *    route. Clustering assumes that when we have multiple
7531 		 *    prefixes hosted on an interface, the prefix of the
7532 		 *    source address matches the prefix of the destination
7533 		 *    route. We do this only if the address is not
7534 		 *    DEPRECATED.
7535 		 *
7536 		 * 3) If the conn is in a different zone than the ire, we
7537 		 *    need to pick a source address from the right zone.
7538 		 *
7539 		 * NOTE : If we hit case (1) above, the prefix of the source
7540 		 *	  address picked may not match the prefix of the
7541 		 *	  destination routes prefix as ipif_select_source
7542 		 *	  does not look at "dst" while picking a source
7543 		 *	  address.
7544 		 *	  If we want the same behavior as (2), we will need
7545 		 *	  to change the behavior of ipif_select_source.
7546 		 */
7547 		ASSERT(src_ipif == NULL);
7548 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
7549 			/*
7550 			 * The RTF_SETSRC flag is set in the parent ire (sire).
7551 			 * Check that the ipif matching the requested source
7552 			 * address still exists.
7553 			 */
7554 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
7555 			    zoneid, NULL, NULL, NULL, NULL);
7556 		}
7557 		if (src_ipif == NULL) {
7558 			ire_marks |= IRE_MARK_USESRC_CHECK;
7559 			if ((dst_ill->ill_group != NULL) ||
7560 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
7561 			    (connp != NULL && ire->ire_zoneid != zoneid &&
7562 			    ire->ire_zoneid != ALL_ZONES) ||
7563 			    (dst_ill->ill_usesrc_ifindex != 0)) {
7564 				/*
7565 				 * If the destination is reachable via a
7566 				 * given gateway, the selected source address
7567 				 * should be in the same subnet as the gateway.
7568 				 * Otherwise, the destination is not reachable.
7569 				 *
7570 				 * If there are no interfaces on the same subnet
7571 				 * as the destination, ipif_select_source gives
7572 				 * first non-deprecated interface which might be
7573 				 * on a different subnet than the gateway.
7574 				 * This is not desirable. Hence pass the dst_ire
7575 				 * source address to ipif_select_source.
7576 				 * It is sure that the destination is reachable
7577 				 * with the dst_ire source address subnet.
7578 				 * So passing dst_ire source address to
7579 				 * ipif_select_source will make sure that the
7580 				 * selected source will be on the same subnet
7581 				 * as dst_ire source address.
7582 				 */
7583 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
7584 				src_ipif = ipif_select_source(dst_ill, saddr,
7585 				    zoneid);
7586 				if (src_ipif == NULL) {
7587 					if (ip_debug > 2) {
7588 						pr_addr_dbg("ip_newroute: "
7589 						    "no src for dst %s ",
7590 						    AF_INET, &dst);
7591 						printf("through interface %s\n",
7592 						    dst_ill->ill_name);
7593 					}
7594 					goto icmp_err_ret;
7595 				}
7596 			} else {
7597 				src_ipif = ire->ire_ipif;
7598 				ASSERT(src_ipif != NULL);
7599 				/* hold src_ipif for uniformity */
7600 				ipif_refhold(src_ipif);
7601 			}
7602 		}
7603 
7604 		/*
7605 		 * Assign a source address while we have the conn.
7606 		 * We can't have ip_wput_ire pick a source address when the
7607 		 * packet returns from arp since we need to look at
7608 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
7609 		 * going through arp.
7610 		 *
7611 		 * NOTE : ip_newroute_v6 does not have this piece of code as
7612 		 *	  it uses ip6i to store this information.
7613 		 */
7614 		if (ipha->ipha_src == INADDR_ANY &&
7615 		    (connp == NULL || !connp->conn_unspec_src)) {
7616 			ipha->ipha_src = src_ipif->ipif_src_addr;
7617 		}
7618 		if (ip_debug > 3) {
7619 			/* ip2dbg */
7620 			pr_addr_dbg("ip_newroute: first hop %s\n",
7621 			    AF_INET, &gw);
7622 		}
7623 		ip2dbg(("\tire type %s (%d)\n",
7624 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
7625 
7626 		/*
7627 		 * The TTL of multirouted packets is bounded by the
7628 		 * ip_multirt_ttl ndd variable.
7629 		 */
7630 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7631 			/* Force TTL of multirouted packets */
7632 			if ((ip_multirt_ttl > 0) &&
7633 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
7634 				ip2dbg(("ip_newroute: forcing multirt TTL "
7635 				    "to %d (was %d), dst 0x%08x\n",
7636 				    ip_multirt_ttl, ipha->ipha_ttl,
7637 				    ntohl(sire->ire_addr)));
7638 				ipha->ipha_ttl = ip_multirt_ttl;
7639 			}
7640 		}
7641 		/*
7642 		 * At this point in ip_newroute(), ire is either the
7643 		 * IRE_CACHE of the next-hop gateway for an off-subnet
7644 		 * destination or an IRE_INTERFACE type that should be used
7645 		 * to resolve an on-subnet destination or an on-subnet
7646 		 * next-hop gateway.
7647 		 *
7648 		 * In the IRE_CACHE case, we have the following :
7649 		 *
7650 		 * 1) src_ipif - used for getting a source address.
7651 		 *
7652 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7653 		 *    means packets using this IRE_CACHE will go out on
7654 		 *    dst_ill.
7655 		 *
7656 		 * 3) The IRE sire will point to the prefix that is the
7657 		 *    longest  matching route for the destination. These
7658 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST,
7659 		 *    and IRE_HOST_REDIRECT.
7660 		 *
7661 		 *    The newly created IRE_CACHE entry for the off-subnet
7662 		 *    destination is tied to both the prefix route and the
7663 		 *    interface route used to resolve the next-hop gateway
7664 		 *    via the ire_phandle and ire_ihandle fields,
7665 		 *    respectively.
7666 		 *
7667 		 * In the IRE_INTERFACE case, we have the following :
7668 		 *
7669 		 * 1) src_ipif - used for getting a source address.
7670 		 *
7671 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
7672 		 *    means packets using the IRE_CACHE that we will build
7673 		 *    here will go out on dst_ill.
7674 		 *
7675 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
7676 		 *    to be created will only be tied to the IRE_INTERFACE
7677 		 *    that was derived from the ire_ihandle field.
7678 		 *
7679 		 *    If sire is non-NULL, it means the destination is
7680 		 *    off-link and we will first create the IRE_CACHE for the
7681 		 *    gateway. Next time through ip_newroute, we will create
7682 		 *    the IRE_CACHE for the final destination as described
7683 		 *    above.
7684 		 *
7685 		 * In both cases, after the current resolution has been
7686 		 * completed (or possibly initialised, in the IRE_INTERFACE
7687 		 * case), the loop may be re-entered to attempt the resolution
7688 		 * of another RTF_MULTIRT route.
7689 		 *
7690 		 * When an IRE_CACHE entry for the off-subnet destination is
7691 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
7692 		 * for further processing in emission loops.
7693 		 */
7694 		save_ire = ire;
7695 		switch (ire->ire_type) {
7696 		case IRE_CACHE: {
7697 			ire_t	*ipif_ire;
7698 			mblk_t	*ire_fp_mp;
7699 
7700 			if (gw == 0)
7701 				gw = ire->ire_gateway_addr;
7702 			/*
7703 			 * We need 3 ire's to create a new cache ire for an
7704 			 * off-link destination from the cache ire of the
7705 			 * gateway.
7706 			 *
7707 			 *	1. The prefix ire 'sire' (Note that this does
7708 			 *	   not apply to the conn_nexthop_set case)
7709 			 *	2. The cache ire of the gateway 'ire'
7710 			 *	3. The interface ire 'ipif_ire'
7711 			 *
7712 			 * We have (1) and (2). We lookup (3) below.
7713 			 *
7714 			 * If there is no interface route to the gateway,
7715 			 * it is a race condition, where we found the cache
7716 			 * but the interface route has been deleted.
7717 			 */
7718 			if (ip_nexthop) {
7719 				ipif_ire = ire_ihandle_lookup_onlink(ire);
7720 			} else {
7721 				ipif_ire =
7722 				    ire_ihandle_lookup_offlink(ire, sire);
7723 			}
7724 			if (ipif_ire == NULL) {
7725 				ip1dbg(("ip_newroute: "
7726 				    "ire_ihandle_lookup_offlink failed\n"));
7727 				goto icmp_err_ret;
7728 			}
7729 			/*
7730 			 * XXX We are using the same dlureq_mp
7731 			 * (DL_UNITDATA_REQ) though the save_ire is not
7732 			 * pointing at the same ill.
7733 			 * This is incorrect. We need to send it up to the
7734 			 * resolver to get the right dlureq_mp. For ethernets
7735 			 * this may be okay (ill_type == DL_ETHER).
7736 			 */
7737 			dlureq_mp = save_ire->ire_dlureq_mp;
7738 			ire_fp_mp = NULL;
7739 			/*
7740 			 * save_ire's ire_fp_mp can't change since it is
7741 			 * not an IRE_MIPRTUN or IRE_BROADCAST
7742 			 * LOCK_IRE_FP_MP does not do any useful work in
7743 			 * the case of IRE_CACHE. So we don't use it below.
7744 			 */
7745 			if (save_ire->ire_stq == dst_ill->ill_wq)
7746 				ire_fp_mp = save_ire->ire_fp_mp;
7747 
7748 			/*
7749 			 * Check cached gateway IRE for any security
7750 			 * attributes; if found, associate the gateway
7751 			 * credentials group to the destination IRE.
7752 			 */
7753 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
7754 				mutex_enter(&attrp->igsa_lock);
7755 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
7756 					GCGRP_REFHOLD(gcgrp);
7757 				mutex_exit(&attrp->igsa_lock);
7758 			}
7759 
7760 			ire = ire_create(
7761 			    (uchar_t *)&dst,		/* dest address */
7762 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7763 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7764 			    (uchar_t *)&gw,		/* gateway address */
7765 			    NULL,
7766 			    &save_ire->ire_max_frag,
7767 			    ire_fp_mp,			/* Fast Path header */
7768 			    dst_ill->ill_rq,		/* recv-from queue */
7769 			    dst_ill->ill_wq,		/* send-to queue */
7770 			    IRE_CACHE,			/* IRE type */
7771 			    save_ire->ire_dlureq_mp,
7772 			    src_ipif,
7773 			    in_ill,			/* incoming ill */
7774 			    (sire != NULL) ?
7775 				sire->ire_mask : 0, 	/* Parent mask */
7776 			    (sire != NULL) ?
7777 				sire->ire_phandle : 0,  /* Parent handle */
7778 			    ipif_ire->ire_ihandle,	/* Interface handle */
7779 			    (sire != NULL) ? (sire->ire_flags &
7780 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
7781 			    (sire != NULL) ?
7782 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
7783 			    NULL,
7784 			    gcgrp);
7785 
7786 			if (ire == NULL) {
7787 				if (gcgrp != NULL) {
7788 					GCGRP_REFRELE(gcgrp);
7789 					gcgrp = NULL;
7790 				}
7791 				ire_refrele(ipif_ire);
7792 				ire_refrele(save_ire);
7793 				break;
7794 			}
7795 
7796 			/* reference now held by IRE */
7797 			gcgrp = NULL;
7798 
7799 			ire->ire_marks |= ire_marks;
7800 
7801 			/*
7802 			 * Prevent sire and ipif_ire from getting deleted.
7803 			 * The newly created ire is tied to both of them via
7804 			 * the phandle and ihandle respectively.
7805 			 */
7806 			if (sire != NULL) {
7807 				IRB_REFHOLD(sire->ire_bucket);
7808 				/* Has it been removed already ? */
7809 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
7810 					IRB_REFRELE(sire->ire_bucket);
7811 					ire_refrele(ipif_ire);
7812 					ire_refrele(save_ire);
7813 					break;
7814 				}
7815 			}
7816 
7817 			IRB_REFHOLD(ipif_ire->ire_bucket);
7818 			/* Has it been removed already ? */
7819 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
7820 				IRB_REFRELE(ipif_ire->ire_bucket);
7821 				if (sire != NULL)
7822 					IRB_REFRELE(sire->ire_bucket);
7823 				ire_refrele(ipif_ire);
7824 				ire_refrele(save_ire);
7825 				break;
7826 			}
7827 
7828 			xmit_mp = first_mp;
7829 			/*
7830 			 * In the case of multirouting, a copy
7831 			 * of the packet is done before its sending.
7832 			 * The copy is used to attempt another
7833 			 * route resolution, in a next loop.
7834 			 */
7835 			if (ire->ire_flags & RTF_MULTIRT) {
7836 				copy_mp = copymsg(first_mp);
7837 				if (copy_mp != NULL) {
7838 					xmit_mp = copy_mp;
7839 					MULTIRT_DEBUG_TAG(first_mp);
7840 				}
7841 			}
7842 			ire_add_then_send(q, ire, xmit_mp);
7843 			ire_refrele(save_ire);
7844 
7845 			/* Assert that sire is not deleted yet. */
7846 			if (sire != NULL) {
7847 				ASSERT(sire->ire_ptpn != NULL);
7848 				IRB_REFRELE(sire->ire_bucket);
7849 			}
7850 
7851 			/* Assert that ipif_ire is not deleted yet. */
7852 			ASSERT(ipif_ire->ire_ptpn != NULL);
7853 			IRB_REFRELE(ipif_ire->ire_bucket);
7854 			ire_refrele(ipif_ire);
7855 
7856 			/*
7857 			 * If copy_mp is not NULL, multirouting was
7858 			 * requested. We loop to initiate a next
7859 			 * route resolution attempt, starting from sire.
7860 			 */
7861 			if (copy_mp != NULL) {
7862 				/*
7863 				 * Search for the next unresolved
7864 				 * multirt route.
7865 				 */
7866 				copy_mp = NULL;
7867 				ipif_ire = NULL;
7868 				ire = NULL;
7869 				multirt_resolve_next = B_TRUE;
7870 				continue;
7871 			}
7872 			if (sire != NULL)
7873 				ire_refrele(sire);
7874 			ipif_refrele(src_ipif);
7875 			ill_refrele(dst_ill);
7876 			return;
7877 		}
7878 		case IRE_IF_NORESOLVER: {
7879 			/*
7880 			 * We have what we need to build an IRE_CACHE.
7881 			 *
7882 			 * Create a new dlureq_mp with the IP gateway address
7883 			 * in destination address in the DLPI hdr if the
7884 			 * physical length is exactly 4 bytes.
7885 			 */
7886 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
7887 				uchar_t *addr;
7888 
7889 				if (gw)
7890 					addr = (uchar_t *)&gw;
7891 				else
7892 					addr = (uchar_t *)&dst;
7893 
7894 				dlureq_mp = ill_dlur_gen(addr,
7895 				    dst_ill->ill_phys_addr_length,
7896 				    dst_ill->ill_sap,
7897 				    dst_ill->ill_sap_length);
7898 			} else {
7899 				dlureq_mp = ire->ire_dlureq_mp;
7900 			}
7901 
7902 			if (dlureq_mp == NULL) {
7903 				ip1dbg(("ip_newroute: dlureq_mp NULL\n"));
7904 				break;
7905 			}
7906 
7907 			/*
7908 			 * TSol note: We are creating the ire cache for the
7909 			 * destination 'dst'. If 'dst' is offlink, going
7910 			 * through the first hop 'gw', the security attributes
7911 			 * of 'dst' must be set to point to the gateway
7912 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
7913 			 * is possible that 'dst' is a potential gateway that is
7914 			 * referenced by some route that has some security
7915 			 * attributes. Thus in the former case, we need to do a
7916 			 * gcgrp_lookup of 'gw' while in the latter case we
7917 			 * need to do gcgrp_lookup of 'dst' itself.
7918 			 */
7919 			ga.ga_af = AF_INET;
7920 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
7921 			    &ga.ga_addr);
7922 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
7923 
7924 			ire = ire_create(
7925 			    (uchar_t *)&dst,		/* dest address */
7926 			    (uchar_t *)&ip_g_all_ones,	/* mask */
7927 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
7928 			    (uchar_t *)&gw,		/* gateway address */
7929 			    NULL,
7930 			    &save_ire->ire_max_frag,
7931 			    NULL,			/* Fast Path header */
7932 			    dst_ill->ill_rq,		/* recv-from queue */
7933 			    dst_ill->ill_wq,		/* send-to queue */
7934 			    IRE_CACHE,
7935 			    dlureq_mp,
7936 			    src_ipif,
7937 			    in_ill,			/* Incoming ill */
7938 			    save_ire->ire_mask,		/* Parent mask */
7939 			    (sire != NULL) ?		/* Parent handle */
7940 				sire->ire_phandle : 0,
7941 			    save_ire->ire_ihandle,	/* Interface handle */
7942 			    (sire != NULL) ? sire->ire_flags &
7943 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
7944 			    &(save_ire->ire_uinfo),
7945 			    NULL,
7946 			    gcgrp);
7947 
7948 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
7949 				freeb(dlureq_mp);
7950 
7951 			if (ire == NULL) {
7952 				if (gcgrp != NULL) {
7953 					GCGRP_REFRELE(gcgrp);
7954 					gcgrp = NULL;
7955 				}
7956 				ire_refrele(save_ire);
7957 				break;
7958 			}
7959 
7960 			/* reference now held by IRE */
7961 			gcgrp = NULL;
7962 
7963 			ire->ire_marks |= ire_marks;
7964 
7965 			/* Prevent save_ire from getting deleted */
7966 			IRB_REFHOLD(save_ire->ire_bucket);
7967 			/* Has it been removed already ? */
7968 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
7969 				IRB_REFRELE(save_ire->ire_bucket);
7970 				ire_refrele(save_ire);
7971 				break;
7972 			}
7973 
7974 			/*
7975 			 * In the case of multirouting, a copy
7976 			 * of the packet is made before it is sent.
7977 			 * The copy is used in the next
7978 			 * loop to attempt another resolution.
7979 			 */
7980 			xmit_mp = first_mp;
7981 			if ((sire != NULL) &&
7982 			    (sire->ire_flags & RTF_MULTIRT)) {
7983 				copy_mp = copymsg(first_mp);
7984 				if (copy_mp != NULL) {
7985 					xmit_mp = copy_mp;
7986 					MULTIRT_DEBUG_TAG(first_mp);
7987 				}
7988 			}
7989 			ire_add_then_send(q, ire, xmit_mp);
7990 
7991 			/* Assert that it is not deleted yet. */
7992 			ASSERT(save_ire->ire_ptpn != NULL);
7993 			IRB_REFRELE(save_ire->ire_bucket);
7994 			ire_refrele(save_ire);
7995 
7996 			if (copy_mp != NULL) {
7997 				/*
7998 				 * If we found a (no)resolver, we ignore any
7999 				 * trailing top priority IRE_CACHE in further
8000 				 * loops. This ensures that we do not omit any
8001 				 * (no)resolver.
8002 				 * This IRE_CACHE, if any, will be processed
8003 				 * by another thread entering ip_newroute().
8004 				 * IRE_CACHE entries, if any, will be processed
8005 				 * by another thread entering ip_newroute(),
8006 				 * (upon resolver response, for instance).
8007 				 * This aims to force parallel multirt
8008 				 * resolutions as soon as a packet must be sent.
8009 				 * In the best case, after the tx of only one
8010 				 * packet, all reachable routes are resolved.
8011 				 * Otherwise, the resolution of all RTF_MULTIRT
8012 				 * routes would require several emissions.
8013 				 */
8014 				multirt_flags &= ~MULTIRT_CACHEGW;
8015 
8016 				/*
8017 				 * Search for the next unresolved multirt
8018 				 * route.
8019 				 */
8020 				copy_mp = NULL;
8021 				save_ire = NULL;
8022 				ire = NULL;
8023 				multirt_resolve_next = B_TRUE;
8024 				continue;
8025 			}
8026 
8027 			/*
8028 			 * Don't need sire anymore
8029 			 */
8030 			if (sire != NULL)
8031 				ire_refrele(sire);
8032 
8033 			ipif_refrele(src_ipif);
8034 			ill_refrele(dst_ill);
8035 			return;
8036 		}
8037 		case IRE_IF_RESOLVER:
8038 			/*
8039 			 * We can't build an IRE_CACHE yet, but at least we
8040 			 * found a resolver that can help.
8041 			 */
8042 			res_mp = dst_ill->ill_resolver_mp;
8043 			if (!OK_RESOLVER_MP(res_mp))
8044 				break;
8045 
8046 			/*
8047 			 * To be at this point in the code with a non-zero gw
8048 			 * means that dst is reachable through a gateway that
8049 			 * we have never resolved.  By changing dst to the gw
8050 			 * addr we resolve the gateway first.
8051 			 * When ire_add_then_send() tries to put the IP dg
8052 			 * to dst, it will reenter ip_newroute() at which
8053 			 * time we will find the IRE_CACHE for the gw and
8054 			 * create another IRE_CACHE in case IRE_CACHE above.
8055 			 */
8056 			if (gw != INADDR_ANY) {
8057 				/*
8058 				 * The source ipif that was determined above was
8059 				 * relative to the destination address, not the
8060 				 * gateway's. If src_ipif was not taken out of
8061 				 * the IRE_IF_RESOLVER entry, we'll need to call
8062 				 * ipif_select_source() again.
8063 				 */
8064 				if (src_ipif != ire->ire_ipif) {
8065 					ipif_refrele(src_ipif);
8066 					src_ipif = ipif_select_source(dst_ill,
8067 					    gw, zoneid);
8068 					if (src_ipif == NULL) {
8069 						if (ip_debug > 2) {
8070 							pr_addr_dbg(
8071 							    "ip_newroute: no "
8072 							    "src for gw %s ",
8073 							    AF_INET, &gw);
8074 							printf("through "
8075 							    "interface %s\n",
8076 							    dst_ill->ill_name);
8077 						}
8078 						goto icmp_err_ret;
8079 					}
8080 				}
8081 				save_dst = dst;
8082 				dst = gw;
8083 				gw = INADDR_ANY;
8084 			}
8085 
8086 			/*
8087 			 * We obtain a partial IRE_CACHE which we will pass
8088 			 * along with the resolver query.  When the response
8089 			 * comes back it will be there ready for us to add.
8090 			 * The ire_max_frag is atomically set under the
8091 			 * irebucket lock in ire_add_v[46].
8092 			 */
8093 			ire = ire_create_mp(
8094 			    (uchar_t *)&dst,		/* dest address */
8095 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8096 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8097 			    (uchar_t *)&gw,		/* gateway address */
8098 			    NULL,			/* no in_src_addr */
8099 			    NULL,			/* ire_max_frag */
8100 			    NULL,			/* Fast Path header */
8101 			    dst_ill->ill_rq,		/* recv-from queue */
8102 			    dst_ill->ill_wq,		/* send-to queue */
8103 			    IRE_CACHE,
8104 			    res_mp,
8105 			    src_ipif,			/* Interface ipif */
8106 			    in_ill,			/* Incoming ILL */
8107 			    save_ire->ire_mask,		/* Parent mask */
8108 			    0,
8109 			    save_ire->ire_ihandle,	/* Interface handle */
8110 			    0,				/* flags if any */
8111 			    &(save_ire->ire_uinfo),
8112 			    NULL,
8113 			    NULL);
8114 
8115 			if (ire == NULL) {
8116 				ire_refrele(save_ire);
8117 				break;
8118 			}
8119 
8120 			if ((sire != NULL) &&
8121 			    (sire->ire_flags & RTF_MULTIRT)) {
8122 				copy_mp = copymsg(first_mp);
8123 				if (copy_mp != NULL)
8124 					MULTIRT_DEBUG_TAG(copy_mp);
8125 			}
8126 
8127 			ire->ire_marks |= ire_marks;
8128 
8129 			/*
8130 			 * Construct message chain for the resolver
8131 			 * of the form:
8132 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8133 			 * Packet could contain a IPSEC_OUT mp.
8134 			 *
8135 			 * NOTE : ire will be added later when the response
8136 			 * comes back from ARP. If the response does not
8137 			 * come back, ARP frees the packet. For this reason,
8138 			 * we can't REFHOLD the bucket of save_ire to prevent
8139 			 * deletions. We may not be able to REFRELE the bucket
8140 			 * if the response never comes back. Thus, before
8141 			 * adding the ire, ire_add_v4 will make sure that the
8142 			 * interface route does not get deleted. This is the
8143 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8144 			 * where we can always prevent deletions because of
8145 			 * the synchronous nature of adding IRES i.e
8146 			 * ire_add_then_send is called after creating the IRE.
8147 			 */
8148 			ASSERT(ire->ire_mp != NULL);
8149 			ire->ire_mp->b_cont = first_mp;
8150 			/* Have saved_mp handy, for cleanup if canput fails */
8151 			saved_mp = mp;
8152 			mp = ire->ire_dlureq_mp;
8153 			ASSERT(mp != NULL);
8154 			ire->ire_dlureq_mp = NULL;
8155 			linkb(mp, ire->ire_mp);
8156 
8157 
8158 			/*
8159 			 * Fill in the source and dest addrs for the resolver.
8160 			 * NOTE: this depends on memory layouts imposed by
8161 			 * ill_init().
8162 			 */
8163 			areq = (areq_t *)mp->b_rptr;
8164 			addrp = (ipaddr_t *)((char *)areq +
8165 			    areq->areq_sender_addr_offset);
8166 			if (do_attach_ill) {
8167 				/*
8168 				 * This is bind to no failover case.
8169 				 * arp packet also must go out on attach_ill.
8170 				 */
8171 				ASSERT(ipha->ipha_src != NULL);
8172 				*addrp = ipha->ipha_src;
8173 			} else {
8174 				*addrp = save_ire->ire_src_addr;
8175 			}
8176 
8177 			ire_refrele(save_ire);
8178 			addrp = (ipaddr_t *)((char *)areq +
8179 			    areq->areq_target_addr_offset);
8180 			*addrp = dst;
8181 			/* Up to the resolver. */
8182 			if (canputnext(dst_ill->ill_rq)) {
8183 				putnext(dst_ill->ill_rq, mp);
8184 				ire = NULL;
8185 				if (copy_mp != NULL) {
8186 					/*
8187 					 * If we found a resolver, we ignore
8188 					 * any trailing top priority IRE_CACHE
8189 					 * in the further loops. This ensures
8190 					 * that we do not omit any resolver.
8191 					 * IRE_CACHE entries, if any, will be
8192 					 * processed next time we enter
8193 					 * ip_newroute().
8194 					 */
8195 					multirt_flags &= ~MULTIRT_CACHEGW;
8196 					/*
8197 					 * Search for the next unresolved
8198 					 * multirt route.
8199 					 */
8200 					first_mp = copy_mp;
8201 					copy_mp = NULL;
8202 					/* Prepare the next resolution loop. */
8203 					mp = first_mp;
8204 					EXTRACT_PKT_MP(mp, first_mp,
8205 					    mctl_present);
8206 					if (mctl_present)
8207 						io = (ipsec_out_t *)
8208 						    first_mp->b_rptr;
8209 					ipha = (ipha_t *)mp->b_rptr;
8210 
8211 					ASSERT(sire != NULL);
8212 
8213 					dst = save_dst;
8214 					multirt_resolve_next = B_TRUE;
8215 					continue;
8216 				}
8217 
8218 				if (sire != NULL)
8219 					ire_refrele(sire);
8220 
8221 				/*
8222 				 * The response will come back in ip_wput
8223 				 * with db_type IRE_DB_TYPE.
8224 				 */
8225 				ipif_refrele(src_ipif);
8226 				ill_refrele(dst_ill);
8227 				return;
8228 			} else {
8229 				/* Prepare for cleanup */
8230 				ire->ire_dlureq_mp = mp;
8231 				mp->b_cont = NULL;
8232 				ire_delete(ire);
8233 				mp = saved_mp;
8234 				ire = NULL;
8235 				if (copy_mp != NULL) {
8236 					MULTIRT_DEBUG_UNTAG(copy_mp);
8237 					freemsg(copy_mp);
8238 					copy_mp = NULL;
8239 				}
8240 				break;
8241 			}
8242 		default:
8243 			break;
8244 		}
8245 	} while (multirt_resolve_next);
8246 
8247 	ip1dbg(("ip_newroute: dropped\n"));
8248 	/* Did this packet originate externally? */
8249 	if (mp->b_prev) {
8250 		mp->b_next = NULL;
8251 		mp->b_prev = NULL;
8252 		BUMP_MIB(&ip_mib, ipInDiscards);
8253 	} else {
8254 		BUMP_MIB(&ip_mib, ipOutDiscards);
8255 	}
8256 	ASSERT(copy_mp == NULL);
8257 	MULTIRT_DEBUG_UNTAG(first_mp);
8258 	freemsg(first_mp);
8259 	if (ire != NULL)
8260 		ire_refrele(ire);
8261 	if (sire != NULL)
8262 		ire_refrele(sire);
8263 	if (src_ipif != NULL)
8264 		ipif_refrele(src_ipif);
8265 	if (dst_ill != NULL)
8266 		ill_refrele(dst_ill);
8267 	return;
8268 
8269 icmp_err_ret:
8270 	ip1dbg(("ip_newroute: no route\n"));
8271 	if (src_ipif != NULL)
8272 		ipif_refrele(src_ipif);
8273 	if (dst_ill != NULL)
8274 		ill_refrele(dst_ill);
8275 	if (sire != NULL)
8276 		ire_refrele(sire);
8277 	/* Did this packet originate externally? */
8278 	if (mp->b_prev) {
8279 		mp->b_next = NULL;
8280 		mp->b_prev = NULL;
8281 		/* XXX ipInNoRoutes */
8282 		q = WR(q);
8283 	} else {
8284 		/*
8285 		 * Since ip_wput() isn't close to finished, we fill
8286 		 * in enough of the header for credible error reporting.
8287 		 */
8288 		if (ip_hdr_complete(ipha, zoneid)) {
8289 			/* Failed */
8290 			MULTIRT_DEBUG_UNTAG(first_mp);
8291 			freemsg(first_mp);
8292 			if (ire != NULL)
8293 				ire_refrele(ire);
8294 			return;
8295 		}
8296 	}
8297 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8298 
8299 	/*
8300 	 * At this point we will have ire only if RTF_BLACKHOLE
8301 	 * or RTF_REJECT flags are set on the IRE. It will not
8302 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8303 	 */
8304 	if (ire != NULL) {
8305 		if (ire->ire_flags & RTF_BLACKHOLE) {
8306 			ire_refrele(ire);
8307 			MULTIRT_DEBUG_UNTAG(first_mp);
8308 			freemsg(first_mp);
8309 			return;
8310 		}
8311 		ire_refrele(ire);
8312 	}
8313 	if (ip_source_routed(ipha)) {
8314 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
8315 		return;
8316 	}
8317 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8318 }
8319 
8320 /*
8321  * IPv4 -
8322  * ip_newroute_ipif is called by ip_wput_multicast and
8323  * ip_rput_forward_multicast whenever we need to send
8324  * out a packet to a destination address for which we do not have specific
8325  * routing information. It is used when the packet will be sent out
8326  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8327  * socket option is set or icmp error message wants to go out on a particular
8328  * interface for a unicast packet.
8329  *
8330  * In most cases, the destination address is resolved thanks to the ipif
8331  * intrinsic resolver. However, there are some cases where the call to
8332  * ip_newroute_ipif must take into account the potential presence of
8333  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8334  * that uses the interface. This is specified through flags,
8335  * which can be a combination of:
8336  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8337  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8338  *   and flags. Additionally, the packet source address has to be set to
8339  *   the specified address. The caller is thus expected to set this flag
8340  *   if the packet has no specific source address yet.
8341  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8342  *   flag, the resulting ire will inherit the flag. All unresolved routes
8343  *   to the destination must be explored in the same call to
8344  *   ip_newroute_ipif().
8345  */
8346 static void
8347 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8348     conn_t *connp, uint32_t flags)
8349 {
8350 	areq_t	*areq;
8351 	ire_t	*ire = NULL;
8352 	mblk_t	*res_mp;
8353 	ipaddr_t *addrp;
8354 	mblk_t *first_mp;
8355 	ire_t	*save_ire = NULL;
8356 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8357 	ipif_t	*src_ipif = NULL;
8358 	ushort_t ire_marks = 0;
8359 	ill_t	*dst_ill = NULL;
8360 	boolean_t mctl_present;
8361 	ipsec_out_t *io;
8362 	ipha_t *ipha;
8363 	int	ihandle = 0;
8364 	mblk_t	*saved_mp;
8365 	ire_t   *fire = NULL;
8366 	mblk_t  *copy_mp = NULL;
8367 	boolean_t multirt_resolve_next;
8368 	ipaddr_t ipha_dst;
8369 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
8370 
8371 	/*
8372 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8373 	 * here for uniformity
8374 	 */
8375 	ipif_refhold(ipif);
8376 
8377 	/*
8378 	 * This loop is run only once in most cases.
8379 	 * We loop to resolve further routes only when the destination
8380 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8381 	 */
8382 	do {
8383 		if (dst_ill != NULL) {
8384 			ill_refrele(dst_ill);
8385 			dst_ill = NULL;
8386 		}
8387 		if (src_ipif != NULL) {
8388 			ipif_refrele(src_ipif);
8389 			src_ipif = NULL;
8390 		}
8391 		multirt_resolve_next = B_FALSE;
8392 
8393 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8394 		    ipif->ipif_ill->ill_name));
8395 
8396 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8397 		if (mctl_present)
8398 			io = (ipsec_out_t *)first_mp->b_rptr;
8399 
8400 		ipha = (ipha_t *)mp->b_rptr;
8401 
8402 		/*
8403 		 * Save the packet destination address, we may need it after
8404 		 * the packet has been consumed.
8405 		 */
8406 		ipha_dst = ipha->ipha_dst;
8407 
8408 		/*
8409 		 * If the interface is a pt-pt interface we look for an
8410 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8411 		 * local_address and the pt-pt destination address. Otherwise
8412 		 * we just match the local address.
8413 		 * NOTE: dst could be different than ipha->ipha_dst in case
8414 		 * of sending igmp multicast packets over a point-to-point
8415 		 * connection.
8416 		 * Thus we must be careful enough to check ipha_dst to be a
8417 		 * multicast address, otherwise it will take xmit_if path for
8418 		 * multicast packets resulting into kernel stack overflow by
8419 		 * repeated calls to ip_newroute_ipif from ire_send().
8420 		 */
8421 		if (CLASSD(ipha_dst) &&
8422 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8423 			goto err_ret;
8424 		}
8425 
8426 		/*
8427 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8428 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8429 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8430 		 * propagate its flags to the new ire.
8431 		 */
8432 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8433 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8434 			ip2dbg(("ip_newroute_ipif: "
8435 			    "ipif_lookup_multi_ire("
8436 			    "ipif %p, dst %08x) = fire %p\n",
8437 			    (void *)ipif, ntohl(dst), (void *)fire));
8438 		}
8439 
8440 		if (mctl_present && io->ipsec_out_attach_if) {
8441 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8442 			    io->ipsec_out_ill_index, B_FALSE);
8443 
8444 			/* Failure case frees things for us. */
8445 			if (attach_ill == NULL) {
8446 				ipif_refrele(ipif);
8447 				if (fire != NULL)
8448 					ire_refrele(fire);
8449 				return;
8450 			}
8451 
8452 			/*
8453 			 * Check if we need an ire that will not be
8454 			 * looked up by anybody else i.e. HIDDEN.
8455 			 */
8456 			if (ill_is_probeonly(attach_ill)) {
8457 				ire_marks = IRE_MARK_HIDDEN;
8458 			}
8459 			/*
8460 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8461 			 * case.
8462 			 */
8463 			dst_ill = ipif->ipif_ill;
8464 			/* attach_ill has been refheld by ip_grab_attach_ill */
8465 			ASSERT(dst_ill == attach_ill);
8466 		} else {
8467 			/*
8468 			 * If this is set by IP_XMIT_IF, then make sure that
8469 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8470 			 * specified ill.
8471 			 */
8472 			ASSERT((connp == NULL) ||
8473 			    (connp->conn_xmit_if_ill == NULL) ||
8474 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8475 			/*
8476 			 * If the interface belongs to an interface group,
8477 			 * make sure the next possible interface in the group
8478 			 * is used.  This encourages load spreading among
8479 			 * peers in an interface group.
8480 			 * Note: load spreading is disabled for RTF_MULTIRT
8481 			 * routes.
8482 			 */
8483 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8484 			    (fire->ire_flags & RTF_MULTIRT)) {
8485 				/*
8486 				 * Don't perform outbound load spreading
8487 				 * in the case of an RTF_MULTIRT issued route,
8488 				 * we actually typically want to replicate
8489 				 * outgoing packets through particular
8490 				 * interfaces.
8491 				 */
8492 				dst_ill = ipif->ipif_ill;
8493 				ill_refhold(dst_ill);
8494 			} else {
8495 				dst_ill = ip_newroute_get_dst_ill(
8496 				    ipif->ipif_ill);
8497 			}
8498 			if (dst_ill == NULL) {
8499 				if (ip_debug > 2) {
8500 					pr_addr_dbg("ip_newroute_ipif: "
8501 					    "no dst ill for dst %s\n",
8502 					    AF_INET, &dst);
8503 				}
8504 				goto err_ret;
8505 			}
8506 		}
8507 
8508 		/*
8509 		 * Pick a source address preferring non-deprecated ones.
8510 		 * Unlike ip_newroute, we don't do any source address
8511 		 * selection here since for multicast it really does not help
8512 		 * in inbound load spreading as in the unicast case.
8513 		 */
8514 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8515 		    (fire->ire_flags & RTF_SETSRC)) {
8516 			/*
8517 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8518 			 * on that interface. This ire has RTF_SETSRC flag, so
8519 			 * the source address of the packet must be changed.
8520 			 * Check that the ipif matching the requested source
8521 			 * address still exists.
8522 			 */
8523 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8524 			    zoneid, NULL, NULL, NULL, NULL);
8525 		}
8526 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8527 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8528 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8529 		    (src_ipif == NULL)) {
8530 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8531 			if (src_ipif == NULL) {
8532 				if (ip_debug > 2) {
8533 					/* ip1dbg */
8534 					pr_addr_dbg("ip_newroute_ipif: "
8535 					    "no src for dst %s",
8536 					    AF_INET, &dst);
8537 				}
8538 				ip1dbg((" through interface %s\n",
8539 				    dst_ill->ill_name));
8540 				goto err_ret;
8541 			}
8542 			ipif_refrele(ipif);
8543 			ipif = src_ipif;
8544 			ipif_refhold(ipif);
8545 		}
8546 		if (src_ipif == NULL) {
8547 			src_ipif = ipif;
8548 			ipif_refhold(src_ipif);
8549 		}
8550 
8551 		/*
8552 		 * Assign a source address while we have the conn.
8553 		 * We can't have ip_wput_ire pick a source address when the
8554 		 * packet returns from arp since conn_unspec_src might be set
8555 		 * and we loose the conn when going through arp.
8556 		 */
8557 		if (ipha->ipha_src == INADDR_ANY &&
8558 		    (connp == NULL || !connp->conn_unspec_src)) {
8559 			ipha->ipha_src = src_ipif->ipif_src_addr;
8560 		}
8561 
8562 		/*
8563 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8564 		 * interface does not have an interface ire.
8565 		 * Example: Thousands of mobileip PPP interfaces to mobile
8566 		 * nodes. We don't want to create interface ires because
8567 		 * packets from other mobile nodes must not take the route
8568 		 * via interface ires to the visiting mobile node without
8569 		 * going through the home agent, in absence of mobileip
8570 		 * route optimization.
8571 		 */
8572 		if (CLASSD(ipha_dst) && (connp == NULL ||
8573 		    connp->conn_xmit_if_ill == NULL)) {
8574 			/* ipif_to_ire returns an held ire */
8575 			ire = ipif_to_ire(ipif);
8576 			if (ire == NULL)
8577 				goto err_ret;
8578 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8579 				goto err_ret;
8580 			/*
8581 			 * ihandle is needed when the ire is added to
8582 			 * cache table.
8583 			 */
8584 			save_ire = ire;
8585 			ihandle = save_ire->ire_ihandle;
8586 
8587 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8588 			    "flags %04x\n",
8589 			    (void *)ire, (void *)ipif, flags));
8590 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8591 			    (fire->ire_flags & RTF_MULTIRT)) {
8592 				/*
8593 				 * As requested by flags, an IRE_OFFSUBNET was
8594 				 * looked up on that interface. This ire has
8595 				 * RTF_MULTIRT flag, so the resolution loop will
8596 				 * be re-entered to resolve additional routes on
8597 				 * other interfaces. For that purpose, a copy of
8598 				 * the packet is performed at this point.
8599 				 */
8600 				fire->ire_last_used_time = lbolt;
8601 				copy_mp = copymsg(first_mp);
8602 				if (copy_mp) {
8603 					MULTIRT_DEBUG_TAG(copy_mp);
8604 				}
8605 			}
8606 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8607 			    (fire->ire_flags & RTF_SETSRC)) {
8608 				/*
8609 				 * As requested by flags, an IRE_OFFSUBET was
8610 				 * looked up on that interface. This ire has
8611 				 * RTF_SETSRC flag, so the source address of the
8612 				 * packet must be changed.
8613 				 */
8614 				ipha->ipha_src = fire->ire_src_addr;
8615 			}
8616 		} else {
8617 			ASSERT((connp == NULL) ||
8618 			    (connp->conn_xmit_if_ill != NULL) ||
8619 			    (connp->conn_dontroute));
8620 			/*
8621 			 * The only ways we can come here are:
8622 			 * 1) IP_XMIT_IF socket option is set
8623 			 * 2) ICMP error message generated from
8624 			 *    ip_mrtun_forward() routine and it needs
8625 			 *    to go through the specified ill.
8626 			 * 3) SO_DONTROUTE socket option is set
8627 			 * In all cases, the new ire will not be added
8628 			 * into cache table.
8629 			 */
8630 			ire_marks |= IRE_MARK_NOADD;
8631 		}
8632 
8633 		switch (ipif->ipif_net_type) {
8634 		case IRE_IF_NORESOLVER: {
8635 			/* We have what we need to build an IRE_CACHE. */
8636 			mblk_t	*dlureq_mp;
8637 
8638 			/*
8639 			 * Create a new dlureq_mp with the
8640 			 * IP gateway address as destination address in the
8641 			 * DLPI hdr if the physical length is exactly 4 bytes.
8642 			 */
8643 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8644 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8645 				    dst_ill->ill_phys_addr_length,
8646 				    dst_ill->ill_sap,
8647 				    dst_ill->ill_sap_length);
8648 			} else {
8649 				/* use the value set in ip_ll_subnet_defaults */
8650 				dlureq_mp = ill_dlur_gen(NULL,
8651 				    dst_ill->ill_phys_addr_length,
8652 				    dst_ill->ill_sap,
8653 				    dst_ill->ill_sap_length);
8654 			}
8655 
8656 			if (dlureq_mp == NULL)
8657 				break;
8658 			/*
8659 			 * The new ire inherits the IRE_OFFSUBNET flags
8660 			 * and source address, if this was requested.
8661 			 */
8662 			ire = ire_create(
8663 			    (uchar_t *)&dst,		/* dest address */
8664 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8665 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8666 			    NULL,			/* gateway address */
8667 			    NULL,
8668 			    &ipif->ipif_mtu,
8669 			    NULL,			/* Fast Path header */
8670 			    dst_ill->ill_rq,		/* recv-from queue */
8671 			    dst_ill->ill_wq,		/* send-to queue */
8672 			    IRE_CACHE,
8673 			    dlureq_mp,
8674 			    src_ipif,
8675 			    NULL,
8676 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8677 			    (fire != NULL) ?		/* Parent handle */
8678 				fire->ire_phandle : 0,
8679 			    ihandle,			/* Interface handle */
8680 			    (fire != NULL) ?
8681 				(fire->ire_flags &
8682 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8683 			    (save_ire == NULL ? &ire_uinfo_null :
8684 				&save_ire->ire_uinfo),
8685 			    NULL,
8686 			    NULL);
8687 
8688 			freeb(dlureq_mp);
8689 
8690 			if (ire == NULL) {
8691 				if (save_ire != NULL)
8692 					ire_refrele(save_ire);
8693 				break;
8694 			}
8695 
8696 			ire->ire_marks |= ire_marks;
8697 
8698 			/*
8699 			 * If IRE_MARK_NOADD is set then we need to convert
8700 			 * the max_fragp to a useable value now. This is
8701 			 * normally done in ire_add_v[46].
8702 			 */
8703 			if (ire->ire_marks & IRE_MARK_NOADD) {
8704 				uint_t  max_frag;
8705 
8706 				max_frag = *ire->ire_max_fragp;
8707 				ire->ire_max_fragp = NULL;
8708 				ire->ire_max_frag = max_frag;
8709 			}
8710 
8711 			/* Prevent save_ire from getting deleted */
8712 			if (save_ire != NULL) {
8713 				IRB_REFHOLD(save_ire->ire_bucket);
8714 				/* Has it been removed already ? */
8715 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8716 					IRB_REFRELE(save_ire->ire_bucket);
8717 					ire_refrele(save_ire);
8718 					break;
8719 				}
8720 			}
8721 
8722 			ire_add_then_send(q, ire, first_mp);
8723 
8724 			/* Assert that save_ire is not deleted yet. */
8725 			if (save_ire != NULL) {
8726 				ASSERT(save_ire->ire_ptpn != NULL);
8727 				IRB_REFRELE(save_ire->ire_bucket);
8728 				ire_refrele(save_ire);
8729 				save_ire = NULL;
8730 			}
8731 			if (fire != NULL) {
8732 				ire_refrele(fire);
8733 				fire = NULL;
8734 			}
8735 
8736 			/*
8737 			 * the resolution loop is re-entered if this
8738 			 * was requested through flags and if we
8739 			 * actually are in a multirouting case.
8740 			 */
8741 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8742 				boolean_t need_resolve =
8743 				    ire_multirt_need_resolve(ipha_dst,
8744 					MBLK_GETLABEL(copy_mp));
8745 				if (!need_resolve) {
8746 					MULTIRT_DEBUG_UNTAG(copy_mp);
8747 					freemsg(copy_mp);
8748 					copy_mp = NULL;
8749 				} else {
8750 					/*
8751 					 * ipif_lookup_group() calls
8752 					 * ire_lookup_multi() that uses
8753 					 * ire_ftable_lookup() to find
8754 					 * an IRE_INTERFACE for the group.
8755 					 * In the multirt case,
8756 					 * ire_lookup_multi() then invokes
8757 					 * ire_multirt_lookup() to find
8758 					 * the next resolvable ire.
8759 					 * As a result, we obtain an new
8760 					 * interface, derived from the
8761 					 * next ire.
8762 					 */
8763 					ipif_refrele(ipif);
8764 					ipif = ipif_lookup_group(ipha_dst,
8765 					    zoneid);
8766 					ip2dbg(("ip_newroute_ipif: "
8767 					    "multirt dst %08x, ipif %p\n",
8768 					    htonl(dst), (void *)ipif));
8769 					if (ipif != NULL) {
8770 						mp = copy_mp;
8771 						copy_mp = NULL;
8772 						multirt_resolve_next = B_TRUE;
8773 						continue;
8774 					} else {
8775 						freemsg(copy_mp);
8776 					}
8777 				}
8778 			}
8779 			if (ipif != NULL)
8780 				ipif_refrele(ipif);
8781 			ill_refrele(dst_ill);
8782 			ipif_refrele(src_ipif);
8783 			return;
8784 		}
8785 		case IRE_IF_RESOLVER:
8786 			/*
8787 			 * We can't build an IRE_CACHE yet, but at least
8788 			 * we found a resolver that can help.
8789 			 */
8790 			res_mp = dst_ill->ill_resolver_mp;
8791 			if (!OK_RESOLVER_MP(res_mp))
8792 				break;
8793 
8794 			/*
8795 			 * We obtain a partial IRE_CACHE which we will pass
8796 			 * along with the resolver query.  When the response
8797 			 * comes back it will be there ready for us to add.
8798 			 * The new ire inherits the IRE_OFFSUBNET flags
8799 			 * and source address, if this was requested.
8800 			 * The ire_max_frag is atomically set under the
8801 			 * irebucket lock in ire_add_v[46]. Only in the
8802 			 * case of IRE_MARK_NOADD, we set it here itself.
8803 			 */
8804 			ire = ire_create_mp(
8805 			    (uchar_t *)&dst,		/* dest address */
8806 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8807 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8808 			    NULL,			/* gateway address */
8809 			    NULL,			/* no in_src_addr */
8810 			    (ire_marks & IRE_MARK_NOADD) ?
8811 				ipif->ipif_mtu : 0,	/* max_frag */
8812 			    NULL,			/* Fast path header */
8813 			    dst_ill->ill_rq,		/* recv-from queue */
8814 			    dst_ill->ill_wq,		/* send-to queue */
8815 			    IRE_CACHE,
8816 			    res_mp,
8817 			    src_ipif,
8818 			    NULL,
8819 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8820 			    (fire != NULL) ?		/* Parent handle */
8821 				fire->ire_phandle : 0,
8822 			    ihandle,			/* Interface handle */
8823 			    (fire != NULL) ?		/* flags if any */
8824 				(fire->ire_flags &
8825 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8826 			    (save_ire == NULL ? &ire_uinfo_null :
8827 				&save_ire->ire_uinfo),
8828 			    NULL,
8829 			    NULL);
8830 
8831 			if (save_ire != NULL) {
8832 				ire_refrele(save_ire);
8833 				save_ire = NULL;
8834 			}
8835 			if (ire == NULL)
8836 				break;
8837 
8838 			ire->ire_marks |= ire_marks;
8839 			/*
8840 			 * Construct message chain for the resolver of the
8841 			 * form:
8842 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8843 			 *
8844 			 * NOTE : ire will be added later when the response
8845 			 * comes back from ARP. If the response does not
8846 			 * come back, ARP frees the packet. For this reason,
8847 			 * we can't REFHOLD the bucket of save_ire to prevent
8848 			 * deletions. We may not be able to REFRELE the
8849 			 * bucket if the response never comes back.
8850 			 * Thus, before adding the ire, ire_add_v4 will make
8851 			 * sure that the interface route does not get deleted.
8852 			 * This is the only case unlike ip_newroute_v6,
8853 			 * ip_newroute_ipif_v6 where we can always prevent
8854 			 * deletions because ire_add_then_send is called after
8855 			 * creating the IRE.
8856 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8857 			 * does not add this IRE into the IRE CACHE.
8858 			 */
8859 			ASSERT(ire->ire_mp != NULL);
8860 			ire->ire_mp->b_cont = first_mp;
8861 			/* Have saved_mp handy, for cleanup if canput fails */
8862 			saved_mp = mp;
8863 			mp = ire->ire_dlureq_mp;
8864 			ASSERT(mp != NULL);
8865 			ire->ire_dlureq_mp = NULL;
8866 			linkb(mp, ire->ire_mp);
8867 
8868 			/*
8869 			 * Fill in the source and dest addrs for the resolver.
8870 			 * NOTE: this depends on memory layouts imposed by
8871 			 * ill_init().
8872 			 */
8873 			areq = (areq_t *)mp->b_rptr;
8874 			addrp = (ipaddr_t *)((char *)areq +
8875 			    areq->areq_sender_addr_offset);
8876 			*addrp = ire->ire_src_addr;
8877 			addrp = (ipaddr_t *)((char *)areq +
8878 			    areq->areq_target_addr_offset);
8879 			*addrp = dst;
8880 			/* Up to the resolver. */
8881 			if (canputnext(dst_ill->ill_rq)) {
8882 				putnext(dst_ill->ill_rq, mp);
8883 				/*
8884 				 * The response will come back in ip_wput
8885 				 * with db_type IRE_DB_TYPE.
8886 				 */
8887 			} else {
8888 				ire->ire_dlureq_mp = mp;
8889 				mp->b_cont = NULL;
8890 				ire_delete(ire);
8891 				saved_mp->b_next = NULL;
8892 				saved_mp->b_prev = NULL;
8893 				freemsg(first_mp);
8894 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8895 			}
8896 
8897 			if (fire != NULL) {
8898 				ire_refrele(fire);
8899 				fire = NULL;
8900 			}
8901 
8902 
8903 			/*
8904 			 * The resolution loop is re-entered if this was
8905 			 * requested through flags and we actually are
8906 			 * in a multirouting case.
8907 			 */
8908 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8909 				boolean_t need_resolve =
8910 				    ire_multirt_need_resolve(ipha_dst,
8911 					MBLK_GETLABEL(copy_mp));
8912 				if (!need_resolve) {
8913 					MULTIRT_DEBUG_UNTAG(copy_mp);
8914 					freemsg(copy_mp);
8915 					copy_mp = NULL;
8916 				} else {
8917 					/*
8918 					 * ipif_lookup_group() calls
8919 					 * ire_lookup_multi() that uses
8920 					 * ire_ftable_lookup() to find
8921 					 * an IRE_INTERFACE for the group.
8922 					 * In the multirt case,
8923 					 * ire_lookup_multi() then invokes
8924 					 * ire_multirt_lookup() to find
8925 					 * the next resolvable ire.
8926 					 * As a result, we obtain an new
8927 					 * interface, derived from the
8928 					 * next ire.
8929 					 */
8930 					ipif_refrele(ipif);
8931 					ipif = ipif_lookup_group(ipha_dst,
8932 					    zoneid);
8933 					if (ipif != NULL) {
8934 						mp = copy_mp;
8935 						copy_mp = NULL;
8936 						multirt_resolve_next = B_TRUE;
8937 						continue;
8938 					} else {
8939 						freemsg(copy_mp);
8940 					}
8941 				}
8942 			}
8943 			if (ipif != NULL)
8944 				ipif_refrele(ipif);
8945 			ill_refrele(dst_ill);
8946 			ipif_refrele(src_ipif);
8947 			return;
8948 		default:
8949 			break;
8950 		}
8951 	} while (multirt_resolve_next);
8952 
8953 err_ret:
8954 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8955 	if (fire != NULL)
8956 		ire_refrele(fire);
8957 	ipif_refrele(ipif);
8958 	/* Did this packet originate externally? */
8959 	if (dst_ill != NULL)
8960 		ill_refrele(dst_ill);
8961 	if (src_ipif != NULL)
8962 		ipif_refrele(src_ipif);
8963 	if (mp->b_prev || mp->b_next) {
8964 		mp->b_next = NULL;
8965 		mp->b_prev = NULL;
8966 	} else {
8967 		/*
8968 		 * Since ip_wput() isn't close to finished, we fill
8969 		 * in enough of the header for credible error reporting.
8970 		 */
8971 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8972 			/* Failed */
8973 			freemsg(first_mp);
8974 			if (ire != NULL)
8975 				ire_refrele(ire);
8976 			return;
8977 		}
8978 	}
8979 	/*
8980 	 * At this point we will have ire only if RTF_BLACKHOLE
8981 	 * or RTF_REJECT flags are set on the IRE. It will not
8982 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8983 	 */
8984 	if (ire != NULL) {
8985 		if (ire->ire_flags & RTF_BLACKHOLE) {
8986 			ire_refrele(ire);
8987 			freemsg(first_mp);
8988 			return;
8989 		}
8990 		ire_refrele(ire);
8991 	}
8992 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8993 }
8994 
8995 /* Name/Value Table Lookup Routine */
8996 char *
8997 ip_nv_lookup(nv_t *nv, int value)
8998 {
8999 	if (!nv)
9000 		return (NULL);
9001 	for (; nv->nv_name; nv++) {
9002 		if (nv->nv_value == value)
9003 			return (nv->nv_name);
9004 	}
9005 	return ("unknown");
9006 }
9007 
9008 /*
9009  * one day it can be patched to 1 from /etc/system for machines that have few
9010  * fast network interfaces feeding multiple cpus.
9011  */
9012 int ill_stream_putlocks = 0;
9013 
9014 /*
9015  * This is a module open, i.e. this is a control stream for access
9016  * to a DLPI device.  We allocate an ill_t as the instance data in
9017  * this case.
9018  */
9019 int
9020 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9021 {
9022 	uint32_t mem_cnt;
9023 	uint32_t cpu_cnt;
9024 	uint32_t min_cnt;
9025 	pgcnt_t mem_avail;
9026 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
9027 	ill_t	*ill;
9028 	int	err;
9029 
9030 	/*
9031 	 * Prevent unprivileged processes from pushing IP so that
9032 	 * they can't send raw IP.
9033 	 */
9034 	if (secpolicy_net_rawaccess(credp) != 0)
9035 		return (EPERM);
9036 
9037 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9038 	q->q_ptr = WR(q)->q_ptr = ill;
9039 
9040 	/*
9041 	 * ill_init initializes the ill fields and then sends down
9042 	 * down a DL_INFO_REQ after calling qprocson.
9043 	 */
9044 	err = ill_init(q, ill);
9045 	if (err != 0) {
9046 		mi_free(ill);
9047 		q->q_ptr = NULL;
9048 		WR(q)->q_ptr = NULL;
9049 		return (err);
9050 	}
9051 
9052 	/* ill_init initializes the ipsq marking this thread as writer */
9053 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9054 	/* Wait for the DL_INFO_ACK */
9055 	mutex_enter(&ill->ill_lock);
9056 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9057 		/*
9058 		 * Return value of 0 indicates a pending signal.
9059 		 */
9060 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9061 		if (err == 0) {
9062 			mutex_exit(&ill->ill_lock);
9063 			(void) ip_close(q, 0);
9064 			return (EINTR);
9065 		}
9066 	}
9067 	mutex_exit(&ill->ill_lock);
9068 
9069 	/*
9070 	 * ip_rput_other could have set an error  in ill_error on
9071 	 * receipt of M_ERROR.
9072 	 */
9073 
9074 	err = ill->ill_error;
9075 	if (err != 0) {
9076 		(void) ip_close(q, 0);
9077 		return (err);
9078 	}
9079 
9080 	/*
9081 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9082 	 * size and the cpu speed of the machine. This is upper
9083 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9084 	 * and is lower bounded by the compile time value of
9085 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9086 	 * ip6_ire_max_bucket_cnt.
9087 	 */
9088 	mem_avail = kmem_avail();
9089 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9090 	    ip_cache_table_size / sizeof (ire_t);
9091 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9092 
9093 	min_cnt = MIN(cpu_cnt, mem_cnt);
9094 	if (min_cnt < ip_ire_min_bucket_cnt)
9095 		min_cnt = ip_ire_min_bucket_cnt;
9096 	if (ip_ire_max_bucket_cnt > min_cnt) {
9097 		ip_ire_max_bucket_cnt = min_cnt;
9098 	}
9099 
9100 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9101 	    ip6_cache_table_size / sizeof (ire_t);
9102 	min_cnt = MIN(cpu_cnt, mem_cnt);
9103 	if (min_cnt < ip6_ire_min_bucket_cnt)
9104 		min_cnt = ip6_ire_min_bucket_cnt;
9105 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9106 		ip6_ire_max_bucket_cnt = min_cnt;
9107 	}
9108 
9109 	ill->ill_credp = credp;
9110 	crhold(credp);
9111 
9112 	mutex_enter(&ip_mi_lock);
9113 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9114 	mutex_exit(&ip_mi_lock);
9115 	if (err) {
9116 		(void) ip_close(q, 0);
9117 		return (err);
9118 	}
9119 	return (0);
9120 }
9121 
9122 /* IP open routine. */
9123 int
9124 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9125 {
9126 	conn_t 		*connp;
9127 	major_t		maj;
9128 
9129 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9130 
9131 	/* Allow reopen. */
9132 	if (q->q_ptr != NULL)
9133 		return (0);
9134 
9135 	if (sflag & MODOPEN) {
9136 		/* This is a module open */
9137 		return (ip_modopen(q, devp, flag, sflag, credp));
9138 	}
9139 
9140 	/*
9141 	 * We are opening as a device. This is an IP client stream, and we
9142 	 * allocate an conn_t as the instance data.
9143 	 */
9144 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9145 	connp->conn_upq = q;
9146 	q->q_ptr = WR(q)->q_ptr = connp;
9147 
9148 	if (flag & SO_SOCKSTR)
9149 		connp->conn_flags |= IPCL_SOCKET;
9150 
9151 	/* Minor tells us which /dev entry was opened */
9152 	if (geteminor(*devp) == IPV6_MINOR) {
9153 		connp->conn_flags |= IPCL_ISV6;
9154 		connp->conn_af_isv6 = B_TRUE;
9155 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9156 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9157 	} else {
9158 		connp->conn_af_isv6 = B_FALSE;
9159 		connp->conn_pkt_isv6 = B_FALSE;
9160 	}
9161 
9162 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9163 		q->q_ptr = WR(q)->q_ptr = NULL;
9164 		CONN_DEC_REF(connp);
9165 		return (EBUSY);
9166 	}
9167 
9168 	maj = getemajor(*devp);
9169 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9170 
9171 	/*
9172 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9173 	 */
9174 	connp->conn_cred = credp;
9175 	crhold(connp->conn_cred);
9176 
9177 	/*
9178 	 * If the caller has the process-wide flag set, then default to MAC
9179 	 * exempt mode.  This allows read-down to unlabeled hosts.
9180 	 */
9181 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9182 		connp->conn_mac_exempt = B_TRUE;
9183 
9184 	connp->conn_zoneid = getzoneid();
9185 
9186 	/*
9187 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9188 	 * administrative ops.  In these cases, we just need a normal conn_t
9189 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9190 	 * an error will be returned.
9191 	 */
9192 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9193 		connp->conn_rq = q;
9194 		connp->conn_wq = WR(q);
9195 	} else {
9196 		connp->conn_ulp = IPPROTO_SCTP;
9197 		connp->conn_rq = connp->conn_wq = NULL;
9198 	}
9199 	/* Non-zero default values */
9200 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9201 
9202 	/*
9203 	 * Make the conn globally visible to walkers
9204 	 */
9205 	mutex_enter(&connp->conn_lock);
9206 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9207 	mutex_exit(&connp->conn_lock);
9208 	ASSERT(connp->conn_ref == 1);
9209 
9210 	qprocson(q);
9211 
9212 	return (0);
9213 }
9214 
9215 /*
9216  * Change q_qinfo based on the value of isv6.
9217  * This can not called on an ill queue.
9218  * Note that there is no race since either q_qinfo works for conn queues - it
9219  * is just an optimization to enter the best wput routine directly.
9220  */
9221 void
9222 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9223 {
9224 	ASSERT(q->q_flag & QREADR);
9225 	ASSERT(WR(q)->q_next == NULL);
9226 	ASSERT(q->q_ptr != NULL);
9227 
9228 	if (minor == IPV6_MINOR)  {
9229 		if (bump_mib)
9230 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9231 		q->q_qinfo = &rinit_ipv6;
9232 		WR(q)->q_qinfo = &winit_ipv6;
9233 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9234 	} else {
9235 		if (bump_mib)
9236 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9237 		q->q_qinfo = &rinit;
9238 		WR(q)->q_qinfo = &winit;
9239 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9240 	}
9241 
9242 }
9243 
9244 /*
9245  * See if IPsec needs loading because of the options in mp.
9246  */
9247 static boolean_t
9248 ipsec_opt_present(mblk_t *mp)
9249 {
9250 	uint8_t *optcp, *next_optcp, *opt_endcp;
9251 	struct opthdr *opt;
9252 	struct T_opthdr *topt;
9253 	int opthdr_len;
9254 	t_uscalar_t optname, optlevel;
9255 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9256 	ipsec_req_t *ipsr;
9257 
9258 	/*
9259 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9260 	 * return TRUE.
9261 	 */
9262 
9263 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9264 	opt_endcp = optcp + tor->OPT_length;
9265 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9266 		opthdr_len = sizeof (struct T_opthdr);
9267 	} else {		/* O_OPTMGMT_REQ */
9268 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9269 		opthdr_len = sizeof (struct opthdr);
9270 	}
9271 	for (; optcp < opt_endcp; optcp = next_optcp) {
9272 		if (optcp + opthdr_len > opt_endcp)
9273 			return (B_FALSE);	/* Not enough option header. */
9274 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9275 			topt = (struct T_opthdr *)optcp;
9276 			optlevel = topt->level;
9277 			optname = topt->name;
9278 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9279 		} else {
9280 			opt = (struct opthdr *)optcp;
9281 			optlevel = opt->level;
9282 			optname = opt->name;
9283 			next_optcp = optcp + opthdr_len +
9284 			    _TPI_ALIGN_OPT(opt->len);
9285 		}
9286 		if ((next_optcp < optcp) || /* wraparound pointer space */
9287 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9288 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9289 			return (B_FALSE); /* bad option buffer */
9290 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9291 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9292 			/*
9293 			 * Check to see if it's an all-bypass or all-zeroes
9294 			 * IPsec request.  Don't bother loading IPsec if
9295 			 * the socket doesn't want to use it.  (A good example
9296 			 * is a bypass request.)
9297 			 *
9298 			 * Basically, if any of the non-NEVER bits are set,
9299 			 * load IPsec.
9300 			 */
9301 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9302 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9303 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9304 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9305 			    != 0)
9306 				return (B_TRUE);
9307 		}
9308 	}
9309 	return (B_FALSE);
9310 }
9311 
9312 /*
9313  * If conn is is waiting for ipsec to finish loading, kick it.
9314  */
9315 /* ARGSUSED */
9316 static void
9317 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9318 {
9319 	t_scalar_t	optreq_prim;
9320 	mblk_t		*mp;
9321 	cred_t		*cr;
9322 	int		err = 0;
9323 
9324 	/*
9325 	 * This function is called, after ipsec loading is complete.
9326 	 * Since IP checks exclusively and atomically (i.e it prevents
9327 	 * ipsec load from completing until ip_optcom_req completes)
9328 	 * whether ipsec load is complete, there cannot be a race with IP
9329 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9330 	 */
9331 	mutex_enter(&connp->conn_lock);
9332 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9333 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9334 		mp = connp->conn_ipsec_opt_mp;
9335 		connp->conn_ipsec_opt_mp = NULL;
9336 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9337 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9338 		mutex_exit(&connp->conn_lock);
9339 
9340 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9341 
9342 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9343 		if (optreq_prim == T_OPTMGMT_REQ) {
9344 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9345 			    &ip_opt_obj);
9346 		} else {
9347 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9348 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9349 			    &ip_opt_obj);
9350 		}
9351 		if (err != EINPROGRESS)
9352 			CONN_OPER_PENDING_DONE(connp);
9353 		return;
9354 	}
9355 	mutex_exit(&connp->conn_lock);
9356 }
9357 
9358 /*
9359  * Called from the ipsec_loader thread, outside any perimeter, to tell
9360  * ip qenable any of the queues waiting for the ipsec loader to
9361  * complete.
9362  *
9363  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9364  * are done with this lock held, so it's guaranteed that none of the
9365  * links will change along the way.
9366  */
9367 void
9368 ip_ipsec_load_complete()
9369 {
9370 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9371 }
9372 
9373 /*
9374  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9375  * determines the grp on which it has to become exclusive, queues the mp
9376  * and sq draining restarts the optmgmt
9377  */
9378 static boolean_t
9379 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9380 {
9381 	conn_t *connp;
9382 
9383 	/*
9384 	 * Take IPsec requests and treat them special.
9385 	 */
9386 	if (ipsec_opt_present(mp)) {
9387 		/* First check if IPsec is loaded. */
9388 		mutex_enter(&ipsec_loader_lock);
9389 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9390 			mutex_exit(&ipsec_loader_lock);
9391 			return (B_FALSE);
9392 		}
9393 		connp = Q_TO_CONN(q);
9394 		mutex_enter(&connp->conn_lock);
9395 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9396 
9397 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9398 		connp->conn_ipsec_opt_mp = mp;
9399 		mutex_exit(&connp->conn_lock);
9400 		mutex_exit(&ipsec_loader_lock);
9401 
9402 		ipsec_loader_loadnow();
9403 		return (B_TRUE);
9404 	}
9405 	return (B_FALSE);
9406 }
9407 
9408 /*
9409  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9410  * all of them are copied to the conn_t. If the req is "zero", the policy is
9411  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9412  * fields.
9413  * We keep only the latest setting of the policy and thus policy setting
9414  * is not incremental/cumulative.
9415  *
9416  * Requests to set policies with multiple alternative actions will
9417  * go through a different API.
9418  */
9419 int
9420 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9421 {
9422 	uint_t ah_req = 0;
9423 	uint_t esp_req = 0;
9424 	uint_t se_req = 0;
9425 	ipsec_selkey_t sel;
9426 	ipsec_act_t *actp = NULL;
9427 	uint_t nact;
9428 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9429 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9430 	ipsec_policy_root_t *pr;
9431 	ipsec_policy_head_t *ph;
9432 	int fam;
9433 	boolean_t is_pol_reset;
9434 	int error = 0;
9435 
9436 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9437 
9438 	/*
9439 	 * The IP_SEC_OPT option does not allow variable length parameters,
9440 	 * hence a request cannot be NULL.
9441 	 */
9442 	if (req == NULL)
9443 		return (EINVAL);
9444 
9445 	ah_req = req->ipsr_ah_req;
9446 	esp_req = req->ipsr_esp_req;
9447 	se_req = req->ipsr_self_encap_req;
9448 
9449 	/*
9450 	 * Are we dealing with a request to reset the policy (i.e.
9451 	 * zero requests).
9452 	 */
9453 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9454 	    (esp_req & REQ_MASK) == 0 &&
9455 	    (se_req & REQ_MASK) == 0);
9456 
9457 	if (!is_pol_reset) {
9458 		/*
9459 		 * If we couldn't load IPsec, fail with "protocol
9460 		 * not supported".
9461 		 * IPsec may not have been loaded for a request with zero
9462 		 * policies, so we don't fail in this case.
9463 		 */
9464 		mutex_enter(&ipsec_loader_lock);
9465 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9466 			mutex_exit(&ipsec_loader_lock);
9467 			return (EPROTONOSUPPORT);
9468 		}
9469 		mutex_exit(&ipsec_loader_lock);
9470 
9471 		/*
9472 		 * Test for valid requests. Invalid algorithms
9473 		 * need to be tested by IPSEC code because new
9474 		 * algorithms can be added dynamically.
9475 		 */
9476 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9477 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9478 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9479 			return (EINVAL);
9480 		}
9481 
9482 		/*
9483 		 * Only privileged users can issue these
9484 		 * requests.
9485 		 */
9486 		if (((ah_req & IPSEC_PREF_NEVER) ||
9487 		    (esp_req & IPSEC_PREF_NEVER) ||
9488 		    (se_req & IPSEC_PREF_NEVER)) &&
9489 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9490 			return (EPERM);
9491 		}
9492 
9493 		/*
9494 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9495 		 * are mutually exclusive.
9496 		 */
9497 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9498 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9499 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9500 			/* Both of them are set */
9501 			return (EINVAL);
9502 		}
9503 	}
9504 
9505 	mutex_enter(&connp->conn_lock);
9506 
9507 	/*
9508 	 * If we have already cached policies in ip_bind_connected*(), don't
9509 	 * let them change now. We cache policies for connections
9510 	 * whose src,dst [addr, port] is known.  The exception to this is
9511 	 * tunnels.  Tunnels are allowed to change policies after having
9512 	 * become fully bound.
9513 	 */
9514 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9515 		mutex_exit(&connp->conn_lock);
9516 		return (EINVAL);
9517 	}
9518 
9519 	/*
9520 	 * We have a zero policies, reset the connection policy if already
9521 	 * set. This will cause the connection to inherit the
9522 	 * global policy, if any.
9523 	 */
9524 	if (is_pol_reset) {
9525 		if (connp->conn_policy != NULL) {
9526 			IPPH_REFRELE(connp->conn_policy);
9527 			connp->conn_policy = NULL;
9528 		}
9529 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9530 		connp->conn_in_enforce_policy = B_FALSE;
9531 		connp->conn_out_enforce_policy = B_FALSE;
9532 		mutex_exit(&connp->conn_lock);
9533 		return (0);
9534 	}
9535 
9536 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9537 	if (ph == NULL)
9538 		goto enomem;
9539 
9540 	ipsec_actvec_from_req(req, &actp, &nact);
9541 	if (actp == NULL)
9542 		goto enomem;
9543 
9544 	/*
9545 	 * Always allocate IPv4 policy entries, since they can also
9546 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9547 	 */
9548 	bzero(&sel, sizeof (sel));
9549 	sel.ipsl_valid = IPSL_IPV4;
9550 
9551 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9552 	if (pin4 == NULL)
9553 		goto enomem;
9554 
9555 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9556 	if (pout4 == NULL)
9557 		goto enomem;
9558 
9559 	if (connp->conn_pkt_isv6) {
9560 		/*
9561 		 * We're looking at a v6 socket, also allocate the
9562 		 * v6-specific entries...
9563 		 */
9564 		sel.ipsl_valid = IPSL_IPV6;
9565 		pin6 = ipsec_policy_create(&sel, actp, nact,
9566 		    IPSEC_PRIO_SOCKET);
9567 		if (pin6 == NULL)
9568 			goto enomem;
9569 
9570 		pout6 = ipsec_policy_create(&sel, actp, nact,
9571 		    IPSEC_PRIO_SOCKET);
9572 		if (pout6 == NULL)
9573 			goto enomem;
9574 
9575 		/*
9576 		 * .. and file them away in the right place.
9577 		 */
9578 		fam = IPSEC_AF_V6;
9579 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9580 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9581 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9582 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9583 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9584 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9585 	}
9586 
9587 	ipsec_actvec_free(actp, nact);
9588 
9589 	/*
9590 	 * File the v4 policies.
9591 	 */
9592 	fam = IPSEC_AF_V4;
9593 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9594 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9595 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9596 
9597 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9598 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9599 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9600 
9601 	/*
9602 	 * If the requests need security, set enforce_policy.
9603 	 * If the requests are IPSEC_PREF_NEVER, one should
9604 	 * still set conn_out_enforce_policy so that an ipsec_out
9605 	 * gets attached in ip_wput. This is needed so that
9606 	 * for connections that we don't cache policy in ip_bind,
9607 	 * if global policy matches in ip_wput_attach_policy, we
9608 	 * don't wrongly inherit global policy. Similarly, we need
9609 	 * to set conn_in_enforce_policy also so that we don't verify
9610 	 * policy wrongly.
9611 	 */
9612 	if ((ah_req & REQ_MASK) != 0 ||
9613 	    (esp_req & REQ_MASK) != 0 ||
9614 	    (se_req & REQ_MASK) != 0) {
9615 		connp->conn_in_enforce_policy = B_TRUE;
9616 		connp->conn_out_enforce_policy = B_TRUE;
9617 		connp->conn_flags |= IPCL_CHECK_POLICY;
9618 	}
9619 
9620 	/*
9621 	 * Tunnels are allowed to set policy after having been fully bound.
9622 	 * If that's the case, cache policy here.
9623 	 */
9624 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9625 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9626 
9627 	mutex_exit(&connp->conn_lock);
9628 	return (error);
9629 #undef REQ_MASK
9630 
9631 	/*
9632 	 * Common memory-allocation-failure exit path.
9633 	 */
9634 enomem:
9635 	mutex_exit(&connp->conn_lock);
9636 	if (actp != NULL)
9637 		ipsec_actvec_free(actp, nact);
9638 	if (pin4 != NULL)
9639 		IPPOL_REFRELE(pin4);
9640 	if (pout4 != NULL)
9641 		IPPOL_REFRELE(pout4);
9642 	if (pin6 != NULL)
9643 		IPPOL_REFRELE(pin6);
9644 	if (pout6 != NULL)
9645 		IPPOL_REFRELE(pout6);
9646 	return (ENOMEM);
9647 }
9648 
9649 /*
9650  * Only for options that pass in an IP addr. Currently only V4 options
9651  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9652  * So this function assumes level is IPPROTO_IP
9653  */
9654 int
9655 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9656     mblk_t *first_mp)
9657 {
9658 	ipif_t *ipif = NULL;
9659 	int error;
9660 	ill_t *ill;
9661 	int zoneid;
9662 
9663 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9664 
9665 	if (addr != INADDR_ANY || checkonly) {
9666 		ASSERT(connp != NULL);
9667 		zoneid = IPCL_ZONEID(connp);
9668 		if (option == IP_NEXTHOP) {
9669 			ipif = ipif_lookup_onlink_addr(addr, zoneid);
9670 		} else {
9671 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
9672 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9673 			    &error);
9674 		}
9675 		if (ipif == NULL) {
9676 			if (error == EINPROGRESS)
9677 				return (error);
9678 			else if ((option == IP_MULTICAST_IF) ||
9679 			    (option == IP_NEXTHOP))
9680 				return (EHOSTUNREACH);
9681 			else
9682 				return (EINVAL);
9683 		} else if (checkonly) {
9684 			if (option == IP_MULTICAST_IF) {
9685 				ill = ipif->ipif_ill;
9686 				/* not supported by the virtual network iface */
9687 				if (IS_VNI(ill)) {
9688 					ipif_refrele(ipif);
9689 					return (EINVAL);
9690 				}
9691 			}
9692 			ipif_refrele(ipif);
9693 			return (0);
9694 		}
9695 		ill = ipif->ipif_ill;
9696 		mutex_enter(&connp->conn_lock);
9697 		mutex_enter(&ill->ill_lock);
9698 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9699 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9700 			mutex_exit(&ill->ill_lock);
9701 			mutex_exit(&connp->conn_lock);
9702 			ipif_refrele(ipif);
9703 			return (option == IP_MULTICAST_IF ?
9704 			    EHOSTUNREACH : EINVAL);
9705 		}
9706 	} else {
9707 		mutex_enter(&connp->conn_lock);
9708 	}
9709 
9710 	/* None of the options below are supported on the VNI */
9711 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9712 		mutex_exit(&ill->ill_lock);
9713 		mutex_exit(&connp->conn_lock);
9714 		ipif_refrele(ipif);
9715 		return (EINVAL);
9716 	}
9717 
9718 	switch (option) {
9719 	case IP_DONTFAILOVER_IF:
9720 		/*
9721 		 * This option is used by in.mpathd to ensure
9722 		 * that IPMP probe packets only go out on the
9723 		 * test interfaces. in.mpathd sets this option
9724 		 * on the non-failover interfaces.
9725 		 * For backward compatibility, this option
9726 		 * implicitly sets IP_MULTICAST_IF, as used
9727 		 * be done in bind(), so that ip_wput gets
9728 		 * this ipif to send mcast packets.
9729 		 */
9730 		if (ipif != NULL) {
9731 			ASSERT(addr != INADDR_ANY);
9732 			connp->conn_nofailover_ill = ipif->ipif_ill;
9733 			connp->conn_multicast_ipif = ipif;
9734 		} else {
9735 			ASSERT(addr == INADDR_ANY);
9736 			connp->conn_nofailover_ill = NULL;
9737 			connp->conn_multicast_ipif = NULL;
9738 		}
9739 		break;
9740 
9741 	case IP_MULTICAST_IF:
9742 		connp->conn_multicast_ipif = ipif;
9743 		break;
9744 	case IP_NEXTHOP:
9745 		connp->conn_nexthop_v4 = addr;
9746 		connp->conn_nexthop_set = B_TRUE;
9747 		break;
9748 	}
9749 
9750 	if (ipif != NULL) {
9751 		mutex_exit(&ill->ill_lock);
9752 		mutex_exit(&connp->conn_lock);
9753 		ipif_refrele(ipif);
9754 		return (0);
9755 	}
9756 	mutex_exit(&connp->conn_lock);
9757 	/* We succeded in cleared the option */
9758 	return (0);
9759 }
9760 
9761 /*
9762  * For options that pass in an ifindex specifying the ill. V6 options always
9763  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9764  */
9765 int
9766 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9767     int level, int option, mblk_t *first_mp)
9768 {
9769 	ill_t *ill = NULL;
9770 	int error = 0;
9771 
9772 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9773 	if (ifindex != 0) {
9774 		ASSERT(connp != NULL);
9775 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9776 		    first_mp, ip_restart_optmgmt, &error);
9777 		if (ill != NULL) {
9778 			if (checkonly) {
9779 				/* not supported by the virtual network iface */
9780 				if (IS_VNI(ill)) {
9781 					ill_refrele(ill);
9782 					return (EINVAL);
9783 				}
9784 				ill_refrele(ill);
9785 				return (0);
9786 			}
9787 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9788 			    0, NULL)) {
9789 				ill_refrele(ill);
9790 				ill = NULL;
9791 				mutex_enter(&connp->conn_lock);
9792 				goto setit;
9793 			}
9794 			mutex_enter(&connp->conn_lock);
9795 			mutex_enter(&ill->ill_lock);
9796 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9797 				mutex_exit(&ill->ill_lock);
9798 				mutex_exit(&connp->conn_lock);
9799 				ill_refrele(ill);
9800 				ill = NULL;
9801 				mutex_enter(&connp->conn_lock);
9802 			}
9803 			goto setit;
9804 		} else if (error == EINPROGRESS) {
9805 			return (error);
9806 		} else {
9807 			error = 0;
9808 		}
9809 	}
9810 	mutex_enter(&connp->conn_lock);
9811 setit:
9812 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9813 
9814 	/*
9815 	 * The options below assume that the ILL (if any) transmits and/or
9816 	 * receives traffic. Neither of which is true for the virtual network
9817 	 * interface, so fail setting these on a VNI.
9818 	 */
9819 	if (IS_VNI(ill)) {
9820 		ASSERT(ill != NULL);
9821 		mutex_exit(&ill->ill_lock);
9822 		mutex_exit(&connp->conn_lock);
9823 		ill_refrele(ill);
9824 		return (EINVAL);
9825 	}
9826 
9827 	if (level == IPPROTO_IP) {
9828 		switch (option) {
9829 		case IP_BOUND_IF:
9830 			connp->conn_incoming_ill = ill;
9831 			connp->conn_outgoing_ill = ill;
9832 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9833 			    0 : ifindex;
9834 			break;
9835 
9836 		case IP_XMIT_IF:
9837 			/*
9838 			 * Similar to IP_BOUND_IF, but this only
9839 			 * determines the outgoing interface for
9840 			 * unicast packets. Also no IRE_CACHE entry
9841 			 * is added for the destination of the
9842 			 * outgoing packets. This feature is needed
9843 			 * for mobile IP.
9844 			 */
9845 			connp->conn_xmit_if_ill = ill;
9846 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9847 			    0 : ifindex;
9848 			break;
9849 
9850 		case IP_MULTICAST_IF:
9851 			/*
9852 			 * This option is an internal special. The socket
9853 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9854 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9855 			 * specifies an ifindex and we try first on V6 ill's.
9856 			 * If we don't find one, we they try using on v4 ill's
9857 			 * intenally and we come here.
9858 			 */
9859 			if (!checkonly && ill != NULL) {
9860 				ipif_t	*ipif;
9861 				ipif = ill->ill_ipif;
9862 
9863 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9864 					mutex_exit(&ill->ill_lock);
9865 					mutex_exit(&connp->conn_lock);
9866 					ill_refrele(ill);
9867 					ill = NULL;
9868 					mutex_enter(&connp->conn_lock);
9869 				} else {
9870 					connp->conn_multicast_ipif = ipif;
9871 				}
9872 			}
9873 			break;
9874 		}
9875 	} else {
9876 		switch (option) {
9877 		case IPV6_BOUND_IF:
9878 			connp->conn_incoming_ill = ill;
9879 			connp->conn_outgoing_ill = ill;
9880 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9881 			    0 : ifindex;
9882 			break;
9883 
9884 		case IPV6_BOUND_PIF:
9885 			/*
9886 			 * Limit all transmit to this ill.
9887 			 * Unlike IPV6_BOUND_IF, using this option
9888 			 * prevents load spreading and failover from
9889 			 * happening when the interface is part of the
9890 			 * group. That's why we don't need to remember
9891 			 * the ifindex in orig_bound_ifindex as in
9892 			 * IPV6_BOUND_IF.
9893 			 */
9894 			connp->conn_outgoing_pill = ill;
9895 			break;
9896 
9897 		case IPV6_DONTFAILOVER_IF:
9898 			/*
9899 			 * This option is used by in.mpathd to ensure
9900 			 * that IPMP probe packets only go out on the
9901 			 * test interfaces. in.mpathd sets this option
9902 			 * on the non-failover interfaces.
9903 			 */
9904 			connp->conn_nofailover_ill = ill;
9905 			/*
9906 			 * For backward compatibility, this option
9907 			 * implicitly sets ip_multicast_ill as used in
9908 			 * IP_MULTICAST_IF so that ip_wput gets
9909 			 * this ipif to send mcast packets.
9910 			 */
9911 			connp->conn_multicast_ill = ill;
9912 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9913 			    0 : ifindex;
9914 			break;
9915 
9916 		case IPV6_MULTICAST_IF:
9917 			/*
9918 			 * Set conn_multicast_ill to be the IPv6 ill.
9919 			 * Set conn_multicast_ipif to be an IPv4 ipif
9920 			 * for ifindex to make IPv4 mapped addresses
9921 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9922 			 * Even if no IPv6 ill exists for the ifindex
9923 			 * we need to check for an IPv4 ifindex in order
9924 			 * for this to work with mapped addresses. In that
9925 			 * case only set conn_multicast_ipif.
9926 			 */
9927 			if (!checkonly) {
9928 				if (ifindex == 0) {
9929 					connp->conn_multicast_ill = NULL;
9930 					connp->conn_orig_multicast_ifindex = 0;
9931 					connp->conn_multicast_ipif = NULL;
9932 				} else if (ill != NULL) {
9933 					connp->conn_multicast_ill = ill;
9934 					connp->conn_orig_multicast_ifindex =
9935 					    ifindex;
9936 				}
9937 			}
9938 			break;
9939 		}
9940 	}
9941 
9942 	if (ill != NULL) {
9943 		mutex_exit(&ill->ill_lock);
9944 		mutex_exit(&connp->conn_lock);
9945 		ill_refrele(ill);
9946 		return (0);
9947 	}
9948 	mutex_exit(&connp->conn_lock);
9949 	/*
9950 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9951 	 * locate the ill and could not set the option (ifindex != 0)
9952 	 */
9953 	return (ifindex == 0 ? 0 : EINVAL);
9954 }
9955 
9956 /* This routine sets socket options. */
9957 /* ARGSUSED */
9958 int
9959 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9960     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9961     void *dummy, cred_t *cr, mblk_t *first_mp)
9962 {
9963 	int		*i1 = (int *)invalp;
9964 	conn_t		*connp = Q_TO_CONN(q);
9965 	int		error = 0;
9966 	boolean_t	checkonly;
9967 	ire_t		*ire;
9968 	boolean_t	found;
9969 
9970 	switch (optset_context) {
9971 
9972 	case SETFN_OPTCOM_CHECKONLY:
9973 		checkonly = B_TRUE;
9974 		/*
9975 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9976 		 * inlen != 0 implies value supplied and
9977 		 * 	we have to "pretend" to set it.
9978 		 * inlen == 0 implies that there is no
9979 		 * 	value part in T_CHECK request and just validation
9980 		 * done elsewhere should be enough, we just return here.
9981 		 */
9982 		if (inlen == 0) {
9983 			*outlenp = 0;
9984 			return (0);
9985 		}
9986 		break;
9987 	case SETFN_OPTCOM_NEGOTIATE:
9988 	case SETFN_UD_NEGOTIATE:
9989 	case SETFN_CONN_NEGOTIATE:
9990 		checkonly = B_FALSE;
9991 		break;
9992 	default:
9993 		/*
9994 		 * We should never get here
9995 		 */
9996 		*outlenp = 0;
9997 		return (EINVAL);
9998 	}
9999 
10000 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10001 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10002 
10003 	/*
10004 	 * For fixed length options, no sanity check
10005 	 * of passed in length is done. It is assumed *_optcom_req()
10006 	 * routines do the right thing.
10007 	 */
10008 
10009 	switch (level) {
10010 	case SOL_SOCKET:
10011 		/*
10012 		 * conn_lock protects the bitfields, and is used to
10013 		 * set the fields atomically.
10014 		 */
10015 		switch (name) {
10016 		case SO_BROADCAST:
10017 			if (!checkonly) {
10018 				/* TODO: use value someplace? */
10019 				mutex_enter(&connp->conn_lock);
10020 				connp->conn_broadcast = *i1 ? 1 : 0;
10021 				mutex_exit(&connp->conn_lock);
10022 			}
10023 			break;	/* goto sizeof (int) option return */
10024 		case SO_USELOOPBACK:
10025 			if (!checkonly) {
10026 				/* TODO: use value someplace? */
10027 				mutex_enter(&connp->conn_lock);
10028 				connp->conn_loopback = *i1 ? 1 : 0;
10029 				mutex_exit(&connp->conn_lock);
10030 			}
10031 			break;	/* goto sizeof (int) option return */
10032 		case SO_DONTROUTE:
10033 			if (!checkonly) {
10034 				mutex_enter(&connp->conn_lock);
10035 				connp->conn_dontroute = *i1 ? 1 : 0;
10036 				mutex_exit(&connp->conn_lock);
10037 			}
10038 			break;	/* goto sizeof (int) option return */
10039 		case SO_REUSEADDR:
10040 			if (!checkonly) {
10041 				mutex_enter(&connp->conn_lock);
10042 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10043 				mutex_exit(&connp->conn_lock);
10044 			}
10045 			break;	/* goto sizeof (int) option return */
10046 		case SO_PROTOTYPE:
10047 			if (!checkonly) {
10048 				mutex_enter(&connp->conn_lock);
10049 				connp->conn_proto = *i1;
10050 				mutex_exit(&connp->conn_lock);
10051 			}
10052 			break;	/* goto sizeof (int) option return */
10053 		case SO_ALLZONES:
10054 			if (!checkonly) {
10055 				mutex_enter(&connp->conn_lock);
10056 				if (IPCL_IS_BOUND(connp)) {
10057 					mutex_exit(&connp->conn_lock);
10058 					return (EINVAL);
10059 				}
10060 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10061 				mutex_exit(&connp->conn_lock);
10062 			}
10063 			break;	/* goto sizeof (int) option return */
10064 		case SO_ANON_MLP:
10065 			if (!checkonly) {
10066 				mutex_enter(&connp->conn_lock);
10067 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10068 				mutex_exit(&connp->conn_lock);
10069 			}
10070 			break;	/* goto sizeof (int) option return */
10071 		case SO_MAC_EXEMPT:
10072 			if (secpolicy_net_mac_aware(cr) != 0 ||
10073 			    IPCL_IS_BOUND(connp))
10074 				return (EACCES);
10075 			if (!checkonly) {
10076 				mutex_enter(&connp->conn_lock);
10077 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10078 				mutex_exit(&connp->conn_lock);
10079 			}
10080 			break;	/* goto sizeof (int) option return */
10081 		default:
10082 			/*
10083 			 * "soft" error (negative)
10084 			 * option not handled at this level
10085 			 * Note: Do not modify *outlenp
10086 			 */
10087 			return (-EINVAL);
10088 		}
10089 		break;
10090 	case IPPROTO_IP:
10091 		switch (name) {
10092 		case IP_NEXTHOP:
10093 		case IP_MULTICAST_IF:
10094 		case IP_DONTFAILOVER_IF: {
10095 			ipaddr_t addr = *i1;
10096 
10097 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10098 			    first_mp);
10099 			if (error != 0)
10100 				return (error);
10101 			break;	/* goto sizeof (int) option return */
10102 		}
10103 
10104 		case IP_MULTICAST_TTL:
10105 			/* Recorded in transport above IP */
10106 			*outvalp = *invalp;
10107 			*outlenp = sizeof (uchar_t);
10108 			return (0);
10109 		case IP_MULTICAST_LOOP:
10110 			if (!checkonly) {
10111 				mutex_enter(&connp->conn_lock);
10112 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10113 				mutex_exit(&connp->conn_lock);
10114 			}
10115 			*outvalp = *invalp;
10116 			*outlenp = sizeof (uchar_t);
10117 			return (0);
10118 		case IP_ADD_MEMBERSHIP:
10119 		case MCAST_JOIN_GROUP:
10120 		case IP_DROP_MEMBERSHIP:
10121 		case MCAST_LEAVE_GROUP: {
10122 			struct ip_mreq *mreqp;
10123 			struct group_req *greqp;
10124 			ire_t *ire;
10125 			boolean_t done = B_FALSE;
10126 			ipaddr_t group, ifaddr;
10127 			struct sockaddr_in *sin;
10128 			uint32_t *ifindexp;
10129 			boolean_t mcast_opt = B_TRUE;
10130 			mcast_record_t fmode;
10131 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10132 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10133 
10134 			switch (name) {
10135 			case IP_ADD_MEMBERSHIP:
10136 				mcast_opt = B_FALSE;
10137 				/* FALLTHRU */
10138 			case MCAST_JOIN_GROUP:
10139 				fmode = MODE_IS_EXCLUDE;
10140 				optfn = ip_opt_add_group;
10141 				break;
10142 
10143 			case IP_DROP_MEMBERSHIP:
10144 				mcast_opt = B_FALSE;
10145 				/* FALLTHRU */
10146 			case MCAST_LEAVE_GROUP:
10147 				fmode = MODE_IS_INCLUDE;
10148 				optfn = ip_opt_delete_group;
10149 				break;
10150 			}
10151 
10152 			if (mcast_opt) {
10153 				greqp = (struct group_req *)i1;
10154 				sin = (struct sockaddr_in *)&greqp->gr_group;
10155 				if (sin->sin_family != AF_INET) {
10156 					*outlenp = 0;
10157 					return (ENOPROTOOPT);
10158 				}
10159 				group = (ipaddr_t)sin->sin_addr.s_addr;
10160 				ifaddr = INADDR_ANY;
10161 				ifindexp = &greqp->gr_interface;
10162 			} else {
10163 				mreqp = (struct ip_mreq *)i1;
10164 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10165 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10166 				ifindexp = NULL;
10167 			}
10168 
10169 			/*
10170 			 * In the multirouting case, we need to replicate
10171 			 * the request on all interfaces that will take part
10172 			 * in replication.  We do so because multirouting is
10173 			 * reflective, thus we will probably receive multi-
10174 			 * casts on those interfaces.
10175 			 * The ip_multirt_apply_membership() succeeds if the
10176 			 * operation succeeds on at least one interface.
10177 			 */
10178 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10179 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10180 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10181 			if (ire != NULL) {
10182 				if (ire->ire_flags & RTF_MULTIRT) {
10183 					error = ip_multirt_apply_membership(
10184 					    optfn, ire, connp, checkonly, group,
10185 					    fmode, INADDR_ANY, first_mp);
10186 					done = B_TRUE;
10187 				}
10188 				ire_refrele(ire);
10189 			}
10190 			if (!done) {
10191 				error = optfn(connp, checkonly, group, ifaddr,
10192 				    ifindexp, fmode, INADDR_ANY, first_mp);
10193 			}
10194 			if (error) {
10195 				/*
10196 				 * EINPROGRESS is a soft error, needs retry
10197 				 * so don't make *outlenp zero.
10198 				 */
10199 				if (error != EINPROGRESS)
10200 					*outlenp = 0;
10201 				return (error);
10202 			}
10203 			/* OK return - copy input buffer into output buffer */
10204 			if (invalp != outvalp) {
10205 				/* don't trust bcopy for identical src/dst */
10206 				bcopy(invalp, outvalp, inlen);
10207 			}
10208 			*outlenp = inlen;
10209 			return (0);
10210 		}
10211 		case IP_BLOCK_SOURCE:
10212 		case IP_UNBLOCK_SOURCE:
10213 		case IP_ADD_SOURCE_MEMBERSHIP:
10214 		case IP_DROP_SOURCE_MEMBERSHIP:
10215 		case MCAST_BLOCK_SOURCE:
10216 		case MCAST_UNBLOCK_SOURCE:
10217 		case MCAST_JOIN_SOURCE_GROUP:
10218 		case MCAST_LEAVE_SOURCE_GROUP: {
10219 			struct ip_mreq_source *imreqp;
10220 			struct group_source_req *gsreqp;
10221 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10222 			uint32_t ifindex = 0;
10223 			mcast_record_t fmode;
10224 			struct sockaddr_in *sin;
10225 			ire_t *ire;
10226 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10227 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10228 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10229 
10230 			switch (name) {
10231 			case IP_BLOCK_SOURCE:
10232 				mcast_opt = B_FALSE;
10233 				/* FALLTHRU */
10234 			case MCAST_BLOCK_SOURCE:
10235 				fmode = MODE_IS_EXCLUDE;
10236 				optfn = ip_opt_add_group;
10237 				break;
10238 
10239 			case IP_UNBLOCK_SOURCE:
10240 				mcast_opt = B_FALSE;
10241 				/* FALLTHRU */
10242 			case MCAST_UNBLOCK_SOURCE:
10243 				fmode = MODE_IS_EXCLUDE;
10244 				optfn = ip_opt_delete_group;
10245 				break;
10246 
10247 			case IP_ADD_SOURCE_MEMBERSHIP:
10248 				mcast_opt = B_FALSE;
10249 				/* FALLTHRU */
10250 			case MCAST_JOIN_SOURCE_GROUP:
10251 				fmode = MODE_IS_INCLUDE;
10252 				optfn = ip_opt_add_group;
10253 				break;
10254 
10255 			case IP_DROP_SOURCE_MEMBERSHIP:
10256 				mcast_opt = B_FALSE;
10257 				/* FALLTHRU */
10258 			case MCAST_LEAVE_SOURCE_GROUP:
10259 				fmode = MODE_IS_INCLUDE;
10260 				optfn = ip_opt_delete_group;
10261 				break;
10262 			}
10263 
10264 			if (mcast_opt) {
10265 				gsreqp = (struct group_source_req *)i1;
10266 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10267 					*outlenp = 0;
10268 					return (ENOPROTOOPT);
10269 				}
10270 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10271 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10272 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10273 				src = (ipaddr_t)sin->sin_addr.s_addr;
10274 				ifindex = gsreqp->gsr_interface;
10275 			} else {
10276 				imreqp = (struct ip_mreq_source *)i1;
10277 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10278 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10279 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10280 			}
10281 
10282 			/*
10283 			 * In the multirouting case, we need to replicate
10284 			 * the request as noted in the mcast cases above.
10285 			 */
10286 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10287 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10288 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10289 			if (ire != NULL) {
10290 				if (ire->ire_flags & RTF_MULTIRT) {
10291 					error = ip_multirt_apply_membership(
10292 					    optfn, ire, connp, checkonly, grp,
10293 					    fmode, src, first_mp);
10294 					done = B_TRUE;
10295 				}
10296 				ire_refrele(ire);
10297 			}
10298 			if (!done) {
10299 				error = optfn(connp, checkonly, grp, ifaddr,
10300 				    &ifindex, fmode, src, first_mp);
10301 			}
10302 			if (error != 0) {
10303 				/*
10304 				 * EINPROGRESS is a soft error, needs retry
10305 				 * so don't make *outlenp zero.
10306 				 */
10307 				if (error != EINPROGRESS)
10308 					*outlenp = 0;
10309 				return (error);
10310 			}
10311 			/* OK return - copy input buffer into output buffer */
10312 			if (invalp != outvalp) {
10313 				bcopy(invalp, outvalp, inlen);
10314 			}
10315 			*outlenp = inlen;
10316 			return (0);
10317 		}
10318 		case IP_SEC_OPT:
10319 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10320 			if (error != 0) {
10321 				*outlenp = 0;
10322 				return (error);
10323 			}
10324 			break;
10325 		case IP_HDRINCL:
10326 		case IP_OPTIONS:
10327 		case T_IP_OPTIONS:
10328 		case IP_TOS:
10329 		case T_IP_TOS:
10330 		case IP_TTL:
10331 		case IP_RECVDSTADDR:
10332 		case IP_RECVOPTS:
10333 			/* OK return - copy input buffer into output buffer */
10334 			if (invalp != outvalp) {
10335 				/* don't trust bcopy for identical src/dst */
10336 				bcopy(invalp, outvalp, inlen);
10337 			}
10338 			*outlenp = inlen;
10339 			return (0);
10340 		case IP_RECVIF:
10341 			/* Retrieve the inbound interface index */
10342 			if (!checkonly) {
10343 				mutex_enter(&connp->conn_lock);
10344 				connp->conn_recvif = *i1 ? 1 : 0;
10345 				mutex_exit(&connp->conn_lock);
10346 			}
10347 			break;	/* goto sizeof (int) option return */
10348 		case IP_RECVSLLA:
10349 			/* Retrieve the source link layer address */
10350 			if (!checkonly) {
10351 				mutex_enter(&connp->conn_lock);
10352 				connp->conn_recvslla = *i1 ? 1 : 0;
10353 				mutex_exit(&connp->conn_lock);
10354 			}
10355 			break;	/* goto sizeof (int) option return */
10356 		case MRT_INIT:
10357 		case MRT_DONE:
10358 		case MRT_ADD_VIF:
10359 		case MRT_DEL_VIF:
10360 		case MRT_ADD_MFC:
10361 		case MRT_DEL_MFC:
10362 		case MRT_ASSERT:
10363 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10364 				*outlenp = 0;
10365 				return (error);
10366 			}
10367 			error = ip_mrouter_set((int)name, q, checkonly,
10368 			    (uchar_t *)invalp, inlen, first_mp);
10369 			if (error) {
10370 				*outlenp = 0;
10371 				return (error);
10372 			}
10373 			/* OK return - copy input buffer into output buffer */
10374 			if (invalp != outvalp) {
10375 				/* don't trust bcopy for identical src/dst */
10376 				bcopy(invalp, outvalp, inlen);
10377 			}
10378 			*outlenp = inlen;
10379 			return (0);
10380 		case IP_BOUND_IF:
10381 		case IP_XMIT_IF:
10382 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10383 			    level, name, first_mp);
10384 			if (error != 0)
10385 				return (error);
10386 			break; 		/* goto sizeof (int) option return */
10387 
10388 		case IP_UNSPEC_SRC:
10389 			/* Allow sending with a zero source address */
10390 			if (!checkonly) {
10391 				mutex_enter(&connp->conn_lock);
10392 				connp->conn_unspec_src = *i1 ? 1 : 0;
10393 				mutex_exit(&connp->conn_lock);
10394 			}
10395 			break;	/* goto sizeof (int) option return */
10396 		default:
10397 			/*
10398 			 * "soft" error (negative)
10399 			 * option not handled at this level
10400 			 * Note: Do not modify *outlenp
10401 			 */
10402 			return (-EINVAL);
10403 		}
10404 		break;
10405 	case IPPROTO_IPV6:
10406 		switch (name) {
10407 		case IPV6_BOUND_IF:
10408 		case IPV6_BOUND_PIF:
10409 		case IPV6_DONTFAILOVER_IF:
10410 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10411 			    level, name, first_mp);
10412 			if (error != 0)
10413 				return (error);
10414 			break; 		/* goto sizeof (int) option return */
10415 
10416 		case IPV6_MULTICAST_IF:
10417 			/*
10418 			 * The only possible errors are EINPROGRESS and
10419 			 * EINVAL. EINPROGRESS will be restarted and is not
10420 			 * a hard error. We call this option on both V4 and V6
10421 			 * If both return EINVAL, then this call returns
10422 			 * EINVAL. If at least one of them succeeds we
10423 			 * return success.
10424 			 */
10425 			found = B_FALSE;
10426 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10427 			    level, name, first_mp);
10428 			if (error == EINPROGRESS)
10429 				return (error);
10430 			if (error == 0)
10431 				found = B_TRUE;
10432 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10433 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10434 			if (error == 0)
10435 				found = B_TRUE;
10436 			if (!found)
10437 				return (error);
10438 			break; 		/* goto sizeof (int) option return */
10439 
10440 		case IPV6_MULTICAST_HOPS:
10441 			/* Recorded in transport above IP */
10442 			break;	/* goto sizeof (int) option return */
10443 		case IPV6_MULTICAST_LOOP:
10444 			if (!checkonly) {
10445 				mutex_enter(&connp->conn_lock);
10446 				connp->conn_multicast_loop = *i1;
10447 				mutex_exit(&connp->conn_lock);
10448 			}
10449 			break;	/* goto sizeof (int) option return */
10450 		case IPV6_JOIN_GROUP:
10451 		case MCAST_JOIN_GROUP:
10452 		case IPV6_LEAVE_GROUP:
10453 		case MCAST_LEAVE_GROUP: {
10454 			struct ipv6_mreq *ip_mreqp;
10455 			struct group_req *greqp;
10456 			ire_t *ire;
10457 			boolean_t done = B_FALSE;
10458 			in6_addr_t groupv6;
10459 			uint32_t ifindex;
10460 			boolean_t mcast_opt = B_TRUE;
10461 			mcast_record_t fmode;
10462 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10463 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10464 
10465 			switch (name) {
10466 			case IPV6_JOIN_GROUP:
10467 				mcast_opt = B_FALSE;
10468 				/* FALLTHRU */
10469 			case MCAST_JOIN_GROUP:
10470 				fmode = MODE_IS_EXCLUDE;
10471 				optfn = ip_opt_add_group_v6;
10472 				break;
10473 
10474 			case IPV6_LEAVE_GROUP:
10475 				mcast_opt = B_FALSE;
10476 				/* FALLTHRU */
10477 			case MCAST_LEAVE_GROUP:
10478 				fmode = MODE_IS_INCLUDE;
10479 				optfn = ip_opt_delete_group_v6;
10480 				break;
10481 			}
10482 
10483 			if (mcast_opt) {
10484 				struct sockaddr_in *sin;
10485 				struct sockaddr_in6 *sin6;
10486 				greqp = (struct group_req *)i1;
10487 				if (greqp->gr_group.ss_family == AF_INET) {
10488 					sin = (struct sockaddr_in *)
10489 					    &(greqp->gr_group);
10490 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10491 					    &groupv6);
10492 				} else {
10493 					sin6 = (struct sockaddr_in6 *)
10494 					    &(greqp->gr_group);
10495 					groupv6 = sin6->sin6_addr;
10496 				}
10497 				ifindex = greqp->gr_interface;
10498 			} else {
10499 				ip_mreqp = (struct ipv6_mreq *)i1;
10500 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10501 				ifindex = ip_mreqp->ipv6mr_interface;
10502 			}
10503 			/*
10504 			 * In the multirouting case, we need to replicate
10505 			 * the request on all interfaces that will take part
10506 			 * in replication.  We do so because multirouting is
10507 			 * reflective, thus we will probably receive multi-
10508 			 * casts on those interfaces.
10509 			 * The ip_multirt_apply_membership_v6() succeeds if
10510 			 * the operation succeeds on at least one interface.
10511 			 */
10512 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10513 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10514 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10515 			if (ire != NULL) {
10516 				if (ire->ire_flags & RTF_MULTIRT) {
10517 					error = ip_multirt_apply_membership_v6(
10518 					    optfn, ire, connp, checkonly,
10519 					    &groupv6, fmode, &ipv6_all_zeros,
10520 					    first_mp);
10521 					done = B_TRUE;
10522 				}
10523 				ire_refrele(ire);
10524 			}
10525 			if (!done) {
10526 				error = optfn(connp, checkonly, &groupv6,
10527 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10528 			}
10529 			if (error) {
10530 				/*
10531 				 * EINPROGRESS is a soft error, needs retry
10532 				 * so don't make *outlenp zero.
10533 				 */
10534 				if (error != EINPROGRESS)
10535 					*outlenp = 0;
10536 				return (error);
10537 			}
10538 			/* OK return - copy input buffer into output buffer */
10539 			if (invalp != outvalp) {
10540 				/* don't trust bcopy for identical src/dst */
10541 				bcopy(invalp, outvalp, inlen);
10542 			}
10543 			*outlenp = inlen;
10544 			return (0);
10545 		}
10546 		case MCAST_BLOCK_SOURCE:
10547 		case MCAST_UNBLOCK_SOURCE:
10548 		case MCAST_JOIN_SOURCE_GROUP:
10549 		case MCAST_LEAVE_SOURCE_GROUP: {
10550 			struct group_source_req *gsreqp;
10551 			in6_addr_t v6grp, v6src;
10552 			uint32_t ifindex;
10553 			mcast_record_t fmode;
10554 			ire_t *ire;
10555 			boolean_t done = B_FALSE;
10556 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10557 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10558 
10559 			switch (name) {
10560 			case MCAST_BLOCK_SOURCE:
10561 				fmode = MODE_IS_EXCLUDE;
10562 				optfn = ip_opt_add_group_v6;
10563 				break;
10564 			case MCAST_UNBLOCK_SOURCE:
10565 				fmode = MODE_IS_EXCLUDE;
10566 				optfn = ip_opt_delete_group_v6;
10567 				break;
10568 			case MCAST_JOIN_SOURCE_GROUP:
10569 				fmode = MODE_IS_INCLUDE;
10570 				optfn = ip_opt_add_group_v6;
10571 				break;
10572 			case MCAST_LEAVE_SOURCE_GROUP:
10573 				fmode = MODE_IS_INCLUDE;
10574 				optfn = ip_opt_delete_group_v6;
10575 				break;
10576 			}
10577 
10578 			gsreqp = (struct group_source_req *)i1;
10579 			ifindex = gsreqp->gsr_interface;
10580 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10581 				struct sockaddr_in *s;
10582 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10583 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10584 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10585 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10586 			} else {
10587 				struct sockaddr_in6 *s6;
10588 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10589 				v6grp = s6->sin6_addr;
10590 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10591 				v6src = s6->sin6_addr;
10592 			}
10593 
10594 			/*
10595 			 * In the multirouting case, we need to replicate
10596 			 * the request as noted in the mcast cases above.
10597 			 */
10598 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10599 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10600 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10601 			if (ire != NULL) {
10602 				if (ire->ire_flags & RTF_MULTIRT) {
10603 					error = ip_multirt_apply_membership_v6(
10604 					    optfn, ire, connp, checkonly,
10605 					    &v6grp, fmode, &v6src, first_mp);
10606 					done = B_TRUE;
10607 				}
10608 				ire_refrele(ire);
10609 			}
10610 			if (!done) {
10611 				error = optfn(connp, checkonly, &v6grp,
10612 				    ifindex, fmode, &v6src, first_mp);
10613 			}
10614 			if (error != 0) {
10615 				/*
10616 				 * EINPROGRESS is a soft error, needs retry
10617 				 * so don't make *outlenp zero.
10618 				 */
10619 				if (error != EINPROGRESS)
10620 					*outlenp = 0;
10621 				return (error);
10622 			}
10623 			/* OK return - copy input buffer into output buffer */
10624 			if (invalp != outvalp) {
10625 				bcopy(invalp, outvalp, inlen);
10626 			}
10627 			*outlenp = inlen;
10628 			return (0);
10629 		}
10630 		case IPV6_UNICAST_HOPS:
10631 			/* Recorded in transport above IP */
10632 			break;	/* goto sizeof (int) option return */
10633 		case IPV6_UNSPEC_SRC:
10634 			/* Allow sending with a zero source address */
10635 			if (!checkonly) {
10636 				mutex_enter(&connp->conn_lock);
10637 				connp->conn_unspec_src = *i1 ? 1 : 0;
10638 				mutex_exit(&connp->conn_lock);
10639 			}
10640 			break;	/* goto sizeof (int) option return */
10641 		case IPV6_RECVPKTINFO:
10642 			if (!checkonly) {
10643 				mutex_enter(&connp->conn_lock);
10644 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10645 				mutex_exit(&connp->conn_lock);
10646 			}
10647 			break;	/* goto sizeof (int) option return */
10648 		case IPV6_RECVTCLASS:
10649 			if (!checkonly) {
10650 				if (*i1 < 0 || *i1 > 1) {
10651 					return (EINVAL);
10652 				}
10653 				mutex_enter(&connp->conn_lock);
10654 				connp->conn_ipv6_recvtclass = *i1;
10655 				mutex_exit(&connp->conn_lock);
10656 			}
10657 			break;
10658 		case IPV6_RECVPATHMTU:
10659 			if (!checkonly) {
10660 				if (*i1 < 0 || *i1 > 1) {
10661 					return (EINVAL);
10662 				}
10663 				mutex_enter(&connp->conn_lock);
10664 				connp->conn_ipv6_recvpathmtu = *i1;
10665 				mutex_exit(&connp->conn_lock);
10666 			}
10667 			break;
10668 		case IPV6_RECVHOPLIMIT:
10669 			if (!checkonly) {
10670 				mutex_enter(&connp->conn_lock);
10671 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10672 				mutex_exit(&connp->conn_lock);
10673 			}
10674 			break;	/* goto sizeof (int) option return */
10675 		case IPV6_RECVHOPOPTS:
10676 			if (!checkonly) {
10677 				mutex_enter(&connp->conn_lock);
10678 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10679 				mutex_exit(&connp->conn_lock);
10680 			}
10681 			break;	/* goto sizeof (int) option return */
10682 		case IPV6_RECVDSTOPTS:
10683 			if (!checkonly) {
10684 				mutex_enter(&connp->conn_lock);
10685 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10686 				mutex_exit(&connp->conn_lock);
10687 			}
10688 			break;	/* goto sizeof (int) option return */
10689 		case IPV6_RECVRTHDR:
10690 			if (!checkonly) {
10691 				mutex_enter(&connp->conn_lock);
10692 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10693 				mutex_exit(&connp->conn_lock);
10694 			}
10695 			break;	/* goto sizeof (int) option return */
10696 		case IPV6_RECVRTHDRDSTOPTS:
10697 			if (!checkonly) {
10698 				mutex_enter(&connp->conn_lock);
10699 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10700 				mutex_exit(&connp->conn_lock);
10701 			}
10702 			break;	/* goto sizeof (int) option return */
10703 		case IPV6_PKTINFO:
10704 			if (inlen == 0)
10705 				return (-EINVAL);	/* clearing option */
10706 			error = ip6_set_pktinfo(cr, connp,
10707 			    (struct in6_pktinfo *)invalp, first_mp);
10708 			if (error != 0)
10709 				*outlenp = 0;
10710 			else
10711 				*outlenp = inlen;
10712 			return (error);
10713 		case IPV6_NEXTHOP: {
10714 			struct sockaddr_in6 *sin6;
10715 
10716 			/* Verify that the nexthop is reachable */
10717 			if (inlen == 0)
10718 				return (-EINVAL);	/* clearing option */
10719 
10720 			sin6 = (struct sockaddr_in6 *)invalp;
10721 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10722 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10723 			    NULL, MATCH_IRE_DEFAULT);
10724 
10725 			if (ire == NULL) {
10726 				*outlenp = 0;
10727 				return (EHOSTUNREACH);
10728 			}
10729 			ire_refrele(ire);
10730 			return (-EINVAL);
10731 		}
10732 		case IPV6_SEC_OPT:
10733 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10734 			if (error != 0) {
10735 				*outlenp = 0;
10736 				return (error);
10737 			}
10738 			break;
10739 		case IPV6_SRC_PREFERENCES: {
10740 			/*
10741 			 * This is implemented strictly in the ip module
10742 			 * (here and in tcp_opt_*() to accomodate tcp
10743 			 * sockets).  Modules above ip pass this option
10744 			 * down here since ip is the only one that needs to
10745 			 * be aware of source address preferences.
10746 			 *
10747 			 * This socket option only affects connected
10748 			 * sockets that haven't already bound to a specific
10749 			 * IPv6 address.  In other words, sockets that
10750 			 * don't call bind() with an address other than the
10751 			 * unspecified address and that call connect().
10752 			 * ip_bind_connected_v6() passes these preferences
10753 			 * to the ipif_select_source_v6() function.
10754 			 */
10755 			if (inlen != sizeof (uint32_t))
10756 				return (EINVAL);
10757 			error = ip6_set_src_preferences(connp,
10758 			    *(uint32_t *)invalp);
10759 			if (error != 0) {
10760 				*outlenp = 0;
10761 				return (error);
10762 			} else {
10763 				*outlenp = sizeof (uint32_t);
10764 			}
10765 			break;
10766 		}
10767 		case IPV6_V6ONLY:
10768 			if (*i1 < 0 || *i1 > 1) {
10769 				return (EINVAL);
10770 			}
10771 			mutex_enter(&connp->conn_lock);
10772 			connp->conn_ipv6_v6only = *i1;
10773 			mutex_exit(&connp->conn_lock);
10774 			break;
10775 		default:
10776 			return (-EINVAL);
10777 		}
10778 		break;
10779 	default:
10780 		/*
10781 		 * "soft" error (negative)
10782 		 * option not handled at this level
10783 		 * Note: Do not modify *outlenp
10784 		 */
10785 		return (-EINVAL);
10786 	}
10787 	/*
10788 	 * Common case of return from an option that is sizeof (int)
10789 	 */
10790 	*(int *)outvalp = *i1;
10791 	*outlenp = sizeof (int);
10792 	return (0);
10793 }
10794 
10795 /*
10796  * This routine gets default values of certain options whose default
10797  * values are maintained by protocol specific code
10798  */
10799 /* ARGSUSED */
10800 int
10801 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10802 {
10803 	int *i1 = (int *)ptr;
10804 
10805 	switch (level) {
10806 	case IPPROTO_IP:
10807 		switch (name) {
10808 		case IP_MULTICAST_TTL:
10809 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10810 			return (sizeof (uchar_t));
10811 		case IP_MULTICAST_LOOP:
10812 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10813 			return (sizeof (uchar_t));
10814 		default:
10815 			return (-1);
10816 		}
10817 	case IPPROTO_IPV6:
10818 		switch (name) {
10819 		case IPV6_UNICAST_HOPS:
10820 			*i1 = ipv6_def_hops;
10821 			return (sizeof (int));
10822 		case IPV6_MULTICAST_HOPS:
10823 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10824 			return (sizeof (int));
10825 		case IPV6_MULTICAST_LOOP:
10826 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10827 			return (sizeof (int));
10828 		case IPV6_V6ONLY:
10829 			*i1 = 1;
10830 			return (sizeof (int));
10831 		default:
10832 			return (-1);
10833 		}
10834 	default:
10835 		return (-1);
10836 	}
10837 	/* NOTREACHED */
10838 }
10839 
10840 /*
10841  * Given a destination address and a pointer to where to put the information
10842  * this routine fills in the mtuinfo.
10843  */
10844 int
10845 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10846     struct ip6_mtuinfo *mtuinfo)
10847 {
10848 	ire_t *ire;
10849 
10850 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10851 		return (-1);
10852 
10853 	bzero(mtuinfo, sizeof (*mtuinfo));
10854 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10855 	mtuinfo->ip6m_addr.sin6_port = port;
10856 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10857 
10858 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
10859 	if (ire != NULL) {
10860 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10861 		ire_refrele(ire);
10862 	} else {
10863 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10864 	}
10865 	return (sizeof (struct ip6_mtuinfo));
10866 }
10867 
10868 /*
10869  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10870  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10871  * isn't.  This doesn't matter as the error checking is done properly for the
10872  * other MRT options coming in through ip_opt_set.
10873  */
10874 int
10875 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10876 {
10877 	conn_t		*connp = Q_TO_CONN(q);
10878 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10879 
10880 	switch (level) {
10881 	case IPPROTO_IP:
10882 		switch (name) {
10883 		case MRT_VERSION:
10884 		case MRT_ASSERT:
10885 			(void) ip_mrouter_get(name, q, ptr);
10886 			return (sizeof (int));
10887 		case IP_SEC_OPT:
10888 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10889 		case IP_NEXTHOP:
10890 			if (connp->conn_nexthop_set) {
10891 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10892 				return (sizeof (ipaddr_t));
10893 			} else
10894 				return (0);
10895 		default:
10896 			break;
10897 		}
10898 		break;
10899 	case IPPROTO_IPV6:
10900 		switch (name) {
10901 		case IPV6_SEC_OPT:
10902 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10903 		case IPV6_SRC_PREFERENCES: {
10904 			return (ip6_get_src_preferences(connp,
10905 			    (uint32_t *)ptr));
10906 		}
10907 		case IPV6_V6ONLY:
10908 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10909 			return (sizeof (int));
10910 		case IPV6_PATHMTU:
10911 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10912 				(struct ip6_mtuinfo *)ptr));
10913 		default:
10914 			break;
10915 		}
10916 		break;
10917 	default:
10918 		break;
10919 	}
10920 	return (-1);
10921 }
10922 
10923 /* Named Dispatch routine to get a current value out of our parameter table. */
10924 /* ARGSUSED */
10925 static int
10926 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10927 {
10928 	ipparam_t *ippa = (ipparam_t *)cp;
10929 
10930 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10931 	return (0);
10932 }
10933 
10934 /* ARGSUSED */
10935 static int
10936 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10937 {
10938 
10939 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10940 	return (0);
10941 }
10942 
10943 /*
10944  * Set ip{,6}_forwarding values.  This means walking through all of the
10945  * ill's and toggling their forwarding values.
10946  */
10947 /* ARGSUSED */
10948 static int
10949 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10950 {
10951 	long new_value;
10952 	int *forwarding_value = (int *)cp;
10953 	ill_t *walker;
10954 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10955 	ill_walk_context_t ctx;
10956 
10957 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10958 	    new_value < 0 || new_value > 1) {
10959 		return (EINVAL);
10960 	}
10961 
10962 	*forwarding_value = new_value;
10963 
10964 	/*
10965 	 * Regardless of the current value of ip_forwarding, set all per-ill
10966 	 * values of ip_forwarding to the value being set.
10967 	 *
10968 	 * Bring all the ill's up to date with the new global value.
10969 	 */
10970 	rw_enter(&ill_g_lock, RW_READER);
10971 
10972 	if (isv6)
10973 		walker = ILL_START_WALK_V6(&ctx);
10974 	else
10975 		walker = ILL_START_WALK_V4(&ctx);
10976 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10977 		(void) ill_forward_set(q, mp, (new_value != 0),
10978 		    (caddr_t)walker);
10979 	}
10980 	rw_exit(&ill_g_lock);
10981 
10982 	return (0);
10983 }
10984 
10985 /*
10986  * Walk through the param array specified registering each element with the
10987  * Named Dispatch handler. This is called only during init. So it is ok
10988  * not to acquire any locks
10989  */
10990 static boolean_t
10991 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10992     ipndp_t *ipnd, size_t ipnd_cnt)
10993 {
10994 	for (; ippa_cnt-- > 0; ippa++) {
10995 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10996 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
10997 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
10998 				nd_free(&ip_g_nd);
10999 				return (B_FALSE);
11000 			}
11001 		}
11002 	}
11003 
11004 	for (; ipnd_cnt-- > 0; ipnd++) {
11005 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11006 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11007 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11008 			    ipnd->ip_ndp_data)) {
11009 				nd_free(&ip_g_nd);
11010 				return (B_FALSE);
11011 			}
11012 		}
11013 	}
11014 
11015 	return (B_TRUE);
11016 }
11017 
11018 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11019 /* ARGSUSED */
11020 static int
11021 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11022 {
11023 	long		new_value;
11024 	ipparam_t	*ippa = (ipparam_t *)cp;
11025 
11026 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11027 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11028 		return (EINVAL);
11029 	}
11030 	ippa->ip_param_value = new_value;
11031 	return (0);
11032 }
11033 
11034 /*
11035  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11036  * When an ipf is passed here for the first time, if
11037  * we already have in-order fragments on the queue, we convert from the fast-
11038  * path reassembly scheme to the hard-case scheme.  From then on, additional
11039  * fragments are reassembled here.  We keep track of the start and end offsets
11040  * of each piece, and the number of holes in the chain.  When the hole count
11041  * goes to zero, we are done!
11042  *
11043  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11044  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11045  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11046  * after the call to ip_reassemble().
11047  */
11048 int
11049 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11050     size_t msg_len)
11051 {
11052 	uint_t	end;
11053 	mblk_t	*next_mp;
11054 	mblk_t	*mp1;
11055 	uint_t	offset;
11056 	boolean_t incr_dups = B_TRUE;
11057 	boolean_t offset_zero_seen = B_FALSE;
11058 	boolean_t pkt_boundary_checked = B_FALSE;
11059 
11060 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11061 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11062 
11063 	/* Add in byte count */
11064 	ipf->ipf_count += msg_len;
11065 	if (ipf->ipf_end) {
11066 		/*
11067 		 * We were part way through in-order reassembly, but now there
11068 		 * is a hole.  We walk through messages already queued, and
11069 		 * mark them for hard case reassembly.  We know that up till
11070 		 * now they were in order starting from offset zero.
11071 		 */
11072 		offset = 0;
11073 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11074 			IP_REASS_SET_START(mp1, offset);
11075 			if (offset == 0) {
11076 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11077 				offset = -ipf->ipf_nf_hdr_len;
11078 			}
11079 			offset += mp1->b_wptr - mp1->b_rptr;
11080 			IP_REASS_SET_END(mp1, offset);
11081 		}
11082 		/* One hole at the end. */
11083 		ipf->ipf_hole_cnt = 1;
11084 		/* Brand it as a hard case, forever. */
11085 		ipf->ipf_end = 0;
11086 	}
11087 	/* Walk through all the new pieces. */
11088 	do {
11089 		end = start + (mp->b_wptr - mp->b_rptr);
11090 		/*
11091 		 * If start is 0, decrease 'end' only for the first mblk of
11092 		 * the fragment. Otherwise 'end' can get wrong value in the
11093 		 * second pass of the loop if first mblk is exactly the
11094 		 * size of ipf_nf_hdr_len.
11095 		 */
11096 		if (start == 0 && !offset_zero_seen) {
11097 			/* First segment */
11098 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11099 			end -= ipf->ipf_nf_hdr_len;
11100 			offset_zero_seen = B_TRUE;
11101 		}
11102 		next_mp = mp->b_cont;
11103 		/*
11104 		 * We are checking to see if there is any interesing data
11105 		 * to process.  If there isn't and the mblk isn't the
11106 		 * one which carries the unfragmentable header then we
11107 		 * drop it.  It's possible to have just the unfragmentable
11108 		 * header come through without any data.  That needs to be
11109 		 * saved.
11110 		 *
11111 		 * If the assert at the top of this function holds then the
11112 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11113 		 * is infrequently traveled enough that the test is left in
11114 		 * to protect against future code changes which break that
11115 		 * invariant.
11116 		 */
11117 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11118 			/* Empty.  Blast it. */
11119 			IP_REASS_SET_START(mp, 0);
11120 			IP_REASS_SET_END(mp, 0);
11121 			/*
11122 			 * If the ipf points to the mblk we are about to free,
11123 			 * update ipf to point to the next mblk (or NULL
11124 			 * if none).
11125 			 */
11126 			if (ipf->ipf_mp->b_cont == mp)
11127 				ipf->ipf_mp->b_cont = next_mp;
11128 			freeb(mp);
11129 			continue;
11130 		}
11131 		mp->b_cont = NULL;
11132 		IP_REASS_SET_START(mp, start);
11133 		IP_REASS_SET_END(mp, end);
11134 		if (!ipf->ipf_tail_mp) {
11135 			ipf->ipf_tail_mp = mp;
11136 			ipf->ipf_mp->b_cont = mp;
11137 			if (start == 0 || !more) {
11138 				ipf->ipf_hole_cnt = 1;
11139 				/*
11140 				 * if the first fragment comes in more than one
11141 				 * mblk, this loop will be executed for each
11142 				 * mblk. Need to adjust hole count so exiting
11143 				 * this routine will leave hole count at 1.
11144 				 */
11145 				if (next_mp)
11146 					ipf->ipf_hole_cnt++;
11147 			} else
11148 				ipf->ipf_hole_cnt = 2;
11149 			continue;
11150 		} else if (ipf->ipf_last_frag_seen && !more &&
11151 			    !pkt_boundary_checked) {
11152 			/*
11153 			 * We check datagram boundary only if this fragment
11154 			 * claims to be the last fragment and we have seen a
11155 			 * last fragment in the past too. We do this only
11156 			 * once for a given fragment.
11157 			 *
11158 			 * start cannot be 0 here as fragments with start=0
11159 			 * and MF=0 gets handled as a complete packet. These
11160 			 * fragments should not reach here.
11161 			 */
11162 
11163 			if (start + msgdsize(mp) !=
11164 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11165 				/*
11166 				 * We have two fragments both of which claim
11167 				 * to be the last fragment but gives conflicting
11168 				 * information about the whole datagram size.
11169 				 * Something fishy is going on. Drop the
11170 				 * fragment and free up the reassembly list.
11171 				 */
11172 				return (IP_REASS_FAILED);
11173 			}
11174 
11175 			/*
11176 			 * We shouldn't come to this code block again for this
11177 			 * particular fragment.
11178 			 */
11179 			pkt_boundary_checked = B_TRUE;
11180 		}
11181 
11182 		/* New stuff at or beyond tail? */
11183 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11184 		if (start >= offset) {
11185 			if (ipf->ipf_last_frag_seen) {
11186 				/* current fragment is beyond last fragment */
11187 				return (IP_REASS_FAILED);
11188 			}
11189 			/* Link it on end. */
11190 			ipf->ipf_tail_mp->b_cont = mp;
11191 			ipf->ipf_tail_mp = mp;
11192 			if (more) {
11193 				if (start != offset)
11194 					ipf->ipf_hole_cnt++;
11195 			} else if (start == offset && next_mp == NULL)
11196 					ipf->ipf_hole_cnt--;
11197 			continue;
11198 		}
11199 		mp1 = ipf->ipf_mp->b_cont;
11200 		offset = IP_REASS_START(mp1);
11201 		/* New stuff at the front? */
11202 		if (start < offset) {
11203 			if (start == 0) {
11204 				if (end >= offset) {
11205 					/* Nailed the hole at the begining. */
11206 					ipf->ipf_hole_cnt--;
11207 				}
11208 			} else if (end < offset) {
11209 				/*
11210 				 * A hole, stuff, and a hole where there used
11211 				 * to be just a hole.
11212 				 */
11213 				ipf->ipf_hole_cnt++;
11214 			}
11215 			mp->b_cont = mp1;
11216 			/* Check for overlap. */
11217 			while (end > offset) {
11218 				if (end < IP_REASS_END(mp1)) {
11219 					mp->b_wptr -= end - offset;
11220 					IP_REASS_SET_END(mp, offset);
11221 					if (ill->ill_isv6) {
11222 						BUMP_MIB(ill->ill_ip6_mib,
11223 						    ipv6ReasmPartDups);
11224 					} else {
11225 						BUMP_MIB(&ip_mib,
11226 						    ipReasmPartDups);
11227 					}
11228 					break;
11229 				}
11230 				/* Did we cover another hole? */
11231 				if ((mp1->b_cont &&
11232 				    IP_REASS_END(mp1) !=
11233 				    IP_REASS_START(mp1->b_cont) &&
11234 				    end >= IP_REASS_START(mp1->b_cont)) ||
11235 				    (!ipf->ipf_last_frag_seen && !more)) {
11236 					ipf->ipf_hole_cnt--;
11237 				}
11238 				/* Clip out mp1. */
11239 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11240 					/*
11241 					 * After clipping out mp1, this guy
11242 					 * is now hanging off the end.
11243 					 */
11244 					ipf->ipf_tail_mp = mp;
11245 				}
11246 				IP_REASS_SET_START(mp1, 0);
11247 				IP_REASS_SET_END(mp1, 0);
11248 				/* Subtract byte count */
11249 				ipf->ipf_count -= mp1->b_datap->db_lim -
11250 				    mp1->b_datap->db_base;
11251 				freeb(mp1);
11252 				if (ill->ill_isv6) {
11253 					BUMP_MIB(ill->ill_ip6_mib,
11254 					    ipv6ReasmPartDups);
11255 				} else {
11256 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11257 				}
11258 				mp1 = mp->b_cont;
11259 				if (!mp1)
11260 					break;
11261 				offset = IP_REASS_START(mp1);
11262 			}
11263 			ipf->ipf_mp->b_cont = mp;
11264 			continue;
11265 		}
11266 		/*
11267 		 * The new piece starts somewhere between the start of the head
11268 		 * and before the end of the tail.
11269 		 */
11270 		for (; mp1; mp1 = mp1->b_cont) {
11271 			offset = IP_REASS_END(mp1);
11272 			if (start < offset) {
11273 				if (end <= offset) {
11274 					/* Nothing new. */
11275 					IP_REASS_SET_START(mp, 0);
11276 					IP_REASS_SET_END(mp, 0);
11277 					/* Subtract byte count */
11278 					ipf->ipf_count -= mp->b_datap->db_lim -
11279 					    mp->b_datap->db_base;
11280 					if (incr_dups) {
11281 						ipf->ipf_num_dups++;
11282 						incr_dups = B_FALSE;
11283 					}
11284 					freeb(mp);
11285 					if (ill->ill_isv6) {
11286 						BUMP_MIB(ill->ill_ip6_mib,
11287 						    ipv6ReasmDuplicates);
11288 					} else {
11289 						BUMP_MIB(&ip_mib,
11290 						    ipReasmDuplicates);
11291 					}
11292 					break;
11293 				}
11294 				/*
11295 				 * Trim redundant stuff off beginning of new
11296 				 * piece.
11297 				 */
11298 				IP_REASS_SET_START(mp, offset);
11299 				mp->b_rptr += offset - start;
11300 				if (ill->ill_isv6) {
11301 					BUMP_MIB(ill->ill_ip6_mib,
11302 					    ipv6ReasmPartDups);
11303 				} else {
11304 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11305 				}
11306 				start = offset;
11307 				if (!mp1->b_cont) {
11308 					/*
11309 					 * After trimming, this guy is now
11310 					 * hanging off the end.
11311 					 */
11312 					mp1->b_cont = mp;
11313 					ipf->ipf_tail_mp = mp;
11314 					if (!more) {
11315 						ipf->ipf_hole_cnt--;
11316 					}
11317 					break;
11318 				}
11319 			}
11320 			if (start >= IP_REASS_START(mp1->b_cont))
11321 				continue;
11322 			/* Fill a hole */
11323 			if (start > offset)
11324 				ipf->ipf_hole_cnt++;
11325 			mp->b_cont = mp1->b_cont;
11326 			mp1->b_cont = mp;
11327 			mp1 = mp->b_cont;
11328 			offset = IP_REASS_START(mp1);
11329 			if (end >= offset) {
11330 				ipf->ipf_hole_cnt--;
11331 				/* Check for overlap. */
11332 				while (end > offset) {
11333 					if (end < IP_REASS_END(mp1)) {
11334 						mp->b_wptr -= end - offset;
11335 						IP_REASS_SET_END(mp, offset);
11336 						/*
11337 						 * TODO we might bump
11338 						 * this up twice if there is
11339 						 * overlap at both ends.
11340 						 */
11341 						if (ill->ill_isv6) {
11342 							BUMP_MIB(
11343 							    ill->ill_ip6_mib,
11344 							    ipv6ReasmPartDups);
11345 						} else {
11346 							BUMP_MIB(&ip_mib,
11347 							    ipReasmPartDups);
11348 						}
11349 						break;
11350 					}
11351 					/* Did we cover another hole? */
11352 					if ((mp1->b_cont &&
11353 					    IP_REASS_END(mp1)
11354 					    != IP_REASS_START(mp1->b_cont) &&
11355 					    end >=
11356 					    IP_REASS_START(mp1->b_cont)) ||
11357 					    (!ipf->ipf_last_frag_seen &&
11358 					    !more)) {
11359 						ipf->ipf_hole_cnt--;
11360 					}
11361 					/* Clip out mp1. */
11362 					if ((mp->b_cont = mp1->b_cont) ==
11363 					    NULL) {
11364 						/*
11365 						 * After clipping out mp1,
11366 						 * this guy is now hanging
11367 						 * off the end.
11368 						 */
11369 						ipf->ipf_tail_mp = mp;
11370 					}
11371 					IP_REASS_SET_START(mp1, 0);
11372 					IP_REASS_SET_END(mp1, 0);
11373 					/* Subtract byte count */
11374 					ipf->ipf_count -=
11375 					    mp1->b_datap->db_lim -
11376 					    mp1->b_datap->db_base;
11377 					freeb(mp1);
11378 					if (ill->ill_isv6) {
11379 						BUMP_MIB(ill->ill_ip6_mib,
11380 						    ipv6ReasmPartDups);
11381 					} else {
11382 						BUMP_MIB(&ip_mib,
11383 						    ipReasmPartDups);
11384 					}
11385 					mp1 = mp->b_cont;
11386 					if (!mp1)
11387 						break;
11388 					offset = IP_REASS_START(mp1);
11389 				}
11390 			}
11391 			break;
11392 		}
11393 	} while (start = end, mp = next_mp);
11394 
11395 	/* Fragment just processed could be the last one. Remember this fact */
11396 	if (!more)
11397 		ipf->ipf_last_frag_seen = B_TRUE;
11398 
11399 	/* Still got holes? */
11400 	if (ipf->ipf_hole_cnt)
11401 		return (IP_REASS_PARTIAL);
11402 	/* Clean up overloaded fields to avoid upstream disasters. */
11403 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11404 		IP_REASS_SET_START(mp1, 0);
11405 		IP_REASS_SET_END(mp1, 0);
11406 	}
11407 	return (IP_REASS_COMPLETE);
11408 }
11409 
11410 /*
11411  * ipsec processing for the fast path, used for input UDP Packets
11412  */
11413 static boolean_t
11414 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11415     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11416 {
11417 	uint32_t	ill_index;
11418 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11419 
11420 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11421 	/* The ill_index of the incoming ILL */
11422 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11423 
11424 	/* pass packet up to the transport */
11425 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11426 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11427 		    NULL, mctl_present);
11428 		if (*first_mpp == NULL) {
11429 			return (B_FALSE);
11430 		}
11431 	}
11432 
11433 	/* Initiate IPPF processing for fastpath UDP */
11434 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11435 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11436 		if (*mpp == NULL) {
11437 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11438 			    "deferred/dropped during IPPF processing\n"));
11439 			return (B_FALSE);
11440 		}
11441 	}
11442 	/*
11443 	 * We make the checks as below since we are in the fast path
11444 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11445 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11446 	 */
11447 	if (connp->conn_recvif || connp->conn_recvslla ||
11448 	    connp->conn_ipv6_recvpktinfo) {
11449 		if (connp->conn_recvif ||
11450 		    connp->conn_ipv6_recvpktinfo) {
11451 			in_flags = IPF_RECVIF;
11452 		}
11453 		if (connp->conn_recvslla) {
11454 			in_flags |= IPF_RECVSLLA;
11455 		}
11456 		/*
11457 		 * since in_flags are being set ill will be
11458 		 * referenced in ip_add_info, so it better not
11459 		 * be NULL.
11460 		 */
11461 		/*
11462 		 * the actual data will be contained in b_cont
11463 		 * upon successful return of the following call.
11464 		 * If the call fails then the original mblk is
11465 		 * returned.
11466 		 */
11467 		*mpp = ip_add_info(*mpp, ill, in_flags);
11468 	}
11469 
11470 	return (B_TRUE);
11471 }
11472 
11473 /*
11474  * Fragmentation reassembly.  Each ILL has a hash table for
11475  * queuing packets undergoing reassembly for all IPIFs
11476  * associated with the ILL.  The hash is based on the packet
11477  * IP ident field.  The ILL frag hash table was allocated
11478  * as a timer block at the time the ILL was created.  Whenever
11479  * there is anything on the reassembly queue, the timer will
11480  * be running.  Returns B_TRUE if successful else B_FALSE;
11481  * frees mp on failure.
11482  */
11483 static boolean_t
11484 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11485     uint32_t *cksum_val, uint16_t *cksum_flags)
11486 {
11487 	uint32_t	frag_offset_flags;
11488 	ill_t		*ill = (ill_t *)q->q_ptr;
11489 	mblk_t		*mp = *mpp;
11490 	mblk_t		*t_mp;
11491 	ipaddr_t	dst;
11492 	uint8_t		proto = ipha->ipha_protocol;
11493 	uint32_t	sum_val;
11494 	uint16_t	sum_flags;
11495 	ipf_t		*ipf;
11496 	ipf_t		**ipfp;
11497 	ipfb_t		*ipfb;
11498 	uint16_t	ident;
11499 	uint32_t	offset;
11500 	ipaddr_t	src;
11501 	uint_t		hdr_length;
11502 	uint32_t	end;
11503 	mblk_t		*mp1;
11504 	mblk_t		*tail_mp;
11505 	size_t		count;
11506 	size_t		msg_len;
11507 	uint8_t		ecn_info = 0;
11508 	uint32_t	packet_size;
11509 	boolean_t	pruned = B_FALSE;
11510 
11511 	if (cksum_val != NULL)
11512 		*cksum_val = 0;
11513 	if (cksum_flags != NULL)
11514 		*cksum_flags = 0;
11515 
11516 	/*
11517 	 * Drop the fragmented as early as possible, if
11518 	 * we don't have resource(s) to re-assemble.
11519 	 */
11520 	if (ip_reass_queue_bytes == 0) {
11521 		freemsg(mp);
11522 		return (B_FALSE);
11523 	}
11524 
11525 	/* Check for fragmentation offset; return if there's none */
11526 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11527 	    (IPH_MF | IPH_OFFSET)) == 0)
11528 		return (B_TRUE);
11529 
11530 	/*
11531 	 * We utilize hardware computed checksum info only for UDP since
11532 	 * IP fragmentation is a normal occurence for the protocol.  In
11533 	 * addition, checksum offload support for IP fragments carrying
11534 	 * UDP payload is commonly implemented across network adapters.
11535 	 */
11536 	ASSERT(ill != NULL);
11537 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11538 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11539 		mblk_t *mp1 = mp->b_cont;
11540 		int32_t len;
11541 
11542 		/* Record checksum information from the packet */
11543 		sum_val = (uint32_t)DB_CKSUM16(mp);
11544 		sum_flags = DB_CKSUMFLAGS(mp);
11545 
11546 		/* IP payload offset from beginning of mblk */
11547 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11548 
11549 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11550 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11551 		    offset >= DB_CKSUMSTART(mp) &&
11552 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11553 			uint32_t adj;
11554 			/*
11555 			 * Partial checksum has been calculated by hardware
11556 			 * and attached to the packet; in addition, any
11557 			 * prepended extraneous data is even byte aligned.
11558 			 * If any such data exists, we adjust the checksum;
11559 			 * this would also handle any postpended data.
11560 			 */
11561 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11562 			    mp, mp1, len, adj);
11563 
11564 			/* One's complement subtract extraneous checksum */
11565 			if (adj >= sum_val)
11566 				sum_val = ~(adj - sum_val) & 0xFFFF;
11567 			else
11568 				sum_val -= adj;
11569 		}
11570 	} else {
11571 		sum_val = 0;
11572 		sum_flags = 0;
11573 	}
11574 
11575 	/* Clear hardware checksumming flag */
11576 	DB_CKSUMFLAGS(mp) = 0;
11577 
11578 	ident = ipha->ipha_ident;
11579 	offset = (frag_offset_flags << 3) & 0xFFFF;
11580 	src = ipha->ipha_src;
11581 	dst = ipha->ipha_dst;
11582 	hdr_length = IPH_HDR_LENGTH(ipha);
11583 	end = ntohs(ipha->ipha_length) - hdr_length;
11584 
11585 	/* If end == 0 then we have a packet with no data, so just free it */
11586 	if (end == 0) {
11587 		freemsg(mp);
11588 		return (B_FALSE);
11589 	}
11590 
11591 	/* Record the ECN field info. */
11592 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11593 	if (offset != 0) {
11594 		/*
11595 		 * If this isn't the first piece, strip the header, and
11596 		 * add the offset to the end value.
11597 		 */
11598 		mp->b_rptr += hdr_length;
11599 		end += offset;
11600 	}
11601 
11602 	msg_len = MBLKSIZE(mp);
11603 	tail_mp = mp;
11604 	while (tail_mp->b_cont != NULL) {
11605 		tail_mp = tail_mp->b_cont;
11606 		msg_len += MBLKSIZE(tail_mp);
11607 	}
11608 
11609 	/* If the reassembly list for this ILL will get too big, prune it */
11610 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11611 	    ip_reass_queue_bytes) {
11612 		ill_frag_prune(ill,
11613 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11614 		    (ip_reass_queue_bytes - msg_len));
11615 		pruned = B_TRUE;
11616 	}
11617 
11618 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11619 	mutex_enter(&ipfb->ipfb_lock);
11620 
11621 	ipfp = &ipfb->ipfb_ipf;
11622 	/* Try to find an existing fragment queue for this packet. */
11623 	for (;;) {
11624 		ipf = ipfp[0];
11625 		if (ipf != NULL) {
11626 			/*
11627 			 * It has to match on ident and src/dst address.
11628 			 */
11629 			if (ipf->ipf_ident == ident &&
11630 			    ipf->ipf_src == src &&
11631 			    ipf->ipf_dst == dst &&
11632 			    ipf->ipf_protocol == proto) {
11633 				/*
11634 				 * If we have received too many
11635 				 * duplicate fragments for this packet
11636 				 * free it.
11637 				 */
11638 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11639 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11640 					freemsg(mp);
11641 					mutex_exit(&ipfb->ipfb_lock);
11642 					return (B_FALSE);
11643 				}
11644 				/* Found it. */
11645 				break;
11646 			}
11647 			ipfp = &ipf->ipf_hash_next;
11648 			continue;
11649 		}
11650 
11651 		/*
11652 		 * If we pruned the list, do we want to store this new
11653 		 * fragment?. We apply an optimization here based on the
11654 		 * fact that most fragments will be received in order.
11655 		 * So if the offset of this incoming fragment is zero,
11656 		 * it is the first fragment of a new packet. We will
11657 		 * keep it.  Otherwise drop the fragment, as we have
11658 		 * probably pruned the packet already (since the
11659 		 * packet cannot be found).
11660 		 */
11661 		if (pruned && offset != 0) {
11662 			mutex_exit(&ipfb->ipfb_lock);
11663 			freemsg(mp);
11664 			return (B_FALSE);
11665 		}
11666 
11667 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11668 			/*
11669 			 * Too many fragmented packets in this hash
11670 			 * bucket. Free the oldest.
11671 			 */
11672 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11673 		}
11674 
11675 		/* New guy.  Allocate a frag message. */
11676 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11677 		if (mp1 == NULL) {
11678 			BUMP_MIB(&ip_mib, ipInDiscards);
11679 			freemsg(mp);
11680 reass_done:
11681 			mutex_exit(&ipfb->ipfb_lock);
11682 			return (B_FALSE);
11683 		}
11684 
11685 
11686 		BUMP_MIB(&ip_mib, ipReasmReqds);
11687 		mp1->b_cont = mp;
11688 
11689 		/* Initialize the fragment header. */
11690 		ipf = (ipf_t *)mp1->b_rptr;
11691 		ipf->ipf_mp = mp1;
11692 		ipf->ipf_ptphn = ipfp;
11693 		ipfp[0] = ipf;
11694 		ipf->ipf_hash_next = NULL;
11695 		ipf->ipf_ident = ident;
11696 		ipf->ipf_protocol = proto;
11697 		ipf->ipf_src = src;
11698 		ipf->ipf_dst = dst;
11699 		ipf->ipf_nf_hdr_len = 0;
11700 		/* Record reassembly start time. */
11701 		ipf->ipf_timestamp = gethrestime_sec();
11702 		/* Record ipf generation and account for frag header */
11703 		ipf->ipf_gen = ill->ill_ipf_gen++;
11704 		ipf->ipf_count = MBLKSIZE(mp1);
11705 		ipf->ipf_last_frag_seen = B_FALSE;
11706 		ipf->ipf_ecn = ecn_info;
11707 		ipf->ipf_num_dups = 0;
11708 		ipfb->ipfb_frag_pkts++;
11709 		ipf->ipf_checksum = 0;
11710 		ipf->ipf_checksum_flags = 0;
11711 
11712 		/* Store checksum value in fragment header */
11713 		if (sum_flags != 0) {
11714 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11715 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11716 			ipf->ipf_checksum = sum_val;
11717 			ipf->ipf_checksum_flags = sum_flags;
11718 		}
11719 
11720 		/*
11721 		 * We handle reassembly two ways.  In the easy case,
11722 		 * where all the fragments show up in order, we do
11723 		 * minimal bookkeeping, and just clip new pieces on
11724 		 * the end.  If we ever see a hole, then we go off
11725 		 * to ip_reassemble which has to mark the pieces and
11726 		 * keep track of the number of holes, etc.  Obviously,
11727 		 * the point of having both mechanisms is so we can
11728 		 * handle the easy case as efficiently as possible.
11729 		 */
11730 		if (offset == 0) {
11731 			/* Easy case, in-order reassembly so far. */
11732 			ipf->ipf_count += msg_len;
11733 			ipf->ipf_tail_mp = tail_mp;
11734 			/*
11735 			 * Keep track of next expected offset in
11736 			 * ipf_end.
11737 			 */
11738 			ipf->ipf_end = end;
11739 			ipf->ipf_nf_hdr_len = hdr_length;
11740 		} else {
11741 			/* Hard case, hole at the beginning. */
11742 			ipf->ipf_tail_mp = NULL;
11743 			/*
11744 			 * ipf_end == 0 means that we have given up
11745 			 * on easy reassembly.
11746 			 */
11747 			ipf->ipf_end = 0;
11748 
11749 			/* Forget checksum offload from now on */
11750 			ipf->ipf_checksum_flags = 0;
11751 
11752 			/*
11753 			 * ipf_hole_cnt is set by ip_reassemble.
11754 			 * ipf_count is updated by ip_reassemble.
11755 			 * No need to check for return value here
11756 			 * as we don't expect reassembly to complete
11757 			 * or fail for the first fragment itself.
11758 			 */
11759 			(void) ip_reassemble(mp, ipf,
11760 			    (frag_offset_flags & IPH_OFFSET) << 3,
11761 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11762 		}
11763 		/* Update per ipfb and ill byte counts */
11764 		ipfb->ipfb_count += ipf->ipf_count;
11765 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11766 		ill->ill_frag_count += ipf->ipf_count;
11767 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11768 		/* If the frag timer wasn't already going, start it. */
11769 		mutex_enter(&ill->ill_lock);
11770 		ill_frag_timer_start(ill);
11771 		mutex_exit(&ill->ill_lock);
11772 		goto reass_done;
11773 	}
11774 
11775 	/*
11776 	 * If the packet's flag has changed (it could be coming up
11777 	 * from an interface different than the previous, therefore
11778 	 * possibly different checksum capability), then forget about
11779 	 * any stored checksum states.  Otherwise add the value to
11780 	 * the existing one stored in the fragment header.
11781 	 */
11782 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11783 		sum_val += ipf->ipf_checksum;
11784 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11785 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11786 		ipf->ipf_checksum = sum_val;
11787 	} else if (ipf->ipf_checksum_flags != 0) {
11788 		/* Forget checksum offload from now on */
11789 		ipf->ipf_checksum_flags = 0;
11790 	}
11791 
11792 	/*
11793 	 * We have a new piece of a datagram which is already being
11794 	 * reassembled.  Update the ECN info if all IP fragments
11795 	 * are ECN capable.  If there is one which is not, clear
11796 	 * all the info.  If there is at least one which has CE
11797 	 * code point, IP needs to report that up to transport.
11798 	 */
11799 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11800 		if (ecn_info == IPH_ECN_CE)
11801 			ipf->ipf_ecn = IPH_ECN_CE;
11802 	} else {
11803 		ipf->ipf_ecn = IPH_ECN_NECT;
11804 	}
11805 	if (offset && ipf->ipf_end == offset) {
11806 		/* The new fragment fits at the end */
11807 		ipf->ipf_tail_mp->b_cont = mp;
11808 		/* Update the byte count */
11809 		ipf->ipf_count += msg_len;
11810 		/* Update per ipfb and ill byte counts */
11811 		ipfb->ipfb_count += msg_len;
11812 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11813 		ill->ill_frag_count += msg_len;
11814 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11815 		if (frag_offset_flags & IPH_MF) {
11816 			/* More to come. */
11817 			ipf->ipf_end = end;
11818 			ipf->ipf_tail_mp = tail_mp;
11819 			goto reass_done;
11820 		}
11821 	} else {
11822 		/* Go do the hard cases. */
11823 		int ret;
11824 
11825 		if (offset == 0)
11826 			ipf->ipf_nf_hdr_len = hdr_length;
11827 
11828 		/* Save current byte count */
11829 		count = ipf->ipf_count;
11830 		ret = ip_reassemble(mp, ipf,
11831 		    (frag_offset_flags & IPH_OFFSET) << 3,
11832 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11833 		/* Count of bytes added and subtracted (freeb()ed) */
11834 		count = ipf->ipf_count - count;
11835 		if (count) {
11836 			/* Update per ipfb and ill byte counts */
11837 			ipfb->ipfb_count += count;
11838 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11839 			ill->ill_frag_count += count;
11840 			ASSERT(ill->ill_frag_count > 0);
11841 		}
11842 		if (ret == IP_REASS_PARTIAL) {
11843 			goto reass_done;
11844 		} else if (ret == IP_REASS_FAILED) {
11845 			/* Reassembly failed. Free up all resources */
11846 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11847 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11848 				IP_REASS_SET_START(t_mp, 0);
11849 				IP_REASS_SET_END(t_mp, 0);
11850 			}
11851 			freemsg(mp);
11852 			goto reass_done;
11853 		}
11854 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11855 	}
11856 	/*
11857 	 * We have completed reassembly.  Unhook the frag header from
11858 	 * the reassembly list.
11859 	 *
11860 	 * Before we free the frag header, record the ECN info
11861 	 * to report back to the transport.
11862 	 */
11863 	ecn_info = ipf->ipf_ecn;
11864 	BUMP_MIB(&ip_mib, ipReasmOKs);
11865 	ipfp = ipf->ipf_ptphn;
11866 
11867 	/* We need to supply these to caller */
11868 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11869 		sum_val = ipf->ipf_checksum;
11870 	else
11871 		sum_val = 0;
11872 
11873 	mp1 = ipf->ipf_mp;
11874 	count = ipf->ipf_count;
11875 	ipf = ipf->ipf_hash_next;
11876 	if (ipf != NULL)
11877 		ipf->ipf_ptphn = ipfp;
11878 	ipfp[0] = ipf;
11879 	ill->ill_frag_count -= count;
11880 	ASSERT(ipfb->ipfb_count >= count);
11881 	ipfb->ipfb_count -= count;
11882 	ipfb->ipfb_frag_pkts--;
11883 	mutex_exit(&ipfb->ipfb_lock);
11884 	/* Ditch the frag header. */
11885 	mp = mp1->b_cont;
11886 
11887 	freeb(mp1);
11888 
11889 	/* Restore original IP length in header. */
11890 	packet_size = (uint32_t)msgdsize(mp);
11891 	if (packet_size > IP_MAXPACKET) {
11892 		freemsg(mp);
11893 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11894 		return (B_FALSE);
11895 	}
11896 
11897 	if (DB_REF(mp) > 1) {
11898 		mblk_t *mp2 = copymsg(mp);
11899 
11900 		freemsg(mp);
11901 		if (mp2 == NULL) {
11902 			BUMP_MIB(&ip_mib, ipInDiscards);
11903 			return (B_FALSE);
11904 		}
11905 		mp = mp2;
11906 	}
11907 	ipha = (ipha_t *)mp->b_rptr;
11908 
11909 	ipha->ipha_length = htons((uint16_t)packet_size);
11910 	/* We're now complete, zip the frag state */
11911 	ipha->ipha_fragment_offset_and_flags = 0;
11912 	/* Record the ECN info. */
11913 	ipha->ipha_type_of_service &= 0xFC;
11914 	ipha->ipha_type_of_service |= ecn_info;
11915 	*mpp = mp;
11916 
11917 	/* Reassembly is successful; return checksum information if needed */
11918 	if (cksum_val != NULL)
11919 		*cksum_val = sum_val;
11920 	if (cksum_flags != NULL)
11921 		*cksum_flags = sum_flags;
11922 
11923 	return (B_TRUE);
11924 }
11925 
11926 /*
11927  * Perform ip header check sum update local options.
11928  * return B_TRUE if all is well, else return B_FALSE and release
11929  * the mp. caller is responsible for decrementing ire ref cnt.
11930  */
11931 static boolean_t
11932 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11933 {
11934 	mblk_t		*first_mp;
11935 	boolean_t	mctl_present;
11936 	uint16_t	sum;
11937 
11938 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11939 	/*
11940 	 * Don't do the checksum if it has gone through AH/ESP
11941 	 * processing.
11942 	 */
11943 	if (!mctl_present) {
11944 		sum = ip_csum_hdr(ipha);
11945 		if (sum != 0) {
11946 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11947 			freemsg(first_mp);
11948 			return (B_FALSE);
11949 		}
11950 	}
11951 
11952 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11953 		if (mctl_present)
11954 			freeb(first_mp);
11955 		return (B_FALSE);
11956 	}
11957 
11958 	return (B_TRUE);
11959 }
11960 
11961 /*
11962  * All udp packet are delivered to the local host via this routine.
11963  */
11964 void
11965 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11966     ill_t *recv_ill)
11967 {
11968 	uint32_t	sum;
11969 	uint32_t	u1;
11970 	boolean_t	mctl_present;
11971 	conn_t		*connp;
11972 	mblk_t		*first_mp;
11973 	uint16_t	*up;
11974 	ill_t		*ill = (ill_t *)q->q_ptr;
11975 	uint16_t	reass_hck_flags = 0;
11976 
11977 #define	rptr    ((uchar_t *)ipha)
11978 
11979 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11980 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11981 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11982 
11983 	/*
11984 	 * FAST PATH for udp packets
11985 	 */
11986 
11987 	/* u1 is # words of IP options */
11988 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11989 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11990 
11991 	/* IP options present */
11992 	if (u1 != 0)
11993 		goto ipoptions;
11994 
11995 	/* Check the IP header checksum.  */
11996 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
11997 		/* Clear the IP header h/w cksum flag */
11998 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
11999 	} else {
12000 #define	uph	((uint16_t *)ipha)
12001 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12002 		    uph[6] + uph[7] + uph[8] + uph[9];
12003 #undef	uph
12004 		/* finish doing IP checksum */
12005 		sum = (sum & 0xFFFF) + (sum >> 16);
12006 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12007 		/*
12008 		 * Don't verify header checksum if this packet is coming
12009 		 * back from AH/ESP as we already did it.
12010 		 */
12011 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12012 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12013 			freemsg(first_mp);
12014 			return;
12015 		}
12016 	}
12017 
12018 	/*
12019 	 * Count for SNMP of inbound packets for ire.
12020 	 * if mctl is present this might be a secure packet and
12021 	 * has already been counted for in ip_proto_input().
12022 	 */
12023 	if (!mctl_present) {
12024 		UPDATE_IB_PKT_COUNT(ire);
12025 		ire->ire_last_used_time = lbolt;
12026 	}
12027 
12028 	/* packet part of fragmented IP packet? */
12029 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12030 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12031 		goto fragmented;
12032 	}
12033 
12034 	/* u1 = IP header length (20 bytes) */
12035 	u1 = IP_SIMPLE_HDR_LENGTH;
12036 
12037 	/* packet does not contain complete IP & UDP headers */
12038 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12039 		goto udppullup;
12040 
12041 	/* up points to UDP header */
12042 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12043 #define	iphs    ((uint16_t *)ipha)
12044 
12045 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12046 	if (up[3] != 0) {
12047 		mblk_t *mp1 = mp->b_cont;
12048 		boolean_t cksum_err;
12049 		uint16_t hck_flags = 0;
12050 
12051 		/* Pseudo-header checksum */
12052 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12053 		    iphs[9] + up[2];
12054 
12055 		/*
12056 		 * Revert to software checksum calculation if the interface
12057 		 * isn't capable of checksum offload or if IPsec is present.
12058 		 */
12059 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12060 			hck_flags = DB_CKSUMFLAGS(mp);
12061 
12062 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12063 			IP_STAT(ip_in_sw_cksum);
12064 
12065 		IP_CKSUM_RECV(hck_flags, u1,
12066 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12067 		    (int32_t)((uchar_t *)up - rptr),
12068 		    mp, mp1, cksum_err);
12069 
12070 		if (cksum_err) {
12071 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12072 
12073 			if (hck_flags & HCK_FULLCKSUM)
12074 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12075 			else if (hck_flags & HCK_PARTIALCKSUM)
12076 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12077 			else
12078 				IP_STAT(ip_udp_in_sw_cksum_err);
12079 
12080 			freemsg(first_mp);
12081 			return;
12082 		}
12083 	}
12084 
12085 	/* Non-fragmented broadcast or multicast packet? */
12086 	if (ire->ire_type == IRE_BROADCAST)
12087 		goto udpslowpath;
12088 
12089 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12090 	    ire->ire_zoneid)) != NULL) {
12091 		ASSERT(connp->conn_upq != NULL);
12092 		IP_STAT(ip_udp_fast_path);
12093 
12094 		if (CONN_UDP_FLOWCTLD(connp)) {
12095 			freemsg(mp);
12096 			BUMP_MIB(&ip_mib, udpInOverflows);
12097 		} else {
12098 			if (!mctl_present) {
12099 				BUMP_MIB(&ip_mib, ipInDelivers);
12100 			}
12101 			/*
12102 			 * mp and first_mp can change.
12103 			 */
12104 			if (ip_udp_check(q, connp, recv_ill,
12105 			    ipha, &mp, &first_mp, mctl_present)) {
12106 				/* Send it upstream */
12107 				CONN_UDP_RECV(connp, mp);
12108 			}
12109 		}
12110 		/*
12111 		 * freeb() cannot deal with null mblk being passed
12112 		 * in and first_mp can be set to null in the call
12113 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12114 		 */
12115 		if (mctl_present && first_mp != NULL) {
12116 			freeb(first_mp);
12117 		}
12118 		CONN_DEC_REF(connp);
12119 		return;
12120 	}
12121 
12122 	/*
12123 	 * if we got here we know the packet is not fragmented and
12124 	 * has no options. The classifier could not find a conn_t and
12125 	 * most likely its an icmp packet so send it through slow path.
12126 	 */
12127 
12128 	goto udpslowpath;
12129 
12130 ipoptions:
12131 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12132 		goto slow_done;
12133 	}
12134 
12135 	UPDATE_IB_PKT_COUNT(ire);
12136 	ire->ire_last_used_time = lbolt;
12137 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12138 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12139 fragmented:
12140 		/*
12141 		 * "sum" and "reass_hck_flags" are non-zero if the
12142 		 * reassembled packet has a valid hardware computed
12143 		 * checksum information associated with it.
12144 		 */
12145 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12146 			goto slow_done;
12147 		/*
12148 		 * Make sure that first_mp points back to mp as
12149 		 * the mp we came in with could have changed in
12150 		 * ip_rput_fragment().
12151 		 */
12152 		ASSERT(!mctl_present);
12153 		ipha = (ipha_t *)mp->b_rptr;
12154 		first_mp = mp;
12155 	}
12156 
12157 	/* Now we have a complete datagram, destined for this machine. */
12158 	u1 = IPH_HDR_LENGTH(ipha);
12159 	/* Pull up the UDP header, if necessary. */
12160 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12161 udppullup:
12162 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12163 			BUMP_MIB(&ip_mib, ipInDiscards);
12164 			freemsg(first_mp);
12165 			goto slow_done;
12166 		}
12167 		ipha = (ipha_t *)mp->b_rptr;
12168 	}
12169 
12170 	/*
12171 	 * Validate the checksum for the reassembled packet; for the
12172 	 * pullup case we calculate the payload checksum in software.
12173 	 */
12174 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12175 	if (up[3] != 0) {
12176 		boolean_t cksum_err;
12177 
12178 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12179 			IP_STAT(ip_in_sw_cksum);
12180 
12181 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12182 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12183 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12184 		    iphs[9] + up[2], sum, cksum_err);
12185 
12186 		if (cksum_err) {
12187 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12188 
12189 			if (reass_hck_flags & HCK_FULLCKSUM)
12190 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12191 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12192 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12193 			else
12194 				IP_STAT(ip_udp_in_sw_cksum_err);
12195 
12196 			freemsg(first_mp);
12197 			goto slow_done;
12198 		}
12199 	}
12200 udpslowpath:
12201 
12202 	/* Clear hardware checksum flag to be safe */
12203 	DB_CKSUMFLAGS(mp) = 0;
12204 
12205 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12206 	    (ire->ire_type == IRE_BROADCAST),
12207 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12208 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12209 
12210 slow_done:
12211 	IP_STAT(ip_udp_slow_path);
12212 	return;
12213 
12214 #undef  iphs
12215 #undef  rptr
12216 }
12217 
12218 /* ARGSUSED */
12219 static mblk_t *
12220 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12221     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12222     ill_rx_ring_t *ill_ring)
12223 {
12224 	conn_t		*connp;
12225 	uint32_t	sum;
12226 	uint32_t	u1;
12227 	uint16_t	*up;
12228 	int		offset;
12229 	ssize_t		len;
12230 	mblk_t		*mp1;
12231 	boolean_t	syn_present = B_FALSE;
12232 	tcph_t		*tcph;
12233 	uint_t		ip_hdr_len;
12234 	ill_t		*ill = (ill_t *)q->q_ptr;
12235 	zoneid_t	zoneid = ire->ire_zoneid;
12236 	boolean_t	cksum_err;
12237 	uint16_t	hck_flags = 0;
12238 
12239 #define	rptr	((uchar_t *)ipha)
12240 
12241 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12242 
12243 	/*
12244 	 * FAST PATH for tcp packets
12245 	 */
12246 
12247 	/* u1 is # words of IP options */
12248 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12249 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12250 
12251 	/* IP options present */
12252 	if (u1) {
12253 		goto ipoptions;
12254 	} else {
12255 		/* Check the IP header checksum.  */
12256 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12257 			/* Clear the IP header h/w cksum flag */
12258 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12259 		} else {
12260 #define	uph	((uint16_t *)ipha)
12261 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12262 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12263 #undef	uph
12264 			/* finish doing IP checksum */
12265 			sum = (sum & 0xFFFF) + (sum >> 16);
12266 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12267 			/*
12268 			 * Don't verify header checksum if this packet
12269 			 * is coming back from AH/ESP as we already did it.
12270 			 */
12271 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12272 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12273 				goto error;
12274 			}
12275 		}
12276 	}
12277 
12278 	if (!mctl_present) {
12279 		UPDATE_IB_PKT_COUNT(ire);
12280 		ire->ire_last_used_time = lbolt;
12281 	}
12282 
12283 	/* packet part of fragmented IP packet? */
12284 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12285 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12286 		goto fragmented;
12287 	}
12288 
12289 	/* u1 = IP header length (20 bytes) */
12290 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12291 
12292 	/* does packet contain IP+TCP headers? */
12293 	len = mp->b_wptr - rptr;
12294 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12295 		IP_STAT(ip_tcppullup);
12296 		goto tcppullup;
12297 	}
12298 
12299 	/* TCP options present? */
12300 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12301 
12302 	/*
12303 	 * If options need to be pulled up, then goto tcpoptions.
12304 	 * otherwise we are still in the fast path
12305 	 */
12306 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12307 		IP_STAT(ip_tcpoptions);
12308 		goto tcpoptions;
12309 	}
12310 
12311 	/* multiple mblks of tcp data? */
12312 	if ((mp1 = mp->b_cont) != NULL) {
12313 		/* more then two? */
12314 		if (mp1->b_cont != NULL) {
12315 			IP_STAT(ip_multipkttcp);
12316 			goto multipkttcp;
12317 		}
12318 		len += mp1->b_wptr - mp1->b_rptr;
12319 	}
12320 
12321 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12322 
12323 	/* part of pseudo checksum */
12324 
12325 	/* TCP datagram length */
12326 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12327 
12328 #define	iphs    ((uint16_t *)ipha)
12329 
12330 #ifdef	_BIG_ENDIAN
12331 	u1 += IPPROTO_TCP;
12332 #else
12333 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12334 #endif
12335 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12336 
12337 	/*
12338 	 * Revert to software checksum calculation if the interface
12339 	 * isn't capable of checksum offload or if IPsec is present.
12340 	 */
12341 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12342 		hck_flags = DB_CKSUMFLAGS(mp);
12343 
12344 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12345 		IP_STAT(ip_in_sw_cksum);
12346 
12347 	IP_CKSUM_RECV(hck_flags, u1,
12348 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12349 	    (int32_t)((uchar_t *)up - rptr),
12350 	    mp, mp1, cksum_err);
12351 
12352 	if (cksum_err) {
12353 		BUMP_MIB(&ip_mib, tcpInErrs);
12354 
12355 		if (hck_flags & HCK_FULLCKSUM)
12356 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12357 		else if (hck_flags & HCK_PARTIALCKSUM)
12358 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12359 		else
12360 			IP_STAT(ip_tcp_in_sw_cksum_err);
12361 
12362 		goto error;
12363 	}
12364 
12365 try_again:
12366 
12367 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12368 	    NULL) {
12369 		/* Send the TH_RST */
12370 		goto no_conn;
12371 	}
12372 
12373 	/*
12374 	 * TCP FAST PATH for AF_INET socket.
12375 	 *
12376 	 * TCP fast path to avoid extra work. An AF_INET socket type
12377 	 * does not have facility to receive extra information via
12378 	 * ip_process or ip_add_info. Also, when the connection was
12379 	 * established, we made a check if this connection is impacted
12380 	 * by any global IPSec policy or per connection policy (a
12381 	 * policy that comes in effect later will not apply to this
12382 	 * connection). Since all this can be determined at the
12383 	 * connection establishment time, a quick check of flags
12384 	 * can avoid extra work.
12385 	 */
12386 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12387 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12388 		ASSERT(first_mp == mp);
12389 		SET_SQUEUE(mp, tcp_rput_data, connp);
12390 		return (mp);
12391 	}
12392 
12393 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12394 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12395 		if (IPCL_IS_TCP(connp)) {
12396 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12397 			DB_CKSUMSTART(mp) =
12398 			    (intptr_t)ip_squeue_get(ill_ring);
12399 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12400 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12401 				SET_SQUEUE(mp, connp->conn_recv, connp);
12402 				return (mp);
12403 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12404 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12405 				ip_squeue_enter_unbound++;
12406 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12407 				    connp);
12408 				return (mp);
12409 			}
12410 			syn_present = B_TRUE;
12411 		}
12412 
12413 	}
12414 
12415 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12416 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12417 
12418 		/* No need to send this packet to TCP */
12419 		if ((flags & TH_RST) || (flags & TH_URG)) {
12420 			CONN_DEC_REF(connp);
12421 			freemsg(first_mp);
12422 			return (NULL);
12423 		}
12424 		if (flags & TH_ACK) {
12425 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
12426 			CONN_DEC_REF(connp);
12427 			return (NULL);
12428 		}
12429 
12430 		CONN_DEC_REF(connp);
12431 		freemsg(first_mp);
12432 		return (NULL);
12433 	}
12434 
12435 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12436 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12437 		    ipha, NULL, mctl_present);
12438 		if (first_mp == NULL) {
12439 			CONN_DEC_REF(connp);
12440 			return (NULL);
12441 		}
12442 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12443 			ASSERT(syn_present);
12444 			if (mctl_present) {
12445 				ASSERT(first_mp != mp);
12446 				first_mp->b_datap->db_struioflag |=
12447 				    STRUIO_POLICY;
12448 			} else {
12449 				ASSERT(first_mp == mp);
12450 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12451 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12452 			}
12453 		} else {
12454 			/*
12455 			 * Discard first_mp early since we're dealing with a
12456 			 * fully-connected conn_t and tcp doesn't do policy in
12457 			 * this case.
12458 			 */
12459 			if (mctl_present) {
12460 				freeb(first_mp);
12461 				mctl_present = B_FALSE;
12462 			}
12463 			first_mp = mp;
12464 		}
12465 	}
12466 
12467 	/* Initiate IPPF processing for fastpath */
12468 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12469 		uint32_t	ill_index;
12470 
12471 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12472 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12473 		if (mp == NULL) {
12474 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12475 			    "deferred/dropped during IPPF processing\n"));
12476 			CONN_DEC_REF(connp);
12477 			if (mctl_present)
12478 				freeb(first_mp);
12479 			return (NULL);
12480 		} else if (mctl_present) {
12481 			/*
12482 			 * ip_process might return a new mp.
12483 			 */
12484 			ASSERT(first_mp != mp);
12485 			first_mp->b_cont = mp;
12486 		} else {
12487 			first_mp = mp;
12488 		}
12489 
12490 	}
12491 
12492 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12493 		mp = ip_add_info(mp, recv_ill, flags);
12494 		if (mp == NULL) {
12495 			CONN_DEC_REF(connp);
12496 			if (mctl_present)
12497 				freeb(first_mp);
12498 			return (NULL);
12499 		} else if (mctl_present) {
12500 			/*
12501 			 * ip_add_info might return a new mp.
12502 			 */
12503 			ASSERT(first_mp != mp);
12504 			first_mp->b_cont = mp;
12505 		} else {
12506 			first_mp = mp;
12507 		}
12508 	}
12509 
12510 	if (IPCL_IS_TCP(connp)) {
12511 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12512 		return (first_mp);
12513 	} else {
12514 		putnext(connp->conn_rq, first_mp);
12515 		CONN_DEC_REF(connp);
12516 		return (NULL);
12517 	}
12518 
12519 no_conn:
12520 	/* Initiate IPPf processing, if needed. */
12521 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12522 		uint32_t ill_index;
12523 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12524 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12525 		if (first_mp == NULL) {
12526 			return (NULL);
12527 		}
12528 	}
12529 	BUMP_MIB(&ip_mib, ipInDelivers);
12530 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12531 	return (NULL);
12532 ipoptions:
12533 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12534 		goto slow_done;
12535 	}
12536 
12537 	UPDATE_IB_PKT_COUNT(ire);
12538 	ire->ire_last_used_time = lbolt;
12539 
12540 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12541 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12542 fragmented:
12543 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12544 			if (mctl_present)
12545 				freeb(first_mp);
12546 			goto slow_done;
12547 		}
12548 		/*
12549 		 * Make sure that first_mp points back to mp as
12550 		 * the mp we came in with could have changed in
12551 		 * ip_rput_fragment().
12552 		 */
12553 		ASSERT(!mctl_present);
12554 		ipha = (ipha_t *)mp->b_rptr;
12555 		first_mp = mp;
12556 	}
12557 
12558 	/* Now we have a complete datagram, destined for this machine. */
12559 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12560 
12561 	len = mp->b_wptr - mp->b_rptr;
12562 	/* Pull up a minimal TCP header, if necessary. */
12563 	if (len < (u1 + 20)) {
12564 tcppullup:
12565 		if (!pullupmsg(mp, u1 + 20)) {
12566 			BUMP_MIB(&ip_mib, ipInDiscards);
12567 			goto error;
12568 		}
12569 		ipha = (ipha_t *)mp->b_rptr;
12570 		len = mp->b_wptr - mp->b_rptr;
12571 	}
12572 
12573 	/*
12574 	 * Extract the offset field from the TCP header.  As usual, we
12575 	 * try to help the compiler more than the reader.
12576 	 */
12577 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12578 	if (offset != 5) {
12579 tcpoptions:
12580 		if (offset < 5) {
12581 			BUMP_MIB(&ip_mib, ipInDiscards);
12582 			goto error;
12583 		}
12584 		/*
12585 		 * There must be TCP options.
12586 		 * Make sure we can grab them.
12587 		 */
12588 		offset <<= 2;
12589 		offset += u1;
12590 		if (len < offset) {
12591 			if (!pullupmsg(mp, offset)) {
12592 				BUMP_MIB(&ip_mib, ipInDiscards);
12593 				goto error;
12594 			}
12595 			ipha = (ipha_t *)mp->b_rptr;
12596 			len = mp->b_wptr - rptr;
12597 		}
12598 	}
12599 
12600 	/* Get the total packet length in len, including headers. */
12601 	if (mp->b_cont) {
12602 multipkttcp:
12603 		len = msgdsize(mp);
12604 	}
12605 
12606 	/*
12607 	 * Check the TCP checksum by pulling together the pseudo-
12608 	 * header checksum, and passing it to ip_csum to be added in
12609 	 * with the TCP datagram.
12610 	 *
12611 	 * Since we are not using the hwcksum if available we must
12612 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12613 	 * If either of these fails along the way the mblk is freed.
12614 	 * If this logic ever changes and mblk is reused to say send
12615 	 * ICMP's back, then this flag may need to be cleared in
12616 	 * other places as well.
12617 	 */
12618 	DB_CKSUMFLAGS(mp) = 0;
12619 
12620 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12621 
12622 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12623 #ifdef	_BIG_ENDIAN
12624 	u1 += IPPROTO_TCP;
12625 #else
12626 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12627 #endif
12628 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12629 	/*
12630 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12631 	 */
12632 	IP_STAT(ip_in_sw_cksum);
12633 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12634 		BUMP_MIB(&ip_mib, tcpInErrs);
12635 		goto error;
12636 	}
12637 
12638 	IP_STAT(ip_tcp_slow_path);
12639 	goto try_again;
12640 #undef  iphs
12641 #undef  rptr
12642 
12643 error:
12644 	freemsg(first_mp);
12645 slow_done:
12646 	return (NULL);
12647 }
12648 
12649 /* ARGSUSED */
12650 static void
12651 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12652     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12653 {
12654 	conn_t		*connp;
12655 	uint32_t	sum;
12656 	uint32_t	u1;
12657 	ssize_t		len;
12658 	sctp_hdr_t	*sctph;
12659 	zoneid_t	zoneid = ire->ire_zoneid;
12660 	uint32_t	pktsum;
12661 	uint32_t	calcsum;
12662 	uint32_t	ports;
12663 	uint_t		ipif_seqid;
12664 	in6_addr_t	map_src, map_dst;
12665 	ill_t		*ill = (ill_t *)q->q_ptr;
12666 
12667 #define	rptr	((uchar_t *)ipha)
12668 
12669 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12670 
12671 	/* u1 is # words of IP options */
12672 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12673 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12674 
12675 	/* IP options present */
12676 	if (u1 > 0) {
12677 		goto ipoptions;
12678 	} else {
12679 		/* Check the IP header checksum.  */
12680 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12681 #define	uph	((uint16_t *)ipha)
12682 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12683 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12684 #undef	uph
12685 			/* finish doing IP checksum */
12686 			sum = (sum & 0xFFFF) + (sum >> 16);
12687 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12688 			/*
12689 			 * Don't verify header checksum if this packet
12690 			 * is coming back from AH/ESP as we already did it.
12691 			 */
12692 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12693 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12694 				goto error;
12695 			}
12696 		}
12697 		/*
12698 		 * Since there is no SCTP h/w cksum support yet, just
12699 		 * clear the flag.
12700 		 */
12701 		DB_CKSUMFLAGS(mp) = 0;
12702 	}
12703 
12704 	/*
12705 	 * Don't verify header checksum if this packet is coming
12706 	 * back from AH/ESP as we already did it.
12707 	 */
12708 	if (!mctl_present) {
12709 		UPDATE_IB_PKT_COUNT(ire);
12710 		ire->ire_last_used_time = lbolt;
12711 	}
12712 
12713 	/* packet part of fragmented IP packet? */
12714 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12715 	if (u1 & (IPH_MF | IPH_OFFSET))
12716 		goto fragmented;
12717 
12718 	/* u1 = IP header length (20 bytes) */
12719 	u1 = IP_SIMPLE_HDR_LENGTH;
12720 
12721 find_sctp_client:
12722 	/* Pullup if we don't have the sctp common header. */
12723 	len = MBLKL(mp);
12724 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12725 		if (mp->b_cont == NULL ||
12726 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12727 			BUMP_MIB(&ip_mib, ipInDiscards);
12728 			goto error;
12729 		}
12730 		ipha = (ipha_t *)mp->b_rptr;
12731 		len = MBLKL(mp);
12732 	}
12733 
12734 	sctph = (sctp_hdr_t *)(rptr + u1);
12735 #ifdef	DEBUG
12736 	if (!skip_sctp_cksum) {
12737 #endif
12738 		pktsum = sctph->sh_chksum;
12739 		sctph->sh_chksum = 0;
12740 		calcsum = sctp_cksum(mp, u1);
12741 		if (calcsum != pktsum) {
12742 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12743 			goto error;
12744 		}
12745 		sctph->sh_chksum = pktsum;
12746 #ifdef	DEBUG	/* skip_sctp_cksum */
12747 	}
12748 #endif
12749 	/* get the ports */
12750 	ports = *(uint32_t *)&sctph->sh_sport;
12751 
12752 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12753 	IRE_REFRELE(ire);
12754 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12755 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12756 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
12757 	    mp)) == NULL) {
12758 		/* Check for raw socket or OOTB handling */
12759 		goto no_conn;
12760 	}
12761 
12762 	/* Found a client; up it goes */
12763 	BUMP_MIB(&ip_mib, ipInDelivers);
12764 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12765 	return;
12766 
12767 no_conn:
12768 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12769 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12770 	return;
12771 
12772 ipoptions:
12773 	DB_CKSUMFLAGS(mp) = 0;
12774 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12775 		goto slow_done;
12776 
12777 	UPDATE_IB_PKT_COUNT(ire);
12778 	ire->ire_last_used_time = lbolt;
12779 
12780 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12781 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12782 fragmented:
12783 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12784 			goto slow_done;
12785 		/*
12786 		 * Make sure that first_mp points back to mp as
12787 		 * the mp we came in with could have changed in
12788 		 * ip_rput_fragment().
12789 		 */
12790 		ASSERT(!mctl_present);
12791 		ipha = (ipha_t *)mp->b_rptr;
12792 		first_mp = mp;
12793 	}
12794 
12795 	/* Now we have a complete datagram, destined for this machine. */
12796 	u1 = IPH_HDR_LENGTH(ipha);
12797 	goto find_sctp_client;
12798 #undef  iphs
12799 #undef  rptr
12800 
12801 error:
12802 	freemsg(first_mp);
12803 slow_done:
12804 	IRE_REFRELE(ire);
12805 }
12806 
12807 #define	VER_BITS	0xF0
12808 #define	VERSION_6	0x60
12809 
12810 static boolean_t
12811 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12812     ipaddr_t *dstp)
12813 {
12814 	uint_t	opt_len;
12815 	ipha_t *ipha;
12816 	ssize_t len;
12817 	uint_t	pkt_len;
12818 
12819 	IP_STAT(ip_ipoptions);
12820 	ipha = *iphapp;
12821 
12822 #define	rptr    ((uchar_t *)ipha)
12823 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12824 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12825 		BUMP_MIB(&ip_mib, ipInIPv6);
12826 		freemsg(mp);
12827 		return (B_FALSE);
12828 	}
12829 
12830 	/* multiple mblk or too short */
12831 	pkt_len = ntohs(ipha->ipha_length);
12832 
12833 	/* Get the number of words of IP options in the IP header. */
12834 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12835 	if (opt_len) {
12836 		/* IP Options present!  Validate and process. */
12837 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12838 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12839 			goto done;
12840 		}
12841 		/*
12842 		 * Recompute complete header length and make sure we
12843 		 * have access to all of it.
12844 		 */
12845 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12846 		if (len > (mp->b_wptr - rptr)) {
12847 			if (len > pkt_len) {
12848 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12849 				goto done;
12850 			}
12851 			if (!pullupmsg(mp, len)) {
12852 				BUMP_MIB(&ip_mib, ipInDiscards);
12853 				goto done;
12854 			}
12855 			ipha = (ipha_t *)mp->b_rptr;
12856 		}
12857 		/*
12858 		 * Go off to ip_rput_options which returns the next hop
12859 		 * destination address, which may have been affected
12860 		 * by source routing.
12861 		 */
12862 		IP_STAT(ip_opt);
12863 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12864 			return (B_FALSE);
12865 		}
12866 	}
12867 	*iphapp = ipha;
12868 	return (B_TRUE);
12869 done:
12870 	/* clear b_prev - used by ip_mroute_decap */
12871 	mp->b_prev = NULL;
12872 	freemsg(mp);
12873 	return (B_FALSE);
12874 #undef  rptr
12875 }
12876 
12877 /*
12878  * Deal with the fact that there is no ire for the destination.
12879  * The incoming ill (in_ill) is passed in to ip_newroute only
12880  * in the case of packets coming from mobile ip forward tunnel.
12881  * It must be null otherwise.
12882  */
12883 static void
12884 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12885     ipaddr_t dst)
12886 {
12887 	ipha_t	*ipha;
12888 	ill_t	*ill;
12889 
12890 	ipha = (ipha_t *)mp->b_rptr;
12891 	ill = (ill_t *)q->q_ptr;
12892 
12893 	ASSERT(ill != NULL);
12894 	/*
12895 	 * No IRE for this destination, so it can't be for us.
12896 	 * Unless we are forwarding, drop the packet.
12897 	 * We have to let source routed packets through
12898 	 * since we don't yet know if they are 'ping -l'
12899 	 * packets i.e. if they will go out over the
12900 	 * same interface as they came in on.
12901 	 */
12902 	if (ll_multicast) {
12903 		freemsg(mp);
12904 		return;
12905 	}
12906 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12907 		BUMP_MIB(&ip_mib, ipForwProhibits);
12908 		freemsg(mp);
12909 		return;
12910 	}
12911 
12912 	/* Check for Martian addresses */
12913 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12914 		freemsg(mp);
12915 		return;
12916 	}
12917 
12918 	/* Mark this packet as having originated externally */
12919 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12920 
12921 	/*
12922 	 * Clear the indication that this may have a hardware checksum
12923 	 * as we are not using it
12924 	 */
12925 	DB_CKSUMFLAGS(mp) = 0;
12926 
12927 	/*
12928 	 * Now hand the packet to ip_newroute.
12929 	 */
12930 	ip_newroute(q, mp, dst, in_ill, NULL);
12931 }
12932 
12933 /*
12934  * check ip header length and align it.
12935  */
12936 static boolean_t
12937 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12938 {
12939 	ssize_t len;
12940 	ill_t *ill;
12941 	ipha_t	*ipha;
12942 
12943 	len = MBLKL(mp);
12944 
12945 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12946 		if (!OK_32PTR(mp->b_rptr))
12947 			IP_STAT(ip_notaligned1);
12948 		else
12949 			IP_STAT(ip_notaligned2);
12950 		/* Guard against bogus device drivers */
12951 		if (len < 0) {
12952 			/* clear b_prev - used by ip_mroute_decap */
12953 			mp->b_prev = NULL;
12954 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12955 			freemsg(mp);
12956 			return (B_FALSE);
12957 		}
12958 
12959 		if (ip_rput_pullups++ == 0) {
12960 			ill = (ill_t *)q->q_ptr;
12961 			ipha = (ipha_t *)mp->b_rptr;
12962 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12963 			    "ip_check_and_align_header: %s forced us to "
12964 			    " pullup pkt, hdr len %ld, hdr addr %p",
12965 			    ill->ill_name, len, ipha);
12966 		}
12967 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12968 			/* clear b_prev - used by ip_mroute_decap */
12969 			mp->b_prev = NULL;
12970 			BUMP_MIB(&ip_mib, ipInDiscards);
12971 			freemsg(mp);
12972 			return (B_FALSE);
12973 		}
12974 	}
12975 	return (B_TRUE);
12976 }
12977 
12978 static boolean_t
12979 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12980 {
12981 	ill_group_t	*ill_group;
12982 	ill_group_t	*ire_group;
12983 	queue_t 	*q;
12984 	ill_t		*ire_ill;
12985 	uint_t		ill_ifindex;
12986 
12987 	q = *qp;
12988 	/*
12989 	 * We need to check to make sure the packet came in
12990 	 * on the queue associated with the destination IRE.
12991 	 * Note that for multicast packets and broadcast packets sent to
12992 	 * a broadcast address which is shared between multiple interfaces
12993 	 * we should not do this since we just got a random broadcast ire.
12994 	 */
12995 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12996 		boolean_t check_multi = B_TRUE;
12997 
12998 		/*
12999 		 * This packet came in on an interface other than the
13000 		 * one associated with the destination address.
13001 		 * "Gateway" it to the appropriate interface here.
13002 		 * As long as the ills belong to the same group,
13003 		 * we don't consider them to arriving on the wrong
13004 		 * interface. Thus, when the switch is doing inbound
13005 		 * load spreading, we won't drop packets when we
13006 		 * are doing strict multihoming checks. Note, the
13007 		 * same holds true for 'usesrc groups' where the
13008 		 * destination address may belong to another interface
13009 		 * to allow multipathing to happen
13010 		 */
13011 		ill_group = ill->ill_group;
13012 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13013 		ill_ifindex = ill->ill_usesrc_ifindex;
13014 		ire_group = ire_ill->ill_group;
13015 
13016 		/*
13017 		 * If it's part of the same IPMP group, or if it's a legal
13018 		 * address on the 'usesrc' interface, then bypass strict
13019 		 * checks.
13020 		 */
13021 		if (ill_group != NULL && ill_group == ire_group) {
13022 			check_multi = B_FALSE;
13023 		} else if (ill_ifindex != 0 &&
13024 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13025 			check_multi = B_FALSE;
13026 		}
13027 
13028 		if (check_multi &&
13029 		    ip_strict_dst_multihoming &&
13030 		    ((ill->ill_flags &
13031 		    ire->ire_ipif->ipif_ill->ill_flags &
13032 		    ILLF_ROUTER) == 0)) {
13033 			/* Drop packet */
13034 			BUMP_MIB(&ip_mib, ipForwProhibits);
13035 			freemsg(mp);
13036 			ire_refrele(ire);
13037 			return (B_TRUE);
13038 		}
13039 
13040 		/*
13041 		 * Change the queue (for non-virtual destination network
13042 		 * interfaces) and ip_rput_local will be called with the right
13043 		 * queue
13044 		 */
13045 		q = ire->ire_rfq;
13046 	}
13047 	/* Must be broadcast.  We'll take it. */
13048 	*qp = q;
13049 	return (B_FALSE);
13050 }
13051 
13052 static void
13053 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13054     ill_t *ill, int ll_multicast)
13055 {
13056 	ill_group_t	*ill_group;
13057 	ill_group_t	*ire_group;
13058 	queue_t	*dev_q;
13059 
13060 	ASSERT(ire->ire_stq != NULL);
13061 	if (ll_multicast != 0)
13062 		goto drop_pkt;
13063 
13064 	if (ip_no_forward(ipha, ill))
13065 		goto drop_pkt;
13066 
13067 	ill_group = ill->ill_group;
13068 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13069 	/*
13070 	 * Check if we want to forward this one at this time.
13071 	 * We allow source routed packets on a host provided that
13072 	 * they go out the same interface or same interface group
13073 	 * as they came in on.
13074 	 *
13075 	 * XXX To be quicker, we may wish to not chase pointers to
13076 	 * get the ILLF_ROUTER flag and instead store the
13077 	 * forwarding policy in the ire.  An unfortunate
13078 	 * side-effect of that would be requiring an ire flush
13079 	 * whenever the ILLF_ROUTER flag changes.
13080 	 */
13081 	if (((ill->ill_flags &
13082 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13083 	    ILLF_ROUTER) == 0) &&
13084 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13085 	    (ill_group != NULL && ill_group == ire_group)))) {
13086 		BUMP_MIB(&ip_mib, ipForwProhibits);
13087 		if (ip_source_routed(ipha)) {
13088 			q = WR(q);
13089 			/*
13090 			 * Clear the indication that this may have
13091 			 * hardware checksum as we are not using it.
13092 			 */
13093 			DB_CKSUMFLAGS(mp) = 0;
13094 			icmp_unreachable(q, mp,
13095 			    ICMP_SOURCE_ROUTE_FAILED);
13096 			ire_refrele(ire);
13097 			return;
13098 		}
13099 		goto drop_pkt;
13100 	}
13101 
13102 	/* Packet is being forwarded. Turning off hwcksum flag. */
13103 	DB_CKSUMFLAGS(mp) = 0;
13104 	if (ip_g_send_redirects) {
13105 		/*
13106 		 * Check whether the incoming interface and outgoing
13107 		 * interface is part of the same group. If so,
13108 		 * send redirects.
13109 		 *
13110 		 * Check the source address to see if it originated
13111 		 * on the same logical subnet it is going back out on.
13112 		 * If so, we should be able to send it a redirect.
13113 		 * Avoid sending a redirect if the destination
13114 		 * is directly connected (gw_addr == 0),
13115 		 * or if the packet was source routed out this
13116 		 * interface.
13117 		 */
13118 		ipaddr_t src;
13119 		mblk_t	*mp1;
13120 		ire_t	*src_ire = NULL;
13121 
13122 		/*
13123 		 * Check whether ire_rfq and q are from the same ill
13124 		 * or if they are not same, they at least belong
13125 		 * to the same group. If so, send redirects.
13126 		 */
13127 		if ((ire->ire_rfq == q ||
13128 		    (ill_group != NULL && ill_group == ire_group)) &&
13129 		    (ire->ire_gateway_addr != 0) &&
13130 		    !ip_source_routed(ipha)) {
13131 
13132 			src = ipha->ipha_src;
13133 			src_ire = ire_ftable_lookup(src, 0, 0,
13134 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13135 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13136 
13137 			if (src_ire != NULL) {
13138 				/*
13139 				 * The source is directly connected.
13140 				 * Just copy the ip header (which is
13141 				 * in the first mblk)
13142 				 */
13143 				mp1 = copyb(mp);
13144 				if (mp1 != NULL) {
13145 					icmp_send_redirect(WR(q), mp1,
13146 					    ire->ire_gateway_addr);
13147 				}
13148 				ire_refrele(src_ire);
13149 			}
13150 		}
13151 	}
13152 
13153 	dev_q = ire->ire_stq->q_next;
13154 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13155 		BUMP_MIB(&ip_mib, ipInDiscards);
13156 		freemsg(mp);
13157 		ire_refrele(ire);
13158 		return;
13159 	}
13160 
13161 	ip_rput_forward(ire, ipha, mp, ill);
13162 	IRE_REFRELE(ire);
13163 	return;
13164 
13165 drop_pkt:
13166 	ire_refrele(ire);
13167 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13168 	freemsg(mp);
13169 }
13170 
13171 static boolean_t
13172 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
13173     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13174 {
13175 	queue_t		*q;
13176 	ire_t		*ire;
13177 	uint16_t	hcksumflags;
13178 
13179 	q = *qp;
13180 	ire = *irep;
13181 
13182 	/*
13183 	 * Clear the indication that this may have hardware
13184 	 * checksum as we are not using it for forwarding.
13185 	 */
13186 	hcksumflags = DB_CKSUMFLAGS(mp);
13187 	DB_CKSUMFLAGS(mp) = 0;
13188 
13189 	/*
13190 	 * Directed broadcast forwarding: if the packet came in over a
13191 	 * different interface then it is routed out over we can forward it.
13192 	 */
13193 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13194 		ire_refrele(ire);
13195 		freemsg(mp);
13196 		BUMP_MIB(&ip_mib, ipInDiscards);
13197 		return (B_TRUE);
13198 	}
13199 	/*
13200 	 * For multicast we have set dst to be INADDR_BROADCAST
13201 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13202 	 * only for broadcast packets.
13203 	 */
13204 	if (!CLASSD(ipha->ipha_dst)) {
13205 		ire_t *new_ire;
13206 		ipif_t *ipif;
13207 		/*
13208 		 * For ill groups, as the switch duplicates broadcasts
13209 		 * across all the ports, we need to filter out and
13210 		 * send up only one copy. There is one copy for every
13211 		 * broadcast address on each ill. Thus, we look for a
13212 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13213 		 * later to see whether this ill is eligible to receive
13214 		 * them or not. ill_nominate_bcast_rcv() nominates only
13215 		 * one set of IREs for receiving.
13216 		 */
13217 
13218 		ipif = ipif_get_next_ipif(NULL, ill);
13219 		if (ipif == NULL) {
13220 			ire_refrele(ire);
13221 			freemsg(mp);
13222 			BUMP_MIB(&ip_mib, ipInDiscards);
13223 			return (B_TRUE);
13224 		}
13225 		new_ire = ire_ctable_lookup(dst, 0, 0,
13226 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13227 		ipif_refrele(ipif);
13228 
13229 		if (new_ire != NULL) {
13230 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13231 				ire_refrele(ire);
13232 				ire_refrele(new_ire);
13233 				freemsg(mp);
13234 				BUMP_MIB(&ip_mib, ipInDiscards);
13235 				return (B_TRUE);
13236 			}
13237 			/*
13238 			 * In the special case of multirouted broadcast
13239 			 * packets, we unconditionally need to "gateway"
13240 			 * them to the appropriate interface here.
13241 			 * In the normal case, this cannot happen, because
13242 			 * there is no broadcast IRE tagged with the
13243 			 * RTF_MULTIRT flag.
13244 			 */
13245 			if (new_ire->ire_flags & RTF_MULTIRT) {
13246 				ire_refrele(new_ire);
13247 				if (ire->ire_rfq != NULL) {
13248 					q = ire->ire_rfq;
13249 					*qp = q;
13250 				}
13251 			} else {
13252 				ire_refrele(ire);
13253 				ire = new_ire;
13254 			}
13255 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13256 			if (!ip_g_forward_directed_bcast) {
13257 				/*
13258 				 * Free the message if
13259 				 * ip_g_forward_directed_bcast is turned
13260 				 * off for non-local broadcast.
13261 				 */
13262 				ire_refrele(ire);
13263 				freemsg(mp);
13264 				BUMP_MIB(&ip_mib, ipInDiscards);
13265 				return (B_TRUE);
13266 			}
13267 		} else {
13268 			/*
13269 			 * This CGTP packet successfully passed the
13270 			 * CGTP filter, but the related CGTP
13271 			 * broadcast IRE has not been found,
13272 			 * meaning that the redundant ipif is
13273 			 * probably down. However, if we discarded
13274 			 * this packet, its duplicate would be
13275 			 * filtered out by the CGTP filter so none
13276 			 * of them would get through. So we keep
13277 			 * going with this one.
13278 			 */
13279 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13280 			if (ire->ire_rfq != NULL) {
13281 				q = ire->ire_rfq;
13282 				*qp = q;
13283 			}
13284 		}
13285 	}
13286 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13287 		/*
13288 		 * Verify that there are not more then one
13289 		 * IRE_BROADCAST with this broadcast address which
13290 		 * has ire_stq set.
13291 		 * TODO: simplify, loop over all IRE's
13292 		 */
13293 		ire_t	*ire1;
13294 		int	num_stq = 0;
13295 		mblk_t	*mp1;
13296 
13297 		/* Find the first one with ire_stq set */
13298 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13299 		for (ire1 = ire; ire1 &&
13300 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13301 		    ire1 = ire1->ire_next)
13302 			;
13303 		if (ire1) {
13304 			ire_refrele(ire);
13305 			ire = ire1;
13306 			IRE_REFHOLD(ire);
13307 		}
13308 
13309 		/* Check if there are additional ones with stq set */
13310 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13311 			if (ire->ire_addr != ire1->ire_addr)
13312 				break;
13313 			if (ire1->ire_stq) {
13314 				num_stq++;
13315 				break;
13316 			}
13317 		}
13318 		rw_exit(&ire->ire_bucket->irb_lock);
13319 		if (num_stq == 1 && ire->ire_stq != NULL) {
13320 			ip1dbg(("ip_rput_process_broadcast: directed "
13321 			    "broadcast to 0x%x\n",
13322 			    ntohl(ire->ire_addr)));
13323 			mp1 = copymsg(mp);
13324 			if (mp1) {
13325 				switch (ipha->ipha_protocol) {
13326 				case IPPROTO_UDP:
13327 					ip_udp_input(q, mp1, ipha, ire, ill);
13328 					break;
13329 				default:
13330 					ip_proto_input(q, mp1, ipha, ire, ill);
13331 					break;
13332 				}
13333 			}
13334 			/*
13335 			 * Adjust ttl to 2 (1+1 - the forward engine
13336 			 * will decrement it by one.
13337 			 */
13338 			if (ip_csum_hdr(ipha)) {
13339 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13340 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13341 				freemsg(mp);
13342 				ire_refrele(ire);
13343 				return (B_TRUE);
13344 			}
13345 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13346 			ipha->ipha_hdr_checksum = 0;
13347 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13348 			ip_rput_process_forward(q, mp, ire, ipha,
13349 			    ill, ll_multicast);
13350 			return (B_TRUE);
13351 		}
13352 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13353 		    ntohl(ire->ire_addr)));
13354 	}
13355 
13356 	*irep = ire;
13357 
13358 	/* Restore any hardware checksum flags */
13359 	DB_CKSUMFLAGS(mp) = hcksumflags;
13360 	return (B_FALSE);
13361 }
13362 
13363 /* ARGSUSED */
13364 static boolean_t
13365 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13366     int *ll_multicast, ipaddr_t *dstp)
13367 {
13368 	/*
13369 	 * Forward packets only if we have joined the allmulti
13370 	 * group on this interface.
13371 	 */
13372 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13373 		int retval;
13374 
13375 		/*
13376 		 * Clear the indication that this may have hardware
13377 		 * checksum as we are not using it.
13378 		 */
13379 		DB_CKSUMFLAGS(mp) = 0;
13380 		retval = ip_mforward(ill, ipha, mp);
13381 		/* ip_mforward updates mib variables if needed */
13382 		/* clear b_prev - used by ip_mroute_decap */
13383 		mp->b_prev = NULL;
13384 
13385 		switch (retval) {
13386 		case 0:
13387 			/*
13388 			 * pkt is okay and arrived on phyint.
13389 			 *
13390 			 * If we are running as a multicast router
13391 			 * we need to see all IGMP and/or PIM packets.
13392 			 */
13393 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13394 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13395 				goto done;
13396 			}
13397 			break;
13398 		case -1:
13399 			/* pkt is mal-formed, toss it */
13400 			goto drop_pkt;
13401 		case 1:
13402 			/* pkt is okay and arrived on a tunnel */
13403 			/*
13404 			 * If we are running a multicast router
13405 			 *  we need to see all igmp packets.
13406 			 */
13407 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13408 				*dstp = INADDR_BROADCAST;
13409 				*ll_multicast = 1;
13410 				return (B_FALSE);
13411 			}
13412 
13413 			goto drop_pkt;
13414 		}
13415 	}
13416 
13417 	ILM_WALKER_HOLD(ill);
13418 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
13419 		/*
13420 		 * This might just be caused by the fact that
13421 		 * multiple IP Multicast addresses map to the same
13422 		 * link layer multicast - no need to increment counter!
13423 		 */
13424 		ILM_WALKER_RELE(ill);
13425 		freemsg(mp);
13426 		return (B_TRUE);
13427 	}
13428 	ILM_WALKER_RELE(ill);
13429 done:
13430 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
13431 	/*
13432 	 * This assumes the we deliver to all streams for multicast
13433 	 * and broadcast packets.
13434 	 */
13435 	*dstp = INADDR_BROADCAST;
13436 	*ll_multicast = 1;
13437 	return (B_FALSE);
13438 drop_pkt:
13439 	ip2dbg(("ip_rput: drop pkt\n"));
13440 	freemsg(mp);
13441 	return (B_TRUE);
13442 }
13443 
13444 static boolean_t
13445 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
13446     int *ll_multicast, mblk_t **mpp)
13447 {
13448 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
13449 	boolean_t must_copy = B_FALSE;
13450 	struct iocblk   *iocp;
13451 	ipha_t		*ipha;
13452 
13453 #define	rptr    ((uchar_t *)ipha)
13454 
13455 	first_mp = *first_mpp;
13456 	mp = *mpp;
13457 
13458 	ASSERT(first_mp == mp);
13459 
13460 	/*
13461 	 * if db_ref > 1 then copymsg and free original. Packet may be
13462 	 * changed and do not want other entity who has a reference to this
13463 	 * message to trip over the changes. This is a blind change because
13464 	 * trying to catch all places that might change packet is too
13465 	 * difficult (since it may be a module above this one)
13466 	 *
13467 	 * This corresponds to the non-fast path case. We walk down the full
13468 	 * chain in this case, and check the db_ref count of all the dblks,
13469 	 * and do a copymsg if required. It is possible that the db_ref counts
13470 	 * of the data blocks in the mblk chain can be different.
13471 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
13472 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
13473 	 * 'snoop' is running.
13474 	 */
13475 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
13476 		if (mp1->b_datap->db_ref > 1) {
13477 			must_copy = B_TRUE;
13478 			break;
13479 		}
13480 	}
13481 
13482 	if (must_copy) {
13483 		mp1 = copymsg(mp);
13484 		if (mp1 == NULL) {
13485 			for (mp1 = mp; mp1 != NULL;
13486 			    mp1 = mp1->b_cont) {
13487 				mp1->b_next = NULL;
13488 				mp1->b_prev = NULL;
13489 			}
13490 			freemsg(mp);
13491 			BUMP_MIB(&ip_mib, ipInDiscards);
13492 			return (B_TRUE);
13493 		}
13494 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
13495 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
13496 			/* Copy b_next - used in M_BREAK messages */
13497 			to_mp->b_next = from_mp->b_next;
13498 			from_mp->b_next = NULL;
13499 			/* Copy b_prev - used by ip_mroute_decap */
13500 			to_mp->b_prev = from_mp->b_prev;
13501 			from_mp->b_prev = NULL;
13502 		}
13503 		*first_mpp = first_mp = mp1;
13504 		freemsg(mp);
13505 		mp = mp1;
13506 		*mpp = mp1;
13507 	}
13508 
13509 	ipha = (ipha_t *)mp->b_rptr;
13510 
13511 	/*
13512 	 * previous code has a case for M_DATA.
13513 	 * We want to check how that happens.
13514 	 */
13515 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13516 	switch (first_mp->b_datap->db_type) {
13517 	case M_PROTO:
13518 	case M_PCPROTO:
13519 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13520 		    DL_UNITDATA_IND) {
13521 			/* Go handle anything other than data elsewhere. */
13522 			ip_rput_dlpi(q, mp);
13523 			return (B_TRUE);
13524 		}
13525 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13526 		/* Ditch the DLPI header. */
13527 		mp1 = mp->b_cont;
13528 		ASSERT(first_mp == mp);
13529 		*first_mpp = mp1;
13530 		freeb(mp);
13531 		*mpp = mp1;
13532 		return (B_FALSE);
13533 	case M_BREAK:
13534 		/*
13535 		 * A packet arrives as M_BREAK following a cycle through
13536 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13537 		 * This is an IP datagram sans lower level header.
13538 		 * M_BREAK are also used to pass back in multicast packets
13539 		 * that are encapsulated with a source route.
13540 		 */
13541 		/* Ditch the M_BREAK mblk */
13542 		mp1 = mp->b_cont;
13543 		ASSERT(first_mp == mp);
13544 		*first_mpp = mp1;
13545 		freeb(mp);
13546 		mp = mp1;
13547 		mp->b_next = NULL;
13548 		*mpp = mp;
13549 		*ll_multicast = 0;
13550 		return (B_FALSE);
13551 	case M_IOCACK:
13552 		ip1dbg(("got iocack "));
13553 		iocp = (struct iocblk *)mp->b_rptr;
13554 		switch (iocp->ioc_cmd) {
13555 		case DL_IOC_HDR_INFO:
13556 			ill = (ill_t *)q->q_ptr;
13557 			ill_fastpath_ack(ill, mp);
13558 			return (B_TRUE);
13559 		case SIOCSTUNPARAM:
13560 		case OSIOCSTUNPARAM:
13561 			/* Go through qwriter_ip */
13562 			break;
13563 		case SIOCGTUNPARAM:
13564 		case OSIOCGTUNPARAM:
13565 			ip_rput_other(NULL, q, mp, NULL);
13566 			return (B_TRUE);
13567 		default:
13568 			putnext(q, mp);
13569 			return (B_TRUE);
13570 		}
13571 		/* FALLTHRU */
13572 	case M_ERROR:
13573 	case M_HANGUP:
13574 		/*
13575 		 * Since this is on the ill stream we unconditionally
13576 		 * bump up the refcount
13577 		 */
13578 		ill_refhold(ill);
13579 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13580 		    B_FALSE);
13581 		return (B_TRUE);
13582 	case M_CTL:
13583 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13584 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13585 			IPHADA_M_CTL)) {
13586 			/*
13587 			 * It's an IPsec accelerated packet.
13588 			 * Make sure that the ill from which we received the
13589 			 * packet has enabled IPsec hardware acceleration.
13590 			 */
13591 			if (!(ill->ill_capabilities &
13592 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13593 				/* IPsec kstats: bean counter */
13594 				freemsg(mp);
13595 				return (B_TRUE);
13596 			}
13597 
13598 			/*
13599 			 * Make mp point to the mblk following the M_CTL,
13600 			 * then process according to type of mp.
13601 			 * After this processing, first_mp will point to
13602 			 * the data-attributes and mp to the pkt following
13603 			 * the M_CTL.
13604 			 */
13605 			mp = first_mp->b_cont;
13606 			if (mp == NULL) {
13607 				freemsg(first_mp);
13608 				return (B_TRUE);
13609 			}
13610 			/*
13611 			 * A Hardware Accelerated packet can only be M_DATA
13612 			 * ESP or AH packet.
13613 			 */
13614 			if (mp->b_datap->db_type != M_DATA) {
13615 				/* non-M_DATA IPsec accelerated packet */
13616 				IPSECHW_DEBUG(IPSECHW_PKT,
13617 				    ("non-M_DATA IPsec accelerated pkt\n"));
13618 				freemsg(first_mp);
13619 				return (B_TRUE);
13620 			}
13621 			ipha = (ipha_t *)mp->b_rptr;
13622 			if (ipha->ipha_protocol != IPPROTO_AH &&
13623 			    ipha->ipha_protocol != IPPROTO_ESP) {
13624 				IPSECHW_DEBUG(IPSECHW_PKT,
13625 				    ("non-M_DATA IPsec accelerated pkt\n"));
13626 				freemsg(first_mp);
13627 				return (B_TRUE);
13628 			}
13629 			*mpp = mp;
13630 			return (B_FALSE);
13631 		}
13632 		putnext(q, mp);
13633 		return (B_TRUE);
13634 	case M_FLUSH:
13635 		if (*mp->b_rptr & FLUSHW) {
13636 			*mp->b_rptr &= ~FLUSHR;
13637 			qreply(q, mp);
13638 			return (B_TRUE);
13639 		}
13640 		freemsg(mp);
13641 		return (B_TRUE);
13642 	case M_IOCNAK:
13643 		ip1dbg(("got iocnak "));
13644 		iocp = (struct iocblk *)mp->b_rptr;
13645 		switch (iocp->ioc_cmd) {
13646 		case DL_IOC_HDR_INFO:
13647 		case SIOCSTUNPARAM:
13648 		case OSIOCSTUNPARAM:
13649 			/*
13650 			 * Since this is on the ill stream we unconditionally
13651 			 * bump up the refcount
13652 			 */
13653 			ill_refhold(ill);
13654 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13655 			    CUR_OP, B_FALSE);
13656 			return (B_TRUE);
13657 		case SIOCGTUNPARAM:
13658 		case OSIOCGTUNPARAM:
13659 			ip_rput_other(NULL, q, mp, NULL);
13660 			return (B_TRUE);
13661 		default:
13662 			break;
13663 		}
13664 		/* FALLTHRU */
13665 	default:
13666 		putnext(q, mp);
13667 		return (B_TRUE);
13668 	}
13669 }
13670 
13671 /* Read side put procedure.  Packets coming from the wire arrive here. */
13672 void
13673 ip_rput(queue_t *q, mblk_t *mp)
13674 {
13675 	ill_t		*ill;
13676 
13677 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13678 
13679 	ill = (ill_t *)q->q_ptr;
13680 
13681 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13682 		union DL_primitives *dl;
13683 
13684 		/*
13685 		 * Things are opening or closing. Only accept DLPI control
13686 		 * messages. In the open case, the ill->ill_ipif has not yet
13687 		 * been created. In the close case, things hanging off the
13688 		 * ill could have been freed already. In either case it
13689 		 * may not be safe to proceed further.
13690 		 */
13691 
13692 		dl = (union DL_primitives *)mp->b_rptr;
13693 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13694 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13695 			/*
13696 			 * Also SIOC[GS]TUN* ioctls can come here.
13697 			 */
13698 			inet_freemsg(mp);
13699 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13700 			    "ip_input_end: q %p (%S)", q, "uninit");
13701 			return;
13702 		}
13703 	}
13704 
13705 	/*
13706 	 * if db_ref > 1 then copymsg and free original. Packet may be
13707 	 * changed and we do not want the other entity who has a reference to
13708 	 * this message to trip over the changes. This is a blind change because
13709 	 * trying to catch all places that might change the packet is too
13710 	 * difficult.
13711 	 *
13712 	 * This corresponds to the fast path case, where we have a chain of
13713 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13714 	 * in the mblk chain. There doesn't seem to be a reason why a device
13715 	 * driver would send up data with varying db_ref counts in the mblk
13716 	 * chain. In any case the Fast path is a private interface, and our
13717 	 * drivers don't do such a thing. Given the above assumption, there is
13718 	 * no need to walk down the entire mblk chain (which could have a
13719 	 * potential performance problem)
13720 	 */
13721 	if (mp->b_datap->db_ref > 1) {
13722 		mblk_t  *mp1;
13723 		boolean_t adjusted = B_FALSE;
13724 		IP_STAT(ip_db_ref);
13725 
13726 		/*
13727 		 * The IP_RECVSLLA option depends on having the link layer
13728 		 * header. First check that:
13729 		 * a> the underlying device is of type ether, since this
13730 		 * option is currently supported only over ethernet.
13731 		 * b> there is enough room to copy over the link layer header.
13732 		 *
13733 		 * Once the checks are done, adjust rptr so that the link layer
13734 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13735 		 * be returned by some non-ethernet drivers but in this case the
13736 		 * second check will fail.
13737 		 */
13738 		if (ill->ill_type == IFT_ETHER &&
13739 		    (mp->b_rptr - mp->b_datap->db_base) >=
13740 		    sizeof (struct ether_header)) {
13741 			mp->b_rptr -= sizeof (struct ether_header);
13742 			adjusted = B_TRUE;
13743 		}
13744 		mp1 = copymsg(mp);
13745 		if (mp1 == NULL) {
13746 			/* Clear b_next - used in M_BREAK messages */
13747 			mp->b_next = NULL;
13748 			/* clear b_prev - used by ip_mroute_decap */
13749 			mp->b_prev = NULL;
13750 			freemsg(mp);
13751 			BUMP_MIB(&ip_mib, ipInDiscards);
13752 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13753 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13754 			return;
13755 		}
13756 		if (adjusted) {
13757 			/*
13758 			 * Copy is done. Restore the pointer in the _new_ mblk
13759 			 */
13760 			mp1->b_rptr += sizeof (struct ether_header);
13761 		}
13762 		/* Copy b_next - used in M_BREAK messages */
13763 		mp1->b_next = mp->b_next;
13764 		mp->b_next = NULL;
13765 		/* Copy b_prev - used by ip_mroute_decap */
13766 		mp1->b_prev = mp->b_prev;
13767 		mp->b_prev = NULL;
13768 		freemsg(mp);
13769 		mp = mp1;
13770 	}
13771 
13772 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13773 	    "ip_rput_end: q %p (%S)", q, "end");
13774 
13775 	ip_input(ill, NULL, mp, 0);
13776 }
13777 
13778 /*
13779  * Direct read side procedure capable of dealing with chains. GLDv3 based
13780  * drivers call this function directly with mblk chains while STREAMS
13781  * read side procedure ip_rput() calls this for single packet with ip_ring
13782  * set to NULL to process one packet at a time.
13783  *
13784  * The ill will always be valid if this function is called directly from
13785  * the driver.
13786  */
13787 /*ARGSUSED*/
13788 void
13789 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13790 {
13791 	ipaddr_t		dst;
13792 	ire_t			*ire;
13793 	ipha_t			*ipha;
13794 	uint_t			pkt_len;
13795 	ssize_t			len;
13796 	uint_t			opt_len;
13797 	int			ll_multicast;
13798 	int			cgtp_flt_pkt;
13799 	queue_t			*q = ill->ill_rq;
13800 	squeue_t		*curr_sqp = NULL;
13801 	mblk_t 			*head = NULL;
13802 	mblk_t			*tail = NULL;
13803 	mblk_t			*first_mp;
13804 	mblk_t 			*mp;
13805 	int			cnt = 0;
13806 
13807 	ASSERT(mp_chain != NULL);
13808 	ASSERT(ill != NULL);
13809 
13810 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13811 
13812 #define	rptr	((uchar_t *)ipha)
13813 
13814 	while (mp_chain != NULL) {
13815 		first_mp = mp = mp_chain;
13816 		mp_chain = mp_chain->b_next;
13817 		mp->b_next = NULL;
13818 		ll_multicast = 0;
13819 		ire = NULL;
13820 
13821 		/*
13822 		 * ip_input fast path
13823 		 */
13824 
13825 		/* mblk type is not M_DATA */
13826 		if (mp->b_datap->db_type != M_DATA) {
13827 			if (ip_rput_process_notdata(q, &first_mp, ill,
13828 			    &ll_multicast, &mp))
13829 				continue;
13830 		}
13831 
13832 		ASSERT(mp->b_datap->db_type == M_DATA);
13833 		ASSERT(mp->b_datap->db_ref == 1);
13834 
13835 
13836 		ipha = (ipha_t *)mp->b_rptr;
13837 		len = mp->b_wptr - rptr;
13838 
13839 		BUMP_MIB(&ip_mib, ipInReceives);
13840 
13841 		/*
13842 		 * IP header ptr not aligned?
13843 		 * OR IP header not complete in first mblk
13844 		 */
13845 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13846 			if (!ip_check_and_align_header(q, mp))
13847 				continue;
13848 			ipha = (ipha_t *)mp->b_rptr;
13849 			len = mp->b_wptr - rptr;
13850 		}
13851 
13852 		/* multiple mblk or too short */
13853 		pkt_len = ntohs(ipha->ipha_length);
13854 		len -= pkt_len;
13855 		if (len != 0) {
13856 			/*
13857 			 * Make sure we have data length consistent
13858 			 * with the IP header.
13859 			 */
13860 			if (mp->b_cont == NULL) {
13861 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13862 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13863 					ip2dbg(("ip_input: drop pkt\n"));
13864 					freemsg(mp);
13865 					continue;
13866 				}
13867 				mp->b_wptr = rptr + pkt_len;
13868 			} else if (len += msgdsize(mp->b_cont)) {
13869 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13870 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13871 					ip2dbg(("ip_input: drop pkt\n"));
13872 					freemsg(mp);
13873 					continue;
13874 				}
13875 				(void) adjmsg(mp, -len);
13876 				IP_STAT(ip_multimblk3);
13877 			}
13878 		}
13879 
13880 		if (ip_loopback_src_or_dst(ipha, ill)) {
13881 			ip2dbg(("ip_input: drop pkt\n"));
13882 			freemsg(mp);
13883 			continue;
13884 		}
13885 
13886 		/*
13887 		 * Attach any necessary label information to this packet.
13888 		 */
13889 		if (is_system_labeled() &&
13890 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
13891 			BUMP_MIB(&ip_mib, ipInDiscards);
13892 			freemsg(mp);
13893 			continue;
13894 		}
13895 
13896 		opt_len = ipha->ipha_version_and_hdr_length -
13897 		    IP_SIMPLE_HDR_VERSION;
13898 		/* IP version bad or there are IP options */
13899 		if (opt_len) {
13900 			if (len != 0)
13901 				IP_STAT(ip_multimblk4);
13902 			else
13903 				IP_STAT(ip_ipoptions);
13904 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13905 				continue;
13906 		} else {
13907 			dst = ipha->ipha_dst;
13908 		}
13909 
13910 		/*
13911 		 * Invoke the CGTP (multirouting) filtering module to process
13912 		 * the incoming packet. Packets identified as duplicates
13913 		 * must be discarded. Filtering is active only if the
13914 		 * the ip_cgtp_filter ndd variable is non-zero.
13915 		 */
13916 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13917 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13918 			cgtp_flt_pkt =
13919 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
13920 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13921 				freemsg(first_mp);
13922 				continue;
13923 			}
13924 		}
13925 
13926 		/*
13927 		 * If rsvpd is running, let RSVP daemon handle its processing
13928 		 * and forwarding of RSVP multicast/unicast packets.
13929 		 * If rsvpd is not running but mrouted is running, RSVP
13930 		 * multicast packets are forwarded as multicast traffic
13931 		 * and RSVP unicast packets are forwarded by unicast router.
13932 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13933 		 * packets are not forwarded, but the unicast packets are
13934 		 * forwarded like unicast traffic.
13935 		 */
13936 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13937 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13938 			/* RSVP packet and rsvpd running. Treat as ours */
13939 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13940 			/*
13941 			 * This assumes that we deliver to all streams for
13942 			 * multicast and broadcast packets.
13943 			 * We have to force ll_multicast to 1 to handle the
13944 			 * M_DATA messages passed in from ip_mroute_decap.
13945 			 */
13946 			dst = INADDR_BROADCAST;
13947 			ll_multicast = 1;
13948 		} else if (CLASSD(dst)) {
13949 			/* packet is multicast */
13950 			mp->b_next = NULL;
13951 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13952 			    &ll_multicast, &dst))
13953 				continue;
13954 		}
13955 
13956 
13957 		/*
13958 		 * Check if the packet is coming from the Mobile IP
13959 		 * forward tunnel interface
13960 		 */
13961 		if (ill->ill_srcif_refcnt > 0) {
13962 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13963 			    NULL, ill, MATCH_IRE_TYPE);
13964 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13965 			    ire->ire_ipif->ipif_net_type ==
13966 			    IRE_IF_RESOLVER) {
13967 				/* We need to resolve the link layer info */
13968 				ire_refrele(ire);
13969 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13970 				    ll_multicast, dst);
13971 				continue;
13972 			}
13973 		}
13974 
13975 		if (ire == NULL) {
13976 			ire = ire_cache_lookup(dst, ALL_ZONES,
13977 			    MBLK_GETLABEL(mp));
13978 		}
13979 
13980 		/*
13981 		 * If mipagent is running and reverse tunnel is created as per
13982 		 * mobile node request, then any packet coming through the
13983 		 * incoming interface from the mobile-node, should be reverse
13984 		 * tunneled to it's home agent except those that are destined
13985 		 * to foreign agent only.
13986 		 * This needs source address based ire lookup. The routing
13987 		 * entries for source address based lookup are only created by
13988 		 * mipagent program only when a reverse tunnel is created.
13989 		 * Reference : RFC2002, RFC2344
13990 		 */
13991 		if (ill->ill_mrtun_refcnt > 0) {
13992 			ipaddr_t	srcaddr;
13993 			ire_t		*tmp_ire;
13994 
13995 			tmp_ire = ire;	/* Save, we might need it later */
13996 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
13997 			    ire->ire_type != IRE_BROADCAST)) {
13998 				srcaddr = ipha->ipha_src;
13999 				ire = ire_mrtun_lookup(srcaddr, ill);
14000 				if (ire != NULL) {
14001 					/*
14002 					 * Should not be getting iphada packet
14003 					 * here. we should only get those for
14004 					 * IRE_LOCAL traffic, excluded above.
14005 					 * Fail-safe (drop packet) in the event
14006 					 * hardware is misbehaving.
14007 					 */
14008 					if (first_mp != mp) {
14009 						/* IPsec KSTATS: beancount me */
14010 						freemsg(first_mp);
14011 					} else {
14012 						/*
14013 						 * This packet must be forwarded
14014 						 * to Reverse Tunnel
14015 						 */
14016 						ip_mrtun_forward(ire, ill, mp);
14017 					}
14018 					ire_refrele(ire);
14019 					if (tmp_ire != NULL)
14020 						ire_refrele(tmp_ire);
14021 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14022 					    "ip_input_end: q %p (%S)",
14023 					    q, "uninit");
14024 					continue;
14025 				}
14026 			}
14027 			/*
14028 			 * If this packet is from a non-mobilenode  or a
14029 			 * mobile-node which does not request reverse
14030 			 * tunnel service
14031 			 */
14032 			ire = tmp_ire;
14033 		}
14034 
14035 
14036 		/*
14037 		 * If we reach here that means the incoming packet satisfies
14038 		 * one of the following conditions:
14039 		 *   - packet is from a mobile node which does not request
14040 		 *	reverse tunnel
14041 		 *   - packet is from a non-mobile node, which is the most
14042 		 *	common case
14043 		 *   - packet is from a reverse tunnel enabled mobile node
14044 		 *	and destined to foreign agent only
14045 		 */
14046 
14047 		if (ire == NULL) {
14048 			/*
14049 			 * No IRE for this destination, so it can't be for us.
14050 			 * Unless we are forwarding, drop the packet.
14051 			 * We have to let source routed packets through
14052 			 * since we don't yet know if they are 'ping -l'
14053 			 * packets i.e. if they will go out over the
14054 			 * same interface as they came in on.
14055 			 */
14056 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14057 			continue;
14058 		}
14059 
14060 		/*
14061 		 * Broadcast IRE may indicate either broadcast or
14062 		 * multicast packet
14063 		 */
14064 		if (ire->ire_type == IRE_BROADCAST) {
14065 			/*
14066 			 * Skip broadcast checks if packet is UDP multicast;
14067 			 * we'd rather not enter ip_rput_process_broadcast()
14068 			 * unless the packet is broadcast for real, since
14069 			 * that routine is a no-op for multicast.
14070 			 */
14071 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
14072 			    !CLASSD(ipha->ipha_dst)) &&
14073 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
14074 			    dst, cgtp_flt_pkt, ll_multicast)) {
14075 				continue;
14076 			}
14077 		} else if (ire->ire_stq != NULL) {
14078 			/* fowarding? */
14079 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14080 			    ll_multicast);
14081 			continue;
14082 		}
14083 
14084 		/* packet not for us */
14085 		if (ire->ire_rfq != q) {
14086 			if (ip_rput_notforus(&q, mp, ire, ill)) {
14087 				continue;
14088 			}
14089 		}
14090 
14091 		switch (ipha->ipha_protocol) {
14092 		case IPPROTO_TCP:
14093 			ASSERT(first_mp == mp);
14094 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14095 				mp, 0, q, ip_ring)) != NULL) {
14096 				if (curr_sqp == NULL) {
14097 					curr_sqp = GET_SQUEUE(mp);
14098 					ASSERT(cnt == 0);
14099 					cnt++;
14100 					head = tail = mp;
14101 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14102 					ASSERT(tail != NULL);
14103 					cnt++;
14104 					tail->b_next = mp;
14105 					tail = mp;
14106 				} else {
14107 					/*
14108 					 * A different squeue. Send the
14109 					 * chain for the previous squeue on
14110 					 * its way. This shouldn't happen
14111 					 * often unless interrupt binding
14112 					 * changes.
14113 					 */
14114 					IP_STAT(ip_input_multi_squeue);
14115 					squeue_enter_chain(curr_sqp, head,
14116 					    tail, cnt, SQTAG_IP_INPUT);
14117 					curr_sqp = GET_SQUEUE(mp);
14118 					head = mp;
14119 					tail = mp;
14120 					cnt = 1;
14121 				}
14122 			}
14123 			IRE_REFRELE(ire);
14124 			continue;
14125 		case IPPROTO_UDP:
14126 			ASSERT(first_mp == mp);
14127 			ip_udp_input(q, mp, ipha, ire, ill);
14128 			IRE_REFRELE(ire);
14129 			continue;
14130 		case IPPROTO_SCTP:
14131 			ASSERT(first_mp == mp);
14132 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14133 			    q, dst);
14134 			continue;
14135 		default:
14136 			ip_proto_input(q, first_mp, ipha, ire, ill);
14137 			IRE_REFRELE(ire);
14138 			continue;
14139 		}
14140 	}
14141 
14142 	if (head != NULL)
14143 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14144 
14145 	/*
14146 	 * This code is there just to make netperf/ttcp look good.
14147 	 *
14148 	 * Its possible that after being in polling mode (and having cleared
14149 	 * the backlog), squeues have turned the interrupt frequency higher
14150 	 * to improve latency at the expense of more CPU utilization (less
14151 	 * packets per interrupts or more number of interrupts). Workloads
14152 	 * like ttcp/netperf do manage to tickle polling once in a while
14153 	 * but for the remaining time, stay in higher interrupt mode since
14154 	 * their packet arrival rate is pretty uniform and this shows up
14155 	 * as higher CPU utilization. Since people care about CPU utilization
14156 	 * while running netperf/ttcp, turn the interrupt frequency back to
14157 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14158 	 */
14159 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14160 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14161 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14162 			ip_ring->rr_blank(ip_ring->rr_handle,
14163 			    ip_ring->rr_normal_blank_time,
14164 			    ip_ring->rr_normal_pkt_cnt);
14165 		}
14166 	}
14167 
14168 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14169 	    "ip_input_end: q %p (%S)", q, "end");
14170 #undef	rptr
14171 }
14172 
14173 static void
14174 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14175     t_uscalar_t err)
14176 {
14177 	if (dl_err == DL_SYSERR) {
14178 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14179 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14180 		    ill->ill_name, dlpi_prim_str(prim), err);
14181 		return;
14182 	}
14183 
14184 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14185 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14186 	    dlpi_err_str(dl_err));
14187 }
14188 
14189 /*
14190  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14191  * than DL_UNITDATA_IND messages. If we need to process this message
14192  * exclusively, we call qwriter_ip, in which case we also need to call
14193  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14194  */
14195 void
14196 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14197 {
14198 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14199 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14200 	ill_t		*ill;
14201 
14202 	ip1dbg(("ip_rput_dlpi"));
14203 	ill = (ill_t *)q->q_ptr;
14204 	switch (dloa->dl_primitive) {
14205 	case DL_ERROR_ACK:
14206 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14207 		    "%s (0x%x), unix %u\n", ill->ill_name,
14208 		    dlpi_prim_str(dlea->dl_error_primitive),
14209 		    dlea->dl_error_primitive,
14210 		    dlpi_err_str(dlea->dl_errno),
14211 		    dlea->dl_errno,
14212 		    dlea->dl_unix_errno));
14213 		switch (dlea->dl_error_primitive) {
14214 		case DL_UNBIND_REQ:
14215 			mutex_enter(&ill->ill_lock);
14216 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14217 			cv_signal(&ill->ill_cv);
14218 			mutex_exit(&ill->ill_lock);
14219 			/* FALLTHRU */
14220 		case DL_NOTIFY_REQ:
14221 		case DL_ATTACH_REQ:
14222 		case DL_DETACH_REQ:
14223 		case DL_INFO_REQ:
14224 		case DL_BIND_REQ:
14225 		case DL_ENABMULTI_REQ:
14226 		case DL_PHYS_ADDR_REQ:
14227 		case DL_CAPABILITY_REQ:
14228 		case DL_CONTROL_REQ:
14229 			/*
14230 			 * Refhold the ill to match qwriter_ip which does a
14231 			 * refrele. Since this is on the ill stream we
14232 			 * unconditionally bump up the refcount without
14233 			 * checking for ILL_CAN_LOOKUP
14234 			 */
14235 			ill_refhold(ill);
14236 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14237 			    CUR_OP, B_FALSE);
14238 			return;
14239 		case DL_DISABMULTI_REQ:
14240 			freemsg(mp);	/* Don't want to pass this up */
14241 			return;
14242 		default:
14243 			break;
14244 		}
14245 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14246 		    dlea->dl_errno, dlea->dl_unix_errno);
14247 		freemsg(mp);
14248 		return;
14249 	case DL_INFO_ACK:
14250 	case DL_BIND_ACK:
14251 	case DL_PHYS_ADDR_ACK:
14252 	case DL_NOTIFY_ACK:
14253 	case DL_CAPABILITY_ACK:
14254 	case DL_CONTROL_ACK:
14255 		/*
14256 		 * Refhold the ill to match qwriter_ip which does a refrele
14257 		 * Since this is on the ill stream we unconditionally
14258 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14259 		 */
14260 		ill_refhold(ill);
14261 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14262 		    CUR_OP, B_FALSE);
14263 		return;
14264 	case DL_NOTIFY_IND:
14265 		ill_refhold(ill);
14266 		/*
14267 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14268 		 * relation to the current ioctl in progress (if any). Hence we
14269 		 * pass in NEW_OP in this case.
14270 		 */
14271 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14272 		    NEW_OP, B_FALSE);
14273 		return;
14274 	case DL_OK_ACK:
14275 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14276 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14277 		switch (dloa->dl_correct_primitive) {
14278 		case DL_UNBIND_REQ:
14279 			mutex_enter(&ill->ill_lock);
14280 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14281 			cv_signal(&ill->ill_cv);
14282 			mutex_exit(&ill->ill_lock);
14283 			/* FALLTHRU */
14284 		case DL_ATTACH_REQ:
14285 		case DL_DETACH_REQ:
14286 			/*
14287 			 * Refhold the ill to match qwriter_ip which does a
14288 			 * refrele. Since this is on the ill stream we
14289 			 * unconditionally bump up the refcount
14290 			 */
14291 			ill_refhold(ill);
14292 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14293 			    CUR_OP, B_FALSE);
14294 			return;
14295 		case DL_ENABMULTI_REQ:
14296 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14297 				ill->ill_dlpi_multicast_state = IDMS_OK;
14298 			break;
14299 
14300 		}
14301 		break;
14302 	default:
14303 		break;
14304 	}
14305 	freemsg(mp);
14306 }
14307 
14308 /*
14309  * Handling of DLPI messages that require exclusive access to the ipsq.
14310  *
14311  * Need to do ill_pending_mp_release on ioctl completion, which could
14312  * happen here. (along with mi_copy_done)
14313  */
14314 /* ARGSUSED */
14315 static void
14316 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14317 {
14318 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14319 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14320 	int		err = 0;
14321 	ill_t		*ill;
14322 	ipif_t		*ipif = NULL;
14323 	mblk_t		*mp1 = NULL;
14324 	conn_t		*connp = NULL;
14325 	t_uscalar_t	physaddr_req;
14326 	mblk_t		*mp_hw;
14327 	union DL_primitives *dlp;
14328 	boolean_t	success;
14329 	boolean_t	ioctl_aborted = B_FALSE;
14330 	boolean_t	log = B_TRUE;
14331 
14332 	ip1dbg(("ip_rput_dlpi_writer .."));
14333 	ill = (ill_t *)q->q_ptr;
14334 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14335 
14336 	ASSERT(IAM_WRITER_ILL(ill));
14337 
14338 	/*
14339 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14340 	 * both are null or non-null. However we can assert that only
14341 	 * after grabbing the ipsq_lock. So we don't make any assertion
14342 	 * here and in other places in the code.
14343 	 */
14344 	ipif = ipsq->ipsq_pending_ipif;
14345 	/*
14346 	 * The current ioctl could have been aborted by the user and a new
14347 	 * ioctl to bring up another ill could have started. We could still
14348 	 * get a response from the driver later.
14349 	 */
14350 	if (ipif != NULL && ipif->ipif_ill != ill)
14351 		ioctl_aborted = B_TRUE;
14352 
14353 	switch (dloa->dl_primitive) {
14354 	case DL_ERROR_ACK:
14355 		switch (dlea->dl_error_primitive) {
14356 		case DL_UNBIND_REQ:
14357 		case DL_ATTACH_REQ:
14358 		case DL_DETACH_REQ:
14359 		case DL_INFO_REQ:
14360 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14361 			break;
14362 		case DL_NOTIFY_REQ:
14363 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
14364 			log = B_FALSE;
14365 			break;
14366 		case DL_PHYS_ADDR_REQ:
14367 			/*
14368 			 * For IPv6 only, there are two additional
14369 			 * phys_addr_req's sent to the driver to get the
14370 			 * IPv6 token and lla. This allows IP to acquire
14371 			 * the hardware address format for a given interface
14372 			 * without having built in knowledge of the hardware
14373 			 * address. ill_phys_addr_pend keeps track of the last
14374 			 * DL_PAR sent so we know which response we are
14375 			 * dealing with. ill_dlpi_done will update
14376 			 * ill_phys_addr_pend when it sends the next req.
14377 			 * We don't complete the IOCTL until all three DL_PARs
14378 			 * have been attempted, so set *_len to 0 and break.
14379 			 */
14380 			physaddr_req = ill->ill_phys_addr_pend;
14381 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14382 			if (physaddr_req == DL_IPV6_TOKEN) {
14383 				ill->ill_token_length = 0;
14384 				log = B_FALSE;
14385 				break;
14386 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14387 				ill->ill_nd_lla_len = 0;
14388 				log = B_FALSE;
14389 				break;
14390 			}
14391 			/*
14392 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
14393 			 * We presumably have an IOCTL hanging out waiting
14394 			 * for completion. Find it and complete the IOCTL
14395 			 * with the error noted.
14396 			 * However, ill_dl_phys was called on an ill queue
14397 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
14398 			 * set. But the ioctl is known to be pending on ill_wq.
14399 			 */
14400 			if (!ill->ill_ifname_pending)
14401 				break;
14402 			ill->ill_ifname_pending = 0;
14403 			if (!ioctl_aborted)
14404 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14405 			if (mp1 != NULL) {
14406 				/*
14407 				 * This operation (SIOCSLIFNAME) must have
14408 				 * happened on the ill. Assert there is no conn
14409 				 */
14410 				ASSERT(connp == NULL);
14411 				q = ill->ill_wq;
14412 			}
14413 			break;
14414 		case DL_BIND_REQ:
14415 			ill_dlpi_done(ill, DL_BIND_REQ);
14416 			if (ill->ill_ifname_pending)
14417 				break;
14418 			/*
14419 			 * Something went wrong with the bind.  We presumably
14420 			 * have an IOCTL hanging out waiting for completion.
14421 			 * Find it, take down the interface that was coming
14422 			 * up, and complete the IOCTL with the error noted.
14423 			 */
14424 			if (!ioctl_aborted)
14425 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14426 			if (mp1 != NULL) {
14427 				/*
14428 				 * This operation (SIOCSLIFFLAGS) must have
14429 				 * happened from a conn.
14430 				 */
14431 				ASSERT(connp != NULL);
14432 				q = CONNP_TO_WQ(connp);
14433 				if (ill->ill_move_in_progress) {
14434 					ILL_CLEAR_MOVE(ill);
14435 				}
14436 				(void) ipif_down(ipif, NULL, NULL);
14437 				/* error is set below the switch */
14438 			}
14439 			break;
14440 		case DL_ENABMULTI_REQ:
14441 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
14442 
14443 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14444 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
14445 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
14446 				ipif_t *ipif;
14447 
14448 				log = B_FALSE;
14449 				printf("ip: joining multicasts failed (%d)"
14450 				    " on %s - will use link layer "
14451 				    "broadcasts for multicast\n",
14452 				    dlea->dl_errno, ill->ill_name);
14453 
14454 				/*
14455 				 * Set up the multicast mapping alone.
14456 				 * writer, so ok to access ill->ill_ipif
14457 				 * without any lock.
14458 				 */
14459 				ipif = ill->ill_ipif;
14460 				mutex_enter(&ill->ill_phyint->phyint_lock);
14461 				ill->ill_phyint->phyint_flags |=
14462 				    PHYI_MULTI_BCAST;
14463 				mutex_exit(&ill->ill_phyint->phyint_lock);
14464 
14465 				if (!ill->ill_isv6) {
14466 					(void) ipif_arp_setup_multicast(ipif,
14467 					    NULL);
14468 				} else {
14469 					(void) ipif_ndp_setup_multicast(ipif,
14470 					    NULL);
14471 				}
14472 			}
14473 			freemsg(mp);	/* Don't want to pass this up */
14474 			return;
14475 		case DL_CAPABILITY_REQ:
14476 		case DL_CONTROL_REQ:
14477 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
14478 			    "DL_CAPABILITY/CONTROL REQ\n"));
14479 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14480 			ill->ill_capab_state = IDMS_FAILED;
14481 			freemsg(mp);
14482 			return;
14483 		}
14484 		/*
14485 		 * Note the error for IOCTL completion (mp1 is set when
14486 		 * ready to complete ioctl). If ill_ifname_pending_err is
14487 		 * set, an error occured during plumbing (ill_ifname_pending),
14488 		 * so we want to report that error.
14489 		 *
14490 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
14491 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
14492 		 * expected to get errack'd if the driver doesn't support
14493 		 * these flags (e.g. ethernet). log will be set to B_FALSE
14494 		 * if these error conditions are encountered.
14495 		 */
14496 		if (mp1 != NULL) {
14497 			if (ill->ill_ifname_pending_err != 0)  {
14498 				err = ill->ill_ifname_pending_err;
14499 				ill->ill_ifname_pending_err = 0;
14500 			} else {
14501 				err = dlea->dl_unix_errno ?
14502 				    dlea->dl_unix_errno : ENXIO;
14503 			}
14504 		/*
14505 		 * If we're plumbing an interface and an error hasn't already
14506 		 * been saved, set ill_ifname_pending_err to the error passed
14507 		 * up. Ignore the error if log is B_FALSE (see comment above).
14508 		 */
14509 		} else if (log && ill->ill_ifname_pending &&
14510 		    ill->ill_ifname_pending_err == 0) {
14511 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
14512 			dlea->dl_unix_errno : ENXIO;
14513 		}
14514 
14515 		if (log)
14516 			ip_dlpi_error(ill, dlea->dl_error_primitive,
14517 			    dlea->dl_errno, dlea->dl_unix_errno);
14518 		break;
14519 	case DL_CAPABILITY_ACK: {
14520 		boolean_t reneg_flag = B_FALSE;
14521 		/* Call a routine to handle this one. */
14522 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
14523 		/*
14524 		 * Check if the ACK is due to renegotiation case since we
14525 		 * will need to send a new CAPABILITY_REQ later.
14526 		 */
14527 		if (ill->ill_capab_state == IDMS_RENEG) {
14528 			/* This is the ack for a renogiation case */
14529 			reneg_flag = B_TRUE;
14530 			ill->ill_capab_state = IDMS_UNKNOWN;
14531 		}
14532 		ill_capability_ack(ill, mp);
14533 		if (reneg_flag)
14534 			ill_capability_probe(ill);
14535 		break;
14536 	}
14537 	case DL_CONTROL_ACK:
14538 		/* We treat all of these as "fire and forget" */
14539 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14540 		break;
14541 	case DL_INFO_ACK:
14542 		/* Call a routine to handle this one. */
14543 		ill_dlpi_done(ill, DL_INFO_REQ);
14544 		ip_ll_subnet_defaults(ill, mp);
14545 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14546 		return;
14547 	case DL_BIND_ACK:
14548 		/*
14549 		 * We should have an IOCTL waiting on this unless
14550 		 * sent by ill_dl_phys, in which case just return
14551 		 */
14552 		ill_dlpi_done(ill, DL_BIND_REQ);
14553 		if (ill->ill_ifname_pending)
14554 			break;
14555 
14556 		if (!ioctl_aborted)
14557 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14558 		if (mp1 == NULL)
14559 			break;
14560 		ASSERT(connp != NULL);
14561 		q = CONNP_TO_WQ(connp);
14562 
14563 		/*
14564 		 * We are exclusive. So nothing can change even after
14565 		 * we get the pending mp. If need be we can put it back
14566 		 * and restart, as in calling ipif_arp_up()  below.
14567 		 */
14568 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14569 
14570 		mutex_enter(&ill->ill_lock);
14571 		ill->ill_dl_up = 1;
14572 		mutex_exit(&ill->ill_lock);
14573 
14574 		/*
14575 		 * Now bring up the resolver, when that is
14576 		 * done we'll create IREs and we are done.
14577 		 */
14578 		if (ill->ill_isv6) {
14579 			/*
14580 			 * v6 interfaces.
14581 			 * Unlike ARP which has to do another bind
14582 			 * and attach, once we get here we are
14583 			 * done withh NDP. Except in the case of
14584 			 * ILLF_XRESOLV, in which case we send an
14585 			 * AR_INTERFACE_UP to the external resolver.
14586 			 * If all goes well, the ioctl will complete
14587 			 * in ip_rput(). If there's an error, we
14588 			 * complete it here.
14589 			 */
14590 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14591 			    B_FALSE);
14592 			if (err == 0) {
14593 				if (ill->ill_flags & ILLF_XRESOLV) {
14594 					mutex_enter(&connp->conn_lock);
14595 					mutex_enter(&ill->ill_lock);
14596 					success = ipsq_pending_mp_add(
14597 					    connp, ipif, q, mp1, 0);
14598 					mutex_exit(&ill->ill_lock);
14599 					mutex_exit(&connp->conn_lock);
14600 					if (success) {
14601 						err = ipif_resolver_up(ipif,
14602 						    B_FALSE);
14603 						if (err == EINPROGRESS) {
14604 							freemsg(mp);
14605 							return;
14606 						}
14607 						ASSERT(err != 0);
14608 						mp1 = ipsq_pending_mp_get(ipsq,
14609 						    &connp);
14610 						ASSERT(mp1 != NULL);
14611 					} else {
14612 						/* conn has started closing */
14613 						err = EINTR;
14614 					}
14615 				} else { /* Non XRESOLV interface */
14616 					err = ipif_up_done_v6(ipif);
14617 				}
14618 			}
14619 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14620 			/*
14621 			 * ARP and other v4 external resolvers.
14622 			 * Leave the pending mblk intact so that
14623 			 * the ioctl completes in ip_rput().
14624 			 */
14625 			mutex_enter(&connp->conn_lock);
14626 			mutex_enter(&ill->ill_lock);
14627 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14628 			mutex_exit(&ill->ill_lock);
14629 			mutex_exit(&connp->conn_lock);
14630 			if (success) {
14631 				err = ipif_resolver_up(ipif, B_FALSE);
14632 				if (err == EINPROGRESS) {
14633 					freemsg(mp);
14634 					return;
14635 				}
14636 				ASSERT(err != 0);
14637 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14638 			} else {
14639 				/* The conn has started closing */
14640 				err = EINTR;
14641 			}
14642 		} else {
14643 			/*
14644 			 * This one is complete. Reply to pending ioctl.
14645 			 */
14646 			err = ipif_up_done(ipif);
14647 		}
14648 
14649 		if ((err == 0) && (ill->ill_up_ipifs)) {
14650 			err = ill_up_ipifs(ill, q, mp1);
14651 			if (err == EINPROGRESS) {
14652 				freemsg(mp);
14653 				return;
14654 			}
14655 		}
14656 
14657 		if (ill->ill_up_ipifs) {
14658 			ill_group_cleanup(ill);
14659 		}
14660 
14661 		break;
14662 	case DL_NOTIFY_IND: {
14663 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14664 		ire_t *ire;
14665 		boolean_t need_ire_walk_v4 = B_FALSE;
14666 		boolean_t need_ire_walk_v6 = B_FALSE;
14667 
14668 		/*
14669 		 * Change the address everywhere we need to.
14670 		 * What we're getting here is a link-level addr or phys addr.
14671 		 * The new addr is at notify + notify->dl_addr_offset
14672 		 * The address length is notify->dl_addr_length;
14673 		 */
14674 		switch (notify->dl_notification) {
14675 		case DL_NOTE_PHYS_ADDR:
14676 			mp_hw = copyb(mp);
14677 			if (mp_hw == NULL) {
14678 				err = ENOMEM;
14679 				break;
14680 			}
14681 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14682 			/*
14683 			 * We currently don't support changing
14684 			 * the token via DL_NOTIFY_IND.
14685 			 * When we do support it, we have to consider
14686 			 * what the implications are with respect to
14687 			 * the token and the link local address.
14688 			 */
14689 			mutex_enter(&ill->ill_lock);
14690 			if (dlp->notify_ind.dl_data ==
14691 			    DL_IPV6_LINK_LAYER_ADDR) {
14692 				if (ill->ill_nd_lla_mp != NULL)
14693 					freemsg(ill->ill_nd_lla_mp);
14694 				ill->ill_nd_lla_mp = mp_hw;
14695 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14696 				    dlp->notify_ind.dl_addr_offset;
14697 				ill->ill_nd_lla_len =
14698 				    dlp->notify_ind.dl_addr_length -
14699 				    ABS(ill->ill_sap_length);
14700 				mutex_exit(&ill->ill_lock);
14701 				break;
14702 			} else if (dlp->notify_ind.dl_data ==
14703 			    DL_CURR_PHYS_ADDR) {
14704 				if (ill->ill_phys_addr_mp != NULL)
14705 					freemsg(ill->ill_phys_addr_mp);
14706 				ill->ill_phys_addr_mp = mp_hw;
14707 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14708 				    dlp->notify_ind.dl_addr_offset;
14709 				ill->ill_phys_addr_length =
14710 				    dlp->notify_ind.dl_addr_length -
14711 				    ABS(ill->ill_sap_length);
14712 				if (ill->ill_isv6 &&
14713 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14714 					if (ill->ill_nd_lla_mp != NULL)
14715 						freemsg(ill->ill_nd_lla_mp);
14716 					ill->ill_nd_lla_mp = copyb(mp_hw);
14717 					ill->ill_nd_lla = (uchar_t *)
14718 					    ill->ill_nd_lla_mp->b_rptr +
14719 					    dlp->notify_ind.dl_addr_offset;
14720 					ill->ill_nd_lla_len =
14721 					    ill->ill_phys_addr_length;
14722 				}
14723 			}
14724 			mutex_exit(&ill->ill_lock);
14725 			/*
14726 			 * Send out gratuitous arp request for our new
14727 			 * hardware address.
14728 			 */
14729 			for (ipif = ill->ill_ipif; ipif != NULL;
14730 			    ipif = ipif->ipif_next) {
14731 				if (!(ipif->ipif_flags & IPIF_UP))
14732 					continue;
14733 				if (ill->ill_isv6) {
14734 					ipif_ndp_down(ipif);
14735 					/*
14736 					 * Set B_TRUE to enable
14737 					 * ipif_ndp_up() to send out
14738 					 * unsolicited advertisements.
14739 					 */
14740 					err = ipif_ndp_up(ipif,
14741 					    &ipif->ipif_v6lcl_addr,
14742 					    B_TRUE);
14743 					if (err) {
14744 						ip1dbg((
14745 						    "ip_rput_dlpi_writer: "
14746 						    "Failed to update ndp "
14747 						    "err %d\n", err));
14748 					}
14749 				} else {
14750 					/*
14751 					 * IPv4 ARP case
14752 					 *
14753 					 * Set B_TRUE, as we only want
14754 					 * ipif_resolver_up to send an
14755 					 * AR_ENTRY_ADD request up to
14756 					 * ARP.
14757 					 */
14758 					err = ipif_resolver_up(ipif,
14759 					    B_TRUE);
14760 					if (err) {
14761 						ip1dbg((
14762 						    "ip_rput_dlpi_writer: "
14763 						    "Failed to update arp "
14764 						    "err %d\n", err));
14765 					}
14766 				}
14767 			}
14768 			/*
14769 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14770 			 * case so that all old fastpath information can be
14771 			 * purged from IRE caches.
14772 			 */
14773 		/* FALLTHRU */
14774 		case DL_NOTE_FASTPATH_FLUSH:
14775 			/*
14776 			 * Any fastpath probe sent henceforth will get the
14777 			 * new fp mp. So we first delete any ires that are
14778 			 * waiting for the fastpath. Then walk all ires and
14779 			 * delete the ire or delete the fp mp. In the case of
14780 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14781 			 * recreate the ire's without going through a complex
14782 			 * ipif up/down dance. So we don't delete the ire
14783 			 * itself, but just the ire_fp_mp for these 2 ire's
14784 			 * In the case of the other ire's we delete the ire's
14785 			 * themselves. Access to ire_fp_mp is completely
14786 			 * protected by ire_lock for IRE_MIPRTUN and
14787 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14788 			 * other cases for performance.
14789 			 */
14790 			if (ill->ill_isv6) {
14791 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14792 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14793 				    NULL);
14794 			} else {
14795 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14796 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14797 				    IRE_CACHE | IRE_BROADCAST,
14798 				    ire_fastpath_flush, NULL, ill);
14799 				mutex_enter(&ire_mrtun_lock);
14800 				if (ire_mrtun_count != 0) {
14801 					mutex_exit(&ire_mrtun_lock);
14802 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14803 					    IRE_MIPRTUN, ire_fastpath_flush,
14804 					    NULL, ill);
14805 				} else {
14806 					mutex_exit(&ire_mrtun_lock);
14807 				}
14808 			}
14809 			break;
14810 		case DL_NOTE_SDU_SIZE:
14811 			/*
14812 			 * Change the MTU size of the interface, of all
14813 			 * attached ipif's, and of all relevant ire's.  The
14814 			 * new value's a uint32_t at notify->dl_data.
14815 			 * Mtu change Vs. new ire creation - protocol below.
14816 			 *
14817 			 * a Mark the ipif as IPIF_CHANGING.
14818 			 * b Set the new mtu in the ipif.
14819 			 * c Change the ire_max_frag on all affected ires
14820 			 * d Unmark the IPIF_CHANGING
14821 			 *
14822 			 * To see how the protocol works, assume an interface
14823 			 * route is also being added simultaneously by
14824 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14825 			 * the ire. If the ire is created before step a,
14826 			 * it will be cleaned up by step c. If the ire is
14827 			 * created after step d, it will see the new value of
14828 			 * ipif_mtu. Any attempt to create the ire between
14829 			 * steps a to d will fail because of the IPIF_CHANGING
14830 			 * flag. Note that ire_create() is passed a pointer to
14831 			 * the ipif_mtu, and not the value. During ire_add
14832 			 * under the bucket lock, the ire_max_frag of the
14833 			 * new ire being created is set from the ipif/ire from
14834 			 * which it is being derived.
14835 			 */
14836 			mutex_enter(&ill->ill_lock);
14837 			ill->ill_max_frag = (uint_t)notify->dl_data;
14838 
14839 			/*
14840 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14841 			 * leave it alone
14842 			 */
14843 			if (ill->ill_mtu_userspecified) {
14844 				mutex_exit(&ill->ill_lock);
14845 				break;
14846 			}
14847 			ill->ill_max_mtu = ill->ill_max_frag;
14848 			if (ill->ill_isv6) {
14849 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14850 					ill->ill_max_mtu = IPV6_MIN_MTU;
14851 			} else {
14852 				if (ill->ill_max_mtu < IP_MIN_MTU)
14853 					ill->ill_max_mtu = IP_MIN_MTU;
14854 			}
14855 			for (ipif = ill->ill_ipif; ipif != NULL;
14856 			    ipif = ipif->ipif_next) {
14857 				/*
14858 				 * Don't override the mtu if the user
14859 				 * has explicitly set it.
14860 				 */
14861 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14862 					continue;
14863 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14864 				if (ipif->ipif_isv6)
14865 					ire = ipif_to_ire_v6(ipif);
14866 				else
14867 					ire = ipif_to_ire(ipif);
14868 				if (ire != NULL) {
14869 					ire->ire_max_frag = ipif->ipif_mtu;
14870 					ire_refrele(ire);
14871 				}
14872 				if (ipif->ipif_flags & IPIF_UP) {
14873 					if (ill->ill_isv6)
14874 						need_ire_walk_v6 = B_TRUE;
14875 					else
14876 						need_ire_walk_v4 = B_TRUE;
14877 				}
14878 			}
14879 			mutex_exit(&ill->ill_lock);
14880 			if (need_ire_walk_v4)
14881 				ire_walk_v4(ill_mtu_change, (char *)ill,
14882 				    ALL_ZONES);
14883 			if (need_ire_walk_v6)
14884 				ire_walk_v6(ill_mtu_change, (char *)ill,
14885 				    ALL_ZONES);
14886 			break;
14887 		case DL_NOTE_LINK_UP:
14888 		case DL_NOTE_LINK_DOWN: {
14889 			/*
14890 			 * We are writer. ill / phyint / ipsq assocs stable.
14891 			 * The RUNNING flag reflects the state of the link.
14892 			 */
14893 			phyint_t *phyint = ill->ill_phyint;
14894 			uint64_t new_phyint_flags;
14895 			boolean_t changed = B_FALSE;
14896 
14897 			mutex_enter(&phyint->phyint_lock);
14898 			new_phyint_flags =
14899 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14900 			    phyint->phyint_flags | PHYI_RUNNING :
14901 			    phyint->phyint_flags & ~PHYI_RUNNING;
14902 			if (new_phyint_flags != phyint->phyint_flags) {
14903 				phyint->phyint_flags = new_phyint_flags;
14904 				changed = B_TRUE;
14905 			}
14906 			mutex_exit(&phyint->phyint_lock);
14907 			/*
14908 			 * If the flags have changed, send a message to
14909 			 * the routing socket.
14910 			 */
14911 			if (changed) {
14912 				if (phyint->phyint_illv4 != NULL) {
14913 					ip_rts_ifmsg(
14914 					    phyint->phyint_illv4->ill_ipif);
14915 				}
14916 				if (phyint->phyint_illv6 != NULL) {
14917 					ip_rts_ifmsg(
14918 					    phyint->phyint_illv6->ill_ipif);
14919 				}
14920 			}
14921 			break;
14922 		}
14923 		case DL_NOTE_PROMISC_ON_PHYS:
14924 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14925 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14926 			mutex_enter(&ill->ill_lock);
14927 			ill->ill_promisc_on_phys = B_TRUE;
14928 			mutex_exit(&ill->ill_lock);
14929 			break;
14930 		case DL_NOTE_PROMISC_OFF_PHYS:
14931 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14932 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14933 			mutex_enter(&ill->ill_lock);
14934 			ill->ill_promisc_on_phys = B_FALSE;
14935 			mutex_exit(&ill->ill_lock);
14936 			break;
14937 		case DL_NOTE_CAPAB_RENEG:
14938 			/*
14939 			 * Something changed on the driver side.
14940 			 * It wants us to renegotiate the capabilities
14941 			 * on this ill. The most likely cause is the
14942 			 * aggregation interface under us where a
14943 			 * port got added or went away.
14944 			 *
14945 			 * We reset the capabilities and set the
14946 			 * state to IDMS_RENG so that when the ack
14947 			 * comes back, we can start the
14948 			 * renegotiation process.
14949 			 */
14950 			ill_capability_reset(ill);
14951 			ill->ill_capab_state = IDMS_RENEG;
14952 			break;
14953 		default:
14954 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14955 			    "type 0x%x for DL_NOTIFY_IND\n",
14956 			    notify->dl_notification));
14957 			break;
14958 		}
14959 
14960 		/*
14961 		 * As this is an asynchronous operation, we
14962 		 * should not call ill_dlpi_done
14963 		 */
14964 		break;
14965 	}
14966 	case DL_NOTIFY_ACK:
14967 		/*
14968 		 * Don't really need to check for what notifications
14969 		 * are supported; we'll process what gets sent upstream,
14970 		 * and we know it'll be something we support changing
14971 		 * based on our DL_NOTIFY_REQ.
14972 		 */
14973 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14974 		break;
14975 	case DL_PHYS_ADDR_ACK: {
14976 		/*
14977 		 * We should have an IOCTL waiting on this when request
14978 		 * sent by ill_dl_phys.
14979 		 * However, ill_dl_phys was called on an ill queue (from
14980 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14981 		 * ioctl is known to be pending on ill_wq.
14982 		 * There are two additional phys_addr_req's sent to the
14983 		 * driver to get the token and lla. ill_phys_addr_pend
14984 		 * keeps track of the last one sent so we know which
14985 		 * response we are dealing with. ill_dlpi_done will
14986 		 * update ill_phys_addr_pend when it sends the next req.
14987 		 * We don't complete the IOCTL until all three DL_PARs
14988 		 * have been attempted.
14989 		 *
14990 		 * We don't need any lock to update ill_nd_lla* fields,
14991 		 * since the ill is not yet up, We grab the lock just
14992 		 * for uniformity with other code that accesses ill_nd_lla.
14993 		 */
14994 		physaddr_req = ill->ill_phys_addr_pend;
14995 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14996 		if (physaddr_req == DL_IPV6_TOKEN ||
14997 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14998 			if (physaddr_req == DL_IPV6_TOKEN) {
14999 				/*
15000 				 * bcopy to low-order bits of ill_token
15001 				 *
15002 				 * XXX Temporary hack - currently,
15003 				 * all known tokens are 64 bits,
15004 				 * so I'll cheat for the moment.
15005 				 */
15006 				dlp = (union DL_primitives *)mp->b_rptr;
15007 
15008 				mutex_enter(&ill->ill_lock);
15009 				bcopy((uchar_t *)(mp->b_rptr +
15010 				dlp->physaddr_ack.dl_addr_offset),
15011 				(void *)&ill->ill_token.s6_addr32[2],
15012 				dlp->physaddr_ack.dl_addr_length);
15013 				ill->ill_token_length =
15014 					dlp->physaddr_ack.dl_addr_length;
15015 				mutex_exit(&ill->ill_lock);
15016 			} else {
15017 				ASSERT(ill->ill_nd_lla_mp == NULL);
15018 				mp_hw = copyb(mp);
15019 				if (mp_hw == NULL) {
15020 					err = ENOMEM;
15021 					break;
15022 				}
15023 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15024 				mutex_enter(&ill->ill_lock);
15025 				ill->ill_nd_lla_mp = mp_hw;
15026 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15027 				dlp->physaddr_ack.dl_addr_offset;
15028 				ill->ill_nd_lla_len =
15029 					dlp->physaddr_ack.dl_addr_length;
15030 				mutex_exit(&ill->ill_lock);
15031 			}
15032 			break;
15033 		}
15034 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15035 		ASSERT(ill->ill_phys_addr_mp == NULL);
15036 		if (!ill->ill_ifname_pending)
15037 			break;
15038 		ill->ill_ifname_pending = 0;
15039 		if (!ioctl_aborted)
15040 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15041 		if (mp1 != NULL) {
15042 			ASSERT(connp == NULL);
15043 			q = ill->ill_wq;
15044 		}
15045 		/*
15046 		 * If any error acks received during the plumbing sequence,
15047 		 * ill_ifname_pending_err will be set. Break out and send up
15048 		 * the error to the pending ioctl.
15049 		 */
15050 		if (ill->ill_ifname_pending_err != 0) {
15051 			err = ill->ill_ifname_pending_err;
15052 			ill->ill_ifname_pending_err = 0;
15053 			break;
15054 		}
15055 		/*
15056 		 * Get the interface token.  If the zeroth interface
15057 		 * address is zero then set the address to the link local
15058 		 * address
15059 		 */
15060 		mp_hw = copyb(mp);
15061 		if (mp_hw == NULL) {
15062 			err = ENOMEM;
15063 			break;
15064 		}
15065 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15066 		ill->ill_phys_addr_mp = mp_hw;
15067 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15068 				dlp->physaddr_ack.dl_addr_offset;
15069 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15070 		    ill->ill_phys_addr_length == 0 ||
15071 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15072 			/*
15073 			 * Compatibility: atun driver returns a length of 0.
15074 			 * ipdptp has an ill_phys_addr_length of zero(from
15075 			 * DL_BIND_ACK) but a non-zero length here.
15076 			 * ipd has an ill_phys_addr_length of 4(from
15077 			 * DL_BIND_ACK) but a non-zero length here.
15078 			 */
15079 			ill->ill_phys_addr = NULL;
15080 		} else if (dlp->physaddr_ack.dl_addr_length !=
15081 		    ill->ill_phys_addr_length) {
15082 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15083 			    "Address length mismatch %d %d\n",
15084 			    dlp->physaddr_ack.dl_addr_length,
15085 			    ill->ill_phys_addr_length));
15086 			err = EINVAL;
15087 			break;
15088 		}
15089 		mutex_enter(&ill->ill_lock);
15090 		if (ill->ill_nd_lla_mp == NULL) {
15091 			ill->ill_nd_lla_mp = copyb(mp_hw);
15092 			if (ill->ill_nd_lla_mp == NULL) {
15093 				err = ENOMEM;
15094 				mutex_exit(&ill->ill_lock);
15095 				break;
15096 			}
15097 			ill->ill_nd_lla =
15098 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15099 			    dlp->physaddr_ack.dl_addr_offset;
15100 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15101 		}
15102 		mutex_exit(&ill->ill_lock);
15103 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15104 			(void) ill_setdefaulttoken(ill);
15105 
15106 		/*
15107 		 * If the ill zero interface has a zero address assign
15108 		 * it the proper link local address.
15109 		 */
15110 		ASSERT(ill->ill_ipif->ipif_id == 0);
15111 		if (ipif != NULL &&
15112 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15113 			(void) ipif_setlinklocal(ipif);
15114 		break;
15115 	}
15116 	case DL_OK_ACK:
15117 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15118 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15119 		    dloa->dl_correct_primitive));
15120 		switch (dloa->dl_correct_primitive) {
15121 		case DL_UNBIND_REQ:
15122 		case DL_ATTACH_REQ:
15123 		case DL_DETACH_REQ:
15124 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15125 			break;
15126 		}
15127 		break;
15128 	default:
15129 		break;
15130 	}
15131 
15132 	freemsg(mp);
15133 	if (mp1) {
15134 		struct iocblk *iocp;
15135 		int mode;
15136 
15137 		/*
15138 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15139 		 * SIOCSLIFNAME do a copyout.
15140 		 */
15141 		iocp = (struct iocblk *)mp1->b_rptr;
15142 
15143 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15144 		    iocp->ioc_cmd == SIOCSLIFNAME)
15145 			mode = COPYOUT;
15146 		else
15147 			mode = NO_COPYOUT;
15148 		/*
15149 		 * The ioctl must complete now without EINPROGRESS
15150 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15151 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15152 		 * stuck for ever in the ipsq.
15153 		 */
15154 		ASSERT(err != EINPROGRESS);
15155 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15156 
15157 	}
15158 }
15159 
15160 /*
15161  * ip_rput_other is called by ip_rput to handle messages modifying the global
15162  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15163  */
15164 /* ARGSUSED */
15165 void
15166 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15167 {
15168 	ill_t		*ill;
15169 	struct iocblk	*iocp;
15170 	mblk_t		*mp1;
15171 	conn_t		*connp = NULL;
15172 
15173 	ip1dbg(("ip_rput_other "));
15174 	ill = (ill_t *)q->q_ptr;
15175 	/*
15176 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15177 	 * in which case ipsq is NULL.
15178 	 */
15179 	if (ipsq != NULL) {
15180 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15181 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15182 	}
15183 
15184 	switch (mp->b_datap->db_type) {
15185 	case M_ERROR:
15186 	case M_HANGUP:
15187 		/*
15188 		 * The device has a problem.  We force the ILL down.  It can
15189 		 * be brought up again manually using SIOCSIFFLAGS (via
15190 		 * ifconfig or equivalent).
15191 		 */
15192 		ASSERT(ipsq != NULL);
15193 		if (mp->b_rptr < mp->b_wptr)
15194 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15195 		if (ill->ill_error == 0)
15196 			ill->ill_error = ENXIO;
15197 		if (!ill_down_start(q, mp))
15198 			return;
15199 		ipif_all_down_tail(ipsq, q, mp, NULL);
15200 		break;
15201 	case M_IOCACK:
15202 		iocp = (struct iocblk *)mp->b_rptr;
15203 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15204 		switch (iocp->ioc_cmd) {
15205 		case SIOCSTUNPARAM:
15206 		case OSIOCSTUNPARAM:
15207 			ASSERT(ipsq != NULL);
15208 			/*
15209 			 * Finish socket ioctl passed through to tun.
15210 			 * We should have an IOCTL waiting on this.
15211 			 */
15212 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15213 			if (ill->ill_isv6) {
15214 				struct iftun_req *ta;
15215 
15216 				/*
15217 				 * if a source or destination is
15218 				 * being set, try and set the link
15219 				 * local address for the tunnel
15220 				 */
15221 				ta = (struct iftun_req *)mp->b_cont->
15222 				    b_cont->b_rptr;
15223 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15224 					ipif_set_tun_llink(ill, ta);
15225 				}
15226 
15227 			}
15228 			if (mp1 != NULL) {
15229 				/*
15230 				 * Now copy back the b_next/b_prev used by
15231 				 * mi code for the mi_copy* functions.
15232 				 * See ip_sioctl_tunparam() for the reason.
15233 				 * Also protect against missing b_cont.
15234 				 */
15235 				if (mp->b_cont != NULL) {
15236 					mp->b_cont->b_next =
15237 					    mp1->b_cont->b_next;
15238 					mp->b_cont->b_prev =
15239 					    mp1->b_cont->b_prev;
15240 				}
15241 				inet_freemsg(mp1);
15242 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15243 				ASSERT(connp != NULL);
15244 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15245 				    iocp->ioc_error, NO_COPYOUT,
15246 				    ipsq->ipsq_current_ipif, ipsq);
15247 			} else {
15248 				ASSERT(connp == NULL);
15249 				putnext(q, mp);
15250 			}
15251 			break;
15252 		case SIOCGTUNPARAM:
15253 		case OSIOCGTUNPARAM:
15254 			/*
15255 			 * This is really M_IOCDATA from the tunnel driver.
15256 			 * convert back and complete the ioctl.
15257 			 * We should have an IOCTL waiting on this.
15258 			 */
15259 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15260 			if (mp1) {
15261 				/*
15262 				 * Now copy back the b_next/b_prev used by
15263 				 * mi code for the mi_copy* functions.
15264 				 * See ip_sioctl_tunparam() for the reason.
15265 				 * Also protect against missing b_cont.
15266 				 */
15267 				if (mp->b_cont != NULL) {
15268 					mp->b_cont->b_next =
15269 					    mp1->b_cont->b_next;
15270 					mp->b_cont->b_prev =
15271 					    mp1->b_cont->b_prev;
15272 				}
15273 				inet_freemsg(mp1);
15274 				if (iocp->ioc_error == 0)
15275 					mp->b_datap->db_type = M_IOCDATA;
15276 				ASSERT(connp != NULL);
15277 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15278 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15279 			} else {
15280 				ASSERT(connp == NULL);
15281 				putnext(q, mp);
15282 			}
15283 			break;
15284 		default:
15285 			break;
15286 		}
15287 		break;
15288 	case M_IOCNAK:
15289 		iocp = (struct iocblk *)mp->b_rptr;
15290 
15291 		switch (iocp->ioc_cmd) {
15292 		int mode;
15293 		ipif_t	*ipif;
15294 
15295 		case DL_IOC_HDR_INFO:
15296 			/*
15297 			 * If this was the first attempt turn of the
15298 			 * fastpath probing.
15299 			 */
15300 			mutex_enter(&ill->ill_lock);
15301 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15302 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15303 				mutex_exit(&ill->ill_lock);
15304 				ill_fastpath_nack(ill);
15305 				ip1dbg(("ip_rput: DLPI fastpath off on "
15306 				    "interface %s\n",
15307 				    ill->ill_name));
15308 			} else {
15309 				mutex_exit(&ill->ill_lock);
15310 			}
15311 			freemsg(mp);
15312 			break;
15313 		case SIOCSTUNPARAM:
15314 		case OSIOCSTUNPARAM:
15315 			ASSERT(ipsq != NULL);
15316 			/*
15317 			 * Finish socket ioctl passed through to tun
15318 			 * We should have an IOCTL waiting on this.
15319 			 */
15320 			/* FALLTHRU */
15321 		case SIOCGTUNPARAM:
15322 		case OSIOCGTUNPARAM:
15323 			/*
15324 			 * This is really M_IOCDATA from the tunnel driver.
15325 			 * convert back and complete the ioctl.
15326 			 * We should have an IOCTL waiting on this.
15327 			 */
15328 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15329 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15330 				mp1 = ill_pending_mp_get(ill, &connp,
15331 				    iocp->ioc_id);
15332 				mode = COPYOUT;
15333 				ipsq = NULL;
15334 				ipif = NULL;
15335 			} else {
15336 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15337 				mode = NO_COPYOUT;
15338 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15339 				ipif = ipsq->ipsq_current_ipif;
15340 			}
15341 			if (mp1 != NULL) {
15342 				/*
15343 				 * Now copy back the b_next/b_prev used by
15344 				 * mi code for the mi_copy* functions.
15345 				 * See ip_sioctl_tunparam() for the reason.
15346 				 * Also protect against missing b_cont.
15347 				 */
15348 				if (mp->b_cont != NULL) {
15349 					mp->b_cont->b_next =
15350 					    mp1->b_cont->b_next;
15351 					mp->b_cont->b_prev =
15352 					    mp1->b_cont->b_prev;
15353 				}
15354 				inet_freemsg(mp1);
15355 				if (iocp->ioc_error == 0)
15356 					iocp->ioc_error = EINVAL;
15357 				ASSERT(connp != NULL);
15358 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15359 				    iocp->ioc_error, mode, ipif, ipsq);
15360 			} else {
15361 				ASSERT(connp == NULL);
15362 				putnext(q, mp);
15363 			}
15364 			break;
15365 		default:
15366 			break;
15367 		}
15368 	default:
15369 		break;
15370 	}
15371 }
15372 
15373 /*
15374  * NOTE : This function does not ire_refrele the ire argument passed in.
15375  *
15376  * IPQoS notes
15377  * IP policy is invoked twice for a forwarded packet, once on the read side
15378  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15379  * enabled. An additional parameter, in_ill, has been added for this purpose.
15380  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15381  * because ip_mroute drops this information.
15382  *
15383  */
15384 void
15385 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15386 {
15387 	uint32_t	pkt_len;
15388 	queue_t	*q;
15389 	uint32_t	sum;
15390 #define	rptr	((uchar_t *)ipha)
15391 	uint32_t	max_frag;
15392 	uint32_t	ill_index;
15393 
15394 	/* Get the ill_index of the incoming ILL */
15395 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15396 
15397 	/* Initiate Read side IPPF processing */
15398 	if (IPP_ENABLED(IPP_FWD_IN)) {
15399 		ip_process(IPP_FWD_IN, &mp, ill_index);
15400 		if (mp == NULL) {
15401 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15402 			    "during IPPF processing\n"));
15403 			return;
15404 		}
15405 	}
15406 	pkt_len = ntohs(ipha->ipha_length);
15407 
15408 	/* Adjust the checksum to reflect the ttl decrement. */
15409 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
15410 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
15411 
15412 	if (ipha->ipha_ttl-- <= 1) {
15413 		if (ip_csum_hdr(ipha)) {
15414 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15415 			goto drop_pkt;
15416 		}
15417 		/*
15418 		 * Note: ire_stq this will be NULL for multicast
15419 		 * datagrams using the long path through arp (the IRE
15420 		 * is not an IRE_CACHE). This should not cause
15421 		 * problems since we don't generate ICMP errors for
15422 		 * multicast packets.
15423 		 */
15424 		q = ire->ire_stq;
15425 		if (q)
15426 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
15427 		else
15428 			freemsg(mp);
15429 		return;
15430 	}
15431 
15432 	/*
15433 	 * Don't forward if the interface is down
15434 	 */
15435 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
15436 		BUMP_MIB(&ip_mib, ipInDiscards);
15437 		goto drop_pkt;
15438 	}
15439 
15440 	/* Get the ill_index of the outgoing ILL */
15441 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
15442 
15443 	if (is_system_labeled()) {
15444 		mblk_t *mp1;
15445 
15446 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
15447 			BUMP_MIB(&ip_mib, ipForwProhibits);
15448 			goto drop_pkt;
15449 		}
15450 		/* Size may have changed */
15451 		mp = mp1;
15452 		ipha = (ipha_t *)mp->b_rptr;
15453 		pkt_len = ntohs(ipha->ipha_length);
15454 	}
15455 
15456 	/* Check if there are options to update */
15457 	if (!IS_SIMPLE_IPH(ipha)) {
15458 		if (ip_csum_hdr(ipha)) {
15459 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15460 			goto drop_pkt;
15461 		}
15462 		if (ip_rput_forward_options(mp, ipha, ire)) {
15463 			return;
15464 		}
15465 
15466 		ipha->ipha_hdr_checksum = 0;
15467 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
15468 	}
15469 	max_frag = ire->ire_max_frag;
15470 	if (pkt_len > max_frag) {
15471 		/*
15472 		 * It needs fragging on its way out.  We haven't
15473 		 * verified the header checksum yet.  Since we
15474 		 * are going to put a surely good checksum in the
15475 		 * outgoing header, we have to make sure that it
15476 		 * was good coming in.
15477 		 */
15478 		if (ip_csum_hdr(ipha)) {
15479 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15480 			goto drop_pkt;
15481 		}
15482 		/* Initiate Write side IPPF processing */
15483 		if (IPP_ENABLED(IPP_FWD_OUT)) {
15484 			ip_process(IPP_FWD_OUT, &mp, ill_index);
15485 			if (mp == NULL) {
15486 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
15487 				    " during IPPF processing\n"));
15488 				return;
15489 			}
15490 		}
15491 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
15492 		return;
15493 	}
15494 
15495 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
15496 	if (mp == NULL) {
15497 		BUMP_MIB(&ip_mib, ipInDiscards);
15498 		return;
15499 	}
15500 
15501 	q = ire->ire_stq;
15502 	UPDATE_IB_PKT_COUNT(ire);
15503 	ire->ire_last_used_time = lbolt;
15504 	BUMP_MIB(&ip_mib, ipForwDatagrams);
15505 	putnext(q, mp);
15506 	return;
15507 
15508 drop_pkt:;
15509 	ip1dbg(("ip_rput_forward: drop pkt\n"));
15510 	freemsg(mp);
15511 #undef	rptr
15512 }
15513 
15514 void
15515 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
15516 {
15517 	ire_t	*ire;
15518 
15519 	ASSERT(!ipif->ipif_isv6);
15520 	/*
15521 	 * Find an IRE which matches the destination and the outgoing
15522 	 * queue in the cache table. All we need is an IRE_CACHE which
15523 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
15524 	 * then it is enough to have some IRE_CACHE in the group.
15525 	 */
15526 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
15527 		dst = ipif->ipif_pp_dst_addr;
15528 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
15529 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
15530 	if (ire == NULL) {
15531 		/*
15532 		 * Mark this packet to make it be delivered to
15533 		 * ip_rput_forward after the new ire has been
15534 		 * created.
15535 		 */
15536 		mp->b_prev = NULL;
15537 		mp->b_next = mp;
15538 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
15539 		    NULL, 0);
15540 	} else {
15541 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
15542 		IRE_REFRELE(ire);
15543 	}
15544 }
15545 
15546 /* Update any source route, record route or timestamp options */
15547 static int
15548 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15549 {
15550 	ipoptp_t	opts;
15551 	uchar_t		*opt;
15552 	uint8_t		optval;
15553 	uint8_t		optlen;
15554 	ipaddr_t	dst;
15555 	uint32_t	ts;
15556 	ire_t		*dst_ire = NULL;
15557 	ire_t		*tmp_ire = NULL;
15558 	timestruc_t	now;
15559 
15560 	ip2dbg(("ip_rput_forward_options\n"));
15561 	dst = ipha->ipha_dst;
15562 	for (optval = ipoptp_first(&opts, ipha);
15563 	    optval != IPOPT_EOL;
15564 	    optval = ipoptp_next(&opts)) {
15565 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15566 		opt = opts.ipoptp_cur;
15567 		optlen = opts.ipoptp_len;
15568 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15569 		    optval, opts.ipoptp_len));
15570 		switch (optval) {
15571 			uint32_t off;
15572 		case IPOPT_SSRR:
15573 		case IPOPT_LSRR:
15574 			/* Check if adminstratively disabled */
15575 			if (!ip_forward_src_routed) {
15576 				BUMP_MIB(&ip_mib, ipForwProhibits);
15577 				if (ire->ire_stq)
15578 					icmp_unreachable(ire->ire_stq, mp,
15579 					    ICMP_SOURCE_ROUTE_FAILED);
15580 				else {
15581 					ip0dbg(("ip_rput_forward_options: "
15582 					    "unable to send unreach\n"));
15583 					freemsg(mp);
15584 				}
15585 				return (-1);
15586 			}
15587 
15588 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15589 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15590 			if (dst_ire == NULL) {
15591 				/*
15592 				 * Must be partial since ip_rput_options
15593 				 * checked for strict.
15594 				 */
15595 				break;
15596 			}
15597 			off = opt[IPOPT_OFFSET];
15598 			off--;
15599 		redo_srr:
15600 			if (optlen < IP_ADDR_LEN ||
15601 			    off > optlen - IP_ADDR_LEN) {
15602 				/* End of source route */
15603 				ip1dbg((
15604 				    "ip_rput_forward_options: end of SR\n"));
15605 				ire_refrele(dst_ire);
15606 				break;
15607 			}
15608 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15609 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15610 			    IP_ADDR_LEN);
15611 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15612 			    ntohl(dst)));
15613 
15614 			/*
15615 			 * Check if our address is present more than
15616 			 * once as consecutive hops in source route.
15617 			 */
15618 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15619 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15620 			if (tmp_ire != NULL) {
15621 				ire_refrele(tmp_ire);
15622 				off += IP_ADDR_LEN;
15623 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15624 				goto redo_srr;
15625 			}
15626 			ipha->ipha_dst = dst;
15627 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15628 			ire_refrele(dst_ire);
15629 			break;
15630 		case IPOPT_RR:
15631 			off = opt[IPOPT_OFFSET];
15632 			off--;
15633 			if (optlen < IP_ADDR_LEN ||
15634 			    off > optlen - IP_ADDR_LEN) {
15635 				/* No more room - ignore */
15636 				ip1dbg((
15637 				    "ip_rput_forward_options: end of RR\n"));
15638 				break;
15639 			}
15640 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15641 			    IP_ADDR_LEN);
15642 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15643 			break;
15644 		case IPOPT_TS:
15645 			/* Insert timestamp if there is room */
15646 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15647 			case IPOPT_TS_TSONLY:
15648 				off = IPOPT_TS_TIMELEN;
15649 				break;
15650 			case IPOPT_TS_PRESPEC:
15651 			case IPOPT_TS_PRESPEC_RFC791:
15652 				/* Verify that the address matched */
15653 				off = opt[IPOPT_OFFSET] - 1;
15654 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15655 				dst_ire = ire_ctable_lookup(dst, 0,
15656 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
15657 				    MATCH_IRE_TYPE);
15658 
15659 				if (dst_ire == NULL) {
15660 					/* Not for us */
15661 					break;
15662 				}
15663 				ire_refrele(dst_ire);
15664 				/* FALLTHRU */
15665 			case IPOPT_TS_TSANDADDR:
15666 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15667 				break;
15668 			default:
15669 				/*
15670 				 * ip_*put_options should have already
15671 				 * dropped this packet.
15672 				 */
15673 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15674 				    "unknown IT - bug in ip_rput_options?\n");
15675 				return (0);	/* Keep "lint" happy */
15676 			}
15677 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15678 				/* Increase overflow counter */
15679 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15680 				opt[IPOPT_POS_OV_FLG] =
15681 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15682 				    (off << 4));
15683 				break;
15684 			}
15685 			off = opt[IPOPT_OFFSET] - 1;
15686 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15687 			case IPOPT_TS_PRESPEC:
15688 			case IPOPT_TS_PRESPEC_RFC791:
15689 			case IPOPT_TS_TSANDADDR:
15690 				bcopy(&ire->ire_src_addr,
15691 				    (char *)opt + off, IP_ADDR_LEN);
15692 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15693 				/* FALLTHRU */
15694 			case IPOPT_TS_TSONLY:
15695 				off = opt[IPOPT_OFFSET] - 1;
15696 				/* Compute # of milliseconds since midnight */
15697 				gethrestime(&now);
15698 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15699 				    now.tv_nsec / (NANOSEC / MILLISEC);
15700 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15701 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15702 				break;
15703 			}
15704 			break;
15705 		}
15706 	}
15707 	return (0);
15708 }
15709 
15710 /*
15711  * This is called after processing at least one of AH/ESP headers.
15712  *
15713  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15714  * the actual, physical interface on which the packet was received,
15715  * but, when ip_strict_dst_multihoming is set to 1, could be the
15716  * interface which had the ipha_dst configured when the packet went
15717  * through ip_rput. The ill_index corresponding to the recv_ill
15718  * is saved in ipsec_in_rill_index
15719  */
15720 void
15721 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15722 {
15723 	mblk_t *mp;
15724 	ipaddr_t dst;
15725 	in6_addr_t *v6dstp;
15726 	ipha_t *ipha;
15727 	ip6_t *ip6h;
15728 	ipsec_in_t *ii;
15729 	boolean_t ill_need_rele = B_FALSE;
15730 	boolean_t rill_need_rele = B_FALSE;
15731 	boolean_t ire_need_rele = B_FALSE;
15732 
15733 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15734 	ASSERT(ii->ipsec_in_ill_index != 0);
15735 
15736 	mp = ipsec_mp->b_cont;
15737 	ASSERT(mp != NULL);
15738 
15739 
15740 	if (ill == NULL) {
15741 		ASSERT(recv_ill == NULL);
15742 		/*
15743 		 * We need to get the original queue on which ip_rput_local
15744 		 * or ip_rput_data_v6 was called.
15745 		 */
15746 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15747 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15748 		ill_need_rele = B_TRUE;
15749 
15750 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15751 			recv_ill = ill_lookup_on_ifindex(
15752 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15753 			    NULL, NULL, NULL, NULL);
15754 			rill_need_rele = B_TRUE;
15755 		} else {
15756 			recv_ill = ill;
15757 		}
15758 
15759 		if ((ill == NULL) || (recv_ill == NULL)) {
15760 			ip0dbg(("ip_fanout_proto_again: interface "
15761 			    "disappeared\n"));
15762 			if (ill != NULL)
15763 				ill_refrele(ill);
15764 			if (recv_ill != NULL)
15765 				ill_refrele(recv_ill);
15766 			freemsg(ipsec_mp);
15767 			return;
15768 		}
15769 	}
15770 
15771 	ASSERT(ill != NULL && recv_ill != NULL);
15772 
15773 	if (mp->b_datap->db_type == M_CTL) {
15774 		/*
15775 		 * AH/ESP is returning the ICMP message after
15776 		 * removing their headers. Fanout again till
15777 		 * it gets to the right protocol.
15778 		 */
15779 		if (ii->ipsec_in_v4) {
15780 			icmph_t *icmph;
15781 			int iph_hdr_length;
15782 			int hdr_length;
15783 
15784 			ipha = (ipha_t *)mp->b_rptr;
15785 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15786 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15787 			ipha = (ipha_t *)&icmph[1];
15788 			hdr_length = IPH_HDR_LENGTH(ipha);
15789 			/*
15790 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15791 			 * Reset the type to M_DATA.
15792 			 */
15793 			mp->b_datap->db_type = M_DATA;
15794 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15795 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15796 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15797 		} else {
15798 			icmp6_t *icmp6;
15799 			int hdr_length;
15800 
15801 			ip6h = (ip6_t *)mp->b_rptr;
15802 			/* Don't call hdr_length_v6() unless you have to. */
15803 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15804 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15805 			else
15806 				hdr_length = IPV6_HDR_LEN;
15807 
15808 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15809 			/*
15810 			 * icmp_inbound_error_fanout_v6 may need to do
15811 			 * pullupmsg.  Reset the type to M_DATA.
15812 			 */
15813 			mp->b_datap->db_type = M_DATA;
15814 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15815 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15816 		}
15817 		if (ill_need_rele)
15818 			ill_refrele(ill);
15819 		if (rill_need_rele)
15820 			ill_refrele(recv_ill);
15821 		return;
15822 	}
15823 
15824 	if (ii->ipsec_in_v4) {
15825 		ipha = (ipha_t *)mp->b_rptr;
15826 		dst = ipha->ipha_dst;
15827 		if (CLASSD(dst)) {
15828 			/*
15829 			 * Multicast has to be delivered to all streams.
15830 			 */
15831 			dst = INADDR_BROADCAST;
15832 		}
15833 
15834 		if (ire == NULL) {
15835 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
15836 			    MBLK_GETLABEL(mp));
15837 			if (ire == NULL) {
15838 				if (ill_need_rele)
15839 					ill_refrele(ill);
15840 				if (rill_need_rele)
15841 					ill_refrele(recv_ill);
15842 				ip1dbg(("ip_fanout_proto_again: "
15843 				    "IRE not found"));
15844 				freemsg(ipsec_mp);
15845 				return;
15846 			}
15847 			ire_need_rele = B_TRUE;
15848 		}
15849 
15850 		switch (ipha->ipha_protocol) {
15851 			case IPPROTO_UDP:
15852 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15853 				    recv_ill);
15854 				if (ire_need_rele)
15855 					ire_refrele(ire);
15856 				break;
15857 			case IPPROTO_TCP:
15858 				if (!ire_need_rele)
15859 					IRE_REFHOLD(ire);
15860 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15861 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15862 				IRE_REFRELE(ire);
15863 				if (mp != NULL)
15864 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15865 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15866 				break;
15867 			case IPPROTO_SCTP:
15868 				if (!ire_need_rele)
15869 					IRE_REFHOLD(ire);
15870 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15871 				    ipsec_mp, 0, ill->ill_rq, dst);
15872 				break;
15873 			default:
15874 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15875 				    recv_ill);
15876 				if (ire_need_rele)
15877 					ire_refrele(ire);
15878 				break;
15879 		}
15880 	} else {
15881 		uint32_t rput_flags = 0;
15882 
15883 		ip6h = (ip6_t *)mp->b_rptr;
15884 		v6dstp = &ip6h->ip6_dst;
15885 		/*
15886 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15887 		 * address.
15888 		 *
15889 		 * Currently, we don't store that state in the IPSEC_IN
15890 		 * message, and we may need to.
15891 		 */
15892 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15893 		    IP6_IN_LLMCAST : 0);
15894 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15895 		    NULL);
15896 	}
15897 	if (ill_need_rele)
15898 		ill_refrele(ill);
15899 	if (rill_need_rele)
15900 		ill_refrele(recv_ill);
15901 }
15902 
15903 /*
15904  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15905  * returns 'true' if there are still fragments left on the queue, in
15906  * which case we restart the timer.
15907  */
15908 void
15909 ill_frag_timer(void *arg)
15910 {
15911 	ill_t	*ill = (ill_t *)arg;
15912 	boolean_t frag_pending;
15913 
15914 	mutex_enter(&ill->ill_lock);
15915 	ASSERT(!ill->ill_fragtimer_executing);
15916 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15917 		ill->ill_frag_timer_id = 0;
15918 		mutex_exit(&ill->ill_lock);
15919 		return;
15920 	}
15921 	ill->ill_fragtimer_executing = 1;
15922 	mutex_exit(&ill->ill_lock);
15923 
15924 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15925 
15926 	/*
15927 	 * Restart the timer, if we have fragments pending or if someone
15928 	 * wanted us to be scheduled again.
15929 	 */
15930 	mutex_enter(&ill->ill_lock);
15931 	ill->ill_fragtimer_executing = 0;
15932 	ill->ill_frag_timer_id = 0;
15933 	if (frag_pending || ill->ill_fragtimer_needrestart)
15934 		ill_frag_timer_start(ill);
15935 	mutex_exit(&ill->ill_lock);
15936 }
15937 
15938 void
15939 ill_frag_timer_start(ill_t *ill)
15940 {
15941 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15942 
15943 	/* If the ill is closing or opening don't proceed */
15944 	if (ill->ill_state_flags & ILL_CONDEMNED)
15945 		return;
15946 
15947 	if (ill->ill_fragtimer_executing) {
15948 		/*
15949 		 * ill_frag_timer is currently executing. Just record the
15950 		 * the fact that we want the timer to be restarted.
15951 		 * ill_frag_timer will post a timeout before it returns,
15952 		 * ensuring it will be called again.
15953 		 */
15954 		ill->ill_fragtimer_needrestart = 1;
15955 		return;
15956 	}
15957 
15958 	if (ill->ill_frag_timer_id == 0) {
15959 		/*
15960 		 * The timer is neither running nor is the timeout handler
15961 		 * executing. Post a timeout so that ill_frag_timer will be
15962 		 * called
15963 		 */
15964 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15965 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15966 		ill->ill_fragtimer_needrestart = 0;
15967 	}
15968 }
15969 
15970 /*
15971  * This routine is needed for loopback when forwarding multicasts.
15972  *
15973  * IPQoS Notes:
15974  * IPPF processing is done in fanout routines.
15975  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15976  * processing for IPSec packets is done when it comes back in clear.
15977  * NOTE : The callers of this function need to do the ire_refrele for the
15978  *	  ire that is being passed in.
15979  */
15980 void
15981 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15982     ill_t *recv_ill)
15983 {
15984 	ill_t	*ill = (ill_t *)q->q_ptr;
15985 	uint32_t	sum;
15986 	uint32_t	u1;
15987 	uint32_t	u2;
15988 	int		hdr_length;
15989 	boolean_t	mctl_present;
15990 	mblk_t		*first_mp = mp;
15991 	mblk_t		*hada_mp = NULL;
15992 	ipha_t		*inner_ipha;
15993 
15994 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15995 	    "ip_rput_locl_start: q %p", q);
15996 
15997 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
15998 
15999 
16000 #define	rptr	((uchar_t *)ipha)
16001 #define	iphs	((uint16_t *)ipha)
16002 
16003 	/*
16004 	 * no UDP or TCP packet should come here anymore.
16005 	 */
16006 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16007 	    (ipha->ipha_protocol != IPPROTO_UDP));
16008 
16009 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16010 	if (mctl_present &&
16011 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16012 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16013 
16014 		/*
16015 		 * It's an IPsec accelerated packet.
16016 		 * Keep a pointer to the data attributes around until
16017 		 * we allocate the ipsec_info_t.
16018 		 */
16019 		IPSECHW_DEBUG(IPSECHW_PKT,
16020 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16021 		hada_mp = first_mp;
16022 		hada_mp->b_cont = NULL;
16023 		/*
16024 		 * Since it is accelerated, it comes directly from
16025 		 * the ill and the data attributes is followed by
16026 		 * the packet data.
16027 		 */
16028 		ASSERT(mp->b_datap->db_type != M_CTL);
16029 		first_mp = mp;
16030 		mctl_present = B_FALSE;
16031 	}
16032 
16033 	/*
16034 	 * IF M_CTL is not present, then ipsec_in_is_secure
16035 	 * should return B_TRUE. There is a case where loopback
16036 	 * packets has an M_CTL in the front with all the
16037 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16038 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16039 	 * packets never comes here, it is safe to ASSERT the
16040 	 * following.
16041 	 */
16042 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16043 
16044 
16045 	/* u1 is # words of IP options */
16046 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16047 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16048 
16049 	if (u1) {
16050 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16051 			if (hada_mp != NULL)
16052 				freemsg(hada_mp);
16053 			return;
16054 		}
16055 	} else {
16056 		/* Check the IP header checksum.  */
16057 #define	uph	((uint16_t *)ipha)
16058 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16059 		    uph[6] + uph[7] + uph[8] + uph[9];
16060 #undef  uph
16061 		/* finish doing IP checksum */
16062 		sum = (sum & 0xFFFF) + (sum >> 16);
16063 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16064 		/*
16065 		 * Don't verify header checksum if this packet is coming
16066 		 * back from AH/ESP as we already did it.
16067 		 */
16068 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16069 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16070 			goto drop_pkt;
16071 		}
16072 	}
16073 
16074 	/*
16075 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16076 	 * might be called more than once for secure packets, count only
16077 	 * the first time.
16078 	 */
16079 	if (!mctl_present) {
16080 		UPDATE_IB_PKT_COUNT(ire);
16081 		ire->ire_last_used_time = lbolt;
16082 	}
16083 
16084 	/* Check for fragmentation offset. */
16085 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16086 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16087 	if (u1) {
16088 		/*
16089 		 * We re-assemble fragments before we do the AH/ESP
16090 		 * processing. Thus, M_CTL should not be present
16091 		 * while we are re-assembling.
16092 		 */
16093 		ASSERT(!mctl_present);
16094 		ASSERT(first_mp == mp);
16095 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16096 			return;
16097 		}
16098 		/*
16099 		 * Make sure that first_mp points back to mp as
16100 		 * the mp we came in with could have changed in
16101 		 * ip_rput_fragment().
16102 		 */
16103 		ipha = (ipha_t *)mp->b_rptr;
16104 		first_mp = mp;
16105 	}
16106 
16107 	/*
16108 	 * Clear hardware checksumming flag as it is currently only
16109 	 * used by TCP and UDP.
16110 	 */
16111 	DB_CKSUMFLAGS(mp) = 0;
16112 
16113 	/* Now we have a complete datagram, destined for this machine. */
16114 	u1 = IPH_HDR_LENGTH(ipha);
16115 	switch (ipha->ipha_protocol) {
16116 	case IPPROTO_ICMP: {
16117 		ire_t		*ire_zone;
16118 		ilm_t		*ilm;
16119 		mblk_t		*mp1;
16120 		zoneid_t	last_zoneid;
16121 
16122 		if (CLASSD(ipha->ipha_dst) &&
16123 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16124 			ASSERT(ire->ire_type == IRE_BROADCAST);
16125 			/*
16126 			 * In the multicast case, applications may have joined
16127 			 * the group from different zones, so we need to deliver
16128 			 * the packet to each of them. Loop through the
16129 			 * multicast memberships structures (ilm) on the receive
16130 			 * ill and send a copy of the packet up each matching
16131 			 * one. However, we don't do this for multicasts sent on
16132 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16133 			 * they must stay in the sender's zone.
16134 			 *
16135 			 * ilm_add_v6() ensures that ilms in the same zone are
16136 			 * contiguous in the ill_ilm list. We use this property
16137 			 * to avoid sending duplicates needed when two
16138 			 * applications in the same zone join the same group on
16139 			 * different logical interfaces: we ignore the ilm if
16140 			 * its zoneid is the same as the last matching one.
16141 			 * In addition, the sending of the packet for
16142 			 * ire_zoneid is delayed until all of the other ilms
16143 			 * have been exhausted.
16144 			 */
16145 			last_zoneid = -1;
16146 			ILM_WALKER_HOLD(recv_ill);
16147 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16148 			    ilm = ilm->ilm_next) {
16149 				if ((ilm->ilm_flags & ILM_DELETED) ||
16150 				    ipha->ipha_dst != ilm->ilm_addr ||
16151 				    ilm->ilm_zoneid == last_zoneid ||
16152 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16153 				    ilm->ilm_zoneid == ALL_ZONES ||
16154 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16155 					continue;
16156 				mp1 = ip_copymsg(first_mp);
16157 				if (mp1 == NULL)
16158 					continue;
16159 				icmp_inbound(q, mp1, B_TRUE, ill,
16160 				    0, sum, mctl_present, B_TRUE,
16161 				    recv_ill, ilm->ilm_zoneid);
16162 				last_zoneid = ilm->ilm_zoneid;
16163 			}
16164 			ILM_WALKER_RELE(recv_ill);
16165 		} else if (ire->ire_type == IRE_BROADCAST) {
16166 			/*
16167 			 * In the broadcast case, there may be many zones
16168 			 * which need a copy of the packet delivered to them.
16169 			 * There is one IRE_BROADCAST per broadcast address
16170 			 * and per zone; we walk those using a helper function.
16171 			 * In addition, the sending of the packet for ire is
16172 			 * delayed until all of the other ires have been
16173 			 * processed.
16174 			 */
16175 			IRB_REFHOLD(ire->ire_bucket);
16176 			ire_zone = NULL;
16177 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16178 			    ire)) != NULL) {
16179 				mp1 = ip_copymsg(first_mp);
16180 				if (mp1 == NULL)
16181 					continue;
16182 
16183 				UPDATE_IB_PKT_COUNT(ire_zone);
16184 				ire_zone->ire_last_used_time = lbolt;
16185 				icmp_inbound(q, mp1, B_TRUE, ill,
16186 				    0, sum, mctl_present, B_TRUE,
16187 				    recv_ill, ire_zone->ire_zoneid);
16188 			}
16189 			IRB_REFRELE(ire->ire_bucket);
16190 		}
16191 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16192 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16193 		    ire->ire_zoneid);
16194 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16195 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16196 		return;
16197 	}
16198 	case IPPROTO_IGMP:
16199 		/*
16200 		 * If we are not willing to accept IGMP packets in clear,
16201 		 * then check with global policy.
16202 		 */
16203 		if (igmp_accept_clear_messages == 0) {
16204 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16205 			    ipha, NULL, mctl_present);
16206 			if (first_mp == NULL)
16207 				return;
16208 		}
16209 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16210 			freemsg(first_mp);
16211 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16212 			BUMP_MIB(&ip_mib, ipInDiscards);
16213 			return;
16214 		}
16215 		if (igmp_input(q, mp, ill)) {
16216 			/* Bad packet - discarded by igmp_input */
16217 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16218 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16219 			if (mctl_present)
16220 				freeb(first_mp);
16221 			return;
16222 		}
16223 		/*
16224 		 * igmp_input() may have pulled up the message so ipha needs to
16225 		 * be reinitialized.
16226 		 */
16227 		ipha = (ipha_t *)mp->b_rptr;
16228 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16229 			/* No user-level listener for IGMP packets */
16230 			goto drop_pkt;
16231 		}
16232 		/* deliver to local raw users */
16233 		break;
16234 	case IPPROTO_PIM:
16235 		/*
16236 		 * If we are not willing to accept PIM packets in clear,
16237 		 * then check with global policy.
16238 		 */
16239 		if (pim_accept_clear_messages == 0) {
16240 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16241 			    ipha, NULL, mctl_present);
16242 			if (first_mp == NULL)
16243 				return;
16244 		}
16245 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16246 			freemsg(first_mp);
16247 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16248 			BUMP_MIB(&ip_mib, ipInDiscards);
16249 			return;
16250 		}
16251 		if (pim_input(q, mp) != 0) {
16252 			/* Bad packet - discarded by pim_input */
16253 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16254 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16255 			if (mctl_present)
16256 				freeb(first_mp);
16257 			return;
16258 		}
16259 
16260 		/*
16261 		 * pim_input() may have pulled up the message so ipha needs to
16262 		 * be reinitialized.
16263 		 */
16264 		ipha = (ipha_t *)mp->b_rptr;
16265 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16266 			/* No user-level listener for PIM packets */
16267 			goto drop_pkt;
16268 		}
16269 		/* deliver to local raw users */
16270 		break;
16271 	case IPPROTO_ENCAP:
16272 		/*
16273 		 * Handle self-encapsulated packets (IP-in-IP where
16274 		 * the inner addresses == the outer addresses).
16275 		 */
16276 		hdr_length = IPH_HDR_LENGTH(ipha);
16277 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16278 		    mp->b_wptr) {
16279 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16280 			    sizeof (ipha_t) - mp->b_rptr)) {
16281 				BUMP_MIB(&ip_mib, ipInDiscards);
16282 				freemsg(first_mp);
16283 				return;
16284 			}
16285 			ipha = (ipha_t *)mp->b_rptr;
16286 		}
16287 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16288 		/*
16289 		 * Check the sanity of the inner IP header.
16290 		 */
16291 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16292 			BUMP_MIB(&ip_mib, ipInDiscards);
16293 			freemsg(first_mp);
16294 			return;
16295 		}
16296 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16297 			BUMP_MIB(&ip_mib, ipInDiscards);
16298 			freemsg(first_mp);
16299 			return;
16300 		}
16301 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16302 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16303 			ipsec_in_t *ii;
16304 
16305 			/*
16306 			 * Self-encapsulated tunnel packet. Remove
16307 			 * the outer IP header and fanout again.
16308 			 * We also need to make sure that the inner
16309 			 * header is pulled up until options.
16310 			 */
16311 			mp->b_rptr = (uchar_t *)inner_ipha;
16312 			ipha = inner_ipha;
16313 			hdr_length = IPH_HDR_LENGTH(ipha);
16314 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16315 				if (!pullupmsg(mp, (uchar_t *)ipha +
16316 				    + hdr_length - mp->b_rptr)) {
16317 					freemsg(first_mp);
16318 					return;
16319 				}
16320 				ipha = (ipha_t *)mp->b_rptr;
16321 			}
16322 			if (!mctl_present) {
16323 				ASSERT(first_mp == mp);
16324 				/*
16325 				 * This means that somebody is sending
16326 				 * Self-encapsualted packets without AH/ESP.
16327 				 * If AH/ESP was present, we would have already
16328 				 * allocated the first_mp.
16329 				 */
16330 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16331 				    NULL) {
16332 					ip1dbg(("ip_proto_input: IPSEC_IN "
16333 					    "allocation failure.\n"));
16334 					BUMP_MIB(&ip_mib, ipInDiscards);
16335 					freemsg(mp);
16336 					return;
16337 				}
16338 				first_mp->b_cont = mp;
16339 			}
16340 			/*
16341 			 * We generally store the ill_index if we need to
16342 			 * do IPSEC processing as we lose the ill queue when
16343 			 * we come back. But in this case, we never should
16344 			 * have to store the ill_index here as it should have
16345 			 * been stored previously when we processed the
16346 			 * AH/ESP header in this routine or for non-ipsec
16347 			 * cases, we still have the queue. But for some bad
16348 			 * packets from the wire, we can get to IPSEC after
16349 			 * this and we better store the index for that case.
16350 			 */
16351 			ill = (ill_t *)q->q_ptr;
16352 			ii = (ipsec_in_t *)first_mp->b_rptr;
16353 			ii->ipsec_in_ill_index =
16354 			    ill->ill_phyint->phyint_ifindex;
16355 			ii->ipsec_in_rill_index =
16356 			    recv_ill->ill_phyint->phyint_ifindex;
16357 			if (ii->ipsec_in_decaps) {
16358 				/*
16359 				 * This packet is self-encapsulated multiple
16360 				 * times. We don't want to recurse infinitely.
16361 				 * To keep it simple, drop the packet.
16362 				 */
16363 				BUMP_MIB(&ip_mib, ipInDiscards);
16364 				freemsg(first_mp);
16365 				return;
16366 			}
16367 			ii->ipsec_in_decaps = B_TRUE;
16368 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16369 			return;
16370 		}
16371 		break;
16372 	case IPPROTO_AH:
16373 	case IPPROTO_ESP: {
16374 		/*
16375 		 * Fast path for AH/ESP. If this is the first time
16376 		 * we are sending a datagram to AH/ESP, allocate
16377 		 * a IPSEC_IN message and prepend it. Otherwise,
16378 		 * just fanout.
16379 		 */
16380 
16381 		int ipsec_rc;
16382 		ipsec_in_t *ii;
16383 
16384 		IP_STAT(ipsec_proto_ahesp);
16385 		if (!mctl_present) {
16386 			ASSERT(first_mp == mp);
16387 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16388 				ip1dbg(("ip_proto_input: IPSEC_IN "
16389 				    "allocation failure.\n"));
16390 				freemsg(hada_mp); /* okay ifnull */
16391 				BUMP_MIB(&ip_mib, ipInDiscards);
16392 				freemsg(mp);
16393 				return;
16394 			}
16395 			/*
16396 			 * Store the ill_index so that when we come back
16397 			 * from IPSEC we ride on the same queue.
16398 			 */
16399 			ill = (ill_t *)q->q_ptr;
16400 			ii = (ipsec_in_t *)first_mp->b_rptr;
16401 			ii->ipsec_in_ill_index =
16402 			    ill->ill_phyint->phyint_ifindex;
16403 			ii->ipsec_in_rill_index =
16404 			    recv_ill->ill_phyint->phyint_ifindex;
16405 			first_mp->b_cont = mp;
16406 			/*
16407 			 * Cache hardware acceleration info.
16408 			 */
16409 			if (hada_mp != NULL) {
16410 				IPSECHW_DEBUG(IPSECHW_PKT,
16411 				    ("ip_rput_local: caching data attr.\n"));
16412 				ii->ipsec_in_accelerated = B_TRUE;
16413 				ii->ipsec_in_da = hada_mp;
16414 				hada_mp = NULL;
16415 			}
16416 		} else {
16417 			ii = (ipsec_in_t *)first_mp->b_rptr;
16418 		}
16419 
16420 		if (!ipsec_loaded()) {
16421 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
16422 			    ire->ire_zoneid);
16423 			return;
16424 		}
16425 
16426 		/* select inbound SA and have IPsec process the pkt */
16427 		if (ipha->ipha_protocol == IPPROTO_ESP) {
16428 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
16429 			if (esph == NULL)
16430 				return;
16431 			ASSERT(ii->ipsec_in_esp_sa != NULL);
16432 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
16433 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
16434 			    first_mp, esph);
16435 		} else {
16436 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
16437 			if (ah == NULL)
16438 				return;
16439 			ASSERT(ii->ipsec_in_ah_sa != NULL);
16440 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
16441 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
16442 			    first_mp, ah);
16443 		}
16444 
16445 		switch (ipsec_rc) {
16446 		case IPSEC_STATUS_SUCCESS:
16447 			break;
16448 		case IPSEC_STATUS_FAILED:
16449 			BUMP_MIB(&ip_mib, ipInDiscards);
16450 			/* FALLTHRU */
16451 		case IPSEC_STATUS_PENDING:
16452 			return;
16453 		}
16454 		/* we're done with IPsec processing, send it up */
16455 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
16456 		return;
16457 	}
16458 	default:
16459 		break;
16460 	}
16461 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
16462 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
16463 		    ire->ire_zoneid));
16464 		goto drop_pkt;
16465 	}
16466 	/*
16467 	 * Handle protocols with which IP is less intimate.  There
16468 	 * can be more than one stream bound to a particular
16469 	 * protocol.  When this is the case, each one gets a copy
16470 	 * of any incoming packets.
16471 	 */
16472 	ip_fanout_proto(q, first_mp, ill, ipha,
16473 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
16474 	    B_TRUE, recv_ill, ire->ire_zoneid);
16475 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16476 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
16477 	return;
16478 
16479 drop_pkt:
16480 	freemsg(first_mp);
16481 	if (hada_mp != NULL)
16482 		freeb(hada_mp);
16483 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16484 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
16485 #undef	rptr
16486 #undef  iphs
16487 
16488 }
16489 
16490 /*
16491  * Update any source route, record route or timestamp options.
16492  * Check that we are at end of strict source route.
16493  * The options have already been checked for sanity in ip_rput_options().
16494  */
16495 static boolean_t
16496 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
16497 {
16498 	ipoptp_t	opts;
16499 	uchar_t		*opt;
16500 	uint8_t		optval;
16501 	uint8_t		optlen;
16502 	ipaddr_t	dst;
16503 	uint32_t	ts;
16504 	ire_t		*dst_ire;
16505 	timestruc_t	now;
16506 
16507 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16508 
16509 	ip2dbg(("ip_rput_local_options\n"));
16510 
16511 	for (optval = ipoptp_first(&opts, ipha);
16512 	    optval != IPOPT_EOL;
16513 	    optval = ipoptp_next(&opts)) {
16514 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16515 		opt = opts.ipoptp_cur;
16516 		optlen = opts.ipoptp_len;
16517 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
16518 		    optval, optlen));
16519 		switch (optval) {
16520 			uint32_t off;
16521 		case IPOPT_SSRR:
16522 		case IPOPT_LSRR:
16523 			off = opt[IPOPT_OFFSET];
16524 			off--;
16525 			if (optlen < IP_ADDR_LEN ||
16526 			    off > optlen - IP_ADDR_LEN) {
16527 				/* End of source route */
16528 				ip1dbg(("ip_rput_local_options: end of SR\n"));
16529 				break;
16530 			}
16531 			/*
16532 			 * This will only happen if two consecutive entries
16533 			 * in the source route contains our address or if
16534 			 * it is a packet with a loose source route which
16535 			 * reaches us before consuming the whole source route
16536 			 */
16537 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
16538 			if (optval == IPOPT_SSRR) {
16539 				goto bad_src_route;
16540 			}
16541 			/*
16542 			 * Hack: instead of dropping the packet truncate the
16543 			 * source route to what has been used by filling the
16544 			 * rest with IPOPT_NOP.
16545 			 */
16546 			opt[IPOPT_OLEN] = (uint8_t)off;
16547 			while (off < optlen) {
16548 				opt[off++] = IPOPT_NOP;
16549 			}
16550 			break;
16551 		case IPOPT_RR:
16552 			off = opt[IPOPT_OFFSET];
16553 			off--;
16554 			if (optlen < IP_ADDR_LEN ||
16555 			    off > optlen - IP_ADDR_LEN) {
16556 				/* No more room - ignore */
16557 				ip1dbg((
16558 				    "ip_rput_local_options: end of RR\n"));
16559 				break;
16560 			}
16561 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16562 			    IP_ADDR_LEN);
16563 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16564 			break;
16565 		case IPOPT_TS:
16566 			/* Insert timestamp if there is romm */
16567 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16568 			case IPOPT_TS_TSONLY:
16569 				off = IPOPT_TS_TIMELEN;
16570 				break;
16571 			case IPOPT_TS_PRESPEC:
16572 			case IPOPT_TS_PRESPEC_RFC791:
16573 				/* Verify that the address matched */
16574 				off = opt[IPOPT_OFFSET] - 1;
16575 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16576 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16577 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16578 				if (dst_ire == NULL) {
16579 					/* Not for us */
16580 					break;
16581 				}
16582 				ire_refrele(dst_ire);
16583 				/* FALLTHRU */
16584 			case IPOPT_TS_TSANDADDR:
16585 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16586 				break;
16587 			default:
16588 				/*
16589 				 * ip_*put_options should have already
16590 				 * dropped this packet.
16591 				 */
16592 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16593 				    "unknown IT - bug in ip_rput_options?\n");
16594 				return (B_TRUE);	/* Keep "lint" happy */
16595 			}
16596 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16597 				/* Increase overflow counter */
16598 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16599 				opt[IPOPT_POS_OV_FLG] =
16600 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16601 				    (off << 4));
16602 				break;
16603 			}
16604 			off = opt[IPOPT_OFFSET] - 1;
16605 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16606 			case IPOPT_TS_PRESPEC:
16607 			case IPOPT_TS_PRESPEC_RFC791:
16608 			case IPOPT_TS_TSANDADDR:
16609 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16610 				    IP_ADDR_LEN);
16611 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16612 				/* FALLTHRU */
16613 			case IPOPT_TS_TSONLY:
16614 				off = opt[IPOPT_OFFSET] - 1;
16615 				/* Compute # of milliseconds since midnight */
16616 				gethrestime(&now);
16617 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16618 				    now.tv_nsec / (NANOSEC / MILLISEC);
16619 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16620 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16621 				break;
16622 			}
16623 			break;
16624 		}
16625 	}
16626 	return (B_TRUE);
16627 
16628 bad_src_route:
16629 	q = WR(q);
16630 	/* make sure we clear any indication of a hardware checksum */
16631 	DB_CKSUMFLAGS(mp) = 0;
16632 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16633 	return (B_FALSE);
16634 
16635 }
16636 
16637 /*
16638  * Process IP options in an inbound packet.  If an option affects the
16639  * effective destination address, return the next hop address via dstp.
16640  * Returns -1 if something fails in which case an ICMP error has been sent
16641  * and mp freed.
16642  */
16643 static int
16644 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16645 {
16646 	ipoptp_t	opts;
16647 	uchar_t		*opt;
16648 	uint8_t		optval;
16649 	uint8_t		optlen;
16650 	ipaddr_t	dst;
16651 	intptr_t	code = 0;
16652 	ire_t		*ire = NULL;
16653 
16654 	ip2dbg(("ip_rput_options\n"));
16655 	dst = ipha->ipha_dst;
16656 	for (optval = ipoptp_first(&opts, ipha);
16657 	    optval != IPOPT_EOL;
16658 	    optval = ipoptp_next(&opts)) {
16659 		opt = opts.ipoptp_cur;
16660 		optlen = opts.ipoptp_len;
16661 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16662 		    optval, optlen));
16663 		/*
16664 		 * Note: we need to verify the checksum before we
16665 		 * modify anything thus this routine only extracts the next
16666 		 * hop dst from any source route.
16667 		 */
16668 		switch (optval) {
16669 			uint32_t off;
16670 		case IPOPT_SSRR:
16671 		case IPOPT_LSRR:
16672 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16673 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16674 			if (ire == NULL) {
16675 				if (optval == IPOPT_SSRR) {
16676 					ip1dbg(("ip_rput_options: not next"
16677 					    " strict source route 0x%x\n",
16678 					    ntohl(dst)));
16679 					code = (char *)&ipha->ipha_dst -
16680 					    (char *)ipha;
16681 					goto param_prob; /* RouterReq's */
16682 				}
16683 				ip2dbg(("ip_rput_options: "
16684 				    "not next source route 0x%x\n",
16685 				    ntohl(dst)));
16686 				break;
16687 			}
16688 			ire_refrele(ire);
16689 
16690 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16691 				ip1dbg((
16692 				    "ip_rput_options: bad option offset\n"));
16693 				code = (char *)&opt[IPOPT_OLEN] -
16694 				    (char *)ipha;
16695 				goto param_prob;
16696 			}
16697 			off = opt[IPOPT_OFFSET];
16698 			off--;
16699 		redo_srr:
16700 			if (optlen < IP_ADDR_LEN ||
16701 			    off > optlen - IP_ADDR_LEN) {
16702 				/* End of source route */
16703 				ip1dbg(("ip_rput_options: end of SR\n"));
16704 				break;
16705 			}
16706 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16707 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16708 			    ntohl(dst)));
16709 
16710 			/*
16711 			 * Check if our address is present more than
16712 			 * once as consecutive hops in source route.
16713 			 * XXX verify per-interface ip_forwarding
16714 			 * for source route?
16715 			 */
16716 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16717 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16718 
16719 			if (ire != NULL) {
16720 				ire_refrele(ire);
16721 				off += IP_ADDR_LEN;
16722 				goto redo_srr;
16723 			}
16724 
16725 			if (dst == htonl(INADDR_LOOPBACK)) {
16726 				ip1dbg(("ip_rput_options: loopback addr in "
16727 				    "source route!\n"));
16728 				goto bad_src_route;
16729 			}
16730 			/*
16731 			 * For strict: verify that dst is directly
16732 			 * reachable.
16733 			 */
16734 			if (optval == IPOPT_SSRR) {
16735 				ire = ire_ftable_lookup(dst, 0, 0,
16736 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16737 				    MBLK_GETLABEL(mp),
16738 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
16739 				if (ire == NULL) {
16740 					ip1dbg(("ip_rput_options: SSRR not "
16741 					    "directly reachable: 0x%x\n",
16742 					    ntohl(dst)));
16743 					goto bad_src_route;
16744 				}
16745 				ire_refrele(ire);
16746 			}
16747 			/*
16748 			 * Defer update of the offset and the record route
16749 			 * until the packet is forwarded.
16750 			 */
16751 			break;
16752 		case IPOPT_RR:
16753 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16754 				ip1dbg((
16755 				    "ip_rput_options: bad option offset\n"));
16756 				code = (char *)&opt[IPOPT_OLEN] -
16757 				    (char *)ipha;
16758 				goto param_prob;
16759 			}
16760 			break;
16761 		case IPOPT_TS:
16762 			/*
16763 			 * Verify that length >= 5 and that there is either
16764 			 * room for another timestamp or that the overflow
16765 			 * counter is not maxed out.
16766 			 */
16767 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16768 			if (optlen < IPOPT_MINLEN_IT) {
16769 				goto param_prob;
16770 			}
16771 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16772 				ip1dbg((
16773 				    "ip_rput_options: bad option offset\n"));
16774 				code = (char *)&opt[IPOPT_OFFSET] -
16775 				    (char *)ipha;
16776 				goto param_prob;
16777 			}
16778 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16779 			case IPOPT_TS_TSONLY:
16780 				off = IPOPT_TS_TIMELEN;
16781 				break;
16782 			case IPOPT_TS_TSANDADDR:
16783 			case IPOPT_TS_PRESPEC:
16784 			case IPOPT_TS_PRESPEC_RFC791:
16785 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16786 				break;
16787 			default:
16788 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16789 				    (char *)ipha;
16790 				goto param_prob;
16791 			}
16792 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16793 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16794 				/*
16795 				 * No room and the overflow counter is 15
16796 				 * already.
16797 				 */
16798 				goto param_prob;
16799 			}
16800 			break;
16801 		}
16802 	}
16803 
16804 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16805 		*dstp = dst;
16806 		return (0);
16807 	}
16808 
16809 	ip1dbg(("ip_rput_options: error processing IP options."));
16810 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16811 
16812 param_prob:
16813 	q = WR(q);
16814 	/* make sure we clear any indication of a hardware checksum */
16815 	DB_CKSUMFLAGS(mp) = 0;
16816 	icmp_param_problem(q, mp, (uint8_t)code);
16817 	return (-1);
16818 
16819 bad_src_route:
16820 	q = WR(q);
16821 	/* make sure we clear any indication of a hardware checksum */
16822 	DB_CKSUMFLAGS(mp) = 0;
16823 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16824 	return (-1);
16825 }
16826 
16827 /*
16828  * IP & ICMP info in >=14 msg's ...
16829  *  - ip fixed part (mib2_ip_t)
16830  *  - icmp fixed part (mib2_icmp_t)
16831  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16832  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16833  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16834  *  - ipRouteAttributeTable (ip 102)	labeled routes
16835  *  - ip multicast membership (ip_member_t)
16836  *  - ip multicast source filtering (ip_grpsrc_t)
16837  *  - igmp fixed part (struct igmpstat)
16838  *  - multicast routing stats (struct mrtstat)
16839  *  - multicast routing vifs (array of struct vifctl)
16840  *  - multicast routing routes (array of struct mfcctl)
16841  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16842  *					One per ill plus one generic
16843  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16844  *					One per ill plus one generic
16845  *  - ipv6RouteEntry			all IPv6 IREs
16846  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
16847  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16848  *  - ipv6AddrEntry			all IPv6 ipifs
16849  *  - ipv6 multicast membership (ipv6_member_t)
16850  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16851  *
16852  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16853  * already present.
16854  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
16855  * already filled in by the caller.
16856  * Return value of 0 indicates that no messages were sent and caller
16857  * should free mpctl.
16858  */
16859 int
16860 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16861 {
16862 
16863 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16864 		return (0);
16865 	}
16866 
16867 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16868 		return (1);
16869 	}
16870 
16871 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16872 		return (1);
16873 	}
16874 
16875 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16876 		return (1);
16877 	}
16878 
16879 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16880 		return (1);
16881 	}
16882 
16883 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16884 		return (1);
16885 	}
16886 
16887 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16888 		return (1);
16889 	}
16890 
16891 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16892 		return (1);
16893 	}
16894 
16895 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16896 		return (1);
16897 	}
16898 
16899 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16900 		return (1);
16901 	}
16902 
16903 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16904 		return (1);
16905 	}
16906 
16907 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16908 		return (1);
16909 	}
16910 
16911 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16912 		return (1);
16913 	}
16914 
16915 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16916 		return (1);
16917 	}
16918 
16919 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16920 		return (1);
16921 	}
16922 
16923 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16924 		return (1);
16925 	}
16926 
16927 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16928 		return (1);
16929 	}
16930 
16931 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16932 		return (1);
16933 	}
16934 	freemsg(mpctl);
16935 	return (1);
16936 }
16937 
16938 
16939 /* Get global IPv4 statistics */
16940 static mblk_t *
16941 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16942 {
16943 	struct opthdr		*optp;
16944 	mblk_t			*mp2ctl;
16945 
16946 	/*
16947 	 * make a copy of the original message
16948 	 */
16949 	mp2ctl = copymsg(mpctl);
16950 
16951 	/* fixed length IP structure... */
16952 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16953 	optp->level = MIB2_IP;
16954 	optp->name = 0;
16955 	SET_MIB(ip_mib.ipForwarding,
16956 	    (WE_ARE_FORWARDING ? 1 : 2));
16957 	SET_MIB(ip_mib.ipDefaultTTL,
16958 	    (uint32_t)ip_def_ttl);
16959 	SET_MIB(ip_mib.ipReasmTimeout,
16960 	    ip_g_frag_timeout);
16961 	SET_MIB(ip_mib.ipAddrEntrySize,
16962 	    sizeof (mib2_ipAddrEntry_t));
16963 	SET_MIB(ip_mib.ipRouteEntrySize,
16964 	    sizeof (mib2_ipRouteEntry_t));
16965 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16966 	    sizeof (mib2_ipNetToMediaEntry_t));
16967 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16968 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16969 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
16970 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
16971 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16972 	    (int)sizeof (ip_mib))) {
16973 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16974 		    (uint_t)sizeof (ip_mib)));
16975 	}
16976 
16977 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16978 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16979 	    (int)optp->level, (int)optp->name, (int)optp->len));
16980 	qreply(q, mpctl);
16981 	return (mp2ctl);
16982 }
16983 
16984 /* Global IPv4 ICMP statistics */
16985 static mblk_t *
16986 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16987 {
16988 	struct opthdr		*optp;
16989 	mblk_t			*mp2ctl;
16990 
16991 	/*
16992 	 * Make a copy of the original message
16993 	 */
16994 	mp2ctl = copymsg(mpctl);
16995 
16996 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16997 	optp->level = MIB2_ICMP;
16998 	optp->name = 0;
16999 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17000 	    (int)sizeof (icmp_mib))) {
17001 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17002 		    (uint_t)sizeof (icmp_mib)));
17003 	}
17004 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17005 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17006 	    (int)optp->level, (int)optp->name, (int)optp->len));
17007 	qreply(q, mpctl);
17008 	return (mp2ctl);
17009 }
17010 
17011 /* Global IPv4 IGMP statistics */
17012 static mblk_t *
17013 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17014 {
17015 	struct opthdr		*optp;
17016 	mblk_t			*mp2ctl;
17017 
17018 	/*
17019 	 * make a copy of the original message
17020 	 */
17021 	mp2ctl = copymsg(mpctl);
17022 
17023 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17024 	optp->level = EXPER_IGMP;
17025 	optp->name = 0;
17026 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17027 	    (int)sizeof (igmpstat))) {
17028 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17029 		    (uint_t)sizeof (igmpstat)));
17030 	}
17031 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17032 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17033 	    (int)optp->level, (int)optp->name, (int)optp->len));
17034 	qreply(q, mpctl);
17035 	return (mp2ctl);
17036 }
17037 
17038 /* Global IPv4 Multicast Routing statistics */
17039 static mblk_t *
17040 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17041 {
17042 	struct opthdr		*optp;
17043 	mblk_t			*mp2ctl;
17044 
17045 	/*
17046 	 * make a copy of the original message
17047 	 */
17048 	mp2ctl = copymsg(mpctl);
17049 
17050 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17051 	optp->level = EXPER_DVMRP;
17052 	optp->name = 0;
17053 	if (!ip_mroute_stats(mpctl->b_cont)) {
17054 		ip0dbg(("ip_mroute_stats: failed\n"));
17055 	}
17056 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17057 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17058 	    (int)optp->level, (int)optp->name, (int)optp->len));
17059 	qreply(q, mpctl);
17060 	return (mp2ctl);
17061 }
17062 
17063 /* IPv4 address information */
17064 static mblk_t *
17065 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17066 {
17067 	struct opthdr		*optp;
17068 	mblk_t			*mp2ctl;
17069 	mblk_t			*mp_tail = NULL;
17070 	ill_t			*ill;
17071 	ipif_t			*ipif;
17072 	uint_t			bitval;
17073 	mib2_ipAddrEntry_t	mae;
17074 	zoneid_t		zoneid;
17075 	ill_walk_context_t ctx;
17076 
17077 	/*
17078 	 * make a copy of the original message
17079 	 */
17080 	mp2ctl = copymsg(mpctl);
17081 
17082 	/* ipAddrEntryTable */
17083 
17084 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17085 	optp->level = MIB2_IP;
17086 	optp->name = MIB2_IP_ADDR;
17087 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17088 
17089 	rw_enter(&ill_g_lock, RW_READER);
17090 	ill = ILL_START_WALK_V4(&ctx);
17091 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17092 		for (ipif = ill->ill_ipif; ipif != NULL;
17093 		    ipif = ipif->ipif_next) {
17094 			if (ipif->ipif_zoneid != zoneid &&
17095 			    ipif->ipif_zoneid != ALL_ZONES)
17096 				continue;
17097 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17098 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17099 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17100 
17101 			(void) ipif_get_name(ipif,
17102 			    mae.ipAdEntIfIndex.o_bytes,
17103 			    OCTET_LENGTH);
17104 			mae.ipAdEntIfIndex.o_length =
17105 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17106 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17107 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17108 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17109 			mae.ipAdEntInfo.ae_subnet_len =
17110 			    ip_mask_to_plen(ipif->ipif_net_mask);
17111 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17112 			for (bitval = 1;
17113 			    bitval &&
17114 			    !(bitval & ipif->ipif_brd_addr);
17115 			    bitval <<= 1)
17116 				noop;
17117 			mae.ipAdEntBcastAddr = bitval;
17118 			mae.ipAdEntReasmMaxSize = 65535;
17119 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17120 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17121 			mae.ipAdEntInfo.ae_broadcast_addr =
17122 			    ipif->ipif_brd_addr;
17123 			mae.ipAdEntInfo.ae_pp_dst_addr =
17124 			    ipif->ipif_pp_dst_addr;
17125 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17126 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17127 
17128 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17129 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17130 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17131 				    "allocate %u bytes\n",
17132 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17133 			}
17134 		}
17135 	}
17136 	rw_exit(&ill_g_lock);
17137 
17138 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17139 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17140 	    (int)optp->level, (int)optp->name, (int)optp->len));
17141 	qreply(q, mpctl);
17142 	return (mp2ctl);
17143 }
17144 
17145 /* IPv6 address information */
17146 static mblk_t *
17147 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17148 {
17149 	struct opthdr		*optp;
17150 	mblk_t			*mp2ctl;
17151 	mblk_t			*mp_tail = NULL;
17152 	ill_t			*ill;
17153 	ipif_t			*ipif;
17154 	mib2_ipv6AddrEntry_t	mae6;
17155 	zoneid_t		zoneid;
17156 	ill_walk_context_t	ctx;
17157 
17158 	/*
17159 	 * make a copy of the original message
17160 	 */
17161 	mp2ctl = copymsg(mpctl);
17162 
17163 	/* ipv6AddrEntryTable */
17164 
17165 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17166 	optp->level = MIB2_IP6;
17167 	optp->name = MIB2_IP6_ADDR;
17168 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17169 
17170 	rw_enter(&ill_g_lock, RW_READER);
17171 	ill = ILL_START_WALK_V6(&ctx);
17172 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17173 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17174 			if (ipif->ipif_zoneid != zoneid &&
17175 			    ipif->ipif_zoneid != ALL_ZONES)
17176 				continue;
17177 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17178 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17179 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17180 
17181 			(void) ipif_get_name(ipif,
17182 			    mae6.ipv6AddrIfIndex.o_bytes,
17183 			    OCTET_LENGTH);
17184 			mae6.ipv6AddrIfIndex.o_length =
17185 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17186 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17187 			mae6.ipv6AddrPfxLength =
17188 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17189 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17190 			mae6.ipv6AddrInfo.ae_subnet_len =
17191 			    mae6.ipv6AddrPfxLength;
17192 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17193 
17194 			/* Type: stateless(1), stateful(2), unknown(3) */
17195 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17196 				mae6.ipv6AddrType = 1;
17197 			else
17198 				mae6.ipv6AddrType = 2;
17199 			/* Anycast: true(1), false(2) */
17200 			if (ipif->ipif_flags & IPIF_ANYCAST)
17201 				mae6.ipv6AddrAnycastFlag = 1;
17202 			else
17203 				mae6.ipv6AddrAnycastFlag = 2;
17204 
17205 			/*
17206 			 * Address status: preferred(1), deprecated(2),
17207 			 * invalid(3), inaccessible(4), unknown(5)
17208 			 */
17209 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17210 				mae6.ipv6AddrStatus = 3;
17211 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17212 				mae6.ipv6AddrStatus = 2;
17213 			else
17214 				mae6.ipv6AddrStatus = 1;
17215 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17216 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17217 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17218 						ipif->ipif_v6pp_dst_addr;
17219 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17220 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17221 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17222 				(char *)&mae6,
17223 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17224 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17225 				    "allocate %u bytes\n",
17226 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17227 			}
17228 		}
17229 	}
17230 	rw_exit(&ill_g_lock);
17231 
17232 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17233 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17234 	    (int)optp->level, (int)optp->name, (int)optp->len));
17235 	qreply(q, mpctl);
17236 	return (mp2ctl);
17237 }
17238 
17239 /* IPv4 multicast group membership. */
17240 static mblk_t *
17241 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17242 {
17243 	struct opthdr		*optp;
17244 	mblk_t			*mp2ctl;
17245 	ill_t			*ill;
17246 	ipif_t			*ipif;
17247 	ilm_t			*ilm;
17248 	ip_member_t		ipm;
17249 	mblk_t			*mp_tail = NULL;
17250 	ill_walk_context_t	ctx;
17251 	zoneid_t		zoneid;
17252 
17253 	/*
17254 	 * make a copy of the original message
17255 	 */
17256 	mp2ctl = copymsg(mpctl);
17257 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17258 
17259 	/* ipGroupMember table */
17260 	optp = (struct opthdr *)&mpctl->b_rptr[
17261 	    sizeof (struct T_optmgmt_ack)];
17262 	optp->level = MIB2_IP;
17263 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17264 
17265 	rw_enter(&ill_g_lock, RW_READER);
17266 	ill = ILL_START_WALK_V4(&ctx);
17267 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17268 		ILM_WALKER_HOLD(ill);
17269 		for (ipif = ill->ill_ipif; ipif != NULL;
17270 		    ipif = ipif->ipif_next) {
17271 			if (ipif->ipif_zoneid != zoneid &&
17272 			    ipif->ipif_zoneid != ALL_ZONES)
17273 				continue;	/* not this zone */
17274 			(void) ipif_get_name(ipif,
17275 			    ipm.ipGroupMemberIfIndex.o_bytes,
17276 			    OCTET_LENGTH);
17277 			ipm.ipGroupMemberIfIndex.o_length =
17278 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17279 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17280 				ASSERT(ilm->ilm_ipif != NULL);
17281 				ASSERT(ilm->ilm_ill == NULL);
17282 				if (ilm->ilm_ipif != ipif)
17283 					continue;
17284 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17285 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17286 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17287 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17288 				    (char *)&ipm, (int)sizeof (ipm))) {
17289 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17290 					    "failed to allocate %u bytes\n",
17291 						(uint_t)sizeof (ipm)));
17292 				}
17293 			}
17294 		}
17295 		ILM_WALKER_RELE(ill);
17296 	}
17297 	rw_exit(&ill_g_lock);
17298 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17299 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17300 	    (int)optp->level, (int)optp->name, (int)optp->len));
17301 	qreply(q, mpctl);
17302 	return (mp2ctl);
17303 }
17304 
17305 /* IPv6 multicast group membership. */
17306 static mblk_t *
17307 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17308 {
17309 	struct opthdr		*optp;
17310 	mblk_t			*mp2ctl;
17311 	ill_t			*ill;
17312 	ilm_t			*ilm;
17313 	ipv6_member_t		ipm6;
17314 	mblk_t			*mp_tail = NULL;
17315 	ill_walk_context_t	ctx;
17316 	zoneid_t		zoneid;
17317 
17318 	/*
17319 	 * make a copy of the original message
17320 	 */
17321 	mp2ctl = copymsg(mpctl);
17322 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17323 
17324 	/* ip6GroupMember table */
17325 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17326 	optp->level = MIB2_IP6;
17327 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17328 
17329 	rw_enter(&ill_g_lock, RW_READER);
17330 	ill = ILL_START_WALK_V6(&ctx);
17331 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17332 		ILM_WALKER_HOLD(ill);
17333 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17334 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17335 			ASSERT(ilm->ilm_ipif == NULL);
17336 			ASSERT(ilm->ilm_ill != NULL);
17337 			if (ilm->ilm_zoneid != zoneid)
17338 				continue;	/* not this zone */
17339 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17340 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17341 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17342 			if (!snmp_append_data2(mpctl->b_cont,
17343 			    &mp_tail,
17344 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17345 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17346 				    "failed to allocate %u bytes\n",
17347 				    (uint_t)sizeof (ipm6)));
17348 			}
17349 		}
17350 		ILM_WALKER_RELE(ill);
17351 	}
17352 	rw_exit(&ill_g_lock);
17353 
17354 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17355 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17356 	    (int)optp->level, (int)optp->name, (int)optp->len));
17357 	qreply(q, mpctl);
17358 	return (mp2ctl);
17359 }
17360 
17361 /* IP multicast filtered sources */
17362 static mblk_t *
17363 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17364 {
17365 	struct opthdr		*optp;
17366 	mblk_t			*mp2ctl;
17367 	ill_t			*ill;
17368 	ipif_t			*ipif;
17369 	ilm_t			*ilm;
17370 	ip_grpsrc_t		ips;
17371 	mblk_t			*mp_tail = NULL;
17372 	ill_walk_context_t	ctx;
17373 	zoneid_t		zoneid;
17374 	int			i;
17375 	slist_t			*sl;
17376 
17377 	/*
17378 	 * make a copy of the original message
17379 	 */
17380 	mp2ctl = copymsg(mpctl);
17381 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17382 
17383 	/* ipGroupSource table */
17384 	optp = (struct opthdr *)&mpctl->b_rptr[
17385 	    sizeof (struct T_optmgmt_ack)];
17386 	optp->level = MIB2_IP;
17387 	optp->name = EXPER_IP_GROUP_SOURCES;
17388 
17389 	rw_enter(&ill_g_lock, RW_READER);
17390 	ill = ILL_START_WALK_V4(&ctx);
17391 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17392 		ILM_WALKER_HOLD(ill);
17393 		for (ipif = ill->ill_ipif; ipif != NULL;
17394 		    ipif = ipif->ipif_next) {
17395 			if (ipif->ipif_zoneid != zoneid)
17396 				continue;	/* not this zone */
17397 			(void) ipif_get_name(ipif,
17398 			    ips.ipGroupSourceIfIndex.o_bytes,
17399 			    OCTET_LENGTH);
17400 			ips.ipGroupSourceIfIndex.o_length =
17401 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17402 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17403 				ASSERT(ilm->ilm_ipif != NULL);
17404 				ASSERT(ilm->ilm_ill == NULL);
17405 				sl = ilm->ilm_filter;
17406 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17407 					continue;
17408 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17409 				for (i = 0; i < sl->sl_numsrc; i++) {
17410 					if (!IN6_IS_ADDR_V4MAPPED(
17411 					    &sl->sl_addr[i]))
17412 						continue;
17413 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
17414 					    ips.ipGroupSourceAddress);
17415 					if (snmp_append_data2(mpctl->b_cont,
17416 					    &mp_tail, (char *)&ips,
17417 					    (int)sizeof (ips)) == 0) {
17418 						ip1dbg(("ip_snmp_get_mib2_"
17419 						    "ip_group_src: failed to "
17420 						    "allocate %u bytes\n",
17421 						    (uint_t)sizeof (ips)));
17422 					}
17423 				}
17424 			}
17425 		}
17426 		ILM_WALKER_RELE(ill);
17427 	}
17428 	rw_exit(&ill_g_lock);
17429 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17430 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17431 	    (int)optp->level, (int)optp->name, (int)optp->len));
17432 	qreply(q, mpctl);
17433 	return (mp2ctl);
17434 }
17435 
17436 /* IPv6 multicast filtered sources. */
17437 static mblk_t *
17438 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
17439 {
17440 	struct opthdr		*optp;
17441 	mblk_t			*mp2ctl;
17442 	ill_t			*ill;
17443 	ilm_t			*ilm;
17444 	ipv6_grpsrc_t		ips6;
17445 	mblk_t			*mp_tail = NULL;
17446 	ill_walk_context_t	ctx;
17447 	zoneid_t		zoneid;
17448 	int			i;
17449 	slist_t			*sl;
17450 
17451 	/*
17452 	 * make a copy of the original message
17453 	 */
17454 	mp2ctl = copymsg(mpctl);
17455 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17456 
17457 	/* ip6GroupMember table */
17458 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17459 	optp->level = MIB2_IP6;
17460 	optp->name = EXPER_IP6_GROUP_SOURCES;
17461 
17462 	rw_enter(&ill_g_lock, RW_READER);
17463 	ill = ILL_START_WALK_V6(&ctx);
17464 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17465 		ILM_WALKER_HOLD(ill);
17466 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
17467 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17468 			ASSERT(ilm->ilm_ipif == NULL);
17469 			ASSERT(ilm->ilm_ill != NULL);
17470 			sl = ilm->ilm_filter;
17471 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
17472 				continue;
17473 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
17474 			for (i = 0; i < sl->sl_numsrc; i++) {
17475 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
17476 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17477 				    (char *)&ips6, (int)sizeof (ips6))) {
17478 					ip1dbg(("ip_snmp_get_mib2_ip6_"
17479 					    "group_src: failed to allocate "
17480 					    "%u bytes\n",
17481 					    (uint_t)sizeof (ips6)));
17482 				}
17483 			}
17484 		}
17485 		ILM_WALKER_RELE(ill);
17486 	}
17487 	rw_exit(&ill_g_lock);
17488 
17489 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17490 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17491 	    (int)optp->level, (int)optp->name, (int)optp->len));
17492 	qreply(q, mpctl);
17493 	return (mp2ctl);
17494 }
17495 
17496 /* Multicast routing virtual interface table. */
17497 static mblk_t *
17498 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
17499 {
17500 	struct opthdr		*optp;
17501 	mblk_t			*mp2ctl;
17502 
17503 	/*
17504 	 * make a copy of the original message
17505 	 */
17506 	mp2ctl = copymsg(mpctl);
17507 
17508 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17509 	optp->level = EXPER_DVMRP;
17510 	optp->name = EXPER_DVMRP_VIF;
17511 	if (!ip_mroute_vif(mpctl->b_cont)) {
17512 		ip0dbg(("ip_mroute_vif: failed\n"));
17513 	}
17514 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17515 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
17516 	    (int)optp->level, (int)optp->name, (int)optp->len));
17517 	qreply(q, mpctl);
17518 	return (mp2ctl);
17519 }
17520 
17521 /* Multicast routing table. */
17522 static mblk_t *
17523 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
17524 {
17525 	struct opthdr		*optp;
17526 	mblk_t			*mp2ctl;
17527 
17528 	/*
17529 	 * make a copy of the original message
17530 	 */
17531 	mp2ctl = copymsg(mpctl);
17532 
17533 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17534 	optp->level = EXPER_DVMRP;
17535 	optp->name = EXPER_DVMRP_MRT;
17536 	if (!ip_mroute_mrt(mpctl->b_cont)) {
17537 		ip0dbg(("ip_mroute_mrt: failed\n"));
17538 	}
17539 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17540 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
17541 	    (int)optp->level, (int)optp->name, (int)optp->len));
17542 	qreply(q, mpctl);
17543 	return (mp2ctl);
17544 }
17545 
17546 /*
17547  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
17548  * in one IRE walk.
17549  */
17550 static mblk_t *
17551 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
17552 {
17553 	struct opthdr	*optp;
17554 	mblk_t		*mp2ctl;	/* Returned */
17555 	mblk_t		*mp3ctl;	/* nettomedia */
17556 	mblk_t		*mp4ctl;	/* routeattrs */
17557 	iproutedata_t	ird;
17558 	zoneid_t	zoneid;
17559 
17560 	/*
17561 	 * make copies of the original message
17562 	 *	- mp2ctl is returned unchanged to the caller for his use
17563 	 *	- mpctl is sent upstream as ipRouteEntryTable
17564 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
17565 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
17566 	 */
17567 	mp2ctl = copymsg(mpctl);
17568 	mp3ctl = copymsg(mpctl);
17569 	mp4ctl = copymsg(mpctl);
17570 	if (mp3ctl == NULL || mp4ctl == NULL) {
17571 		freemsg(mp4ctl);
17572 		freemsg(mp3ctl);
17573 		freemsg(mp2ctl);
17574 		freemsg(mpctl);
17575 		return (NULL);
17576 	}
17577 
17578 	bzero(&ird, sizeof (ird));
17579 
17580 	ird.ird_route.lp_head = mpctl->b_cont;
17581 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17582 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17583 
17584 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17585 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
17586 	if (zoneid == GLOBAL_ZONEID) {
17587 		/*
17588 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17589 		 * the sys_net_config privilege, it can only run in the global
17590 		 * zone, so we don't display these IREs in the other zones.
17591 		 */
17592 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
17593 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
17594 	}
17595 
17596 	/* ipRouteEntryTable in mpctl */
17597 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17598 	optp->level = MIB2_IP;
17599 	optp->name = MIB2_IP_ROUTE;
17600 	optp->len = msgdsize(ird.ird_route.lp_head);
17601 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17602 	    (int)optp->level, (int)optp->name, (int)optp->len));
17603 	qreply(q, mpctl);
17604 
17605 	/* ipNetToMediaEntryTable in mp3ctl */
17606 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17607 	optp->level = MIB2_IP;
17608 	optp->name = MIB2_IP_MEDIA;
17609 	optp->len = msgdsize(ird.ird_netmedia.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, mp3ctl);
17613 
17614 	/* ipRouteAttributeTable in mp4ctl */
17615 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17616 	optp->level = MIB2_IP;
17617 	optp->name = EXPER_IP_RTATTR;
17618 	optp->len = msgdsize(ird.ird_attrs.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 	if (optp->len == 0)
17622 		freemsg(mp4ctl);
17623 	else
17624 		qreply(q, mp4ctl);
17625 
17626 	return (mp2ctl);
17627 }
17628 
17629 /*
17630  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
17631  * ipv6NetToMediaEntryTable in an NDP walk.
17632  */
17633 static mblk_t *
17634 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17635 {
17636 	struct opthdr	*optp;
17637 	mblk_t		*mp2ctl;	/* Returned */
17638 	mblk_t		*mp3ctl;	/* nettomedia */
17639 	mblk_t		*mp4ctl;	/* routeattrs */
17640 	iproutedata_t	ird;
17641 	zoneid_t	zoneid;
17642 
17643 	/*
17644 	 * make copies of the original message
17645 	 *	- mp2ctl is returned unchanged to the caller for his use
17646 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
17647 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
17648 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
17649 	 */
17650 	mp2ctl = copymsg(mpctl);
17651 	mp3ctl = copymsg(mpctl);
17652 	mp4ctl = copymsg(mpctl);
17653 	if (mp3ctl == NULL || mp4ctl == NULL) {
17654 		freemsg(mp4ctl);
17655 		freemsg(mp3ctl);
17656 		freemsg(mp2ctl);
17657 		freemsg(mpctl);
17658 		return (NULL);
17659 	}
17660 
17661 	bzero(&ird, sizeof (ird));
17662 
17663 	ird.ird_route.lp_head = mpctl->b_cont;
17664 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17665 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17666 
17667 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17668 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
17669 
17670 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17671 	optp->level = MIB2_IP6;
17672 	optp->name = MIB2_IP6_ROUTE;
17673 	optp->len = msgdsize(ird.ird_route.lp_head);
17674 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17675 	    (int)optp->level, (int)optp->name, (int)optp->len));
17676 	qreply(q, mpctl);
17677 
17678 	/* ipv6NetToMediaEntryTable in mp3ctl */
17679 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
17680 
17681 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17682 	optp->level = MIB2_IP6;
17683 	optp->name = MIB2_IP6_MEDIA;
17684 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17685 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17686 	    (int)optp->level, (int)optp->name, (int)optp->len));
17687 	qreply(q, mp3ctl);
17688 
17689 	/* ipv6RouteAttributeTable in mp4ctl */
17690 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17691 	optp->level = MIB2_IP6;
17692 	optp->name = EXPER_IP_RTATTR;
17693 	optp->len = msgdsize(ird.ird_attrs.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 	if (optp->len == 0)
17697 		freemsg(mp4ctl);
17698 	else
17699 		qreply(q, mp4ctl);
17700 
17701 	return (mp2ctl);
17702 }
17703 
17704 /*
17705  * ICMPv6 mib: One per ill
17706  */
17707 static mblk_t *
17708 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17709 {
17710 	struct opthdr		*optp;
17711 	mblk_t			*mp2ctl;
17712 	ill_t			*ill;
17713 	ill_walk_context_t	ctx;
17714 	mblk_t			*mp_tail = NULL;
17715 
17716 	/*
17717 	 * Make a copy of the original message
17718 	 */
17719 	mp2ctl = copymsg(mpctl);
17720 
17721 	/* fixed length IPv6 structure ... */
17722 
17723 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17724 	optp->level = MIB2_IP6;
17725 	optp->name = 0;
17726 	/* Include "unknown interface" ip6_mib */
17727 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17728 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17729 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17730 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17731 	    sizeof (mib2_ipv6IfStatsEntry_t));
17732 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17733 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17734 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17735 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17736 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17737 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17738 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17739 	    (int)sizeof (ip6_mib))) {
17740 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17741 		    (uint_t)sizeof (ip6_mib)));
17742 	}
17743 
17744 	rw_enter(&ill_g_lock, RW_READER);
17745 	ill = ILL_START_WALK_V6(&ctx);
17746 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17747 		ill->ill_ip6_mib->ipv6IfIndex =
17748 		    ill->ill_phyint->phyint_ifindex;
17749 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17750 		    ipv6_forward ? 1 : 2);
17751 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17752 		    ill->ill_max_hops);
17753 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17754 		    sizeof (mib2_ipv6IfStatsEntry_t));
17755 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17756 		    sizeof (mib2_ipv6AddrEntry_t));
17757 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17758 		    sizeof (mib2_ipv6RouteEntry_t));
17759 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17760 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17761 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17762 		    sizeof (ipv6_member_t));
17763 
17764 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17765 		    (char *)ill->ill_ip6_mib,
17766 		    (int)sizeof (*ill->ill_ip6_mib))) {
17767 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17768 				"%u bytes\n",
17769 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17770 		}
17771 	}
17772 	rw_exit(&ill_g_lock);
17773 
17774 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17775 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17776 	    (int)optp->level, (int)optp->name, (int)optp->len));
17777 	qreply(q, mpctl);
17778 	return (mp2ctl);
17779 }
17780 
17781 /*
17782  * ICMPv6 mib: One per ill
17783  */
17784 static mblk_t *
17785 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17786 {
17787 	struct opthdr		*optp;
17788 	mblk_t			*mp2ctl;
17789 	ill_t			*ill;
17790 	ill_walk_context_t	ctx;
17791 	mblk_t			*mp_tail = NULL;
17792 	/*
17793 	 * Make a copy of the original message
17794 	 */
17795 	mp2ctl = copymsg(mpctl);
17796 
17797 	/* fixed length ICMPv6 structure ... */
17798 
17799 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17800 	optp->level = MIB2_ICMP6;
17801 	optp->name = 0;
17802 	/* Include "unknown interface" icmp6_mib */
17803 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17804 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17805 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17806 	    (int)sizeof (icmp6_mib))) {
17807 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17808 		    (uint_t)sizeof (icmp6_mib)));
17809 	}
17810 
17811 	rw_enter(&ill_g_lock, RW_READER);
17812 	ill = ILL_START_WALK_V6(&ctx);
17813 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17814 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17815 		    ill->ill_phyint->phyint_ifindex;
17816 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17817 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17818 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17819 		    (char *)ill->ill_icmp6_mib,
17820 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17821 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17822 			    "%u bytes\n",
17823 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17824 		}
17825 	}
17826 	rw_exit(&ill_g_lock);
17827 
17828 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17829 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17830 	    (int)optp->level, (int)optp->name, (int)optp->len));
17831 	qreply(q, mpctl);
17832 	return (mp2ctl);
17833 }
17834 
17835 /*
17836  * ire_walk routine to create both ipRouteEntryTable and
17837  * ipNetToMediaEntryTable in one IRE walk
17838  */
17839 static void
17840 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
17841 {
17842 	ill_t				*ill;
17843 	ipif_t				*ipif;
17844 	mblk_t				*llmp;
17845 	dl_unitdata_req_t		*dlup;
17846 	mib2_ipRouteEntry_t		*re;
17847 	mib2_ipNetToMediaEntry_t	ntme;
17848 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
17849 	ipaddr_t			gw_addr;
17850 	tsol_ire_gw_secattr_t		*attrp;
17851 	tsol_gc_t			*gc = NULL;
17852 	tsol_gcgrp_t			*gcgrp = NULL;
17853 	uint_t				sacnt = 0;
17854 	int				i;
17855 
17856 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17857 
17858 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
17859 		return;
17860 
17861 	if ((attrp = ire->ire_gw_secattr) != NULL) {
17862 		mutex_enter(&attrp->igsa_lock);
17863 		if ((gc = attrp->igsa_gc) != NULL) {
17864 			gcgrp = gc->gc_grp;
17865 			ASSERT(gcgrp != NULL);
17866 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17867 			sacnt = 1;
17868 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
17869 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17870 			gc = gcgrp->gcgrp_head;
17871 			sacnt = gcgrp->gcgrp_count;
17872 		}
17873 		mutex_exit(&attrp->igsa_lock);
17874 
17875 		/* do nothing if there's no gc to report */
17876 		if (gc == NULL) {
17877 			ASSERT(sacnt == 0);
17878 			if (gcgrp != NULL) {
17879 				/* we might as well drop the lock now */
17880 				rw_exit(&gcgrp->gcgrp_rwlock);
17881 				gcgrp = NULL;
17882 			}
17883 			attrp = NULL;
17884 		}
17885 
17886 		ASSERT(gc == NULL || (gcgrp != NULL &&
17887 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
17888 	}
17889 	ASSERT(sacnt == 0 || gc != NULL);
17890 
17891 	if (sacnt != 0 &&
17892 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
17893 		kmem_free(re, sizeof (*re));
17894 		rw_exit(&gcgrp->gcgrp_rwlock);
17895 		return;
17896 	}
17897 
17898 	/*
17899 	 * Return all IRE types for route table... let caller pick and choose
17900 	 */
17901 	re->ipRouteDest = ire->ire_addr;
17902 	ipif = ire->ire_ipif;
17903 	re->ipRouteIfIndex.o_length = 0;
17904 	if (ire->ire_type == IRE_CACHE) {
17905 		ill = (ill_t *)ire->ire_stq->q_ptr;
17906 		re->ipRouteIfIndex.o_length =
17907 		    ill->ill_name_length == 0 ? 0 :
17908 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17909 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
17910 		    re->ipRouteIfIndex.o_length);
17911 	} else if (ipif != NULL) {
17912 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
17913 		    OCTET_LENGTH);
17914 		re->ipRouteIfIndex.o_length =
17915 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
17916 	}
17917 	re->ipRouteMetric1 = -1;
17918 	re->ipRouteMetric2 = -1;
17919 	re->ipRouteMetric3 = -1;
17920 	re->ipRouteMetric4 = -1;
17921 
17922 	gw_addr = ire->ire_gateway_addr;
17923 
17924 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17925 		re->ipRouteNextHop = ire->ire_src_addr;
17926 	else
17927 		re->ipRouteNextHop = gw_addr;
17928 	/* indirect(4), direct(3), or invalid(2) */
17929 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17930 		re->ipRouteType = 2;
17931 	else
17932 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
17933 	re->ipRouteProto = -1;
17934 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17935 	re->ipRouteMask = ire->ire_mask;
17936 	re->ipRouteMetric5 = -1;
17937 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
17938 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
17939 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17940 	llmp = ire->ire_dlureq_mp;
17941 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
17942 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
17943 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
17944 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17945 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17946 	re->ipRouteInfo.re_flags	= ire->ire_flags;
17947 	re->ipRouteInfo.re_in_ill.o_length = 0;
17948 	if (ire->ire_in_ill != NULL) {
17949 		re->ipRouteInfo.re_in_ill.o_length =
17950 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17951 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17952 		bcopy(ire->ire_in_ill->ill_name,
17953 		    re->ipRouteInfo.re_in_ill.o_bytes,
17954 		    re->ipRouteInfo.re_in_ill.o_length);
17955 	}
17956 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17957 
17958 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
17959 	    (char *)re, (int)sizeof (*re))) {
17960 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17961 		    (uint_t)sizeof (*re)));
17962 	}
17963 
17964 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
17965 		iaeptr->iae_routeidx = ird->ird_idx;
17966 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
17967 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
17968 	}
17969 
17970 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
17971 	    (char *)iae, sacnt * sizeof (*iae))) {
17972 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17973 		    (unsigned)(sacnt * sizeof (*iae))));
17974 	}
17975 
17976 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17977 		goto done;
17978 	/*
17979 	 * only IRE_CACHE entries that are for a directly connected subnet
17980 	 * get appended to net -> phys addr table
17981 	 * (others in arp)
17982 	 */
17983 	ntme.ipNetToMediaIfIndex.o_length = 0;
17984 	ill = ire_to_ill(ire);
17985 	ASSERT(ill != NULL);
17986 	ntme.ipNetToMediaIfIndex.o_length =
17987 	    ill->ill_name_length == 0 ? 0 :
17988 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17989 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17990 		    ntme.ipNetToMediaIfIndex.o_length);
17991 
17992 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17993 	if (llmp) {
17994 		uchar_t *addr;
17995 
17996 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
17997 		/* Remove sap from  address */
17998 		if (ill->ill_sap_length < 0)
17999 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18000 		else
18001 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18002 			    ill->ill_sap_length;
18003 
18004 		ntme.ipNetToMediaPhysAddress.o_length =
18005 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18006 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18007 		    ntme.ipNetToMediaPhysAddress.o_length);
18008 	}
18009 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18010 	/* assume dynamic (may be changed in arp) */
18011 	ntme.ipNetToMediaType = 3;
18012 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18013 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18014 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18015 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18016 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18017 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18018 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18019 		    (uint_t)sizeof (ntme)));
18020 	}
18021 done:
18022 	/* bump route index for next pass */
18023 	ird->ird_idx++;
18024 
18025 	kmem_free(re, sizeof (*re));
18026 	if (sacnt != 0)
18027 		kmem_free(iae, sacnt * sizeof (*iae));
18028 
18029 	if (gcgrp != NULL)
18030 		rw_exit(&gcgrp->gcgrp_rwlock);
18031 }
18032 
18033 /*
18034  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18035  */
18036 static void
18037 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18038 {
18039 	ill_t				*ill;
18040 	ipif_t				*ipif;
18041 	mib2_ipv6RouteEntry_t		*re;
18042 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18043 	in6_addr_t			gw_addr_v6;
18044 	tsol_ire_gw_secattr_t		*attrp;
18045 	tsol_gc_t			*gc = NULL;
18046 	tsol_gcgrp_t			*gcgrp = NULL;
18047 	uint_t				sacnt = 0;
18048 	int				i;
18049 
18050 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18051 
18052 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18053 		return;
18054 
18055 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18056 		mutex_enter(&attrp->igsa_lock);
18057 		if ((gc = attrp->igsa_gc) != NULL) {
18058 			gcgrp = gc->gc_grp;
18059 			ASSERT(gcgrp != NULL);
18060 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18061 			sacnt = 1;
18062 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18063 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18064 			gc = gcgrp->gcgrp_head;
18065 			sacnt = gcgrp->gcgrp_count;
18066 		}
18067 		mutex_exit(&attrp->igsa_lock);
18068 
18069 		/* do nothing if there's no gc to report */
18070 		if (gc == NULL) {
18071 			ASSERT(sacnt == 0);
18072 			if (gcgrp != NULL) {
18073 				/* we might as well drop the lock now */
18074 				rw_exit(&gcgrp->gcgrp_rwlock);
18075 				gcgrp = NULL;
18076 			}
18077 			attrp = NULL;
18078 		}
18079 
18080 		ASSERT(gc == NULL || (gcgrp != NULL &&
18081 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18082 	}
18083 	ASSERT(sacnt == 0 || gc != NULL);
18084 
18085 	if (sacnt != 0 &&
18086 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18087 		kmem_free(re, sizeof (*re));
18088 		rw_exit(&gcgrp->gcgrp_rwlock);
18089 		return;
18090 	}
18091 
18092 	/*
18093 	 * Return all IRE types for route table... let caller pick and choose
18094 	 */
18095 	re->ipv6RouteDest = ire->ire_addr_v6;
18096 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18097 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18098 	re->ipv6RouteIfIndex.o_length = 0;
18099 	ipif = ire->ire_ipif;
18100 	if (ire->ire_type == IRE_CACHE) {
18101 		ill = (ill_t *)ire->ire_stq->q_ptr;
18102 		re->ipv6RouteIfIndex.o_length =
18103 		    ill->ill_name_length == 0 ? 0 :
18104 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18105 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18106 		    re->ipv6RouteIfIndex.o_length);
18107 	} else if (ipif != NULL) {
18108 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18109 		    OCTET_LENGTH);
18110 		re->ipv6RouteIfIndex.o_length =
18111 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18112 	}
18113 
18114 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18115 
18116 	mutex_enter(&ire->ire_lock);
18117 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18118 	mutex_exit(&ire->ire_lock);
18119 
18120 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18121 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18122 	else
18123 		re->ipv6RouteNextHop = gw_addr_v6;
18124 
18125 	/* remote(4), local(3), or discard(2) */
18126 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18127 		re->ipv6RouteType = 2;
18128 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18129 		re->ipv6RouteType = 3;
18130 	else
18131 		re->ipv6RouteType = 4;
18132 
18133 	re->ipv6RouteProtocol	= -1;
18134 	re->ipv6RoutePolicy	= 0;
18135 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18136 	re->ipv6RouteNextHopRDI	= 0;
18137 	re->ipv6RouteWeight	= 0;
18138 	re->ipv6RouteMetric	= 0;
18139 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18140 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18141 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18142 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18143 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18144 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18145 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18146 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18147 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18148 
18149 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18150 	    (char *)re, (int)sizeof (*re))) {
18151 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18152 		    (uint_t)sizeof (*re)));
18153 	}
18154 
18155 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18156 		iaeptr->iae_routeidx = ird->ird_idx;
18157 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18158 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18159 	}
18160 
18161 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18162 	    (char *)iae, sacnt * sizeof (*iae))) {
18163 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18164 		    (unsigned)(sacnt * sizeof (*iae))));
18165 	}
18166 
18167 	/* bump route index for next pass */
18168 	ird->ird_idx++;
18169 
18170 	kmem_free(re, sizeof (*re));
18171 	if (sacnt != 0)
18172 		kmem_free(iae, sacnt * sizeof (*iae));
18173 
18174 	if (gcgrp != NULL)
18175 		rw_exit(&gcgrp->gcgrp_rwlock);
18176 }
18177 
18178 /*
18179  * ndp_walk routine to create ipv6NetToMediaEntryTable
18180  */
18181 static int
18182 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18183 {
18184 	ill_t				*ill;
18185 	mib2_ipv6NetToMediaEntry_t	ntme;
18186 	dl_unitdata_req_t		*dl;
18187 
18188 	ill = nce->nce_ill;
18189 	ASSERT(ill->ill_isv6);
18190 
18191 	/*
18192 	 * Neighbor cache entry attached to IRE with on-link
18193 	 * destination.
18194 	 */
18195 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18196 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18197 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18198 	    (nce->nce_res_mp != NULL)) {
18199 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18200 		ntme.ipv6NetToMediaPhysAddress.o_length =
18201 		    dl->dl_dest_addr_length;
18202 	} else {
18203 		ntme.ipv6NetToMediaPhysAddress.o_length =
18204 		    ill->ill_phys_addr_length;
18205 	}
18206 	if (nce->nce_res_mp != NULL) {
18207 		bcopy((char *)nce->nce_res_mp->b_rptr +
18208 		    NCE_LL_ADDR_OFFSET(ill),
18209 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18210 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18211 	} else {
18212 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18213 		    ill->ill_phys_addr_length);
18214 	}
18215 	/*
18216 	 * Note: Returns ND_* states. Should be:
18217 	 * reachable(1), stale(2), delay(3), probe(4),
18218 	 * invalid(5), unknown(6)
18219 	 */
18220 	ntme.ipv6NetToMediaState = nce->nce_state;
18221 	ntme.ipv6NetToMediaLastUpdated = 0;
18222 
18223 	/* other(1), dynamic(2), static(3), local(4) */
18224 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18225 		ntme.ipv6NetToMediaType = 4;
18226 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18227 		ntme.ipv6NetToMediaType = 1;
18228 	} else {
18229 		ntme.ipv6NetToMediaType = 2;
18230 	}
18231 
18232 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18233 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18234 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18235 		    (uint_t)sizeof (ntme)));
18236 	}
18237 	return (0);
18238 }
18239 
18240 /*
18241  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18242  */
18243 /* ARGSUSED */
18244 int
18245 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18246 {
18247 	switch (level) {
18248 	case MIB2_IP:
18249 	case MIB2_ICMP:
18250 		switch (name) {
18251 		default:
18252 			break;
18253 		}
18254 		return (1);
18255 	default:
18256 		return (1);
18257 	}
18258 }
18259 
18260 /*
18261  * Called before the options are updated to check if this packet will
18262  * be source routed from here.
18263  * This routine assumes that the options are well formed i.e. that they
18264  * have already been checked.
18265  */
18266 static boolean_t
18267 ip_source_routed(ipha_t *ipha)
18268 {
18269 	ipoptp_t	opts;
18270 	uchar_t		*opt;
18271 	uint8_t		optval;
18272 	uint8_t		optlen;
18273 	ipaddr_t	dst;
18274 	ire_t		*ire;
18275 
18276 	if (IS_SIMPLE_IPH(ipha)) {
18277 		ip2dbg(("not source routed\n"));
18278 		return (B_FALSE);
18279 	}
18280 	dst = ipha->ipha_dst;
18281 	for (optval = ipoptp_first(&opts, ipha);
18282 	    optval != IPOPT_EOL;
18283 	    optval = ipoptp_next(&opts)) {
18284 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18285 		opt = opts.ipoptp_cur;
18286 		optlen = opts.ipoptp_len;
18287 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18288 		    optval, optlen));
18289 		switch (optval) {
18290 			uint32_t off;
18291 		case IPOPT_SSRR:
18292 		case IPOPT_LSRR:
18293 			/*
18294 			 * If dst is one of our addresses and there are some
18295 			 * entries left in the source route return (true).
18296 			 */
18297 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18298 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18299 			if (ire == NULL) {
18300 				ip2dbg(("ip_source_routed: not next"
18301 				    " source route 0x%x\n",
18302 				    ntohl(dst)));
18303 				return (B_FALSE);
18304 			}
18305 			ire_refrele(ire);
18306 			off = opt[IPOPT_OFFSET];
18307 			off--;
18308 			if (optlen < IP_ADDR_LEN ||
18309 			    off > optlen - IP_ADDR_LEN) {
18310 				/* End of source route */
18311 				ip1dbg(("ip_source_routed: end of SR\n"));
18312 				return (B_FALSE);
18313 			}
18314 			return (B_TRUE);
18315 		}
18316 	}
18317 	ip2dbg(("not source routed\n"));
18318 	return (B_FALSE);
18319 }
18320 
18321 /*
18322  * Check if the packet contains any source route.
18323  */
18324 static boolean_t
18325 ip_source_route_included(ipha_t *ipha)
18326 {
18327 	ipoptp_t	opts;
18328 	uint8_t		optval;
18329 
18330 	if (IS_SIMPLE_IPH(ipha))
18331 		return (B_FALSE);
18332 	for (optval = ipoptp_first(&opts, ipha);
18333 	    optval != IPOPT_EOL;
18334 	    optval = ipoptp_next(&opts)) {
18335 		switch (optval) {
18336 		case IPOPT_SSRR:
18337 		case IPOPT_LSRR:
18338 			return (B_TRUE);
18339 		}
18340 	}
18341 	return (B_FALSE);
18342 }
18343 
18344 /*
18345  * Called when the IRE expiration timer fires.
18346  */
18347 /* ARGSUSED */
18348 void
18349 ip_trash_timer_expire(void *args)
18350 {
18351 	int	flush_flag = 0;
18352 
18353 	/*
18354 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18355 	 * This lock makes sure that a new invocation of this function
18356 	 * that occurs due to an almost immediate timer firing will not
18357 	 * progress beyond this point until the current invocation is done
18358 	 */
18359 	mutex_enter(&ip_trash_timer_lock);
18360 	ip_ire_expire_id = 0;
18361 	mutex_exit(&ip_trash_timer_lock);
18362 
18363 	/* Periodic timer */
18364 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18365 		/*
18366 		 * Remove all IRE_CACHE entries since they might
18367 		 * contain arp information.
18368 		 */
18369 		flush_flag |= FLUSH_ARP_TIME;
18370 		ip_ire_arp_time_elapsed = 0;
18371 		IP_STAT(ip_ire_arp_timer_expired);
18372 	}
18373 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18374 		/* Remove all redirects */
18375 		flush_flag |= FLUSH_REDIRECT_TIME;
18376 		ip_ire_rd_time_elapsed = 0;
18377 		IP_STAT(ip_ire_redirect_timer_expired);
18378 	}
18379 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18380 		/* Increase path mtu */
18381 		flush_flag |= FLUSH_MTU_TIME;
18382 		ip_ire_pmtu_time_elapsed = 0;
18383 		IP_STAT(ip_ire_pmtu_timer_expired);
18384 	}
18385 	if (flush_flag != 0) {
18386 		/* Walk all IPv4 IRE's and update them */
18387 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
18388 		    ALL_ZONES);
18389 	}
18390 	if (flush_flag & FLUSH_MTU_TIME) {
18391 		/*
18392 		 * Walk all IPv6 IRE's and update them
18393 		 * Note that ARP and redirect timers are not
18394 		 * needed since NUD handles stale entries.
18395 		 */
18396 		flush_flag = FLUSH_MTU_TIME;
18397 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18398 		    ALL_ZONES);
18399 	}
18400 
18401 	ip_ire_arp_time_elapsed += ip_timer_interval;
18402 	ip_ire_rd_time_elapsed += ip_timer_interval;
18403 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
18404 
18405 	/*
18406 	 * Hold the lock to serialize timeout calls and prevent
18407 	 * stale values in ip_ire_expire_id. Otherwise it is possible
18408 	 * for the timer to fire and a new invocation of this function
18409 	 * to start before the return value of timeout has been stored
18410 	 * in ip_ire_expire_id by the current invocation.
18411 	 */
18412 	mutex_enter(&ip_trash_timer_lock);
18413 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
18414 	    MSEC_TO_TICK(ip_timer_interval));
18415 	mutex_exit(&ip_trash_timer_lock);
18416 }
18417 
18418 /*
18419  * Called by the memory allocator subsystem directly, when the system
18420  * is running low on memory.
18421  */
18422 /* ARGSUSED */
18423 void
18424 ip_trash_ire_reclaim(void *args)
18425 {
18426 	ire_cache_count_t icc;
18427 	ire_cache_reclaim_t icr;
18428 	ncc_cache_count_t ncc;
18429 	nce_cache_reclaim_t ncr;
18430 	uint_t delete_cnt;
18431 	/*
18432 	 * Memory reclaim call back.
18433 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
18434 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
18435 	 * entries, determine what fraction to free for
18436 	 * each category of IRE_CACHE entries giving absolute priority
18437 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
18438 	 * entry will be freed unless all offlink entries are freed).
18439 	 */
18440 	icc.icc_total = 0;
18441 	icc.icc_unused = 0;
18442 	icc.icc_offlink = 0;
18443 	icc.icc_pmtu = 0;
18444 	icc.icc_onlink = 0;
18445 	ire_walk(ire_cache_count, (char *)&icc);
18446 
18447 	/*
18448 	 * Free NCEs for IPv6 like the onlink ires.
18449 	 */
18450 	ncc.ncc_total = 0;
18451 	ncc.ncc_host = 0;
18452 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
18453 
18454 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
18455 	    icc.icc_pmtu + icc.icc_onlink);
18456 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
18457 	IP_STAT(ip_trash_ire_reclaim_calls);
18458 	if (delete_cnt == 0)
18459 		return;
18460 	IP_STAT(ip_trash_ire_reclaim_success);
18461 	/* Always delete all unused offlink entries */
18462 	icr.icr_unused = 1;
18463 	if (delete_cnt <= icc.icc_unused) {
18464 		/*
18465 		 * Only need to free unused entries.  In other words,
18466 		 * there are enough unused entries to free to meet our
18467 		 * target number of freed ire cache entries.
18468 		 */
18469 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
18470 		ncr.ncr_host = 0;
18471 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
18472 		/*
18473 		 * Only need to free unused entries, plus a fraction of offlink
18474 		 * entries.  It follows from the first if statement that
18475 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
18476 		 */
18477 		delete_cnt -= icc.icc_unused;
18478 		/* Round up # deleted by truncating fraction */
18479 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
18480 		icr.icr_pmtu = icr.icr_onlink = 0;
18481 		ncr.ncr_host = 0;
18482 	} else if (delete_cnt <=
18483 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
18484 		/*
18485 		 * Free all unused and offlink entries, plus a fraction of
18486 		 * pmtu entries.  It follows from the previous if statement
18487 		 * that icc_pmtu is non-zero, and that
18488 		 * delete_cnt != icc_unused + icc_offlink.
18489 		 */
18490 		icr.icr_offlink = 1;
18491 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
18492 		/* Round up # deleted by truncating fraction */
18493 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
18494 		icr.icr_onlink = 0;
18495 		ncr.ncr_host = 0;
18496 	} else {
18497 		/*
18498 		 * Free all unused, offlink, and pmtu entries, plus a fraction
18499 		 * of onlink entries.  If we're here, then we know that
18500 		 * icc_onlink is non-zero, and that
18501 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
18502 		 */
18503 		icr.icr_offlink = icr.icr_pmtu = 1;
18504 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
18505 		    icc.icc_pmtu;
18506 		/* Round up # deleted by truncating fraction */
18507 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
18508 		/* Using the same delete fraction as for onlink IREs */
18509 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
18510 	}
18511 #ifdef DEBUG
18512 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
18513 	    "fractions %d/%d/%d/%d\n",
18514 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
18515 	    icc.icc_unused, icc.icc_offlink,
18516 	    icc.icc_pmtu, icc.icc_onlink,
18517 	    icr.icr_unused, icr.icr_offlink,
18518 	    icr.icr_pmtu, icr.icr_onlink));
18519 #endif
18520 	ire_walk(ire_cache_reclaim, (char *)&icr);
18521 	if (ncr.ncr_host != 0)
18522 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
18523 		    (uchar_t *)&ncr);
18524 #ifdef DEBUG
18525 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
18526 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
18527 	ire_walk(ire_cache_count, (char *)&icc);
18528 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
18529 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
18530 	    icc.icc_pmtu, icc.icc_onlink));
18531 #endif
18532 }
18533 
18534 /*
18535  * ip_unbind is called when a copy of an unbind request is received from the
18536  * upper level protocol.  We remove this conn from any fanout hash list it is
18537  * on, and zero out the bind information.  No reply is expected up above.
18538  */
18539 mblk_t *
18540 ip_unbind(queue_t *q, mblk_t *mp)
18541 {
18542 	conn_t	*connp = Q_TO_CONN(q);
18543 
18544 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
18545 
18546 	if (is_system_labeled() && connp->conn_anon_port) {
18547 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
18548 		    connp->conn_mlp_type, connp->conn_ulp,
18549 		    ntohs(connp->conn_lport), B_FALSE);
18550 		connp->conn_anon_port = 0;
18551 	}
18552 	connp->conn_mlp_type = mlptSingle;
18553 
18554 	ipcl_hash_remove(connp);
18555 
18556 	ASSERT(mp->b_cont == NULL);
18557 	/*
18558 	 * Convert mp into a T_OK_ACK
18559 	 */
18560 	mp = mi_tpi_ok_ack_alloc(mp);
18561 
18562 	/*
18563 	 * should not happen in practice... T_OK_ACK is smaller than the
18564 	 * original message.
18565 	 */
18566 	if (mp == NULL)
18567 		return (NULL);
18568 
18569 	/*
18570 	 * Don't bzero the ports if its TCP since TCP still needs the
18571 	 * lport to remove it from its own bind hash. TCP will do the
18572 	 * cleanup.
18573 	 */
18574 	if (!IPCL_IS_TCP(connp))
18575 		bzero(&connp->u_port, sizeof (connp->u_port));
18576 
18577 	return (mp);
18578 }
18579 
18580 /*
18581  * Write side put procedure.  Outbound data, IOCTLs, responses from
18582  * resolvers, etc, come down through here.
18583  */
18584 void
18585 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
18586 {
18587 	conn_t		*connp = NULL;
18588 	queue_t		*q = (queue_t *)arg2;
18589 	ipha_t		*ipha;
18590 #define	rptr	((uchar_t *)ipha)
18591 	ire_t		*ire = NULL;
18592 	ire_t		*sctp_ire = NULL;
18593 	uint32_t	v_hlen_tos_len;
18594 	ipaddr_t	dst;
18595 	mblk_t		*first_mp = NULL;
18596 	boolean_t	mctl_present;
18597 	ipsec_out_t	*io;
18598 	int		match_flags;
18599 	ill_t		*attach_ill = NULL;
18600 					/* Bind to IPIF_NOFAILOVER ill etc. */
18601 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
18602 	ipif_t		*dst_ipif;
18603 	boolean_t	multirt_need_resolve = B_FALSE;
18604 	mblk_t		*copy_mp = NULL;
18605 	int		err;
18606 	zoneid_t	zoneid;
18607 	int	adjust;
18608 	uint16_t iplen;
18609 	boolean_t	need_decref = B_FALSE;
18610 	boolean_t	ignore_dontroute = B_FALSE;
18611 	boolean_t	ignore_nexthop = B_FALSE;
18612 	boolean_t	ip_nexthop = B_FALSE;
18613 	ipaddr_t	nexthop_addr;
18614 
18615 #ifdef	_BIG_ENDIAN
18616 #define	V_HLEN	(v_hlen_tos_len >> 24)
18617 #else
18618 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
18619 #endif
18620 
18621 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
18622 	    "ip_wput_start: q %p", q);
18623 
18624 	/*
18625 	 * ip_wput fast path
18626 	 */
18627 
18628 	/* is packet from ARP ? */
18629 	if (q->q_next != NULL)
18630 		goto qnext;
18631 
18632 	connp = (conn_t *)arg;
18633 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
18634 
18635 	/* is queue flow controlled? */
18636 	if ((q->q_first != NULL || connp->conn_draining) &&
18637 	    (caller == IP_WPUT)) {
18638 		ASSERT(!need_decref);
18639 		(void) putq(q, mp);
18640 		return;
18641 	}
18642 
18643 	/* Multidata transmit? */
18644 	if (DB_TYPE(mp) == M_MULTIDATA) {
18645 		/*
18646 		 * We should never get here, since all Multidata messages
18647 		 * originating from tcp should have been directed over to
18648 		 * tcp_multisend() in the first place.
18649 		 */
18650 		BUMP_MIB(&ip_mib, ipOutDiscards);
18651 		freemsg(mp);
18652 		return;
18653 	} else if (DB_TYPE(mp) != M_DATA)
18654 		goto notdata;
18655 
18656 	if (mp->b_flag & MSGHASREF) {
18657 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18658 		mp->b_flag &= ~MSGHASREF;
18659 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
18660 		need_decref = B_TRUE;
18661 	}
18662 	ipha = (ipha_t *)mp->b_rptr;
18663 
18664 	/* is IP header non-aligned or mblk smaller than basic IP header */
18665 #ifndef SAFETY_BEFORE_SPEED
18666 	if (!OK_32PTR(rptr) ||
18667 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
18668 		goto hdrtoosmall;
18669 #endif
18670 
18671 	ASSERT(OK_32PTR(ipha));
18672 
18673 	/*
18674 	 * This function assumes that mp points to an IPv4 packet.  If it's the
18675 	 * wrong version, we'll catch it again in ip_output_v6.
18676 	 *
18677 	 * Note that this is *only* locally-generated output here, and never
18678 	 * forwarded data, and that we need to deal only with transports that
18679 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
18680 	 * label.)
18681 	 */
18682 	if (is_system_labeled() &&
18683 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
18684 	    !connp->conn_ulp_labeled) {
18685 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
18686 		    connp->conn_mac_exempt);
18687 		ipha = (ipha_t *)mp->b_rptr;
18688 		if (err != 0) {
18689 			first_mp = mp;
18690 			if (err == EINVAL)
18691 				goto icmp_parameter_problem;
18692 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
18693 			goto drop_pkt;
18694 		}
18695 		iplen = ntohs(ipha->ipha_length) + adjust;
18696 		ipha->ipha_length = htons(iplen);
18697 	}
18698 
18699 	/*
18700 	 * If there is a policy, try to attach an ipsec_out in
18701 	 * the front. At the end, first_mp either points to a
18702 	 * M_DATA message or IPSEC_OUT message linked to a
18703 	 * M_DATA message. We have to do it now as we might
18704 	 * lose the "conn" if we go through ip_newroute.
18705 	 */
18706 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
18707 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
18708 		    ipha->ipha_protocol)) == NULL)) {
18709 			if (need_decref)
18710 				CONN_DEC_REF(connp);
18711 			return;
18712 		} else {
18713 			ASSERT(mp->b_datap->db_type == M_CTL);
18714 			first_mp = mp;
18715 			mp = mp->b_cont;
18716 			mctl_present = B_TRUE;
18717 		}
18718 	} else {
18719 		first_mp = mp;
18720 		mctl_present = B_FALSE;
18721 	}
18722 
18723 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18724 
18725 	/* is wrong version or IP options present */
18726 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
18727 		goto version_hdrlen_check;
18728 	dst = ipha->ipha_dst;
18729 
18730 	if (connp->conn_nofailover_ill != NULL) {
18731 		attach_ill = conn_get_held_ill(connp,
18732 		    &connp->conn_nofailover_ill, &err);
18733 		if (err == ILL_LOOKUP_FAILED) {
18734 			if (need_decref)
18735 				CONN_DEC_REF(connp);
18736 			freemsg(first_mp);
18737 			return;
18738 		}
18739 	}
18740 
18741 	/* is packet multicast? */
18742 	if (CLASSD(dst))
18743 		goto multicast;
18744 
18745 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
18746 	    (connp->conn_nexthop_set)) {
18747 		/*
18748 		 * If the destination is a broadcast or a loopback
18749 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
18750 		 * through the standard path. But in the case of local
18751 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
18752 		 * the standard path not IP_XMIT_IF.
18753 		 */
18754 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18755 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
18756 		    (ire->ire_type != IRE_LOOPBACK))) {
18757 			if ((connp->conn_dontroute ||
18758 			    connp->conn_nexthop_set) && (ire != NULL) &&
18759 			    (ire->ire_type == IRE_LOCAL))
18760 				goto standard_path;
18761 
18762 			if (ire != NULL) {
18763 				ire_refrele(ire);
18764 				/* No more access to ire */
18765 				ire = NULL;
18766 			}
18767 			/*
18768 			 * bypass routing checks and go directly to
18769 			 * interface.
18770 			 */
18771 			if (connp->conn_dontroute) {
18772 				goto dontroute;
18773 			} else if (connp->conn_nexthop_set) {
18774 				ip_nexthop = B_TRUE;
18775 				nexthop_addr = connp->conn_nexthop_v4;
18776 				goto send_from_ill;
18777 			}
18778 
18779 			/*
18780 			 * If IP_XMIT_IF socket option is set,
18781 			 * then we allow unicast and multicast
18782 			 * packets to go through the ill. It is
18783 			 * quite possible that the destination
18784 			 * is not in the ire cache table and we
18785 			 * do not want to go to ip_newroute()
18786 			 * instead we call ip_newroute_ipif.
18787 			 */
18788 			xmit_ill = conn_get_held_ill(connp,
18789 			    &connp->conn_xmit_if_ill, &err);
18790 			if (err == ILL_LOOKUP_FAILED) {
18791 				if (attach_ill != NULL)
18792 					ill_refrele(attach_ill);
18793 				if (need_decref)
18794 					CONN_DEC_REF(connp);
18795 				freemsg(first_mp);
18796 				return;
18797 			}
18798 			goto send_from_ill;
18799 		}
18800 standard_path:
18801 		/* Must be a broadcast, a loopback or a local ire */
18802 		if (ire != NULL) {
18803 			ire_refrele(ire);
18804 			/* No more access to ire */
18805 			ire = NULL;
18806 		}
18807 	}
18808 
18809 	if (attach_ill != NULL)
18810 		goto send_from_ill;
18811 
18812 	/*
18813 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18814 	 * this for the tcp global queue and listen end point
18815 	 * as it does not really have a real destination to
18816 	 * talk to.  This is also true for SCTP.
18817 	 */
18818 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18819 	    !connp->conn_fully_bound) {
18820 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18821 		if (ire == NULL)
18822 			goto noirefound;
18823 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18824 		    "ip_wput_end: q %p (%S)", q, "end");
18825 
18826 		/*
18827 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18828 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18829 		 */
18830 		if (ire->ire_flags & RTF_MULTIRT) {
18831 
18832 			/*
18833 			 * Force the TTL of multirouted packets if required.
18834 			 * The TTL of such packets is bounded by the
18835 			 * ip_multirt_ttl ndd variable.
18836 			 */
18837 			if ((ip_multirt_ttl > 0) &&
18838 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18839 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18840 				    "(was %d), dst 0x%08x\n",
18841 				    ip_multirt_ttl, ipha->ipha_ttl,
18842 				    ntohl(ire->ire_addr)));
18843 				ipha->ipha_ttl = ip_multirt_ttl;
18844 			}
18845 			/*
18846 			 * We look at this point if there are pending
18847 			 * unresolved routes. ire_multirt_resolvable()
18848 			 * checks in O(n) that all IRE_OFFSUBNET ire
18849 			 * entries for the packet's destination and
18850 			 * flagged RTF_MULTIRT are currently resolved.
18851 			 * If some remain unresolved, we make a copy
18852 			 * of the current message. It will be used
18853 			 * to initiate additional route resolutions.
18854 			 */
18855 			multirt_need_resolve =
18856 			    ire_multirt_need_resolve(ire->ire_addr,
18857 			    MBLK_GETLABEL(first_mp));
18858 			ip2dbg(("ip_wput[TCP]: ire %p, "
18859 			    "multirt_need_resolve %d, first_mp %p\n",
18860 			    (void *)ire, multirt_need_resolve,
18861 			    (void *)first_mp));
18862 			if (multirt_need_resolve) {
18863 				copy_mp = copymsg(first_mp);
18864 				if (copy_mp != NULL) {
18865 					MULTIRT_DEBUG_TAG(copy_mp);
18866 				}
18867 			}
18868 		}
18869 
18870 		ip_wput_ire(q, first_mp, ire, connp, caller);
18871 
18872 		/*
18873 		 * Try to resolve another multiroute if
18874 		 * ire_multirt_need_resolve() deemed it necessary.
18875 		 */
18876 		if (copy_mp != NULL) {
18877 			ip_newroute(q, copy_mp, dst, NULL, connp);
18878 		}
18879 		if (need_decref)
18880 			CONN_DEC_REF(connp);
18881 		return;
18882 	}
18883 
18884 	/*
18885 	 * Access to conn_ire_cache. (protected by conn_lock)
18886 	 *
18887 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18888 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18889 	 * send a packet or two with the IRE_CACHE that is going away.
18890 	 * Access to the ire requires an ire refhold on the ire prior to
18891 	 * its use since an interface unplumb thread may delete the cached
18892 	 * ire and release the refhold at any time.
18893 	 *
18894 	 * Caching an ire in the conn_ire_cache
18895 	 *
18896 	 * o Caching an ire pointer in the conn requires a strict check for
18897 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18898 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18899 	 * in the conn is done after making sure under the bucket lock that the
18900 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18901 	 * caching an ire after the unplumb thread has cleaned up the conn.
18902 	 * If the conn does not send a packet subsequently the unplumb thread
18903 	 * will be hanging waiting for the ire count to drop to zero.
18904 	 *
18905 	 * o We also need to atomically test for a null conn_ire_cache and
18906 	 * set the conn_ire_cache under the the protection of the conn_lock
18907 	 * to avoid races among concurrent threads trying to simultaneously
18908 	 * cache an ire in the conn_ire_cache.
18909 	 */
18910 	mutex_enter(&connp->conn_lock);
18911 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18912 
18913 	if (ire != NULL && ire->ire_addr == dst &&
18914 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18915 
18916 		IRE_REFHOLD(ire);
18917 		mutex_exit(&connp->conn_lock);
18918 
18919 	} else {
18920 		boolean_t cached = B_FALSE;
18921 		connp->conn_ire_cache = NULL;
18922 		mutex_exit(&connp->conn_lock);
18923 		/* Release the old ire */
18924 		if (ire != NULL && sctp_ire == NULL)
18925 			IRE_REFRELE_NOTR(ire);
18926 
18927 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18928 		if (ire == NULL)
18929 			goto noirefound;
18930 		IRE_REFHOLD_NOTR(ire);
18931 
18932 		mutex_enter(&connp->conn_lock);
18933 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18934 		    connp->conn_ire_cache == NULL) {
18935 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18936 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18937 				connp->conn_ire_cache = ire;
18938 				cached = B_TRUE;
18939 			}
18940 			rw_exit(&ire->ire_bucket->irb_lock);
18941 		}
18942 		mutex_exit(&connp->conn_lock);
18943 
18944 		/*
18945 		 * We can continue to use the ire but since it was
18946 		 * not cached, we should drop the extra reference.
18947 		 */
18948 		if (!cached)
18949 			IRE_REFRELE_NOTR(ire);
18950 	}
18951 
18952 
18953 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18954 	    "ip_wput_end: q %p (%S)", q, "end");
18955 
18956 	/*
18957 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18958 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18959 	 */
18960 	if (ire->ire_flags & RTF_MULTIRT) {
18961 
18962 		/*
18963 		 * Force the TTL of multirouted packets if required.
18964 		 * The TTL of such packets is bounded by the
18965 		 * ip_multirt_ttl ndd variable.
18966 		 */
18967 		if ((ip_multirt_ttl > 0) &&
18968 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18969 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18970 			    "(was %d), dst 0x%08x\n",
18971 			    ip_multirt_ttl, ipha->ipha_ttl,
18972 			    ntohl(ire->ire_addr)));
18973 			ipha->ipha_ttl = ip_multirt_ttl;
18974 		}
18975 
18976 		/*
18977 		 * At this point, we check to see if there are any pending
18978 		 * unresolved routes. ire_multirt_resolvable()
18979 		 * checks in O(n) that all IRE_OFFSUBNET ire
18980 		 * entries for the packet's destination and
18981 		 * flagged RTF_MULTIRT are currently resolved.
18982 		 * If some remain unresolved, we make a copy
18983 		 * of the current message. It will be used
18984 		 * to initiate additional route resolutions.
18985 		 */
18986 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
18987 		    MBLK_GETLABEL(first_mp));
18988 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18989 		    "multirt_need_resolve %d, first_mp %p\n",
18990 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18991 		if (multirt_need_resolve) {
18992 			copy_mp = copymsg(first_mp);
18993 			if (copy_mp != NULL) {
18994 				MULTIRT_DEBUG_TAG(copy_mp);
18995 			}
18996 		}
18997 	}
18998 
18999 	ip_wput_ire(q, first_mp, ire, connp, caller);
19000 
19001 	/*
19002 	 * Try to resolve another multiroute if
19003 	 * ire_multirt_resolvable() deemed it necessary
19004 	 */
19005 	if (copy_mp != NULL) {
19006 		ip_newroute(q, copy_mp, dst, NULL, connp);
19007 	}
19008 	if (need_decref)
19009 		CONN_DEC_REF(connp);
19010 	return;
19011 
19012 qnext:
19013 	/*
19014 	 * Upper Level Protocols pass down complete IP datagrams
19015 	 * as M_DATA messages.	Everything else is a sideshow.
19016 	 *
19017 	 * 1) We could be re-entering ip_wput because of ip_neworute
19018 	 *    in which case we could have a IPSEC_OUT message. We
19019 	 *    need to pass through ip_wput like other datagrams and
19020 	 *    hence cannot branch to ip_wput_nondata.
19021 	 *
19022 	 * 2) ARP, AH, ESP, and other clients who are on the module
19023 	 *    instance of IP stream, give us something to deal with.
19024 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19025 	 *
19026 	 * 3) ICMP replies also could come here.
19027 	 */
19028 	if (DB_TYPE(mp) != M_DATA) {
19029 	    notdata:
19030 		if (DB_TYPE(mp) == M_CTL) {
19031 			/*
19032 			 * M_CTL messages are used by ARP, AH and ESP to
19033 			 * communicate with IP. We deal with IPSEC_IN and
19034 			 * IPSEC_OUT here. ip_wput_nondata handles other
19035 			 * cases.
19036 			 */
19037 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19038 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19039 				first_mp = mp->b_cont;
19040 				first_mp->b_flag &= ~MSGHASREF;
19041 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19042 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19043 				CONN_DEC_REF(connp);
19044 				connp = NULL;
19045 			}
19046 			if (ii->ipsec_info_type == IPSEC_IN) {
19047 				/*
19048 				 * Either this message goes back to
19049 				 * IPSEC for further processing or to
19050 				 * ULP after policy checks.
19051 				 */
19052 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19053 				return;
19054 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19055 				io = (ipsec_out_t *)ii;
19056 				if (io->ipsec_out_proc_begin) {
19057 					/*
19058 					 * IPSEC processing has already started.
19059 					 * Complete it.
19060 					 * IPQoS notes: We don't care what is
19061 					 * in ipsec_out_ill_index since this
19062 					 * won't be processed for IPQoS policies
19063 					 * in ipsec_out_process.
19064 					 */
19065 					ipsec_out_process(q, mp, NULL,
19066 					    io->ipsec_out_ill_index);
19067 					return;
19068 				} else {
19069 					connp = (q->q_next != NULL) ?
19070 					    NULL : Q_TO_CONN(q);
19071 					first_mp = mp;
19072 					mp = mp->b_cont;
19073 					mctl_present = B_TRUE;
19074 				}
19075 				zoneid = io->ipsec_out_zoneid;
19076 				ASSERT(zoneid != ALL_ZONES);
19077 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19078 				/*
19079 				 * It's an IPsec control message requesting
19080 				 * an SADB update to be sent to the IPsec
19081 				 * hardware acceleration capable ills.
19082 				 */
19083 				ipsec_ctl_t *ipsec_ctl =
19084 				    (ipsec_ctl_t *)mp->b_rptr;
19085 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19086 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19087 				mblk_t *cmp = mp->b_cont;
19088 
19089 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19090 				ASSERT(cmp != NULL);
19091 
19092 				freeb(mp);
19093 				ill_ipsec_capab_send_all(satype, cmp, sa);
19094 				return;
19095 			} else {
19096 				/*
19097 				 * This must be ARP or special TSOL signaling.
19098 				 */
19099 				ip_wput_nondata(NULL, q, mp, NULL);
19100 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19101 				    "ip_wput_end: q %p (%S)", q, "nondata");
19102 				return;
19103 			}
19104 		} else {
19105 			/*
19106 			 * This must be non-(ARP/AH/ESP) messages.
19107 			 */
19108 			ASSERT(!need_decref);
19109 			ip_wput_nondata(NULL, q, mp, NULL);
19110 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19111 			    "ip_wput_end: q %p (%S)", q, "nondata");
19112 			return;
19113 		}
19114 	} else {
19115 		first_mp = mp;
19116 		mctl_present = B_FALSE;
19117 	}
19118 
19119 	ASSERT(first_mp != NULL);
19120 	/*
19121 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19122 	 * to make sure that this packet goes out on the same interface it
19123 	 * came in. We handle that here.
19124 	 */
19125 	if (mctl_present) {
19126 		uint_t ifindex;
19127 
19128 		io = (ipsec_out_t *)first_mp->b_rptr;
19129 		if (io->ipsec_out_attach_if ||
19130 		    io->ipsec_out_xmit_if ||
19131 		    io->ipsec_out_ip_nexthop) {
19132 			ill_t	*ill;
19133 
19134 			/*
19135 			 * We may have lost the conn context if we are
19136 			 * coming here from ip_newroute(). Copy the
19137 			 * nexthop information.
19138 			 */
19139 			if (io->ipsec_out_ip_nexthop) {
19140 				ip_nexthop = B_TRUE;
19141 				nexthop_addr = io->ipsec_out_nexthop_addr;
19142 
19143 				ipha = (ipha_t *)mp->b_rptr;
19144 				dst = ipha->ipha_dst;
19145 				goto send_from_ill;
19146 			} else {
19147 				ASSERT(io->ipsec_out_ill_index != 0);
19148 				ifindex = io->ipsec_out_ill_index;
19149 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19150 				    NULL, NULL, NULL, NULL);
19151 				/*
19152 				 * ipsec_out_xmit_if bit is used to tell
19153 				 * ip_wput to use the ill to send outgoing data
19154 				 * as we have no conn when data comes from ICMP
19155 				 * error msg routines. Currently this feature is
19156 				 * only used by ip_mrtun_forward routine.
19157 				 */
19158 				if (io->ipsec_out_xmit_if) {
19159 					xmit_ill = ill;
19160 					if (xmit_ill == NULL) {
19161 						ip1dbg(("ip_output:bad ifindex "
19162 						    "for xmit_ill %d\n",
19163 						    ifindex));
19164 						freemsg(first_mp);
19165 						BUMP_MIB(&ip_mib,
19166 						    ipOutDiscards);
19167 						ASSERT(!need_decref);
19168 						return;
19169 					}
19170 					/* Free up the ipsec_out_t mblk */
19171 					ASSERT(first_mp->b_cont == mp);
19172 					first_mp->b_cont = NULL;
19173 					freeb(first_mp);
19174 					/* Just send the IP header+ICMP+data */
19175 					first_mp = mp;
19176 					ipha = (ipha_t *)mp->b_rptr;
19177 					dst = ipha->ipha_dst;
19178 					goto send_from_ill;
19179 				} else {
19180 					attach_ill = ill;
19181 				}
19182 
19183 				if (attach_ill == NULL) {
19184 					ASSERT(xmit_ill == NULL);
19185 					ip1dbg(("ip_output: bad ifindex for "
19186 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19187 					    ifindex));
19188 					freemsg(first_mp);
19189 					BUMP_MIB(&ip_mib, ipOutDiscards);
19190 					ASSERT(!need_decref);
19191 					return;
19192 				}
19193 			}
19194 		}
19195 	}
19196 
19197 	ASSERT(xmit_ill == NULL);
19198 
19199 	/* We have a complete IP datagram heading outbound. */
19200 	ipha = (ipha_t *)mp->b_rptr;
19201 
19202 #ifndef SPEED_BEFORE_SAFETY
19203 	/*
19204 	 * Make sure we have a full-word aligned message and that at least
19205 	 * a simple IP header is accessible in the first message.  If not,
19206 	 * try a pullup.
19207 	 */
19208 	if (!OK_32PTR(rptr) ||
19209 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19210 	    hdrtoosmall:
19211 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19212 			BUMP_MIB(&ip_mib, ipOutDiscards);
19213 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19214 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19215 			if (first_mp == NULL)
19216 				first_mp = mp;
19217 			goto drop_pkt;
19218 		}
19219 
19220 		/* This function assumes that mp points to an IPv4 packet. */
19221 		if (is_system_labeled() && q->q_next == NULL &&
19222 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19223 		    !connp->conn_ulp_labeled) {
19224 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19225 			    &adjust, connp->conn_mac_exempt);
19226 			ipha = (ipha_t *)mp->b_rptr;
19227 			if (first_mp != NULL)
19228 				first_mp->b_cont = mp;
19229 			if (err != 0) {
19230 				if (first_mp == NULL)
19231 					first_mp = mp;
19232 				if (err == EINVAL)
19233 					goto icmp_parameter_problem;
19234 				ip2dbg(("ip_wput: label check failed (%d)\n",
19235 				    err));
19236 				goto drop_pkt;
19237 			}
19238 			iplen = ntohs(ipha->ipha_length) + adjust;
19239 			ipha->ipha_length = htons(iplen);
19240 		}
19241 
19242 		ipha = (ipha_t *)mp->b_rptr;
19243 		if (first_mp == NULL) {
19244 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19245 			/*
19246 			 * If we got here because of "goto hdrtoosmall"
19247 			 * We need to attach a IPSEC_OUT.
19248 			 */
19249 			if (connp->conn_out_enforce_policy) {
19250 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19251 				    NULL, ipha->ipha_protocol)) == NULL)) {
19252 					if (need_decref)
19253 						CONN_DEC_REF(connp);
19254 					return;
19255 				} else {
19256 					ASSERT(mp->b_datap->db_type == M_CTL);
19257 					first_mp = mp;
19258 					mp = mp->b_cont;
19259 					mctl_present = B_TRUE;
19260 				}
19261 			} else {
19262 				first_mp = mp;
19263 				mctl_present = B_FALSE;
19264 			}
19265 		}
19266 	}
19267 #endif
19268 
19269 	/* Most of the code below is written for speed, not readability */
19270 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19271 
19272 	/*
19273 	 * If ip_newroute() fails, we're going to need a full
19274 	 * header for the icmp wraparound.
19275 	 */
19276 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19277 		uint_t	v_hlen;
19278 	    version_hdrlen_check:
19279 		ASSERT(first_mp != NULL);
19280 		v_hlen = V_HLEN;
19281 		/*
19282 		 * siphon off IPv6 packets coming down from transport
19283 		 * layer modules here.
19284 		 * Note: high-order bit carries NUD reachability confirmation
19285 		 */
19286 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19287 			/*
19288 			 * XXX implement a IPv4 and IPv6 packet counter per
19289 			 * conn and switch when ratio exceeds e.g. 10:1
19290 			 */
19291 #ifdef notyet
19292 			if (q->q_next == NULL) /* Avoid ill queue */
19293 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19294 #endif
19295 			BUMP_MIB(&ip_mib, ipOutIPv6);
19296 			ASSERT(xmit_ill == NULL);
19297 			if (attach_ill != NULL)
19298 				ill_refrele(attach_ill);
19299 			if (need_decref)
19300 				mp->b_flag |= MSGHASREF;
19301 			(void) ip_output_v6(connp, first_mp, q, caller);
19302 			return;
19303 		}
19304 
19305 		if ((v_hlen >> 4) != IP_VERSION) {
19306 			BUMP_MIB(&ip_mib, ipOutDiscards);
19307 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19308 			    "ip_wput_end: q %p (%S)", q, "badvers");
19309 			goto drop_pkt;
19310 		}
19311 		/*
19312 		 * Is the header length at least 20 bytes?
19313 		 *
19314 		 * Are there enough bytes accessible in the header?  If
19315 		 * not, try a pullup.
19316 		 */
19317 		v_hlen &= 0xF;
19318 		v_hlen <<= 2;
19319 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19320 			BUMP_MIB(&ip_mib, ipOutDiscards);
19321 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19322 			    "ip_wput_end: q %p (%S)", q, "badlen");
19323 			goto drop_pkt;
19324 		}
19325 		if (v_hlen > (mp->b_wptr - rptr)) {
19326 			if (!pullupmsg(mp, v_hlen)) {
19327 				BUMP_MIB(&ip_mib, ipOutDiscards);
19328 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19329 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19330 				goto drop_pkt;
19331 			}
19332 			ipha = (ipha_t *)mp->b_rptr;
19333 		}
19334 		/*
19335 		 * Move first entry from any source route into ipha_dst and
19336 		 * verify the options
19337 		 */
19338 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19339 			ASSERT(xmit_ill == NULL);
19340 			if (attach_ill != NULL)
19341 				ill_refrele(attach_ill);
19342 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19343 			    "ip_wput_end: q %p (%S)", q, "badopts");
19344 			if (need_decref)
19345 				CONN_DEC_REF(connp);
19346 			return;
19347 		}
19348 	}
19349 	dst = ipha->ipha_dst;
19350 
19351 	/*
19352 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19353 	 * we have to run the packet through ip_newroute which will take
19354 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19355 	 * a resolver, or assigning a default gateway, etc.
19356 	 */
19357 	if (CLASSD(dst)) {
19358 		ipif_t	*ipif;
19359 		uint32_t setsrc = 0;
19360 
19361 	    multicast:
19362 		ASSERT(first_mp != NULL);
19363 		ASSERT(xmit_ill == NULL);
19364 		ip2dbg(("ip_wput: CLASSD\n"));
19365 		if (connp == NULL) {
19366 			/*
19367 			 * Use the first good ipif on the ill.
19368 			 * XXX Should this ever happen? (Appears
19369 			 * to show up with just ppp and no ethernet due
19370 			 * to in.rdisc.)
19371 			 * However, ire_send should be able to
19372 			 * call ip_wput_ire directly.
19373 			 *
19374 			 * XXX Also, this can happen for ICMP and other packets
19375 			 * with multicast source addresses.  Perhaps we should
19376 			 * fix things so that we drop the packet in question,
19377 			 * but for now, just run with it.
19378 			 */
19379 			ill_t *ill = (ill_t *)q->q_ptr;
19380 
19381 			/*
19382 			 * Don't honor attach_if for this case. If ill
19383 			 * is part of the group, ipif could belong to
19384 			 * any ill and we cannot maintain attach_ill
19385 			 * and ipif_ill same anymore and the assert
19386 			 * below would fail.
19387 			 */
19388 			if (mctl_present) {
19389 				io->ipsec_out_ill_index = 0;
19390 				io->ipsec_out_attach_if = B_FALSE;
19391 				ASSERT(attach_ill != NULL);
19392 				ill_refrele(attach_ill);
19393 				attach_ill = NULL;
19394 			}
19395 
19396 			ASSERT(attach_ill == NULL);
19397 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19398 			if (ipif == NULL) {
19399 				if (need_decref)
19400 					CONN_DEC_REF(connp);
19401 				freemsg(first_mp);
19402 				return;
19403 			}
19404 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
19405 			    ntohl(dst), ill->ill_name));
19406 		} else {
19407 			/*
19408 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
19409 			 * IP_XMIT_IF is honoured.
19410 			 * Block comment above this function explains the
19411 			 * locking mechanism used here
19412 			 */
19413 			xmit_ill = conn_get_held_ill(connp,
19414 			    &connp->conn_xmit_if_ill, &err);
19415 			if (err == ILL_LOOKUP_FAILED) {
19416 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
19417 				goto drop_pkt;
19418 			}
19419 			if (xmit_ill == NULL) {
19420 				ipif = conn_get_held_ipif(connp,
19421 				    &connp->conn_multicast_ipif, &err);
19422 				if (err == IPIF_LOOKUP_FAILED) {
19423 					ip1dbg(("ip_wput: No ipif for "
19424 					    "multicast\n"));
19425 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19426 					goto drop_pkt;
19427 				}
19428 			}
19429 			if (xmit_ill != NULL) {
19430 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19431 				if (ipif == NULL) {
19432 					ip1dbg(("ip_wput: No ipif for "
19433 					    "IP_XMIT_IF\n"));
19434 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19435 					goto drop_pkt;
19436 				}
19437 			} else if (ipif == NULL || ipif->ipif_isv6) {
19438 				/*
19439 				 * We must do this ipif determination here
19440 				 * else we could pass through ip_newroute
19441 				 * and come back here without the conn context.
19442 				 *
19443 				 * Note: we do late binding i.e. we bind to
19444 				 * the interface when the first packet is sent.
19445 				 * For performance reasons we do not rebind on
19446 				 * each packet but keep the binding until the
19447 				 * next IP_MULTICAST_IF option.
19448 				 *
19449 				 * conn_multicast_{ipif,ill} are shared between
19450 				 * IPv4 and IPv6 and AF_INET6 sockets can
19451 				 * send both IPv4 and IPv6 packets. Hence
19452 				 * we have to check that "isv6" matches above.
19453 				 */
19454 				if (ipif != NULL)
19455 					ipif_refrele(ipif);
19456 				ipif = ipif_lookup_group(dst, zoneid);
19457 				if (ipif == NULL) {
19458 					ip1dbg(("ip_wput: No ipif for "
19459 					    "multicast\n"));
19460 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19461 					goto drop_pkt;
19462 				}
19463 				err = conn_set_held_ipif(connp,
19464 				    &connp->conn_multicast_ipif, ipif);
19465 				if (err == IPIF_LOOKUP_FAILED) {
19466 					ipif_refrele(ipif);
19467 					ip1dbg(("ip_wput: No ipif for "
19468 					    "multicast\n"));
19469 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19470 					goto drop_pkt;
19471 				}
19472 			}
19473 		}
19474 		ASSERT(!ipif->ipif_isv6);
19475 		/*
19476 		 * As we may lose the conn by the time we reach ip_wput_ire,
19477 		 * we copy conn_multicast_loop and conn_dontroute on to an
19478 		 * ipsec_out. In case if this datagram goes out secure,
19479 		 * we need the ill_index also. Copy that also into the
19480 		 * ipsec_out.
19481 		 */
19482 		if (mctl_present) {
19483 			io = (ipsec_out_t *)first_mp->b_rptr;
19484 			ASSERT(first_mp->b_datap->db_type == M_CTL);
19485 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
19486 		} else {
19487 			ASSERT(mp == first_mp);
19488 			if ((first_mp = allocb(sizeof (ipsec_info_t),
19489 			    BPRI_HI)) == NULL) {
19490 				ipif_refrele(ipif);
19491 				first_mp = mp;
19492 				goto drop_pkt;
19493 			}
19494 			first_mp->b_datap->db_type = M_CTL;
19495 			first_mp->b_wptr += sizeof (ipsec_info_t);
19496 			/* ipsec_out_secure is B_FALSE now */
19497 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
19498 			io = (ipsec_out_t *)first_mp->b_rptr;
19499 			io->ipsec_out_type = IPSEC_OUT;
19500 			io->ipsec_out_len = sizeof (ipsec_out_t);
19501 			io->ipsec_out_use_global_policy = B_TRUE;
19502 			first_mp->b_cont = mp;
19503 			mctl_present = B_TRUE;
19504 		}
19505 		if (attach_ill != NULL) {
19506 			ASSERT(attach_ill == ipif->ipif_ill);
19507 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19508 
19509 			/*
19510 			 * Check if we need an ire that will not be
19511 			 * looked up by anybody else i.e. HIDDEN.
19512 			 */
19513 			if (ill_is_probeonly(attach_ill)) {
19514 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19515 			}
19516 			io->ipsec_out_ill_index =
19517 			    attach_ill->ill_phyint->phyint_ifindex;
19518 			io->ipsec_out_attach_if = B_TRUE;
19519 		} else {
19520 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
19521 			io->ipsec_out_ill_index =
19522 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
19523 		}
19524 		if (connp != NULL) {
19525 			io->ipsec_out_multicast_loop =
19526 			    connp->conn_multicast_loop;
19527 			io->ipsec_out_dontroute = connp->conn_dontroute;
19528 			io->ipsec_out_zoneid = connp->conn_zoneid;
19529 		}
19530 		/*
19531 		 * If the application uses IP_MULTICAST_IF with
19532 		 * different logical addresses of the same ILL, we
19533 		 * need to make sure that the soruce address of
19534 		 * the packet matches the logical IP address used
19535 		 * in the option. We do it by initializing ipha_src
19536 		 * here. This should keep IPSEC also happy as
19537 		 * when we return from IPSEC processing, we don't
19538 		 * have to worry about getting the right address on
19539 		 * the packet. Thus it is sufficient to look for
19540 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
19541 		 * MATCH_IRE_IPIF.
19542 		 *
19543 		 * NOTE : We need to do it for non-secure case also as
19544 		 * this might go out secure if there is a global policy
19545 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
19546 		 * address, the source should be initialized already and
19547 		 * hence we won't be initializing here.
19548 		 *
19549 		 * As we do not have the ire yet, it is possible that
19550 		 * we set the source address here and then later discover
19551 		 * that the ire implies the source address to be assigned
19552 		 * through the RTF_SETSRC flag.
19553 		 * In that case, the setsrc variable will remind us
19554 		 * that overwritting the source address by the one
19555 		 * of the RTF_SETSRC-flagged ire is allowed.
19556 		 */
19557 		if (ipha->ipha_src == INADDR_ANY &&
19558 		    (connp == NULL || !connp->conn_unspec_src)) {
19559 			ipha->ipha_src = ipif->ipif_src_addr;
19560 			setsrc = RTF_SETSRC;
19561 		}
19562 		/*
19563 		 * Find an IRE which matches the destination and the outgoing
19564 		 * queue (i.e. the outgoing interface.)
19565 		 * For loopback use a unicast IP address for
19566 		 * the ire lookup.
19567 		 */
19568 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
19569 		    PHYI_LOOPBACK) {
19570 			dst = ipif->ipif_lcl_addr;
19571 		}
19572 		/*
19573 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
19574 		 * We don't need to lookup ire in ctable as the packet
19575 		 * needs to be sent to the destination through the specified
19576 		 * ill irrespective of ires in the cache table.
19577 		 */
19578 		ire = NULL;
19579 		if (xmit_ill == NULL) {
19580 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
19581 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19582 		}
19583 
19584 		/*
19585 		 * refrele attach_ill as its not needed anymore.
19586 		 */
19587 		if (attach_ill != NULL) {
19588 			ill_refrele(attach_ill);
19589 			attach_ill = NULL;
19590 		}
19591 
19592 		if (ire == NULL) {
19593 			/*
19594 			 * Multicast loopback and multicast forwarding is
19595 			 * done in ip_wput_ire.
19596 			 *
19597 			 * Mark this packet to make it be delivered to
19598 			 * ip_wput_ire after the new ire has been
19599 			 * created.
19600 			 *
19601 			 * The call to ip_newroute_ipif takes into account
19602 			 * the setsrc reminder. In any case, we take care
19603 			 * of the RTF_MULTIRT flag.
19604 			 */
19605 			mp->b_prev = mp->b_next = NULL;
19606 			if (xmit_ill == NULL ||
19607 			    xmit_ill->ill_ipif_up_count > 0) {
19608 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
19609 				    setsrc | RTF_MULTIRT);
19610 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19611 				    "ip_wput_end: q %p (%S)", q, "noire");
19612 			} else {
19613 				freemsg(first_mp);
19614 			}
19615 			ipif_refrele(ipif);
19616 			if (xmit_ill != NULL)
19617 				ill_refrele(xmit_ill);
19618 			if (need_decref)
19619 				CONN_DEC_REF(connp);
19620 			return;
19621 		}
19622 
19623 		ipif_refrele(ipif);
19624 		ipif = NULL;
19625 		ASSERT(xmit_ill == NULL);
19626 
19627 		/*
19628 		 * Honor the RTF_SETSRC flag for multicast packets,
19629 		 * if allowed by the setsrc reminder.
19630 		 */
19631 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
19632 			ipha->ipha_src = ire->ire_src_addr;
19633 		}
19634 
19635 		/*
19636 		 * Unconditionally force the TTL to 1 for
19637 		 * multirouted multicast packets:
19638 		 * multirouted multicast should not cross
19639 		 * multicast routers.
19640 		 */
19641 		if (ire->ire_flags & RTF_MULTIRT) {
19642 			if (ipha->ipha_ttl > 1) {
19643 				ip2dbg(("ip_wput: forcing multicast "
19644 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
19645 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
19646 				ipha->ipha_ttl = 1;
19647 			}
19648 		}
19649 	} else {
19650 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19651 		if ((ire != NULL) && (ire->ire_type &
19652 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
19653 			ignore_dontroute = B_TRUE;
19654 			ignore_nexthop = B_TRUE;
19655 		}
19656 		if (ire != NULL) {
19657 			ire_refrele(ire);
19658 			ire = NULL;
19659 		}
19660 		/*
19661 		 * Guard against coming in from arp in which case conn is NULL.
19662 		 * Also guard against non M_DATA with dontroute set but
19663 		 * destined to local, loopback or broadcast addresses.
19664 		 */
19665 		if (connp != NULL && connp->conn_dontroute &&
19666 		    !ignore_dontroute) {
19667 dontroute:
19668 			/*
19669 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
19670 			 * routing protocols from seeing false direct
19671 			 * connectivity.
19672 			 */
19673 			ipha->ipha_ttl = 1;
19674 			/*
19675 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
19676 			 * along with SO_DONTROUTE, higher precedence is
19677 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
19678 			 */
19679 			if (connp->conn_xmit_if_ill == NULL) {
19680 				/* If suitable ipif not found, drop packet */
19681 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
19682 				if (dst_ipif == NULL) {
19683 					ip1dbg(("ip_wput: no route for "
19684 					    "dst using SO_DONTROUTE\n"));
19685 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19686 					mp->b_prev = mp->b_next = NULL;
19687 					if (first_mp == NULL)
19688 						first_mp = mp;
19689 					goto drop_pkt;
19690 				} else {
19691 					/*
19692 					 * If suitable ipif has been found, set
19693 					 * xmit_ill to the corresponding
19694 					 * ipif_ill because we'll be following
19695 					 * the IP_XMIT_IF logic.
19696 					 */
19697 					ASSERT(xmit_ill == NULL);
19698 					xmit_ill = dst_ipif->ipif_ill;
19699 					mutex_enter(&xmit_ill->ill_lock);
19700 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
19701 						mutex_exit(&xmit_ill->ill_lock);
19702 						xmit_ill = NULL;
19703 						ipif_refrele(dst_ipif);
19704 						ip1dbg(("ip_wput: no route for"
19705 						    " dst using"
19706 						    " SO_DONTROUTE\n"));
19707 						BUMP_MIB(&ip_mib,
19708 						    ipOutNoRoutes);
19709 						mp->b_prev = mp->b_next = NULL;
19710 						if (first_mp == NULL)
19711 							first_mp = mp;
19712 						goto drop_pkt;
19713 					}
19714 					ill_refhold_locked(xmit_ill);
19715 					mutex_exit(&xmit_ill->ill_lock);
19716 					ipif_refrele(dst_ipif);
19717 				}
19718 			}
19719 
19720 		}
19721 		/*
19722 		 * If we are bound to IPIF_NOFAILOVER address, look for
19723 		 * an IRE_CACHE matching the ill.
19724 		 */
19725 send_from_ill:
19726 		if (attach_ill != NULL) {
19727 			ipif_t	*attach_ipif;
19728 
19729 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19730 
19731 			/*
19732 			 * Check if we need an ire that will not be
19733 			 * looked up by anybody else i.e. HIDDEN.
19734 			 */
19735 			if (ill_is_probeonly(attach_ill)) {
19736 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19737 			}
19738 
19739 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
19740 			if (attach_ipif == NULL) {
19741 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
19742 				goto drop_pkt;
19743 			}
19744 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
19745 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19746 			ipif_refrele(attach_ipif);
19747 		} else if (xmit_ill != NULL || (connp != NULL &&
19748 			    connp->conn_xmit_if_ill != NULL)) {
19749 			/*
19750 			 * Mark this packet as originated locally
19751 			 */
19752 			mp->b_prev = mp->b_next = NULL;
19753 			/*
19754 			 * xmit_ill could be NULL if SO_DONTROUTE
19755 			 * is also set.
19756 			 */
19757 			if (xmit_ill == NULL) {
19758 				xmit_ill = conn_get_held_ill(connp,
19759 				    &connp->conn_xmit_if_ill, &err);
19760 				if (err == ILL_LOOKUP_FAILED) {
19761 					if (need_decref)
19762 						CONN_DEC_REF(connp);
19763 					freemsg(first_mp);
19764 					return;
19765 				}
19766 				if (xmit_ill == NULL) {
19767 					if (connp->conn_dontroute)
19768 						goto dontroute;
19769 					goto send_from_ill;
19770 				}
19771 			}
19772 			/*
19773 			 * could be SO_DONTROUTE case also.
19774 			 * check at least one interface is UP as
19775 			 * spcified by this ILL, and then call
19776 			 * ip_newroute_ipif()
19777 			 */
19778 			if (xmit_ill->ill_ipif_up_count > 0) {
19779 				ipif_t *ipif;
19780 
19781 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19782 				if (ipif != NULL) {
19783 					ip_newroute_ipif(q, first_mp, ipif,
19784 					    dst, connp, 0);
19785 					ipif_refrele(ipif);
19786 					ip1dbg(("ip_wput: ip_unicast_if\n"));
19787 				}
19788 			} else {
19789 				freemsg(first_mp);
19790 			}
19791 			ill_refrele(xmit_ill);
19792 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19793 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
19794 			if (need_decref)
19795 				CONN_DEC_REF(connp);
19796 			return;
19797 		} else if (ip_nexthop || (connp != NULL &&
19798 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
19799 			if (!ip_nexthop) {
19800 				ip_nexthop = B_TRUE;
19801 				nexthop_addr = connp->conn_nexthop_v4;
19802 			}
19803 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
19804 			    MATCH_IRE_GW;
19805 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19806 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
19807 		} else {
19808 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19809 		}
19810 		if (!ire) {
19811 			/*
19812 			 * Make sure we don't load spread if this
19813 			 * is IPIF_NOFAILOVER case.
19814 			 */
19815 			if ((attach_ill != NULL) ||
19816 			    (ip_nexthop && !ignore_nexthop)) {
19817 				if (mctl_present) {
19818 					io = (ipsec_out_t *)first_mp->b_rptr;
19819 					ASSERT(first_mp->b_datap->db_type ==
19820 					    M_CTL);
19821 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19822 				} else {
19823 					ASSERT(mp == first_mp);
19824 					first_mp = allocb(
19825 					    sizeof (ipsec_info_t), BPRI_HI);
19826 					if (first_mp == NULL) {
19827 						first_mp = mp;
19828 						goto drop_pkt;
19829 					}
19830 					first_mp->b_datap->db_type = M_CTL;
19831 					first_mp->b_wptr +=
19832 					    sizeof (ipsec_info_t);
19833 					/* ipsec_out_secure is B_FALSE now */
19834 					bzero(first_mp->b_rptr,
19835 					    sizeof (ipsec_info_t));
19836 					io = (ipsec_out_t *)first_mp->b_rptr;
19837 					io->ipsec_out_type = IPSEC_OUT;
19838 					io->ipsec_out_len =
19839 					    sizeof (ipsec_out_t);
19840 					io->ipsec_out_use_global_policy =
19841 					    B_TRUE;
19842 					first_mp->b_cont = mp;
19843 					mctl_present = B_TRUE;
19844 				}
19845 				if (attach_ill != NULL) {
19846 					io->ipsec_out_ill_index = attach_ill->
19847 					    ill_phyint->phyint_ifindex;
19848 					io->ipsec_out_attach_if = B_TRUE;
19849 				} else {
19850 					io->ipsec_out_ip_nexthop = ip_nexthop;
19851 					io->ipsec_out_nexthop_addr =
19852 					    nexthop_addr;
19853 				}
19854 			}
19855 noirefound:
19856 			/*
19857 			 * Mark this packet as having originated on
19858 			 * this machine.  This will be noted in
19859 			 * ire_add_then_send, which needs to know
19860 			 * whether to run it back through ip_wput or
19861 			 * ip_rput following successful resolution.
19862 			 */
19863 			mp->b_prev = NULL;
19864 			mp->b_next = NULL;
19865 			ip_newroute(q, first_mp, dst, NULL, connp);
19866 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19867 			    "ip_wput_end: q %p (%S)", q, "newroute");
19868 			if (attach_ill != NULL)
19869 				ill_refrele(attach_ill);
19870 			if (xmit_ill != NULL)
19871 				ill_refrele(xmit_ill);
19872 			if (need_decref)
19873 				CONN_DEC_REF(connp);
19874 			return;
19875 		}
19876 	}
19877 
19878 	/* We now know where we are going with it. */
19879 
19880 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19881 	    "ip_wput_end: q %p (%S)", q, "end");
19882 
19883 	/*
19884 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19885 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19886 	 */
19887 	if (ire->ire_flags & RTF_MULTIRT) {
19888 		/*
19889 		 * Force the TTL of multirouted packets if required.
19890 		 * The TTL of such packets is bounded by the
19891 		 * ip_multirt_ttl ndd variable.
19892 		 */
19893 		if ((ip_multirt_ttl > 0) &&
19894 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19895 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19896 			    "(was %d), dst 0x%08x\n",
19897 			    ip_multirt_ttl, ipha->ipha_ttl,
19898 			    ntohl(ire->ire_addr)));
19899 			ipha->ipha_ttl = ip_multirt_ttl;
19900 		}
19901 		/*
19902 		 * At this point, we check to see if there are any pending
19903 		 * unresolved routes. ire_multirt_resolvable()
19904 		 * checks in O(n) that all IRE_OFFSUBNET ire
19905 		 * entries for the packet's destination and
19906 		 * flagged RTF_MULTIRT are currently resolved.
19907 		 * If some remain unresolved, we make a copy
19908 		 * of the current message. It will be used
19909 		 * to initiate additional route resolutions.
19910 		 */
19911 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19912 		    MBLK_GETLABEL(first_mp));
19913 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19914 		    "multirt_need_resolve %d, first_mp %p\n",
19915 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19916 		if (multirt_need_resolve) {
19917 			copy_mp = copymsg(first_mp);
19918 			if (copy_mp != NULL) {
19919 				MULTIRT_DEBUG_TAG(copy_mp);
19920 			}
19921 		}
19922 	}
19923 
19924 	ip_wput_ire(q, first_mp, ire, connp, caller);
19925 	/*
19926 	 * Try to resolve another multiroute if
19927 	 * ire_multirt_resolvable() deemed it necessary.
19928 	 * At this point, we need to distinguish
19929 	 * multicasts from other packets. For multicasts,
19930 	 * we call ip_newroute_ipif() and request that both
19931 	 * multirouting and setsrc flags are checked.
19932 	 */
19933 	if (copy_mp != NULL) {
19934 		if (CLASSD(dst)) {
19935 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19936 			if (ipif) {
19937 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19938 				    RTF_SETSRC | RTF_MULTIRT);
19939 				ipif_refrele(ipif);
19940 			} else {
19941 				MULTIRT_DEBUG_UNTAG(copy_mp);
19942 				freemsg(copy_mp);
19943 				copy_mp = NULL;
19944 			}
19945 		} else {
19946 			ip_newroute(q, copy_mp, dst, NULL, connp);
19947 		}
19948 	}
19949 	if (attach_ill != NULL)
19950 		ill_refrele(attach_ill);
19951 	if (xmit_ill != NULL)
19952 		ill_refrele(xmit_ill);
19953 	if (need_decref)
19954 		CONN_DEC_REF(connp);
19955 	return;
19956 
19957 icmp_parameter_problem:
19958 	/* could not have originated externally */
19959 	ASSERT(mp->b_prev == NULL);
19960 	if (ip_hdr_complete(ipha, zoneid) == 0) {
19961 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
19962 		/* it's the IP header length that's in trouble */
19963 		icmp_param_problem(q, first_mp, 0);
19964 		first_mp = NULL;
19965 	}
19966 
19967 drop_pkt:
19968 	ip1dbg(("ip_wput: dropped packet\n"));
19969 	if (ire != NULL)
19970 		ire_refrele(ire);
19971 	if (need_decref)
19972 		CONN_DEC_REF(connp);
19973 	freemsg(first_mp);
19974 	if (attach_ill != NULL)
19975 		ill_refrele(attach_ill);
19976 	if (xmit_ill != NULL)
19977 		ill_refrele(xmit_ill);
19978 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19979 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19980 }
19981 
19982 void
19983 ip_wput(queue_t *q, mblk_t *mp)
19984 {
19985 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19986 }
19987 
19988 /*
19989  *
19990  * The following rules must be observed when accessing any ipif or ill
19991  * that has been cached in the conn. Typically conn_nofailover_ill,
19992  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19993  *
19994  * Access: The ipif or ill pointed to from the conn can be accessed under
19995  * the protection of the conn_lock or after it has been refheld under the
19996  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
19997  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
19998  * The reason for this is that a concurrent unplumb could actually be
19999  * cleaning up these cached pointers by walking the conns and might have
20000  * finished cleaning up the conn in question. The macros check that an
20001  * unplumb has not yet started on the ipif or ill.
20002  *
20003  * Caching: An ipif or ill pointer may be cached in the conn only after
20004  * making sure that an unplumb has not started. So the caching is done
20005  * while holding both the conn_lock and the ill_lock and after using the
20006  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20007  * flag before starting the cleanup of conns.
20008  *
20009  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20010  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20011  * or a reference to the ipif or a reference to an ire that references the
20012  * ipif. An ipif does not change its ill except for failover/failback. Since
20013  * failover/failback happens only after bringing down the ipif and making sure
20014  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20015  * the above holds.
20016  */
20017 ipif_t *
20018 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20019 {
20020 	ipif_t	*ipif;
20021 	ill_t	*ill;
20022 
20023 	*err = 0;
20024 	rw_enter(&ill_g_lock, RW_READER);
20025 	mutex_enter(&connp->conn_lock);
20026 	ipif = *ipifp;
20027 	if (ipif != NULL) {
20028 		ill = ipif->ipif_ill;
20029 		mutex_enter(&ill->ill_lock);
20030 		if (IPIF_CAN_LOOKUP(ipif)) {
20031 			ipif_refhold_locked(ipif);
20032 			mutex_exit(&ill->ill_lock);
20033 			mutex_exit(&connp->conn_lock);
20034 			rw_exit(&ill_g_lock);
20035 			return (ipif);
20036 		} else {
20037 			*err = IPIF_LOOKUP_FAILED;
20038 		}
20039 		mutex_exit(&ill->ill_lock);
20040 	}
20041 	mutex_exit(&connp->conn_lock);
20042 	rw_exit(&ill_g_lock);
20043 	return (NULL);
20044 }
20045 
20046 ill_t *
20047 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20048 {
20049 	ill_t	*ill;
20050 
20051 	*err = 0;
20052 	mutex_enter(&connp->conn_lock);
20053 	ill = *illp;
20054 	if (ill != NULL) {
20055 		mutex_enter(&ill->ill_lock);
20056 		if (ILL_CAN_LOOKUP(ill)) {
20057 			ill_refhold_locked(ill);
20058 			mutex_exit(&ill->ill_lock);
20059 			mutex_exit(&connp->conn_lock);
20060 			return (ill);
20061 		} else {
20062 			*err = ILL_LOOKUP_FAILED;
20063 		}
20064 		mutex_exit(&ill->ill_lock);
20065 	}
20066 	mutex_exit(&connp->conn_lock);
20067 	return (NULL);
20068 }
20069 
20070 static int
20071 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20072 {
20073 	ill_t	*ill;
20074 
20075 	ill = ipif->ipif_ill;
20076 	mutex_enter(&connp->conn_lock);
20077 	mutex_enter(&ill->ill_lock);
20078 	if (IPIF_CAN_LOOKUP(ipif)) {
20079 		*ipifp = ipif;
20080 		mutex_exit(&ill->ill_lock);
20081 		mutex_exit(&connp->conn_lock);
20082 		return (0);
20083 	}
20084 	mutex_exit(&ill->ill_lock);
20085 	mutex_exit(&connp->conn_lock);
20086 	return (IPIF_LOOKUP_FAILED);
20087 }
20088 
20089 /*
20090  * This is called if the outbound datagram needs fragmentation.
20091  *
20092  * NOTE : This function does not ire_refrele the ire argument passed in.
20093  */
20094 static void
20095 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20096 {
20097 	ipha_t		*ipha;
20098 	mblk_t		*mp;
20099 	uint32_t	v_hlen_tos_len;
20100 	uint32_t	max_frag;
20101 	uint32_t	frag_flag;
20102 	boolean_t	dont_use;
20103 
20104 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20105 		mp = ipsec_mp->b_cont;
20106 	} else {
20107 		mp = ipsec_mp;
20108 	}
20109 
20110 	ipha = (ipha_t *)mp->b_rptr;
20111 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20112 
20113 #ifdef	_BIG_ENDIAN
20114 #define	V_HLEN	(v_hlen_tos_len >> 24)
20115 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20116 #else
20117 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20118 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20119 #endif
20120 
20121 #ifndef SPEED_BEFORE_SAFETY
20122 	/*
20123 	 * Check that ipha_length is consistent with
20124 	 * the mblk length
20125 	 */
20126 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20127 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20128 		    LENGTH, msgdsize(mp)));
20129 		freemsg(ipsec_mp);
20130 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20131 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20132 		    "packet length mismatch");
20133 		return;
20134 	}
20135 #endif
20136 	/*
20137 	 * Don't use frag_flag if pre-built packet or source
20138 	 * routed or if multicast (since multicast packets do not solicit
20139 	 * ICMP "packet too big" messages). Get the values of
20140 	 * max_frag and frag_flag atomically by acquiring the
20141 	 * ire_lock.
20142 	 */
20143 	mutex_enter(&ire->ire_lock);
20144 	max_frag = ire->ire_max_frag;
20145 	frag_flag = ire->ire_frag_flag;
20146 	mutex_exit(&ire->ire_lock);
20147 
20148 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20149 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20150 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20151 
20152 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20153 	    (dont_use ? 0 : frag_flag));
20154 }
20155 
20156 /*
20157  * Used for deciding the MSS size for the upper layer. Thus
20158  * we need to check the outbound policy values in the conn.
20159  */
20160 int
20161 conn_ipsec_length(conn_t *connp)
20162 {
20163 	ipsec_latch_t *ipl;
20164 
20165 	ipl = connp->conn_latch;
20166 	if (ipl == NULL)
20167 		return (0);
20168 
20169 	if (ipl->ipl_out_policy == NULL)
20170 		return (0);
20171 
20172 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20173 }
20174 
20175 /*
20176  * Returns an estimate of the IPSEC headers size. This is used if
20177  * we don't want to call into IPSEC to get the exact size.
20178  */
20179 int
20180 ipsec_out_extra_length(mblk_t *ipsec_mp)
20181 {
20182 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20183 	ipsec_action_t *a;
20184 
20185 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20186 	if (!io->ipsec_out_secure)
20187 		return (0);
20188 
20189 	a = io->ipsec_out_act;
20190 
20191 	if (a == NULL) {
20192 		ASSERT(io->ipsec_out_policy != NULL);
20193 		a = io->ipsec_out_policy->ipsp_act;
20194 	}
20195 	ASSERT(a != NULL);
20196 
20197 	return (a->ipa_ovhd);
20198 }
20199 
20200 /*
20201  * Returns an estimate of the IPSEC headers size. This is used if
20202  * we don't want to call into IPSEC to get the exact size.
20203  */
20204 int
20205 ipsec_in_extra_length(mblk_t *ipsec_mp)
20206 {
20207 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20208 	ipsec_action_t *a;
20209 
20210 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20211 
20212 	a = ii->ipsec_in_action;
20213 	return (a == NULL ? 0 : a->ipa_ovhd);
20214 }
20215 
20216 /*
20217  * If there are any source route options, return the true final
20218  * destination. Otherwise, return the destination.
20219  */
20220 ipaddr_t
20221 ip_get_dst(ipha_t *ipha)
20222 {
20223 	ipoptp_t	opts;
20224 	uchar_t		*opt;
20225 	uint8_t		optval;
20226 	uint8_t		optlen;
20227 	ipaddr_t	dst;
20228 	uint32_t off;
20229 
20230 	dst = ipha->ipha_dst;
20231 
20232 	if (IS_SIMPLE_IPH(ipha))
20233 		return (dst);
20234 
20235 	for (optval = ipoptp_first(&opts, ipha);
20236 	    optval != IPOPT_EOL;
20237 	    optval = ipoptp_next(&opts)) {
20238 		opt = opts.ipoptp_cur;
20239 		optlen = opts.ipoptp_len;
20240 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20241 		switch (optval) {
20242 		case IPOPT_SSRR:
20243 		case IPOPT_LSRR:
20244 			off = opt[IPOPT_OFFSET];
20245 			/*
20246 			 * If one of the conditions is true, it means
20247 			 * end of options and dst already has the right
20248 			 * value.
20249 			 */
20250 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20251 				off = optlen - IP_ADDR_LEN;
20252 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20253 			}
20254 			return (dst);
20255 		default:
20256 			break;
20257 		}
20258 	}
20259 
20260 	return (dst);
20261 }
20262 
20263 mblk_t *
20264 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20265     conn_t *connp, boolean_t unspec_src)
20266 {
20267 	ipsec_out_t	*io;
20268 	mblk_t		*first_mp;
20269 	boolean_t policy_present;
20270 
20271 	first_mp = mp;
20272 	if (mp->b_datap->db_type == M_CTL) {
20273 		io = (ipsec_out_t *)first_mp->b_rptr;
20274 		/*
20275 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20276 		 *
20277 		 * 1) There is per-socket policy (including cached global
20278 		 *    policy).
20279 		 * 2) There is no per-socket policy, but it is
20280 		 *    a multicast packet that needs to go out
20281 		 *    on a specific interface. This is the case
20282 		 *    where (ip_wput and ip_wput_multicast) attaches
20283 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20284 		 *
20285 		 * In case (2) we check with global policy to
20286 		 * see if there is a match and set the ill_index
20287 		 * appropriately so that we can lookup the ire
20288 		 * properly in ip_wput_ipsec_out.
20289 		 */
20290 
20291 		/*
20292 		 * ipsec_out_use_global_policy is set to B_FALSE
20293 		 * in ipsec_in_to_out(). Refer to that function for
20294 		 * details.
20295 		 */
20296 		if ((io->ipsec_out_latch == NULL) &&
20297 		    (io->ipsec_out_use_global_policy)) {
20298 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20299 			    ire, connp, unspec_src));
20300 		}
20301 		if (!io->ipsec_out_secure) {
20302 			/*
20303 			 * If this is not a secure packet, drop
20304 			 * the IPSEC_OUT mp and treat it as a clear
20305 			 * packet. This happens when we are sending
20306 			 * a ICMP reply back to a clear packet. See
20307 			 * ipsec_in_to_out() for details.
20308 			 */
20309 			mp = first_mp->b_cont;
20310 			freeb(first_mp);
20311 		}
20312 		return (mp);
20313 	}
20314 	/*
20315 	 * See whether we need to attach a global policy here. We
20316 	 * don't depend on the conn (as it could be null) for deciding
20317 	 * what policy this datagram should go through because it
20318 	 * should have happened in ip_wput if there was some
20319 	 * policy. This normally happens for connections which are not
20320 	 * fully bound preventing us from caching policies in
20321 	 * ip_bind. Packets coming from the TCP listener/global queue
20322 	 * - which are non-hard_bound - could also be affected by
20323 	 * applying policy here.
20324 	 *
20325 	 * If this packet is coming from tcp global queue or listener,
20326 	 * we will be applying policy here.  This may not be *right*
20327 	 * if these packets are coming from the detached connection as
20328 	 * it could have gone in clear before. This happens only if a
20329 	 * TCP connection started when there is no policy and somebody
20330 	 * added policy before it became detached. Thus packets of the
20331 	 * detached connection could go out secure and the other end
20332 	 * would drop it because it will be expecting in clear. The
20333 	 * converse is not true i.e if somebody starts a TCP
20334 	 * connection and deletes the policy, all the packets will
20335 	 * still go out with the policy that existed before deleting
20336 	 * because ip_unbind sends up policy information which is used
20337 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20338 	 * TCP to attach a dummy IPSEC_OUT and set
20339 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20340 	 * affect performance for normal cases, we are not doing it.
20341 	 * Thus, set policy before starting any TCP connections.
20342 	 *
20343 	 * NOTE - We might apply policy even for a hard bound connection
20344 	 * - for which we cached policy in ip_bind - if somebody added
20345 	 * global policy after we inherited the policy in ip_bind.
20346 	 * This means that the packets that were going out in clear
20347 	 * previously would start going secure and hence get dropped
20348 	 * on the other side. To fix this, TCP attaches a dummy
20349 	 * ipsec_out and make sure that we don't apply global policy.
20350 	 */
20351 	if (ipha != NULL)
20352 		policy_present = ipsec_outbound_v4_policy_present;
20353 	else
20354 		policy_present = ipsec_outbound_v6_policy_present;
20355 	if (!policy_present)
20356 		return (mp);
20357 
20358 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20359 }
20360 
20361 ire_t *
20362 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20363 {
20364 	ipaddr_t addr;
20365 	ire_t *save_ire;
20366 	irb_t *irb;
20367 	ill_group_t *illgrp;
20368 	int	err;
20369 
20370 	save_ire = ire;
20371 	addr = ire->ire_addr;
20372 
20373 	ASSERT(ire->ire_type == IRE_BROADCAST);
20374 
20375 	illgrp = connp->conn_outgoing_ill->ill_group;
20376 	if (illgrp == NULL) {
20377 		*conn_outgoing_ill = conn_get_held_ill(connp,
20378 		    &connp->conn_outgoing_ill, &err);
20379 		if (err == ILL_LOOKUP_FAILED) {
20380 			ire_refrele(save_ire);
20381 			return (NULL);
20382 		}
20383 		return (save_ire);
20384 	}
20385 	/*
20386 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20387 	 * If it is part of the group, we need to send on the ire
20388 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20389 	 * to this group. This is okay as IP_BOUND_IF really means
20390 	 * any ill in the group. We depend on the fact that the
20391 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20392 	 * if such an ire exists. This is possible only if you have
20393 	 * at least one ill in the group that has not failed.
20394 	 *
20395 	 * First get to the ire that matches the address and group.
20396 	 *
20397 	 * We don't look for an ire with a matching zoneid because a given zone
20398 	 * won't always have broadcast ires on all ills in the group.
20399 	 */
20400 	irb = ire->ire_bucket;
20401 	rw_enter(&irb->irb_lock, RW_READER);
20402 	if (ire->ire_marks & IRE_MARK_NORECV) {
20403 		/*
20404 		 * If the current zone only has an ire broadcast for this
20405 		 * address marked NORECV, the ire we want is ahead in the
20406 		 * bucket, so we look it up deliberately ignoring the zoneid.
20407 		 */
20408 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
20409 			if (ire->ire_addr != addr)
20410 				continue;
20411 			/* skip over deleted ires */
20412 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
20413 				continue;
20414 		}
20415 	}
20416 	while (ire != NULL) {
20417 		/*
20418 		 * If a new interface is coming up, we could end up
20419 		 * seeing the loopback ire and the non-loopback ire
20420 		 * may not have been added yet. So check for ire_stq
20421 		 */
20422 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
20423 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
20424 			break;
20425 		}
20426 		ire = ire->ire_next;
20427 	}
20428 	if (ire != NULL && ire->ire_addr == addr &&
20429 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
20430 		IRE_REFHOLD(ire);
20431 		rw_exit(&irb->irb_lock);
20432 		ire_refrele(save_ire);
20433 		*conn_outgoing_ill = ire_to_ill(ire);
20434 		/*
20435 		 * Refhold the ill to make the conn_outgoing_ill
20436 		 * independent of the ire. ip_wput_ire goes in a loop
20437 		 * and may refrele the ire. Since we have an ire at this
20438 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
20439 		 */
20440 		ill_refhold(*conn_outgoing_ill);
20441 		return (ire);
20442 	}
20443 	rw_exit(&irb->irb_lock);
20444 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
20445 	/*
20446 	 * If we can't find a suitable ire, return the original ire.
20447 	 */
20448 	return (save_ire);
20449 }
20450 
20451 /*
20452  * This function does the ire_refrele of the ire passed in as the
20453  * argument. As this function looks up more ires i.e broadcast ires,
20454  * it needs to REFRELE them. Currently, for simplicity we don't
20455  * differentiate the one passed in and looked up here. We always
20456  * REFRELE.
20457  * IPQoS Notes:
20458  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
20459  * IPSec packets are done in ipsec_out_process.
20460  *
20461  */
20462 void
20463 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
20464 {
20465 	ipha_t		*ipha;
20466 #define	rptr	((uchar_t *)ipha)
20467 	mblk_t		*mp1;
20468 	queue_t		*stq;
20469 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
20470 	uint32_t	v_hlen_tos_len;
20471 	uint32_t	ttl_protocol;
20472 	ipaddr_t	src;
20473 	ipaddr_t	dst;
20474 	uint32_t	cksum;
20475 	ipaddr_t	orig_src;
20476 	ire_t		*ire1;
20477 	mblk_t		*next_mp;
20478 	uint_t		hlen;
20479 	uint16_t	*up;
20480 	uint32_t	max_frag = ire->ire_max_frag;
20481 	ill_t		*ill = ire_to_ill(ire);
20482 	int		clusterwide;
20483 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
20484 	int		ipsec_len;
20485 	mblk_t		*first_mp;
20486 	ipsec_out_t	*io;
20487 	boolean_t	conn_dontroute;		/* conn value for multicast */
20488 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
20489 	boolean_t	multicast_forward;	/* Should we forward ? */
20490 	boolean_t	unspec_src;
20491 	ill_t		*conn_outgoing_ill = NULL;
20492 	ill_t		*ire_ill;
20493 	ill_t		*ire1_ill;
20494 	uint32_t 	ill_index = 0;
20495 	boolean_t	multirt_send = B_FALSE;
20496 	int		err;
20497 	zoneid_t	zoneid;
20498 
20499 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
20500 	    "ip_wput_ire_start: q %p", q);
20501 
20502 	multicast_forward = B_FALSE;
20503 	unspec_src = (connp != NULL && connp->conn_unspec_src);
20504 
20505 	if (ire->ire_flags & RTF_MULTIRT) {
20506 		/*
20507 		 * Multirouting case. The bucket where ire is stored
20508 		 * probably holds other RTF_MULTIRT flagged ire
20509 		 * to the destination. In this call to ip_wput_ire,
20510 		 * we attempt to send the packet through all
20511 		 * those ires. Thus, we first ensure that ire is the
20512 		 * first RTF_MULTIRT ire in the bucket,
20513 		 * before walking the ire list.
20514 		 */
20515 		ire_t *first_ire;
20516 		irb_t *irb = ire->ire_bucket;
20517 		ASSERT(irb != NULL);
20518 
20519 		/* Make sure we do not omit any multiroute ire. */
20520 		IRB_REFHOLD(irb);
20521 		for (first_ire = irb->irb_ire;
20522 		    first_ire != NULL;
20523 		    first_ire = first_ire->ire_next) {
20524 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
20525 			    (first_ire->ire_addr == ire->ire_addr) &&
20526 			    !(first_ire->ire_marks &
20527 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
20528 				break;
20529 		}
20530 
20531 		if ((first_ire != NULL) && (first_ire != ire)) {
20532 			IRE_REFHOLD(first_ire);
20533 			ire_refrele(ire);
20534 			ire = first_ire;
20535 			ill = ire_to_ill(ire);
20536 		}
20537 		IRB_REFRELE(irb);
20538 	}
20539 
20540 	/*
20541 	 * conn_outgoing_ill is used only in the broadcast loop.
20542 	 * for performance we don't grab the mutexs in the fastpath
20543 	 */
20544 	if ((connp != NULL) &&
20545 	    (connp->conn_xmit_if_ill == NULL) &&
20546 	    (ire->ire_type == IRE_BROADCAST) &&
20547 	    ((connp->conn_nofailover_ill != NULL) ||
20548 	    (connp->conn_outgoing_ill != NULL))) {
20549 		/*
20550 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
20551 		 * option. So, see if this endpoint is bound to a
20552 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
20553 		 * that if the interface is failed, we will still send
20554 		 * the packet on the same ill which is what we want.
20555 		 */
20556 		conn_outgoing_ill = conn_get_held_ill(connp,
20557 		    &connp->conn_nofailover_ill, &err);
20558 		if (err == ILL_LOOKUP_FAILED) {
20559 			ire_refrele(ire);
20560 			freemsg(mp);
20561 			return;
20562 		}
20563 		if (conn_outgoing_ill == NULL) {
20564 			/*
20565 			 * Choose a good ill in the group to send the
20566 			 * packets on.
20567 			 */
20568 			ire = conn_set_outgoing_ill(connp, ire,
20569 			    &conn_outgoing_ill);
20570 			if (ire == NULL) {
20571 				freemsg(mp);
20572 				return;
20573 			}
20574 		}
20575 	}
20576 
20577 	if (mp->b_datap->db_type != M_CTL) {
20578 		ipha = (ipha_t *)mp->b_rptr;
20579 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
20580 	} else {
20581 		io = (ipsec_out_t *)mp->b_rptr;
20582 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20583 		zoneid = io->ipsec_out_zoneid;
20584 		ASSERT(zoneid != ALL_ZONES);
20585 		ipha = (ipha_t *)mp->b_cont->b_rptr;
20586 		dst = ipha->ipha_dst;
20587 		/*
20588 		 * For the multicast case, ipsec_out carries conn_dontroute and
20589 		 * conn_multicast_loop as conn may not be available here. We
20590 		 * need this for multicast loopback and forwarding which is done
20591 		 * later in the code.
20592 		 */
20593 		if (CLASSD(dst)) {
20594 			conn_dontroute = io->ipsec_out_dontroute;
20595 			conn_multicast_loop = io->ipsec_out_multicast_loop;
20596 			/*
20597 			 * If conn_dontroute is not set or conn_multicast_loop
20598 			 * is set, we need to do forwarding/loopback. For
20599 			 * datagrams from ip_wput_multicast, conn_dontroute is
20600 			 * set to B_TRUE and conn_multicast_loop is set to
20601 			 * B_FALSE so that we neither do forwarding nor
20602 			 * loopback.
20603 			 */
20604 			if (!conn_dontroute || conn_multicast_loop)
20605 				multicast_forward = B_TRUE;
20606 		}
20607 	}
20608 
20609 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
20610 	    ire->ire_zoneid != ALL_ZONES) {
20611 		/*
20612 		 * When a zone sends a packet to another zone, we try to deliver
20613 		 * the packet under the same conditions as if the destination
20614 		 * was a real node on the network. To do so, we look for a
20615 		 * matching route in the forwarding table.
20616 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
20617 		 * ip_newroute() does.
20618 		 */
20619 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
20620 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
20621 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
20622 		if (src_ire != NULL &&
20623 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
20624 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
20625 				ipha->ipha_src = src_ire->ire_src_addr;
20626 			ire_refrele(src_ire);
20627 		} else {
20628 			ire_refrele(ire);
20629 			if (conn_outgoing_ill != NULL)
20630 				ill_refrele(conn_outgoing_ill);
20631 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
20632 			if (src_ire != NULL) {
20633 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
20634 					ire_refrele(src_ire);
20635 					freemsg(mp);
20636 					return;
20637 				}
20638 				ire_refrele(src_ire);
20639 			}
20640 			if (ip_hdr_complete(ipha, zoneid)) {
20641 				/* Failed */
20642 				freemsg(mp);
20643 				return;
20644 			}
20645 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
20646 			return;
20647 		}
20648 	}
20649 
20650 	if (mp->b_datap->db_type == M_CTL ||
20651 	    ipsec_outbound_v4_policy_present) {
20652 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
20653 		    unspec_src);
20654 		if (mp == NULL) {
20655 			ire_refrele(ire);
20656 			if (conn_outgoing_ill != NULL)
20657 				ill_refrele(conn_outgoing_ill);
20658 			return;
20659 		}
20660 	}
20661 
20662 	first_mp = mp;
20663 	ipsec_len = 0;
20664 
20665 	if (first_mp->b_datap->db_type == M_CTL) {
20666 		io = (ipsec_out_t *)first_mp->b_rptr;
20667 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20668 		mp = first_mp->b_cont;
20669 		ipsec_len = ipsec_out_extra_length(first_mp);
20670 		ASSERT(ipsec_len >= 0);
20671 		zoneid = io->ipsec_out_zoneid;
20672 		ASSERT(zoneid != ALL_ZONES);
20673 
20674 		/*
20675 		 * Drop M_CTL here if IPsec processing is not needed.
20676 		 * (Non-IPsec use of M_CTL extracted any information it
20677 		 * needed above).
20678 		 */
20679 		if (ipsec_len == 0) {
20680 			freeb(first_mp);
20681 			first_mp = mp;
20682 		}
20683 	}
20684 
20685 	/*
20686 	 * Fast path for ip_wput_ire
20687 	 */
20688 
20689 	ipha = (ipha_t *)mp->b_rptr;
20690 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20691 	dst = ipha->ipha_dst;
20692 
20693 	/*
20694 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
20695 	 * if the socket is a SOCK_RAW type. The transport checksum should
20696 	 * be provided in the pre-built packet, so we don't need to compute it.
20697 	 * Also, other application set flags, like DF, should not be altered.
20698 	 * Other transport MUST pass down zero.
20699 	 */
20700 	ip_hdr_included = ipha->ipha_ident;
20701 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20702 
20703 	if (CLASSD(dst)) {
20704 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
20705 		    ntohl(dst),
20706 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
20707 		    ntohl(ire->ire_addr)));
20708 	}
20709 
20710 /* Macros to extract header fields from data already in registers */
20711 #ifdef	_BIG_ENDIAN
20712 #define	V_HLEN	(v_hlen_tos_len >> 24)
20713 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20714 #define	PROTO	(ttl_protocol & 0xFF)
20715 #else
20716 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20717 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20718 #define	PROTO	(ttl_protocol >> 8)
20719 #endif
20720 
20721 
20722 	orig_src = src = ipha->ipha_src;
20723 	/* (The loop back to "another" is explained down below.) */
20724 another:;
20725 	/*
20726 	 * Assign an ident value for this packet.  We assign idents on
20727 	 * a per destination basis out of the IRE.  There could be
20728 	 * other threads targeting the same destination, so we have to
20729 	 * arrange for a atomic increment.  Note that we use a 32-bit
20730 	 * atomic add because it has better performance than its
20731 	 * 16-bit sibling.
20732 	 *
20733 	 * If running in cluster mode and if the source address
20734 	 * belongs to a replicated service then vector through
20735 	 * cl_inet_ipident vector to allocate ip identifier
20736 	 * NOTE: This is a contract private interface with the
20737 	 * clustering group.
20738 	 */
20739 	clusterwide = 0;
20740 	if (cl_inet_ipident) {
20741 		ASSERT(cl_inet_isclusterwide);
20742 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20743 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
20744 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
20745 			    AF_INET, (uint8_t *)(uintptr_t)src,
20746 			    (uint8_t *)(uintptr_t)dst);
20747 			clusterwide = 1;
20748 		}
20749 	}
20750 	if (!clusterwide) {
20751 		ipha->ipha_ident =
20752 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
20753 	}
20754 
20755 #ifndef _BIG_ENDIAN
20756 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20757 #endif
20758 
20759 	/*
20760 	 * Set source address unless sent on an ill or conn_unspec_src is set.
20761 	 * This is needed to obey conn_unspec_src when packets go through
20762 	 * ip_newroute + arp.
20763 	 * Assumes ip_newroute{,_multi} sets the source address as well.
20764 	 */
20765 	if (src == INADDR_ANY && !unspec_src) {
20766 		/*
20767 		 * Assign the appropriate source address from the IRE if none
20768 		 * was specified.
20769 		 */
20770 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
20771 
20772 		/*
20773 		 * With IP multipathing, broadcast packets are sent on the ire
20774 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
20775 		 * the group. However, this ire might not be in the same zone so
20776 		 * we can't always use its source address. We look for a
20777 		 * broadcast ire in the same group and in the right zone.
20778 		 */
20779 		if (ire->ire_type == IRE_BROADCAST &&
20780 		    ire->ire_zoneid != zoneid) {
20781 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
20782 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
20783 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
20784 			if (src_ire != NULL) {
20785 				src = src_ire->ire_src_addr;
20786 				ire_refrele(src_ire);
20787 			} else {
20788 				ire_refrele(ire);
20789 				if (conn_outgoing_ill != NULL)
20790 					ill_refrele(conn_outgoing_ill);
20791 				freemsg(first_mp);
20792 				BUMP_MIB(&ip_mib, ipOutDiscards);
20793 				return;
20794 			}
20795 		} else {
20796 			src = ire->ire_src_addr;
20797 		}
20798 
20799 		if (connp == NULL) {
20800 			ip1dbg(("ip_wput_ire: no connp and no src "
20801 			    "address for dst 0x%x, using src 0x%x\n",
20802 			    ntohl(dst),
20803 			    ntohl(src)));
20804 		}
20805 		ipha->ipha_src = src;
20806 	}
20807 	stq = ire->ire_stq;
20808 
20809 	/*
20810 	 * We only allow ire chains for broadcasts since there will
20811 	 * be multiple IRE_CACHE entries for the same multicast
20812 	 * address (one per ipif).
20813 	 */
20814 	next_mp = NULL;
20815 
20816 	/* broadcast packet */
20817 	if (ire->ire_type == IRE_BROADCAST)
20818 		goto broadcast;
20819 
20820 	/* loopback ? */
20821 	if (stq == NULL)
20822 		goto nullstq;
20823 
20824 	/* The ill_index for outbound ILL */
20825 	ill_index = Q_TO_INDEX(stq);
20826 
20827 	BUMP_MIB(&ip_mib, ipOutRequests);
20828 	ttl_protocol = ((uint16_t *)ipha)[4];
20829 
20830 	/* pseudo checksum (do it in parts for IP header checksum) */
20831 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20832 
20833 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20834 		queue_t *dev_q = stq->q_next;
20835 
20836 		/* flow controlled */
20837 		if ((dev_q->q_next || dev_q->q_first) &&
20838 		    !canput(dev_q))
20839 			goto blocked;
20840 		if ((PROTO == IPPROTO_UDP) &&
20841 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20842 			hlen = (V_HLEN & 0xF) << 2;
20843 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20844 			if (*up != 0) {
20845 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20846 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20847 				/* Software checksum? */
20848 				if (DB_CKSUMFLAGS(mp) == 0) {
20849 					IP_STAT(ip_out_sw_cksum);
20850 					IP_STAT_UPDATE(
20851 					    ip_udp_out_sw_cksum_bytes,
20852 					    LENGTH - hlen);
20853 				}
20854 			}
20855 		}
20856 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20857 		hlen = (V_HLEN & 0xF) << 2;
20858 		if (PROTO == IPPROTO_TCP) {
20859 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20860 			/*
20861 			 * The packet header is processed once and for all, even
20862 			 * in the multirouting case. We disable hardware
20863 			 * checksum if the packet is multirouted, as it will be
20864 			 * replicated via several interfaces, and not all of
20865 			 * them may have this capability.
20866 			 */
20867 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20868 			    LENGTH, max_frag, ipsec_len, cksum);
20869 			/* Software checksum? */
20870 			if (DB_CKSUMFLAGS(mp) == 0) {
20871 				IP_STAT(ip_out_sw_cksum);
20872 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20873 				    LENGTH - hlen);
20874 			}
20875 		} else {
20876 			sctp_hdr_t	*sctph;
20877 
20878 			ASSERT(PROTO == IPPROTO_SCTP);
20879 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20880 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20881 			/*
20882 			 * Zero out the checksum field to ensure proper
20883 			 * checksum calculation.
20884 			 */
20885 			sctph->sh_chksum = 0;
20886 #ifdef	DEBUG
20887 			if (!skip_sctp_cksum)
20888 #endif
20889 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20890 		}
20891 	}
20892 
20893 	/*
20894 	 * If this is a multicast packet and originated from ip_wput
20895 	 * we need to do loopback and forwarding checks. If it comes
20896 	 * from ip_wput_multicast, we SHOULD not do this.
20897 	 */
20898 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20899 
20900 	/* checksum */
20901 	cksum += ttl_protocol;
20902 
20903 	/* fragment the packet */
20904 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20905 		goto fragmentit;
20906 	/*
20907 	 * Don't use frag_flag if packet is pre-built or source
20908 	 * routed or if multicast (since multicast packets do
20909 	 * not solicit ICMP "packet too big" messages).
20910 	 */
20911 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20912 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20913 	    !ip_source_route_included(ipha)) &&
20914 	    !CLASSD(ipha->ipha_dst))
20915 		ipha->ipha_fragment_offset_and_flags |=
20916 		    htons(ire->ire_frag_flag);
20917 
20918 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20919 		/* calculate IP header checksum */
20920 		cksum += ipha->ipha_ident;
20921 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20922 		cksum += ipha->ipha_fragment_offset_and_flags;
20923 
20924 		/* IP options present */
20925 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20926 		if (hlen)
20927 			goto checksumoptions;
20928 
20929 		/* calculate hdr checksum */
20930 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20931 		cksum = ~(cksum + (cksum >> 16));
20932 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20933 	}
20934 	if (ipsec_len != 0) {
20935 		/*
20936 		 * We will do the rest of the processing after
20937 		 * we come back from IPSEC in ip_wput_ipsec_out().
20938 		 */
20939 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20940 
20941 		io = (ipsec_out_t *)first_mp->b_rptr;
20942 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20943 				ill_phyint->phyint_ifindex;
20944 
20945 		ipsec_out_process(q, first_mp, ire, ill_index);
20946 		ire_refrele(ire);
20947 		if (conn_outgoing_ill != NULL)
20948 			ill_refrele(conn_outgoing_ill);
20949 		return;
20950 	}
20951 
20952 	/*
20953 	 * In most cases, the emission loop below is entered only
20954 	 * once. Only in the case where the ire holds the
20955 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20956 	 * flagged ires in the bucket, and send the packet
20957 	 * through all crossed RTF_MULTIRT routes.
20958 	 */
20959 	if (ire->ire_flags & RTF_MULTIRT) {
20960 		multirt_send = B_TRUE;
20961 	}
20962 	do {
20963 		if (multirt_send) {
20964 			irb_t *irb;
20965 			/*
20966 			 * We are in a multiple send case, need to get
20967 			 * the next ire and make a duplicate of the packet.
20968 			 * ire1 holds here the next ire to process in the
20969 			 * bucket. If multirouting is expected,
20970 			 * any non-RTF_MULTIRT ire that has the
20971 			 * right destination address is ignored.
20972 			 */
20973 			irb = ire->ire_bucket;
20974 			ASSERT(irb != NULL);
20975 
20976 			IRB_REFHOLD(irb);
20977 			for (ire1 = ire->ire_next;
20978 			    ire1 != NULL;
20979 			    ire1 = ire1->ire_next) {
20980 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20981 					continue;
20982 				if (ire1->ire_addr != ire->ire_addr)
20983 					continue;
20984 				if (ire1->ire_marks &
20985 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20986 					continue;
20987 
20988 				/* Got one */
20989 				IRE_REFHOLD(ire1);
20990 				break;
20991 			}
20992 			IRB_REFRELE(irb);
20993 
20994 			if (ire1 != NULL) {
20995 				next_mp = copyb(mp);
20996 				if ((next_mp == NULL) ||
20997 				    ((mp->b_cont != NULL) &&
20998 				    ((next_mp->b_cont =
20999 				    dupmsg(mp->b_cont)) == NULL))) {
21000 					freemsg(next_mp);
21001 					next_mp = NULL;
21002 					ire_refrele(ire1);
21003 					ire1 = NULL;
21004 				}
21005 			}
21006 
21007 			/* Last multiroute ire; don't loop anymore. */
21008 			if (ire1 == NULL) {
21009 				multirt_send = B_FALSE;
21010 			}
21011 		}
21012 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
21013 		if (mp == NULL) {
21014 			BUMP_MIB(&ip_mib, ipOutDiscards);
21015 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
21016 			    "during IPPF processing\n"));
21017 			ire_refrele(ire);
21018 			if (next_mp != NULL) {
21019 				freemsg(next_mp);
21020 				ire_refrele(ire1);
21021 			}
21022 			if (conn_outgoing_ill != NULL)
21023 				ill_refrele(conn_outgoing_ill);
21024 			return;
21025 		}
21026 		UPDATE_OB_PKT_COUNT(ire);
21027 		ire->ire_last_used_time = lbolt;
21028 
21029 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21030 		    "ip_wput_ire_end: q %p (%S)",
21031 		    q, "last copy out");
21032 		putnext(stq, mp);
21033 		IRE_REFRELE(ire);
21034 
21035 		if (multirt_send) {
21036 			ASSERT(ire1);
21037 			/*
21038 			 * Proceed with the next RTF_MULTIRT ire,
21039 			 * Also set up the send-to queue accordingly.
21040 			 */
21041 			ire = ire1;
21042 			ire1 = NULL;
21043 			stq = ire->ire_stq;
21044 			mp = next_mp;
21045 			next_mp = NULL;
21046 			ipha = (ipha_t *)mp->b_rptr;
21047 			ill_index = Q_TO_INDEX(stq);
21048 		}
21049 	} while (multirt_send);
21050 	if (conn_outgoing_ill != NULL)
21051 		ill_refrele(conn_outgoing_ill);
21052 	return;
21053 
21054 	/*
21055 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21056 	 */
21057 broadcast:
21058 	{
21059 		/*
21060 		 * Avoid broadcast storms by setting the ttl to 1
21061 		 * for broadcasts. This parameter can be set
21062 		 * via ndd, so make sure that for the SO_DONTROUTE
21063 		 * case that ipha_ttl is always set to 1.
21064 		 * In the event that we are replying to incoming
21065 		 * ICMP packets, conn could be NULL.
21066 		 */
21067 		if ((connp != NULL) && connp->conn_dontroute)
21068 			ipha->ipha_ttl = 1;
21069 		else
21070 			ipha->ipha_ttl = ip_broadcast_ttl;
21071 
21072 		/*
21073 		 * Note that we are not doing a IRB_REFHOLD here.
21074 		 * Actually we don't care if the list changes i.e
21075 		 * if somebody deletes an IRE from the list while
21076 		 * we drop the lock, the next time we come around
21077 		 * ire_next will be NULL and hence we won't send
21078 		 * out multiple copies which is fine.
21079 		 */
21080 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21081 		ire1 = ire->ire_next;
21082 		if (conn_outgoing_ill != NULL) {
21083 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21084 				ASSERT(ire1 == ire->ire_next);
21085 				if (ire1 != NULL && ire1->ire_addr == dst) {
21086 					ire_refrele(ire);
21087 					ire = ire1;
21088 					IRE_REFHOLD(ire);
21089 					ire1 = ire->ire_next;
21090 					continue;
21091 				}
21092 				rw_exit(&ire->ire_bucket->irb_lock);
21093 				/* Did not find a matching ill */
21094 				ip1dbg(("ip_wput_ire: broadcast with no "
21095 				    "matching IP_BOUND_IF ill %s\n",
21096 				    conn_outgoing_ill->ill_name));
21097 				freemsg(first_mp);
21098 				if (ire != NULL)
21099 					ire_refrele(ire);
21100 				ill_refrele(conn_outgoing_ill);
21101 				return;
21102 			}
21103 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21104 			/*
21105 			 * If the next IRE has the same address and is not one
21106 			 * of the two copies that we need to send, try to see
21107 			 * whether this copy should be sent at all. This
21108 			 * assumes that we insert loopbacks first and then
21109 			 * non-loopbacks. This is acheived by inserting the
21110 			 * loopback always before non-loopback.
21111 			 * This is used to send a single copy of a broadcast
21112 			 * packet out all physical interfaces that have an
21113 			 * matching IRE_BROADCAST while also looping
21114 			 * back one copy (to ip_wput_local) for each
21115 			 * matching physical interface. However, we avoid
21116 			 * sending packets out different logical that match by
21117 			 * having ipif_up/ipif_down supress duplicate
21118 			 * IRE_BROADCASTS.
21119 			 *
21120 			 * This feature is currently used to get broadcasts
21121 			 * sent to multiple interfaces, when the broadcast
21122 			 * address being used applies to multiple interfaces.
21123 			 * For example, a whole net broadcast will be
21124 			 * replicated on every connected subnet of
21125 			 * the target net.
21126 			 *
21127 			 * Each zone has its own set of IRE_BROADCASTs, so that
21128 			 * we're able to distribute inbound packets to multiple
21129 			 * zones who share a broadcast address. We avoid looping
21130 			 * back outbound packets in different zones but on the
21131 			 * same ill, as the application would see duplicates.
21132 			 *
21133 			 * If the interfaces are part of the same group,
21134 			 * we would want to send only one copy out for
21135 			 * whole group.
21136 			 *
21137 			 * This logic assumes that ire_add_v4() groups the
21138 			 * IRE_BROADCAST entries so that those with the same
21139 			 * ire_addr and ill_group are kept together.
21140 			 */
21141 			ire_ill = ire->ire_ipif->ipif_ill;
21142 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21143 				if (ire_ill->ill_group != NULL &&
21144 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21145 					/*
21146 					 * If the current zone only has an ire
21147 					 * broadcast for this address marked
21148 					 * NORECV, the ire we want is ahead in
21149 					 * the bucket, so we look it up
21150 					 * deliberately ignoring the zoneid.
21151 					 */
21152 					for (ire1 = ire->ire_bucket->irb_ire;
21153 					    ire1 != NULL;
21154 					    ire1 = ire1->ire_next) {
21155 						ire1_ill =
21156 						    ire1->ire_ipif->ipif_ill;
21157 						if (ire1->ire_addr != dst)
21158 							continue;
21159 						/* skip over the current ire */
21160 						if (ire1 == ire)
21161 							continue;
21162 						/* skip over deleted ires */
21163 						if (ire1->ire_marks &
21164 						    IRE_MARK_CONDEMNED)
21165 							continue;
21166 						/*
21167 						 * non-loopback ire in our
21168 						 * group: use it for the next
21169 						 * pass in the loop
21170 						 */
21171 						if (ire1->ire_stq != NULL &&
21172 						    ire1_ill->ill_group ==
21173 						    ire_ill->ill_group)
21174 							break;
21175 					}
21176 				}
21177 			} else {
21178 				while (ire1 != NULL && ire1->ire_addr == dst) {
21179 					ire1_ill = ire1->ire_ipif->ipif_ill;
21180 					/*
21181 					 * We can have two broadcast ires on the
21182 					 * same ill in different zones; here
21183 					 * we'll send a copy of the packet on
21184 					 * each ill and the fanout code will
21185 					 * call conn_wantpacket() to check that
21186 					 * the zone has the broadcast address
21187 					 * configured on the ill. If the two
21188 					 * ires are in the same group we only
21189 					 * send one copy up.
21190 					 */
21191 					if (ire1_ill != ire_ill &&
21192 					    (ire1_ill->ill_group == NULL ||
21193 					    ire_ill->ill_group == NULL ||
21194 					    ire1_ill->ill_group !=
21195 					    ire_ill->ill_group)) {
21196 						break;
21197 					}
21198 					ire1 = ire1->ire_next;
21199 				}
21200 			}
21201 		}
21202 		ASSERT(multirt_send == B_FALSE);
21203 		if (ire1 != NULL && ire1->ire_addr == dst) {
21204 			if ((ire->ire_flags & RTF_MULTIRT) &&
21205 			    (ire1->ire_flags & RTF_MULTIRT)) {
21206 				/*
21207 				 * We are in the multirouting case.
21208 				 * The message must be sent at least
21209 				 * on both ires. These ires have been
21210 				 * inserted AFTER the standard ones
21211 				 * in ip_rt_add(). There are thus no
21212 				 * other ire entries for the destination
21213 				 * address in the rest of the bucket
21214 				 * that do not have the RTF_MULTIRT
21215 				 * flag. We don't process a copy
21216 				 * of the message here. This will be
21217 				 * done in the final sending loop.
21218 				 */
21219 				multirt_send = B_TRUE;
21220 			} else {
21221 				next_mp = ip_copymsg(first_mp);
21222 				if (next_mp != NULL)
21223 					IRE_REFHOLD(ire1);
21224 			}
21225 		}
21226 		rw_exit(&ire->ire_bucket->irb_lock);
21227 	}
21228 
21229 	if (stq) {
21230 		/*
21231 		 * A non-NULL send-to queue means this packet is going
21232 		 * out of this machine.
21233 		 */
21234 
21235 		BUMP_MIB(&ip_mib, ipOutRequests);
21236 		ttl_protocol = ((uint16_t *)ipha)[4];
21237 		/*
21238 		 * We accumulate the pseudo header checksum in cksum.
21239 		 * This is pretty hairy code, so watch close.  One
21240 		 * thing to keep in mind is that UDP and TCP have
21241 		 * stored their respective datagram lengths in their
21242 		 * checksum fields.  This lines things up real nice.
21243 		 */
21244 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21245 		    (src >> 16) + (src & 0xFFFF);
21246 		/*
21247 		 * We assume the udp checksum field contains the
21248 		 * length, so to compute the pseudo header checksum,
21249 		 * all we need is the protocol number and src/dst.
21250 		 */
21251 		/* Provide the checksums for UDP and TCP. */
21252 		if ((PROTO == IPPROTO_TCP) &&
21253 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21254 			/* hlen gets the number of uchar_ts in the IP header */
21255 			hlen = (V_HLEN & 0xF) << 2;
21256 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21257 			IP_STAT(ip_out_sw_cksum);
21258 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21259 			    LENGTH - hlen);
21260 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21261 			if (*up == 0)
21262 				*up = 0xFFFF;
21263 		} else if (PROTO == IPPROTO_SCTP &&
21264 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21265 			sctp_hdr_t	*sctph;
21266 
21267 			hlen = (V_HLEN & 0xF) << 2;
21268 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21269 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21270 			sctph->sh_chksum = 0;
21271 #ifdef	DEBUG
21272 			if (!skip_sctp_cksum)
21273 #endif
21274 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21275 		} else {
21276 			queue_t *dev_q = stq->q_next;
21277 
21278 			if ((dev_q->q_next || dev_q->q_first) &&
21279 			    !canput(dev_q)) {
21280 			    blocked:
21281 				ipha->ipha_ident = ip_hdr_included;
21282 				/*
21283 				 * If we don't have a conn to apply
21284 				 * backpressure, free the message.
21285 				 * In the ire_send path, we don't know
21286 				 * the position to requeue the packet. Rather
21287 				 * than reorder packets, we just drop this
21288 				 * packet.
21289 				 */
21290 				if (ip_output_queue && connp != NULL &&
21291 				    caller != IRE_SEND) {
21292 					if (caller == IP_WSRV) {
21293 						connp->conn_did_putbq = 1;
21294 						(void) putbq(connp->conn_wq,
21295 						    first_mp);
21296 						conn_drain_insert(connp);
21297 						/*
21298 						 * This is the service thread,
21299 						 * and the queue is already
21300 						 * noenabled. The check for
21301 						 * canput and the putbq is not
21302 						 * atomic. So we need to check
21303 						 * again.
21304 						 */
21305 						if (canput(stq->q_next))
21306 							connp->conn_did_putbq
21307 							    = 0;
21308 						IP_STAT(ip_conn_flputbq);
21309 					} else {
21310 						/*
21311 						 * We are not the service proc.
21312 						 * ip_wsrv will be scheduled or
21313 						 * is already running.
21314 						 */
21315 						(void) putq(connp->conn_wq,
21316 						    first_mp);
21317 					}
21318 				} else {
21319 					BUMP_MIB(&ip_mib, ipOutDiscards);
21320 					freemsg(first_mp);
21321 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21322 					    "ip_wput_ire_end: q %p (%S)",
21323 					    q, "discard");
21324 				}
21325 				ire_refrele(ire);
21326 				if (next_mp) {
21327 					ire_refrele(ire1);
21328 					freemsg(next_mp);
21329 				}
21330 				if (conn_outgoing_ill != NULL)
21331 					ill_refrele(conn_outgoing_ill);
21332 				return;
21333 			}
21334 			if ((PROTO == IPPROTO_UDP) &&
21335 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21336 				/*
21337 				 * hlen gets the number of uchar_ts in the
21338 				 * IP header
21339 				 */
21340 				hlen = (V_HLEN & 0xF) << 2;
21341 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21342 				max_frag = ire->ire_max_frag;
21343 				if (*up != 0) {
21344 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21345 					    up, PROTO, hlen, LENGTH, max_frag,
21346 					    ipsec_len, cksum);
21347 					/* Software checksum? */
21348 					if (DB_CKSUMFLAGS(mp) == 0) {
21349 						IP_STAT(ip_out_sw_cksum);
21350 						IP_STAT_UPDATE(
21351 						    ip_udp_out_sw_cksum_bytes,
21352 						    LENGTH - hlen);
21353 					}
21354 				}
21355 			}
21356 		}
21357 		/*
21358 		 * Need to do this even when fragmenting. The local
21359 		 * loopback can be done without computing checksums
21360 		 * but forwarding out other interface must be done
21361 		 * after the IP checksum (and ULP checksums) have been
21362 		 * computed.
21363 		 *
21364 		 * NOTE : multicast_forward is set only if this packet
21365 		 * originated from ip_wput. For packets originating from
21366 		 * ip_wput_multicast, it is not set.
21367 		 */
21368 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21369 		    multi_loopback:
21370 			ip2dbg(("ip_wput: multicast, loop %d\n",
21371 			    conn_multicast_loop));
21372 
21373 			/*  Forget header checksum offload */
21374 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21375 
21376 			/*
21377 			 * Local loopback of multicasts?  Check the
21378 			 * ill.
21379 			 *
21380 			 * Note that the loopback function will not come
21381 			 * in through ip_rput - it will only do the
21382 			 * client fanout thus we need to do an mforward
21383 			 * as well.  The is different from the BSD
21384 			 * logic.
21385 			 */
21386 			if (ill != NULL) {
21387 				ilm_t	*ilm;
21388 
21389 				ILM_WALKER_HOLD(ill);
21390 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21391 				    ALL_ZONES);
21392 				ILM_WALKER_RELE(ill);
21393 				if (ilm != NULL) {
21394 					/*
21395 					 * Pass along the virtual output q.
21396 					 * ip_wput_local() will distribute the
21397 					 * packet to all the matching zones,
21398 					 * except the sending zone when
21399 					 * IP_MULTICAST_LOOP is false.
21400 					 */
21401 					ip_multicast_loopback(q, ill, first_mp,
21402 					    conn_multicast_loop ? 0 :
21403 					    IP_FF_NO_MCAST_LOOP, zoneid);
21404 				}
21405 			}
21406 			if (ipha->ipha_ttl == 0) {
21407 				/*
21408 				 * 0 => only to this host i.e. we are
21409 				 * done. We are also done if this was the
21410 				 * loopback interface since it is sufficient
21411 				 * to loopback one copy of a multicast packet.
21412 				 */
21413 				freemsg(first_mp);
21414 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21415 				    "ip_wput_ire_end: q %p (%S)",
21416 				    q, "loopback");
21417 				ire_refrele(ire);
21418 				if (conn_outgoing_ill != NULL)
21419 					ill_refrele(conn_outgoing_ill);
21420 				return;
21421 			}
21422 			/*
21423 			 * ILLF_MULTICAST is checked in ip_newroute
21424 			 * i.e. we don't need to check it here since
21425 			 * all IRE_CACHEs come from ip_newroute.
21426 			 * For multicast traffic, SO_DONTROUTE is interpreted
21427 			 * to mean only send the packet out the interface
21428 			 * (optionally specified with IP_MULTICAST_IF)
21429 			 * and do not forward it out additional interfaces.
21430 			 * RSVP and the rsvp daemon is an example of a
21431 			 * protocol and user level process that
21432 			 * handles it's own routing. Hence, it uses the
21433 			 * SO_DONTROUTE option to accomplish this.
21434 			 */
21435 
21436 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
21437 				/* Unconditionally redo the checksum */
21438 				ipha->ipha_hdr_checksum = 0;
21439 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21440 
21441 				/*
21442 				 * If this needs to go out secure, we need
21443 				 * to wait till we finish the IPSEC
21444 				 * processing.
21445 				 */
21446 				if (ipsec_len == 0 &&
21447 				    ip_mforward(ill, ipha, mp)) {
21448 					freemsg(first_mp);
21449 					ip1dbg(("ip_wput: mforward failed\n"));
21450 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21451 					    "ip_wput_ire_end: q %p (%S)",
21452 					    q, "mforward failed");
21453 					ire_refrele(ire);
21454 					if (conn_outgoing_ill != NULL)
21455 						ill_refrele(conn_outgoing_ill);
21456 					return;
21457 				}
21458 			}
21459 		}
21460 		max_frag = ire->ire_max_frag;
21461 		cksum += ttl_protocol;
21462 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
21463 			/* No fragmentation required for this one. */
21464 			/*
21465 			 * Don't use frag_flag if packet is pre-built or source
21466 			 * routed or if multicast (since multicast packets do
21467 			 * not solicit ICMP "packet too big" messages).
21468 			 */
21469 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21470 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21471 			    !ip_source_route_included(ipha)) &&
21472 			    !CLASSD(ipha->ipha_dst))
21473 				ipha->ipha_fragment_offset_and_flags |=
21474 				    htons(ire->ire_frag_flag);
21475 
21476 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21477 				/* Complete the IP header checksum. */
21478 				cksum += ipha->ipha_ident;
21479 				cksum += (v_hlen_tos_len >> 16)+
21480 				    (v_hlen_tos_len & 0xFFFF);
21481 				cksum += ipha->ipha_fragment_offset_and_flags;
21482 				hlen = (V_HLEN & 0xF) -
21483 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21484 				if (hlen) {
21485 				    checksumoptions:
21486 					/*
21487 					 * Account for the IP Options in the IP
21488 					 * header checksum.
21489 					 */
21490 					up = (uint16_t *)(rptr+
21491 					    IP_SIMPLE_HDR_LENGTH);
21492 					do {
21493 						cksum += up[0];
21494 						cksum += up[1];
21495 						up += 2;
21496 					} while (--hlen);
21497 				}
21498 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21499 				cksum = ~(cksum + (cksum >> 16));
21500 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
21501 			}
21502 			if (ipsec_len != 0) {
21503 				ipsec_out_process(q, first_mp, ire, ill_index);
21504 				if (!next_mp) {
21505 					ire_refrele(ire);
21506 					if (conn_outgoing_ill != NULL)
21507 						ill_refrele(conn_outgoing_ill);
21508 					return;
21509 				}
21510 				goto next;
21511 			}
21512 
21513 			/*
21514 			 * multirt_send has already been handled
21515 			 * for broadcast, but not yet for multicast
21516 			 * or IP options.
21517 			 */
21518 			if (next_mp == NULL) {
21519 				if (ire->ire_flags & RTF_MULTIRT) {
21520 					multirt_send = B_TRUE;
21521 				}
21522 			}
21523 
21524 			/*
21525 			 * In most cases, the emission loop below is
21526 			 * entered only once. Only in the case where
21527 			 * the ire holds the RTF_MULTIRT flag, do we loop
21528 			 * to process all RTF_MULTIRT ires in the bucket,
21529 			 * and send the packet through all crossed
21530 			 * RTF_MULTIRT routes.
21531 			 */
21532 			do {
21533 				if (multirt_send) {
21534 					irb_t *irb;
21535 
21536 					irb = ire->ire_bucket;
21537 					ASSERT(irb != NULL);
21538 					/*
21539 					 * We are in a multiple send case,
21540 					 * need to get the next IRE and make
21541 					 * a duplicate of the packet.
21542 					 */
21543 					IRB_REFHOLD(irb);
21544 					for (ire1 = ire->ire_next;
21545 					    ire1 != NULL;
21546 					    ire1 = ire1->ire_next) {
21547 						if (!(ire1->ire_flags &
21548 						    RTF_MULTIRT))
21549 							continue;
21550 						if (ire1->ire_addr !=
21551 						    ire->ire_addr)
21552 							continue;
21553 						if (ire1->ire_marks &
21554 						    (IRE_MARK_CONDEMNED|
21555 							IRE_MARK_HIDDEN))
21556 							continue;
21557 
21558 						/* Got one */
21559 						IRE_REFHOLD(ire1);
21560 						break;
21561 					}
21562 					IRB_REFRELE(irb);
21563 
21564 					if (ire1 != NULL) {
21565 						next_mp = copyb(mp);
21566 						if ((next_mp == NULL) ||
21567 						    ((mp->b_cont != NULL) &&
21568 						    ((next_mp->b_cont =
21569 						    dupmsg(mp->b_cont))
21570 						    == NULL))) {
21571 							freemsg(next_mp);
21572 							next_mp = NULL;
21573 							ire_refrele(ire1);
21574 							ire1 = NULL;
21575 						}
21576 					}
21577 
21578 					/*
21579 					 * Last multiroute ire; don't loop
21580 					 * anymore. The emission is over
21581 					 * and next_mp is NULL.
21582 					 */
21583 					if (ire1 == NULL) {
21584 						multirt_send = B_FALSE;
21585 					}
21586 				}
21587 
21588 				ASSERT(ipsec_len == 0);
21589 				mp1 = ip_wput_attach_llhdr(mp, ire,
21590 				    IPP_LOCAL_OUT, ill_index);
21591 				if (mp1 == NULL) {
21592 					BUMP_MIB(&ip_mib, ipOutDiscards);
21593 					if (next_mp) {
21594 						freemsg(next_mp);
21595 						ire_refrele(ire1);
21596 					}
21597 					ire_refrele(ire);
21598 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21599 					    "ip_wput_ire_end: q %p (%S)",
21600 					    q, "discard MDATA");
21601 					if (conn_outgoing_ill != NULL)
21602 						ill_refrele(conn_outgoing_ill);
21603 					return;
21604 				}
21605 				UPDATE_OB_PKT_COUNT(ire);
21606 				ire->ire_last_used_time = lbolt;
21607 
21608 				if (multirt_send) {
21609 					/*
21610 					 * We are in a multiple send case,
21611 					 * need to re-enter the sending loop
21612 					 * using the next ire.
21613 					 */
21614 					putnext(stq, mp1);
21615 					ire_refrele(ire);
21616 					ire = ire1;
21617 					stq = ire->ire_stq;
21618 					mp = next_mp;
21619 					next_mp = NULL;
21620 					ipha = (ipha_t *)mp->b_rptr;
21621 					ill_index = Q_TO_INDEX(stq);
21622 				}
21623 			} while (multirt_send);
21624 
21625 			if (!next_mp) {
21626 				/*
21627 				 * Last copy going out (the ultra-common
21628 				 * case).  Note that we intentionally replicate
21629 				 * the putnext rather than calling it before
21630 				 * the next_mp check in hopes of a little
21631 				 * tail-call action out of the compiler.
21632 				 */
21633 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21634 				    "ip_wput_ire_end: q %p (%S)",
21635 				    q, "last copy out(1)");
21636 				putnext(stq, mp1);
21637 				ire_refrele(ire);
21638 				if (conn_outgoing_ill != NULL)
21639 					ill_refrele(conn_outgoing_ill);
21640 				return;
21641 			}
21642 			/* More copies going out below. */
21643 			putnext(stq, mp1);
21644 		} else {
21645 			int offset;
21646 		    fragmentit:
21647 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21648 			/*
21649 			 * If this would generate a icmp_frag_needed message,
21650 			 * we need to handle it before we do the IPSEC
21651 			 * processing. Otherwise, we need to strip the IPSEC
21652 			 * headers before we send up the message to the ULPs
21653 			 * which becomes messy and difficult.
21654 			 */
21655 			if (ipsec_len != 0) {
21656 				if ((max_frag < (unsigned int)(LENGTH +
21657 				    ipsec_len)) && (offset & IPH_DF)) {
21658 
21659 					BUMP_MIB(&ip_mib, ipFragFails);
21660 					ipha->ipha_hdr_checksum = 0;
21661 					ipha->ipha_hdr_checksum =
21662 					    (uint16_t)ip_csum_hdr(ipha);
21663 					icmp_frag_needed(ire->ire_stq, first_mp,
21664 					    max_frag);
21665 					if (!next_mp) {
21666 						ire_refrele(ire);
21667 						if (conn_outgoing_ill != NULL) {
21668 							ill_refrele(
21669 							    conn_outgoing_ill);
21670 						}
21671 						return;
21672 					}
21673 				} else {
21674 					/*
21675 					 * This won't cause a icmp_frag_needed
21676 					 * message. to be gnerated. Send it on
21677 					 * the wire. Note that this could still
21678 					 * cause fragmentation and all we
21679 					 * do is the generation of the message
21680 					 * to the ULP if needed before IPSEC.
21681 					 */
21682 					if (!next_mp) {
21683 						ipsec_out_process(q, first_mp,
21684 						    ire, ill_index);
21685 						TRACE_2(TR_FAC_IP,
21686 						    TR_IP_WPUT_IRE_END,
21687 						    "ip_wput_ire_end: q %p "
21688 						    "(%S)", q,
21689 						    "last ipsec_out_process");
21690 						ire_refrele(ire);
21691 						if (conn_outgoing_ill != NULL) {
21692 							ill_refrele(
21693 							    conn_outgoing_ill);
21694 						}
21695 						return;
21696 					}
21697 					ipsec_out_process(q, first_mp,
21698 					    ire, ill_index);
21699 				}
21700 			} else {
21701 				/* Initiate IPPF processing */
21702 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21703 					ip_process(IPP_LOCAL_OUT, &mp,
21704 					    ill_index);
21705 					if (mp == NULL) {
21706 						BUMP_MIB(&ip_mib,
21707 						    ipOutDiscards);
21708 						if (next_mp != NULL) {
21709 							freemsg(next_mp);
21710 							ire_refrele(ire1);
21711 						}
21712 						ire_refrele(ire);
21713 						TRACE_2(TR_FAC_IP,
21714 						    TR_IP_WPUT_IRE_END,
21715 						    "ip_wput_ire: q %p (%S)",
21716 						    q, "discard MDATA");
21717 						if (conn_outgoing_ill != NULL) {
21718 							ill_refrele(
21719 							    conn_outgoing_ill);
21720 						}
21721 						return;
21722 					}
21723 				}
21724 				if (!next_mp) {
21725 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21726 					    "ip_wput_ire_end: q %p (%S)",
21727 					    q, "last fragmentation");
21728 					ip_wput_ire_fragmentit(mp, ire);
21729 					ire_refrele(ire);
21730 					if (conn_outgoing_ill != NULL)
21731 						ill_refrele(conn_outgoing_ill);
21732 					return;
21733 				}
21734 				ip_wput_ire_fragmentit(mp, ire);
21735 			}
21736 		}
21737 	} else {
21738 	    nullstq:
21739 		/* A NULL stq means the destination address is local. */
21740 		UPDATE_OB_PKT_COUNT(ire);
21741 		ire->ire_last_used_time = lbolt;
21742 		ASSERT(ire->ire_ipif != NULL);
21743 		if (!next_mp) {
21744 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21745 			    "ip_wput_ire_end: q %p (%S)",
21746 			    q, "local address");
21747 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
21748 			    first_mp, ire, 0, ire->ire_zoneid);
21749 			ire_refrele(ire);
21750 			if (conn_outgoing_ill != NULL)
21751 				ill_refrele(conn_outgoing_ill);
21752 			return;
21753 		}
21754 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
21755 		    ire, 0, ire->ire_zoneid);
21756 	}
21757 next:
21758 	/*
21759 	 * More copies going out to additional interfaces.
21760 	 * ire1 has already been held. We don't need the
21761 	 * "ire" anymore.
21762 	 */
21763 	ire_refrele(ire);
21764 	ire = ire1;
21765 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
21766 	mp = next_mp;
21767 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
21768 	ill = ire_to_ill(ire);
21769 	first_mp = mp;
21770 	if (ipsec_len != 0) {
21771 		ASSERT(first_mp->b_datap->db_type == M_CTL);
21772 		mp = mp->b_cont;
21773 	}
21774 	dst = ire->ire_addr;
21775 	ipha = (ipha_t *)mp->b_rptr;
21776 	/*
21777 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
21778 	 * Restore ipha_ident "no checksum" flag.
21779 	 */
21780 	src = orig_src;
21781 	ipha->ipha_ident = ip_hdr_included;
21782 	goto another;
21783 
21784 #undef	rptr
21785 #undef	Q_TO_INDEX
21786 }
21787 
21788 /*
21789  * Routine to allocate a message that is used to notify the ULP about MDT.
21790  * The caller may provide a pointer to the link-layer MDT capabilities,
21791  * or NULL if MDT is to be disabled on the stream.
21792  */
21793 mblk_t *
21794 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
21795 {
21796 	mblk_t *mp;
21797 	ip_mdt_info_t *mdti;
21798 	ill_mdt_capab_t *idst;
21799 
21800 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
21801 		DB_TYPE(mp) = M_CTL;
21802 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
21803 		mdti = (ip_mdt_info_t *)mp->b_rptr;
21804 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
21805 		idst = &(mdti->mdt_capab);
21806 
21807 		/*
21808 		 * If the caller provides us with the capability, copy
21809 		 * it over into our notification message; otherwise
21810 		 * we zero out the capability portion.
21811 		 */
21812 		if (isrc != NULL)
21813 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
21814 		else
21815 			bzero((caddr_t)idst, sizeof (*idst));
21816 	}
21817 	return (mp);
21818 }
21819 
21820 /*
21821  * Routine which determines whether MDT can be enabled on the destination
21822  * IRE and IPC combination, and if so, allocates and returns the MDT
21823  * notification mblk that may be used by ULP.  We also check if we need to
21824  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21825  * MDT usage in the past have been lifted.  This gets called during IP
21826  * and ULP binding.
21827  */
21828 mblk_t *
21829 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21830     ill_mdt_capab_t *mdt_cap)
21831 {
21832 	mblk_t *mp;
21833 	boolean_t rc = B_FALSE;
21834 
21835 	ASSERT(dst_ire != NULL);
21836 	ASSERT(connp != NULL);
21837 	ASSERT(mdt_cap != NULL);
21838 
21839 	/*
21840 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21841 	 * Multidata, which is handled in tcp_multisend().  This
21842 	 * is the reason why we do all these checks here, to ensure
21843 	 * that we don't enable Multidata for the cases which we
21844 	 * can't handle at the moment.
21845 	 */
21846 	do {
21847 		/* Only do TCP at the moment */
21848 		if (connp->conn_ulp != IPPROTO_TCP)
21849 			break;
21850 
21851 		/*
21852 		 * IPSEC outbound policy present?  Note that we get here
21853 		 * after calling ipsec_conn_cache_policy() where the global
21854 		 * policy checking is performed.  conn_latch will be
21855 		 * non-NULL as long as there's a policy defined,
21856 		 * i.e. conn_out_enforce_policy may be NULL in such case
21857 		 * when the connection is non-secure, and hence we check
21858 		 * further if the latch refers to an outbound policy.
21859 		 */
21860 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21861 			break;
21862 
21863 		/* CGTP (multiroute) is enabled? */
21864 		if (dst_ire->ire_flags & RTF_MULTIRT)
21865 			break;
21866 
21867 		/* Outbound IPQoS enabled? */
21868 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21869 			/*
21870 			 * In this case, we disable MDT for this and all
21871 			 * future connections going over the interface.
21872 			 */
21873 			mdt_cap->ill_mdt_on = 0;
21874 			break;
21875 		}
21876 
21877 		/* socket option(s) present? */
21878 		if (!CONN_IS_MD_FASTPATH(connp))
21879 			break;
21880 
21881 		rc = B_TRUE;
21882 	/* CONSTCOND */
21883 	} while (0);
21884 
21885 	/* Remember the result */
21886 	connp->conn_mdt_ok = rc;
21887 
21888 	if (!rc)
21889 		return (NULL);
21890 	else if (!mdt_cap->ill_mdt_on) {
21891 		/*
21892 		 * If MDT has been previously turned off in the past, and we
21893 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21894 		 * then enable it for this interface.
21895 		 */
21896 		mdt_cap->ill_mdt_on = 1;
21897 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21898 		    "interface %s\n", ill_name));
21899 	}
21900 
21901 	/* Allocate the MDT info mblk */
21902 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21903 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21904 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21905 		return (NULL);
21906 	}
21907 	return (mp);
21908 }
21909 
21910 /*
21911  * Create destination address attribute, and fill it with the physical
21912  * destination address and SAP taken from the template DL_UNITDATA_REQ
21913  * message block.
21914  */
21915 boolean_t
21916 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21917 {
21918 	dl_unitdata_req_t *dlurp;
21919 	pattr_t *pa;
21920 	pattrinfo_t pa_info;
21921 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21922 	uint_t das_len, das_off;
21923 
21924 	ASSERT(dlmp != NULL);
21925 
21926 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21927 	das_len = dlurp->dl_dest_addr_length;
21928 	das_off = dlurp->dl_dest_addr_offset;
21929 
21930 	pa_info.type = PATTR_DSTADDRSAP;
21931 	pa_info.len = sizeof (**das) + das_len - 1;
21932 
21933 	/* create and associate the attribute */
21934 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21935 	if (pa != NULL) {
21936 		ASSERT(*das != NULL);
21937 		(*das)->addr_is_group = 0;
21938 		(*das)->addr_len = (uint8_t)das_len;
21939 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21940 	}
21941 
21942 	return (pa != NULL);
21943 }
21944 
21945 /*
21946  * Create hardware checksum attribute and fill it with the values passed.
21947  */
21948 boolean_t
21949 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21950     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21951 {
21952 	pattr_t *pa;
21953 	pattrinfo_t pa_info;
21954 
21955 	ASSERT(mmd != NULL);
21956 
21957 	pa_info.type = PATTR_HCKSUM;
21958 	pa_info.len = sizeof (pattr_hcksum_t);
21959 
21960 	/* create and associate the attribute */
21961 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21962 	if (pa != NULL) {
21963 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21964 
21965 		hck->hcksum_start_offset = start_offset;
21966 		hck->hcksum_stuff_offset = stuff_offset;
21967 		hck->hcksum_end_offset = end_offset;
21968 		hck->hcksum_flags = flags;
21969 	}
21970 	return (pa != NULL);
21971 }
21972 
21973 /*
21974  * Create zerocopy attribute and fill it with the specified flags
21975  */
21976 boolean_t
21977 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21978 {
21979 	pattr_t *pa;
21980 	pattrinfo_t pa_info;
21981 
21982 	ASSERT(mmd != NULL);
21983 	pa_info.type = PATTR_ZCOPY;
21984 	pa_info.len = sizeof (pattr_zcopy_t);
21985 
21986 	/* create and associate the attribute */
21987 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21988 	if (pa != NULL) {
21989 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21990 
21991 		zcopy->zcopy_flags = flags;
21992 	}
21993 	return (pa != NULL);
21994 }
21995 
21996 /*
21997  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
21998  * block chain. We could rewrite to handle arbitrary message block chains but
21999  * that would make the code complicated and slow. Right now there three
22000  * restrictions:
22001  *
22002  *   1. The first message block must contain the complete IP header and
22003  *	at least 1 byte of payload data.
22004  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22005  *	so that we can use a single Multidata message.
22006  *   3. No frag must be distributed over two or more message blocks so
22007  *	that we don't need more than two packet descriptors per frag.
22008  *
22009  * The above restrictions allow us to support userland applications (which
22010  * will send down a single message block) and NFS over UDP (which will
22011  * send down a chain of at most three message blocks).
22012  *
22013  * We also don't use MDT for payloads with less than or equal to
22014  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22015  */
22016 boolean_t
22017 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22018 {
22019 	int	blocks;
22020 	ssize_t	total, missing, size;
22021 
22022 	ASSERT(mp != NULL);
22023 	ASSERT(hdr_len > 0);
22024 
22025 	size = MBLKL(mp) - hdr_len;
22026 	if (size <= 0)
22027 		return (B_FALSE);
22028 
22029 	/* The first mblk contains the header and some payload. */
22030 	blocks = 1;
22031 	total = size;
22032 	size %= len;
22033 	missing = (size == 0) ? 0 : (len - size);
22034 	mp = mp->b_cont;
22035 
22036 	while (mp != NULL) {
22037 		/*
22038 		 * Give up if we encounter a zero length message block.
22039 		 * In practice, this should rarely happen and therefore
22040 		 * not worth the trouble of freeing and re-linking the
22041 		 * mblk from the chain to handle such case.
22042 		 */
22043 		if ((size = MBLKL(mp)) == 0)
22044 			return (B_FALSE);
22045 
22046 		/* Too many payload buffers for a single Multidata message? */
22047 		if (++blocks > MULTIDATA_MAX_PBUFS)
22048 			return (B_FALSE);
22049 
22050 		total += size;
22051 		/* Is a frag distributed over two or more message blocks? */
22052 		if (missing > size)
22053 			return (B_FALSE);
22054 		size -= missing;
22055 
22056 		size %= len;
22057 		missing = (size == 0) ? 0 : (len - size);
22058 
22059 		mp = mp->b_cont;
22060 	}
22061 
22062 	return (total > ip_wput_frag_mdt_min);
22063 }
22064 
22065 /*
22066  * Outbound IPv4 fragmentation routine using MDT.
22067  */
22068 static void
22069 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22070     uint32_t frag_flag, int offset)
22071 {
22072 	ipha_t		*ipha_orig;
22073 	int		i1, ip_data_end;
22074 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22075 	mblk_t		*hdr_mp, *md_mp = NULL;
22076 	unsigned char	*hdr_ptr, *pld_ptr;
22077 	multidata_t	*mmd;
22078 	ip_pdescinfo_t	pdi;
22079 
22080 	ASSERT(DB_TYPE(mp) == M_DATA);
22081 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22082 
22083 	ipha_orig = (ipha_t *)mp->b_rptr;
22084 	mp->b_rptr += sizeof (ipha_t);
22085 
22086 	/* Calculate how many packets we will send out */
22087 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22088 	pkts = (i1 + len - 1) / len;
22089 	ASSERT(pkts > 1);
22090 
22091 	/* Allocate a message block which will hold all the IP Headers. */
22092 	wroff = ip_wroff_extra;
22093 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22094 
22095 	i1 = pkts * hdr_chunk_len;
22096 	/*
22097 	 * Create the header buffer, Multidata and destination address
22098 	 * and SAP attribute that should be associated with it.
22099 	 */
22100 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22101 	    ((hdr_mp->b_wptr += i1),
22102 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22103 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
22104 		freemsg(mp);
22105 		if (md_mp == NULL) {
22106 			freemsg(hdr_mp);
22107 		} else {
22108 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22109 			freemsg(md_mp);
22110 		}
22111 		IP_STAT(ip_frag_mdt_allocfail);
22112 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22113 		return;
22114 	}
22115 	IP_STAT(ip_frag_mdt_allocd);
22116 
22117 	/*
22118 	 * Add a payload buffer to the Multidata; this operation must not
22119 	 * fail, or otherwise our logic in this routine is broken.  There
22120 	 * is no memory allocation done by the routine, so any returned
22121 	 * failure simply tells us that we've done something wrong.
22122 	 *
22123 	 * A failure tells us that either we're adding the same payload
22124 	 * buffer more than once, or we're trying to add more buffers than
22125 	 * allowed.  None of the above cases should happen, and we panic
22126 	 * because either there's horrible heap corruption, and/or
22127 	 * programming mistake.
22128 	 */
22129 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22130 		goto pbuf_panic;
22131 
22132 	hdr_ptr = hdr_mp->b_rptr;
22133 	pld_ptr = mp->b_rptr;
22134 
22135 	/* Establish the ending byte offset, based on the starting offset. */
22136 	offset <<= 3;
22137 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22138 	    IP_SIMPLE_HDR_LENGTH;
22139 
22140 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22141 
22142 	while (pld_ptr < mp->b_wptr) {
22143 		ipha_t		*ipha;
22144 		uint16_t	offset_and_flags;
22145 		uint16_t	ip_len;
22146 		int		error;
22147 
22148 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22149 		ipha = (ipha_t *)(hdr_ptr + wroff);
22150 		ASSERT(OK_32PTR(ipha));
22151 		*ipha = *ipha_orig;
22152 
22153 		if (ip_data_end - offset > len) {
22154 			offset_and_flags = IPH_MF;
22155 		} else {
22156 			/*
22157 			 * Last frag. Set len to the length of this last piece.
22158 			 */
22159 			len = ip_data_end - offset;
22160 			/* A frag of a frag might have IPH_MF non-zero */
22161 			offset_and_flags =
22162 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22163 			    IPH_MF;
22164 		}
22165 		offset_and_flags |= (uint16_t)(offset >> 3);
22166 		offset_and_flags |= (uint16_t)frag_flag;
22167 		/* Store the offset and flags in the IP header. */
22168 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22169 
22170 		/* Store the length in the IP header. */
22171 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22172 		ipha->ipha_length = htons(ip_len);
22173 
22174 		/*
22175 		 * Set the IP header checksum.  Note that mp is just
22176 		 * the header, so this is easy to pass to ip_csum.
22177 		 */
22178 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22179 
22180 		/*
22181 		 * Record offset and size of header and data of the next packet
22182 		 * in the multidata message.
22183 		 */
22184 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22185 		PDESC_PLD_INIT(&pdi);
22186 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22187 		ASSERT(i1 > 0);
22188 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22189 		if (i1 == len) {
22190 			pld_ptr += len;
22191 		} else {
22192 			i1 = len - i1;
22193 			mp = mp->b_cont;
22194 			ASSERT(mp != NULL);
22195 			ASSERT(MBLKL(mp) >= i1);
22196 			/*
22197 			 * Attach the next payload message block to the
22198 			 * multidata message.
22199 			 */
22200 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22201 				goto pbuf_panic;
22202 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22203 			pld_ptr = mp->b_rptr + i1;
22204 		}
22205 
22206 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22207 		    KM_NOSLEEP)) == NULL) {
22208 			/*
22209 			 * Any failure other than ENOMEM indicates that we
22210 			 * have passed in invalid pdesc info or parameters
22211 			 * to mmd_addpdesc, which must not happen.
22212 			 *
22213 			 * EINVAL is a result of failure on boundary checks
22214 			 * against the pdesc info contents.  It should not
22215 			 * happen, and we panic because either there's
22216 			 * horrible heap corruption, and/or programming
22217 			 * mistake.
22218 			 */
22219 			if (error != ENOMEM) {
22220 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22221 				    "pdesc logic error detected for "
22222 				    "mmd %p pinfo %p (%d)\n",
22223 				    (void *)mmd, (void *)&pdi, error);
22224 				/* NOTREACHED */
22225 			}
22226 			IP_STAT(ip_frag_mdt_addpdescfail);
22227 			/* Free unattached payload message blocks as well */
22228 			md_mp->b_cont = mp->b_cont;
22229 			goto free_mmd;
22230 		}
22231 
22232 		/* Advance fragment offset. */
22233 		offset += len;
22234 
22235 		/* Advance to location for next header in the buffer. */
22236 		hdr_ptr += hdr_chunk_len;
22237 
22238 		/* Did we reach the next payload message block? */
22239 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22240 			mp = mp->b_cont;
22241 			/*
22242 			 * Attach the next message block with payload
22243 			 * data to the multidata message.
22244 			 */
22245 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22246 				goto pbuf_panic;
22247 			pld_ptr = mp->b_rptr;
22248 		}
22249 	}
22250 
22251 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22252 	ASSERT(mp->b_wptr == pld_ptr);
22253 
22254 	/* Update IP statistics */
22255 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22256 	BUMP_MIB(&ip_mib, ipFragOKs);
22257 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22258 
22259 	if (pkt_type == OB_PKT) {
22260 		ire->ire_ob_pkt_count += pkts;
22261 		if (ire->ire_ipif != NULL)
22262 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22263 	} else {
22264 		/*
22265 		 * The type is IB_PKT in the forwarding path and in
22266 		 * the mobile IP case when the packet is being reverse-
22267 		 * tunneled to the home agent.
22268 		 */
22269 		ire->ire_ib_pkt_count += pkts;
22270 		ASSERT(!IRE_IS_LOCAL(ire));
22271 		if (ire->ire_type & IRE_BROADCAST)
22272 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22273 		else
22274 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22275 	}
22276 	ire->ire_last_used_time = lbolt;
22277 	/* Send it down */
22278 	putnext(ire->ire_stq, md_mp);
22279 	return;
22280 
22281 pbuf_panic:
22282 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22283 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22284 	    pbuf_idx);
22285 	/* NOTREACHED */
22286 }
22287 
22288 /*
22289  * Outbound IP fragmentation routine.
22290  *
22291  * NOTE : This routine does not ire_refrele the ire that is passed in
22292  * as the argument.
22293  */
22294 static void
22295 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22296     uint32_t frag_flag)
22297 {
22298 	int		i1;
22299 	mblk_t		*ll_hdr_mp;
22300 	int 		ll_hdr_len;
22301 	int		hdr_len;
22302 	mblk_t		*hdr_mp;
22303 	ipha_t		*ipha;
22304 	int		ip_data_end;
22305 	int		len;
22306 	mblk_t		*mp = mp_orig;
22307 	int		offset;
22308 	queue_t		*q;
22309 	uint32_t	v_hlen_tos_len;
22310 	mblk_t		*first_mp;
22311 	boolean_t	mctl_present;
22312 	ill_t		*ill;
22313 	mblk_t		*xmit_mp;
22314 	mblk_t		*carve_mp;
22315 	ire_t		*ire1 = NULL;
22316 	ire_t		*save_ire = NULL;
22317 	mblk_t  	*next_mp = NULL;
22318 	boolean_t	last_frag = B_FALSE;
22319 	boolean_t	multirt_send = B_FALSE;
22320 	ire_t		*first_ire = NULL;
22321 	irb_t		*irb = NULL;
22322 
22323 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22324 	    "ip_wput_frag_start:");
22325 
22326 	if (mp->b_datap->db_type == M_CTL) {
22327 		first_mp = mp;
22328 		mp_orig = mp = mp->b_cont;
22329 		mctl_present = B_TRUE;
22330 	} else {
22331 		first_mp = mp;
22332 		mctl_present = B_FALSE;
22333 	}
22334 
22335 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22336 	ipha = (ipha_t *)mp->b_rptr;
22337 
22338 	/*
22339 	 * If the Don't Fragment flag is on, generate an ICMP destination
22340 	 * unreachable, fragmentation needed.
22341 	 */
22342 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22343 	if (offset & IPH_DF) {
22344 		BUMP_MIB(&ip_mib, ipFragFails);
22345 		/*
22346 		 * Need to compute hdr checksum if called from ip_wput_ire.
22347 		 * Note that ip_rput_forward verifies the checksum before
22348 		 * calling this routine so in that case this is a noop.
22349 		 */
22350 		ipha->ipha_hdr_checksum = 0;
22351 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22352 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22353 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22354 		    "ip_wput_frag_end:(%S)",
22355 		    "don't fragment");
22356 		return;
22357 	}
22358 	if (mctl_present)
22359 		freeb(first_mp);
22360 	/*
22361 	 * Establish the starting offset.  May not be zero if we are fragging
22362 	 * a fragment that is being forwarded.
22363 	 */
22364 	offset = offset & IPH_OFFSET;
22365 
22366 	/* TODO why is this test needed? */
22367 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22368 	if (((max_frag - LENGTH) & ~7) < 8) {
22369 		/* TODO: notify ulp somehow */
22370 		BUMP_MIB(&ip_mib, ipFragFails);
22371 		freemsg(mp);
22372 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22373 		    "ip_wput_frag_end:(%S)",
22374 		    "len < 8");
22375 		return;
22376 	}
22377 
22378 	hdr_len = (V_HLEN & 0xF) << 2;
22379 
22380 	ipha->ipha_hdr_checksum = 0;
22381 
22382 	/*
22383 	 * Establish the number of bytes maximum per frag, after putting
22384 	 * in the header.
22385 	 */
22386 	len = (max_frag - hdr_len) & ~7;
22387 
22388 	/* Check if we can use MDT to send out the frags. */
22389 	ASSERT(!IRE_IS_LOCAL(ire));
22390 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
22391 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
22392 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
22393 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
22394 		ASSERT(ill->ill_mdt_capab != NULL);
22395 		if (!ill->ill_mdt_capab->ill_mdt_on) {
22396 			/*
22397 			 * If MDT has been previously turned off in the past,
22398 			 * and we currently can do MDT (due to IPQoS policy
22399 			 * removal, etc.) then enable it for this interface.
22400 			 */
22401 			ill->ill_mdt_capab->ill_mdt_on = 1;
22402 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
22403 			    ill->ill_name));
22404 		}
22405 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
22406 		    offset);
22407 		return;
22408 	}
22409 
22410 	/* Get a copy of the header for the trailing frags */
22411 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
22412 	if (!hdr_mp) {
22413 		BUMP_MIB(&ip_mib, ipOutDiscards);
22414 		freemsg(mp);
22415 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22416 		    "ip_wput_frag_end:(%S)",
22417 		    "couldn't copy hdr");
22418 		return;
22419 	}
22420 	if (DB_CRED(mp) != NULL)
22421 		mblk_setcred(hdr_mp, DB_CRED(mp));
22422 
22423 	/* Store the starting offset, with the MoreFrags flag. */
22424 	i1 = offset | IPH_MF | frag_flag;
22425 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
22426 
22427 	/* Establish the ending byte offset, based on the starting offset. */
22428 	offset <<= 3;
22429 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
22430 
22431 	/* Store the length of the first fragment in the IP header. */
22432 	i1 = len + hdr_len;
22433 	ASSERT(i1 <= IP_MAXPACKET);
22434 	ipha->ipha_length = htons((uint16_t)i1);
22435 
22436 	/*
22437 	 * Compute the IP header checksum for the first frag.  We have to
22438 	 * watch out that we stop at the end of the header.
22439 	 */
22440 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22441 
22442 	/*
22443 	 * Now carve off the first frag.  Note that this will include the
22444 	 * original IP header.
22445 	 */
22446 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
22447 		BUMP_MIB(&ip_mib, ipOutDiscards);
22448 		freeb(hdr_mp);
22449 		freemsg(mp_orig);
22450 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22451 		    "ip_wput_frag_end:(%S)",
22452 		    "couldn't carve first");
22453 		return;
22454 	}
22455 
22456 	/*
22457 	 * Multirouting case. Each fragment is replicated
22458 	 * via all non-condemned RTF_MULTIRT routes
22459 	 * currently resolved.
22460 	 * We ensure that first_ire is the first RTF_MULTIRT
22461 	 * ire in the bucket.
22462 	 */
22463 	if (ire->ire_flags & RTF_MULTIRT) {
22464 		irb = ire->ire_bucket;
22465 		ASSERT(irb != NULL);
22466 
22467 		multirt_send = B_TRUE;
22468 
22469 		/* Make sure we do not omit any multiroute ire. */
22470 		IRB_REFHOLD(irb);
22471 		for (first_ire = irb->irb_ire;
22472 		    first_ire != NULL;
22473 		    first_ire = first_ire->ire_next) {
22474 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22475 			    (first_ire->ire_addr == ire->ire_addr) &&
22476 			    !(first_ire->ire_marks &
22477 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22478 				break;
22479 		}
22480 
22481 		if (first_ire != NULL) {
22482 			if (first_ire != ire) {
22483 				IRE_REFHOLD(first_ire);
22484 				/*
22485 				 * Do not release the ire passed in
22486 				 * as the argument.
22487 				 */
22488 				ire = first_ire;
22489 			} else {
22490 				first_ire = NULL;
22491 			}
22492 		}
22493 		IRB_REFRELE(irb);
22494 
22495 		/*
22496 		 * Save the first ire; we will need to restore it
22497 		 * for the trailing frags.
22498 		 * We REFHOLD save_ire, as each iterated ire will be
22499 		 * REFRELEd.
22500 		 */
22501 		save_ire = ire;
22502 		IRE_REFHOLD(save_ire);
22503 	}
22504 
22505 	/*
22506 	 * First fragment emission loop.
22507 	 * In most cases, the emission loop below is entered only
22508 	 * once. Only in the case where the ire holds the RTF_MULTIRT
22509 	 * flag, do we loop to process all RTF_MULTIRT ires in the
22510 	 * bucket, and send the fragment through all crossed
22511 	 * RTF_MULTIRT routes.
22512 	 */
22513 	do {
22514 		if (ire->ire_flags & RTF_MULTIRT) {
22515 			/*
22516 			 * We are in a multiple send case, need to get
22517 			 * the next ire and make a copy of the packet.
22518 			 * ire1 holds here the next ire to process in the
22519 			 * bucket. If multirouting is expected,
22520 			 * any non-RTF_MULTIRT ire that has the
22521 			 * right destination address is ignored.
22522 			 *
22523 			 * We have to take into account the MTU of
22524 			 * each walked ire. max_frag is set by the
22525 			 * the caller and generally refers to
22526 			 * the primary ire entry. Here we ensure that
22527 			 * no route with a lower MTU will be used, as
22528 			 * fragments are carved once for all ires,
22529 			 * then replicated.
22530 			 */
22531 			ASSERT(irb != NULL);
22532 			IRB_REFHOLD(irb);
22533 			for (ire1 = ire->ire_next;
22534 			    ire1 != NULL;
22535 			    ire1 = ire1->ire_next) {
22536 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22537 					continue;
22538 				if (ire1->ire_addr != ire->ire_addr)
22539 					continue;
22540 				if (ire1->ire_marks &
22541 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22542 					continue;
22543 				/*
22544 				 * Ensure we do not exceed the MTU
22545 				 * of the next route.
22546 				 */
22547 				if (ire1->ire_max_frag < max_frag) {
22548 					ip_multirt_bad_mtu(ire1, max_frag);
22549 					continue;
22550 				}
22551 
22552 				/* Got one. */
22553 				IRE_REFHOLD(ire1);
22554 				break;
22555 			}
22556 			IRB_REFRELE(irb);
22557 
22558 			if (ire1 != NULL) {
22559 				next_mp = copyb(mp);
22560 				if ((next_mp == NULL) ||
22561 				    ((mp->b_cont != NULL) &&
22562 				    ((next_mp->b_cont =
22563 				    dupmsg(mp->b_cont)) == NULL))) {
22564 					freemsg(next_mp);
22565 					next_mp = NULL;
22566 					ire_refrele(ire1);
22567 					ire1 = NULL;
22568 				}
22569 			}
22570 
22571 			/* Last multiroute ire; don't loop anymore. */
22572 			if (ire1 == NULL) {
22573 				multirt_send = B_FALSE;
22574 			}
22575 		}
22576 
22577 		ll_hdr_len = 0;
22578 		LOCK_IRE_FP_MP(ire);
22579 		ll_hdr_mp = ire->ire_fp_mp;
22580 		if (ll_hdr_mp != NULL) {
22581 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22582 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
22583 		} else {
22584 			ll_hdr_mp = ire->ire_dlureq_mp;
22585 		}
22586 
22587 		/* If there is a transmit header, get a copy for this frag. */
22588 		/*
22589 		 * TODO: should check db_ref before calling ip_carve_mp since
22590 		 * it might give us a dup.
22591 		 */
22592 		if (!ll_hdr_mp) {
22593 			/* No xmit header. */
22594 			xmit_mp = mp;
22595 		} else if (mp->b_datap->db_ref == 1 &&
22596 		    ll_hdr_len != 0 &&
22597 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22598 			/* M_DATA fastpath */
22599 			mp->b_rptr -= ll_hdr_len;
22600 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
22601 			xmit_mp = mp;
22602 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
22603 			UNLOCK_IRE_FP_MP(ire);
22604 			BUMP_MIB(&ip_mib, ipOutDiscards);
22605 			freeb(hdr_mp);
22606 			freemsg(mp);
22607 			freemsg(mp_orig);
22608 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22609 			    "ip_wput_frag_end:(%S)",
22610 			    "discard");
22611 
22612 			if (multirt_send) {
22613 				ASSERT(ire1);
22614 				ASSERT(next_mp);
22615 
22616 				freemsg(next_mp);
22617 				ire_refrele(ire1);
22618 			}
22619 			if (save_ire != NULL)
22620 				IRE_REFRELE(save_ire);
22621 
22622 			if (first_ire != NULL)
22623 				ire_refrele(first_ire);
22624 			return;
22625 		} else {
22626 			xmit_mp->b_cont = mp;
22627 			if (DB_CRED(mp) != NULL)
22628 				mblk_setcred(xmit_mp, DB_CRED(mp));
22629 			/* Get priority marking, if any. */
22630 			if (DB_TYPE(xmit_mp) == M_DATA)
22631 				xmit_mp->b_band = mp->b_band;
22632 		}
22633 		UNLOCK_IRE_FP_MP(ire);
22634 		q = ire->ire_stq;
22635 		BUMP_MIB(&ip_mib, ipFragCreates);
22636 		putnext(q, xmit_mp);
22637 		if (pkt_type != OB_PKT) {
22638 			/*
22639 			 * Update the packet count of trailing
22640 			 * RTF_MULTIRT ires.
22641 			 */
22642 			UPDATE_OB_PKT_COUNT(ire);
22643 		}
22644 
22645 		if (multirt_send) {
22646 			/*
22647 			 * We are in a multiple send case; look for
22648 			 * the next ire and re-enter the loop.
22649 			 */
22650 			ASSERT(ire1);
22651 			ASSERT(next_mp);
22652 			/* REFRELE the current ire before looping */
22653 			ire_refrele(ire);
22654 			ire = ire1;
22655 			ire1 = NULL;
22656 			mp = next_mp;
22657 			next_mp = NULL;
22658 		}
22659 	} while (multirt_send);
22660 
22661 	ASSERT(ire1 == NULL);
22662 
22663 	/* Restore the original ire; we need it for the trailing frags */
22664 	if (save_ire != NULL) {
22665 		/* REFRELE the last iterated ire */
22666 		ire_refrele(ire);
22667 		/* save_ire has been REFHOLDed */
22668 		ire = save_ire;
22669 		save_ire = NULL;
22670 		q = ire->ire_stq;
22671 	}
22672 
22673 	if (pkt_type == OB_PKT) {
22674 		UPDATE_OB_PKT_COUNT(ire);
22675 	} else {
22676 		UPDATE_IB_PKT_COUNT(ire);
22677 	}
22678 
22679 	/* Advance the offset to the second frag starting point. */
22680 	offset += len;
22681 	/*
22682 	 * Update hdr_len from the copied header - there might be less options
22683 	 * in the later fragments.
22684 	 */
22685 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
22686 	/* Loop until done. */
22687 	for (;;) {
22688 		uint16_t	offset_and_flags;
22689 		uint16_t	ip_len;
22690 
22691 		if (ip_data_end - offset > len) {
22692 			/*
22693 			 * Carve off the appropriate amount from the original
22694 			 * datagram.
22695 			 */
22696 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22697 				mp = NULL;
22698 				break;
22699 			}
22700 			/*
22701 			 * More frags after this one.  Get another copy
22702 			 * of the header.
22703 			 */
22704 			if (carve_mp->b_datap->db_ref == 1 &&
22705 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22706 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22707 				/* Inline IP header */
22708 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22709 				    hdr_mp->b_rptr;
22710 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22711 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22712 				mp = carve_mp;
22713 			} else {
22714 				if (!(mp = copyb(hdr_mp))) {
22715 					freemsg(carve_mp);
22716 					break;
22717 				}
22718 				/* Get priority marking, if any. */
22719 				mp->b_band = carve_mp->b_band;
22720 				mp->b_cont = carve_mp;
22721 			}
22722 			ipha = (ipha_t *)mp->b_rptr;
22723 			offset_and_flags = IPH_MF;
22724 		} else {
22725 			/*
22726 			 * Last frag.  Consume the header. Set len to
22727 			 * the length of this last piece.
22728 			 */
22729 			len = ip_data_end - offset;
22730 
22731 			/*
22732 			 * Carve off the appropriate amount from the original
22733 			 * datagram.
22734 			 */
22735 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22736 				mp = NULL;
22737 				break;
22738 			}
22739 			if (carve_mp->b_datap->db_ref == 1 &&
22740 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22741 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22742 				/* Inline IP header */
22743 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22744 				    hdr_mp->b_rptr;
22745 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22746 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22747 				mp = carve_mp;
22748 				freeb(hdr_mp);
22749 				hdr_mp = mp;
22750 			} else {
22751 				mp = hdr_mp;
22752 				/* Get priority marking, if any. */
22753 				mp->b_band = carve_mp->b_band;
22754 				mp->b_cont = carve_mp;
22755 			}
22756 			ipha = (ipha_t *)mp->b_rptr;
22757 			/* A frag of a frag might have IPH_MF non-zero */
22758 			offset_and_flags =
22759 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22760 			    IPH_MF;
22761 		}
22762 		offset_and_flags |= (uint16_t)(offset >> 3);
22763 		offset_and_flags |= (uint16_t)frag_flag;
22764 		/* Store the offset and flags in the IP header. */
22765 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22766 
22767 		/* Store the length in the IP header. */
22768 		ip_len = (uint16_t)(len + hdr_len);
22769 		ipha->ipha_length = htons(ip_len);
22770 
22771 		/*
22772 		 * Set the IP header checksum.	Note that mp is just
22773 		 * the header, so this is easy to pass to ip_csum.
22774 		 */
22775 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22776 
22777 		/* Attach a transmit header, if any, and ship it. */
22778 		if (pkt_type == OB_PKT) {
22779 			UPDATE_OB_PKT_COUNT(ire);
22780 		} else {
22781 			UPDATE_IB_PKT_COUNT(ire);
22782 		}
22783 
22784 		if (ire->ire_flags & RTF_MULTIRT) {
22785 			irb = ire->ire_bucket;
22786 			ASSERT(irb != NULL);
22787 
22788 			multirt_send = B_TRUE;
22789 
22790 			/*
22791 			 * Save the original ire; we will need to restore it
22792 			 * for the tailing frags.
22793 			 */
22794 			save_ire = ire;
22795 			IRE_REFHOLD(save_ire);
22796 		}
22797 		/*
22798 		 * Emission loop for this fragment, similar
22799 		 * to what is done for the first fragment.
22800 		 */
22801 		do {
22802 			if (multirt_send) {
22803 				/*
22804 				 * We are in a multiple send case, need to get
22805 				 * the next ire and make a copy of the packet.
22806 				 */
22807 				ASSERT(irb != NULL);
22808 				IRB_REFHOLD(irb);
22809 				for (ire1 = ire->ire_next;
22810 				    ire1 != NULL;
22811 				    ire1 = ire1->ire_next) {
22812 					if (!(ire1->ire_flags & RTF_MULTIRT))
22813 						continue;
22814 					if (ire1->ire_addr != ire->ire_addr)
22815 						continue;
22816 					if (ire1->ire_marks &
22817 					    (IRE_MARK_CONDEMNED|
22818 						IRE_MARK_HIDDEN))
22819 						continue;
22820 					/*
22821 					 * Ensure we do not exceed the MTU
22822 					 * of the next route.
22823 					 */
22824 					if (ire1->ire_max_frag < max_frag) {
22825 						ip_multirt_bad_mtu(ire1,
22826 						    max_frag);
22827 						continue;
22828 					}
22829 
22830 					/* Got one. */
22831 					IRE_REFHOLD(ire1);
22832 					break;
22833 				}
22834 				IRB_REFRELE(irb);
22835 
22836 				if (ire1 != NULL) {
22837 					next_mp = copyb(mp);
22838 					if ((next_mp == NULL) ||
22839 					    ((mp->b_cont != NULL) &&
22840 					    ((next_mp->b_cont =
22841 					    dupmsg(mp->b_cont)) == NULL))) {
22842 						freemsg(next_mp);
22843 						next_mp = NULL;
22844 						ire_refrele(ire1);
22845 						ire1 = NULL;
22846 					}
22847 				}
22848 
22849 				/* Last multiroute ire; don't loop anymore. */
22850 				if (ire1 == NULL) {
22851 					multirt_send = B_FALSE;
22852 				}
22853 			}
22854 
22855 			/* Update transmit header */
22856 			ll_hdr_len = 0;
22857 			LOCK_IRE_FP_MP(ire);
22858 			ll_hdr_mp = ire->ire_fp_mp;
22859 			if (ll_hdr_mp != NULL) {
22860 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22861 				ll_hdr_len = MBLKL(ll_hdr_mp);
22862 			} else {
22863 				ll_hdr_mp = ire->ire_dlureq_mp;
22864 			}
22865 
22866 			if (!ll_hdr_mp) {
22867 				xmit_mp = mp;
22868 			} else if (mp->b_datap->db_ref == 1 &&
22869 			    ll_hdr_len != 0 &&
22870 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22871 				/* M_DATA fastpath */
22872 				mp->b_rptr -= ll_hdr_len;
22873 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22874 				    ll_hdr_len);
22875 				xmit_mp = mp;
22876 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22877 				xmit_mp->b_cont = mp;
22878 				if (DB_CRED(mp) != NULL)
22879 					mblk_setcred(xmit_mp, DB_CRED(mp));
22880 				/* Get priority marking, if any. */
22881 				if (DB_TYPE(xmit_mp) == M_DATA)
22882 					xmit_mp->b_band = mp->b_band;
22883 			} else {
22884 				/*
22885 				 * Exit both the replication and
22886 				 * fragmentation loops.
22887 				 */
22888 				UNLOCK_IRE_FP_MP(ire);
22889 				goto drop_pkt;
22890 			}
22891 			UNLOCK_IRE_FP_MP(ire);
22892 			BUMP_MIB(&ip_mib, ipFragCreates);
22893 			putnext(q, xmit_mp);
22894 
22895 			if (pkt_type != OB_PKT) {
22896 				/*
22897 				 * Update the packet count of trailing
22898 				 * RTF_MULTIRT ires.
22899 				 */
22900 				UPDATE_OB_PKT_COUNT(ire);
22901 			}
22902 
22903 			/* All done if we just consumed the hdr_mp. */
22904 			if (mp == hdr_mp) {
22905 				last_frag = B_TRUE;
22906 			}
22907 
22908 			if (multirt_send) {
22909 				/*
22910 				 * We are in a multiple send case; look for
22911 				 * the next ire and re-enter the loop.
22912 				 */
22913 				ASSERT(ire1);
22914 				ASSERT(next_mp);
22915 				/* REFRELE the current ire before looping */
22916 				ire_refrele(ire);
22917 				ire = ire1;
22918 				ire1 = NULL;
22919 				q = ire->ire_stq;
22920 				mp = next_mp;
22921 				next_mp = NULL;
22922 			}
22923 		} while (multirt_send);
22924 		/*
22925 		 * Restore the original ire; we need it for the
22926 		 * trailing frags
22927 		 */
22928 		if (save_ire != NULL) {
22929 			ASSERT(ire1 == NULL);
22930 			/* REFRELE the last iterated ire */
22931 			ire_refrele(ire);
22932 			/* save_ire has been REFHOLDed */
22933 			ire = save_ire;
22934 			q = ire->ire_stq;
22935 			save_ire = NULL;
22936 		}
22937 
22938 		if (last_frag) {
22939 			BUMP_MIB(&ip_mib, ipFragOKs);
22940 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22941 			    "ip_wput_frag_end:(%S)",
22942 			    "consumed hdr_mp");
22943 
22944 			if (first_ire != NULL)
22945 				ire_refrele(first_ire);
22946 			return;
22947 		}
22948 		/* Otherwise, advance and loop. */
22949 		offset += len;
22950 	}
22951 
22952 drop_pkt:
22953 	/* Clean up following allocation failure. */
22954 	BUMP_MIB(&ip_mib, ipOutDiscards);
22955 	freemsg(mp);
22956 	if (mp != hdr_mp)
22957 		freeb(hdr_mp);
22958 	if (mp != mp_orig)
22959 		freemsg(mp_orig);
22960 
22961 	if (save_ire != NULL)
22962 		IRE_REFRELE(save_ire);
22963 	if (first_ire != NULL)
22964 		ire_refrele(first_ire);
22965 
22966 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22967 	    "ip_wput_frag_end:(%S)",
22968 	    "end--alloc failure");
22969 }
22970 
22971 /*
22972  * Copy the header plus those options which have the copy bit set
22973  */
22974 static mblk_t *
22975 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22976 {
22977 	mblk_t	*mp;
22978 	uchar_t	*up;
22979 
22980 	/*
22981 	 * Quick check if we need to look for options without the copy bit
22982 	 * set
22983 	 */
22984 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22985 	if (!mp)
22986 		return (mp);
22987 	mp->b_rptr += ip_wroff_extra;
22988 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22989 		bcopy(rptr, mp->b_rptr, hdr_len);
22990 		mp->b_wptr += hdr_len + ip_wroff_extra;
22991 		return (mp);
22992 	}
22993 	up  = mp->b_rptr;
22994 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22995 	up += IP_SIMPLE_HDR_LENGTH;
22996 	rptr += IP_SIMPLE_HDR_LENGTH;
22997 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
22998 	while (hdr_len > 0) {
22999 		uint32_t optval;
23000 		uint32_t optlen;
23001 
23002 		optval = *rptr;
23003 		if (optval == IPOPT_EOL)
23004 			break;
23005 		if (optval == IPOPT_NOP)
23006 			optlen = 1;
23007 		else
23008 			optlen = rptr[1];
23009 		if (optval & IPOPT_COPY) {
23010 			bcopy(rptr, up, optlen);
23011 			up += optlen;
23012 		}
23013 		rptr += optlen;
23014 		hdr_len -= optlen;
23015 	}
23016 	/*
23017 	 * Make sure that we drop an even number of words by filling
23018 	 * with EOL to the next word boundary.
23019 	 */
23020 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23021 	    hdr_len & 0x3; hdr_len++)
23022 		*up++ = IPOPT_EOL;
23023 	mp->b_wptr = up;
23024 	/* Update header length */
23025 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23026 	return (mp);
23027 }
23028 
23029 /*
23030  * Delivery to local recipients including fanout to multiple recipients.
23031  * Does not do checksumming of UDP/TCP.
23032  * Note: q should be the read side queue for either the ill or conn.
23033  * Note: rq should be the read side q for the lower (ill) stream.
23034  * We don't send packets to IPPF processing, thus the last argument
23035  * to all the fanout calls are B_FALSE.
23036  */
23037 void
23038 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23039     int fanout_flags, zoneid_t zoneid)
23040 {
23041 	uint32_t	protocol;
23042 	mblk_t		*first_mp;
23043 	boolean_t	mctl_present;
23044 	int		ire_type;
23045 #define	rptr	((uchar_t *)ipha)
23046 
23047 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23048 	    "ip_wput_local_start: q %p", q);
23049 
23050 	if (ire != NULL) {
23051 		ire_type = ire->ire_type;
23052 	} else {
23053 		/*
23054 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23055 		 * packet is not multicast, we can't tell the ire type.
23056 		 */
23057 		ASSERT(CLASSD(ipha->ipha_dst));
23058 		ire_type = IRE_BROADCAST;
23059 	}
23060 
23061 	first_mp = mp;
23062 	if (first_mp->b_datap->db_type == M_CTL) {
23063 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23064 		if (!io->ipsec_out_secure) {
23065 			/*
23066 			 * This ipsec_out_t was allocated in ip_wput
23067 			 * for multicast packets to store the ill_index.
23068 			 * As this is being delivered locally, we don't
23069 			 * need this anymore.
23070 			 */
23071 			mp = first_mp->b_cont;
23072 			freeb(first_mp);
23073 			first_mp = mp;
23074 			mctl_present = B_FALSE;
23075 		} else {
23076 			mctl_present = B_TRUE;
23077 			mp = first_mp->b_cont;
23078 			ASSERT(mp != NULL);
23079 			ipsec_out_to_in(first_mp);
23080 		}
23081 	} else {
23082 		mctl_present = B_FALSE;
23083 	}
23084 
23085 	loopback_packets++;
23086 
23087 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23088 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23089 	if (!IS_SIMPLE_IPH(ipha)) {
23090 		ip_wput_local_options(ipha);
23091 	}
23092 
23093 	protocol = ipha->ipha_protocol;
23094 	switch (protocol) {
23095 	case IPPROTO_ICMP: {
23096 		ire_t		*ire_zone;
23097 		ilm_t		*ilm;
23098 		mblk_t		*mp1;
23099 		zoneid_t	last_zoneid;
23100 
23101 		if (CLASSD(ipha->ipha_dst) &&
23102 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23103 			ASSERT(ire_type == IRE_BROADCAST);
23104 			/*
23105 			 * In the multicast case, applications may have joined
23106 			 * the group from different zones, so we need to deliver
23107 			 * the packet to each of them. Loop through the
23108 			 * multicast memberships structures (ilm) on the receive
23109 			 * ill and send a copy of the packet up each matching
23110 			 * one. However, we don't do this for multicasts sent on
23111 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23112 			 * they must stay in the sender's zone.
23113 			 *
23114 			 * ilm_add_v6() ensures that ilms in the same zone are
23115 			 * contiguous in the ill_ilm list. We use this property
23116 			 * to avoid sending duplicates needed when two
23117 			 * applications in the same zone join the same group on
23118 			 * different logical interfaces: we ignore the ilm if
23119 			 * its zoneid is the same as the last matching one.
23120 			 * In addition, the sending of the packet for
23121 			 * ire_zoneid is delayed until all of the other ilms
23122 			 * have been exhausted.
23123 			 */
23124 			last_zoneid = -1;
23125 			ILM_WALKER_HOLD(ill);
23126 			for (ilm = ill->ill_ilm; ilm != NULL;
23127 			    ilm = ilm->ilm_next) {
23128 				if ((ilm->ilm_flags & ILM_DELETED) ||
23129 				    ipha->ipha_dst != ilm->ilm_addr ||
23130 				    ilm->ilm_zoneid == last_zoneid ||
23131 				    ilm->ilm_zoneid == zoneid ||
23132 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23133 					continue;
23134 				mp1 = ip_copymsg(first_mp);
23135 				if (mp1 == NULL)
23136 					continue;
23137 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23138 				    mctl_present, B_FALSE, ill,
23139 				    ilm->ilm_zoneid);
23140 				last_zoneid = ilm->ilm_zoneid;
23141 			}
23142 			ILM_WALKER_RELE(ill);
23143 			/*
23144 			 * Loopback case: the sending endpoint has
23145 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23146 			 * dispatch the multicast packet to the sending zone.
23147 			 */
23148 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23149 				freemsg(first_mp);
23150 				return;
23151 			}
23152 		} else if (ire_type == IRE_BROADCAST) {
23153 			/*
23154 			 * In the broadcast case, there may be many zones
23155 			 * which need a copy of the packet delivered to them.
23156 			 * There is one IRE_BROADCAST per broadcast address
23157 			 * and per zone; we walk those using a helper function.
23158 			 * In addition, the sending of the packet for zoneid is
23159 			 * delayed until all of the other ires have been
23160 			 * processed.
23161 			 */
23162 			IRB_REFHOLD(ire->ire_bucket);
23163 			ire_zone = NULL;
23164 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23165 			    ire)) != NULL) {
23166 				mp1 = ip_copymsg(first_mp);
23167 				if (mp1 == NULL)
23168 					continue;
23169 
23170 				UPDATE_IB_PKT_COUNT(ire_zone);
23171 				ire_zone->ire_last_used_time = lbolt;
23172 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23173 				    mctl_present, B_FALSE, ill,
23174 				    ire_zone->ire_zoneid);
23175 			}
23176 			IRB_REFRELE(ire->ire_bucket);
23177 		}
23178 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23179 		    0, mctl_present, B_FALSE, ill, zoneid);
23180 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23181 		    "ip_wput_local_end: q %p (%S)",
23182 		    q, "icmp");
23183 		return;
23184 	}
23185 	case IPPROTO_IGMP:
23186 		if (igmp_input(q, mp, ill)) {
23187 			/* Bad packet - discarded by igmp_input */
23188 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23189 			    "ip_wput_local_end: q %p (%S)",
23190 			    q, "igmp_input--bad packet");
23191 			if (mctl_present)
23192 				freeb(first_mp);
23193 			return;
23194 		}
23195 		/*
23196 		 * igmp_input() may have pulled up the message so ipha needs to
23197 		 * be reinitialized.
23198 		 */
23199 		ipha = (ipha_t *)mp->b_rptr;
23200 		/* deliver to local raw users */
23201 		break;
23202 	case IPPROTO_ENCAP:
23203 		/*
23204 		 * This case is covered by either ip_fanout_proto, or by
23205 		 * the above security processing for self-tunneled packets.
23206 		 */
23207 		break;
23208 	case IPPROTO_UDP: {
23209 		uint16_t	*up;
23210 		uint32_t	ports;
23211 
23212 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23213 		    UDP_PORTS_OFFSET);
23214 		/* Force a 'valid' checksum. */
23215 		up[3] = 0;
23216 
23217 		ports = *(uint32_t *)up;
23218 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23219 		    (ire_type == IRE_BROADCAST),
23220 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23221 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23222 		    ill, zoneid);
23223 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23224 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23225 		return;
23226 	}
23227 	case IPPROTO_TCP: {
23228 
23229 		/*
23230 		 * For TCP, discard broadcast packets.
23231 		 */
23232 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23233 			freemsg(first_mp);
23234 			BUMP_MIB(&ip_mib, ipInDiscards);
23235 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23236 			return;
23237 		}
23238 
23239 		if (mp->b_datap->db_type == M_DATA) {
23240 			/*
23241 			 * M_DATA mblk, so init mblk (chain) for no struio().
23242 			 */
23243 			mblk_t	*mp1 = mp;
23244 
23245 			do
23246 				mp1->b_datap->db_struioflag = 0;
23247 			while ((mp1 = mp1->b_cont) != NULL);
23248 		}
23249 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23250 		    <= mp->b_wptr);
23251 		ip_fanout_tcp(q, first_mp, ill, ipha,
23252 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23253 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23254 		    mctl_present, B_FALSE, zoneid);
23255 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23256 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23257 		return;
23258 	}
23259 	case IPPROTO_SCTP:
23260 	{
23261 		uint32_t	ports;
23262 
23263 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23264 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23265 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23266 		    IP_FF_IP6INFO,
23267 		    mctl_present, B_FALSE, 0, zoneid);
23268 		return;
23269 	}
23270 
23271 	default:
23272 		break;
23273 	}
23274 	/*
23275 	 * Find a client for some other protocol.  We give
23276 	 * copies to multiple clients, if more than one is
23277 	 * bound.
23278 	 */
23279 	ip_fanout_proto(q, first_mp, ill, ipha,
23280 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23281 	    mctl_present, B_FALSE, ill, zoneid);
23282 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23283 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23284 #undef	rptr
23285 }
23286 
23287 /*
23288  * Update any source route, record route, or timestamp options.
23289  * Check that we are at end of strict source route.
23290  * The options have been sanity checked by ip_wput_options().
23291  */
23292 static void
23293 ip_wput_local_options(ipha_t *ipha)
23294 {
23295 	ipoptp_t	opts;
23296 	uchar_t		*opt;
23297 	uint8_t		optval;
23298 	uint8_t		optlen;
23299 	ipaddr_t	dst;
23300 	uint32_t	ts;
23301 	ire_t		*ire;
23302 	timestruc_t	now;
23303 
23304 	ip2dbg(("ip_wput_local_options\n"));
23305 	for (optval = ipoptp_first(&opts, ipha);
23306 	    optval != IPOPT_EOL;
23307 	    optval = ipoptp_next(&opts)) {
23308 		opt = opts.ipoptp_cur;
23309 		optlen = opts.ipoptp_len;
23310 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23311 		switch (optval) {
23312 			uint32_t off;
23313 		case IPOPT_SSRR:
23314 		case IPOPT_LSRR:
23315 			off = opt[IPOPT_OFFSET];
23316 			off--;
23317 			if (optlen < IP_ADDR_LEN ||
23318 			    off > optlen - IP_ADDR_LEN) {
23319 				/* End of source route */
23320 				break;
23321 			}
23322 			/*
23323 			 * This will only happen if two consecutive entries
23324 			 * in the source route contains our address or if
23325 			 * it is a packet with a loose source route which
23326 			 * reaches us before consuming the whole source route
23327 			 */
23328 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23329 			if (optval == IPOPT_SSRR) {
23330 				return;
23331 			}
23332 			/*
23333 			 * Hack: instead of dropping the packet truncate the
23334 			 * source route to what has been used by filling the
23335 			 * rest with IPOPT_NOP.
23336 			 */
23337 			opt[IPOPT_OLEN] = (uint8_t)off;
23338 			while (off < optlen) {
23339 				opt[off++] = IPOPT_NOP;
23340 			}
23341 			break;
23342 		case IPOPT_RR:
23343 			off = opt[IPOPT_OFFSET];
23344 			off--;
23345 			if (optlen < IP_ADDR_LEN ||
23346 			    off > optlen - IP_ADDR_LEN) {
23347 				/* No more room - ignore */
23348 				ip1dbg((
23349 				    "ip_wput_forward_options: end of RR\n"));
23350 				break;
23351 			}
23352 			dst = htonl(INADDR_LOOPBACK);
23353 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23354 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23355 			break;
23356 		case IPOPT_TS:
23357 			/* Insert timestamp if there is romm */
23358 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23359 			case IPOPT_TS_TSONLY:
23360 				off = IPOPT_TS_TIMELEN;
23361 				break;
23362 			case IPOPT_TS_PRESPEC:
23363 			case IPOPT_TS_PRESPEC_RFC791:
23364 				/* Verify that the address matched */
23365 				off = opt[IPOPT_OFFSET] - 1;
23366 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
23367 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
23368 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
23369 				if (ire == NULL) {
23370 					/* Not for us */
23371 					break;
23372 				}
23373 				ire_refrele(ire);
23374 				/* FALLTHRU */
23375 			case IPOPT_TS_TSANDADDR:
23376 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
23377 				break;
23378 			default:
23379 				/*
23380 				 * ip_*put_options should have already
23381 				 * dropped this packet.
23382 				 */
23383 				cmn_err(CE_PANIC, "ip_wput_local_options: "
23384 				    "unknown IT - bug in ip_wput_options?\n");
23385 				return;	/* Keep "lint" happy */
23386 			}
23387 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
23388 				/* Increase overflow counter */
23389 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
23390 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
23391 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
23392 				    (off << 4);
23393 				break;
23394 			}
23395 			off = opt[IPOPT_OFFSET] - 1;
23396 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23397 			case IPOPT_TS_PRESPEC:
23398 			case IPOPT_TS_PRESPEC_RFC791:
23399 			case IPOPT_TS_TSANDADDR:
23400 				dst = htonl(INADDR_LOOPBACK);
23401 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23402 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23403 				/* FALLTHRU */
23404 			case IPOPT_TS_TSONLY:
23405 				off = opt[IPOPT_OFFSET] - 1;
23406 				/* Compute # of milliseconds since midnight */
23407 				gethrestime(&now);
23408 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
23409 				    now.tv_nsec / (NANOSEC / MILLISEC);
23410 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
23411 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
23412 				break;
23413 			}
23414 			break;
23415 		}
23416 	}
23417 }
23418 
23419 /*
23420  * Send out a multicast packet on interface ipif.
23421  * The sender does not have an conn.
23422  * Caller verifies that this isn't a PHYI_LOOPBACK.
23423  */
23424 void
23425 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
23426 {
23427 	ipha_t	*ipha;
23428 	ire_t	*ire;
23429 	ipaddr_t	dst;
23430 	mblk_t		*first_mp;
23431 
23432 	/* igmp_sendpkt always allocates a ipsec_out_t */
23433 	ASSERT(mp->b_datap->db_type == M_CTL);
23434 	ASSERT(!ipif->ipif_isv6);
23435 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
23436 
23437 	first_mp = mp;
23438 	mp = first_mp->b_cont;
23439 	ASSERT(mp->b_datap->db_type == M_DATA);
23440 	ipha = (ipha_t *)mp->b_rptr;
23441 
23442 	/*
23443 	 * Find an IRE which matches the destination and the outgoing
23444 	 * queue (i.e. the outgoing interface.)
23445 	 */
23446 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
23447 		dst = ipif->ipif_pp_dst_addr;
23448 	else
23449 		dst = ipha->ipha_dst;
23450 	/*
23451 	 * The source address has already been initialized by the
23452 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
23453 	 * be sufficient rather than MATCH_IRE_IPIF.
23454 	 *
23455 	 * This function is used for sending IGMP packets. We need
23456 	 * to make sure that we send the packet out of the interface
23457 	 * (ipif->ipif_ill) where we joined the group. This is to
23458 	 * prevent from switches doing IGMP snooping to send us multicast
23459 	 * packets for a given group on the interface we have joined.
23460 	 * If we can't find an ire, igmp_sendpkt has already initialized
23461 	 * ipsec_out_attach_if so that this will not be load spread in
23462 	 * ip_newroute_ipif.
23463 	 */
23464 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
23465 	    MATCH_IRE_ILL);
23466 	if (!ire) {
23467 		/*
23468 		 * Mark this packet to make it be delivered to
23469 		 * ip_wput_ire after the new ire has been
23470 		 * created.
23471 		 */
23472 		mp->b_prev = NULL;
23473 		mp->b_next = NULL;
23474 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
23475 		return;
23476 	}
23477 
23478 	/*
23479 	 * Honor the RTF_SETSRC flag; this is the only case
23480 	 * where we force this addr whatever the current src addr is,
23481 	 * because this address is set by igmp_sendpkt(), and
23482 	 * cannot be specified by any user.
23483 	 */
23484 	if (ire->ire_flags & RTF_SETSRC) {
23485 		ipha->ipha_src = ire->ire_src_addr;
23486 	}
23487 
23488 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
23489 }
23490 
23491 /*
23492  * NOTE : This function does not ire_refrele the ire argument passed in.
23493  *
23494  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
23495  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
23496  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
23497  * the ire_lock to access the ire_fp_mp in this case.
23498  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
23499  * prepending a fastpath message IPQoS processing must precede it, we also set
23500  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
23501  * (IPQoS might have set the b_band for CoS marking).
23502  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
23503  * must follow it so that IPQoS can mark the dl_priority field for CoS
23504  * marking, if needed.
23505  */
23506 static mblk_t *
23507 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
23508 {
23509 	uint_t	hlen;
23510 	ipha_t *ipha;
23511 	mblk_t *mp1;
23512 	boolean_t qos_done = B_FALSE;
23513 	uchar_t	*ll_hdr;
23514 
23515 #define	rptr	((uchar_t *)ipha)
23516 
23517 	ipha = (ipha_t *)mp->b_rptr;
23518 	hlen = 0;
23519 	LOCK_IRE_FP_MP(ire);
23520 	if ((mp1 = ire->ire_fp_mp) != NULL) {
23521 		ASSERT(DB_TYPE(mp1) == M_DATA);
23522 		/* Initiate IPPF processing */
23523 		if ((proc != 0) && IPP_ENABLED(proc)) {
23524 			UNLOCK_IRE_FP_MP(ire);
23525 			ip_process(proc, &mp, ill_index);
23526 			if (mp == NULL)
23527 				return (NULL);
23528 
23529 			ipha = (ipha_t *)mp->b_rptr;
23530 			LOCK_IRE_FP_MP(ire);
23531 			if ((mp1 = ire->ire_fp_mp) == NULL) {
23532 				qos_done = B_TRUE;
23533 				goto no_fp_mp;
23534 			}
23535 			ASSERT(DB_TYPE(mp1) == M_DATA);
23536 		}
23537 		hlen = MBLKL(mp1);
23538 		/*
23539 		 * Check if we have enough room to prepend fastpath
23540 		 * header
23541 		 */
23542 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
23543 			ll_hdr = rptr - hlen;
23544 			bcopy(mp1->b_rptr, ll_hdr, hlen);
23545 			/* XXX ipha is not aligned here */
23546 			ipha = (ipha_t *)(rptr - hlen);
23547 			/*
23548 			 * Set the b_rptr to the start of the link layer
23549 			 * header
23550 			 */
23551 			mp->b_rptr = rptr;
23552 			mp1 = mp;
23553 		} else {
23554 			mp1 = copyb(mp1);
23555 			if (mp1 == NULL)
23556 				goto unlock_err;
23557 			mp1->b_band = mp->b_band;
23558 			mp1->b_cont = mp;
23559 			/*
23560 			 * certain system generated traffic may not
23561 			 * have cred/label in ip header block. This
23562 			 * is true even for a labeled system. But for
23563 			 * labeled traffic, inherit the label in the
23564 			 * new header.
23565 			 */
23566 			if (DB_CRED(mp) != NULL)
23567 				mblk_setcred(mp1, DB_CRED(mp));
23568 			/*
23569 			 * XXX disable ICK_VALID and compute checksum
23570 			 * here; can happen if ire_fp_mp changes and
23571 			 * it can't be copied now due to insufficient
23572 			 * space. (unlikely, fp mp can change, but it
23573 			 * does not increase in length)
23574 			 */
23575 		}
23576 		UNLOCK_IRE_FP_MP(ire);
23577 	} else {
23578 no_fp_mp:
23579 		mp1 = copyb(ire->ire_dlureq_mp);
23580 		if (mp1 == NULL) {
23581 unlock_err:
23582 			UNLOCK_IRE_FP_MP(ire);
23583 			freemsg(mp);
23584 			return (NULL);
23585 		}
23586 		UNLOCK_IRE_FP_MP(ire);
23587 		mp1->b_cont = mp;
23588 		/*
23589 		 * certain system generated traffic may not
23590 		 * have cred/label in ip header block. This
23591 		 * is true even for a labeled system. But for
23592 		 * labeled traffic, inherit the label in the
23593 		 * new header.
23594 		 */
23595 		if (DB_CRED(mp) != NULL)
23596 			mblk_setcred(mp1, DB_CRED(mp));
23597 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
23598 			ip_process(proc, &mp1, ill_index);
23599 			if (mp1 == NULL)
23600 				return (NULL);
23601 		}
23602 	}
23603 	return (mp1);
23604 #undef rptr
23605 }
23606 
23607 /*
23608  * Finish the outbound IPsec processing for an IPv6 packet. This function
23609  * is called from ipsec_out_process() if the IPsec packet was processed
23610  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23611  * asynchronously.
23612  */
23613 void
23614 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
23615     ire_t *ire_arg)
23616 {
23617 	in6_addr_t *v6dstp;
23618 	ire_t *ire;
23619 	mblk_t *mp;
23620 	uint_t	ill_index;
23621 	ipsec_out_t *io;
23622 	boolean_t attach_if, hwaccel;
23623 	uint32_t flags = IP6_NO_IPPOLICY;
23624 	int match_flags;
23625 	zoneid_t zoneid;
23626 	boolean_t ill_need_rele = B_FALSE;
23627 	boolean_t ire_need_rele = B_FALSE;
23628 
23629 	mp = ipsec_mp->b_cont;
23630 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23631 	ill_index = io->ipsec_out_ill_index;
23632 	if (io->ipsec_out_reachable) {
23633 		flags |= IPV6_REACHABILITY_CONFIRMATION;
23634 	}
23635 	attach_if = io->ipsec_out_attach_if;
23636 	hwaccel = io->ipsec_out_accelerated;
23637 	zoneid = io->ipsec_out_zoneid;
23638 	ASSERT(zoneid != ALL_ZONES);
23639 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23640 	/* Multicast addresses should have non-zero ill_index. */
23641 	v6dstp = &ip6h->ip6_dst;
23642 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
23643 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
23644 	ASSERT(!attach_if || ill_index != 0);
23645 	if (ill_index != 0) {
23646 		if (ill == NULL) {
23647 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
23648 			    B_TRUE);
23649 
23650 			/* Failure case frees things for us. */
23651 			if (ill == NULL)
23652 				return;
23653 
23654 			ill_need_rele = B_TRUE;
23655 		}
23656 		/*
23657 		 * If this packet needs to go out on a particular interface
23658 		 * honor it.
23659 		 */
23660 		if (attach_if) {
23661 			match_flags = MATCH_IRE_ILL;
23662 
23663 			/*
23664 			 * Check if we need an ire that will not be
23665 			 * looked up by anybody else i.e. HIDDEN.
23666 			 */
23667 			if (ill_is_probeonly(ill)) {
23668 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23669 			}
23670 		}
23671 	}
23672 	ASSERT(mp != NULL);
23673 
23674 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
23675 		boolean_t unspec_src;
23676 		ipif_t	*ipif;
23677 
23678 		/*
23679 		 * Use the ill_index to get the right ill.
23680 		 */
23681 		unspec_src = io->ipsec_out_unspec_src;
23682 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23683 		if (ipif == NULL) {
23684 			if (ill_need_rele)
23685 				ill_refrele(ill);
23686 			freemsg(ipsec_mp);
23687 			return;
23688 		}
23689 
23690 		if (ire_arg != NULL) {
23691 			ire = ire_arg;
23692 		} else {
23693 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23694 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23695 			ire_need_rele = B_TRUE;
23696 		}
23697 		if (ire != NULL) {
23698 			ipif_refrele(ipif);
23699 			/*
23700 			 * XXX Do the multicast forwarding now, as the IPSEC
23701 			 * processing has been done.
23702 			 */
23703 			goto send;
23704 		}
23705 
23706 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
23707 		mp->b_prev = NULL;
23708 		mp->b_next = NULL;
23709 
23710 		/*
23711 		 * If the IPsec packet was processed asynchronously,
23712 		 * drop it now.
23713 		 */
23714 		if (q == NULL) {
23715 			if (ill_need_rele)
23716 				ill_refrele(ill);
23717 			freemsg(ipsec_mp);
23718 			return;
23719 		}
23720 
23721 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
23722 		    unspec_src, zoneid);
23723 		ipif_refrele(ipif);
23724 	} else {
23725 		if (attach_if) {
23726 			ipif_t	*ipif;
23727 
23728 			ipif = ipif_get_next_ipif(NULL, ill);
23729 			if (ipif == NULL) {
23730 				if (ill_need_rele)
23731 					ill_refrele(ill);
23732 				freemsg(ipsec_mp);
23733 				return;
23734 			}
23735 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23736 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23737 			ire_need_rele = B_TRUE;
23738 			ipif_refrele(ipif);
23739 		} else {
23740 			if (ire_arg != NULL) {
23741 				ire = ire_arg;
23742 			} else {
23743 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
23744 				ire_need_rele = B_TRUE;
23745 			}
23746 		}
23747 		if (ire != NULL)
23748 			goto send;
23749 		/*
23750 		 * ire disappeared underneath.
23751 		 *
23752 		 * What we need to do here is the ip_newroute
23753 		 * logic to get the ire without doing the IPSEC
23754 		 * processing. Follow the same old path. But this
23755 		 * time, ip_wput or ire_add_then_send will call us
23756 		 * directly as all the IPSEC operations are done.
23757 		 */
23758 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
23759 		mp->b_prev = NULL;
23760 		mp->b_next = NULL;
23761 
23762 		/*
23763 		 * If the IPsec packet was processed asynchronously,
23764 		 * drop it now.
23765 		 */
23766 		if (q == NULL) {
23767 			if (ill_need_rele)
23768 				ill_refrele(ill);
23769 			freemsg(ipsec_mp);
23770 			return;
23771 		}
23772 
23773 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
23774 		    zoneid);
23775 	}
23776 	if (ill != NULL && ill_need_rele)
23777 		ill_refrele(ill);
23778 	return;
23779 send:
23780 	if (ill != NULL && ill_need_rele)
23781 		ill_refrele(ill);
23782 
23783 	/* Local delivery */
23784 	if (ire->ire_stq == NULL) {
23785 		ASSERT(q != NULL);
23786 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
23787 		    ire, 0);
23788 		if (ire_need_rele)
23789 			ire_refrele(ire);
23790 		return;
23791 	}
23792 	/*
23793 	 * Everything is done. Send it out on the wire.
23794 	 * We force the insertion of a fragment header using the
23795 	 * IPH_FRAG_HDR flag in two cases:
23796 	 * - after reception of an ICMPv6 "packet too big" message
23797 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
23798 	 * - for multirouted IPv6 packets, so that the receiver can
23799 	 *   discard duplicates according to their fragment identifier
23800 	 */
23801 	/* XXX fix flow control problems. */
23802 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
23803 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
23804 		if (hwaccel) {
23805 			/*
23806 			 * hardware acceleration does not handle these
23807 			 * "slow path" cases.
23808 			 */
23809 			/* IPsec KSTATS: should bump bean counter here. */
23810 			if (ire_need_rele)
23811 				ire_refrele(ire);
23812 			freemsg(ipsec_mp);
23813 			return;
23814 		}
23815 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
23816 		    (mp->b_cont ? msgdsize(mp) :
23817 		    mp->b_wptr - (uchar_t *)ip6h)) {
23818 			/* IPsec KSTATS: should bump bean counter here. */
23819 			ip0dbg(("Packet length mismatch: %d, %ld\n",
23820 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
23821 			    msgdsize(mp)));
23822 			if (ire_need_rele)
23823 				ire_refrele(ire);
23824 			freemsg(ipsec_mp);
23825 			return;
23826 		}
23827 		ASSERT(mp->b_prev == NULL);
23828 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
23829 		    ntohs(ip6h->ip6_plen) +
23830 		    IPV6_HDR_LEN, ire->ire_max_frag));
23831 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
23832 		    ire->ire_max_frag);
23833 	} else {
23834 		UPDATE_OB_PKT_COUNT(ire);
23835 		ire->ire_last_used_time = lbolt;
23836 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
23837 	}
23838 	if (ire_need_rele)
23839 		ire_refrele(ire);
23840 	freeb(ipsec_mp);
23841 }
23842 
23843 void
23844 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23845 {
23846 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23847 	da_ipsec_t *hada;	/* data attributes */
23848 	ill_t *ill = (ill_t *)q->q_ptr;
23849 
23850 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23851 
23852 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23853 		/* IPsec KSTATS: Bump lose counter here! */
23854 		freemsg(mp);
23855 		return;
23856 	}
23857 
23858 	/*
23859 	 * It's an IPsec packet that must be
23860 	 * accelerated by the Provider, and the
23861 	 * outbound ill is IPsec acceleration capable.
23862 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23863 	 * to the ill.
23864 	 * IPsec KSTATS: should bump packet counter here.
23865 	 */
23866 
23867 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23868 	if (hada_mp == NULL) {
23869 		/* IPsec KSTATS: should bump packet counter here. */
23870 		freemsg(mp);
23871 		return;
23872 	}
23873 
23874 	hada_mp->b_datap->db_type = M_CTL;
23875 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23876 	hada_mp->b_cont = mp;
23877 
23878 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23879 	bzero(hada, sizeof (da_ipsec_t));
23880 	hada->da_type = IPHADA_M_CTL;
23881 
23882 	putnext(q, hada_mp);
23883 }
23884 
23885 /*
23886  * Finish the outbound IPsec processing. This function is called from
23887  * ipsec_out_process() if the IPsec packet was processed
23888  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23889  * asynchronously.
23890  */
23891 void
23892 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23893     ire_t *ire_arg)
23894 {
23895 	uint32_t v_hlen_tos_len;
23896 	ipaddr_t	dst;
23897 	ipif_t	*ipif = NULL;
23898 	ire_t *ire;
23899 	ire_t *ire1 = NULL;
23900 	mblk_t *next_mp = NULL;
23901 	uint32_t max_frag;
23902 	boolean_t multirt_send = B_FALSE;
23903 	mblk_t *mp;
23904 	mblk_t *mp1;
23905 	uint_t	ill_index;
23906 	ipsec_out_t *io;
23907 	boolean_t attach_if;
23908 	int match_flags, offset;
23909 	irb_t *irb = NULL;
23910 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23911 	zoneid_t zoneid;
23912 	uint32_t cksum;
23913 	uint16_t *up;
23914 #ifdef	_BIG_ENDIAN
23915 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23916 #else
23917 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23918 #endif
23919 
23920 	mp = ipsec_mp->b_cont;
23921 	ASSERT(mp != NULL);
23922 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23923 	dst = ipha->ipha_dst;
23924 
23925 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23926 	ill_index = io->ipsec_out_ill_index;
23927 	attach_if = io->ipsec_out_attach_if;
23928 	zoneid = io->ipsec_out_zoneid;
23929 	ASSERT(zoneid != ALL_ZONES);
23930 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23931 	if (ill_index != 0) {
23932 		if (ill == NULL) {
23933 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23934 			    ill_index, B_FALSE);
23935 
23936 			/* Failure case frees things for us. */
23937 			if (ill == NULL)
23938 				return;
23939 
23940 			ill_need_rele = B_TRUE;
23941 		}
23942 		/*
23943 		 * If this packet needs to go out on a particular interface
23944 		 * honor it.
23945 		 */
23946 		if (attach_if) {
23947 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
23948 
23949 			/*
23950 			 * Check if we need an ire that will not be
23951 			 * looked up by anybody else i.e. HIDDEN.
23952 			 */
23953 			if (ill_is_probeonly(ill)) {
23954 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23955 			}
23956 		}
23957 	}
23958 
23959 	if (CLASSD(dst)) {
23960 		boolean_t conn_dontroute;
23961 		/*
23962 		 * Use the ill_index to get the right ipif.
23963 		 */
23964 		conn_dontroute = io->ipsec_out_dontroute;
23965 		if (ill_index == 0)
23966 			ipif = ipif_lookup_group(dst, zoneid);
23967 		else
23968 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23969 		if (ipif == NULL) {
23970 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23971 			    " multicast\n"));
23972 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23973 			freemsg(ipsec_mp);
23974 			goto done;
23975 		}
23976 		/*
23977 		 * ipha_src has already been intialized with the
23978 		 * value of the ipif in ip_wput. All we need now is
23979 		 * an ire to send this downstream.
23980 		 */
23981 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
23982 		    MBLK_GETLABEL(mp), match_flags);
23983 		if (ire != NULL) {
23984 			ill_t *ill1;
23985 			/*
23986 			 * Do the multicast forwarding now, as the IPSEC
23987 			 * processing has been done.
23988 			 */
23989 			if (ip_g_mrouter && !conn_dontroute &&
23990 			    (ill1 = ire_to_ill(ire))) {
23991 				if (ip_mforward(ill1, ipha, mp)) {
23992 					freemsg(ipsec_mp);
23993 					ip1dbg(("ip_wput_ipsec_out: mforward "
23994 					    "failed\n"));
23995 					ire_refrele(ire);
23996 					goto done;
23997 				}
23998 			}
23999 			goto send;
24000 		}
24001 
24002 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24003 		mp->b_prev = NULL;
24004 		mp->b_next = NULL;
24005 
24006 		/*
24007 		 * If the IPsec packet was processed asynchronously,
24008 		 * drop it now.
24009 		 */
24010 		if (q == NULL) {
24011 			freemsg(ipsec_mp);
24012 			goto done;
24013 		}
24014 
24015 		/*
24016 		 * We may be using a wrong ipif to create the ire.
24017 		 * But it is okay as the source address is assigned
24018 		 * for the packet already. Next outbound packet would
24019 		 * create the IRE with the right IPIF in ip_wput.
24020 		 *
24021 		 * Also handle RTF_MULTIRT routes.
24022 		 */
24023 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24024 	} else {
24025 		if (attach_if) {
24026 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24027 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24028 		} else {
24029 			if (ire_arg != NULL) {
24030 				ire = ire_arg;
24031 				ire_need_rele = B_FALSE;
24032 			} else {
24033 				ire = ire_cache_lookup(dst, zoneid,
24034 				    MBLK_GETLABEL(mp));
24035 			}
24036 		}
24037 		if (ire != NULL) {
24038 			goto send;
24039 		}
24040 
24041 		/*
24042 		 * ire disappeared underneath.
24043 		 *
24044 		 * What we need to do here is the ip_newroute
24045 		 * logic to get the ire without doing the IPSEC
24046 		 * processing. Follow the same old path. But this
24047 		 * time, ip_wput or ire_add_then_put will call us
24048 		 * directly as all the IPSEC operations are done.
24049 		 */
24050 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24051 		mp->b_prev = NULL;
24052 		mp->b_next = NULL;
24053 
24054 		/*
24055 		 * If the IPsec packet was processed asynchronously,
24056 		 * drop it now.
24057 		 */
24058 		if (q == NULL) {
24059 			freemsg(ipsec_mp);
24060 			goto done;
24061 		}
24062 
24063 		/*
24064 		 * Since we're going through ip_newroute() again, we
24065 		 * need to make sure we don't:
24066 		 *
24067 		 *	1.) Trigger the ASSERT() with the ipha_ident
24068 		 *	    overloading.
24069 		 *	2.) Redo transport-layer checksumming, since we've
24070 		 *	    already done all that to get this far.
24071 		 *
24072 		 * The easiest way not do either of the above is to set
24073 		 * the ipha_ident field to IP_HDR_INCLUDED.
24074 		 */
24075 		ipha->ipha_ident = IP_HDR_INCLUDED;
24076 		ip_newroute(q, ipsec_mp, dst, NULL,
24077 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24078 	}
24079 	goto done;
24080 send:
24081 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24082 		/*
24083 		 * ESP NAT-Traversal packet.
24084 		 *
24085 		 * Just do software checksum for now.
24086 		 */
24087 
24088 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24089 		IP_STAT(ip_out_sw_cksum);
24090 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24091 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24092 #define	iphs	((uint16_t *)ipha)
24093 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24094 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24095 		    IP_SIMPLE_HDR_LENGTH);
24096 #undef iphs
24097 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24098 			cksum = 0xFFFF;
24099 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24100 			if (mp1->b_wptr - mp1->b_rptr >=
24101 			    offset + sizeof (uint16_t)) {
24102 				up = (uint16_t *)(mp1->b_rptr + offset);
24103 				*up = cksum;
24104 				break;	/* out of for loop */
24105 			} else {
24106 				offset -= (mp->b_wptr - mp->b_rptr);
24107 			}
24108 	} /* Otherwise, just keep the all-zero checksum. */
24109 
24110 	if (ire->ire_stq == NULL) {
24111 		/*
24112 		 * Loopbacks go through ip_wput_local except for one case.
24113 		 * We come here if we generate a icmp_frag_needed message
24114 		 * after IPSEC processing is over. When this function calls
24115 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24116 		 * icmp_frag_needed. The message generated comes back here
24117 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24118 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24119 		 * source address as it is usually set in ip_wput_ire. As
24120 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24121 		 * and we end up here. We can't enter ip_wput_ire once the
24122 		 * IPSEC processing is over and hence we need to do it here.
24123 		 */
24124 		ASSERT(q != NULL);
24125 		UPDATE_OB_PKT_COUNT(ire);
24126 		ire->ire_last_used_time = lbolt;
24127 		if (ipha->ipha_src == 0)
24128 			ipha->ipha_src = ire->ire_src_addr;
24129 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24130 		    ire, 0, zoneid);
24131 		if (ire_need_rele)
24132 			ire_refrele(ire);
24133 		goto done;
24134 	}
24135 
24136 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24137 		/*
24138 		 * We are through with IPSEC processing.
24139 		 * Fragment this and send it on the wire.
24140 		 */
24141 		if (io->ipsec_out_accelerated) {
24142 			/*
24143 			 * The packet has been accelerated but must
24144 			 * be fragmented. This should not happen
24145 			 * since AH and ESP must not accelerate
24146 			 * packets that need fragmentation, however
24147 			 * the configuration could have changed
24148 			 * since the AH or ESP processing.
24149 			 * Drop packet.
24150 			 * IPsec KSTATS: bump bean counter here.
24151 			 */
24152 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24153 			    "fragmented accelerated packet!\n"));
24154 			freemsg(ipsec_mp);
24155 		} else {
24156 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24157 		}
24158 		if (ire_need_rele)
24159 			ire_refrele(ire);
24160 		goto done;
24161 	}
24162 
24163 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24164 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24165 	    (void *)ire->ire_ipif, (void *)ipif));
24166 
24167 	/*
24168 	 * Multiroute the secured packet, unless IPsec really
24169 	 * requires the packet to go out only through a particular
24170 	 * interface.
24171 	 */
24172 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24173 		ire_t *first_ire;
24174 		irb = ire->ire_bucket;
24175 		ASSERT(irb != NULL);
24176 		/*
24177 		 * This ire has been looked up as the one that
24178 		 * goes through the given ipif;
24179 		 * make sure we do not omit any other multiroute ire
24180 		 * that may be present in the bucket before this one.
24181 		 */
24182 		IRB_REFHOLD(irb);
24183 		for (first_ire = irb->irb_ire;
24184 		    first_ire != NULL;
24185 		    first_ire = first_ire->ire_next) {
24186 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24187 			    (first_ire->ire_addr == ire->ire_addr) &&
24188 			    !(first_ire->ire_marks &
24189 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24190 				break;
24191 		}
24192 
24193 		if ((first_ire != NULL) && (first_ire != ire)) {
24194 			/*
24195 			 * Don't change the ire if the packet must
24196 			 * be fragmented if sent via this new one.
24197 			 */
24198 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24199 				IRE_REFHOLD(first_ire);
24200 				if (ire_need_rele)
24201 					ire_refrele(ire);
24202 				else
24203 					ire_need_rele = B_TRUE;
24204 				ire = first_ire;
24205 			}
24206 		}
24207 		IRB_REFRELE(irb);
24208 
24209 		multirt_send = B_TRUE;
24210 		max_frag = ire->ire_max_frag;
24211 	} else {
24212 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24213 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24214 			    "flag, attach_if %d\n", attach_if));
24215 		}
24216 	}
24217 
24218 	/*
24219 	 * In most cases, the emission loop below is entered only once.
24220 	 * Only in the case where the ire holds the RTF_MULTIRT
24221 	 * flag, we loop to process all RTF_MULTIRT ires in the
24222 	 * bucket, and send the packet through all crossed
24223 	 * RTF_MULTIRT routes.
24224 	 */
24225 	do {
24226 		if (multirt_send) {
24227 			/*
24228 			 * ire1 holds here the next ire to process in the
24229 			 * bucket. If multirouting is expected,
24230 			 * any non-RTF_MULTIRT ire that has the
24231 			 * right destination address is ignored.
24232 			 */
24233 			ASSERT(irb != NULL);
24234 			IRB_REFHOLD(irb);
24235 			for (ire1 = ire->ire_next;
24236 			    ire1 != NULL;
24237 			    ire1 = ire1->ire_next) {
24238 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24239 					continue;
24240 				if (ire1->ire_addr != ire->ire_addr)
24241 					continue;
24242 				if (ire1->ire_marks &
24243 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24244 					continue;
24245 				/* No loopback here */
24246 				if (ire1->ire_stq == NULL)
24247 					continue;
24248 				/*
24249 				 * Ensure we do not exceed the MTU
24250 				 * of the next route.
24251 				 */
24252 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24253 					ip_multirt_bad_mtu(ire1, max_frag);
24254 					continue;
24255 				}
24256 
24257 				IRE_REFHOLD(ire1);
24258 				break;
24259 			}
24260 			IRB_REFRELE(irb);
24261 			if (ire1 != NULL) {
24262 				/*
24263 				 * We are in a multiple send case, need to
24264 				 * make a copy of the packet.
24265 				 */
24266 				next_mp = copymsg(ipsec_mp);
24267 				if (next_mp == NULL) {
24268 					ire_refrele(ire1);
24269 					ire1 = NULL;
24270 				}
24271 			}
24272 		}
24273 
24274 		/* Everything is done. Send it out on the wire */
24275 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
24276 		if (mp1 == NULL) {
24277 			BUMP_MIB(&ip_mib, ipOutDiscards);
24278 			freemsg(ipsec_mp);
24279 			if (ire_need_rele)
24280 				ire_refrele(ire);
24281 			if (ire1 != NULL) {
24282 				ire_refrele(ire1);
24283 				freemsg(next_mp);
24284 			}
24285 			goto done;
24286 		}
24287 		UPDATE_OB_PKT_COUNT(ire);
24288 		ire->ire_last_used_time = lbolt;
24289 		if (!io->ipsec_out_accelerated) {
24290 			putnext(ire->ire_stq, mp1);
24291 		} else {
24292 			/*
24293 			 * Safety Pup says: make sure this is going to
24294 			 * the right interface!
24295 			 */
24296 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
24297 			int ifindex = ill1->ill_phyint->phyint_ifindex;
24298 
24299 			if (ifindex != io->ipsec_out_capab_ill_index) {
24300 				/* IPsec kstats: bump lose counter */
24301 				freemsg(mp1);
24302 			} else {
24303 				ipsec_hw_putnext(ire->ire_stq, mp1);
24304 			}
24305 		}
24306 
24307 		freeb(ipsec_mp);
24308 		if (ire_need_rele)
24309 			ire_refrele(ire);
24310 
24311 		if (ire1 != NULL) {
24312 			ire = ire1;
24313 			ire_need_rele = B_TRUE;
24314 			ASSERT(next_mp);
24315 			ipsec_mp = next_mp;
24316 			mp = ipsec_mp->b_cont;
24317 			ire1 = NULL;
24318 			next_mp = NULL;
24319 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
24320 		} else {
24321 			multirt_send = B_FALSE;
24322 		}
24323 	} while (multirt_send);
24324 done:
24325 	if (ill != NULL && ill_need_rele)
24326 		ill_refrele(ill);
24327 	if (ipif != NULL)
24328 		ipif_refrele(ipif);
24329 }
24330 
24331 /*
24332  * Get the ill corresponding to the specified ire, and compare its
24333  * capabilities with the protocol and algorithms specified by the
24334  * the SA obtained from ipsec_out. If they match, annotate the
24335  * ipsec_out structure to indicate that the packet needs acceleration.
24336  *
24337  *
24338  * A packet is eligible for outbound hardware acceleration if the
24339  * following conditions are satisfied:
24340  *
24341  * 1. the packet will not be fragmented
24342  * 2. the provider supports the algorithm
24343  * 3. there is no pending control message being exchanged
24344  * 4. snoop is not attached
24345  * 5. the destination address is not a broadcast or multicast address.
24346  *
24347  * Rationale:
24348  *	- Hardware drivers do not support fragmentation with
24349  *	  the current interface.
24350  *	- snoop, multicast, and broadcast may result in exposure of
24351  *	  a cleartext datagram.
24352  * We check all five of these conditions here.
24353  *
24354  * XXX would like to nuke "ire_t *" parameter here; problem is that
24355  * IRE is only way to figure out if a v4 address is a broadcast and
24356  * thus ineligible for acceleration...
24357  */
24358 static void
24359 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
24360 {
24361 	ipsec_out_t *io;
24362 	mblk_t *data_mp;
24363 	uint_t plen, overhead;
24364 
24365 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
24366 		return;
24367 
24368 	if (ill == NULL)
24369 		return;
24370 
24371 	/*
24372 	 * Destination address is a broadcast or multicast.  Punt.
24373 	 */
24374 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
24375 	    IRE_LOCAL)))
24376 		return;
24377 
24378 	data_mp = ipsec_mp->b_cont;
24379 
24380 	if (ill->ill_isv6) {
24381 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
24382 
24383 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
24384 			return;
24385 
24386 		plen = ip6h->ip6_plen;
24387 	} else {
24388 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
24389 
24390 		if (CLASSD(ipha->ipha_dst))
24391 			return;
24392 
24393 		plen = ipha->ipha_length;
24394 	}
24395 	/*
24396 	 * Is there a pending DLPI control message being exchanged
24397 	 * between IP/IPsec and the DLS Provider? If there is, it
24398 	 * could be a SADB update, and the state of the DLS Provider
24399 	 * SADB might not be in sync with the SADB maintained by
24400 	 * IPsec. To avoid dropping packets or using the wrong keying
24401 	 * material, we do not accelerate this packet.
24402 	 */
24403 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
24404 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24405 		    "ill_dlpi_pending! don't accelerate packet\n"));
24406 		return;
24407 	}
24408 
24409 	/*
24410 	 * Is the Provider in promiscous mode? If it does, we don't
24411 	 * accelerate the packet since it will bounce back up to the
24412 	 * listeners in the clear.
24413 	 */
24414 	if (ill->ill_promisc_on_phys) {
24415 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24416 		    "ill in promiscous mode, don't accelerate packet\n"));
24417 		return;
24418 	}
24419 
24420 	/*
24421 	 * Will the packet require fragmentation?
24422 	 */
24423 
24424 	/*
24425 	 * IPsec ESP note: this is a pessimistic estimate, but the same
24426 	 * as is used elsewhere.
24427 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
24428 	 *	+ 2-byte trailer
24429 	 */
24430 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
24431 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
24432 
24433 	if ((plen + overhead) > ill->ill_max_mtu)
24434 		return;
24435 
24436 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24437 
24438 	/*
24439 	 * Can the ill accelerate this IPsec protocol and algorithm
24440 	 * specified by the SA?
24441 	 */
24442 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
24443 	    ill->ill_isv6, sa)) {
24444 		return;
24445 	}
24446 
24447 	/*
24448 	 * Tell AH or ESP that the outbound ill is capable of
24449 	 * accelerating this packet.
24450 	 */
24451 	io->ipsec_out_is_capab_ill = B_TRUE;
24452 }
24453 
24454 /*
24455  * Select which AH & ESP SA's to use (if any) for the outbound packet.
24456  *
24457  * If this function returns B_TRUE, the requested SA's have been filled
24458  * into the ipsec_out_*_sa pointers.
24459  *
24460  * If the function returns B_FALSE, the packet has been "consumed", most
24461  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
24462  *
24463  * The SA references created by the protocol-specific "select"
24464  * function will be released when the ipsec_mp is freed, thanks to the
24465  * ipsec_out_free destructor -- see spd.c.
24466  */
24467 static boolean_t
24468 ipsec_out_select_sa(mblk_t *ipsec_mp)
24469 {
24470 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
24471 	ipsec_out_t *io;
24472 	ipsec_policy_t *pp;
24473 	ipsec_action_t *ap;
24474 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24475 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24476 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24477 
24478 	if (!io->ipsec_out_secure) {
24479 		/*
24480 		 * We came here by mistake.
24481 		 * Don't bother with ipsec processing
24482 		 * We should "discourage" this path in the future.
24483 		 */
24484 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24485 		return (B_FALSE);
24486 	}
24487 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24488 	ASSERT((io->ipsec_out_policy != NULL) ||
24489 	    (io->ipsec_out_act != NULL));
24490 
24491 	ASSERT(io->ipsec_out_failed == B_FALSE);
24492 
24493 	/*
24494 	 * IPSEC processing has started.
24495 	 */
24496 	io->ipsec_out_proc_begin = B_TRUE;
24497 	ap = io->ipsec_out_act;
24498 	if (ap == NULL) {
24499 		pp = io->ipsec_out_policy;
24500 		ASSERT(pp != NULL);
24501 		ap = pp->ipsp_act;
24502 		ASSERT(ap != NULL);
24503 	}
24504 
24505 	/*
24506 	 * We have an action.  now, let's select SA's.
24507 	 * (In the future, we can cache this in the conn_t..)
24508 	 */
24509 	if (ap->ipa_want_esp) {
24510 		if (io->ipsec_out_esp_sa == NULL) {
24511 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
24512 			    IPPROTO_ESP);
24513 		}
24514 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
24515 	}
24516 
24517 	if (ap->ipa_want_ah) {
24518 		if (io->ipsec_out_ah_sa == NULL) {
24519 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
24520 			    IPPROTO_AH);
24521 		}
24522 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
24523 		/*
24524 		 * The ESP and AH processing order needs to be preserved
24525 		 * when both protocols are required (ESP should be applied
24526 		 * before AH for an outbound packet). Force an ESP ACQUIRE
24527 		 * when both ESP and AH are required, and an AH ACQUIRE
24528 		 * is needed.
24529 		 */
24530 		if (ap->ipa_want_esp && need_ah_acquire)
24531 			need_esp_acquire = B_TRUE;
24532 	}
24533 
24534 	/*
24535 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
24536 	 * Release SAs that got referenced, but will not be used until we
24537 	 * acquire _all_ of the SAs we need.
24538 	 */
24539 	if (need_ah_acquire || need_esp_acquire) {
24540 		if (io->ipsec_out_ah_sa != NULL) {
24541 			IPSA_REFRELE(io->ipsec_out_ah_sa);
24542 			io->ipsec_out_ah_sa = NULL;
24543 		}
24544 		if (io->ipsec_out_esp_sa != NULL) {
24545 			IPSA_REFRELE(io->ipsec_out_esp_sa);
24546 			io->ipsec_out_esp_sa = NULL;
24547 		}
24548 
24549 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
24550 		return (B_FALSE);
24551 	}
24552 
24553 	return (B_TRUE);
24554 }
24555 
24556 /*
24557  * Process an IPSEC_OUT message and see what you can
24558  * do with it.
24559  * IPQoS Notes:
24560  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
24561  * IPSec.
24562  * XXX would like to nuke ire_t.
24563  * XXX ill_index better be "real"
24564  */
24565 void
24566 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
24567 {
24568 	ipsec_out_t *io;
24569 	ipsec_policy_t *pp;
24570 	ipsec_action_t *ap;
24571 	ipha_t *ipha;
24572 	ip6_t *ip6h;
24573 	mblk_t *mp;
24574 	ill_t *ill;
24575 	zoneid_t zoneid;
24576 	ipsec_status_t ipsec_rc;
24577 	boolean_t ill_need_rele = B_FALSE;
24578 
24579 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24580 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24581 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24582 	mp = ipsec_mp->b_cont;
24583 
24584 	/*
24585 	 * Initiate IPPF processing. We do it here to account for packets
24586 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
24587 	 * We can check for ipsec_out_proc_begin even for such packets, as
24588 	 * they will always be false (asserted below).
24589 	 */
24590 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
24591 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
24592 		    io->ipsec_out_ill_index : ill_index);
24593 		if (mp == NULL) {
24594 			ip2dbg(("ipsec_out_process: packet dropped "\
24595 			    "during IPPF processing\n"));
24596 			freeb(ipsec_mp);
24597 			BUMP_MIB(&ip_mib, ipOutDiscards);
24598 			return;
24599 		}
24600 	}
24601 
24602 	if (!io->ipsec_out_secure) {
24603 		/*
24604 		 * We came here by mistake.
24605 		 * Don't bother with ipsec processing
24606 		 * Should "discourage" this path in the future.
24607 		 */
24608 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24609 		goto done;
24610 	}
24611 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24612 	ASSERT((io->ipsec_out_policy != NULL) ||
24613 	    (io->ipsec_out_act != NULL));
24614 	ASSERT(io->ipsec_out_failed == B_FALSE);
24615 
24616 	if (!ipsec_loaded()) {
24617 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
24618 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24619 			BUMP_MIB(&ip_mib, ipOutDiscards);
24620 		} else {
24621 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
24622 		}
24623 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
24624 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
24625 		return;
24626 	}
24627 
24628 	/*
24629 	 * IPSEC processing has started.
24630 	 */
24631 	io->ipsec_out_proc_begin = B_TRUE;
24632 	ap = io->ipsec_out_act;
24633 	if (ap == NULL) {
24634 		pp = io->ipsec_out_policy;
24635 		ASSERT(pp != NULL);
24636 		ap = pp->ipsp_act;
24637 		ASSERT(ap != NULL);
24638 	}
24639 
24640 	/*
24641 	 * Save the outbound ill index. When the packet comes back
24642 	 * from IPsec, we make sure the ill hasn't changed or disappeared
24643 	 * before sending it the accelerated packet.
24644 	 */
24645 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
24646 		int ifindex;
24647 		ill = ire_to_ill(ire);
24648 		ifindex = ill->ill_phyint->phyint_ifindex;
24649 		io->ipsec_out_capab_ill_index = ifindex;
24650 	}
24651 
24652 	/*
24653 	 * The order of processing is first insert a IP header if needed.
24654 	 * Then insert the ESP header and then the AH header.
24655 	 */
24656 	if ((io->ipsec_out_se_done == B_FALSE) &&
24657 	    (ap->ipa_want_se)) {
24658 		/*
24659 		 * First get the outer IP header before sending
24660 		 * it to ESP.
24661 		 */
24662 		ipha_t *oipha, *iipha;
24663 		mblk_t *outer_mp, *inner_mp;
24664 
24665 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
24666 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
24667 			    "ipsec_out_process: "
24668 			    "Self-Encapsulation failed: Out of memory\n");
24669 			freemsg(ipsec_mp);
24670 			BUMP_MIB(&ip_mib, ipOutDiscards);
24671 			return;
24672 		}
24673 		inner_mp = ipsec_mp->b_cont;
24674 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
24675 		oipha = (ipha_t *)outer_mp->b_rptr;
24676 		iipha = (ipha_t *)inner_mp->b_rptr;
24677 		*oipha = *iipha;
24678 		outer_mp->b_wptr += sizeof (ipha_t);
24679 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
24680 		    sizeof (ipha_t));
24681 		oipha->ipha_protocol = IPPROTO_ENCAP;
24682 		oipha->ipha_version_and_hdr_length =
24683 		    IP_SIMPLE_HDR_VERSION;
24684 		oipha->ipha_hdr_checksum = 0;
24685 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
24686 		outer_mp->b_cont = inner_mp;
24687 		ipsec_mp->b_cont = outer_mp;
24688 
24689 		io->ipsec_out_se_done = B_TRUE;
24690 		io->ipsec_out_encaps = B_TRUE;
24691 	}
24692 
24693 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
24694 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
24695 	    !ipsec_out_select_sa(ipsec_mp))
24696 		return;
24697 
24698 	/*
24699 	 * By now, we know what SA's to use.  Toss over to ESP & AH
24700 	 * to do the heavy lifting.
24701 	 */
24702 	zoneid = io->ipsec_out_zoneid;
24703 	ASSERT(zoneid != ALL_ZONES);
24704 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
24705 		ASSERT(io->ipsec_out_esp_sa != NULL);
24706 		io->ipsec_out_esp_done = B_TRUE;
24707 		/*
24708 		 * Note that since hw accel can only apply one transform,
24709 		 * not two, we skip hw accel for ESP if we also have AH
24710 		 * This is an design limitation of the interface
24711 		 * which should be revisited.
24712 		 */
24713 		ASSERT(ire != NULL);
24714 		if (io->ipsec_out_ah_sa == NULL) {
24715 			ill = (ill_t *)ire->ire_stq->q_ptr;
24716 			ipsec_out_is_accelerated(ipsec_mp,
24717 			    io->ipsec_out_esp_sa, ill, ire);
24718 		}
24719 
24720 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
24721 		switch (ipsec_rc) {
24722 		case IPSEC_STATUS_SUCCESS:
24723 			break;
24724 		case IPSEC_STATUS_FAILED:
24725 			BUMP_MIB(&ip_mib, ipOutDiscards);
24726 			/* FALLTHRU */
24727 		case IPSEC_STATUS_PENDING:
24728 			return;
24729 		}
24730 	}
24731 
24732 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
24733 		ASSERT(io->ipsec_out_ah_sa != NULL);
24734 		io->ipsec_out_ah_done = B_TRUE;
24735 		if (ire == NULL) {
24736 			int idx = io->ipsec_out_capab_ill_index;
24737 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
24738 			    NULL, NULL, NULL, NULL);
24739 			ill_need_rele = B_TRUE;
24740 		} else {
24741 			ill = (ill_t *)ire->ire_stq->q_ptr;
24742 		}
24743 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
24744 		    ire);
24745 
24746 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
24747 		switch (ipsec_rc) {
24748 		case IPSEC_STATUS_SUCCESS:
24749 			break;
24750 		case IPSEC_STATUS_FAILED:
24751 			BUMP_MIB(&ip_mib, ipOutDiscards);
24752 			/* FALLTHRU */
24753 		case IPSEC_STATUS_PENDING:
24754 			if (ill != NULL && ill_need_rele)
24755 				ill_refrele(ill);
24756 			return;
24757 		}
24758 	}
24759 	/*
24760 	 * We are done with IPSEC processing. Send it over
24761 	 * the wire.
24762 	 */
24763 done:
24764 	mp = ipsec_mp->b_cont;
24765 	ipha = (ipha_t *)mp->b_rptr;
24766 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24767 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
24768 	} else {
24769 		ip6h = (ip6_t *)ipha;
24770 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
24771 	}
24772 	if (ill != NULL && ill_need_rele)
24773 		ill_refrele(ill);
24774 }
24775 
24776 /* ARGSUSED */
24777 void
24778 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
24779 {
24780 	opt_restart_t	*or;
24781 	int	err;
24782 	conn_t	*connp;
24783 
24784 	ASSERT(CONN_Q(q));
24785 	connp = Q_TO_CONN(q);
24786 
24787 	ASSERT(first_mp->b_datap->db_type == M_CTL);
24788 	or = (opt_restart_t *)first_mp->b_rptr;
24789 	/*
24790 	 * We don't need to pass any credentials here since this is just
24791 	 * a restart. The credentials are passed in when svr4_optcom_req
24792 	 * is called the first time (from ip_wput_nondata).
24793 	 */
24794 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
24795 		err = svr4_optcom_req(q, first_mp, NULL,
24796 		    &ip_opt_obj);
24797 	} else {
24798 		ASSERT(or->or_type == T_OPTMGMT_REQ);
24799 		err = tpi_optcom_req(q, first_mp, NULL,
24800 		    &ip_opt_obj);
24801 	}
24802 	if (err != EINPROGRESS) {
24803 		/* operation is done */
24804 		CONN_OPER_PENDING_DONE(connp);
24805 	}
24806 }
24807 
24808 /*
24809  * ioctls that go through a down/up sequence may need to wait for the down
24810  * to complete. This involves waiting for the ire and ipif refcnts to go down
24811  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
24812  */
24813 /* ARGSUSED */
24814 void
24815 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24816 {
24817 	struct iocblk *iocp;
24818 	mblk_t *mp1;
24819 	ipif_t	*ipif;
24820 	ip_ioctl_cmd_t *ipip;
24821 	int err;
24822 	sin_t	*sin;
24823 	struct lifreq *lifr;
24824 	struct ifreq *ifr;
24825 
24826 	iocp = (struct iocblk *)mp->b_rptr;
24827 	ASSERT(ipsq != NULL);
24828 	/* Existence of mp1 verified in ip_wput_nondata */
24829 	mp1 = mp->b_cont->b_cont;
24830 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24831 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
24832 		ill_t *ill;
24833 		/*
24834 		 * Special case where ipsq_current_ipif may not be set.
24835 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
24836 		 * ill could also have become part of a ipmp group in the
24837 		 * process, we are here as were not able to complete the
24838 		 * operation in ipif_set_values because we could not become
24839 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
24840 		 * will not be set so we need to set it.
24841 		 */
24842 		ill = (ill_t *)q->q_ptr;
24843 		ipsq->ipsq_current_ipif = ill->ill_ipif;
24844 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24845 	}
24846 
24847 	ipif = ipsq->ipsq_current_ipif;
24848 	ASSERT(ipif != NULL);
24849 	if (ipip->ipi_cmd_type == IF_CMD) {
24850 		/* This a old style SIOC[GS]IF* command */
24851 		ifr = (struct ifreq *)mp1->b_rptr;
24852 		sin = (sin_t *)&ifr->ifr_addr;
24853 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24854 		/* This a new style SIOC[GS]LIF* command */
24855 		lifr = (struct lifreq *)mp1->b_rptr;
24856 		sin = (sin_t *)&lifr->lifr_addr;
24857 	} else {
24858 		sin = NULL;
24859 	}
24860 
24861 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24862 	    (void *)mp1->b_rptr);
24863 
24864 	/* SIOCLIFREMOVEIF could have removed the ipif */
24865 	ip_ioctl_finish(q, mp, err,
24866 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24867 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24868 }
24869 
24870 /*
24871  * ioctl processing
24872  *
24873  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24874  * the ioctl command in the ioctl tables and determines the copyin data size
24875  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24876  * size.
24877  *
24878  * ioctl processing then continues when the M_IOCDATA makes its way down.
24879  * Now the ioctl is looked up again in the ioctl table, and its properties are
24880  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24881  * and the general ioctl processing function ip_process_ioctl is called.
24882  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24883  * so goes thru the serialization primitive ipsq_try_enter. Then the
24884  * appropriate function to handle the ioctl is called based on the entry in
24885  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24886  * which also refreleases the 'conn' that was refheld at the start of the
24887  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24888  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24889  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24890  *
24891  * Many exclusive ioctls go thru an internal down up sequence as part of
24892  * the operation. For example an attempt to change the IP address of an
24893  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24894  * does all the cleanup such as deleting all ires that use this address.
24895  * Then we need to wait till all references to the interface go away.
24896  */
24897 void
24898 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24899 {
24900 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24901 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24902 	cmd_info_t ci;
24903 	int err;
24904 	boolean_t entered_ipsq = B_FALSE;
24905 
24906 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24907 
24908 	if (ipip == NULL)
24909 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24910 
24911 	/*
24912 	 * SIOCLIFADDIF needs to go thru a special path since the
24913 	 * ill may not exist yet. This happens in the case of lo0
24914 	 * which is created using this ioctl.
24915 	 */
24916 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24917 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24918 		ip_ioctl_finish(q, mp, err,
24919 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24920 		    NULL, NULL);
24921 		return;
24922 	}
24923 
24924 	ci.ci_ipif = NULL;
24925 	switch (ipip->ipi_cmd_type) {
24926 	case IF_CMD:
24927 	case LIF_CMD:
24928 		/*
24929 		 * ioctls that pass in a [l]ifreq appear here.
24930 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24931 		 * ci.ci_ipif
24932 		 */
24933 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24934 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24935 		if (err != 0) {
24936 			ip_ioctl_finish(q, mp, err,
24937 			    ipip->ipi_flags & IPI_GET_CMD ?
24938 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24939 			return;
24940 		}
24941 		ASSERT(ci.ci_ipif != NULL);
24942 		break;
24943 
24944 	case TUN_CMD:
24945 		/*
24946 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24947 		 * a refheld ipif in ci.ci_ipif
24948 		 */
24949 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24950 		if (err != 0) {
24951 			ip_ioctl_finish(q, mp, err,
24952 			    ipip->ipi_flags & IPI_GET_CMD ?
24953 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24954 			return;
24955 		}
24956 		ASSERT(ci.ci_ipif != NULL);
24957 		break;
24958 
24959 	case MISC_CMD:
24960 		/*
24961 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24962 		 * For eg. SIOCGLIFCONF will appear here.
24963 		 */
24964 		switch (ipip->ipi_cmd) {
24965 		case IF_UNITSEL:
24966 			/* ioctl comes down the ill */
24967 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24968 			ipif_refhold(ci.ci_ipif);
24969 			break;
24970 		case SIOCGMSFILTER:
24971 		case SIOCSMSFILTER:
24972 		case SIOCGIPMSFILTER:
24973 		case SIOCSIPMSFILTER:
24974 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24975 			    ip_process_ioctl);
24976 			if (err != 0) {
24977 				ip_ioctl_finish(q, mp, err,
24978 				    ipip->ipi_flags & IPI_GET_CMD ?
24979 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24980 				return;
24981 			}
24982 			break;
24983 		}
24984 		err = 0;
24985 		ci.ci_sin = NULL;
24986 		ci.ci_sin6 = NULL;
24987 		ci.ci_lifr = NULL;
24988 		break;
24989 	}
24990 
24991 	/*
24992 	 * If ipsq is non-null, we are already being called exclusively
24993 	 */
24994 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
24995 	if (!(ipip->ipi_flags & IPI_WR)) {
24996 		/*
24997 		 * A return value of EINPROGRESS means the ioctl is
24998 		 * either queued and waiting for some reason or has
24999 		 * already completed.
25000 		 */
25001 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25002 		    ci.ci_lifr);
25003 		if (ci.ci_ipif != NULL)
25004 			ipif_refrele(ci.ci_ipif);
25005 		ip_ioctl_finish(q, mp, err,
25006 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25007 		    NULL, NULL);
25008 		return;
25009 	}
25010 
25011 	ASSERT(ci.ci_ipif != NULL);
25012 
25013 	if (ipsq == NULL) {
25014 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25015 		    ip_process_ioctl, NEW_OP, B_TRUE);
25016 		entered_ipsq = B_TRUE;
25017 	}
25018 	/*
25019 	 * Release the ipif so that ipif_down and friends that wait for
25020 	 * references to go away are not misled about the current ipif_refcnt
25021 	 * values. We are writer so we can access the ipif even after releasing
25022 	 * the ipif.
25023 	 */
25024 	ipif_refrele(ci.ci_ipif);
25025 	if (ipsq == NULL)
25026 		return;
25027 
25028 	mutex_enter(&ipsq->ipsq_lock);
25029 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25030 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25031 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25032 	mutex_exit(&ipsq->ipsq_lock);
25033 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25034 	/*
25035 	 * For most set ioctls that come here, this serves as a single point
25036 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25037 	 * be any new references to the ipif. This helps functions that go
25038 	 * through this path and end up trying to wait for the refcnts
25039 	 * associated with the ipif to go down to zero. Some exceptions are
25040 	 * Failover, Failback, and Groupname commands that operate on more than
25041 	 * just the ci.ci_ipif. These commands internally determine the
25042 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25043 	 * flags on that set. Another exception is the Removeif command that
25044 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25045 	 * ipif to operate on.
25046 	 */
25047 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25048 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25049 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25050 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25051 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25052 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25053 
25054 	/*
25055 	 * A return value of EINPROGRESS means the ioctl is
25056 	 * either queued and waiting for some reason or has
25057 	 * already completed.
25058 	 */
25059 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25060 	    ci.ci_lifr);
25061 
25062 	/* SIOCLIFREMOVEIF could have removed the ipif */
25063 	ip_ioctl_finish(q, mp, err,
25064 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25065 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25066 
25067 	if (entered_ipsq)
25068 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25069 }
25070 
25071 /*
25072  * Complete the ioctl. Typically ioctls use the mi package and need to
25073  * do mi_copyout/mi_copy_done.
25074  */
25075 void
25076 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25077     ipif_t *ipif, ipsq_t *ipsq)
25078 {
25079 	conn_t	*connp = NULL;
25080 
25081 	if (err == EINPROGRESS)
25082 		return;
25083 
25084 	if (CONN_Q(q)) {
25085 		connp = Q_TO_CONN(q);
25086 		ASSERT(connp->conn_ref >= 2);
25087 	}
25088 
25089 	switch (mode) {
25090 	case COPYOUT:
25091 		if (err == 0)
25092 			mi_copyout(q, mp);
25093 		else
25094 			mi_copy_done(q, mp, err);
25095 		break;
25096 
25097 	case NO_COPYOUT:
25098 		mi_copy_done(q, mp, err);
25099 		break;
25100 
25101 	default:
25102 		/* An ioctl aborted through a conn close would take this path */
25103 		break;
25104 	}
25105 
25106 	/*
25107 	 * The refhold placed at the start of the ioctl is released here.
25108 	 */
25109 	if (connp != NULL)
25110 		CONN_OPER_PENDING_DONE(connp);
25111 
25112 	/*
25113 	 * If the ioctl were an exclusive ioctl it would have set
25114 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25115 	 */
25116 	if (ipif != NULL) {
25117 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25118 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25119 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25120 	}
25121 
25122 	/*
25123 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25124 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25125 	 * entering the ipsq
25126 	 */
25127 	if (ipsq != NULL) {
25128 		mutex_enter(&ipsq->ipsq_lock);
25129 		ipsq->ipsq_current_ipif = NULL;
25130 		mutex_exit(&ipsq->ipsq_lock);
25131 	}
25132 }
25133 
25134 /*
25135  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25136  */
25137 /* ARGSUSED */
25138 void
25139 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25140 {
25141 	conn_t *connp = arg;
25142 	tcp_t	*tcp;
25143 
25144 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25145 	tcp = connp->conn_tcp;
25146 
25147 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25148 		freemsg(mp);
25149 	else
25150 		tcp_rput_other(tcp, mp);
25151 	CONN_OPER_PENDING_DONE(connp);
25152 }
25153 
25154 /* Called from ip_wput for all non data messages */
25155 /* ARGSUSED */
25156 void
25157 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25158 {
25159 	mblk_t		*mp1;
25160 	ire_t		*ire;
25161 	ill_t		*ill;
25162 	struct iocblk	*iocp;
25163 	ip_ioctl_cmd_t	*ipip;
25164 	cred_t		*cr;
25165 	conn_t		*connp = NULL;
25166 	int		cmd, err;
25167 
25168 	if (CONN_Q(q))
25169 		connp = Q_TO_CONN(q);
25170 
25171 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25172 
25173 	/* Check if it is a queue to /dev/sctp. */
25174 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25175 	    connp->conn_rq == NULL) {
25176 		sctp_wput(q, mp);
25177 		return;
25178 	}
25179 
25180 	switch (DB_TYPE(mp)) {
25181 	case M_IOCTL:
25182 		/*
25183 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25184 		 * will arrange to copy in associated control structures.
25185 		 */
25186 		ip_sioctl_copyin_setup(q, mp);
25187 		return;
25188 	case M_IOCDATA:
25189 		/*
25190 		 * Ensure that this is associated with one of our trans-
25191 		 * parent ioctls.  If it's not ours, discard it if we're
25192 		 * running as a driver, or pass it on if we're a module.
25193 		 */
25194 		iocp = (struct iocblk *)mp->b_rptr;
25195 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25196 		if (ipip == NULL) {
25197 			if (q->q_next == NULL) {
25198 				goto nak;
25199 			} else {
25200 				putnext(q, mp);
25201 			}
25202 			return;
25203 		} else if ((q->q_next != NULL) &&
25204 		    !(ipip->ipi_flags & IPI_MODOK)) {
25205 			/*
25206 			 * the ioctl is one we recognise, but is not
25207 			 * consumed by IP as a module, pass M_IOCDATA
25208 			 * for processing downstream, but only for
25209 			 * common Streams ioctls.
25210 			 */
25211 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25212 				putnext(q, mp);
25213 				return;
25214 			} else {
25215 				goto nak;
25216 			}
25217 		}
25218 
25219 		/* IOCTL continuation following copyin or copyout. */
25220 		if (mi_copy_state(q, mp, NULL) == -1) {
25221 			/*
25222 			 * The copy operation failed.  mi_copy_state already
25223 			 * cleaned up, so we're out of here.
25224 			 */
25225 			return;
25226 		}
25227 		/*
25228 		 * If we just completed a copy in, we become writer and
25229 		 * continue processing in ip_sioctl_copyin_done.  If it
25230 		 * was a copy out, we call mi_copyout again.  If there is
25231 		 * nothing more to copy out, it will complete the IOCTL.
25232 		 */
25233 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25234 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25235 				mi_copy_done(q, mp, EPROTO);
25236 				return;
25237 			}
25238 			/*
25239 			 * Check for cases that need more copying.  A return
25240 			 * value of 0 means a second copyin has been started,
25241 			 * so we return; a return value of 1 means no more
25242 			 * copying is needed, so we continue.
25243 			 */
25244 			cmd = iocp->ioc_cmd;
25245 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25246 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25247 			    MI_COPY_COUNT(mp) == 1) {
25248 				if (ip_copyin_msfilter(q, mp) == 0)
25249 					return;
25250 			}
25251 			/*
25252 			 * Refhold the conn, till the ioctl completes. This is
25253 			 * needed in case the ioctl ends up in the pending mp
25254 			 * list. Every mp in the ill_pending_mp list and
25255 			 * the ipsq_pending_mp must have a refhold on the conn
25256 			 * to resume processing. The refhold is released when
25257 			 * the ioctl completes. (normally or abnormally)
25258 			 * In all cases ip_ioctl_finish is called to finish
25259 			 * the ioctl.
25260 			 */
25261 			if (connp != NULL) {
25262 				/* This is not a reentry */
25263 				ASSERT(ipsq == NULL);
25264 				CONN_INC_REF(connp);
25265 			} else {
25266 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25267 					mi_copy_done(q, mp, EINVAL);
25268 					return;
25269 				}
25270 			}
25271 
25272 			ip_process_ioctl(ipsq, q, mp, ipip);
25273 
25274 		} else {
25275 			mi_copyout(q, mp);
25276 		}
25277 		return;
25278 nak:
25279 		iocp->ioc_error = EINVAL;
25280 		mp->b_datap->db_type = M_IOCNAK;
25281 		iocp->ioc_count = 0;
25282 		qreply(q, mp);
25283 		return;
25284 
25285 	case M_IOCNAK:
25286 		/*
25287 		 * The only way we could get here is if a resolver didn't like
25288 		 * an IOCTL we sent it.	 This shouldn't happen.
25289 		 */
25290 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25291 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25292 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25293 		freemsg(mp);
25294 		return;
25295 	case M_IOCACK:
25296 		/* Finish socket ioctls passed through to ARP. */
25297 		ip_sioctl_iocack(q, mp);
25298 		return;
25299 	case M_FLUSH:
25300 		if (*mp->b_rptr & FLUSHW)
25301 			flushq(q, FLUSHALL);
25302 		if (q->q_next) {
25303 			/*
25304 			 * M_FLUSH is sent up to IP by some drivers during
25305 			 * unbind. ip_rput has already replied to it. We are
25306 			 * here for the M_FLUSH that we originated in IP
25307 			 * before sending the unbind request to the driver.
25308 			 * Just free it as we don't queue packets in IP
25309 			 * on the write side of the device instance.
25310 			 */
25311 			freemsg(mp);
25312 			return;
25313 		}
25314 		if (*mp->b_rptr & FLUSHR) {
25315 			*mp->b_rptr &= ~FLUSHW;
25316 			qreply(q, mp);
25317 			return;
25318 		}
25319 		freemsg(mp);
25320 		return;
25321 	case IRE_DB_REQ_TYPE:
25322 		/* An Upper Level Protocol wants a copy of an IRE. */
25323 		ip_ire_req(q, mp);
25324 		return;
25325 	case M_CTL:
25326 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
25327 			break;
25328 
25329 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
25330 		    IP_ULP_OUT_LABELED) {
25331 			out_labeled_t *olp;
25332 
25333 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
25334 				break;
25335 			olp = (out_labeled_t *)mp->b_rptr;
25336 			connp->conn_ulp_labeled = olp->out_qnext == q;
25337 			freemsg(mp);
25338 			return;
25339 		}
25340 
25341 		/* M_CTL messages are used by ARP to tell us things. */
25342 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
25343 			break;
25344 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
25345 		case AR_ENTRY_SQUERY:
25346 			ip_wput_ctl(q, mp);
25347 			return;
25348 		case AR_CLIENT_NOTIFY:
25349 			ip_arp_news(q, mp);
25350 			return;
25351 		case AR_DLPIOP_DONE:
25352 			ASSERT(q->q_next != NULL);
25353 			ill = (ill_t *)q->q_ptr;
25354 			/* qwriter_ip releases the refhold */
25355 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
25356 			ill_refhold(ill);
25357 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
25358 			    CUR_OP, B_FALSE);
25359 			return;
25360 		case AR_ARP_CLOSING:
25361 			/*
25362 			 * ARP (above us) is closing. If no ARP bringup is
25363 			 * currently pending, ack the message so that ARP
25364 			 * can complete its close. Also mark ill_arp_closing
25365 			 * so that new ARP bringups will fail. If any
25366 			 * ARP bringup is currently in progress, we will
25367 			 * ack this when the current ARP bringup completes.
25368 			 */
25369 			ASSERT(q->q_next != NULL);
25370 			ill = (ill_t *)q->q_ptr;
25371 			mutex_enter(&ill->ill_lock);
25372 			ill->ill_arp_closing = 1;
25373 			if (!ill->ill_arp_bringup_pending) {
25374 				mutex_exit(&ill->ill_lock);
25375 				qreply(q, mp);
25376 			} else {
25377 				mutex_exit(&ill->ill_lock);
25378 				freemsg(mp);
25379 			}
25380 			return;
25381 		default:
25382 			break;
25383 		}
25384 		break;
25385 	case M_PROTO:
25386 	case M_PCPROTO:
25387 		/*
25388 		 * The only PROTO messages we expect are ULP binds and
25389 		 * copies of option negotiation acknowledgements.
25390 		 */
25391 		switch (((union T_primitives *)mp->b_rptr)->type) {
25392 		case O_T_BIND_REQ:
25393 		case T_BIND_REQ: {
25394 			/* Request can get queued in bind */
25395 			ASSERT(connp != NULL);
25396 			/*
25397 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
25398 			 * instead of going through this path.  We only get
25399 			 * here in the following cases:
25400 			 *
25401 			 * a. Bind retries, where ipsq is non-NULL.
25402 			 * b. T_BIND_REQ is issued from non TCP/UDP
25403 			 *    transport, e.g. icmp for raw socket,
25404 			 *    in which case ipsq will be NULL.
25405 			 */
25406 			ASSERT(ipsq != NULL ||
25407 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
25408 
25409 			/* Don't increment refcnt if this is a re-entry */
25410 			if (ipsq == NULL)
25411 				CONN_INC_REF(connp);
25412 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
25413 			    connp, NULL) : ip_bind_v4(q, mp, connp);
25414 			if (mp == NULL)
25415 				return;
25416 			if (IPCL_IS_TCP(connp)) {
25417 				/*
25418 				 * In the case of TCP endpoint we
25419 				 * come here only for bind retries
25420 				 */
25421 				ASSERT(ipsq != NULL);
25422 				CONN_INC_REF(connp);
25423 				squeue_fill(connp->conn_sqp, mp,
25424 				    ip_resume_tcp_bind, connp,
25425 				    SQTAG_BIND_RETRY);
25426 				return;
25427 			} else if (IPCL_IS_UDP(connp)) {
25428 				/*
25429 				 * In the case of UDP endpoint we
25430 				 * come here only for bind retries
25431 				 */
25432 				ASSERT(ipsq != NULL);
25433 				udp_resume_bind(connp, mp);
25434 				return;
25435 			}
25436 			qreply(q, mp);
25437 			CONN_OPER_PENDING_DONE(connp);
25438 			return;
25439 		}
25440 		case T_SVR4_OPTMGMT_REQ:
25441 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
25442 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
25443 
25444 			ASSERT(connp != NULL);
25445 			if (!snmpcom_req(q, mp, ip_snmp_set,
25446 			    ip_snmp_get, cr)) {
25447 				/*
25448 				 * Call svr4_optcom_req so that it can
25449 				 * generate the ack. We don't come here
25450 				 * if this operation is being restarted.
25451 				 * ip_restart_optmgmt will drop the conn ref.
25452 				 * In the case of ipsec option after the ipsec
25453 				 * load is complete conn_restart_ipsec_waiter
25454 				 * drops the conn ref.
25455 				 */
25456 				ASSERT(ipsq == NULL);
25457 				CONN_INC_REF(connp);
25458 				if (ip_check_for_ipsec_opt(q, mp))
25459 					return;
25460 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
25461 				if (err != EINPROGRESS) {
25462 					/* Operation is done */
25463 					CONN_OPER_PENDING_DONE(connp);
25464 				}
25465 			}
25466 			return;
25467 		case T_OPTMGMT_REQ:
25468 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
25469 			/*
25470 			 * Note: No snmpcom_req support through new
25471 			 * T_OPTMGMT_REQ.
25472 			 * Call tpi_optcom_req so that it can
25473 			 * generate the ack.
25474 			 */
25475 			ASSERT(connp != NULL);
25476 			ASSERT(ipsq == NULL);
25477 			/*
25478 			 * We don't come here for restart. ip_restart_optmgmt
25479 			 * will drop the conn ref. In the case of ipsec option
25480 			 * after the ipsec load is complete
25481 			 * conn_restart_ipsec_waiter drops the conn ref.
25482 			 */
25483 			CONN_INC_REF(connp);
25484 			if (ip_check_for_ipsec_opt(q, mp))
25485 				return;
25486 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
25487 			if (err != EINPROGRESS) {
25488 				/* Operation is done */
25489 				CONN_OPER_PENDING_DONE(connp);
25490 			}
25491 			return;
25492 		case T_UNBIND_REQ:
25493 			mp = ip_unbind(q, mp);
25494 			qreply(q, mp);
25495 			return;
25496 		default:
25497 			/*
25498 			 * Have to drop any DLPI messages coming down from
25499 			 * arp (such as an info_req which would cause ip
25500 			 * to receive an extra info_ack if it was passed
25501 			 * through.
25502 			 */
25503 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
25504 			    (int)*(uint_t *)mp->b_rptr));
25505 			freemsg(mp);
25506 			return;
25507 		}
25508 		/* NOTREACHED */
25509 	case IRE_DB_TYPE: {
25510 		nce_t		*nce;
25511 		ill_t		*ill;
25512 		in6_addr_t	gw_addr_v6;
25513 
25514 
25515 		/*
25516 		 * This is a response back from a resolver.  It
25517 		 * consists of a message chain containing:
25518 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
25519 		 * The IRE_MBLK is the one we allocated in ip_newroute.
25520 		 * The LL_HDR_MBLK is the DLPI header to use to get
25521 		 * the attached packet, and subsequent ones for the
25522 		 * same destination, transmitted.
25523 		 */
25524 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
25525 			break;
25526 		/*
25527 		 * First, check to make sure the resolution succeeded.
25528 		 * If it failed, the second mblk will be empty.
25529 		 * If it is, free the chain, dropping the packet.
25530 		 * (We must ire_delete the ire; that frees the ire mblk)
25531 		 * We're doing this now to support PVCs for ATM; it's
25532 		 * a partial xresolv implementation. When we fully implement
25533 		 * xresolv interfaces, instead of freeing everything here
25534 		 * we'll initiate neighbor discovery.
25535 		 *
25536 		 * For v4 (ARP and other external resolvers) the resolver
25537 		 * frees the message, so no check is needed. This check
25538 		 * is required, though, for a full xresolve implementation.
25539 		 * Including this code here now both shows how external
25540 		 * resolvers can NACK a resolution request using an
25541 		 * existing design that has no specific provisions for NACKs,
25542 		 * and also takes into account that the current non-ARP
25543 		 * external resolver has been coded to use this method of
25544 		 * NACKing for all IPv6 (xresolv) cases,
25545 		 * whether our xresolv implementation is complete or not.
25546 		 *
25547 		 */
25548 		ire = (ire_t *)mp->b_rptr;
25549 		ill = ire_to_ill(ire);
25550 		mp1 = mp->b_cont;		/* dl_unitdata_req */
25551 		if (mp1->b_rptr == mp1->b_wptr) {
25552 			if (ire->ire_ipversion == IPV6_VERSION) {
25553 				/*
25554 				 * XRESOLV interface.
25555 				 */
25556 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
25557 				mutex_enter(&ire->ire_lock);
25558 				gw_addr_v6 = ire->ire_gateway_addr_v6;
25559 				mutex_exit(&ire->ire_lock);
25560 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25561 					nce = ndp_lookup(ill,
25562 					    &ire->ire_addr_v6, B_FALSE);
25563 				} else {
25564 					nce = ndp_lookup(ill, &gw_addr_v6,
25565 					    B_FALSE);
25566 				}
25567 				if (nce != NULL) {
25568 					nce_resolv_failed(nce);
25569 					ndp_delete(nce);
25570 					NCE_REFRELE(nce);
25571 				}
25572 			}
25573 			mp->b_cont = NULL;
25574 			freemsg(mp1);		/* frees the pkt as well */
25575 			ire_delete((ire_t *)mp->b_rptr);
25576 			return;
25577 		}
25578 		/*
25579 		 * Split them into IRE_MBLK and pkt and feed it into
25580 		 * ire_add_then_send. Then in ire_add_then_send
25581 		 * the IRE will be added, and then the packet will be
25582 		 * run back through ip_wput. This time it will make
25583 		 * it to the wire.
25584 		 */
25585 		mp->b_cont = NULL;
25586 		mp = mp1->b_cont;		/* now, mp points to pkt */
25587 		mp1->b_cont = NULL;
25588 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
25589 		if (ire->ire_ipversion == IPV6_VERSION) {
25590 			/*
25591 			 * XRESOLV interface. Find the nce and put a copy
25592 			 * of the dl_unitdata_req in nce_res_mp
25593 			 */
25594 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
25595 			mutex_enter(&ire->ire_lock);
25596 			gw_addr_v6 = ire->ire_gateway_addr_v6;
25597 			mutex_exit(&ire->ire_lock);
25598 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25599 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
25600 				    B_FALSE);
25601 			} else {
25602 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
25603 			}
25604 			if (nce != NULL) {
25605 				/*
25606 				 * We have to protect nce_res_mp here
25607 				 * from being accessed by other threads
25608 				 * while we change the mblk pointer.
25609 				 * Other functions will also lock the nce when
25610 				 * accessing nce_res_mp.
25611 				 *
25612 				 * The reason we change the mblk pointer
25613 				 * here rather than copying the resolved address
25614 				 * into the template is that, unlike with
25615 				 * ethernet, we have no guarantee that the
25616 				 * resolved address length will be
25617 				 * smaller than or equal to the lla length
25618 				 * with which the template was allocated,
25619 				 * (for ethernet, they're equal)
25620 				 * so we have to use the actual resolved
25621 				 * address mblk - which holds the real
25622 				 * dl_unitdata_req with the resolved address.
25623 				 *
25624 				 * Doing this is the same behavior as was
25625 				 * previously used in the v4 ARP case.
25626 				 */
25627 				mutex_enter(&nce->nce_lock);
25628 				if (nce->nce_res_mp != NULL)
25629 					freemsg(nce->nce_res_mp);
25630 				nce->nce_res_mp = mp1;
25631 				mutex_exit(&nce->nce_lock);
25632 				/*
25633 				 * We do a fastpath probe here because
25634 				 * we have resolved the address without
25635 				 * using Neighbor Discovery.
25636 				 * In the non-XRESOLV v6 case, the fastpath
25637 				 * probe is done right after neighbor
25638 				 * discovery completes.
25639 				 */
25640 				if (nce->nce_res_mp != NULL) {
25641 					int res;
25642 					nce_fastpath_list_add(nce);
25643 					res = ill_fastpath_probe(ill,
25644 					    nce->nce_res_mp);
25645 					if (res != 0 && res != EAGAIN)
25646 						nce_fastpath_list_delete(nce);
25647 				}
25648 
25649 				ire_add_then_send(q, ire, mp);
25650 				/*
25651 				 * Now we have to clean out any packets
25652 				 * that may have been queued on the nce
25653 				 * while it was waiting for address resolution
25654 				 * to complete.
25655 				 */
25656 				mutex_enter(&nce->nce_lock);
25657 				mp1 = nce->nce_qd_mp;
25658 				nce->nce_qd_mp = NULL;
25659 				mutex_exit(&nce->nce_lock);
25660 				while (mp1 != NULL) {
25661 					mblk_t *nxt_mp;
25662 					queue_t *fwdq = NULL;
25663 					ill_t   *inbound_ill;
25664 					uint_t ifindex;
25665 
25666 					nxt_mp = mp1->b_next;
25667 					mp1->b_next = NULL;
25668 					/*
25669 					 * Retrieve ifindex stored in
25670 					 * ip_rput_data_v6()
25671 					 */
25672 					ifindex =
25673 					    (uint_t)(uintptr_t)mp1->b_prev;
25674 					inbound_ill =
25675 						ill_lookup_on_ifindex(ifindex,
25676 						    B_TRUE, NULL, NULL, NULL,
25677 						    NULL);
25678 					mp1->b_prev = NULL;
25679 					if (inbound_ill != NULL)
25680 						fwdq = inbound_ill->ill_rq;
25681 
25682 					if (fwdq != NULL) {
25683 						put(fwdq, mp1);
25684 						ill_refrele(inbound_ill);
25685 					} else
25686 						put(WR(ill->ill_rq), mp1);
25687 					mp1 = nxt_mp;
25688 				}
25689 				NCE_REFRELE(nce);
25690 			} else {	/* nce is NULL; clean up */
25691 				ire_delete(ire);
25692 				freemsg(mp);
25693 				freemsg(mp1);
25694 				return;
25695 			}
25696 		} else {
25697 			ire->ire_dlureq_mp = mp1;
25698 			ire_add_then_send(q, ire, mp);
25699 		}
25700 		return;	/* All is well, the packet has been sent. */
25701 	}
25702 	default:
25703 		break;
25704 	}
25705 	if (q->q_next) {
25706 		putnext(q, mp);
25707 	} else
25708 		freemsg(mp);
25709 }
25710 
25711 /*
25712  * Process IP options in an outbound packet.  Modify the destination if there
25713  * is a source route option.
25714  * Returns non-zero if something fails in which case an ICMP error has been
25715  * sent and mp freed.
25716  */
25717 static int
25718 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
25719     boolean_t mctl_present, zoneid_t zoneid)
25720 {
25721 	ipoptp_t	opts;
25722 	uchar_t		*opt;
25723 	uint8_t		optval;
25724 	uint8_t		optlen;
25725 	ipaddr_t	dst;
25726 	intptr_t	code = 0;
25727 	mblk_t		*mp;
25728 	ire_t		*ire = NULL;
25729 
25730 	ip2dbg(("ip_wput_options\n"));
25731 	mp = ipsec_mp;
25732 	if (mctl_present) {
25733 		mp = ipsec_mp->b_cont;
25734 	}
25735 
25736 	dst = ipha->ipha_dst;
25737 	for (optval = ipoptp_first(&opts, ipha);
25738 	    optval != IPOPT_EOL;
25739 	    optval = ipoptp_next(&opts)) {
25740 		opt = opts.ipoptp_cur;
25741 		optlen = opts.ipoptp_len;
25742 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
25743 		    optval, optlen));
25744 		switch (optval) {
25745 			uint32_t off;
25746 		case IPOPT_SSRR:
25747 		case IPOPT_LSRR:
25748 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25749 				ip1dbg((
25750 				    "ip_wput_options: bad option offset\n"));
25751 				code = (char *)&opt[IPOPT_OLEN] -
25752 				    (char *)ipha;
25753 				goto param_prob;
25754 			}
25755 			off = opt[IPOPT_OFFSET];
25756 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
25757 			    ntohl(dst)));
25758 			/*
25759 			 * For strict: verify that dst is directly
25760 			 * reachable.
25761 			 */
25762 			if (optval == IPOPT_SSRR) {
25763 				ire = ire_ftable_lookup(dst, 0, 0,
25764 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25765 				    MBLK_GETLABEL(mp),
25766 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
25767 				if (ire == NULL) {
25768 					ip1dbg(("ip_wput_options: SSRR not"
25769 					    " directly reachable: 0x%x\n",
25770 					    ntohl(dst)));
25771 					goto bad_src_route;
25772 				}
25773 				ire_refrele(ire);
25774 			}
25775 			break;
25776 		case IPOPT_RR:
25777 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25778 				ip1dbg((
25779 				    "ip_wput_options: bad option offset\n"));
25780 				code = (char *)&opt[IPOPT_OLEN] -
25781 				    (char *)ipha;
25782 				goto param_prob;
25783 			}
25784 			break;
25785 		case IPOPT_TS:
25786 			/*
25787 			 * Verify that length >=5 and that there is either
25788 			 * room for another timestamp or that the overflow
25789 			 * counter is not maxed out.
25790 			 */
25791 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
25792 			if (optlen < IPOPT_MINLEN_IT) {
25793 				goto param_prob;
25794 			}
25795 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25796 				ip1dbg((
25797 				    "ip_wput_options: bad option offset\n"));
25798 				code = (char *)&opt[IPOPT_OFFSET] -
25799 				    (char *)ipha;
25800 				goto param_prob;
25801 			}
25802 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25803 			case IPOPT_TS_TSONLY:
25804 				off = IPOPT_TS_TIMELEN;
25805 				break;
25806 			case IPOPT_TS_TSANDADDR:
25807 			case IPOPT_TS_PRESPEC:
25808 			case IPOPT_TS_PRESPEC_RFC791:
25809 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25810 				break;
25811 			default:
25812 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
25813 				    (char *)ipha;
25814 				goto param_prob;
25815 			}
25816 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
25817 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
25818 				/*
25819 				 * No room and the overflow counter is 15
25820 				 * already.
25821 				 */
25822 				goto param_prob;
25823 			}
25824 			break;
25825 		}
25826 	}
25827 
25828 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
25829 		return (0);
25830 
25831 	ip1dbg(("ip_wput_options: error processing IP options."));
25832 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
25833 
25834 param_prob:
25835 	/*
25836 	 * Since ip_wput() isn't close to finished, we fill
25837 	 * in enough of the header for credible error reporting.
25838 	 */
25839 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25840 		/* Failed */
25841 		freemsg(ipsec_mp);
25842 		return (-1);
25843 	}
25844 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
25845 	return (-1);
25846 
25847 bad_src_route:
25848 	/*
25849 	 * Since ip_wput() isn't close to finished, we fill
25850 	 * in enough of the header for credible error reporting.
25851 	 */
25852 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25853 		/* Failed */
25854 		freemsg(ipsec_mp);
25855 		return (-1);
25856 	}
25857 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
25858 	return (-1);
25859 }
25860 
25861 /*
25862  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25863  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25864  * thru /etc/system.
25865  */
25866 #define	CONN_MAXDRAINCNT	64
25867 
25868 static void
25869 conn_drain_init(void)
25870 {
25871 	int i;
25872 
25873 	conn_drain_list_cnt = conn_drain_nthreads;
25874 
25875 	if ((conn_drain_list_cnt == 0) ||
25876 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25877 		/*
25878 		 * Default value of the number of drainers is the
25879 		 * number of cpus, subject to maximum of 8 drainers.
25880 		 */
25881 		if (boot_max_ncpus != -1)
25882 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25883 		else
25884 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25885 	}
25886 
25887 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25888 	    KM_SLEEP);
25889 
25890 	for (i = 0; i < conn_drain_list_cnt; i++) {
25891 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25892 		    MUTEX_DEFAULT, NULL);
25893 	}
25894 }
25895 
25896 static void
25897 conn_drain_fini(void)
25898 {
25899 	int i;
25900 
25901 	for (i = 0; i < conn_drain_list_cnt; i++)
25902 		mutex_destroy(&conn_drain_list[i].idl_lock);
25903 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25904 	conn_drain_list = NULL;
25905 }
25906 
25907 /*
25908  * Note: For an overview of how flowcontrol is handled in IP please see the
25909  * IP Flowcontrol notes at the top of this file.
25910  *
25911  * Flow control has blocked us from proceeding. Insert the given conn in one
25912  * of the conn drain lists. These conn wq's will be qenabled later on when
25913  * STREAMS flow control does a backenable. conn_walk_drain will enable
25914  * the first conn in each of these drain lists. Each of these qenabled conns
25915  * in turn enables the next in the list, after it runs, or when it closes,
25916  * thus sustaining the drain process.
25917  *
25918  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25919  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25920  * running at any time, on a given conn, since there can be only 1 service proc
25921  * running on a queue at any time.
25922  */
25923 void
25924 conn_drain_insert(conn_t *connp)
25925 {
25926 	idl_t	*idl;
25927 	uint_t	index;
25928 
25929 	mutex_enter(&connp->conn_lock);
25930 	if (connp->conn_state_flags & CONN_CLOSING) {
25931 		/*
25932 		 * The conn is closing as a result of which CONN_CLOSING
25933 		 * is set. Return.
25934 		 */
25935 		mutex_exit(&connp->conn_lock);
25936 		return;
25937 	} else if (connp->conn_idl == NULL) {
25938 		/*
25939 		 * Assign the next drain list round robin. We dont' use
25940 		 * a lock, and thus it may not be strictly round robin.
25941 		 * Atomicity of load/stores is enough to make sure that
25942 		 * conn_drain_list_index is always within bounds.
25943 		 */
25944 		index = conn_drain_list_index;
25945 		ASSERT(index < conn_drain_list_cnt);
25946 		connp->conn_idl = &conn_drain_list[index];
25947 		index++;
25948 		if (index == conn_drain_list_cnt)
25949 			index = 0;
25950 		conn_drain_list_index = index;
25951 	}
25952 	mutex_exit(&connp->conn_lock);
25953 
25954 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25955 	if ((connp->conn_drain_prev != NULL) ||
25956 	    (connp->conn_state_flags & CONN_CLOSING)) {
25957 		/*
25958 		 * The conn is already in the drain list, OR
25959 		 * the conn is closing. We need to check again for
25960 		 * the closing case again since close can happen
25961 		 * after we drop the conn_lock, and before we
25962 		 * acquire the CONN_DRAIN_LIST_LOCK.
25963 		 */
25964 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25965 		return;
25966 	} else {
25967 		idl = connp->conn_idl;
25968 	}
25969 
25970 	/*
25971 	 * The conn is not in the drain list. Insert it at the
25972 	 * tail of the drain list. The drain list is circular
25973 	 * and doubly linked. idl_conn points to the 1st element
25974 	 * in the list.
25975 	 */
25976 	if (idl->idl_conn == NULL) {
25977 		idl->idl_conn = connp;
25978 		connp->conn_drain_next = connp;
25979 		connp->conn_drain_prev = connp;
25980 	} else {
25981 		conn_t *head = idl->idl_conn;
25982 
25983 		connp->conn_drain_next = head;
25984 		connp->conn_drain_prev = head->conn_drain_prev;
25985 		head->conn_drain_prev->conn_drain_next = connp;
25986 		head->conn_drain_prev = connp;
25987 	}
25988 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25989 }
25990 
25991 /*
25992  * This conn is closing, and we are called from ip_close. OR
25993  * This conn has been serviced by ip_wsrv, and we need to do the tail
25994  * processing.
25995  * If this conn is part of the drain list, we may need to sustain the drain
25996  * process by qenabling the next conn in the drain list. We may also need to
25997  * remove this conn from the list, if it is done.
25998  */
25999 static void
26000 conn_drain_tail(conn_t *connp, boolean_t closing)
26001 {
26002 	idl_t *idl;
26003 
26004 	/*
26005 	 * connp->conn_idl is stable at this point, and no lock is needed
26006 	 * to check it. If we are called from ip_close, close has already
26007 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26008 	 * called us only because conn_idl is non-null. If we are called thru
26009 	 * service, conn_idl could be null, but it cannot change because
26010 	 * service is single-threaded per queue, and there cannot be another
26011 	 * instance of service trying to call conn_drain_insert on this conn
26012 	 * now.
26013 	 */
26014 	ASSERT(!closing || (connp->conn_idl != NULL));
26015 
26016 	/*
26017 	 * If connp->conn_idl is null, the conn has not been inserted into any
26018 	 * drain list even once since creation of the conn. Just return.
26019 	 */
26020 	if (connp->conn_idl == NULL)
26021 		return;
26022 
26023 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26024 
26025 	if (connp->conn_drain_prev == NULL) {
26026 		/* This conn is currently not in the drain list.  */
26027 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26028 		return;
26029 	}
26030 	idl = connp->conn_idl;
26031 	if (idl->idl_conn_draining == connp) {
26032 		/*
26033 		 * This conn is the current drainer. If this is the last conn
26034 		 * in the drain list, we need to do more checks, in the 'if'
26035 		 * below. Otherwwise we need to just qenable the next conn,
26036 		 * to sustain the draining, and is handled in the 'else'
26037 		 * below.
26038 		 */
26039 		if (connp->conn_drain_next == idl->idl_conn) {
26040 			/*
26041 			 * This conn is the last in this list. This round
26042 			 * of draining is complete. If idl_repeat is set,
26043 			 * it means another flow enabling has happened from
26044 			 * the driver/streams and we need to another round
26045 			 * of draining.
26046 			 * If there are more than 2 conns in the drain list,
26047 			 * do a left rotate by 1, so that all conns except the
26048 			 * conn at the head move towards the head by 1, and the
26049 			 * the conn at the head goes to the tail. This attempts
26050 			 * a more even share for all queues that are being
26051 			 * drained.
26052 			 */
26053 			if ((connp->conn_drain_next != connp) &&
26054 			    (idl->idl_conn->conn_drain_next != connp)) {
26055 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26056 			}
26057 			if (idl->idl_repeat) {
26058 				qenable(idl->idl_conn->conn_wq);
26059 				idl->idl_conn_draining = idl->idl_conn;
26060 				idl->idl_repeat = 0;
26061 			} else {
26062 				idl->idl_conn_draining = NULL;
26063 			}
26064 		} else {
26065 			/*
26066 			 * If the next queue that we are now qenable'ing,
26067 			 * is closing, it will remove itself from this list
26068 			 * and qenable the subsequent queue in ip_close().
26069 			 * Serialization is acheived thru idl_lock.
26070 			 */
26071 			qenable(connp->conn_drain_next->conn_wq);
26072 			idl->idl_conn_draining = connp->conn_drain_next;
26073 		}
26074 	}
26075 	if (!connp->conn_did_putbq || closing) {
26076 		/*
26077 		 * Remove ourself from the drain list, if we did not do
26078 		 * a putbq, or if the conn is closing.
26079 		 * Note: It is possible that q->q_first is non-null. It means
26080 		 * that these messages landed after we did a enableok() in
26081 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26082 		 * service them.
26083 		 */
26084 		if (connp->conn_drain_next == connp) {
26085 			/* Singleton in the list */
26086 			ASSERT(connp->conn_drain_prev == connp);
26087 			idl->idl_conn = NULL;
26088 			idl->idl_conn_draining = NULL;
26089 		} else {
26090 			connp->conn_drain_prev->conn_drain_next =
26091 			    connp->conn_drain_next;
26092 			connp->conn_drain_next->conn_drain_prev =
26093 			    connp->conn_drain_prev;
26094 			if (idl->idl_conn == connp)
26095 				idl->idl_conn = connp->conn_drain_next;
26096 			ASSERT(idl->idl_conn_draining != connp);
26097 
26098 		}
26099 		connp->conn_drain_next = NULL;
26100 		connp->conn_drain_prev = NULL;
26101 	}
26102 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26103 }
26104 
26105 /*
26106  * Write service routine. Shared perimeter entry point.
26107  * ip_wsrv can be called in any of the following ways.
26108  * 1. The device queue's messages has fallen below the low water mark
26109  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26110  *    the drain lists and backenable the first conn in each list.
26111  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
26112  *    qenabled non-tcp upper layers. We start dequeing messages and call
26113  *    ip_wput for each message.
26114  */
26115 
26116 void
26117 ip_wsrv(queue_t *q)
26118 {
26119 	conn_t	*connp;
26120 	ill_t	*ill;
26121 	mblk_t	*mp;
26122 
26123 	if (q->q_next) {
26124 		ill = (ill_t *)q->q_ptr;
26125 		if (ill->ill_state_flags == 0) {
26126 			/*
26127 			 * The device flow control has opened up.
26128 			 * Walk through conn drain lists and qenable the
26129 			 * first conn in each list. This makes sense only
26130 			 * if the stream is fully plumbed and setup.
26131 			 * Hence the if check above.
26132 			 */
26133 			ip1dbg(("ip_wsrv: walking\n"));
26134 			conn_walk_drain();
26135 		}
26136 		return;
26137 	}
26138 
26139 	connp = Q_TO_CONN(q);
26140 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
26141 
26142 	/*
26143 	 * 1. Set conn_draining flag to signal that service is active.
26144 	 *
26145 	 * 2. ip_output determines whether it has been called from service,
26146 	 *    based on the last parameter. If it is IP_WSRV it concludes it
26147 	 *    has been called from service.
26148 	 *
26149 	 * 3. Message ordering is preserved by the following logic.
26150 	 *    i. A directly called ip_output (i.e. not thru service) will queue
26151 	 *    the message at the tail, if conn_draining is set (i.e. service
26152 	 *    is running) or if q->q_first is non-null.
26153 	 *
26154 	 *    ii. If ip_output is called from service, and if ip_output cannot
26155 	 *    putnext due to flow control, it does a putbq.
26156 	 *
26157 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
26158 	 *    (causing an infinite loop).
26159 	 */
26160 	ASSERT(!connp->conn_did_putbq);
26161 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
26162 		connp->conn_draining = 1;
26163 		noenable(q);
26164 		while ((mp = getq(q)) != NULL) {
26165 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
26166 			if (connp->conn_did_putbq) {
26167 				/* ip_wput did a putbq */
26168 				break;
26169 			}
26170 		}
26171 		/*
26172 		 * At this point, a thread coming down from top, calling
26173 		 * ip_wput, may end up queueing the message. We have not yet
26174 		 * enabled the queue, so ip_wsrv won't be called again.
26175 		 * To avoid this race, check q->q_first again (in the loop)
26176 		 * If the other thread queued the message before we call
26177 		 * enableok(), we will catch it in the q->q_first check.
26178 		 * If the other thread queues the message after we call
26179 		 * enableok(), ip_wsrv will be called again by STREAMS.
26180 		 */
26181 		connp->conn_draining = 0;
26182 		enableok(q);
26183 	}
26184 
26185 	/* Enable the next conn for draining */
26186 	conn_drain_tail(connp, B_FALSE);
26187 
26188 	connp->conn_did_putbq = 0;
26189 }
26190 
26191 /*
26192  * Walk the list of all conn's calling the function provided with the
26193  * specified argument for each.	 Note that this only walks conn's that
26194  * have been bound.
26195  * Applies to both IPv4 and IPv6.
26196  */
26197 static void
26198 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
26199 {
26200 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
26201 	    func, arg, zoneid);
26202 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
26203 	    func, arg, zoneid);
26204 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
26205 	    func, arg, zoneid);
26206 	conn_walk_fanout_table(ipcl_proto_fanout,
26207 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
26208 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
26209 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
26210 }
26211 
26212 /*
26213  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
26214  * of conns that need to be drained, check if drain is already in progress.
26215  * If so set the idl_repeat bit, indicating that the last conn in the list
26216  * needs to reinitiate the drain once again, for the list. If drain is not
26217  * in progress for the list, initiate the draining, by qenabling the 1st
26218  * conn in the list. The drain is self-sustaining, each qenabled conn will
26219  * in turn qenable the next conn, when it is done/blocked/closing.
26220  */
26221 static void
26222 conn_walk_drain(void)
26223 {
26224 	int i;
26225 	idl_t *idl;
26226 
26227 	IP_STAT(ip_conn_walk_drain);
26228 
26229 	for (i = 0; i < conn_drain_list_cnt; i++) {
26230 		idl = &conn_drain_list[i];
26231 		mutex_enter(&idl->idl_lock);
26232 		if (idl->idl_conn == NULL) {
26233 			mutex_exit(&idl->idl_lock);
26234 			continue;
26235 		}
26236 		/*
26237 		 * If this list is not being drained currently by
26238 		 * an ip_wsrv thread, start the process.
26239 		 */
26240 		if (idl->idl_conn_draining == NULL) {
26241 			ASSERT(idl->idl_repeat == 0);
26242 			qenable(idl->idl_conn->conn_wq);
26243 			idl->idl_conn_draining = idl->idl_conn;
26244 		} else {
26245 			idl->idl_repeat = 1;
26246 		}
26247 		mutex_exit(&idl->idl_lock);
26248 	}
26249 }
26250 
26251 /*
26252  * Walk an conn hash table of `count' buckets, calling func for each entry.
26253  */
26254 static void
26255 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
26256     zoneid_t zoneid)
26257 {
26258 	conn_t	*connp;
26259 
26260 	while (count-- > 0) {
26261 		mutex_enter(&connfp->connf_lock);
26262 		for (connp = connfp->connf_head; connp != NULL;
26263 		    connp = connp->conn_next) {
26264 			if (zoneid == GLOBAL_ZONEID ||
26265 			    zoneid == connp->conn_zoneid) {
26266 				CONN_INC_REF(connp);
26267 				mutex_exit(&connfp->connf_lock);
26268 				(*func)(connp, arg);
26269 				mutex_enter(&connfp->connf_lock);
26270 				CONN_DEC_REF(connp);
26271 			}
26272 		}
26273 		mutex_exit(&connfp->connf_lock);
26274 		connfp++;
26275 	}
26276 }
26277 
26278 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
26279 static void
26280 conn_report1(conn_t *connp, void *mp)
26281 {
26282 	char	buf1[INET6_ADDRSTRLEN];
26283 	char	buf2[INET6_ADDRSTRLEN];
26284 	uint_t	print_len, buf_len;
26285 
26286 	ASSERT(connp != NULL);
26287 
26288 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
26289 	if (buf_len <= 0)
26290 		return;
26291 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
26292 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
26293 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
26294 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
26295 	    "%5d %s/%05d %s/%05d\n",
26296 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
26297 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
26298 	    buf1, connp->conn_lport,
26299 	    buf2, connp->conn_fport);
26300 	if (print_len < buf_len) {
26301 		((mblk_t *)mp)->b_wptr += print_len;
26302 	} else {
26303 		((mblk_t *)mp)->b_wptr += buf_len;
26304 	}
26305 }
26306 
26307 /*
26308  * Named Dispatch routine to produce a formatted report on all conns
26309  * that are listed in one of the fanout tables.
26310  * This report is accessed by using the ndd utility to "get" ND variable
26311  * "ip_conn_status".
26312  */
26313 /* ARGSUSED */
26314 static int
26315 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
26316 {
26317 	(void) mi_mpprintf(mp,
26318 	    "CONN      " MI_COL_HDRPAD_STR
26319 	    "rfq      " MI_COL_HDRPAD_STR
26320 	    "stq      " MI_COL_HDRPAD_STR
26321 	    " zone local                 remote");
26322 
26323 	/*
26324 	 * Because of the ndd constraint, at most we can have 64K buffer
26325 	 * to put in all conn info.  So to be more efficient, just
26326 	 * allocate a 64K buffer here, assuming we need that large buffer.
26327 	 * This should be OK as only privileged processes can do ndd /dev/ip.
26328 	 */
26329 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
26330 		/* The following may work even if we cannot get a large buf. */
26331 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
26332 		return (0);
26333 	}
26334 
26335 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
26336 	return (0);
26337 }
26338 
26339 /*
26340  * Determine if the ill and multicast aspects of that packets
26341  * "matches" the conn.
26342  */
26343 boolean_t
26344 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
26345     zoneid_t zoneid)
26346 {
26347 	ill_t *in_ill;
26348 	boolean_t found;
26349 	ipif_t *ipif;
26350 	ire_t *ire;
26351 	ipaddr_t dst, src;
26352 
26353 	dst = ipha->ipha_dst;
26354 	src = ipha->ipha_src;
26355 
26356 	/*
26357 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
26358 	 * unicast, broadcast and multicast reception to
26359 	 * conn_incoming_ill. conn_wantpacket itself is called
26360 	 * only for BROADCAST and multicast.
26361 	 *
26362 	 * 1) ip_rput supresses duplicate broadcasts if the ill
26363 	 *    is part of a group. Hence, we should be receiving
26364 	 *    just one copy of broadcast for the whole group.
26365 	 *    Thus, if it is part of the group the packet could
26366 	 *    come on any ill of the group and hence we need a
26367 	 *    match on the group. Otherwise, match on ill should
26368 	 *    be sufficient.
26369 	 *
26370 	 * 2) ip_rput does not suppress duplicate multicast packets.
26371 	 *    If there are two interfaces in a ill group and we have
26372 	 *    2 applications (conns) joined a multicast group G on
26373 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
26374 	 *    will give us two packets because we join G on both the
26375 	 *    interfaces rather than nominating just one interface
26376 	 *    for receiving multicast like broadcast above. So,
26377 	 *    we have to call ilg_lookup_ill to filter out duplicate
26378 	 *    copies, if ill is part of a group.
26379 	 */
26380 	in_ill = connp->conn_incoming_ill;
26381 	if (in_ill != NULL) {
26382 		if (in_ill->ill_group == NULL) {
26383 			if (in_ill != ill)
26384 				return (B_FALSE);
26385 		} else if (in_ill->ill_group != ill->ill_group) {
26386 			return (B_FALSE);
26387 		}
26388 	}
26389 
26390 	if (!CLASSD(dst)) {
26391 		if (IPCL_ZONE_MATCH(connp, zoneid))
26392 			return (B_TRUE);
26393 		/*
26394 		 * The conn is in a different zone; we need to check that this
26395 		 * broadcast address is configured in the application's zone and
26396 		 * on one ill in the group.
26397 		 */
26398 		ipif = ipif_get_next_ipif(NULL, ill);
26399 		if (ipif == NULL)
26400 			return (B_FALSE);
26401 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
26402 		    connp->conn_zoneid, NULL,
26403 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
26404 		ipif_refrele(ipif);
26405 		if (ire != NULL) {
26406 			ire_refrele(ire);
26407 			return (B_TRUE);
26408 		} else {
26409 			return (B_FALSE);
26410 		}
26411 	}
26412 
26413 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
26414 	    connp->conn_zoneid == zoneid) {
26415 		/*
26416 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
26417 		 * disabled, therefore we don't dispatch the multicast packet to
26418 		 * the sending zone.
26419 		 */
26420 		return (B_FALSE);
26421 	}
26422 
26423 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
26424 	    connp->conn_zoneid != zoneid) {
26425 		/*
26426 		 * Multicast packet on the loopback interface: we only match
26427 		 * conns who joined the group in the specified zone.
26428 		 */
26429 		return (B_FALSE);
26430 	}
26431 
26432 	if (connp->conn_multi_router) {
26433 		/* multicast packet and multicast router socket: send up */
26434 		return (B_TRUE);
26435 	}
26436 
26437 	mutex_enter(&connp->conn_lock);
26438 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
26439 	mutex_exit(&connp->conn_lock);
26440 	return (found);
26441 }
26442 
26443 /*
26444  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
26445  */
26446 /* ARGSUSED */
26447 static void
26448 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
26449 {
26450 	ill_t *ill = (ill_t *)q->q_ptr;
26451 	mblk_t	*mp1, *mp2;
26452 	ipif_t  *ipif;
26453 	int err = 0;
26454 	conn_t *connp = NULL;
26455 	ipsq_t	*ipsq;
26456 	arc_t	*arc;
26457 
26458 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
26459 
26460 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
26461 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
26462 
26463 	ASSERT(IAM_WRITER_ILL(ill));
26464 	mp2 = mp->b_cont;
26465 	mp->b_cont = NULL;
26466 
26467 	/*
26468 	 * We have now received the arp bringup completion message
26469 	 * from ARP. Mark the arp bringup as done. Also if the arp
26470 	 * stream has already started closing, send up the AR_ARP_CLOSING
26471 	 * ack now since ARP is waiting in close for this ack.
26472 	 */
26473 	mutex_enter(&ill->ill_lock);
26474 	ill->ill_arp_bringup_pending = 0;
26475 	if (ill->ill_arp_closing) {
26476 		mutex_exit(&ill->ill_lock);
26477 		/* Let's reuse the mp for sending the ack */
26478 		arc = (arc_t *)mp->b_rptr;
26479 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
26480 		arc->arc_cmd = AR_ARP_CLOSING;
26481 		qreply(q, mp);
26482 	} else {
26483 		mutex_exit(&ill->ill_lock);
26484 		freeb(mp);
26485 	}
26486 
26487 	/* We should have an IOCTL waiting on this. */
26488 	ipsq = ill->ill_phyint->phyint_ipsq;
26489 	ipif = ipsq->ipsq_pending_ipif;
26490 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
26491 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
26492 	if (mp1 == NULL) {
26493 		/* bringup was aborted by the user */
26494 		freemsg(mp2);
26495 		return;
26496 	}
26497 	ASSERT(connp != NULL);
26498 	q = CONNP_TO_WQ(connp);
26499 	/*
26500 	 * If the DL_BIND_REQ fails, it is noted
26501 	 * in arc_name_offset.
26502 	 */
26503 	err = *((int *)mp2->b_rptr);
26504 	if (err == 0) {
26505 		if (ipif->ipif_isv6) {
26506 			if ((err = ipif_up_done_v6(ipif)) != 0)
26507 				ip0dbg(("ip_arp_done: init failed\n"));
26508 		} else {
26509 			if ((err = ipif_up_done(ipif)) != 0)
26510 				ip0dbg(("ip_arp_done: init failed\n"));
26511 		}
26512 	} else {
26513 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
26514 	}
26515 
26516 	freemsg(mp2);
26517 
26518 	if ((err == 0) && (ill->ill_up_ipifs)) {
26519 		err = ill_up_ipifs(ill, q, mp1);
26520 		if (err == EINPROGRESS)
26521 			return;
26522 	}
26523 
26524 	if (ill->ill_up_ipifs) {
26525 		ill_group_cleanup(ill);
26526 	}
26527 
26528 	/*
26529 	 * The ioctl must complete now without EINPROGRESS
26530 	 * since ipsq_pending_mp_get has removed the ioctl mblk
26531 	 * from ipsq_pending_mp. Otherwise the ioctl will be
26532 	 * stuck for ever in the ipsq.
26533 	 */
26534 	ASSERT(err != EINPROGRESS);
26535 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
26536 }
26537 
26538 /* Allocate the private structure */
26539 static int
26540 ip_priv_alloc(void **bufp)
26541 {
26542 	void	*buf;
26543 
26544 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
26545 		return (ENOMEM);
26546 
26547 	*bufp = buf;
26548 	return (0);
26549 }
26550 
26551 /* Function to delete the private structure */
26552 void
26553 ip_priv_free(void *buf)
26554 {
26555 	ASSERT(buf != NULL);
26556 	kmem_free(buf, sizeof (ip_priv_t));
26557 }
26558 
26559 /*
26560  * The entry point for IPPF processing.
26561  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
26562  * routine just returns.
26563  *
26564  * When called, ip_process generates an ipp_packet_t structure
26565  * which holds the state information for this packet and invokes the
26566  * the classifier (via ipp_packet_process). The classification, depending on
26567  * configured filters, results in a list of actions for this packet. Invoking
26568  * an action may cause the packet to be dropped, in which case the resulting
26569  * mblk (*mpp) is NULL. proc indicates the callout position for
26570  * this packet and ill_index is the interface this packet on or will leave
26571  * on (inbound and outbound resp.).
26572  */
26573 void
26574 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
26575 {
26576 	mblk_t		*mp;
26577 	ip_priv_t	*priv;
26578 	ipp_action_id_t	aid;
26579 	int		rc = 0;
26580 	ipp_packet_t	*pp;
26581 #define	IP_CLASS	"ip"
26582 
26583 	/* If the classifier is not loaded, return  */
26584 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
26585 		return;
26586 	}
26587 
26588 	mp = *mpp;
26589 	ASSERT(mp != NULL);
26590 
26591 	/* Allocate the packet structure */
26592 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
26593 	if (rc != 0) {
26594 		*mpp = NULL;
26595 		freemsg(mp);
26596 		return;
26597 	}
26598 
26599 	/* Allocate the private structure */
26600 	rc = ip_priv_alloc((void **)&priv);
26601 	if (rc != 0) {
26602 		*mpp = NULL;
26603 		freemsg(mp);
26604 		ipp_packet_free(pp);
26605 		return;
26606 	}
26607 	priv->proc = proc;
26608 	priv->ill_index = ill_index;
26609 	ipp_packet_set_private(pp, priv, ip_priv_free);
26610 	ipp_packet_set_data(pp, mp);
26611 
26612 	/* Invoke the classifier */
26613 	rc = ipp_packet_process(&pp);
26614 	if (pp != NULL) {
26615 		mp = ipp_packet_get_data(pp);
26616 		ipp_packet_free(pp);
26617 		if (rc != 0) {
26618 			freemsg(mp);
26619 			*mpp = NULL;
26620 		}
26621 	} else {
26622 		*mpp = NULL;
26623 	}
26624 #undef	IP_CLASS
26625 }
26626 
26627 /*
26628  * Propagate a multicast group membership operation (add/drop) on
26629  * all the interfaces crossed by the related multirt routes.
26630  * The call is considered successful if the operation succeeds
26631  * on at least one interface.
26632  */
26633 static int
26634 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
26635     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
26636     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
26637     mblk_t *first_mp)
26638 {
26639 	ire_t		*ire_gw;
26640 	irb_t		*irb;
26641 	int		error = 0;
26642 	opt_restart_t	*or;
26643 
26644 	irb = ire->ire_bucket;
26645 	ASSERT(irb != NULL);
26646 
26647 	ASSERT(DB_TYPE(first_mp) == M_CTL);
26648 
26649 	or = (opt_restart_t *)first_mp->b_rptr;
26650 	IRB_REFHOLD(irb);
26651 	for (; ire != NULL; ire = ire->ire_next) {
26652 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
26653 			continue;
26654 		if (ire->ire_addr != group)
26655 			continue;
26656 
26657 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
26658 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
26659 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
26660 		/* No resolver exists for the gateway; skip this ire. */
26661 		if (ire_gw == NULL)
26662 			continue;
26663 
26664 		/*
26665 		 * This function can return EINPROGRESS. If so the operation
26666 		 * will be restarted from ip_restart_optmgmt which will
26667 		 * call ip_opt_set and option processing will restart for
26668 		 * this option. So we may end up calling 'fn' more than once.
26669 		 * This requires that 'fn' is idempotent except for the
26670 		 * return value. The operation is considered a success if
26671 		 * it succeeds at least once on any one interface.
26672 		 */
26673 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
26674 		    NULL, fmode, src, first_mp);
26675 		if (error == 0)
26676 			or->or_private = CGTP_MCAST_SUCCESS;
26677 
26678 		if (ip_debug > 0) {
26679 			ulong_t	off;
26680 			char	*ksym;
26681 			ksym = kobj_getsymname((uintptr_t)fn, &off);
26682 			ip2dbg(("ip_multirt_apply_membership: "
26683 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
26684 			    "error %d [success %u]\n",
26685 			    ksym ? ksym : "?",
26686 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
26687 			    error, or->or_private));
26688 		}
26689 
26690 		ire_refrele(ire_gw);
26691 		if (error == EINPROGRESS) {
26692 			IRB_REFRELE(irb);
26693 			return (error);
26694 		}
26695 	}
26696 	IRB_REFRELE(irb);
26697 	/*
26698 	 * Consider the call as successful if we succeeded on at least
26699 	 * one interface. Otherwise, return the last encountered error.
26700 	 */
26701 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
26702 }
26703 
26704 
26705 /*
26706  * Issue a warning regarding a route crossing an interface with an
26707  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
26708  * amount of time is logged.
26709  */
26710 static void
26711 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
26712 {
26713 	hrtime_t	current = gethrtime();
26714 	char		buf[16];
26715 
26716 	/* Convert interval in ms to hrtime in ns */
26717 	if (multirt_bad_mtu_last_time +
26718 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
26719 	    current) {
26720 		cmn_err(CE_WARN, "ip: ignoring multiroute "
26721 		    "to %s, incorrect MTU %u (expected %u)\n",
26722 		    ip_dot_addr(ire->ire_addr, buf),
26723 		    ire->ire_max_frag, max_frag);
26724 
26725 		multirt_bad_mtu_last_time = current;
26726 	}
26727 }
26728 
26729 
26730 /*
26731  * Get the CGTP (multirouting) filtering status.
26732  * If 0, the CGTP hooks are transparent.
26733  */
26734 /* ARGSUSED */
26735 static int
26736 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
26737 {
26738 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26739 
26740 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
26741 	return (0);
26742 }
26743 
26744 
26745 /*
26746  * Set the CGTP (multirouting) filtering status.
26747  * If the status is changed from active to transparent
26748  * or from transparent to active, forward the new status
26749  * to the filtering module (if loaded).
26750  */
26751 /* ARGSUSED */
26752 static int
26753 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
26754     cred_t *ioc_cr)
26755 {
26756 	long		new_value;
26757 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26758 
26759 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
26760 	    new_value < 0 || new_value > 1) {
26761 		return (EINVAL);
26762 	}
26763 
26764 	/*
26765 	 * Do not enable CGTP filtering - thus preventing the hooks
26766 	 * from being invoked - if the version number of the
26767 	 * filtering module hooks does not match.
26768 	 */
26769 	if ((ip_cgtp_filter_ops != NULL) &&
26770 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
26771 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
26772 		    "(module hooks version %d, expecting %d)\n",
26773 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
26774 		return (ENOTSUP);
26775 	}
26776 
26777 	if ((!*ip_cgtp_filter_value) && new_value) {
26778 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
26779 		    ip_cgtp_filter_ops == NULL ?
26780 		    " (module not loaded)" : "");
26781 	}
26782 	if (*ip_cgtp_filter_value && (!new_value)) {
26783 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
26784 		    ip_cgtp_filter_ops == NULL ?
26785 		    " (module not loaded)" : "");
26786 	}
26787 
26788 	if (ip_cgtp_filter_ops != NULL) {
26789 		int	res;
26790 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
26791 			return (res);
26792 		}
26793 	}
26794 
26795 	*ip_cgtp_filter_value = (boolean_t)new_value;
26796 
26797 	return (0);
26798 }
26799 
26800 
26801 /*
26802  * Return the expected CGTP hooks version number.
26803  */
26804 int
26805 ip_cgtp_filter_supported(void)
26806 {
26807 	return (ip_cgtp_filter_rev);
26808 }
26809 
26810 
26811 /*
26812  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
26813  * or by invoking this function. In the first case, the version number
26814  * of the registered structure is checked at hooks activation time
26815  * in ip_cgtp_filter_set().
26816  */
26817 int
26818 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
26819 {
26820 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
26821 		return (ENOTSUP);
26822 
26823 	ip_cgtp_filter_ops = ops;
26824 	return (0);
26825 }
26826 
26827 static squeue_func_t
26828 ip_squeue_switch(int val)
26829 {
26830 	squeue_func_t rval = squeue_fill;
26831 
26832 	switch (val) {
26833 	case IP_SQUEUE_ENTER_NODRAIN:
26834 		rval = squeue_enter_nodrain;
26835 		break;
26836 	case IP_SQUEUE_ENTER:
26837 		rval = squeue_enter;
26838 		break;
26839 	default:
26840 		break;
26841 	}
26842 	return (rval);
26843 }
26844 
26845 /* ARGSUSED */
26846 static int
26847 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
26848     caddr_t addr, cred_t *cr)
26849 {
26850 	int *v = (int *)addr;
26851 	long new_value;
26852 
26853 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26854 		return (EINVAL);
26855 
26856 	ip_input_proc = ip_squeue_switch(new_value);
26857 	*v = new_value;
26858 	return (0);
26859 }
26860 
26861 /* ARGSUSED */
26862 static int
26863 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26864     caddr_t addr, cred_t *cr)
26865 {
26866 	int *v = (int *)addr;
26867 	long new_value;
26868 
26869 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26870 		return (EINVAL);
26871 
26872 	*v = new_value;
26873 	return (0);
26874 }
26875 
26876 static void
26877 ip_kstat_init(void)
26878 {
26879 	ip_named_kstat_t template = {
26880 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26881 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26882 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26883 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26884 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26885 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26886 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26887 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26888 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26889 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26890 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26891 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26892 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26893 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26894 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26895 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26896 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26897 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26898 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26899 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26900 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26901 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26902 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26903 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26904 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26905 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26906 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26907 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26908 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26909 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26910 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26911 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26912 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26913 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26914 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26915 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26916 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26917 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26918 	};
26919 
26920 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26921 					NUM_OF_FIELDS(ip_named_kstat_t),
26922 					0);
26923 	if (!ip_mibkp)
26924 		return;
26925 
26926 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26927 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26928 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26929 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26930 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26931 
26932 	template.netToMediaEntrySize.value.i32 =
26933 		sizeof (mib2_ipNetToMediaEntry_t);
26934 
26935 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26936 
26937 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26938 
26939 	ip_mibkp->ks_update = ip_kstat_update;
26940 
26941 	kstat_install(ip_mibkp);
26942 }
26943 
26944 static void
26945 ip_kstat_fini(void)
26946 {
26947 
26948 	if (ip_mibkp != NULL) {
26949 		kstat_delete(ip_mibkp);
26950 		ip_mibkp = NULL;
26951 	}
26952 }
26953 
26954 static int
26955 ip_kstat_update(kstat_t *kp, int rw)
26956 {
26957 	ip_named_kstat_t *ipkp;
26958 
26959 	if (!kp || !kp->ks_data)
26960 		return (EIO);
26961 
26962 	if (rw == KSTAT_WRITE)
26963 		return (EACCES);
26964 
26965 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26966 
26967 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26968 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26969 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26970 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26971 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26972 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26973 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26974 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26975 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26976 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26977 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26978 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26979 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26980 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26981 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26982 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26983 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26984 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26985 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26986 
26987 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26988 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26989 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26990 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
26991 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
26992 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
26993 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
26994 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
26995 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
26996 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
26997 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
26998 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
26999 
27000 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
27001 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
27002 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
27003 
27004 	return (0);
27005 }
27006 
27007 static void
27008 icmp_kstat_init(void)
27009 {
27010 	icmp_named_kstat_t template = {
27011 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27012 		{ "inErrors",		KSTAT_DATA_UINT32 },
27013 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27014 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27015 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27016 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27017 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27018 		{ "inEchos",		KSTAT_DATA_UINT32 },
27019 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27020 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27021 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27022 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27023 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27024 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27025 		{ "outErrors",		KSTAT_DATA_UINT32 },
27026 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27027 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27028 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27029 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27030 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27031 		{ "outEchos",		KSTAT_DATA_UINT32 },
27032 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27033 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27034 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27035 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27036 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27037 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27038 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27039 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27040 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27041 		{ "outDrops",		KSTAT_DATA_UINT32 },
27042 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27043 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27044 	};
27045 
27046 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27047 					NUM_OF_FIELDS(icmp_named_kstat_t),
27048 					0);
27049 	if (icmp_mibkp == NULL)
27050 		return;
27051 
27052 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27053 
27054 	icmp_mibkp->ks_update = icmp_kstat_update;
27055 
27056 	kstat_install(icmp_mibkp);
27057 }
27058 
27059 static void
27060 icmp_kstat_fini(void)
27061 {
27062 
27063 	if (icmp_mibkp != NULL) {
27064 		kstat_delete(icmp_mibkp);
27065 		icmp_mibkp = NULL;
27066 	}
27067 }
27068 
27069 static int
27070 icmp_kstat_update(kstat_t *kp, int rw)
27071 {
27072 	icmp_named_kstat_t *icmpkp;
27073 
27074 	if ((kp == NULL) || (kp->ks_data == NULL))
27075 		return (EIO);
27076 
27077 	if (rw == KSTAT_WRITE)
27078 		return (EACCES);
27079 
27080 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27081 
27082 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27083 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27084 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27085 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27086 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27087 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27088 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27089 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27090 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27091 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27092 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27093 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27094 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27095 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27096 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27097 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27098 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27099 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27100 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27101 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27102 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27103 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27104 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27105 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27106 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27107 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27108 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27109 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27110 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27111 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
27112 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
27113 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
27114 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
27115 
27116 	return (0);
27117 }
27118 
27119 /*
27120  * This is the fanout function for raw socket opened for SCTP.  Note
27121  * that it is called after SCTP checks that there is no socket which
27122  * wants a packet.  Then before SCTP handles this out of the blue packet,
27123  * this function is called to see if there is any raw socket for SCTP.
27124  * If there is and it is bound to the correct address, the packet will
27125  * be sent to that socket.  Note that only one raw socket can be bound to
27126  * a port.  This is assured in ipcl_sctp_hash_insert();
27127  */
27128 void
27129 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
27130     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
27131     uint_t ipif_seqid, zoneid_t zoneid)
27132 {
27133 	conn_t		*connp;
27134 	queue_t		*rq;
27135 	mblk_t		*first_mp;
27136 	boolean_t	secure;
27137 	ip6_t		*ip6h;
27138 
27139 	first_mp = mp;
27140 	if (mctl_present) {
27141 		mp = first_mp->b_cont;
27142 		secure = ipsec_in_is_secure(first_mp);
27143 		ASSERT(mp != NULL);
27144 	} else {
27145 		secure = B_FALSE;
27146 	}
27147 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
27148 
27149 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
27150 	if (connp == NULL) {
27151 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
27152 		    mctl_present);
27153 		return;
27154 	}
27155 	rq = connp->conn_rq;
27156 	if (!canputnext(rq)) {
27157 		CONN_DEC_REF(connp);
27158 		BUMP_MIB(&ip_mib, rawipInOverflows);
27159 		freemsg(first_mp);
27160 		return;
27161 	}
27162 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
27163 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
27164 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
27165 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
27166 		if (first_mp == NULL) {
27167 			CONN_DEC_REF(connp);
27168 			return;
27169 		}
27170 	}
27171 	/*
27172 	 * We probably should not send M_CTL message up to
27173 	 * raw socket.
27174 	 */
27175 	if (mctl_present)
27176 		freeb(first_mp);
27177 
27178 	/* Initiate IPPF processing here if needed. */
27179 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
27180 	    (!isv4 && IP6_IN_IPP(flags))) {
27181 		ip_process(IPP_LOCAL_IN, &mp,
27182 		    recv_ill->ill_phyint->phyint_ifindex);
27183 		if (mp == NULL) {
27184 			CONN_DEC_REF(connp);
27185 			return;
27186 		}
27187 	}
27188 
27189 	if (connp->conn_recvif || connp->conn_recvslla ||
27190 	    ((connp->conn_ipv6_recvpktinfo ||
27191 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
27192 	    (flags & IP_FF_IP6INFO))) {
27193 		int in_flags = 0;
27194 
27195 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
27196 			in_flags = IPF_RECVIF;
27197 		}
27198 		if (connp->conn_recvslla) {
27199 			in_flags |= IPF_RECVSLLA;
27200 		}
27201 		if (isv4) {
27202 			mp = ip_add_info(mp, recv_ill, in_flags);
27203 		} else {
27204 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
27205 			if (mp == NULL) {
27206 				CONN_DEC_REF(connp);
27207 				return;
27208 			}
27209 		}
27210 	}
27211 
27212 	BUMP_MIB(&ip_mib, ipInDelivers);
27213 	/*
27214 	 * We are sending the IPSEC_IN message also up. Refer
27215 	 * to comments above this function.
27216 	 */
27217 	putnext(rq, mp);
27218 	CONN_DEC_REF(connp);
27219 }
27220 
27221 /*
27222  * Martian Address Filtering [RFC 1812, Section 5.3.7]
27223  */
27224 static boolean_t
27225 ip_no_forward(ipha_t *ipha, ill_t *ill)
27226 {
27227 	ipaddr_t ip_src, ip_dst;
27228 	ire_t *src_ire = NULL;
27229 
27230 	ip_src = ntohl(ipha->ipha_src);
27231 	ip_dst = ntohl(ipha->ipha_dst);
27232 
27233 	if (ip_dst == INADDR_ANY)
27234 		goto dont_forward;
27235 
27236 	if (IN_CLASSD(ip_src))
27237 		goto dont_forward;
27238 
27239 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
27240 		goto dont_forward;
27241 
27242 	if (IN_BADCLASS(ip_dst))
27243 		goto dont_forward;
27244 
27245 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
27246 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
27247 	if (src_ire != NULL) {
27248 		ire_refrele(src_ire);
27249 		goto dont_forward;
27250 	}
27251 
27252 	return (B_FALSE);
27253 
27254 dont_forward:
27255 	if (ip_debug > 2) {
27256 		printf("ip_no_forward: dropping packet received on %s\n",
27257 		    ill->ill_name);
27258 		pr_addr_dbg("ip_no_forward: from src %s\n",
27259 		    AF_INET, &ipha->ipha_src);
27260 		pr_addr_dbg("ip_no_forward: to dst %s\n",
27261 		    AF_INET, &ipha->ipha_dst);
27262 	}
27263 	BUMP_MIB(&ip_mib, ipForwProhibits);
27264 	return (B_TRUE);
27265 }
27266 
27267 static boolean_t
27268 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
27269 {
27270 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
27271 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
27272 		if (ip_debug > 2) {
27273 			if (ill != NULL) {
27274 				printf("ip_loopback_src_or_dst: "
27275 				    "dropping packet received on %s\n",
27276 				    ill->ill_name);
27277 			} else {
27278 				printf("ip_loopback_src_or_dst: "
27279 				    "dropping packet\n");
27280 			}
27281 
27282 			pr_addr_dbg(
27283 			    "ip_loopback_src_or_dst: from src %s\n",
27284 			    AF_INET, &ipha->ipha_src);
27285 			pr_addr_dbg(
27286 			    "ip_loopback_src_or_dst: to dst %s\n",
27287 			    AF_INET, &ipha->ipha_dst);
27288 		}
27289 
27290 		BUMP_MIB(&ip_mib, ipInAddrErrors);
27291 		return (B_TRUE);
27292 	}
27293 	return (B_FALSE);
27294 }
27295 
27296 /*
27297  * Return B_TRUE if the buffers differ in length or content.
27298  * This is used for comparing extension header buffers.
27299  * Note that an extension header would be declared different
27300  * even if all that changed was the next header value in that header i.e.
27301  * what really changed is the next extension header.
27302  */
27303 boolean_t
27304 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
27305     uint_t blen)
27306 {
27307 	if (!b_valid)
27308 		blen = 0;
27309 
27310 	if (alen != blen)
27311 		return (B_TRUE);
27312 	if (alen == 0)
27313 		return (B_FALSE);	/* Both zero length */
27314 	return (bcmp(abuf, bbuf, alen));
27315 }
27316 
27317 /*
27318  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
27319  * Return B_FALSE if memory allocation fails - don't change any state!
27320  */
27321 boolean_t
27322 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27323     const void *src, uint_t srclen)
27324 {
27325 	void *dst;
27326 
27327 	if (!src_valid)
27328 		srclen = 0;
27329 
27330 	ASSERT(*dstlenp == 0);
27331 	if (src != NULL && srclen != 0) {
27332 		dst = mi_alloc(srclen, BPRI_MED);
27333 		if (dst == NULL)
27334 			return (B_FALSE);
27335 	} else {
27336 		dst = NULL;
27337 	}
27338 	if (*dstp != NULL)
27339 		mi_free(*dstp);
27340 	*dstp = dst;
27341 	*dstlenp = dst == NULL ? 0 : srclen;
27342 	return (B_TRUE);
27343 }
27344 
27345 /*
27346  * Replace what is in *dst, *dstlen with the source.
27347  * Assumes ip_allocbuf has already been called.
27348  */
27349 void
27350 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27351     const void *src, uint_t srclen)
27352 {
27353 	if (!src_valid)
27354 		srclen = 0;
27355 
27356 	ASSERT(*dstlenp == srclen);
27357 	if (src != NULL && srclen != 0)
27358 		bcopy(src, *dstp, srclen);
27359 }
27360 
27361 /*
27362  * Free the storage pointed to by the members of an ip6_pkt_t.
27363  */
27364 void
27365 ip6_pkt_free(ip6_pkt_t *ipp)
27366 {
27367 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
27368 
27369 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
27370 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
27371 		ipp->ipp_hopopts = NULL;
27372 		ipp->ipp_hopoptslen = 0;
27373 	}
27374 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
27375 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
27376 		ipp->ipp_rtdstopts = NULL;
27377 		ipp->ipp_rtdstoptslen = 0;
27378 	}
27379 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
27380 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
27381 		ipp->ipp_dstopts = NULL;
27382 		ipp->ipp_dstoptslen = 0;
27383 	}
27384 	if (ipp->ipp_fields & IPPF_RTHDR) {
27385 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
27386 		ipp->ipp_rthdr = NULL;
27387 		ipp->ipp_rthdrlen = 0;
27388 	}
27389 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
27390 	    IPPF_RTHDR);
27391 }
27392