xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision f808c858fa61e7769218966759510a8b1190dfcf)
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 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10094 				return (EPERM);
10095 			/* FALLTHRU */
10096 		case IP_MULTICAST_IF:
10097 		case IP_DONTFAILOVER_IF: {
10098 			ipaddr_t addr = *i1;
10099 
10100 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10101 			    first_mp);
10102 			if (error != 0)
10103 				return (error);
10104 			break;	/* goto sizeof (int) option return */
10105 		}
10106 
10107 		case IP_MULTICAST_TTL:
10108 			/* Recorded in transport above IP */
10109 			*outvalp = *invalp;
10110 			*outlenp = sizeof (uchar_t);
10111 			return (0);
10112 		case IP_MULTICAST_LOOP:
10113 			if (!checkonly) {
10114 				mutex_enter(&connp->conn_lock);
10115 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10116 				mutex_exit(&connp->conn_lock);
10117 			}
10118 			*outvalp = *invalp;
10119 			*outlenp = sizeof (uchar_t);
10120 			return (0);
10121 		case IP_ADD_MEMBERSHIP:
10122 		case MCAST_JOIN_GROUP:
10123 		case IP_DROP_MEMBERSHIP:
10124 		case MCAST_LEAVE_GROUP: {
10125 			struct ip_mreq *mreqp;
10126 			struct group_req *greqp;
10127 			ire_t *ire;
10128 			boolean_t done = B_FALSE;
10129 			ipaddr_t group, ifaddr;
10130 			struct sockaddr_in *sin;
10131 			uint32_t *ifindexp;
10132 			boolean_t mcast_opt = B_TRUE;
10133 			mcast_record_t fmode;
10134 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10135 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10136 
10137 			switch (name) {
10138 			case IP_ADD_MEMBERSHIP:
10139 				mcast_opt = B_FALSE;
10140 				/* FALLTHRU */
10141 			case MCAST_JOIN_GROUP:
10142 				fmode = MODE_IS_EXCLUDE;
10143 				optfn = ip_opt_add_group;
10144 				break;
10145 
10146 			case IP_DROP_MEMBERSHIP:
10147 				mcast_opt = B_FALSE;
10148 				/* FALLTHRU */
10149 			case MCAST_LEAVE_GROUP:
10150 				fmode = MODE_IS_INCLUDE;
10151 				optfn = ip_opt_delete_group;
10152 				break;
10153 			}
10154 
10155 			if (mcast_opt) {
10156 				greqp = (struct group_req *)i1;
10157 				sin = (struct sockaddr_in *)&greqp->gr_group;
10158 				if (sin->sin_family != AF_INET) {
10159 					*outlenp = 0;
10160 					return (ENOPROTOOPT);
10161 				}
10162 				group = (ipaddr_t)sin->sin_addr.s_addr;
10163 				ifaddr = INADDR_ANY;
10164 				ifindexp = &greqp->gr_interface;
10165 			} else {
10166 				mreqp = (struct ip_mreq *)i1;
10167 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10168 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10169 				ifindexp = NULL;
10170 			}
10171 
10172 			/*
10173 			 * In the multirouting case, we need to replicate
10174 			 * the request on all interfaces that will take part
10175 			 * in replication.  We do so because multirouting is
10176 			 * reflective, thus we will probably receive multi-
10177 			 * casts on those interfaces.
10178 			 * The ip_multirt_apply_membership() succeeds if the
10179 			 * operation succeeds on at least one interface.
10180 			 */
10181 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10182 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10183 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10184 			if (ire != NULL) {
10185 				if (ire->ire_flags & RTF_MULTIRT) {
10186 					error = ip_multirt_apply_membership(
10187 					    optfn, ire, connp, checkonly, group,
10188 					    fmode, INADDR_ANY, first_mp);
10189 					done = B_TRUE;
10190 				}
10191 				ire_refrele(ire);
10192 			}
10193 			if (!done) {
10194 				error = optfn(connp, checkonly, group, ifaddr,
10195 				    ifindexp, fmode, INADDR_ANY, first_mp);
10196 			}
10197 			if (error) {
10198 				/*
10199 				 * EINPROGRESS is a soft error, needs retry
10200 				 * so don't make *outlenp zero.
10201 				 */
10202 				if (error != EINPROGRESS)
10203 					*outlenp = 0;
10204 				return (error);
10205 			}
10206 			/* OK return - copy input buffer into output buffer */
10207 			if (invalp != outvalp) {
10208 				/* don't trust bcopy for identical src/dst */
10209 				bcopy(invalp, outvalp, inlen);
10210 			}
10211 			*outlenp = inlen;
10212 			return (0);
10213 		}
10214 		case IP_BLOCK_SOURCE:
10215 		case IP_UNBLOCK_SOURCE:
10216 		case IP_ADD_SOURCE_MEMBERSHIP:
10217 		case IP_DROP_SOURCE_MEMBERSHIP:
10218 		case MCAST_BLOCK_SOURCE:
10219 		case MCAST_UNBLOCK_SOURCE:
10220 		case MCAST_JOIN_SOURCE_GROUP:
10221 		case MCAST_LEAVE_SOURCE_GROUP: {
10222 			struct ip_mreq_source *imreqp;
10223 			struct group_source_req *gsreqp;
10224 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10225 			uint32_t ifindex = 0;
10226 			mcast_record_t fmode;
10227 			struct sockaddr_in *sin;
10228 			ire_t *ire;
10229 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10230 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10231 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10232 
10233 			switch (name) {
10234 			case IP_BLOCK_SOURCE:
10235 				mcast_opt = B_FALSE;
10236 				/* FALLTHRU */
10237 			case MCAST_BLOCK_SOURCE:
10238 				fmode = MODE_IS_EXCLUDE;
10239 				optfn = ip_opt_add_group;
10240 				break;
10241 
10242 			case IP_UNBLOCK_SOURCE:
10243 				mcast_opt = B_FALSE;
10244 				/* FALLTHRU */
10245 			case MCAST_UNBLOCK_SOURCE:
10246 				fmode = MODE_IS_EXCLUDE;
10247 				optfn = ip_opt_delete_group;
10248 				break;
10249 
10250 			case IP_ADD_SOURCE_MEMBERSHIP:
10251 				mcast_opt = B_FALSE;
10252 				/* FALLTHRU */
10253 			case MCAST_JOIN_SOURCE_GROUP:
10254 				fmode = MODE_IS_INCLUDE;
10255 				optfn = ip_opt_add_group;
10256 				break;
10257 
10258 			case IP_DROP_SOURCE_MEMBERSHIP:
10259 				mcast_opt = B_FALSE;
10260 				/* FALLTHRU */
10261 			case MCAST_LEAVE_SOURCE_GROUP:
10262 				fmode = MODE_IS_INCLUDE;
10263 				optfn = ip_opt_delete_group;
10264 				break;
10265 			}
10266 
10267 			if (mcast_opt) {
10268 				gsreqp = (struct group_source_req *)i1;
10269 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10270 					*outlenp = 0;
10271 					return (ENOPROTOOPT);
10272 				}
10273 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10274 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10275 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10276 				src = (ipaddr_t)sin->sin_addr.s_addr;
10277 				ifindex = gsreqp->gsr_interface;
10278 			} else {
10279 				imreqp = (struct ip_mreq_source *)i1;
10280 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10281 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10282 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10283 			}
10284 
10285 			/*
10286 			 * In the multirouting case, we need to replicate
10287 			 * the request as noted in the mcast cases above.
10288 			 */
10289 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10290 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10291 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10292 			if (ire != NULL) {
10293 				if (ire->ire_flags & RTF_MULTIRT) {
10294 					error = ip_multirt_apply_membership(
10295 					    optfn, ire, connp, checkonly, grp,
10296 					    fmode, src, first_mp);
10297 					done = B_TRUE;
10298 				}
10299 				ire_refrele(ire);
10300 			}
10301 			if (!done) {
10302 				error = optfn(connp, checkonly, grp, ifaddr,
10303 				    &ifindex, fmode, src, first_mp);
10304 			}
10305 			if (error != 0) {
10306 				/*
10307 				 * EINPROGRESS is a soft error, needs retry
10308 				 * so don't make *outlenp zero.
10309 				 */
10310 				if (error != EINPROGRESS)
10311 					*outlenp = 0;
10312 				return (error);
10313 			}
10314 			/* OK return - copy input buffer into output buffer */
10315 			if (invalp != outvalp) {
10316 				bcopy(invalp, outvalp, inlen);
10317 			}
10318 			*outlenp = inlen;
10319 			return (0);
10320 		}
10321 		case IP_SEC_OPT:
10322 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10323 			if (error != 0) {
10324 				*outlenp = 0;
10325 				return (error);
10326 			}
10327 			break;
10328 		case IP_HDRINCL:
10329 		case IP_OPTIONS:
10330 		case T_IP_OPTIONS:
10331 		case IP_TOS:
10332 		case T_IP_TOS:
10333 		case IP_TTL:
10334 		case IP_RECVDSTADDR:
10335 		case IP_RECVOPTS:
10336 			/* OK return - copy input buffer into output buffer */
10337 			if (invalp != outvalp) {
10338 				/* don't trust bcopy for identical src/dst */
10339 				bcopy(invalp, outvalp, inlen);
10340 			}
10341 			*outlenp = inlen;
10342 			return (0);
10343 		case IP_RECVIF:
10344 			/* Retrieve the inbound interface index */
10345 			if (!checkonly) {
10346 				mutex_enter(&connp->conn_lock);
10347 				connp->conn_recvif = *i1 ? 1 : 0;
10348 				mutex_exit(&connp->conn_lock);
10349 			}
10350 			break;	/* goto sizeof (int) option return */
10351 		case IP_RECVSLLA:
10352 			/* Retrieve the source link layer address */
10353 			if (!checkonly) {
10354 				mutex_enter(&connp->conn_lock);
10355 				connp->conn_recvslla = *i1 ? 1 : 0;
10356 				mutex_exit(&connp->conn_lock);
10357 			}
10358 			break;	/* goto sizeof (int) option return */
10359 		case MRT_INIT:
10360 		case MRT_DONE:
10361 		case MRT_ADD_VIF:
10362 		case MRT_DEL_VIF:
10363 		case MRT_ADD_MFC:
10364 		case MRT_DEL_MFC:
10365 		case MRT_ASSERT:
10366 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10367 				*outlenp = 0;
10368 				return (error);
10369 			}
10370 			error = ip_mrouter_set((int)name, q, checkonly,
10371 			    (uchar_t *)invalp, inlen, first_mp);
10372 			if (error) {
10373 				*outlenp = 0;
10374 				return (error);
10375 			}
10376 			/* OK return - copy input buffer into output buffer */
10377 			if (invalp != outvalp) {
10378 				/* don't trust bcopy for identical src/dst */
10379 				bcopy(invalp, outvalp, inlen);
10380 			}
10381 			*outlenp = inlen;
10382 			return (0);
10383 		case IP_BOUND_IF:
10384 		case IP_XMIT_IF:
10385 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10386 			    level, name, first_mp);
10387 			if (error != 0)
10388 				return (error);
10389 			break; 		/* goto sizeof (int) option return */
10390 
10391 		case IP_UNSPEC_SRC:
10392 			/* Allow sending with a zero source address */
10393 			if (!checkonly) {
10394 				mutex_enter(&connp->conn_lock);
10395 				connp->conn_unspec_src = *i1 ? 1 : 0;
10396 				mutex_exit(&connp->conn_lock);
10397 			}
10398 			break;	/* goto sizeof (int) option return */
10399 		default:
10400 			/*
10401 			 * "soft" error (negative)
10402 			 * option not handled at this level
10403 			 * Note: Do not modify *outlenp
10404 			 */
10405 			return (-EINVAL);
10406 		}
10407 		break;
10408 	case IPPROTO_IPV6:
10409 		switch (name) {
10410 		case IPV6_BOUND_IF:
10411 		case IPV6_BOUND_PIF:
10412 		case IPV6_DONTFAILOVER_IF:
10413 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10414 			    level, name, first_mp);
10415 			if (error != 0)
10416 				return (error);
10417 			break; 		/* goto sizeof (int) option return */
10418 
10419 		case IPV6_MULTICAST_IF:
10420 			/*
10421 			 * The only possible errors are EINPROGRESS and
10422 			 * EINVAL. EINPROGRESS will be restarted and is not
10423 			 * a hard error. We call this option on both V4 and V6
10424 			 * If both return EINVAL, then this call returns
10425 			 * EINVAL. If at least one of them succeeds we
10426 			 * return success.
10427 			 */
10428 			found = B_FALSE;
10429 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10430 			    level, name, first_mp);
10431 			if (error == EINPROGRESS)
10432 				return (error);
10433 			if (error == 0)
10434 				found = B_TRUE;
10435 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10436 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10437 			if (error == 0)
10438 				found = B_TRUE;
10439 			if (!found)
10440 				return (error);
10441 			break; 		/* goto sizeof (int) option return */
10442 
10443 		case IPV6_MULTICAST_HOPS:
10444 			/* Recorded in transport above IP */
10445 			break;	/* goto sizeof (int) option return */
10446 		case IPV6_MULTICAST_LOOP:
10447 			if (!checkonly) {
10448 				mutex_enter(&connp->conn_lock);
10449 				connp->conn_multicast_loop = *i1;
10450 				mutex_exit(&connp->conn_lock);
10451 			}
10452 			break;	/* goto sizeof (int) option return */
10453 		case IPV6_JOIN_GROUP:
10454 		case MCAST_JOIN_GROUP:
10455 		case IPV6_LEAVE_GROUP:
10456 		case MCAST_LEAVE_GROUP: {
10457 			struct ipv6_mreq *ip_mreqp;
10458 			struct group_req *greqp;
10459 			ire_t *ire;
10460 			boolean_t done = B_FALSE;
10461 			in6_addr_t groupv6;
10462 			uint32_t ifindex;
10463 			boolean_t mcast_opt = B_TRUE;
10464 			mcast_record_t fmode;
10465 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10466 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10467 
10468 			switch (name) {
10469 			case IPV6_JOIN_GROUP:
10470 				mcast_opt = B_FALSE;
10471 				/* FALLTHRU */
10472 			case MCAST_JOIN_GROUP:
10473 				fmode = MODE_IS_EXCLUDE;
10474 				optfn = ip_opt_add_group_v6;
10475 				break;
10476 
10477 			case IPV6_LEAVE_GROUP:
10478 				mcast_opt = B_FALSE;
10479 				/* FALLTHRU */
10480 			case MCAST_LEAVE_GROUP:
10481 				fmode = MODE_IS_INCLUDE;
10482 				optfn = ip_opt_delete_group_v6;
10483 				break;
10484 			}
10485 
10486 			if (mcast_opt) {
10487 				struct sockaddr_in *sin;
10488 				struct sockaddr_in6 *sin6;
10489 				greqp = (struct group_req *)i1;
10490 				if (greqp->gr_group.ss_family == AF_INET) {
10491 					sin = (struct sockaddr_in *)
10492 					    &(greqp->gr_group);
10493 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10494 					    &groupv6);
10495 				} else {
10496 					sin6 = (struct sockaddr_in6 *)
10497 					    &(greqp->gr_group);
10498 					groupv6 = sin6->sin6_addr;
10499 				}
10500 				ifindex = greqp->gr_interface;
10501 			} else {
10502 				ip_mreqp = (struct ipv6_mreq *)i1;
10503 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10504 				ifindex = ip_mreqp->ipv6mr_interface;
10505 			}
10506 			/*
10507 			 * In the multirouting case, we need to replicate
10508 			 * the request on all interfaces that will take part
10509 			 * in replication.  We do so because multirouting is
10510 			 * reflective, thus we will probably receive multi-
10511 			 * casts on those interfaces.
10512 			 * The ip_multirt_apply_membership_v6() succeeds if
10513 			 * the operation succeeds on at least one interface.
10514 			 */
10515 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10516 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10517 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10518 			if (ire != NULL) {
10519 				if (ire->ire_flags & RTF_MULTIRT) {
10520 					error = ip_multirt_apply_membership_v6(
10521 					    optfn, ire, connp, checkonly,
10522 					    &groupv6, fmode, &ipv6_all_zeros,
10523 					    first_mp);
10524 					done = B_TRUE;
10525 				}
10526 				ire_refrele(ire);
10527 			}
10528 			if (!done) {
10529 				error = optfn(connp, checkonly, &groupv6,
10530 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10531 			}
10532 			if (error) {
10533 				/*
10534 				 * EINPROGRESS is a soft error, needs retry
10535 				 * so don't make *outlenp zero.
10536 				 */
10537 				if (error != EINPROGRESS)
10538 					*outlenp = 0;
10539 				return (error);
10540 			}
10541 			/* OK return - copy input buffer into output buffer */
10542 			if (invalp != outvalp) {
10543 				/* don't trust bcopy for identical src/dst */
10544 				bcopy(invalp, outvalp, inlen);
10545 			}
10546 			*outlenp = inlen;
10547 			return (0);
10548 		}
10549 		case MCAST_BLOCK_SOURCE:
10550 		case MCAST_UNBLOCK_SOURCE:
10551 		case MCAST_JOIN_SOURCE_GROUP:
10552 		case MCAST_LEAVE_SOURCE_GROUP: {
10553 			struct group_source_req *gsreqp;
10554 			in6_addr_t v6grp, v6src;
10555 			uint32_t ifindex;
10556 			mcast_record_t fmode;
10557 			ire_t *ire;
10558 			boolean_t done = B_FALSE;
10559 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10560 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10561 
10562 			switch (name) {
10563 			case MCAST_BLOCK_SOURCE:
10564 				fmode = MODE_IS_EXCLUDE;
10565 				optfn = ip_opt_add_group_v6;
10566 				break;
10567 			case MCAST_UNBLOCK_SOURCE:
10568 				fmode = MODE_IS_EXCLUDE;
10569 				optfn = ip_opt_delete_group_v6;
10570 				break;
10571 			case MCAST_JOIN_SOURCE_GROUP:
10572 				fmode = MODE_IS_INCLUDE;
10573 				optfn = ip_opt_add_group_v6;
10574 				break;
10575 			case MCAST_LEAVE_SOURCE_GROUP:
10576 				fmode = MODE_IS_INCLUDE;
10577 				optfn = ip_opt_delete_group_v6;
10578 				break;
10579 			}
10580 
10581 			gsreqp = (struct group_source_req *)i1;
10582 			ifindex = gsreqp->gsr_interface;
10583 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10584 				struct sockaddr_in *s;
10585 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10586 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10587 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10588 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10589 			} else {
10590 				struct sockaddr_in6 *s6;
10591 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10592 				v6grp = s6->sin6_addr;
10593 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10594 				v6src = s6->sin6_addr;
10595 			}
10596 
10597 			/*
10598 			 * In the multirouting case, we need to replicate
10599 			 * the request as noted in the mcast cases above.
10600 			 */
10601 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10602 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10603 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10604 			if (ire != NULL) {
10605 				if (ire->ire_flags & RTF_MULTIRT) {
10606 					error = ip_multirt_apply_membership_v6(
10607 					    optfn, ire, connp, checkonly,
10608 					    &v6grp, fmode, &v6src, first_mp);
10609 					done = B_TRUE;
10610 				}
10611 				ire_refrele(ire);
10612 			}
10613 			if (!done) {
10614 				error = optfn(connp, checkonly, &v6grp,
10615 				    ifindex, fmode, &v6src, first_mp);
10616 			}
10617 			if (error != 0) {
10618 				/*
10619 				 * EINPROGRESS is a soft error, needs retry
10620 				 * so don't make *outlenp zero.
10621 				 */
10622 				if (error != EINPROGRESS)
10623 					*outlenp = 0;
10624 				return (error);
10625 			}
10626 			/* OK return - copy input buffer into output buffer */
10627 			if (invalp != outvalp) {
10628 				bcopy(invalp, outvalp, inlen);
10629 			}
10630 			*outlenp = inlen;
10631 			return (0);
10632 		}
10633 		case IPV6_UNICAST_HOPS:
10634 			/* Recorded in transport above IP */
10635 			break;	/* goto sizeof (int) option return */
10636 		case IPV6_UNSPEC_SRC:
10637 			/* Allow sending with a zero source address */
10638 			if (!checkonly) {
10639 				mutex_enter(&connp->conn_lock);
10640 				connp->conn_unspec_src = *i1 ? 1 : 0;
10641 				mutex_exit(&connp->conn_lock);
10642 			}
10643 			break;	/* goto sizeof (int) option return */
10644 		case IPV6_RECVPKTINFO:
10645 			if (!checkonly) {
10646 				mutex_enter(&connp->conn_lock);
10647 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10648 				mutex_exit(&connp->conn_lock);
10649 			}
10650 			break;	/* goto sizeof (int) option return */
10651 		case IPV6_RECVTCLASS:
10652 			if (!checkonly) {
10653 				if (*i1 < 0 || *i1 > 1) {
10654 					return (EINVAL);
10655 				}
10656 				mutex_enter(&connp->conn_lock);
10657 				connp->conn_ipv6_recvtclass = *i1;
10658 				mutex_exit(&connp->conn_lock);
10659 			}
10660 			break;
10661 		case IPV6_RECVPATHMTU:
10662 			if (!checkonly) {
10663 				if (*i1 < 0 || *i1 > 1) {
10664 					return (EINVAL);
10665 				}
10666 				mutex_enter(&connp->conn_lock);
10667 				connp->conn_ipv6_recvpathmtu = *i1;
10668 				mutex_exit(&connp->conn_lock);
10669 			}
10670 			break;
10671 		case IPV6_RECVHOPLIMIT:
10672 			if (!checkonly) {
10673 				mutex_enter(&connp->conn_lock);
10674 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10675 				mutex_exit(&connp->conn_lock);
10676 			}
10677 			break;	/* goto sizeof (int) option return */
10678 		case IPV6_RECVHOPOPTS:
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			break;	/* goto sizeof (int) option return */
10685 		case IPV6_RECVDSTOPTS:
10686 			if (!checkonly) {
10687 				mutex_enter(&connp->conn_lock);
10688 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10689 				mutex_exit(&connp->conn_lock);
10690 			}
10691 			break;	/* goto sizeof (int) option return */
10692 		case IPV6_RECVRTHDR:
10693 			if (!checkonly) {
10694 				mutex_enter(&connp->conn_lock);
10695 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10696 				mutex_exit(&connp->conn_lock);
10697 			}
10698 			break;	/* goto sizeof (int) option return */
10699 		case IPV6_RECVRTHDRDSTOPTS:
10700 			if (!checkonly) {
10701 				mutex_enter(&connp->conn_lock);
10702 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10703 				mutex_exit(&connp->conn_lock);
10704 			}
10705 			break;	/* goto sizeof (int) option return */
10706 		case IPV6_PKTINFO:
10707 			if (inlen == 0)
10708 				return (-EINVAL);	/* clearing option */
10709 			error = ip6_set_pktinfo(cr, connp,
10710 			    (struct in6_pktinfo *)invalp, first_mp);
10711 			if (error != 0)
10712 				*outlenp = 0;
10713 			else
10714 				*outlenp = inlen;
10715 			return (error);
10716 		case IPV6_NEXTHOP: {
10717 			struct sockaddr_in6 *sin6;
10718 
10719 			/* Verify that the nexthop is reachable */
10720 			if (inlen == 0)
10721 				return (-EINVAL);	/* clearing option */
10722 
10723 			sin6 = (struct sockaddr_in6 *)invalp;
10724 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10725 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10726 			    NULL, MATCH_IRE_DEFAULT);
10727 
10728 			if (ire == NULL) {
10729 				*outlenp = 0;
10730 				return (EHOSTUNREACH);
10731 			}
10732 			ire_refrele(ire);
10733 			return (-EINVAL);
10734 		}
10735 		case IPV6_SEC_OPT:
10736 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10737 			if (error != 0) {
10738 				*outlenp = 0;
10739 				return (error);
10740 			}
10741 			break;
10742 		case IPV6_SRC_PREFERENCES: {
10743 			/*
10744 			 * This is implemented strictly in the ip module
10745 			 * (here and in tcp_opt_*() to accomodate tcp
10746 			 * sockets).  Modules above ip pass this option
10747 			 * down here since ip is the only one that needs to
10748 			 * be aware of source address preferences.
10749 			 *
10750 			 * This socket option only affects connected
10751 			 * sockets that haven't already bound to a specific
10752 			 * IPv6 address.  In other words, sockets that
10753 			 * don't call bind() with an address other than the
10754 			 * unspecified address and that call connect().
10755 			 * ip_bind_connected_v6() passes these preferences
10756 			 * to the ipif_select_source_v6() function.
10757 			 */
10758 			if (inlen != sizeof (uint32_t))
10759 				return (EINVAL);
10760 			error = ip6_set_src_preferences(connp,
10761 			    *(uint32_t *)invalp);
10762 			if (error != 0) {
10763 				*outlenp = 0;
10764 				return (error);
10765 			} else {
10766 				*outlenp = sizeof (uint32_t);
10767 			}
10768 			break;
10769 		}
10770 		case IPV6_V6ONLY:
10771 			if (*i1 < 0 || *i1 > 1) {
10772 				return (EINVAL);
10773 			}
10774 			mutex_enter(&connp->conn_lock);
10775 			connp->conn_ipv6_v6only = *i1;
10776 			mutex_exit(&connp->conn_lock);
10777 			break;
10778 		default:
10779 			return (-EINVAL);
10780 		}
10781 		break;
10782 	default:
10783 		/*
10784 		 * "soft" error (negative)
10785 		 * option not handled at this level
10786 		 * Note: Do not modify *outlenp
10787 		 */
10788 		return (-EINVAL);
10789 	}
10790 	/*
10791 	 * Common case of return from an option that is sizeof (int)
10792 	 */
10793 	*(int *)outvalp = *i1;
10794 	*outlenp = sizeof (int);
10795 	return (0);
10796 }
10797 
10798 /*
10799  * This routine gets default values of certain options whose default
10800  * values are maintained by protocol specific code
10801  */
10802 /* ARGSUSED */
10803 int
10804 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10805 {
10806 	int *i1 = (int *)ptr;
10807 
10808 	switch (level) {
10809 	case IPPROTO_IP:
10810 		switch (name) {
10811 		case IP_MULTICAST_TTL:
10812 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10813 			return (sizeof (uchar_t));
10814 		case IP_MULTICAST_LOOP:
10815 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10816 			return (sizeof (uchar_t));
10817 		default:
10818 			return (-1);
10819 		}
10820 	case IPPROTO_IPV6:
10821 		switch (name) {
10822 		case IPV6_UNICAST_HOPS:
10823 			*i1 = ipv6_def_hops;
10824 			return (sizeof (int));
10825 		case IPV6_MULTICAST_HOPS:
10826 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10827 			return (sizeof (int));
10828 		case IPV6_MULTICAST_LOOP:
10829 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10830 			return (sizeof (int));
10831 		case IPV6_V6ONLY:
10832 			*i1 = 1;
10833 			return (sizeof (int));
10834 		default:
10835 			return (-1);
10836 		}
10837 	default:
10838 		return (-1);
10839 	}
10840 	/* NOTREACHED */
10841 }
10842 
10843 /*
10844  * Given a destination address and a pointer to where to put the information
10845  * this routine fills in the mtuinfo.
10846  */
10847 int
10848 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10849     struct ip6_mtuinfo *mtuinfo)
10850 {
10851 	ire_t *ire;
10852 
10853 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10854 		return (-1);
10855 
10856 	bzero(mtuinfo, sizeof (*mtuinfo));
10857 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10858 	mtuinfo->ip6m_addr.sin6_port = port;
10859 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10860 
10861 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
10862 	if (ire != NULL) {
10863 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10864 		ire_refrele(ire);
10865 	} else {
10866 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10867 	}
10868 	return (sizeof (struct ip6_mtuinfo));
10869 }
10870 
10871 /*
10872  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10873  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10874  * isn't.  This doesn't matter as the error checking is done properly for the
10875  * other MRT options coming in through ip_opt_set.
10876  */
10877 int
10878 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10879 {
10880 	conn_t		*connp = Q_TO_CONN(q);
10881 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10882 
10883 	switch (level) {
10884 	case IPPROTO_IP:
10885 		switch (name) {
10886 		case MRT_VERSION:
10887 		case MRT_ASSERT:
10888 			(void) ip_mrouter_get(name, q, ptr);
10889 			return (sizeof (int));
10890 		case IP_SEC_OPT:
10891 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10892 		case IP_NEXTHOP:
10893 			if (connp->conn_nexthop_set) {
10894 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10895 				return (sizeof (ipaddr_t));
10896 			} else
10897 				return (0);
10898 		default:
10899 			break;
10900 		}
10901 		break;
10902 	case IPPROTO_IPV6:
10903 		switch (name) {
10904 		case IPV6_SEC_OPT:
10905 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10906 		case IPV6_SRC_PREFERENCES: {
10907 			return (ip6_get_src_preferences(connp,
10908 			    (uint32_t *)ptr));
10909 		}
10910 		case IPV6_V6ONLY:
10911 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10912 			return (sizeof (int));
10913 		case IPV6_PATHMTU:
10914 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10915 				(struct ip6_mtuinfo *)ptr));
10916 		default:
10917 			break;
10918 		}
10919 		break;
10920 	default:
10921 		break;
10922 	}
10923 	return (-1);
10924 }
10925 
10926 /* Named Dispatch routine to get a current value out of our parameter table. */
10927 /* ARGSUSED */
10928 static int
10929 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10930 {
10931 	ipparam_t *ippa = (ipparam_t *)cp;
10932 
10933 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10934 	return (0);
10935 }
10936 
10937 /* ARGSUSED */
10938 static int
10939 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10940 {
10941 
10942 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10943 	return (0);
10944 }
10945 
10946 /*
10947  * Set ip{,6}_forwarding values.  This means walking through all of the
10948  * ill's and toggling their forwarding values.
10949  */
10950 /* ARGSUSED */
10951 static int
10952 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10953 {
10954 	long new_value;
10955 	int *forwarding_value = (int *)cp;
10956 	ill_t *walker;
10957 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10958 	ill_walk_context_t ctx;
10959 
10960 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10961 	    new_value < 0 || new_value > 1) {
10962 		return (EINVAL);
10963 	}
10964 
10965 	*forwarding_value = new_value;
10966 
10967 	/*
10968 	 * Regardless of the current value of ip_forwarding, set all per-ill
10969 	 * values of ip_forwarding to the value being set.
10970 	 *
10971 	 * Bring all the ill's up to date with the new global value.
10972 	 */
10973 	rw_enter(&ill_g_lock, RW_READER);
10974 
10975 	if (isv6)
10976 		walker = ILL_START_WALK_V6(&ctx);
10977 	else
10978 		walker = ILL_START_WALK_V4(&ctx);
10979 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10980 		(void) ill_forward_set(q, mp, (new_value != 0),
10981 		    (caddr_t)walker);
10982 	}
10983 	rw_exit(&ill_g_lock);
10984 
10985 	return (0);
10986 }
10987 
10988 /*
10989  * Walk through the param array specified registering each element with the
10990  * Named Dispatch handler. This is called only during init. So it is ok
10991  * not to acquire any locks
10992  */
10993 static boolean_t
10994 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
10995     ipndp_t *ipnd, size_t ipnd_cnt)
10996 {
10997 	for (; ippa_cnt-- > 0; ippa++) {
10998 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
10999 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11000 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11001 				nd_free(&ip_g_nd);
11002 				return (B_FALSE);
11003 			}
11004 		}
11005 	}
11006 
11007 	for (; ipnd_cnt-- > 0; ipnd++) {
11008 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11009 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11010 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11011 			    ipnd->ip_ndp_data)) {
11012 				nd_free(&ip_g_nd);
11013 				return (B_FALSE);
11014 			}
11015 		}
11016 	}
11017 
11018 	return (B_TRUE);
11019 }
11020 
11021 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11022 /* ARGSUSED */
11023 static int
11024 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11025 {
11026 	long		new_value;
11027 	ipparam_t	*ippa = (ipparam_t *)cp;
11028 
11029 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11030 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11031 		return (EINVAL);
11032 	}
11033 	ippa->ip_param_value = new_value;
11034 	return (0);
11035 }
11036 
11037 /*
11038  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11039  * When an ipf is passed here for the first time, if
11040  * we already have in-order fragments on the queue, we convert from the fast-
11041  * path reassembly scheme to the hard-case scheme.  From then on, additional
11042  * fragments are reassembled here.  We keep track of the start and end offsets
11043  * of each piece, and the number of holes in the chain.  When the hole count
11044  * goes to zero, we are done!
11045  *
11046  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11047  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11048  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11049  * after the call to ip_reassemble().
11050  */
11051 int
11052 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11053     size_t msg_len)
11054 {
11055 	uint_t	end;
11056 	mblk_t	*next_mp;
11057 	mblk_t	*mp1;
11058 	uint_t	offset;
11059 	boolean_t incr_dups = B_TRUE;
11060 	boolean_t offset_zero_seen = B_FALSE;
11061 	boolean_t pkt_boundary_checked = B_FALSE;
11062 
11063 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11064 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11065 
11066 	/* Add in byte count */
11067 	ipf->ipf_count += msg_len;
11068 	if (ipf->ipf_end) {
11069 		/*
11070 		 * We were part way through in-order reassembly, but now there
11071 		 * is a hole.  We walk through messages already queued, and
11072 		 * mark them for hard case reassembly.  We know that up till
11073 		 * now they were in order starting from offset zero.
11074 		 */
11075 		offset = 0;
11076 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11077 			IP_REASS_SET_START(mp1, offset);
11078 			if (offset == 0) {
11079 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11080 				offset = -ipf->ipf_nf_hdr_len;
11081 			}
11082 			offset += mp1->b_wptr - mp1->b_rptr;
11083 			IP_REASS_SET_END(mp1, offset);
11084 		}
11085 		/* One hole at the end. */
11086 		ipf->ipf_hole_cnt = 1;
11087 		/* Brand it as a hard case, forever. */
11088 		ipf->ipf_end = 0;
11089 	}
11090 	/* Walk through all the new pieces. */
11091 	do {
11092 		end = start + (mp->b_wptr - mp->b_rptr);
11093 		/*
11094 		 * If start is 0, decrease 'end' only for the first mblk of
11095 		 * the fragment. Otherwise 'end' can get wrong value in the
11096 		 * second pass of the loop if first mblk is exactly the
11097 		 * size of ipf_nf_hdr_len.
11098 		 */
11099 		if (start == 0 && !offset_zero_seen) {
11100 			/* First segment */
11101 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11102 			end -= ipf->ipf_nf_hdr_len;
11103 			offset_zero_seen = B_TRUE;
11104 		}
11105 		next_mp = mp->b_cont;
11106 		/*
11107 		 * We are checking to see if there is any interesing data
11108 		 * to process.  If there isn't and the mblk isn't the
11109 		 * one which carries the unfragmentable header then we
11110 		 * drop it.  It's possible to have just the unfragmentable
11111 		 * header come through without any data.  That needs to be
11112 		 * saved.
11113 		 *
11114 		 * If the assert at the top of this function holds then the
11115 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11116 		 * is infrequently traveled enough that the test is left in
11117 		 * to protect against future code changes which break that
11118 		 * invariant.
11119 		 */
11120 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11121 			/* Empty.  Blast it. */
11122 			IP_REASS_SET_START(mp, 0);
11123 			IP_REASS_SET_END(mp, 0);
11124 			/*
11125 			 * If the ipf points to the mblk we are about to free,
11126 			 * update ipf to point to the next mblk (or NULL
11127 			 * if none).
11128 			 */
11129 			if (ipf->ipf_mp->b_cont == mp)
11130 				ipf->ipf_mp->b_cont = next_mp;
11131 			freeb(mp);
11132 			continue;
11133 		}
11134 		mp->b_cont = NULL;
11135 		IP_REASS_SET_START(mp, start);
11136 		IP_REASS_SET_END(mp, end);
11137 		if (!ipf->ipf_tail_mp) {
11138 			ipf->ipf_tail_mp = mp;
11139 			ipf->ipf_mp->b_cont = mp;
11140 			if (start == 0 || !more) {
11141 				ipf->ipf_hole_cnt = 1;
11142 				/*
11143 				 * if the first fragment comes in more than one
11144 				 * mblk, this loop will be executed for each
11145 				 * mblk. Need to adjust hole count so exiting
11146 				 * this routine will leave hole count at 1.
11147 				 */
11148 				if (next_mp)
11149 					ipf->ipf_hole_cnt++;
11150 			} else
11151 				ipf->ipf_hole_cnt = 2;
11152 			continue;
11153 		} else if (ipf->ipf_last_frag_seen && !more &&
11154 			    !pkt_boundary_checked) {
11155 			/*
11156 			 * We check datagram boundary only if this fragment
11157 			 * claims to be the last fragment and we have seen a
11158 			 * last fragment in the past too. We do this only
11159 			 * once for a given fragment.
11160 			 *
11161 			 * start cannot be 0 here as fragments with start=0
11162 			 * and MF=0 gets handled as a complete packet. These
11163 			 * fragments should not reach here.
11164 			 */
11165 
11166 			if (start + msgdsize(mp) !=
11167 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11168 				/*
11169 				 * We have two fragments both of which claim
11170 				 * to be the last fragment but gives conflicting
11171 				 * information about the whole datagram size.
11172 				 * Something fishy is going on. Drop the
11173 				 * fragment and free up the reassembly list.
11174 				 */
11175 				return (IP_REASS_FAILED);
11176 			}
11177 
11178 			/*
11179 			 * We shouldn't come to this code block again for this
11180 			 * particular fragment.
11181 			 */
11182 			pkt_boundary_checked = B_TRUE;
11183 		}
11184 
11185 		/* New stuff at or beyond tail? */
11186 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11187 		if (start >= offset) {
11188 			if (ipf->ipf_last_frag_seen) {
11189 				/* current fragment is beyond last fragment */
11190 				return (IP_REASS_FAILED);
11191 			}
11192 			/* Link it on end. */
11193 			ipf->ipf_tail_mp->b_cont = mp;
11194 			ipf->ipf_tail_mp = mp;
11195 			if (more) {
11196 				if (start != offset)
11197 					ipf->ipf_hole_cnt++;
11198 			} else if (start == offset && next_mp == NULL)
11199 					ipf->ipf_hole_cnt--;
11200 			continue;
11201 		}
11202 		mp1 = ipf->ipf_mp->b_cont;
11203 		offset = IP_REASS_START(mp1);
11204 		/* New stuff at the front? */
11205 		if (start < offset) {
11206 			if (start == 0) {
11207 				if (end >= offset) {
11208 					/* Nailed the hole at the begining. */
11209 					ipf->ipf_hole_cnt--;
11210 				}
11211 			} else if (end < offset) {
11212 				/*
11213 				 * A hole, stuff, and a hole where there used
11214 				 * to be just a hole.
11215 				 */
11216 				ipf->ipf_hole_cnt++;
11217 			}
11218 			mp->b_cont = mp1;
11219 			/* Check for overlap. */
11220 			while (end > offset) {
11221 				if (end < IP_REASS_END(mp1)) {
11222 					mp->b_wptr -= end - offset;
11223 					IP_REASS_SET_END(mp, offset);
11224 					if (ill->ill_isv6) {
11225 						BUMP_MIB(ill->ill_ip6_mib,
11226 						    ipv6ReasmPartDups);
11227 					} else {
11228 						BUMP_MIB(&ip_mib,
11229 						    ipReasmPartDups);
11230 					}
11231 					break;
11232 				}
11233 				/* Did we cover another hole? */
11234 				if ((mp1->b_cont &&
11235 				    IP_REASS_END(mp1) !=
11236 				    IP_REASS_START(mp1->b_cont) &&
11237 				    end >= IP_REASS_START(mp1->b_cont)) ||
11238 				    (!ipf->ipf_last_frag_seen && !more)) {
11239 					ipf->ipf_hole_cnt--;
11240 				}
11241 				/* Clip out mp1. */
11242 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11243 					/*
11244 					 * After clipping out mp1, this guy
11245 					 * is now hanging off the end.
11246 					 */
11247 					ipf->ipf_tail_mp = mp;
11248 				}
11249 				IP_REASS_SET_START(mp1, 0);
11250 				IP_REASS_SET_END(mp1, 0);
11251 				/* Subtract byte count */
11252 				ipf->ipf_count -= mp1->b_datap->db_lim -
11253 				    mp1->b_datap->db_base;
11254 				freeb(mp1);
11255 				if (ill->ill_isv6) {
11256 					BUMP_MIB(ill->ill_ip6_mib,
11257 					    ipv6ReasmPartDups);
11258 				} else {
11259 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11260 				}
11261 				mp1 = mp->b_cont;
11262 				if (!mp1)
11263 					break;
11264 				offset = IP_REASS_START(mp1);
11265 			}
11266 			ipf->ipf_mp->b_cont = mp;
11267 			continue;
11268 		}
11269 		/*
11270 		 * The new piece starts somewhere between the start of the head
11271 		 * and before the end of the tail.
11272 		 */
11273 		for (; mp1; mp1 = mp1->b_cont) {
11274 			offset = IP_REASS_END(mp1);
11275 			if (start < offset) {
11276 				if (end <= offset) {
11277 					/* Nothing new. */
11278 					IP_REASS_SET_START(mp, 0);
11279 					IP_REASS_SET_END(mp, 0);
11280 					/* Subtract byte count */
11281 					ipf->ipf_count -= mp->b_datap->db_lim -
11282 					    mp->b_datap->db_base;
11283 					if (incr_dups) {
11284 						ipf->ipf_num_dups++;
11285 						incr_dups = B_FALSE;
11286 					}
11287 					freeb(mp);
11288 					if (ill->ill_isv6) {
11289 						BUMP_MIB(ill->ill_ip6_mib,
11290 						    ipv6ReasmDuplicates);
11291 					} else {
11292 						BUMP_MIB(&ip_mib,
11293 						    ipReasmDuplicates);
11294 					}
11295 					break;
11296 				}
11297 				/*
11298 				 * Trim redundant stuff off beginning of new
11299 				 * piece.
11300 				 */
11301 				IP_REASS_SET_START(mp, offset);
11302 				mp->b_rptr += offset - start;
11303 				if (ill->ill_isv6) {
11304 					BUMP_MIB(ill->ill_ip6_mib,
11305 					    ipv6ReasmPartDups);
11306 				} else {
11307 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11308 				}
11309 				start = offset;
11310 				if (!mp1->b_cont) {
11311 					/*
11312 					 * After trimming, this guy is now
11313 					 * hanging off the end.
11314 					 */
11315 					mp1->b_cont = mp;
11316 					ipf->ipf_tail_mp = mp;
11317 					if (!more) {
11318 						ipf->ipf_hole_cnt--;
11319 					}
11320 					break;
11321 				}
11322 			}
11323 			if (start >= IP_REASS_START(mp1->b_cont))
11324 				continue;
11325 			/* Fill a hole */
11326 			if (start > offset)
11327 				ipf->ipf_hole_cnt++;
11328 			mp->b_cont = mp1->b_cont;
11329 			mp1->b_cont = mp;
11330 			mp1 = mp->b_cont;
11331 			offset = IP_REASS_START(mp1);
11332 			if (end >= offset) {
11333 				ipf->ipf_hole_cnt--;
11334 				/* Check for overlap. */
11335 				while (end > offset) {
11336 					if (end < IP_REASS_END(mp1)) {
11337 						mp->b_wptr -= end - offset;
11338 						IP_REASS_SET_END(mp, offset);
11339 						/*
11340 						 * TODO we might bump
11341 						 * this up twice if there is
11342 						 * overlap at both ends.
11343 						 */
11344 						if (ill->ill_isv6) {
11345 							BUMP_MIB(
11346 							    ill->ill_ip6_mib,
11347 							    ipv6ReasmPartDups);
11348 						} else {
11349 							BUMP_MIB(&ip_mib,
11350 							    ipReasmPartDups);
11351 						}
11352 						break;
11353 					}
11354 					/* Did we cover another hole? */
11355 					if ((mp1->b_cont &&
11356 					    IP_REASS_END(mp1)
11357 					    != IP_REASS_START(mp1->b_cont) &&
11358 					    end >=
11359 					    IP_REASS_START(mp1->b_cont)) ||
11360 					    (!ipf->ipf_last_frag_seen &&
11361 					    !more)) {
11362 						ipf->ipf_hole_cnt--;
11363 					}
11364 					/* Clip out mp1. */
11365 					if ((mp->b_cont = mp1->b_cont) ==
11366 					    NULL) {
11367 						/*
11368 						 * After clipping out mp1,
11369 						 * this guy is now hanging
11370 						 * off the end.
11371 						 */
11372 						ipf->ipf_tail_mp = mp;
11373 					}
11374 					IP_REASS_SET_START(mp1, 0);
11375 					IP_REASS_SET_END(mp1, 0);
11376 					/* Subtract byte count */
11377 					ipf->ipf_count -=
11378 					    mp1->b_datap->db_lim -
11379 					    mp1->b_datap->db_base;
11380 					freeb(mp1);
11381 					if (ill->ill_isv6) {
11382 						BUMP_MIB(ill->ill_ip6_mib,
11383 						    ipv6ReasmPartDups);
11384 					} else {
11385 						BUMP_MIB(&ip_mib,
11386 						    ipReasmPartDups);
11387 					}
11388 					mp1 = mp->b_cont;
11389 					if (!mp1)
11390 						break;
11391 					offset = IP_REASS_START(mp1);
11392 				}
11393 			}
11394 			break;
11395 		}
11396 	} while (start = end, mp = next_mp);
11397 
11398 	/* Fragment just processed could be the last one. Remember this fact */
11399 	if (!more)
11400 		ipf->ipf_last_frag_seen = B_TRUE;
11401 
11402 	/* Still got holes? */
11403 	if (ipf->ipf_hole_cnt)
11404 		return (IP_REASS_PARTIAL);
11405 	/* Clean up overloaded fields to avoid upstream disasters. */
11406 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11407 		IP_REASS_SET_START(mp1, 0);
11408 		IP_REASS_SET_END(mp1, 0);
11409 	}
11410 	return (IP_REASS_COMPLETE);
11411 }
11412 
11413 /*
11414  * ipsec processing for the fast path, used for input UDP Packets
11415  */
11416 static boolean_t
11417 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11418     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11419 {
11420 	uint32_t	ill_index;
11421 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11422 
11423 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11424 	/* The ill_index of the incoming ILL */
11425 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11426 
11427 	/* pass packet up to the transport */
11428 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11429 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11430 		    NULL, mctl_present);
11431 		if (*first_mpp == NULL) {
11432 			return (B_FALSE);
11433 		}
11434 	}
11435 
11436 	/* Initiate IPPF processing for fastpath UDP */
11437 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11438 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11439 		if (*mpp == NULL) {
11440 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11441 			    "deferred/dropped during IPPF processing\n"));
11442 			return (B_FALSE);
11443 		}
11444 	}
11445 	/*
11446 	 * We make the checks as below since we are in the fast path
11447 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11448 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11449 	 */
11450 	if (connp->conn_recvif || connp->conn_recvslla ||
11451 	    connp->conn_ipv6_recvpktinfo) {
11452 		if (connp->conn_recvif ||
11453 		    connp->conn_ipv6_recvpktinfo) {
11454 			in_flags = IPF_RECVIF;
11455 		}
11456 		if (connp->conn_recvslla) {
11457 			in_flags |= IPF_RECVSLLA;
11458 		}
11459 		/*
11460 		 * since in_flags are being set ill will be
11461 		 * referenced in ip_add_info, so it better not
11462 		 * be NULL.
11463 		 */
11464 		/*
11465 		 * the actual data will be contained in b_cont
11466 		 * upon successful return of the following call.
11467 		 * If the call fails then the original mblk is
11468 		 * returned.
11469 		 */
11470 		*mpp = ip_add_info(*mpp, ill, in_flags);
11471 	}
11472 
11473 	return (B_TRUE);
11474 }
11475 
11476 /*
11477  * Fragmentation reassembly.  Each ILL has a hash table for
11478  * queuing packets undergoing reassembly for all IPIFs
11479  * associated with the ILL.  The hash is based on the packet
11480  * IP ident field.  The ILL frag hash table was allocated
11481  * as a timer block at the time the ILL was created.  Whenever
11482  * there is anything on the reassembly queue, the timer will
11483  * be running.  Returns B_TRUE if successful else B_FALSE;
11484  * frees mp on failure.
11485  */
11486 static boolean_t
11487 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11488     uint32_t *cksum_val, uint16_t *cksum_flags)
11489 {
11490 	uint32_t	frag_offset_flags;
11491 	ill_t		*ill = (ill_t *)q->q_ptr;
11492 	mblk_t		*mp = *mpp;
11493 	mblk_t		*t_mp;
11494 	ipaddr_t	dst;
11495 	uint8_t		proto = ipha->ipha_protocol;
11496 	uint32_t	sum_val;
11497 	uint16_t	sum_flags;
11498 	ipf_t		*ipf;
11499 	ipf_t		**ipfp;
11500 	ipfb_t		*ipfb;
11501 	uint16_t	ident;
11502 	uint32_t	offset;
11503 	ipaddr_t	src;
11504 	uint_t		hdr_length;
11505 	uint32_t	end;
11506 	mblk_t		*mp1;
11507 	mblk_t		*tail_mp;
11508 	size_t		count;
11509 	size_t		msg_len;
11510 	uint8_t		ecn_info = 0;
11511 	uint32_t	packet_size;
11512 	boolean_t	pruned = B_FALSE;
11513 
11514 	if (cksum_val != NULL)
11515 		*cksum_val = 0;
11516 	if (cksum_flags != NULL)
11517 		*cksum_flags = 0;
11518 
11519 	/*
11520 	 * Drop the fragmented as early as possible, if
11521 	 * we don't have resource(s) to re-assemble.
11522 	 */
11523 	if (ip_reass_queue_bytes == 0) {
11524 		freemsg(mp);
11525 		return (B_FALSE);
11526 	}
11527 
11528 	/* Check for fragmentation offset; return if there's none */
11529 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11530 	    (IPH_MF | IPH_OFFSET)) == 0)
11531 		return (B_TRUE);
11532 
11533 	/*
11534 	 * We utilize hardware computed checksum info only for UDP since
11535 	 * IP fragmentation is a normal occurence for the protocol.  In
11536 	 * addition, checksum offload support for IP fragments carrying
11537 	 * UDP payload is commonly implemented across network adapters.
11538 	 */
11539 	ASSERT(ill != NULL);
11540 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11541 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11542 		mblk_t *mp1 = mp->b_cont;
11543 		int32_t len;
11544 
11545 		/* Record checksum information from the packet */
11546 		sum_val = (uint32_t)DB_CKSUM16(mp);
11547 		sum_flags = DB_CKSUMFLAGS(mp);
11548 
11549 		/* IP payload offset from beginning of mblk */
11550 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11551 
11552 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11553 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11554 		    offset >= DB_CKSUMSTART(mp) &&
11555 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11556 			uint32_t adj;
11557 			/*
11558 			 * Partial checksum has been calculated by hardware
11559 			 * and attached to the packet; in addition, any
11560 			 * prepended extraneous data is even byte aligned.
11561 			 * If any such data exists, we adjust the checksum;
11562 			 * this would also handle any postpended data.
11563 			 */
11564 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11565 			    mp, mp1, len, adj);
11566 
11567 			/* One's complement subtract extraneous checksum */
11568 			if (adj >= sum_val)
11569 				sum_val = ~(adj - sum_val) & 0xFFFF;
11570 			else
11571 				sum_val -= adj;
11572 		}
11573 	} else {
11574 		sum_val = 0;
11575 		sum_flags = 0;
11576 	}
11577 
11578 	/* Clear hardware checksumming flag */
11579 	DB_CKSUMFLAGS(mp) = 0;
11580 
11581 	ident = ipha->ipha_ident;
11582 	offset = (frag_offset_flags << 3) & 0xFFFF;
11583 	src = ipha->ipha_src;
11584 	dst = ipha->ipha_dst;
11585 	hdr_length = IPH_HDR_LENGTH(ipha);
11586 	end = ntohs(ipha->ipha_length) - hdr_length;
11587 
11588 	/* If end == 0 then we have a packet with no data, so just free it */
11589 	if (end == 0) {
11590 		freemsg(mp);
11591 		return (B_FALSE);
11592 	}
11593 
11594 	/* Record the ECN field info. */
11595 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11596 	if (offset != 0) {
11597 		/*
11598 		 * If this isn't the first piece, strip the header, and
11599 		 * add the offset to the end value.
11600 		 */
11601 		mp->b_rptr += hdr_length;
11602 		end += offset;
11603 	}
11604 
11605 	msg_len = MBLKSIZE(mp);
11606 	tail_mp = mp;
11607 	while (tail_mp->b_cont != NULL) {
11608 		tail_mp = tail_mp->b_cont;
11609 		msg_len += MBLKSIZE(tail_mp);
11610 	}
11611 
11612 	/* If the reassembly list for this ILL will get too big, prune it */
11613 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11614 	    ip_reass_queue_bytes) {
11615 		ill_frag_prune(ill,
11616 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11617 		    (ip_reass_queue_bytes - msg_len));
11618 		pruned = B_TRUE;
11619 	}
11620 
11621 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11622 	mutex_enter(&ipfb->ipfb_lock);
11623 
11624 	ipfp = &ipfb->ipfb_ipf;
11625 	/* Try to find an existing fragment queue for this packet. */
11626 	for (;;) {
11627 		ipf = ipfp[0];
11628 		if (ipf != NULL) {
11629 			/*
11630 			 * It has to match on ident and src/dst address.
11631 			 */
11632 			if (ipf->ipf_ident == ident &&
11633 			    ipf->ipf_src == src &&
11634 			    ipf->ipf_dst == dst &&
11635 			    ipf->ipf_protocol == proto) {
11636 				/*
11637 				 * If we have received too many
11638 				 * duplicate fragments for this packet
11639 				 * free it.
11640 				 */
11641 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11642 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11643 					freemsg(mp);
11644 					mutex_exit(&ipfb->ipfb_lock);
11645 					return (B_FALSE);
11646 				}
11647 				/* Found it. */
11648 				break;
11649 			}
11650 			ipfp = &ipf->ipf_hash_next;
11651 			continue;
11652 		}
11653 
11654 		/*
11655 		 * If we pruned the list, do we want to store this new
11656 		 * fragment?. We apply an optimization here based on the
11657 		 * fact that most fragments will be received in order.
11658 		 * So if the offset of this incoming fragment is zero,
11659 		 * it is the first fragment of a new packet. We will
11660 		 * keep it.  Otherwise drop the fragment, as we have
11661 		 * probably pruned the packet already (since the
11662 		 * packet cannot be found).
11663 		 */
11664 		if (pruned && offset != 0) {
11665 			mutex_exit(&ipfb->ipfb_lock);
11666 			freemsg(mp);
11667 			return (B_FALSE);
11668 		}
11669 
11670 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11671 			/*
11672 			 * Too many fragmented packets in this hash
11673 			 * bucket. Free the oldest.
11674 			 */
11675 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11676 		}
11677 
11678 		/* New guy.  Allocate a frag message. */
11679 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11680 		if (mp1 == NULL) {
11681 			BUMP_MIB(&ip_mib, ipInDiscards);
11682 			freemsg(mp);
11683 reass_done:
11684 			mutex_exit(&ipfb->ipfb_lock);
11685 			return (B_FALSE);
11686 		}
11687 
11688 
11689 		BUMP_MIB(&ip_mib, ipReasmReqds);
11690 		mp1->b_cont = mp;
11691 
11692 		/* Initialize the fragment header. */
11693 		ipf = (ipf_t *)mp1->b_rptr;
11694 		ipf->ipf_mp = mp1;
11695 		ipf->ipf_ptphn = ipfp;
11696 		ipfp[0] = ipf;
11697 		ipf->ipf_hash_next = NULL;
11698 		ipf->ipf_ident = ident;
11699 		ipf->ipf_protocol = proto;
11700 		ipf->ipf_src = src;
11701 		ipf->ipf_dst = dst;
11702 		ipf->ipf_nf_hdr_len = 0;
11703 		/* Record reassembly start time. */
11704 		ipf->ipf_timestamp = gethrestime_sec();
11705 		/* Record ipf generation and account for frag header */
11706 		ipf->ipf_gen = ill->ill_ipf_gen++;
11707 		ipf->ipf_count = MBLKSIZE(mp1);
11708 		ipf->ipf_last_frag_seen = B_FALSE;
11709 		ipf->ipf_ecn = ecn_info;
11710 		ipf->ipf_num_dups = 0;
11711 		ipfb->ipfb_frag_pkts++;
11712 		ipf->ipf_checksum = 0;
11713 		ipf->ipf_checksum_flags = 0;
11714 
11715 		/* Store checksum value in fragment header */
11716 		if (sum_flags != 0) {
11717 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11718 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11719 			ipf->ipf_checksum = sum_val;
11720 			ipf->ipf_checksum_flags = sum_flags;
11721 		}
11722 
11723 		/*
11724 		 * We handle reassembly two ways.  In the easy case,
11725 		 * where all the fragments show up in order, we do
11726 		 * minimal bookkeeping, and just clip new pieces on
11727 		 * the end.  If we ever see a hole, then we go off
11728 		 * to ip_reassemble which has to mark the pieces and
11729 		 * keep track of the number of holes, etc.  Obviously,
11730 		 * the point of having both mechanisms is so we can
11731 		 * handle the easy case as efficiently as possible.
11732 		 */
11733 		if (offset == 0) {
11734 			/* Easy case, in-order reassembly so far. */
11735 			ipf->ipf_count += msg_len;
11736 			ipf->ipf_tail_mp = tail_mp;
11737 			/*
11738 			 * Keep track of next expected offset in
11739 			 * ipf_end.
11740 			 */
11741 			ipf->ipf_end = end;
11742 			ipf->ipf_nf_hdr_len = hdr_length;
11743 		} else {
11744 			/* Hard case, hole at the beginning. */
11745 			ipf->ipf_tail_mp = NULL;
11746 			/*
11747 			 * ipf_end == 0 means that we have given up
11748 			 * on easy reassembly.
11749 			 */
11750 			ipf->ipf_end = 0;
11751 
11752 			/* Forget checksum offload from now on */
11753 			ipf->ipf_checksum_flags = 0;
11754 
11755 			/*
11756 			 * ipf_hole_cnt is set by ip_reassemble.
11757 			 * ipf_count is updated by ip_reassemble.
11758 			 * No need to check for return value here
11759 			 * as we don't expect reassembly to complete
11760 			 * or fail for the first fragment itself.
11761 			 */
11762 			(void) ip_reassemble(mp, ipf,
11763 			    (frag_offset_flags & IPH_OFFSET) << 3,
11764 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11765 		}
11766 		/* Update per ipfb and ill byte counts */
11767 		ipfb->ipfb_count += ipf->ipf_count;
11768 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11769 		ill->ill_frag_count += ipf->ipf_count;
11770 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11771 		/* If the frag timer wasn't already going, start it. */
11772 		mutex_enter(&ill->ill_lock);
11773 		ill_frag_timer_start(ill);
11774 		mutex_exit(&ill->ill_lock);
11775 		goto reass_done;
11776 	}
11777 
11778 	/*
11779 	 * If the packet's flag has changed (it could be coming up
11780 	 * from an interface different than the previous, therefore
11781 	 * possibly different checksum capability), then forget about
11782 	 * any stored checksum states.  Otherwise add the value to
11783 	 * the existing one stored in the fragment header.
11784 	 */
11785 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11786 		sum_val += ipf->ipf_checksum;
11787 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11788 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11789 		ipf->ipf_checksum = sum_val;
11790 	} else if (ipf->ipf_checksum_flags != 0) {
11791 		/* Forget checksum offload from now on */
11792 		ipf->ipf_checksum_flags = 0;
11793 	}
11794 
11795 	/*
11796 	 * We have a new piece of a datagram which is already being
11797 	 * reassembled.  Update the ECN info if all IP fragments
11798 	 * are ECN capable.  If there is one which is not, clear
11799 	 * all the info.  If there is at least one which has CE
11800 	 * code point, IP needs to report that up to transport.
11801 	 */
11802 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11803 		if (ecn_info == IPH_ECN_CE)
11804 			ipf->ipf_ecn = IPH_ECN_CE;
11805 	} else {
11806 		ipf->ipf_ecn = IPH_ECN_NECT;
11807 	}
11808 	if (offset && ipf->ipf_end == offset) {
11809 		/* The new fragment fits at the end */
11810 		ipf->ipf_tail_mp->b_cont = mp;
11811 		/* Update the byte count */
11812 		ipf->ipf_count += msg_len;
11813 		/* Update per ipfb and ill byte counts */
11814 		ipfb->ipfb_count += msg_len;
11815 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11816 		ill->ill_frag_count += msg_len;
11817 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11818 		if (frag_offset_flags & IPH_MF) {
11819 			/* More to come. */
11820 			ipf->ipf_end = end;
11821 			ipf->ipf_tail_mp = tail_mp;
11822 			goto reass_done;
11823 		}
11824 	} else {
11825 		/* Go do the hard cases. */
11826 		int ret;
11827 
11828 		if (offset == 0)
11829 			ipf->ipf_nf_hdr_len = hdr_length;
11830 
11831 		/* Save current byte count */
11832 		count = ipf->ipf_count;
11833 		ret = ip_reassemble(mp, ipf,
11834 		    (frag_offset_flags & IPH_OFFSET) << 3,
11835 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11836 		/* Count of bytes added and subtracted (freeb()ed) */
11837 		count = ipf->ipf_count - count;
11838 		if (count) {
11839 			/* Update per ipfb and ill byte counts */
11840 			ipfb->ipfb_count += count;
11841 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11842 			ill->ill_frag_count += count;
11843 			ASSERT(ill->ill_frag_count > 0);
11844 		}
11845 		if (ret == IP_REASS_PARTIAL) {
11846 			goto reass_done;
11847 		} else if (ret == IP_REASS_FAILED) {
11848 			/* Reassembly failed. Free up all resources */
11849 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11850 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11851 				IP_REASS_SET_START(t_mp, 0);
11852 				IP_REASS_SET_END(t_mp, 0);
11853 			}
11854 			freemsg(mp);
11855 			goto reass_done;
11856 		}
11857 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11858 	}
11859 	/*
11860 	 * We have completed reassembly.  Unhook the frag header from
11861 	 * the reassembly list.
11862 	 *
11863 	 * Before we free the frag header, record the ECN info
11864 	 * to report back to the transport.
11865 	 */
11866 	ecn_info = ipf->ipf_ecn;
11867 	BUMP_MIB(&ip_mib, ipReasmOKs);
11868 	ipfp = ipf->ipf_ptphn;
11869 
11870 	/* We need to supply these to caller */
11871 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11872 		sum_val = ipf->ipf_checksum;
11873 	else
11874 		sum_val = 0;
11875 
11876 	mp1 = ipf->ipf_mp;
11877 	count = ipf->ipf_count;
11878 	ipf = ipf->ipf_hash_next;
11879 	if (ipf != NULL)
11880 		ipf->ipf_ptphn = ipfp;
11881 	ipfp[0] = ipf;
11882 	ill->ill_frag_count -= count;
11883 	ASSERT(ipfb->ipfb_count >= count);
11884 	ipfb->ipfb_count -= count;
11885 	ipfb->ipfb_frag_pkts--;
11886 	mutex_exit(&ipfb->ipfb_lock);
11887 	/* Ditch the frag header. */
11888 	mp = mp1->b_cont;
11889 
11890 	freeb(mp1);
11891 
11892 	/* Restore original IP length in header. */
11893 	packet_size = (uint32_t)msgdsize(mp);
11894 	if (packet_size > IP_MAXPACKET) {
11895 		freemsg(mp);
11896 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11897 		return (B_FALSE);
11898 	}
11899 
11900 	if (DB_REF(mp) > 1) {
11901 		mblk_t *mp2 = copymsg(mp);
11902 
11903 		freemsg(mp);
11904 		if (mp2 == NULL) {
11905 			BUMP_MIB(&ip_mib, ipInDiscards);
11906 			return (B_FALSE);
11907 		}
11908 		mp = mp2;
11909 	}
11910 	ipha = (ipha_t *)mp->b_rptr;
11911 
11912 	ipha->ipha_length = htons((uint16_t)packet_size);
11913 	/* We're now complete, zip the frag state */
11914 	ipha->ipha_fragment_offset_and_flags = 0;
11915 	/* Record the ECN info. */
11916 	ipha->ipha_type_of_service &= 0xFC;
11917 	ipha->ipha_type_of_service |= ecn_info;
11918 	*mpp = mp;
11919 
11920 	/* Reassembly is successful; return checksum information if needed */
11921 	if (cksum_val != NULL)
11922 		*cksum_val = sum_val;
11923 	if (cksum_flags != NULL)
11924 		*cksum_flags = sum_flags;
11925 
11926 	return (B_TRUE);
11927 }
11928 
11929 /*
11930  * Perform ip header check sum update local options.
11931  * return B_TRUE if all is well, else return B_FALSE and release
11932  * the mp. caller is responsible for decrementing ire ref cnt.
11933  */
11934 static boolean_t
11935 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11936 {
11937 	mblk_t		*first_mp;
11938 	boolean_t	mctl_present;
11939 	uint16_t	sum;
11940 
11941 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11942 	/*
11943 	 * Don't do the checksum if it has gone through AH/ESP
11944 	 * processing.
11945 	 */
11946 	if (!mctl_present) {
11947 		sum = ip_csum_hdr(ipha);
11948 		if (sum != 0) {
11949 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11950 			freemsg(first_mp);
11951 			return (B_FALSE);
11952 		}
11953 	}
11954 
11955 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11956 		if (mctl_present)
11957 			freeb(first_mp);
11958 		return (B_FALSE);
11959 	}
11960 
11961 	return (B_TRUE);
11962 }
11963 
11964 /*
11965  * All udp packet are delivered to the local host via this routine.
11966  */
11967 void
11968 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11969     ill_t *recv_ill)
11970 {
11971 	uint32_t	sum;
11972 	uint32_t	u1;
11973 	boolean_t	mctl_present;
11974 	conn_t		*connp;
11975 	mblk_t		*first_mp;
11976 	uint16_t	*up;
11977 	ill_t		*ill = (ill_t *)q->q_ptr;
11978 	uint16_t	reass_hck_flags = 0;
11979 
11980 #define	rptr    ((uchar_t *)ipha)
11981 
11982 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11983 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11984 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11985 
11986 	/*
11987 	 * FAST PATH for udp packets
11988 	 */
11989 
11990 	/* u1 is # words of IP options */
11991 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
11992 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
11993 
11994 	/* IP options present */
11995 	if (u1 != 0)
11996 		goto ipoptions;
11997 
11998 	/* Check the IP header checksum.  */
11999 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12000 		/* Clear the IP header h/w cksum flag */
12001 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12002 	} else {
12003 #define	uph	((uint16_t *)ipha)
12004 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12005 		    uph[6] + uph[7] + uph[8] + uph[9];
12006 #undef	uph
12007 		/* finish doing IP checksum */
12008 		sum = (sum & 0xFFFF) + (sum >> 16);
12009 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12010 		/*
12011 		 * Don't verify header checksum if this packet is coming
12012 		 * back from AH/ESP as we already did it.
12013 		 */
12014 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12015 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12016 			freemsg(first_mp);
12017 			return;
12018 		}
12019 	}
12020 
12021 	/*
12022 	 * Count for SNMP of inbound packets for ire.
12023 	 * if mctl is present this might be a secure packet and
12024 	 * has already been counted for in ip_proto_input().
12025 	 */
12026 	if (!mctl_present) {
12027 		UPDATE_IB_PKT_COUNT(ire);
12028 		ire->ire_last_used_time = lbolt;
12029 	}
12030 
12031 	/* packet part of fragmented IP packet? */
12032 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12033 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12034 		goto fragmented;
12035 	}
12036 
12037 	/* u1 = IP header length (20 bytes) */
12038 	u1 = IP_SIMPLE_HDR_LENGTH;
12039 
12040 	/* packet does not contain complete IP & UDP headers */
12041 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12042 		goto udppullup;
12043 
12044 	/* up points to UDP header */
12045 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12046 #define	iphs    ((uint16_t *)ipha)
12047 
12048 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12049 	if (up[3] != 0) {
12050 		mblk_t *mp1 = mp->b_cont;
12051 		boolean_t cksum_err;
12052 		uint16_t hck_flags = 0;
12053 
12054 		/* Pseudo-header checksum */
12055 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12056 		    iphs[9] + up[2];
12057 
12058 		/*
12059 		 * Revert to software checksum calculation if the interface
12060 		 * isn't capable of checksum offload or if IPsec is present.
12061 		 */
12062 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12063 			hck_flags = DB_CKSUMFLAGS(mp);
12064 
12065 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12066 			IP_STAT(ip_in_sw_cksum);
12067 
12068 		IP_CKSUM_RECV(hck_flags, u1,
12069 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12070 		    (int32_t)((uchar_t *)up - rptr),
12071 		    mp, mp1, cksum_err);
12072 
12073 		if (cksum_err) {
12074 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12075 
12076 			if (hck_flags & HCK_FULLCKSUM)
12077 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12078 			else if (hck_flags & HCK_PARTIALCKSUM)
12079 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12080 			else
12081 				IP_STAT(ip_udp_in_sw_cksum_err);
12082 
12083 			freemsg(first_mp);
12084 			return;
12085 		}
12086 	}
12087 
12088 	/* Non-fragmented broadcast or multicast packet? */
12089 	if (ire->ire_type == IRE_BROADCAST)
12090 		goto udpslowpath;
12091 
12092 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12093 	    ire->ire_zoneid)) != NULL) {
12094 		ASSERT(connp->conn_upq != NULL);
12095 		IP_STAT(ip_udp_fast_path);
12096 
12097 		if (CONN_UDP_FLOWCTLD(connp)) {
12098 			freemsg(mp);
12099 			BUMP_MIB(&ip_mib, udpInOverflows);
12100 		} else {
12101 			if (!mctl_present) {
12102 				BUMP_MIB(&ip_mib, ipInDelivers);
12103 			}
12104 			/*
12105 			 * mp and first_mp can change.
12106 			 */
12107 			if (ip_udp_check(q, connp, recv_ill,
12108 			    ipha, &mp, &first_mp, mctl_present)) {
12109 				/* Send it upstream */
12110 				CONN_UDP_RECV(connp, mp);
12111 			}
12112 		}
12113 		/*
12114 		 * freeb() cannot deal with null mblk being passed
12115 		 * in and first_mp can be set to null in the call
12116 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12117 		 */
12118 		if (mctl_present && first_mp != NULL) {
12119 			freeb(first_mp);
12120 		}
12121 		CONN_DEC_REF(connp);
12122 		return;
12123 	}
12124 
12125 	/*
12126 	 * if we got here we know the packet is not fragmented and
12127 	 * has no options. The classifier could not find a conn_t and
12128 	 * most likely its an icmp packet so send it through slow path.
12129 	 */
12130 
12131 	goto udpslowpath;
12132 
12133 ipoptions:
12134 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12135 		goto slow_done;
12136 	}
12137 
12138 	UPDATE_IB_PKT_COUNT(ire);
12139 	ire->ire_last_used_time = lbolt;
12140 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12141 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12142 fragmented:
12143 		/*
12144 		 * "sum" and "reass_hck_flags" are non-zero if the
12145 		 * reassembled packet has a valid hardware computed
12146 		 * checksum information associated with it.
12147 		 */
12148 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12149 			goto slow_done;
12150 		/*
12151 		 * Make sure that first_mp points back to mp as
12152 		 * the mp we came in with could have changed in
12153 		 * ip_rput_fragment().
12154 		 */
12155 		ASSERT(!mctl_present);
12156 		ipha = (ipha_t *)mp->b_rptr;
12157 		first_mp = mp;
12158 	}
12159 
12160 	/* Now we have a complete datagram, destined for this machine. */
12161 	u1 = IPH_HDR_LENGTH(ipha);
12162 	/* Pull up the UDP header, if necessary. */
12163 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12164 udppullup:
12165 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12166 			BUMP_MIB(&ip_mib, ipInDiscards);
12167 			freemsg(first_mp);
12168 			goto slow_done;
12169 		}
12170 		ipha = (ipha_t *)mp->b_rptr;
12171 	}
12172 
12173 	/*
12174 	 * Validate the checksum for the reassembled packet; for the
12175 	 * pullup case we calculate the payload checksum in software.
12176 	 */
12177 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12178 	if (up[3] != 0) {
12179 		boolean_t cksum_err;
12180 
12181 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12182 			IP_STAT(ip_in_sw_cksum);
12183 
12184 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12185 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12186 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12187 		    iphs[9] + up[2], sum, cksum_err);
12188 
12189 		if (cksum_err) {
12190 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12191 
12192 			if (reass_hck_flags & HCK_FULLCKSUM)
12193 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12194 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12195 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12196 			else
12197 				IP_STAT(ip_udp_in_sw_cksum_err);
12198 
12199 			freemsg(first_mp);
12200 			goto slow_done;
12201 		}
12202 	}
12203 udpslowpath:
12204 
12205 	/* Clear hardware checksum flag to be safe */
12206 	DB_CKSUMFLAGS(mp) = 0;
12207 
12208 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12209 	    (ire->ire_type == IRE_BROADCAST),
12210 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12211 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12212 
12213 slow_done:
12214 	IP_STAT(ip_udp_slow_path);
12215 	return;
12216 
12217 #undef  iphs
12218 #undef  rptr
12219 }
12220 
12221 /* ARGSUSED */
12222 static mblk_t *
12223 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12224     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12225     ill_rx_ring_t *ill_ring)
12226 {
12227 	conn_t		*connp;
12228 	uint32_t	sum;
12229 	uint32_t	u1;
12230 	uint16_t	*up;
12231 	int		offset;
12232 	ssize_t		len;
12233 	mblk_t		*mp1;
12234 	boolean_t	syn_present = B_FALSE;
12235 	tcph_t		*tcph;
12236 	uint_t		ip_hdr_len;
12237 	ill_t		*ill = (ill_t *)q->q_ptr;
12238 	zoneid_t	zoneid = ire->ire_zoneid;
12239 	boolean_t	cksum_err;
12240 	uint16_t	hck_flags = 0;
12241 
12242 #define	rptr	((uchar_t *)ipha)
12243 
12244 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12245 
12246 	/*
12247 	 * FAST PATH for tcp packets
12248 	 */
12249 
12250 	/* u1 is # words of IP options */
12251 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12252 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12253 
12254 	/* IP options present */
12255 	if (u1) {
12256 		goto ipoptions;
12257 	} else {
12258 		/* Check the IP header checksum.  */
12259 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12260 			/* Clear the IP header h/w cksum flag */
12261 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12262 		} else {
12263 #define	uph	((uint16_t *)ipha)
12264 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12265 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12266 #undef	uph
12267 			/* finish doing IP checksum */
12268 			sum = (sum & 0xFFFF) + (sum >> 16);
12269 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12270 			/*
12271 			 * Don't verify header checksum if this packet
12272 			 * is coming back from AH/ESP as we already did it.
12273 			 */
12274 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12275 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12276 				goto error;
12277 			}
12278 		}
12279 	}
12280 
12281 	if (!mctl_present) {
12282 		UPDATE_IB_PKT_COUNT(ire);
12283 		ire->ire_last_used_time = lbolt;
12284 	}
12285 
12286 	/* packet part of fragmented IP packet? */
12287 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12288 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12289 		goto fragmented;
12290 	}
12291 
12292 	/* u1 = IP header length (20 bytes) */
12293 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12294 
12295 	/* does packet contain IP+TCP headers? */
12296 	len = mp->b_wptr - rptr;
12297 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12298 		IP_STAT(ip_tcppullup);
12299 		goto tcppullup;
12300 	}
12301 
12302 	/* TCP options present? */
12303 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12304 
12305 	/*
12306 	 * If options need to be pulled up, then goto tcpoptions.
12307 	 * otherwise we are still in the fast path
12308 	 */
12309 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12310 		IP_STAT(ip_tcpoptions);
12311 		goto tcpoptions;
12312 	}
12313 
12314 	/* multiple mblks of tcp data? */
12315 	if ((mp1 = mp->b_cont) != NULL) {
12316 		/* more then two? */
12317 		if (mp1->b_cont != NULL) {
12318 			IP_STAT(ip_multipkttcp);
12319 			goto multipkttcp;
12320 		}
12321 		len += mp1->b_wptr - mp1->b_rptr;
12322 	}
12323 
12324 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12325 
12326 	/* part of pseudo checksum */
12327 
12328 	/* TCP datagram length */
12329 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12330 
12331 #define	iphs    ((uint16_t *)ipha)
12332 
12333 #ifdef	_BIG_ENDIAN
12334 	u1 += IPPROTO_TCP;
12335 #else
12336 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12337 #endif
12338 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12339 
12340 	/*
12341 	 * Revert to software checksum calculation if the interface
12342 	 * isn't capable of checksum offload or if IPsec is present.
12343 	 */
12344 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12345 		hck_flags = DB_CKSUMFLAGS(mp);
12346 
12347 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12348 		IP_STAT(ip_in_sw_cksum);
12349 
12350 	IP_CKSUM_RECV(hck_flags, u1,
12351 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12352 	    (int32_t)((uchar_t *)up - rptr),
12353 	    mp, mp1, cksum_err);
12354 
12355 	if (cksum_err) {
12356 		BUMP_MIB(&ip_mib, tcpInErrs);
12357 
12358 		if (hck_flags & HCK_FULLCKSUM)
12359 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12360 		else if (hck_flags & HCK_PARTIALCKSUM)
12361 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12362 		else
12363 			IP_STAT(ip_tcp_in_sw_cksum_err);
12364 
12365 		goto error;
12366 	}
12367 
12368 try_again:
12369 
12370 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12371 	    NULL) {
12372 		/* Send the TH_RST */
12373 		goto no_conn;
12374 	}
12375 
12376 	/*
12377 	 * TCP FAST PATH for AF_INET socket.
12378 	 *
12379 	 * TCP fast path to avoid extra work. An AF_INET socket type
12380 	 * does not have facility to receive extra information via
12381 	 * ip_process or ip_add_info. Also, when the connection was
12382 	 * established, we made a check if this connection is impacted
12383 	 * by any global IPSec policy or per connection policy (a
12384 	 * policy that comes in effect later will not apply to this
12385 	 * connection). Since all this can be determined at the
12386 	 * connection establishment time, a quick check of flags
12387 	 * can avoid extra work.
12388 	 */
12389 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12390 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12391 		ASSERT(first_mp == mp);
12392 		SET_SQUEUE(mp, tcp_rput_data, connp);
12393 		return (mp);
12394 	}
12395 
12396 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12397 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12398 		if (IPCL_IS_TCP(connp)) {
12399 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12400 			DB_CKSUMSTART(mp) =
12401 			    (intptr_t)ip_squeue_get(ill_ring);
12402 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12403 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12404 				SET_SQUEUE(mp, connp->conn_recv, connp);
12405 				return (mp);
12406 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12407 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12408 				ip_squeue_enter_unbound++;
12409 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12410 				    connp);
12411 				return (mp);
12412 			}
12413 			syn_present = B_TRUE;
12414 		}
12415 
12416 	}
12417 
12418 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12419 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12420 
12421 		/* No need to send this packet to TCP */
12422 		if ((flags & TH_RST) || (flags & TH_URG)) {
12423 			CONN_DEC_REF(connp);
12424 			freemsg(first_mp);
12425 			return (NULL);
12426 		}
12427 		if (flags & TH_ACK) {
12428 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
12429 			CONN_DEC_REF(connp);
12430 			return (NULL);
12431 		}
12432 
12433 		CONN_DEC_REF(connp);
12434 		freemsg(first_mp);
12435 		return (NULL);
12436 	}
12437 
12438 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12439 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12440 		    ipha, NULL, mctl_present);
12441 		if (first_mp == NULL) {
12442 			CONN_DEC_REF(connp);
12443 			return (NULL);
12444 		}
12445 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12446 			ASSERT(syn_present);
12447 			if (mctl_present) {
12448 				ASSERT(first_mp != mp);
12449 				first_mp->b_datap->db_struioflag |=
12450 				    STRUIO_POLICY;
12451 			} else {
12452 				ASSERT(first_mp == mp);
12453 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12454 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12455 			}
12456 		} else {
12457 			/*
12458 			 * Discard first_mp early since we're dealing with a
12459 			 * fully-connected conn_t and tcp doesn't do policy in
12460 			 * this case.
12461 			 */
12462 			if (mctl_present) {
12463 				freeb(first_mp);
12464 				mctl_present = B_FALSE;
12465 			}
12466 			first_mp = mp;
12467 		}
12468 	}
12469 
12470 	/* Initiate IPPF processing for fastpath */
12471 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12472 		uint32_t	ill_index;
12473 
12474 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12475 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12476 		if (mp == NULL) {
12477 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12478 			    "deferred/dropped during IPPF processing\n"));
12479 			CONN_DEC_REF(connp);
12480 			if (mctl_present)
12481 				freeb(first_mp);
12482 			return (NULL);
12483 		} else if (mctl_present) {
12484 			/*
12485 			 * ip_process might return a new mp.
12486 			 */
12487 			ASSERT(first_mp != mp);
12488 			first_mp->b_cont = mp;
12489 		} else {
12490 			first_mp = mp;
12491 		}
12492 
12493 	}
12494 
12495 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12496 		mp = ip_add_info(mp, recv_ill, flags);
12497 		if (mp == NULL) {
12498 			CONN_DEC_REF(connp);
12499 			if (mctl_present)
12500 				freeb(first_mp);
12501 			return (NULL);
12502 		} else if (mctl_present) {
12503 			/*
12504 			 * ip_add_info might return a new mp.
12505 			 */
12506 			ASSERT(first_mp != mp);
12507 			first_mp->b_cont = mp;
12508 		} else {
12509 			first_mp = mp;
12510 		}
12511 	}
12512 
12513 	if (IPCL_IS_TCP(connp)) {
12514 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12515 		return (first_mp);
12516 	} else {
12517 		putnext(connp->conn_rq, first_mp);
12518 		CONN_DEC_REF(connp);
12519 		return (NULL);
12520 	}
12521 
12522 no_conn:
12523 	/* Initiate IPPf processing, if needed. */
12524 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12525 		uint32_t ill_index;
12526 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12527 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12528 		if (first_mp == NULL) {
12529 			return (NULL);
12530 		}
12531 	}
12532 	BUMP_MIB(&ip_mib, ipInDelivers);
12533 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12534 	return (NULL);
12535 ipoptions:
12536 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12537 		goto slow_done;
12538 	}
12539 
12540 	UPDATE_IB_PKT_COUNT(ire);
12541 	ire->ire_last_used_time = lbolt;
12542 
12543 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12544 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12545 fragmented:
12546 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12547 			if (mctl_present)
12548 				freeb(first_mp);
12549 			goto slow_done;
12550 		}
12551 		/*
12552 		 * Make sure that first_mp points back to mp as
12553 		 * the mp we came in with could have changed in
12554 		 * ip_rput_fragment().
12555 		 */
12556 		ASSERT(!mctl_present);
12557 		ipha = (ipha_t *)mp->b_rptr;
12558 		first_mp = mp;
12559 	}
12560 
12561 	/* Now we have a complete datagram, destined for this machine. */
12562 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12563 
12564 	len = mp->b_wptr - mp->b_rptr;
12565 	/* Pull up a minimal TCP header, if necessary. */
12566 	if (len < (u1 + 20)) {
12567 tcppullup:
12568 		if (!pullupmsg(mp, u1 + 20)) {
12569 			BUMP_MIB(&ip_mib, ipInDiscards);
12570 			goto error;
12571 		}
12572 		ipha = (ipha_t *)mp->b_rptr;
12573 		len = mp->b_wptr - mp->b_rptr;
12574 	}
12575 
12576 	/*
12577 	 * Extract the offset field from the TCP header.  As usual, we
12578 	 * try to help the compiler more than the reader.
12579 	 */
12580 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12581 	if (offset != 5) {
12582 tcpoptions:
12583 		if (offset < 5) {
12584 			BUMP_MIB(&ip_mib, ipInDiscards);
12585 			goto error;
12586 		}
12587 		/*
12588 		 * There must be TCP options.
12589 		 * Make sure we can grab them.
12590 		 */
12591 		offset <<= 2;
12592 		offset += u1;
12593 		if (len < offset) {
12594 			if (!pullupmsg(mp, offset)) {
12595 				BUMP_MIB(&ip_mib, ipInDiscards);
12596 				goto error;
12597 			}
12598 			ipha = (ipha_t *)mp->b_rptr;
12599 			len = mp->b_wptr - rptr;
12600 		}
12601 	}
12602 
12603 	/* Get the total packet length in len, including headers. */
12604 	if (mp->b_cont) {
12605 multipkttcp:
12606 		len = msgdsize(mp);
12607 	}
12608 
12609 	/*
12610 	 * Check the TCP checksum by pulling together the pseudo-
12611 	 * header checksum, and passing it to ip_csum to be added in
12612 	 * with the TCP datagram.
12613 	 *
12614 	 * Since we are not using the hwcksum if available we must
12615 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12616 	 * If either of these fails along the way the mblk is freed.
12617 	 * If this logic ever changes and mblk is reused to say send
12618 	 * ICMP's back, then this flag may need to be cleared in
12619 	 * other places as well.
12620 	 */
12621 	DB_CKSUMFLAGS(mp) = 0;
12622 
12623 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12624 
12625 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12626 #ifdef	_BIG_ENDIAN
12627 	u1 += IPPROTO_TCP;
12628 #else
12629 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12630 #endif
12631 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12632 	/*
12633 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12634 	 */
12635 	IP_STAT(ip_in_sw_cksum);
12636 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12637 		BUMP_MIB(&ip_mib, tcpInErrs);
12638 		goto error;
12639 	}
12640 
12641 	IP_STAT(ip_tcp_slow_path);
12642 	goto try_again;
12643 #undef  iphs
12644 #undef  rptr
12645 
12646 error:
12647 	freemsg(first_mp);
12648 slow_done:
12649 	return (NULL);
12650 }
12651 
12652 /* ARGSUSED */
12653 static void
12654 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12655     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12656 {
12657 	conn_t		*connp;
12658 	uint32_t	sum;
12659 	uint32_t	u1;
12660 	ssize_t		len;
12661 	sctp_hdr_t	*sctph;
12662 	zoneid_t	zoneid = ire->ire_zoneid;
12663 	uint32_t	pktsum;
12664 	uint32_t	calcsum;
12665 	uint32_t	ports;
12666 	uint_t		ipif_seqid;
12667 	in6_addr_t	map_src, map_dst;
12668 	ill_t		*ill = (ill_t *)q->q_ptr;
12669 
12670 #define	rptr	((uchar_t *)ipha)
12671 
12672 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12673 
12674 	/* u1 is # words of IP options */
12675 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12676 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12677 
12678 	/* IP options present */
12679 	if (u1 > 0) {
12680 		goto ipoptions;
12681 	} else {
12682 		/* Check the IP header checksum.  */
12683 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12684 #define	uph	((uint16_t *)ipha)
12685 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12686 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12687 #undef	uph
12688 			/* finish doing IP checksum */
12689 			sum = (sum & 0xFFFF) + (sum >> 16);
12690 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12691 			/*
12692 			 * Don't verify header checksum if this packet
12693 			 * is coming back from AH/ESP as we already did it.
12694 			 */
12695 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12696 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12697 				goto error;
12698 			}
12699 		}
12700 		/*
12701 		 * Since there is no SCTP h/w cksum support yet, just
12702 		 * clear the flag.
12703 		 */
12704 		DB_CKSUMFLAGS(mp) = 0;
12705 	}
12706 
12707 	/*
12708 	 * Don't verify header checksum if this packet is coming
12709 	 * back from AH/ESP as we already did it.
12710 	 */
12711 	if (!mctl_present) {
12712 		UPDATE_IB_PKT_COUNT(ire);
12713 		ire->ire_last_used_time = lbolt;
12714 	}
12715 
12716 	/* packet part of fragmented IP packet? */
12717 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12718 	if (u1 & (IPH_MF | IPH_OFFSET))
12719 		goto fragmented;
12720 
12721 	/* u1 = IP header length (20 bytes) */
12722 	u1 = IP_SIMPLE_HDR_LENGTH;
12723 
12724 find_sctp_client:
12725 	/* Pullup if we don't have the sctp common header. */
12726 	len = MBLKL(mp);
12727 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12728 		if (mp->b_cont == NULL ||
12729 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12730 			BUMP_MIB(&ip_mib, ipInDiscards);
12731 			goto error;
12732 		}
12733 		ipha = (ipha_t *)mp->b_rptr;
12734 		len = MBLKL(mp);
12735 	}
12736 
12737 	sctph = (sctp_hdr_t *)(rptr + u1);
12738 #ifdef	DEBUG
12739 	if (!skip_sctp_cksum) {
12740 #endif
12741 		pktsum = sctph->sh_chksum;
12742 		sctph->sh_chksum = 0;
12743 		calcsum = sctp_cksum(mp, u1);
12744 		if (calcsum != pktsum) {
12745 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12746 			goto error;
12747 		}
12748 		sctph->sh_chksum = pktsum;
12749 #ifdef	DEBUG	/* skip_sctp_cksum */
12750 	}
12751 #endif
12752 	/* get the ports */
12753 	ports = *(uint32_t *)&sctph->sh_sport;
12754 
12755 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12756 	IRE_REFRELE(ire);
12757 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12758 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12759 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
12760 	    mp)) == NULL) {
12761 		/* Check for raw socket or OOTB handling */
12762 		goto no_conn;
12763 	}
12764 
12765 	/* Found a client; up it goes */
12766 	BUMP_MIB(&ip_mib, ipInDelivers);
12767 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12768 	return;
12769 
12770 no_conn:
12771 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12772 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12773 	return;
12774 
12775 ipoptions:
12776 	DB_CKSUMFLAGS(mp) = 0;
12777 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12778 		goto slow_done;
12779 
12780 	UPDATE_IB_PKT_COUNT(ire);
12781 	ire->ire_last_used_time = lbolt;
12782 
12783 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12784 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12785 fragmented:
12786 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12787 			goto slow_done;
12788 		/*
12789 		 * Make sure that first_mp points back to mp as
12790 		 * the mp we came in with could have changed in
12791 		 * ip_rput_fragment().
12792 		 */
12793 		ASSERT(!mctl_present);
12794 		ipha = (ipha_t *)mp->b_rptr;
12795 		first_mp = mp;
12796 	}
12797 
12798 	/* Now we have a complete datagram, destined for this machine. */
12799 	u1 = IPH_HDR_LENGTH(ipha);
12800 	goto find_sctp_client;
12801 #undef  iphs
12802 #undef  rptr
12803 
12804 error:
12805 	freemsg(first_mp);
12806 slow_done:
12807 	IRE_REFRELE(ire);
12808 }
12809 
12810 #define	VER_BITS	0xF0
12811 #define	VERSION_6	0x60
12812 
12813 static boolean_t
12814 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12815     ipaddr_t *dstp)
12816 {
12817 	uint_t	opt_len;
12818 	ipha_t *ipha;
12819 	ssize_t len;
12820 	uint_t	pkt_len;
12821 
12822 	IP_STAT(ip_ipoptions);
12823 	ipha = *iphapp;
12824 
12825 #define	rptr    ((uchar_t *)ipha)
12826 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12827 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12828 		BUMP_MIB(&ip_mib, ipInIPv6);
12829 		freemsg(mp);
12830 		return (B_FALSE);
12831 	}
12832 
12833 	/* multiple mblk or too short */
12834 	pkt_len = ntohs(ipha->ipha_length);
12835 
12836 	/* Get the number of words of IP options in the IP header. */
12837 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12838 	if (opt_len) {
12839 		/* IP Options present!  Validate and process. */
12840 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12841 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12842 			goto done;
12843 		}
12844 		/*
12845 		 * Recompute complete header length and make sure we
12846 		 * have access to all of it.
12847 		 */
12848 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12849 		if (len > (mp->b_wptr - rptr)) {
12850 			if (len > pkt_len) {
12851 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12852 				goto done;
12853 			}
12854 			if (!pullupmsg(mp, len)) {
12855 				BUMP_MIB(&ip_mib, ipInDiscards);
12856 				goto done;
12857 			}
12858 			ipha = (ipha_t *)mp->b_rptr;
12859 		}
12860 		/*
12861 		 * Go off to ip_rput_options which returns the next hop
12862 		 * destination address, which may have been affected
12863 		 * by source routing.
12864 		 */
12865 		IP_STAT(ip_opt);
12866 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12867 			return (B_FALSE);
12868 		}
12869 	}
12870 	*iphapp = ipha;
12871 	return (B_TRUE);
12872 done:
12873 	/* clear b_prev - used by ip_mroute_decap */
12874 	mp->b_prev = NULL;
12875 	freemsg(mp);
12876 	return (B_FALSE);
12877 #undef  rptr
12878 }
12879 
12880 /*
12881  * Deal with the fact that there is no ire for the destination.
12882  * The incoming ill (in_ill) is passed in to ip_newroute only
12883  * in the case of packets coming from mobile ip forward tunnel.
12884  * It must be null otherwise.
12885  */
12886 static void
12887 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12888     ipaddr_t dst)
12889 {
12890 	ipha_t	*ipha;
12891 	ill_t	*ill;
12892 
12893 	ipha = (ipha_t *)mp->b_rptr;
12894 	ill = (ill_t *)q->q_ptr;
12895 
12896 	ASSERT(ill != NULL);
12897 	/*
12898 	 * No IRE for this destination, so it can't be for us.
12899 	 * Unless we are forwarding, drop the packet.
12900 	 * We have to let source routed packets through
12901 	 * since we don't yet know if they are 'ping -l'
12902 	 * packets i.e. if they will go out over the
12903 	 * same interface as they came in on.
12904 	 */
12905 	if (ll_multicast) {
12906 		freemsg(mp);
12907 		return;
12908 	}
12909 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12910 		BUMP_MIB(&ip_mib, ipForwProhibits);
12911 		freemsg(mp);
12912 		return;
12913 	}
12914 
12915 	/* Check for Martian addresses */
12916 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12917 		freemsg(mp);
12918 		return;
12919 	}
12920 
12921 	/* Mark this packet as having originated externally */
12922 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12923 
12924 	/*
12925 	 * Clear the indication that this may have a hardware checksum
12926 	 * as we are not using it
12927 	 */
12928 	DB_CKSUMFLAGS(mp) = 0;
12929 
12930 	/*
12931 	 * Now hand the packet to ip_newroute.
12932 	 */
12933 	ip_newroute(q, mp, dst, in_ill, NULL);
12934 }
12935 
12936 /*
12937  * check ip header length and align it.
12938  */
12939 static boolean_t
12940 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12941 {
12942 	ssize_t len;
12943 	ill_t *ill;
12944 	ipha_t	*ipha;
12945 
12946 	len = MBLKL(mp);
12947 
12948 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12949 		if (!OK_32PTR(mp->b_rptr))
12950 			IP_STAT(ip_notaligned1);
12951 		else
12952 			IP_STAT(ip_notaligned2);
12953 		/* Guard against bogus device drivers */
12954 		if (len < 0) {
12955 			/* clear b_prev - used by ip_mroute_decap */
12956 			mp->b_prev = NULL;
12957 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12958 			freemsg(mp);
12959 			return (B_FALSE);
12960 		}
12961 
12962 		if (ip_rput_pullups++ == 0) {
12963 			ill = (ill_t *)q->q_ptr;
12964 			ipha = (ipha_t *)mp->b_rptr;
12965 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12966 			    "ip_check_and_align_header: %s forced us to "
12967 			    " pullup pkt, hdr len %ld, hdr addr %p",
12968 			    ill->ill_name, len, ipha);
12969 		}
12970 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12971 			/* clear b_prev - used by ip_mroute_decap */
12972 			mp->b_prev = NULL;
12973 			BUMP_MIB(&ip_mib, ipInDiscards);
12974 			freemsg(mp);
12975 			return (B_FALSE);
12976 		}
12977 	}
12978 	return (B_TRUE);
12979 }
12980 
12981 static boolean_t
12982 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12983 {
12984 	ill_group_t	*ill_group;
12985 	ill_group_t	*ire_group;
12986 	queue_t 	*q;
12987 	ill_t		*ire_ill;
12988 	uint_t		ill_ifindex;
12989 
12990 	q = *qp;
12991 	/*
12992 	 * We need to check to make sure the packet came in
12993 	 * on the queue associated with the destination IRE.
12994 	 * Note that for multicast packets and broadcast packets sent to
12995 	 * a broadcast address which is shared between multiple interfaces
12996 	 * we should not do this since we just got a random broadcast ire.
12997 	 */
12998 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
12999 		boolean_t check_multi = B_TRUE;
13000 
13001 		/*
13002 		 * This packet came in on an interface other than the
13003 		 * one associated with the destination address.
13004 		 * "Gateway" it to the appropriate interface here.
13005 		 * As long as the ills belong to the same group,
13006 		 * we don't consider them to arriving on the wrong
13007 		 * interface. Thus, when the switch is doing inbound
13008 		 * load spreading, we won't drop packets when we
13009 		 * are doing strict multihoming checks. Note, the
13010 		 * same holds true for 'usesrc groups' where the
13011 		 * destination address may belong to another interface
13012 		 * to allow multipathing to happen
13013 		 */
13014 		ill_group = ill->ill_group;
13015 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13016 		ill_ifindex = ill->ill_usesrc_ifindex;
13017 		ire_group = ire_ill->ill_group;
13018 
13019 		/*
13020 		 * If it's part of the same IPMP group, or if it's a legal
13021 		 * address on the 'usesrc' interface, then bypass strict
13022 		 * checks.
13023 		 */
13024 		if (ill_group != NULL && ill_group == ire_group) {
13025 			check_multi = B_FALSE;
13026 		} else if (ill_ifindex != 0 &&
13027 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13028 			check_multi = B_FALSE;
13029 		}
13030 
13031 		if (check_multi &&
13032 		    ip_strict_dst_multihoming &&
13033 		    ((ill->ill_flags &
13034 		    ire->ire_ipif->ipif_ill->ill_flags &
13035 		    ILLF_ROUTER) == 0)) {
13036 			/* Drop packet */
13037 			BUMP_MIB(&ip_mib, ipForwProhibits);
13038 			freemsg(mp);
13039 			ire_refrele(ire);
13040 			return (B_TRUE);
13041 		}
13042 
13043 		/*
13044 		 * Change the queue (for non-virtual destination network
13045 		 * interfaces) and ip_rput_local will be called with the right
13046 		 * queue
13047 		 */
13048 		q = ire->ire_rfq;
13049 	}
13050 	/* Must be broadcast.  We'll take it. */
13051 	*qp = q;
13052 	return (B_FALSE);
13053 }
13054 
13055 static void
13056 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13057     ill_t *ill, int ll_multicast)
13058 {
13059 	ill_group_t	*ill_group;
13060 	ill_group_t	*ire_group;
13061 	queue_t	*dev_q;
13062 
13063 	ASSERT(ire->ire_stq != NULL);
13064 	if (ll_multicast != 0)
13065 		goto drop_pkt;
13066 
13067 	if (ip_no_forward(ipha, ill))
13068 		goto drop_pkt;
13069 
13070 	ill_group = ill->ill_group;
13071 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13072 	/*
13073 	 * Check if we want to forward this one at this time.
13074 	 * We allow source routed packets on a host provided that
13075 	 * they go out the same interface or same interface group
13076 	 * as they came in on.
13077 	 *
13078 	 * XXX To be quicker, we may wish to not chase pointers to
13079 	 * get the ILLF_ROUTER flag and instead store the
13080 	 * forwarding policy in the ire.  An unfortunate
13081 	 * side-effect of that would be requiring an ire flush
13082 	 * whenever the ILLF_ROUTER flag changes.
13083 	 */
13084 	if (((ill->ill_flags &
13085 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13086 	    ILLF_ROUTER) == 0) &&
13087 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13088 	    (ill_group != NULL && ill_group == ire_group)))) {
13089 		BUMP_MIB(&ip_mib, ipForwProhibits);
13090 		if (ip_source_routed(ipha)) {
13091 			q = WR(q);
13092 			/*
13093 			 * Clear the indication that this may have
13094 			 * hardware checksum as we are not using it.
13095 			 */
13096 			DB_CKSUMFLAGS(mp) = 0;
13097 			icmp_unreachable(q, mp,
13098 			    ICMP_SOURCE_ROUTE_FAILED);
13099 			ire_refrele(ire);
13100 			return;
13101 		}
13102 		goto drop_pkt;
13103 	}
13104 
13105 	/* Packet is being forwarded. Turning off hwcksum flag. */
13106 	DB_CKSUMFLAGS(mp) = 0;
13107 	if (ip_g_send_redirects) {
13108 		/*
13109 		 * Check whether the incoming interface and outgoing
13110 		 * interface is part of the same group. If so,
13111 		 * send redirects.
13112 		 *
13113 		 * Check the source address to see if it originated
13114 		 * on the same logical subnet it is going back out on.
13115 		 * If so, we should be able to send it a redirect.
13116 		 * Avoid sending a redirect if the destination
13117 		 * is directly connected (gw_addr == 0),
13118 		 * or if the packet was source routed out this
13119 		 * interface.
13120 		 */
13121 		ipaddr_t src;
13122 		mblk_t	*mp1;
13123 		ire_t	*src_ire = NULL;
13124 
13125 		/*
13126 		 * Check whether ire_rfq and q are from the same ill
13127 		 * or if they are not same, they at least belong
13128 		 * to the same group. If so, send redirects.
13129 		 */
13130 		if ((ire->ire_rfq == q ||
13131 		    (ill_group != NULL && ill_group == ire_group)) &&
13132 		    (ire->ire_gateway_addr != 0) &&
13133 		    !ip_source_routed(ipha)) {
13134 
13135 			src = ipha->ipha_src;
13136 			src_ire = ire_ftable_lookup(src, 0, 0,
13137 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13138 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13139 
13140 			if (src_ire != NULL) {
13141 				/*
13142 				 * The source is directly connected.
13143 				 * Just copy the ip header (which is
13144 				 * in the first mblk)
13145 				 */
13146 				mp1 = copyb(mp);
13147 				if (mp1 != NULL) {
13148 					icmp_send_redirect(WR(q), mp1,
13149 					    ire->ire_gateway_addr);
13150 				}
13151 				ire_refrele(src_ire);
13152 			}
13153 		}
13154 	}
13155 
13156 	dev_q = ire->ire_stq->q_next;
13157 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13158 		BUMP_MIB(&ip_mib, ipInDiscards);
13159 		freemsg(mp);
13160 		ire_refrele(ire);
13161 		return;
13162 	}
13163 
13164 	ip_rput_forward(ire, ipha, mp, ill);
13165 	IRE_REFRELE(ire);
13166 	return;
13167 
13168 drop_pkt:
13169 	ire_refrele(ire);
13170 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13171 	freemsg(mp);
13172 }
13173 
13174 static boolean_t
13175 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
13176     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13177 {
13178 	queue_t		*q;
13179 	ire_t		*ire;
13180 	uint16_t	hcksumflags;
13181 
13182 	q = *qp;
13183 	ire = *irep;
13184 
13185 	/*
13186 	 * Clear the indication that this may have hardware
13187 	 * checksum as we are not using it for forwarding.
13188 	 */
13189 	hcksumflags = DB_CKSUMFLAGS(mp);
13190 	DB_CKSUMFLAGS(mp) = 0;
13191 
13192 	/*
13193 	 * Directed broadcast forwarding: if the packet came in over a
13194 	 * different interface then it is routed out over we can forward it.
13195 	 */
13196 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13197 		ire_refrele(ire);
13198 		freemsg(mp);
13199 		BUMP_MIB(&ip_mib, ipInDiscards);
13200 		return (B_TRUE);
13201 	}
13202 	/*
13203 	 * For multicast we have set dst to be INADDR_BROADCAST
13204 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13205 	 * only for broadcast packets.
13206 	 */
13207 	if (!CLASSD(ipha->ipha_dst)) {
13208 		ire_t *new_ire;
13209 		ipif_t *ipif;
13210 		/*
13211 		 * For ill groups, as the switch duplicates broadcasts
13212 		 * across all the ports, we need to filter out and
13213 		 * send up only one copy. There is one copy for every
13214 		 * broadcast address on each ill. Thus, we look for a
13215 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13216 		 * later to see whether this ill is eligible to receive
13217 		 * them or not. ill_nominate_bcast_rcv() nominates only
13218 		 * one set of IREs for receiving.
13219 		 */
13220 
13221 		ipif = ipif_get_next_ipif(NULL, ill);
13222 		if (ipif == NULL) {
13223 			ire_refrele(ire);
13224 			freemsg(mp);
13225 			BUMP_MIB(&ip_mib, ipInDiscards);
13226 			return (B_TRUE);
13227 		}
13228 		new_ire = ire_ctable_lookup(dst, 0, 0,
13229 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13230 		ipif_refrele(ipif);
13231 
13232 		if (new_ire != NULL) {
13233 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13234 				ire_refrele(ire);
13235 				ire_refrele(new_ire);
13236 				freemsg(mp);
13237 				BUMP_MIB(&ip_mib, ipInDiscards);
13238 				return (B_TRUE);
13239 			}
13240 			/*
13241 			 * In the special case of multirouted broadcast
13242 			 * packets, we unconditionally need to "gateway"
13243 			 * them to the appropriate interface here.
13244 			 * In the normal case, this cannot happen, because
13245 			 * there is no broadcast IRE tagged with the
13246 			 * RTF_MULTIRT flag.
13247 			 */
13248 			if (new_ire->ire_flags & RTF_MULTIRT) {
13249 				ire_refrele(new_ire);
13250 				if (ire->ire_rfq != NULL) {
13251 					q = ire->ire_rfq;
13252 					*qp = q;
13253 				}
13254 			} else {
13255 				ire_refrele(ire);
13256 				ire = new_ire;
13257 			}
13258 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13259 			if (!ip_g_forward_directed_bcast) {
13260 				/*
13261 				 * Free the message if
13262 				 * ip_g_forward_directed_bcast is turned
13263 				 * off for non-local broadcast.
13264 				 */
13265 				ire_refrele(ire);
13266 				freemsg(mp);
13267 				BUMP_MIB(&ip_mib, ipInDiscards);
13268 				return (B_TRUE);
13269 			}
13270 		} else {
13271 			/*
13272 			 * This CGTP packet successfully passed the
13273 			 * CGTP filter, but the related CGTP
13274 			 * broadcast IRE has not been found,
13275 			 * meaning that the redundant ipif is
13276 			 * probably down. However, if we discarded
13277 			 * this packet, its duplicate would be
13278 			 * filtered out by the CGTP filter so none
13279 			 * of them would get through. So we keep
13280 			 * going with this one.
13281 			 */
13282 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13283 			if (ire->ire_rfq != NULL) {
13284 				q = ire->ire_rfq;
13285 				*qp = q;
13286 			}
13287 		}
13288 	}
13289 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13290 		/*
13291 		 * Verify that there are not more then one
13292 		 * IRE_BROADCAST with this broadcast address which
13293 		 * has ire_stq set.
13294 		 * TODO: simplify, loop over all IRE's
13295 		 */
13296 		ire_t	*ire1;
13297 		int	num_stq = 0;
13298 		mblk_t	*mp1;
13299 
13300 		/* Find the first one with ire_stq set */
13301 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13302 		for (ire1 = ire; ire1 &&
13303 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13304 		    ire1 = ire1->ire_next)
13305 			;
13306 		if (ire1) {
13307 			ire_refrele(ire);
13308 			ire = ire1;
13309 			IRE_REFHOLD(ire);
13310 		}
13311 
13312 		/* Check if there are additional ones with stq set */
13313 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13314 			if (ire->ire_addr != ire1->ire_addr)
13315 				break;
13316 			if (ire1->ire_stq) {
13317 				num_stq++;
13318 				break;
13319 			}
13320 		}
13321 		rw_exit(&ire->ire_bucket->irb_lock);
13322 		if (num_stq == 1 && ire->ire_stq != NULL) {
13323 			ip1dbg(("ip_rput_process_broadcast: directed "
13324 			    "broadcast to 0x%x\n",
13325 			    ntohl(ire->ire_addr)));
13326 			mp1 = copymsg(mp);
13327 			if (mp1) {
13328 				switch (ipha->ipha_protocol) {
13329 				case IPPROTO_UDP:
13330 					ip_udp_input(q, mp1, ipha, ire, ill);
13331 					break;
13332 				default:
13333 					ip_proto_input(q, mp1, ipha, ire, ill);
13334 					break;
13335 				}
13336 			}
13337 			/*
13338 			 * Adjust ttl to 2 (1+1 - the forward engine
13339 			 * will decrement it by one.
13340 			 */
13341 			if (ip_csum_hdr(ipha)) {
13342 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13343 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13344 				freemsg(mp);
13345 				ire_refrele(ire);
13346 				return (B_TRUE);
13347 			}
13348 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13349 			ipha->ipha_hdr_checksum = 0;
13350 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13351 			ip_rput_process_forward(q, mp, ire, ipha,
13352 			    ill, ll_multicast);
13353 			return (B_TRUE);
13354 		}
13355 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13356 		    ntohl(ire->ire_addr)));
13357 	}
13358 
13359 	*irep = ire;
13360 
13361 	/* Restore any hardware checksum flags */
13362 	DB_CKSUMFLAGS(mp) = hcksumflags;
13363 	return (B_FALSE);
13364 }
13365 
13366 /* ARGSUSED */
13367 static boolean_t
13368 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13369     int *ll_multicast, ipaddr_t *dstp)
13370 {
13371 	/*
13372 	 * Forward packets only if we have joined the allmulti
13373 	 * group on this interface.
13374 	 */
13375 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13376 		int retval;
13377 
13378 		/*
13379 		 * Clear the indication that this may have hardware
13380 		 * checksum as we are not using it.
13381 		 */
13382 		DB_CKSUMFLAGS(mp) = 0;
13383 		retval = ip_mforward(ill, ipha, mp);
13384 		/* ip_mforward updates mib variables if needed */
13385 		/* clear b_prev - used by ip_mroute_decap */
13386 		mp->b_prev = NULL;
13387 
13388 		switch (retval) {
13389 		case 0:
13390 			/*
13391 			 * pkt is okay and arrived on phyint.
13392 			 *
13393 			 * If we are running as a multicast router
13394 			 * we need to see all IGMP and/or PIM packets.
13395 			 */
13396 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13397 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13398 				goto done;
13399 			}
13400 			break;
13401 		case -1:
13402 			/* pkt is mal-formed, toss it */
13403 			goto drop_pkt;
13404 		case 1:
13405 			/* pkt is okay and arrived on a tunnel */
13406 			/*
13407 			 * If we are running a multicast router
13408 			 *  we need to see all igmp packets.
13409 			 */
13410 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13411 				*dstp = INADDR_BROADCAST;
13412 				*ll_multicast = 1;
13413 				return (B_FALSE);
13414 			}
13415 
13416 			goto drop_pkt;
13417 		}
13418 	}
13419 
13420 	ILM_WALKER_HOLD(ill);
13421 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
13422 		/*
13423 		 * This might just be caused by the fact that
13424 		 * multiple IP Multicast addresses map to the same
13425 		 * link layer multicast - no need to increment counter!
13426 		 */
13427 		ILM_WALKER_RELE(ill);
13428 		freemsg(mp);
13429 		return (B_TRUE);
13430 	}
13431 	ILM_WALKER_RELE(ill);
13432 done:
13433 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
13434 	/*
13435 	 * This assumes the we deliver to all streams for multicast
13436 	 * and broadcast packets.
13437 	 */
13438 	*dstp = INADDR_BROADCAST;
13439 	*ll_multicast = 1;
13440 	return (B_FALSE);
13441 drop_pkt:
13442 	ip2dbg(("ip_rput: drop pkt\n"));
13443 	freemsg(mp);
13444 	return (B_TRUE);
13445 }
13446 
13447 static boolean_t
13448 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
13449     int *ll_multicast, mblk_t **mpp)
13450 {
13451 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
13452 	boolean_t must_copy = B_FALSE;
13453 	struct iocblk   *iocp;
13454 	ipha_t		*ipha;
13455 
13456 #define	rptr    ((uchar_t *)ipha)
13457 
13458 	first_mp = *first_mpp;
13459 	mp = *mpp;
13460 
13461 	ASSERT(first_mp == mp);
13462 
13463 	/*
13464 	 * if db_ref > 1 then copymsg and free original. Packet may be
13465 	 * changed and do not want other entity who has a reference to this
13466 	 * message to trip over the changes. This is a blind change because
13467 	 * trying to catch all places that might change packet is too
13468 	 * difficult (since it may be a module above this one)
13469 	 *
13470 	 * This corresponds to the non-fast path case. We walk down the full
13471 	 * chain in this case, and check the db_ref count of all the dblks,
13472 	 * and do a copymsg if required. It is possible that the db_ref counts
13473 	 * of the data blocks in the mblk chain can be different.
13474 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
13475 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
13476 	 * 'snoop' is running.
13477 	 */
13478 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
13479 		if (mp1->b_datap->db_ref > 1) {
13480 			must_copy = B_TRUE;
13481 			break;
13482 		}
13483 	}
13484 
13485 	if (must_copy) {
13486 		mp1 = copymsg(mp);
13487 		if (mp1 == NULL) {
13488 			for (mp1 = mp; mp1 != NULL;
13489 			    mp1 = mp1->b_cont) {
13490 				mp1->b_next = NULL;
13491 				mp1->b_prev = NULL;
13492 			}
13493 			freemsg(mp);
13494 			BUMP_MIB(&ip_mib, ipInDiscards);
13495 			return (B_TRUE);
13496 		}
13497 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
13498 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
13499 			/* Copy b_next - used in M_BREAK messages */
13500 			to_mp->b_next = from_mp->b_next;
13501 			from_mp->b_next = NULL;
13502 			/* Copy b_prev - used by ip_mroute_decap */
13503 			to_mp->b_prev = from_mp->b_prev;
13504 			from_mp->b_prev = NULL;
13505 		}
13506 		*first_mpp = first_mp = mp1;
13507 		freemsg(mp);
13508 		mp = mp1;
13509 		*mpp = mp1;
13510 	}
13511 
13512 	ipha = (ipha_t *)mp->b_rptr;
13513 
13514 	/*
13515 	 * previous code has a case for M_DATA.
13516 	 * We want to check how that happens.
13517 	 */
13518 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13519 	switch (first_mp->b_datap->db_type) {
13520 	case M_PROTO:
13521 	case M_PCPROTO:
13522 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13523 		    DL_UNITDATA_IND) {
13524 			/* Go handle anything other than data elsewhere. */
13525 			ip_rput_dlpi(q, mp);
13526 			return (B_TRUE);
13527 		}
13528 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13529 		/* Ditch the DLPI header. */
13530 		mp1 = mp->b_cont;
13531 		ASSERT(first_mp == mp);
13532 		*first_mpp = mp1;
13533 		freeb(mp);
13534 		*mpp = mp1;
13535 		return (B_FALSE);
13536 	case M_BREAK:
13537 		/*
13538 		 * A packet arrives as M_BREAK following a cycle through
13539 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13540 		 * This is an IP datagram sans lower level header.
13541 		 * M_BREAK are also used to pass back in multicast packets
13542 		 * that are encapsulated with a source route.
13543 		 */
13544 		/* Ditch the M_BREAK mblk */
13545 		mp1 = mp->b_cont;
13546 		ASSERT(first_mp == mp);
13547 		*first_mpp = mp1;
13548 		freeb(mp);
13549 		mp = mp1;
13550 		mp->b_next = NULL;
13551 		*mpp = mp;
13552 		*ll_multicast = 0;
13553 		return (B_FALSE);
13554 	case M_IOCACK:
13555 		ip1dbg(("got iocack "));
13556 		iocp = (struct iocblk *)mp->b_rptr;
13557 		switch (iocp->ioc_cmd) {
13558 		case DL_IOC_HDR_INFO:
13559 			ill = (ill_t *)q->q_ptr;
13560 			ill_fastpath_ack(ill, mp);
13561 			return (B_TRUE);
13562 		case SIOCSTUNPARAM:
13563 		case OSIOCSTUNPARAM:
13564 			/* Go through qwriter_ip */
13565 			break;
13566 		case SIOCGTUNPARAM:
13567 		case OSIOCGTUNPARAM:
13568 			ip_rput_other(NULL, q, mp, NULL);
13569 			return (B_TRUE);
13570 		default:
13571 			putnext(q, mp);
13572 			return (B_TRUE);
13573 		}
13574 		/* FALLTHRU */
13575 	case M_ERROR:
13576 	case M_HANGUP:
13577 		/*
13578 		 * Since this is on the ill stream we unconditionally
13579 		 * bump up the refcount
13580 		 */
13581 		ill_refhold(ill);
13582 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13583 		    B_FALSE);
13584 		return (B_TRUE);
13585 	case M_CTL:
13586 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13587 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13588 			IPHADA_M_CTL)) {
13589 			/*
13590 			 * It's an IPsec accelerated packet.
13591 			 * Make sure that the ill from which we received the
13592 			 * packet has enabled IPsec hardware acceleration.
13593 			 */
13594 			if (!(ill->ill_capabilities &
13595 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13596 				/* IPsec kstats: bean counter */
13597 				freemsg(mp);
13598 				return (B_TRUE);
13599 			}
13600 
13601 			/*
13602 			 * Make mp point to the mblk following the M_CTL,
13603 			 * then process according to type of mp.
13604 			 * After this processing, first_mp will point to
13605 			 * the data-attributes and mp to the pkt following
13606 			 * the M_CTL.
13607 			 */
13608 			mp = first_mp->b_cont;
13609 			if (mp == NULL) {
13610 				freemsg(first_mp);
13611 				return (B_TRUE);
13612 			}
13613 			/*
13614 			 * A Hardware Accelerated packet can only be M_DATA
13615 			 * ESP or AH packet.
13616 			 */
13617 			if (mp->b_datap->db_type != M_DATA) {
13618 				/* non-M_DATA IPsec accelerated packet */
13619 				IPSECHW_DEBUG(IPSECHW_PKT,
13620 				    ("non-M_DATA IPsec accelerated pkt\n"));
13621 				freemsg(first_mp);
13622 				return (B_TRUE);
13623 			}
13624 			ipha = (ipha_t *)mp->b_rptr;
13625 			if (ipha->ipha_protocol != IPPROTO_AH &&
13626 			    ipha->ipha_protocol != IPPROTO_ESP) {
13627 				IPSECHW_DEBUG(IPSECHW_PKT,
13628 				    ("non-M_DATA IPsec accelerated pkt\n"));
13629 				freemsg(first_mp);
13630 				return (B_TRUE);
13631 			}
13632 			*mpp = mp;
13633 			return (B_FALSE);
13634 		}
13635 		putnext(q, mp);
13636 		return (B_TRUE);
13637 	case M_FLUSH:
13638 		if (*mp->b_rptr & FLUSHW) {
13639 			*mp->b_rptr &= ~FLUSHR;
13640 			qreply(q, mp);
13641 			return (B_TRUE);
13642 		}
13643 		freemsg(mp);
13644 		return (B_TRUE);
13645 	case M_IOCNAK:
13646 		ip1dbg(("got iocnak "));
13647 		iocp = (struct iocblk *)mp->b_rptr;
13648 		switch (iocp->ioc_cmd) {
13649 		case DL_IOC_HDR_INFO:
13650 		case SIOCSTUNPARAM:
13651 		case OSIOCSTUNPARAM:
13652 			/*
13653 			 * Since this is on the ill stream we unconditionally
13654 			 * bump up the refcount
13655 			 */
13656 			ill_refhold(ill);
13657 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13658 			    CUR_OP, B_FALSE);
13659 			return (B_TRUE);
13660 		case SIOCGTUNPARAM:
13661 		case OSIOCGTUNPARAM:
13662 			ip_rput_other(NULL, q, mp, NULL);
13663 			return (B_TRUE);
13664 		default:
13665 			break;
13666 		}
13667 		/* FALLTHRU */
13668 	default:
13669 		putnext(q, mp);
13670 		return (B_TRUE);
13671 	}
13672 }
13673 
13674 /* Read side put procedure.  Packets coming from the wire arrive here. */
13675 void
13676 ip_rput(queue_t *q, mblk_t *mp)
13677 {
13678 	ill_t		*ill;
13679 
13680 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13681 
13682 	ill = (ill_t *)q->q_ptr;
13683 
13684 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13685 		union DL_primitives *dl;
13686 
13687 		/*
13688 		 * Things are opening or closing. Only accept DLPI control
13689 		 * messages. In the open case, the ill->ill_ipif has not yet
13690 		 * been created. In the close case, things hanging off the
13691 		 * ill could have been freed already. In either case it
13692 		 * may not be safe to proceed further.
13693 		 */
13694 
13695 		dl = (union DL_primitives *)mp->b_rptr;
13696 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13697 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13698 			/*
13699 			 * Also SIOC[GS]TUN* ioctls can come here.
13700 			 */
13701 			inet_freemsg(mp);
13702 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13703 			    "ip_input_end: q %p (%S)", q, "uninit");
13704 			return;
13705 		}
13706 	}
13707 
13708 	/*
13709 	 * if db_ref > 1 then copymsg and free original. Packet may be
13710 	 * changed and we do not want the other entity who has a reference to
13711 	 * this message to trip over the changes. This is a blind change because
13712 	 * trying to catch all places that might change the packet is too
13713 	 * difficult.
13714 	 *
13715 	 * This corresponds to the fast path case, where we have a chain of
13716 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13717 	 * in the mblk chain. There doesn't seem to be a reason why a device
13718 	 * driver would send up data with varying db_ref counts in the mblk
13719 	 * chain. In any case the Fast path is a private interface, and our
13720 	 * drivers don't do such a thing. Given the above assumption, there is
13721 	 * no need to walk down the entire mblk chain (which could have a
13722 	 * potential performance problem)
13723 	 */
13724 	if (mp->b_datap->db_ref > 1) {
13725 		mblk_t  *mp1;
13726 		boolean_t adjusted = B_FALSE;
13727 		IP_STAT(ip_db_ref);
13728 
13729 		/*
13730 		 * The IP_RECVSLLA option depends on having the link layer
13731 		 * header. First check that:
13732 		 * a> the underlying device is of type ether, since this
13733 		 * option is currently supported only over ethernet.
13734 		 * b> there is enough room to copy over the link layer header.
13735 		 *
13736 		 * Once the checks are done, adjust rptr so that the link layer
13737 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13738 		 * be returned by some non-ethernet drivers but in this case the
13739 		 * second check will fail.
13740 		 */
13741 		if (ill->ill_type == IFT_ETHER &&
13742 		    (mp->b_rptr - mp->b_datap->db_base) >=
13743 		    sizeof (struct ether_header)) {
13744 			mp->b_rptr -= sizeof (struct ether_header);
13745 			adjusted = B_TRUE;
13746 		}
13747 		mp1 = copymsg(mp);
13748 		if (mp1 == NULL) {
13749 			/* Clear b_next - used in M_BREAK messages */
13750 			mp->b_next = NULL;
13751 			/* clear b_prev - used by ip_mroute_decap */
13752 			mp->b_prev = NULL;
13753 			freemsg(mp);
13754 			BUMP_MIB(&ip_mib, ipInDiscards);
13755 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13756 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13757 			return;
13758 		}
13759 		if (adjusted) {
13760 			/*
13761 			 * Copy is done. Restore the pointer in the _new_ mblk
13762 			 */
13763 			mp1->b_rptr += sizeof (struct ether_header);
13764 		}
13765 		/* Copy b_next - used in M_BREAK messages */
13766 		mp1->b_next = mp->b_next;
13767 		mp->b_next = NULL;
13768 		/* Copy b_prev - used by ip_mroute_decap */
13769 		mp1->b_prev = mp->b_prev;
13770 		mp->b_prev = NULL;
13771 		freemsg(mp);
13772 		mp = mp1;
13773 	}
13774 
13775 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13776 	    "ip_rput_end: q %p (%S)", q, "end");
13777 
13778 	ip_input(ill, NULL, mp, 0);
13779 }
13780 
13781 /*
13782  * Direct read side procedure capable of dealing with chains. GLDv3 based
13783  * drivers call this function directly with mblk chains while STREAMS
13784  * read side procedure ip_rput() calls this for single packet with ip_ring
13785  * set to NULL to process one packet at a time.
13786  *
13787  * The ill will always be valid if this function is called directly from
13788  * the driver.
13789  */
13790 /*ARGSUSED*/
13791 void
13792 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13793 {
13794 	ipaddr_t		dst;
13795 	ire_t			*ire;
13796 	ipha_t			*ipha;
13797 	uint_t			pkt_len;
13798 	ssize_t			len;
13799 	uint_t			opt_len;
13800 	int			ll_multicast;
13801 	int			cgtp_flt_pkt;
13802 	queue_t			*q = ill->ill_rq;
13803 	squeue_t		*curr_sqp = NULL;
13804 	mblk_t 			*head = NULL;
13805 	mblk_t			*tail = NULL;
13806 	mblk_t			*first_mp;
13807 	mblk_t 			*mp;
13808 	int			cnt = 0;
13809 
13810 	ASSERT(mp_chain != NULL);
13811 	ASSERT(ill != NULL);
13812 
13813 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13814 
13815 #define	rptr	((uchar_t *)ipha)
13816 
13817 	while (mp_chain != NULL) {
13818 		first_mp = mp = mp_chain;
13819 		mp_chain = mp_chain->b_next;
13820 		mp->b_next = NULL;
13821 		ll_multicast = 0;
13822 		ire = NULL;
13823 
13824 		/*
13825 		 * ip_input fast path
13826 		 */
13827 
13828 		/* mblk type is not M_DATA */
13829 		if (mp->b_datap->db_type != M_DATA) {
13830 			if (ip_rput_process_notdata(q, &first_mp, ill,
13831 			    &ll_multicast, &mp))
13832 				continue;
13833 		}
13834 
13835 		ASSERT(mp->b_datap->db_type == M_DATA);
13836 		ASSERT(mp->b_datap->db_ref == 1);
13837 
13838 
13839 		ipha = (ipha_t *)mp->b_rptr;
13840 		len = mp->b_wptr - rptr;
13841 
13842 		BUMP_MIB(&ip_mib, ipInReceives);
13843 
13844 		/*
13845 		 * IP header ptr not aligned?
13846 		 * OR IP header not complete in first mblk
13847 		 */
13848 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13849 			if (!ip_check_and_align_header(q, mp))
13850 				continue;
13851 			ipha = (ipha_t *)mp->b_rptr;
13852 			len = mp->b_wptr - rptr;
13853 		}
13854 
13855 		/* multiple mblk or too short */
13856 		pkt_len = ntohs(ipha->ipha_length);
13857 		len -= pkt_len;
13858 		if (len != 0) {
13859 			/*
13860 			 * Make sure we have data length consistent
13861 			 * with the IP header.
13862 			 */
13863 			if (mp->b_cont == NULL) {
13864 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13865 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13866 					ip2dbg(("ip_input: drop pkt\n"));
13867 					freemsg(mp);
13868 					continue;
13869 				}
13870 				mp->b_wptr = rptr + pkt_len;
13871 			} else if (len += msgdsize(mp->b_cont)) {
13872 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13873 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13874 					ip2dbg(("ip_input: drop pkt\n"));
13875 					freemsg(mp);
13876 					continue;
13877 				}
13878 				(void) adjmsg(mp, -len);
13879 				IP_STAT(ip_multimblk3);
13880 			}
13881 		}
13882 
13883 		if (ip_loopback_src_or_dst(ipha, ill)) {
13884 			ip2dbg(("ip_input: drop pkt\n"));
13885 			freemsg(mp);
13886 			continue;
13887 		}
13888 
13889 		/*
13890 		 * Attach any necessary label information to this packet.
13891 		 */
13892 		if (is_system_labeled() &&
13893 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
13894 			BUMP_MIB(&ip_mib, ipInDiscards);
13895 			freemsg(mp);
13896 			continue;
13897 		}
13898 
13899 		opt_len = ipha->ipha_version_and_hdr_length -
13900 		    IP_SIMPLE_HDR_VERSION;
13901 		/* IP version bad or there are IP options */
13902 		if (opt_len) {
13903 			if (len != 0)
13904 				IP_STAT(ip_multimblk4);
13905 			else
13906 				IP_STAT(ip_ipoptions);
13907 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13908 				continue;
13909 		} else {
13910 			dst = ipha->ipha_dst;
13911 		}
13912 
13913 		/*
13914 		 * Invoke the CGTP (multirouting) filtering module to process
13915 		 * the incoming packet. Packets identified as duplicates
13916 		 * must be discarded. Filtering is active only if the
13917 		 * the ip_cgtp_filter ndd variable is non-zero.
13918 		 */
13919 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13920 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13921 			cgtp_flt_pkt =
13922 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
13923 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13924 				freemsg(first_mp);
13925 				continue;
13926 			}
13927 		}
13928 
13929 		/*
13930 		 * If rsvpd is running, let RSVP daemon handle its processing
13931 		 * and forwarding of RSVP multicast/unicast packets.
13932 		 * If rsvpd is not running but mrouted is running, RSVP
13933 		 * multicast packets are forwarded as multicast traffic
13934 		 * and RSVP unicast packets are forwarded by unicast router.
13935 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13936 		 * packets are not forwarded, but the unicast packets are
13937 		 * forwarded like unicast traffic.
13938 		 */
13939 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13940 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13941 			/* RSVP packet and rsvpd running. Treat as ours */
13942 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13943 			/*
13944 			 * This assumes that we deliver to all streams for
13945 			 * multicast and broadcast packets.
13946 			 * We have to force ll_multicast to 1 to handle the
13947 			 * M_DATA messages passed in from ip_mroute_decap.
13948 			 */
13949 			dst = INADDR_BROADCAST;
13950 			ll_multicast = 1;
13951 		} else if (CLASSD(dst)) {
13952 			/* packet is multicast */
13953 			mp->b_next = NULL;
13954 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13955 			    &ll_multicast, &dst))
13956 				continue;
13957 		}
13958 
13959 
13960 		/*
13961 		 * Check if the packet is coming from the Mobile IP
13962 		 * forward tunnel interface
13963 		 */
13964 		if (ill->ill_srcif_refcnt > 0) {
13965 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13966 			    NULL, ill, MATCH_IRE_TYPE);
13967 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13968 			    ire->ire_ipif->ipif_net_type ==
13969 			    IRE_IF_RESOLVER) {
13970 				/* We need to resolve the link layer info */
13971 				ire_refrele(ire);
13972 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13973 				    ll_multicast, dst);
13974 				continue;
13975 			}
13976 		}
13977 
13978 		if (ire == NULL) {
13979 			ire = ire_cache_lookup(dst, ALL_ZONES,
13980 			    MBLK_GETLABEL(mp));
13981 		}
13982 
13983 		/*
13984 		 * If mipagent is running and reverse tunnel is created as per
13985 		 * mobile node request, then any packet coming through the
13986 		 * incoming interface from the mobile-node, should be reverse
13987 		 * tunneled to it's home agent except those that are destined
13988 		 * to foreign agent only.
13989 		 * This needs source address based ire lookup. The routing
13990 		 * entries for source address based lookup are only created by
13991 		 * mipagent program only when a reverse tunnel is created.
13992 		 * Reference : RFC2002, RFC2344
13993 		 */
13994 		if (ill->ill_mrtun_refcnt > 0) {
13995 			ipaddr_t	srcaddr;
13996 			ire_t		*tmp_ire;
13997 
13998 			tmp_ire = ire;	/* Save, we might need it later */
13999 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14000 			    ire->ire_type != IRE_BROADCAST)) {
14001 				srcaddr = ipha->ipha_src;
14002 				ire = ire_mrtun_lookup(srcaddr, ill);
14003 				if (ire != NULL) {
14004 					/*
14005 					 * Should not be getting iphada packet
14006 					 * here. we should only get those for
14007 					 * IRE_LOCAL traffic, excluded above.
14008 					 * Fail-safe (drop packet) in the event
14009 					 * hardware is misbehaving.
14010 					 */
14011 					if (first_mp != mp) {
14012 						/* IPsec KSTATS: beancount me */
14013 						freemsg(first_mp);
14014 					} else {
14015 						/*
14016 						 * This packet must be forwarded
14017 						 * to Reverse Tunnel
14018 						 */
14019 						ip_mrtun_forward(ire, ill, mp);
14020 					}
14021 					ire_refrele(ire);
14022 					if (tmp_ire != NULL)
14023 						ire_refrele(tmp_ire);
14024 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14025 					    "ip_input_end: q %p (%S)",
14026 					    q, "uninit");
14027 					continue;
14028 				}
14029 			}
14030 			/*
14031 			 * If this packet is from a non-mobilenode  or a
14032 			 * mobile-node which does not request reverse
14033 			 * tunnel service
14034 			 */
14035 			ire = tmp_ire;
14036 		}
14037 
14038 
14039 		/*
14040 		 * If we reach here that means the incoming packet satisfies
14041 		 * one of the following conditions:
14042 		 *   - packet is from a mobile node which does not request
14043 		 *	reverse tunnel
14044 		 *   - packet is from a non-mobile node, which is the most
14045 		 *	common case
14046 		 *   - packet is from a reverse tunnel enabled mobile node
14047 		 *	and destined to foreign agent only
14048 		 */
14049 
14050 		if (ire == NULL) {
14051 			/*
14052 			 * No IRE for this destination, so it can't be for us.
14053 			 * Unless we are forwarding, drop the packet.
14054 			 * We have to let source routed packets through
14055 			 * since we don't yet know if they are 'ping -l'
14056 			 * packets i.e. if they will go out over the
14057 			 * same interface as they came in on.
14058 			 */
14059 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14060 			continue;
14061 		}
14062 
14063 		/*
14064 		 * Broadcast IRE may indicate either broadcast or
14065 		 * multicast packet
14066 		 */
14067 		if (ire->ire_type == IRE_BROADCAST) {
14068 			/*
14069 			 * Skip broadcast checks if packet is UDP multicast;
14070 			 * we'd rather not enter ip_rput_process_broadcast()
14071 			 * unless the packet is broadcast for real, since
14072 			 * that routine is a no-op for multicast.
14073 			 */
14074 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
14075 			    !CLASSD(ipha->ipha_dst)) &&
14076 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
14077 			    dst, cgtp_flt_pkt, ll_multicast)) {
14078 				continue;
14079 			}
14080 		} else if (ire->ire_stq != NULL) {
14081 			/* fowarding? */
14082 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14083 			    ll_multicast);
14084 			continue;
14085 		}
14086 
14087 		/* packet not for us */
14088 		if (ire->ire_rfq != q) {
14089 			if (ip_rput_notforus(&q, mp, ire, ill)) {
14090 				continue;
14091 			}
14092 		}
14093 
14094 		switch (ipha->ipha_protocol) {
14095 		case IPPROTO_TCP:
14096 			ASSERT(first_mp == mp);
14097 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14098 				mp, 0, q, ip_ring)) != NULL) {
14099 				if (curr_sqp == NULL) {
14100 					curr_sqp = GET_SQUEUE(mp);
14101 					ASSERT(cnt == 0);
14102 					cnt++;
14103 					head = tail = mp;
14104 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14105 					ASSERT(tail != NULL);
14106 					cnt++;
14107 					tail->b_next = mp;
14108 					tail = mp;
14109 				} else {
14110 					/*
14111 					 * A different squeue. Send the
14112 					 * chain for the previous squeue on
14113 					 * its way. This shouldn't happen
14114 					 * often unless interrupt binding
14115 					 * changes.
14116 					 */
14117 					IP_STAT(ip_input_multi_squeue);
14118 					squeue_enter_chain(curr_sqp, head,
14119 					    tail, cnt, SQTAG_IP_INPUT);
14120 					curr_sqp = GET_SQUEUE(mp);
14121 					head = mp;
14122 					tail = mp;
14123 					cnt = 1;
14124 				}
14125 			}
14126 			IRE_REFRELE(ire);
14127 			continue;
14128 		case IPPROTO_UDP:
14129 			ASSERT(first_mp == mp);
14130 			ip_udp_input(q, mp, ipha, ire, ill);
14131 			IRE_REFRELE(ire);
14132 			continue;
14133 		case IPPROTO_SCTP:
14134 			ASSERT(first_mp == mp);
14135 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14136 			    q, dst);
14137 			continue;
14138 		default:
14139 			ip_proto_input(q, first_mp, ipha, ire, ill);
14140 			IRE_REFRELE(ire);
14141 			continue;
14142 		}
14143 	}
14144 
14145 	if (head != NULL)
14146 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14147 
14148 	/*
14149 	 * This code is there just to make netperf/ttcp look good.
14150 	 *
14151 	 * Its possible that after being in polling mode (and having cleared
14152 	 * the backlog), squeues have turned the interrupt frequency higher
14153 	 * to improve latency at the expense of more CPU utilization (less
14154 	 * packets per interrupts or more number of interrupts). Workloads
14155 	 * like ttcp/netperf do manage to tickle polling once in a while
14156 	 * but for the remaining time, stay in higher interrupt mode since
14157 	 * their packet arrival rate is pretty uniform and this shows up
14158 	 * as higher CPU utilization. Since people care about CPU utilization
14159 	 * while running netperf/ttcp, turn the interrupt frequency back to
14160 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14161 	 */
14162 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14163 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14164 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14165 			ip_ring->rr_blank(ip_ring->rr_handle,
14166 			    ip_ring->rr_normal_blank_time,
14167 			    ip_ring->rr_normal_pkt_cnt);
14168 		}
14169 	}
14170 
14171 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14172 	    "ip_input_end: q %p (%S)", q, "end");
14173 #undef	rptr
14174 }
14175 
14176 static void
14177 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14178     t_uscalar_t err)
14179 {
14180 	if (dl_err == DL_SYSERR) {
14181 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14182 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14183 		    ill->ill_name, dlpi_prim_str(prim), err);
14184 		return;
14185 	}
14186 
14187 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14188 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14189 	    dlpi_err_str(dl_err));
14190 }
14191 
14192 /*
14193  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14194  * than DL_UNITDATA_IND messages. If we need to process this message
14195  * exclusively, we call qwriter_ip, in which case we also need to call
14196  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14197  */
14198 void
14199 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14200 {
14201 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14202 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14203 	ill_t		*ill;
14204 
14205 	ip1dbg(("ip_rput_dlpi"));
14206 	ill = (ill_t *)q->q_ptr;
14207 	switch (dloa->dl_primitive) {
14208 	case DL_ERROR_ACK:
14209 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14210 		    "%s (0x%x), unix %u\n", ill->ill_name,
14211 		    dlpi_prim_str(dlea->dl_error_primitive),
14212 		    dlea->dl_error_primitive,
14213 		    dlpi_err_str(dlea->dl_errno),
14214 		    dlea->dl_errno,
14215 		    dlea->dl_unix_errno));
14216 		switch (dlea->dl_error_primitive) {
14217 		case DL_UNBIND_REQ:
14218 			mutex_enter(&ill->ill_lock);
14219 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14220 			cv_signal(&ill->ill_cv);
14221 			mutex_exit(&ill->ill_lock);
14222 			/* FALLTHRU */
14223 		case DL_NOTIFY_REQ:
14224 		case DL_ATTACH_REQ:
14225 		case DL_DETACH_REQ:
14226 		case DL_INFO_REQ:
14227 		case DL_BIND_REQ:
14228 		case DL_ENABMULTI_REQ:
14229 		case DL_PHYS_ADDR_REQ:
14230 		case DL_CAPABILITY_REQ:
14231 		case DL_CONTROL_REQ:
14232 			/*
14233 			 * Refhold the ill to match qwriter_ip which does a
14234 			 * refrele. Since this is on the ill stream we
14235 			 * unconditionally bump up the refcount without
14236 			 * checking for ILL_CAN_LOOKUP
14237 			 */
14238 			ill_refhold(ill);
14239 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14240 			    CUR_OP, B_FALSE);
14241 			return;
14242 		case DL_DISABMULTI_REQ:
14243 			freemsg(mp);	/* Don't want to pass this up */
14244 			return;
14245 		default:
14246 			break;
14247 		}
14248 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14249 		    dlea->dl_errno, dlea->dl_unix_errno);
14250 		freemsg(mp);
14251 		return;
14252 	case DL_INFO_ACK:
14253 	case DL_BIND_ACK:
14254 	case DL_PHYS_ADDR_ACK:
14255 	case DL_NOTIFY_ACK:
14256 	case DL_CAPABILITY_ACK:
14257 	case DL_CONTROL_ACK:
14258 		/*
14259 		 * Refhold the ill to match qwriter_ip which does a refrele
14260 		 * Since this is on the ill stream we unconditionally
14261 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14262 		 */
14263 		ill_refhold(ill);
14264 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14265 		    CUR_OP, B_FALSE);
14266 		return;
14267 	case DL_NOTIFY_IND:
14268 		ill_refhold(ill);
14269 		/*
14270 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14271 		 * relation to the current ioctl in progress (if any). Hence we
14272 		 * pass in NEW_OP in this case.
14273 		 */
14274 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14275 		    NEW_OP, B_FALSE);
14276 		return;
14277 	case DL_OK_ACK:
14278 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14279 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14280 		switch (dloa->dl_correct_primitive) {
14281 		case DL_UNBIND_REQ:
14282 			mutex_enter(&ill->ill_lock);
14283 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14284 			cv_signal(&ill->ill_cv);
14285 			mutex_exit(&ill->ill_lock);
14286 			/* FALLTHRU */
14287 		case DL_ATTACH_REQ:
14288 		case DL_DETACH_REQ:
14289 			/*
14290 			 * Refhold the ill to match qwriter_ip which does a
14291 			 * refrele. Since this is on the ill stream we
14292 			 * unconditionally bump up the refcount
14293 			 */
14294 			ill_refhold(ill);
14295 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14296 			    CUR_OP, B_FALSE);
14297 			return;
14298 		case DL_ENABMULTI_REQ:
14299 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14300 				ill->ill_dlpi_multicast_state = IDMS_OK;
14301 			break;
14302 
14303 		}
14304 		break;
14305 	default:
14306 		break;
14307 	}
14308 	freemsg(mp);
14309 }
14310 
14311 /*
14312  * Handling of DLPI messages that require exclusive access to the ipsq.
14313  *
14314  * Need to do ill_pending_mp_release on ioctl completion, which could
14315  * happen here. (along with mi_copy_done)
14316  */
14317 /* ARGSUSED */
14318 static void
14319 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14320 {
14321 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14322 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14323 	int		err = 0;
14324 	ill_t		*ill;
14325 	ipif_t		*ipif = NULL;
14326 	mblk_t		*mp1 = NULL;
14327 	conn_t		*connp = NULL;
14328 	t_uscalar_t	physaddr_req;
14329 	mblk_t		*mp_hw;
14330 	union DL_primitives *dlp;
14331 	boolean_t	success;
14332 	boolean_t	ioctl_aborted = B_FALSE;
14333 	boolean_t	log = B_TRUE;
14334 
14335 	ip1dbg(("ip_rput_dlpi_writer .."));
14336 	ill = (ill_t *)q->q_ptr;
14337 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14338 
14339 	ASSERT(IAM_WRITER_ILL(ill));
14340 
14341 	/*
14342 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14343 	 * both are null or non-null. However we can assert that only
14344 	 * after grabbing the ipsq_lock. So we don't make any assertion
14345 	 * here and in other places in the code.
14346 	 */
14347 	ipif = ipsq->ipsq_pending_ipif;
14348 	/*
14349 	 * The current ioctl could have been aborted by the user and a new
14350 	 * ioctl to bring up another ill could have started. We could still
14351 	 * get a response from the driver later.
14352 	 */
14353 	if (ipif != NULL && ipif->ipif_ill != ill)
14354 		ioctl_aborted = B_TRUE;
14355 
14356 	switch (dloa->dl_primitive) {
14357 	case DL_ERROR_ACK:
14358 		switch (dlea->dl_error_primitive) {
14359 		case DL_UNBIND_REQ:
14360 		case DL_ATTACH_REQ:
14361 		case DL_DETACH_REQ:
14362 		case DL_INFO_REQ:
14363 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14364 			break;
14365 		case DL_NOTIFY_REQ:
14366 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
14367 			log = B_FALSE;
14368 			break;
14369 		case DL_PHYS_ADDR_REQ:
14370 			/*
14371 			 * For IPv6 only, there are two additional
14372 			 * phys_addr_req's sent to the driver to get the
14373 			 * IPv6 token and lla. This allows IP to acquire
14374 			 * the hardware address format for a given interface
14375 			 * without having built in knowledge of the hardware
14376 			 * address. ill_phys_addr_pend keeps track of the last
14377 			 * DL_PAR sent so we know which response we are
14378 			 * dealing with. ill_dlpi_done will update
14379 			 * ill_phys_addr_pend when it sends the next req.
14380 			 * We don't complete the IOCTL until all three DL_PARs
14381 			 * have been attempted, so set *_len to 0 and break.
14382 			 */
14383 			physaddr_req = ill->ill_phys_addr_pend;
14384 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14385 			if (physaddr_req == DL_IPV6_TOKEN) {
14386 				ill->ill_token_length = 0;
14387 				log = B_FALSE;
14388 				break;
14389 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14390 				ill->ill_nd_lla_len = 0;
14391 				log = B_FALSE;
14392 				break;
14393 			}
14394 			/*
14395 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
14396 			 * We presumably have an IOCTL hanging out waiting
14397 			 * for completion. Find it and complete the IOCTL
14398 			 * with the error noted.
14399 			 * However, ill_dl_phys was called on an ill queue
14400 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
14401 			 * set. But the ioctl is known to be pending on ill_wq.
14402 			 */
14403 			if (!ill->ill_ifname_pending)
14404 				break;
14405 			ill->ill_ifname_pending = 0;
14406 			if (!ioctl_aborted)
14407 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14408 			if (mp1 != NULL) {
14409 				/*
14410 				 * This operation (SIOCSLIFNAME) must have
14411 				 * happened on the ill. Assert there is no conn
14412 				 */
14413 				ASSERT(connp == NULL);
14414 				q = ill->ill_wq;
14415 			}
14416 			break;
14417 		case DL_BIND_REQ:
14418 			ill_dlpi_done(ill, DL_BIND_REQ);
14419 			if (ill->ill_ifname_pending)
14420 				break;
14421 			/*
14422 			 * Something went wrong with the bind.  We presumably
14423 			 * have an IOCTL hanging out waiting for completion.
14424 			 * Find it, take down the interface that was coming
14425 			 * up, and complete the IOCTL with the error noted.
14426 			 */
14427 			if (!ioctl_aborted)
14428 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14429 			if (mp1 != NULL) {
14430 				/*
14431 				 * This operation (SIOCSLIFFLAGS) must have
14432 				 * happened from a conn.
14433 				 */
14434 				ASSERT(connp != NULL);
14435 				q = CONNP_TO_WQ(connp);
14436 				if (ill->ill_move_in_progress) {
14437 					ILL_CLEAR_MOVE(ill);
14438 				}
14439 				(void) ipif_down(ipif, NULL, NULL);
14440 				/* error is set below the switch */
14441 			}
14442 			break;
14443 		case DL_ENABMULTI_REQ:
14444 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
14445 
14446 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14447 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
14448 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
14449 				ipif_t *ipif;
14450 
14451 				log = B_FALSE;
14452 				printf("ip: joining multicasts failed (%d)"
14453 				    " on %s - will use link layer "
14454 				    "broadcasts for multicast\n",
14455 				    dlea->dl_errno, ill->ill_name);
14456 
14457 				/*
14458 				 * Set up the multicast mapping alone.
14459 				 * writer, so ok to access ill->ill_ipif
14460 				 * without any lock.
14461 				 */
14462 				ipif = ill->ill_ipif;
14463 				mutex_enter(&ill->ill_phyint->phyint_lock);
14464 				ill->ill_phyint->phyint_flags |=
14465 				    PHYI_MULTI_BCAST;
14466 				mutex_exit(&ill->ill_phyint->phyint_lock);
14467 
14468 				if (!ill->ill_isv6) {
14469 					(void) ipif_arp_setup_multicast(ipif,
14470 					    NULL);
14471 				} else {
14472 					(void) ipif_ndp_setup_multicast(ipif,
14473 					    NULL);
14474 				}
14475 			}
14476 			freemsg(mp);	/* Don't want to pass this up */
14477 			return;
14478 		case DL_CAPABILITY_REQ:
14479 		case DL_CONTROL_REQ:
14480 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
14481 			    "DL_CAPABILITY/CONTROL REQ\n"));
14482 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14483 			ill->ill_capab_state = IDMS_FAILED;
14484 			freemsg(mp);
14485 			return;
14486 		}
14487 		/*
14488 		 * Note the error for IOCTL completion (mp1 is set when
14489 		 * ready to complete ioctl). If ill_ifname_pending_err is
14490 		 * set, an error occured during plumbing (ill_ifname_pending),
14491 		 * so we want to report that error.
14492 		 *
14493 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
14494 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
14495 		 * expected to get errack'd if the driver doesn't support
14496 		 * these flags (e.g. ethernet). log will be set to B_FALSE
14497 		 * if these error conditions are encountered.
14498 		 */
14499 		if (mp1 != NULL) {
14500 			if (ill->ill_ifname_pending_err != 0)  {
14501 				err = ill->ill_ifname_pending_err;
14502 				ill->ill_ifname_pending_err = 0;
14503 			} else {
14504 				err = dlea->dl_unix_errno ?
14505 				    dlea->dl_unix_errno : ENXIO;
14506 			}
14507 		/*
14508 		 * If we're plumbing an interface and an error hasn't already
14509 		 * been saved, set ill_ifname_pending_err to the error passed
14510 		 * up. Ignore the error if log is B_FALSE (see comment above).
14511 		 */
14512 		} else if (log && ill->ill_ifname_pending &&
14513 		    ill->ill_ifname_pending_err == 0) {
14514 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
14515 			dlea->dl_unix_errno : ENXIO;
14516 		}
14517 
14518 		if (log)
14519 			ip_dlpi_error(ill, dlea->dl_error_primitive,
14520 			    dlea->dl_errno, dlea->dl_unix_errno);
14521 		break;
14522 	case DL_CAPABILITY_ACK: {
14523 		boolean_t reneg_flag = B_FALSE;
14524 		/* Call a routine to handle this one. */
14525 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
14526 		/*
14527 		 * Check if the ACK is due to renegotiation case since we
14528 		 * will need to send a new CAPABILITY_REQ later.
14529 		 */
14530 		if (ill->ill_capab_state == IDMS_RENEG) {
14531 			/* This is the ack for a renogiation case */
14532 			reneg_flag = B_TRUE;
14533 			ill->ill_capab_state = IDMS_UNKNOWN;
14534 		}
14535 		ill_capability_ack(ill, mp);
14536 		if (reneg_flag)
14537 			ill_capability_probe(ill);
14538 		break;
14539 	}
14540 	case DL_CONTROL_ACK:
14541 		/* We treat all of these as "fire and forget" */
14542 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14543 		break;
14544 	case DL_INFO_ACK:
14545 		/* Call a routine to handle this one. */
14546 		ill_dlpi_done(ill, DL_INFO_REQ);
14547 		ip_ll_subnet_defaults(ill, mp);
14548 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14549 		return;
14550 	case DL_BIND_ACK:
14551 		/*
14552 		 * We should have an IOCTL waiting on this unless
14553 		 * sent by ill_dl_phys, in which case just return
14554 		 */
14555 		ill_dlpi_done(ill, DL_BIND_REQ);
14556 		if (ill->ill_ifname_pending)
14557 			break;
14558 
14559 		if (!ioctl_aborted)
14560 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14561 		if (mp1 == NULL)
14562 			break;
14563 		ASSERT(connp != NULL);
14564 		q = CONNP_TO_WQ(connp);
14565 
14566 		/*
14567 		 * We are exclusive. So nothing can change even after
14568 		 * we get the pending mp. If need be we can put it back
14569 		 * and restart, as in calling ipif_arp_up()  below.
14570 		 */
14571 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14572 
14573 		mutex_enter(&ill->ill_lock);
14574 		ill->ill_dl_up = 1;
14575 		mutex_exit(&ill->ill_lock);
14576 
14577 		/*
14578 		 * Now bring up the resolver, when that is
14579 		 * done we'll create IREs and we are done.
14580 		 */
14581 		if (ill->ill_isv6) {
14582 			/*
14583 			 * v6 interfaces.
14584 			 * Unlike ARP which has to do another bind
14585 			 * and attach, once we get here we are
14586 			 * done withh NDP. Except in the case of
14587 			 * ILLF_XRESOLV, in which case we send an
14588 			 * AR_INTERFACE_UP to the external resolver.
14589 			 * If all goes well, the ioctl will complete
14590 			 * in ip_rput(). If there's an error, we
14591 			 * complete it here.
14592 			 */
14593 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14594 			    B_FALSE);
14595 			if (err == 0) {
14596 				if (ill->ill_flags & ILLF_XRESOLV) {
14597 					mutex_enter(&connp->conn_lock);
14598 					mutex_enter(&ill->ill_lock);
14599 					success = ipsq_pending_mp_add(
14600 					    connp, ipif, q, mp1, 0);
14601 					mutex_exit(&ill->ill_lock);
14602 					mutex_exit(&connp->conn_lock);
14603 					if (success) {
14604 						err = ipif_resolver_up(ipif,
14605 						    B_FALSE);
14606 						if (err == EINPROGRESS) {
14607 							freemsg(mp);
14608 							return;
14609 						}
14610 						ASSERT(err != 0);
14611 						mp1 = ipsq_pending_mp_get(ipsq,
14612 						    &connp);
14613 						ASSERT(mp1 != NULL);
14614 					} else {
14615 						/* conn has started closing */
14616 						err = EINTR;
14617 					}
14618 				} else { /* Non XRESOLV interface */
14619 					err = ipif_up_done_v6(ipif);
14620 				}
14621 			}
14622 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14623 			/*
14624 			 * ARP and other v4 external resolvers.
14625 			 * Leave the pending mblk intact so that
14626 			 * the ioctl completes in ip_rput().
14627 			 */
14628 			mutex_enter(&connp->conn_lock);
14629 			mutex_enter(&ill->ill_lock);
14630 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14631 			mutex_exit(&ill->ill_lock);
14632 			mutex_exit(&connp->conn_lock);
14633 			if (success) {
14634 				err = ipif_resolver_up(ipif, B_FALSE);
14635 				if (err == EINPROGRESS) {
14636 					freemsg(mp);
14637 					return;
14638 				}
14639 				ASSERT(err != 0);
14640 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14641 			} else {
14642 				/* The conn has started closing */
14643 				err = EINTR;
14644 			}
14645 		} else {
14646 			/*
14647 			 * This one is complete. Reply to pending ioctl.
14648 			 */
14649 			err = ipif_up_done(ipif);
14650 		}
14651 
14652 		if ((err == 0) && (ill->ill_up_ipifs)) {
14653 			err = ill_up_ipifs(ill, q, mp1);
14654 			if (err == EINPROGRESS) {
14655 				freemsg(mp);
14656 				return;
14657 			}
14658 		}
14659 
14660 		if (ill->ill_up_ipifs) {
14661 			ill_group_cleanup(ill);
14662 		}
14663 
14664 		break;
14665 	case DL_NOTIFY_IND: {
14666 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14667 		ire_t *ire;
14668 		boolean_t need_ire_walk_v4 = B_FALSE;
14669 		boolean_t need_ire_walk_v6 = B_FALSE;
14670 
14671 		/*
14672 		 * Change the address everywhere we need to.
14673 		 * What we're getting here is a link-level addr or phys addr.
14674 		 * The new addr is at notify + notify->dl_addr_offset
14675 		 * The address length is notify->dl_addr_length;
14676 		 */
14677 		switch (notify->dl_notification) {
14678 		case DL_NOTE_PHYS_ADDR:
14679 			mp_hw = copyb(mp);
14680 			if (mp_hw == NULL) {
14681 				err = ENOMEM;
14682 				break;
14683 			}
14684 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14685 			/*
14686 			 * We currently don't support changing
14687 			 * the token via DL_NOTIFY_IND.
14688 			 * When we do support it, we have to consider
14689 			 * what the implications are with respect to
14690 			 * the token and the link local address.
14691 			 */
14692 			mutex_enter(&ill->ill_lock);
14693 			if (dlp->notify_ind.dl_data ==
14694 			    DL_IPV6_LINK_LAYER_ADDR) {
14695 				if (ill->ill_nd_lla_mp != NULL)
14696 					freemsg(ill->ill_nd_lla_mp);
14697 				ill->ill_nd_lla_mp = mp_hw;
14698 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14699 				    dlp->notify_ind.dl_addr_offset;
14700 				ill->ill_nd_lla_len =
14701 				    dlp->notify_ind.dl_addr_length -
14702 				    ABS(ill->ill_sap_length);
14703 				mutex_exit(&ill->ill_lock);
14704 				break;
14705 			} else if (dlp->notify_ind.dl_data ==
14706 			    DL_CURR_PHYS_ADDR) {
14707 				if (ill->ill_phys_addr_mp != NULL)
14708 					freemsg(ill->ill_phys_addr_mp);
14709 				ill->ill_phys_addr_mp = mp_hw;
14710 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14711 				    dlp->notify_ind.dl_addr_offset;
14712 				ill->ill_phys_addr_length =
14713 				    dlp->notify_ind.dl_addr_length -
14714 				    ABS(ill->ill_sap_length);
14715 				if (ill->ill_isv6 &&
14716 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14717 					if (ill->ill_nd_lla_mp != NULL)
14718 						freemsg(ill->ill_nd_lla_mp);
14719 					ill->ill_nd_lla_mp = copyb(mp_hw);
14720 					ill->ill_nd_lla = (uchar_t *)
14721 					    ill->ill_nd_lla_mp->b_rptr +
14722 					    dlp->notify_ind.dl_addr_offset;
14723 					ill->ill_nd_lla_len =
14724 					    ill->ill_phys_addr_length;
14725 				}
14726 			}
14727 			mutex_exit(&ill->ill_lock);
14728 			/*
14729 			 * Send out gratuitous arp request for our new
14730 			 * hardware address.
14731 			 */
14732 			for (ipif = ill->ill_ipif; ipif != NULL;
14733 			    ipif = ipif->ipif_next) {
14734 				if (!(ipif->ipif_flags & IPIF_UP))
14735 					continue;
14736 				if (ill->ill_isv6) {
14737 					ipif_ndp_down(ipif);
14738 					/*
14739 					 * Set B_TRUE to enable
14740 					 * ipif_ndp_up() to send out
14741 					 * unsolicited advertisements.
14742 					 */
14743 					err = ipif_ndp_up(ipif,
14744 					    &ipif->ipif_v6lcl_addr,
14745 					    B_TRUE);
14746 					if (err) {
14747 						ip1dbg((
14748 						    "ip_rput_dlpi_writer: "
14749 						    "Failed to update ndp "
14750 						    "err %d\n", err));
14751 					}
14752 				} else {
14753 					/*
14754 					 * IPv4 ARP case
14755 					 *
14756 					 * Set B_TRUE, as we only want
14757 					 * ipif_resolver_up to send an
14758 					 * AR_ENTRY_ADD request up to
14759 					 * ARP.
14760 					 */
14761 					err = ipif_resolver_up(ipif,
14762 					    B_TRUE);
14763 					if (err) {
14764 						ip1dbg((
14765 						    "ip_rput_dlpi_writer: "
14766 						    "Failed to update arp "
14767 						    "err %d\n", err));
14768 					}
14769 				}
14770 			}
14771 			/*
14772 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14773 			 * case so that all old fastpath information can be
14774 			 * purged from IRE caches.
14775 			 */
14776 		/* FALLTHRU */
14777 		case DL_NOTE_FASTPATH_FLUSH:
14778 			/*
14779 			 * Any fastpath probe sent henceforth will get the
14780 			 * new fp mp. So we first delete any ires that are
14781 			 * waiting for the fastpath. Then walk all ires and
14782 			 * delete the ire or delete the fp mp. In the case of
14783 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14784 			 * recreate the ire's without going through a complex
14785 			 * ipif up/down dance. So we don't delete the ire
14786 			 * itself, but just the ire_fp_mp for these 2 ire's
14787 			 * In the case of the other ire's we delete the ire's
14788 			 * themselves. Access to ire_fp_mp is completely
14789 			 * protected by ire_lock for IRE_MIPRTUN and
14790 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14791 			 * other cases for performance.
14792 			 */
14793 			if (ill->ill_isv6) {
14794 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14795 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14796 				    NULL);
14797 			} else {
14798 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14799 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14800 				    IRE_CACHE | IRE_BROADCAST,
14801 				    ire_fastpath_flush, NULL, ill);
14802 				mutex_enter(&ire_mrtun_lock);
14803 				if (ire_mrtun_count != 0) {
14804 					mutex_exit(&ire_mrtun_lock);
14805 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14806 					    IRE_MIPRTUN, ire_fastpath_flush,
14807 					    NULL, ill);
14808 				} else {
14809 					mutex_exit(&ire_mrtun_lock);
14810 				}
14811 			}
14812 			break;
14813 		case DL_NOTE_SDU_SIZE:
14814 			/*
14815 			 * Change the MTU size of the interface, of all
14816 			 * attached ipif's, and of all relevant ire's.  The
14817 			 * new value's a uint32_t at notify->dl_data.
14818 			 * Mtu change Vs. new ire creation - protocol below.
14819 			 *
14820 			 * a Mark the ipif as IPIF_CHANGING.
14821 			 * b Set the new mtu in the ipif.
14822 			 * c Change the ire_max_frag on all affected ires
14823 			 * d Unmark the IPIF_CHANGING
14824 			 *
14825 			 * To see how the protocol works, assume an interface
14826 			 * route is also being added simultaneously by
14827 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14828 			 * the ire. If the ire is created before step a,
14829 			 * it will be cleaned up by step c. If the ire is
14830 			 * created after step d, it will see the new value of
14831 			 * ipif_mtu. Any attempt to create the ire between
14832 			 * steps a to d will fail because of the IPIF_CHANGING
14833 			 * flag. Note that ire_create() is passed a pointer to
14834 			 * the ipif_mtu, and not the value. During ire_add
14835 			 * under the bucket lock, the ire_max_frag of the
14836 			 * new ire being created is set from the ipif/ire from
14837 			 * which it is being derived.
14838 			 */
14839 			mutex_enter(&ill->ill_lock);
14840 			ill->ill_max_frag = (uint_t)notify->dl_data;
14841 
14842 			/*
14843 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14844 			 * leave it alone
14845 			 */
14846 			if (ill->ill_mtu_userspecified) {
14847 				mutex_exit(&ill->ill_lock);
14848 				break;
14849 			}
14850 			ill->ill_max_mtu = ill->ill_max_frag;
14851 			if (ill->ill_isv6) {
14852 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14853 					ill->ill_max_mtu = IPV6_MIN_MTU;
14854 			} else {
14855 				if (ill->ill_max_mtu < IP_MIN_MTU)
14856 					ill->ill_max_mtu = IP_MIN_MTU;
14857 			}
14858 			for (ipif = ill->ill_ipif; ipif != NULL;
14859 			    ipif = ipif->ipif_next) {
14860 				/*
14861 				 * Don't override the mtu if the user
14862 				 * has explicitly set it.
14863 				 */
14864 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14865 					continue;
14866 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14867 				if (ipif->ipif_isv6)
14868 					ire = ipif_to_ire_v6(ipif);
14869 				else
14870 					ire = ipif_to_ire(ipif);
14871 				if (ire != NULL) {
14872 					ire->ire_max_frag = ipif->ipif_mtu;
14873 					ire_refrele(ire);
14874 				}
14875 				if (ipif->ipif_flags & IPIF_UP) {
14876 					if (ill->ill_isv6)
14877 						need_ire_walk_v6 = B_TRUE;
14878 					else
14879 						need_ire_walk_v4 = B_TRUE;
14880 				}
14881 			}
14882 			mutex_exit(&ill->ill_lock);
14883 			if (need_ire_walk_v4)
14884 				ire_walk_v4(ill_mtu_change, (char *)ill,
14885 				    ALL_ZONES);
14886 			if (need_ire_walk_v6)
14887 				ire_walk_v6(ill_mtu_change, (char *)ill,
14888 				    ALL_ZONES);
14889 			break;
14890 		case DL_NOTE_LINK_UP:
14891 		case DL_NOTE_LINK_DOWN: {
14892 			/*
14893 			 * We are writer. ill / phyint / ipsq assocs stable.
14894 			 * The RUNNING flag reflects the state of the link.
14895 			 */
14896 			phyint_t *phyint = ill->ill_phyint;
14897 			uint64_t new_phyint_flags;
14898 			boolean_t changed = B_FALSE;
14899 
14900 			mutex_enter(&phyint->phyint_lock);
14901 			new_phyint_flags =
14902 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14903 			    phyint->phyint_flags | PHYI_RUNNING :
14904 			    phyint->phyint_flags & ~PHYI_RUNNING;
14905 			if (new_phyint_flags != phyint->phyint_flags) {
14906 				phyint->phyint_flags = new_phyint_flags;
14907 				changed = B_TRUE;
14908 			}
14909 			mutex_exit(&phyint->phyint_lock);
14910 			/*
14911 			 * If the flags have changed, send a message to
14912 			 * the routing socket.
14913 			 */
14914 			if (changed) {
14915 				if (phyint->phyint_illv4 != NULL) {
14916 					ip_rts_ifmsg(
14917 					    phyint->phyint_illv4->ill_ipif);
14918 				}
14919 				if (phyint->phyint_illv6 != NULL) {
14920 					ip_rts_ifmsg(
14921 					    phyint->phyint_illv6->ill_ipif);
14922 				}
14923 			}
14924 			break;
14925 		}
14926 		case DL_NOTE_PROMISC_ON_PHYS:
14927 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14928 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14929 			mutex_enter(&ill->ill_lock);
14930 			ill->ill_promisc_on_phys = B_TRUE;
14931 			mutex_exit(&ill->ill_lock);
14932 			break;
14933 		case DL_NOTE_PROMISC_OFF_PHYS:
14934 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14935 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14936 			mutex_enter(&ill->ill_lock);
14937 			ill->ill_promisc_on_phys = B_FALSE;
14938 			mutex_exit(&ill->ill_lock);
14939 			break;
14940 		case DL_NOTE_CAPAB_RENEG:
14941 			/*
14942 			 * Something changed on the driver side.
14943 			 * It wants us to renegotiate the capabilities
14944 			 * on this ill. The most likely cause is the
14945 			 * aggregation interface under us where a
14946 			 * port got added or went away.
14947 			 *
14948 			 * We reset the capabilities and set the
14949 			 * state to IDMS_RENG so that when the ack
14950 			 * comes back, we can start the
14951 			 * renegotiation process.
14952 			 */
14953 			ill_capability_reset(ill);
14954 			ill->ill_capab_state = IDMS_RENEG;
14955 			break;
14956 		default:
14957 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14958 			    "type 0x%x for DL_NOTIFY_IND\n",
14959 			    notify->dl_notification));
14960 			break;
14961 		}
14962 
14963 		/*
14964 		 * As this is an asynchronous operation, we
14965 		 * should not call ill_dlpi_done
14966 		 */
14967 		break;
14968 	}
14969 	case DL_NOTIFY_ACK:
14970 		/*
14971 		 * Don't really need to check for what notifications
14972 		 * are supported; we'll process what gets sent upstream,
14973 		 * and we know it'll be something we support changing
14974 		 * based on our DL_NOTIFY_REQ.
14975 		 */
14976 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14977 		break;
14978 	case DL_PHYS_ADDR_ACK: {
14979 		/*
14980 		 * We should have an IOCTL waiting on this when request
14981 		 * sent by ill_dl_phys.
14982 		 * However, ill_dl_phys was called on an ill queue (from
14983 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14984 		 * ioctl is known to be pending on ill_wq.
14985 		 * There are two additional phys_addr_req's sent to the
14986 		 * driver to get the token and lla. ill_phys_addr_pend
14987 		 * keeps track of the last one sent so we know which
14988 		 * response we are dealing with. ill_dlpi_done will
14989 		 * update ill_phys_addr_pend when it sends the next req.
14990 		 * We don't complete the IOCTL until all three DL_PARs
14991 		 * have been attempted.
14992 		 *
14993 		 * We don't need any lock to update ill_nd_lla* fields,
14994 		 * since the ill is not yet up, We grab the lock just
14995 		 * for uniformity with other code that accesses ill_nd_lla.
14996 		 */
14997 		physaddr_req = ill->ill_phys_addr_pend;
14998 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14999 		if (physaddr_req == DL_IPV6_TOKEN ||
15000 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15001 			if (physaddr_req == DL_IPV6_TOKEN) {
15002 				/*
15003 				 * bcopy to low-order bits of ill_token
15004 				 *
15005 				 * XXX Temporary hack - currently,
15006 				 * all known tokens are 64 bits,
15007 				 * so I'll cheat for the moment.
15008 				 */
15009 				dlp = (union DL_primitives *)mp->b_rptr;
15010 
15011 				mutex_enter(&ill->ill_lock);
15012 				bcopy((uchar_t *)(mp->b_rptr +
15013 				dlp->physaddr_ack.dl_addr_offset),
15014 				(void *)&ill->ill_token.s6_addr32[2],
15015 				dlp->physaddr_ack.dl_addr_length);
15016 				ill->ill_token_length =
15017 					dlp->physaddr_ack.dl_addr_length;
15018 				mutex_exit(&ill->ill_lock);
15019 			} else {
15020 				ASSERT(ill->ill_nd_lla_mp == NULL);
15021 				mp_hw = copyb(mp);
15022 				if (mp_hw == NULL) {
15023 					err = ENOMEM;
15024 					break;
15025 				}
15026 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15027 				mutex_enter(&ill->ill_lock);
15028 				ill->ill_nd_lla_mp = mp_hw;
15029 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15030 				dlp->physaddr_ack.dl_addr_offset;
15031 				ill->ill_nd_lla_len =
15032 					dlp->physaddr_ack.dl_addr_length;
15033 				mutex_exit(&ill->ill_lock);
15034 			}
15035 			break;
15036 		}
15037 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15038 		ASSERT(ill->ill_phys_addr_mp == NULL);
15039 		if (!ill->ill_ifname_pending)
15040 			break;
15041 		ill->ill_ifname_pending = 0;
15042 		if (!ioctl_aborted)
15043 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15044 		if (mp1 != NULL) {
15045 			ASSERT(connp == NULL);
15046 			q = ill->ill_wq;
15047 		}
15048 		/*
15049 		 * If any error acks received during the plumbing sequence,
15050 		 * ill_ifname_pending_err will be set. Break out and send up
15051 		 * the error to the pending ioctl.
15052 		 */
15053 		if (ill->ill_ifname_pending_err != 0) {
15054 			err = ill->ill_ifname_pending_err;
15055 			ill->ill_ifname_pending_err = 0;
15056 			break;
15057 		}
15058 		/*
15059 		 * Get the interface token.  If the zeroth interface
15060 		 * address is zero then set the address to the link local
15061 		 * address
15062 		 */
15063 		mp_hw = copyb(mp);
15064 		if (mp_hw == NULL) {
15065 			err = ENOMEM;
15066 			break;
15067 		}
15068 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15069 		ill->ill_phys_addr_mp = mp_hw;
15070 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15071 				dlp->physaddr_ack.dl_addr_offset;
15072 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15073 		    ill->ill_phys_addr_length == 0 ||
15074 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15075 			/*
15076 			 * Compatibility: atun driver returns a length of 0.
15077 			 * ipdptp has an ill_phys_addr_length of zero(from
15078 			 * DL_BIND_ACK) but a non-zero length here.
15079 			 * ipd has an ill_phys_addr_length of 4(from
15080 			 * DL_BIND_ACK) but a non-zero length here.
15081 			 */
15082 			ill->ill_phys_addr = NULL;
15083 		} else if (dlp->physaddr_ack.dl_addr_length !=
15084 		    ill->ill_phys_addr_length) {
15085 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15086 			    "Address length mismatch %d %d\n",
15087 			    dlp->physaddr_ack.dl_addr_length,
15088 			    ill->ill_phys_addr_length));
15089 			err = EINVAL;
15090 			break;
15091 		}
15092 		mutex_enter(&ill->ill_lock);
15093 		if (ill->ill_nd_lla_mp == NULL) {
15094 			ill->ill_nd_lla_mp = copyb(mp_hw);
15095 			if (ill->ill_nd_lla_mp == NULL) {
15096 				err = ENOMEM;
15097 				mutex_exit(&ill->ill_lock);
15098 				break;
15099 			}
15100 			ill->ill_nd_lla =
15101 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15102 			    dlp->physaddr_ack.dl_addr_offset;
15103 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15104 		}
15105 		mutex_exit(&ill->ill_lock);
15106 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15107 			(void) ill_setdefaulttoken(ill);
15108 
15109 		/*
15110 		 * If the ill zero interface has a zero address assign
15111 		 * it the proper link local address.
15112 		 */
15113 		ASSERT(ill->ill_ipif->ipif_id == 0);
15114 		if (ipif != NULL &&
15115 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15116 			(void) ipif_setlinklocal(ipif);
15117 		break;
15118 	}
15119 	case DL_OK_ACK:
15120 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15121 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15122 		    dloa->dl_correct_primitive));
15123 		switch (dloa->dl_correct_primitive) {
15124 		case DL_UNBIND_REQ:
15125 		case DL_ATTACH_REQ:
15126 		case DL_DETACH_REQ:
15127 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15128 			break;
15129 		}
15130 		break;
15131 	default:
15132 		break;
15133 	}
15134 
15135 	freemsg(mp);
15136 	if (mp1) {
15137 		struct iocblk *iocp;
15138 		int mode;
15139 
15140 		/*
15141 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15142 		 * SIOCSLIFNAME do a copyout.
15143 		 */
15144 		iocp = (struct iocblk *)mp1->b_rptr;
15145 
15146 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15147 		    iocp->ioc_cmd == SIOCSLIFNAME)
15148 			mode = COPYOUT;
15149 		else
15150 			mode = NO_COPYOUT;
15151 		/*
15152 		 * The ioctl must complete now without EINPROGRESS
15153 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15154 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15155 		 * stuck for ever in the ipsq.
15156 		 */
15157 		ASSERT(err != EINPROGRESS);
15158 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15159 
15160 	}
15161 }
15162 
15163 /*
15164  * ip_rput_other is called by ip_rput to handle messages modifying the global
15165  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15166  */
15167 /* ARGSUSED */
15168 void
15169 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15170 {
15171 	ill_t		*ill;
15172 	struct iocblk	*iocp;
15173 	mblk_t		*mp1;
15174 	conn_t		*connp = NULL;
15175 
15176 	ip1dbg(("ip_rput_other "));
15177 	ill = (ill_t *)q->q_ptr;
15178 	/*
15179 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15180 	 * in which case ipsq is NULL.
15181 	 */
15182 	if (ipsq != NULL) {
15183 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15184 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15185 	}
15186 
15187 	switch (mp->b_datap->db_type) {
15188 	case M_ERROR:
15189 	case M_HANGUP:
15190 		/*
15191 		 * The device has a problem.  We force the ILL down.  It can
15192 		 * be brought up again manually using SIOCSIFFLAGS (via
15193 		 * ifconfig or equivalent).
15194 		 */
15195 		ASSERT(ipsq != NULL);
15196 		if (mp->b_rptr < mp->b_wptr)
15197 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15198 		if (ill->ill_error == 0)
15199 			ill->ill_error = ENXIO;
15200 		if (!ill_down_start(q, mp))
15201 			return;
15202 		ipif_all_down_tail(ipsq, q, mp, NULL);
15203 		break;
15204 	case M_IOCACK:
15205 		iocp = (struct iocblk *)mp->b_rptr;
15206 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15207 		switch (iocp->ioc_cmd) {
15208 		case SIOCSTUNPARAM:
15209 		case OSIOCSTUNPARAM:
15210 			ASSERT(ipsq != NULL);
15211 			/*
15212 			 * Finish socket ioctl passed through to tun.
15213 			 * We should have an IOCTL waiting on this.
15214 			 */
15215 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15216 			if (ill->ill_isv6) {
15217 				struct iftun_req *ta;
15218 
15219 				/*
15220 				 * if a source or destination is
15221 				 * being set, try and set the link
15222 				 * local address for the tunnel
15223 				 */
15224 				ta = (struct iftun_req *)mp->b_cont->
15225 				    b_cont->b_rptr;
15226 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15227 					ipif_set_tun_llink(ill, ta);
15228 				}
15229 
15230 			}
15231 			if (mp1 != NULL) {
15232 				/*
15233 				 * Now copy back the b_next/b_prev used by
15234 				 * mi code for the mi_copy* functions.
15235 				 * See ip_sioctl_tunparam() for the reason.
15236 				 * Also protect against missing b_cont.
15237 				 */
15238 				if (mp->b_cont != NULL) {
15239 					mp->b_cont->b_next =
15240 					    mp1->b_cont->b_next;
15241 					mp->b_cont->b_prev =
15242 					    mp1->b_cont->b_prev;
15243 				}
15244 				inet_freemsg(mp1);
15245 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15246 				ASSERT(connp != NULL);
15247 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15248 				    iocp->ioc_error, NO_COPYOUT,
15249 				    ipsq->ipsq_current_ipif, ipsq);
15250 			} else {
15251 				ASSERT(connp == NULL);
15252 				putnext(q, mp);
15253 			}
15254 			break;
15255 		case SIOCGTUNPARAM:
15256 		case OSIOCGTUNPARAM:
15257 			/*
15258 			 * This is really M_IOCDATA from the tunnel driver.
15259 			 * convert back and complete the ioctl.
15260 			 * We should have an IOCTL waiting on this.
15261 			 */
15262 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15263 			if (mp1) {
15264 				/*
15265 				 * Now copy back the b_next/b_prev used by
15266 				 * mi code for the mi_copy* functions.
15267 				 * See ip_sioctl_tunparam() for the reason.
15268 				 * Also protect against missing b_cont.
15269 				 */
15270 				if (mp->b_cont != NULL) {
15271 					mp->b_cont->b_next =
15272 					    mp1->b_cont->b_next;
15273 					mp->b_cont->b_prev =
15274 					    mp1->b_cont->b_prev;
15275 				}
15276 				inet_freemsg(mp1);
15277 				if (iocp->ioc_error == 0)
15278 					mp->b_datap->db_type = M_IOCDATA;
15279 				ASSERT(connp != NULL);
15280 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15281 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15282 			} else {
15283 				ASSERT(connp == NULL);
15284 				putnext(q, mp);
15285 			}
15286 			break;
15287 		default:
15288 			break;
15289 		}
15290 		break;
15291 	case M_IOCNAK:
15292 		iocp = (struct iocblk *)mp->b_rptr;
15293 
15294 		switch (iocp->ioc_cmd) {
15295 		int mode;
15296 		ipif_t	*ipif;
15297 
15298 		case DL_IOC_HDR_INFO:
15299 			/*
15300 			 * If this was the first attempt turn of the
15301 			 * fastpath probing.
15302 			 */
15303 			mutex_enter(&ill->ill_lock);
15304 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15305 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15306 				mutex_exit(&ill->ill_lock);
15307 				ill_fastpath_nack(ill);
15308 				ip1dbg(("ip_rput: DLPI fastpath off on "
15309 				    "interface %s\n",
15310 				    ill->ill_name));
15311 			} else {
15312 				mutex_exit(&ill->ill_lock);
15313 			}
15314 			freemsg(mp);
15315 			break;
15316 		case SIOCSTUNPARAM:
15317 		case OSIOCSTUNPARAM:
15318 			ASSERT(ipsq != NULL);
15319 			/*
15320 			 * Finish socket ioctl passed through to tun
15321 			 * We should have an IOCTL waiting on this.
15322 			 */
15323 			/* FALLTHRU */
15324 		case SIOCGTUNPARAM:
15325 		case OSIOCGTUNPARAM:
15326 			/*
15327 			 * This is really M_IOCDATA from the tunnel driver.
15328 			 * convert back and complete the ioctl.
15329 			 * We should have an IOCTL waiting on this.
15330 			 */
15331 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15332 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15333 				mp1 = ill_pending_mp_get(ill, &connp,
15334 				    iocp->ioc_id);
15335 				mode = COPYOUT;
15336 				ipsq = NULL;
15337 				ipif = NULL;
15338 			} else {
15339 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15340 				mode = NO_COPYOUT;
15341 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15342 				ipif = ipsq->ipsq_current_ipif;
15343 			}
15344 			if (mp1 != NULL) {
15345 				/*
15346 				 * Now copy back the b_next/b_prev used by
15347 				 * mi code for the mi_copy* functions.
15348 				 * See ip_sioctl_tunparam() for the reason.
15349 				 * Also protect against missing b_cont.
15350 				 */
15351 				if (mp->b_cont != NULL) {
15352 					mp->b_cont->b_next =
15353 					    mp1->b_cont->b_next;
15354 					mp->b_cont->b_prev =
15355 					    mp1->b_cont->b_prev;
15356 				}
15357 				inet_freemsg(mp1);
15358 				if (iocp->ioc_error == 0)
15359 					iocp->ioc_error = EINVAL;
15360 				ASSERT(connp != NULL);
15361 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15362 				    iocp->ioc_error, mode, ipif, ipsq);
15363 			} else {
15364 				ASSERT(connp == NULL);
15365 				putnext(q, mp);
15366 			}
15367 			break;
15368 		default:
15369 			break;
15370 		}
15371 	default:
15372 		break;
15373 	}
15374 }
15375 
15376 /*
15377  * NOTE : This function does not ire_refrele the ire argument passed in.
15378  *
15379  * IPQoS notes
15380  * IP policy is invoked twice for a forwarded packet, once on the read side
15381  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15382  * enabled. An additional parameter, in_ill, has been added for this purpose.
15383  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15384  * because ip_mroute drops this information.
15385  *
15386  */
15387 void
15388 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15389 {
15390 	uint32_t	pkt_len;
15391 	queue_t	*q;
15392 	uint32_t	sum;
15393 #define	rptr	((uchar_t *)ipha)
15394 	uint32_t	max_frag;
15395 	uint32_t	ill_index;
15396 
15397 	/* Get the ill_index of the incoming ILL */
15398 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15399 
15400 	/* Initiate Read side IPPF processing */
15401 	if (IPP_ENABLED(IPP_FWD_IN)) {
15402 		ip_process(IPP_FWD_IN, &mp, ill_index);
15403 		if (mp == NULL) {
15404 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15405 			    "during IPPF processing\n"));
15406 			return;
15407 		}
15408 	}
15409 	pkt_len = ntohs(ipha->ipha_length);
15410 
15411 	/* Adjust the checksum to reflect the ttl decrement. */
15412 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
15413 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
15414 
15415 	if (ipha->ipha_ttl-- <= 1) {
15416 		if (ip_csum_hdr(ipha)) {
15417 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15418 			goto drop_pkt;
15419 		}
15420 		/*
15421 		 * Note: ire_stq this will be NULL for multicast
15422 		 * datagrams using the long path through arp (the IRE
15423 		 * is not an IRE_CACHE). This should not cause
15424 		 * problems since we don't generate ICMP errors for
15425 		 * multicast packets.
15426 		 */
15427 		q = ire->ire_stq;
15428 		if (q)
15429 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
15430 		else
15431 			freemsg(mp);
15432 		return;
15433 	}
15434 
15435 	/*
15436 	 * Don't forward if the interface is down
15437 	 */
15438 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
15439 		BUMP_MIB(&ip_mib, ipInDiscards);
15440 		goto drop_pkt;
15441 	}
15442 
15443 	/* Get the ill_index of the outgoing ILL */
15444 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
15445 
15446 	if (is_system_labeled()) {
15447 		mblk_t *mp1;
15448 
15449 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
15450 			BUMP_MIB(&ip_mib, ipForwProhibits);
15451 			goto drop_pkt;
15452 		}
15453 		/* Size may have changed */
15454 		mp = mp1;
15455 		ipha = (ipha_t *)mp->b_rptr;
15456 		pkt_len = ntohs(ipha->ipha_length);
15457 	}
15458 
15459 	/* Check if there are options to update */
15460 	if (!IS_SIMPLE_IPH(ipha)) {
15461 		if (ip_csum_hdr(ipha)) {
15462 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15463 			goto drop_pkt;
15464 		}
15465 		if (ip_rput_forward_options(mp, ipha, ire)) {
15466 			return;
15467 		}
15468 
15469 		ipha->ipha_hdr_checksum = 0;
15470 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
15471 	}
15472 	max_frag = ire->ire_max_frag;
15473 	if (pkt_len > max_frag) {
15474 		/*
15475 		 * It needs fragging on its way out.  We haven't
15476 		 * verified the header checksum yet.  Since we
15477 		 * are going to put a surely good checksum in the
15478 		 * outgoing header, we have to make sure that it
15479 		 * was good coming in.
15480 		 */
15481 		if (ip_csum_hdr(ipha)) {
15482 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15483 			goto drop_pkt;
15484 		}
15485 		/* Initiate Write side IPPF processing */
15486 		if (IPP_ENABLED(IPP_FWD_OUT)) {
15487 			ip_process(IPP_FWD_OUT, &mp, ill_index);
15488 			if (mp == NULL) {
15489 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
15490 				    " during IPPF processing\n"));
15491 				return;
15492 			}
15493 		}
15494 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
15495 		return;
15496 	}
15497 
15498 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
15499 	if (mp == NULL) {
15500 		BUMP_MIB(&ip_mib, ipInDiscards);
15501 		return;
15502 	}
15503 
15504 	q = ire->ire_stq;
15505 	UPDATE_IB_PKT_COUNT(ire);
15506 	ire->ire_last_used_time = lbolt;
15507 	BUMP_MIB(&ip_mib, ipForwDatagrams);
15508 	putnext(q, mp);
15509 	return;
15510 
15511 drop_pkt:;
15512 	ip1dbg(("ip_rput_forward: drop pkt\n"));
15513 	freemsg(mp);
15514 #undef	rptr
15515 }
15516 
15517 void
15518 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
15519 {
15520 	ire_t	*ire;
15521 
15522 	ASSERT(!ipif->ipif_isv6);
15523 	/*
15524 	 * Find an IRE which matches the destination and the outgoing
15525 	 * queue in the cache table. All we need is an IRE_CACHE which
15526 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
15527 	 * then it is enough to have some IRE_CACHE in the group.
15528 	 */
15529 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
15530 		dst = ipif->ipif_pp_dst_addr;
15531 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
15532 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
15533 	if (ire == NULL) {
15534 		/*
15535 		 * Mark this packet to make it be delivered to
15536 		 * ip_rput_forward after the new ire has been
15537 		 * created.
15538 		 */
15539 		mp->b_prev = NULL;
15540 		mp->b_next = mp;
15541 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
15542 		    NULL, 0);
15543 	} else {
15544 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
15545 		IRE_REFRELE(ire);
15546 	}
15547 }
15548 
15549 /* Update any source route, record route or timestamp options */
15550 static int
15551 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15552 {
15553 	ipoptp_t	opts;
15554 	uchar_t		*opt;
15555 	uint8_t		optval;
15556 	uint8_t		optlen;
15557 	ipaddr_t	dst;
15558 	uint32_t	ts;
15559 	ire_t		*dst_ire = NULL;
15560 	ire_t		*tmp_ire = NULL;
15561 	timestruc_t	now;
15562 
15563 	ip2dbg(("ip_rput_forward_options\n"));
15564 	dst = ipha->ipha_dst;
15565 	for (optval = ipoptp_first(&opts, ipha);
15566 	    optval != IPOPT_EOL;
15567 	    optval = ipoptp_next(&opts)) {
15568 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15569 		opt = opts.ipoptp_cur;
15570 		optlen = opts.ipoptp_len;
15571 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15572 		    optval, opts.ipoptp_len));
15573 		switch (optval) {
15574 			uint32_t off;
15575 		case IPOPT_SSRR:
15576 		case IPOPT_LSRR:
15577 			/* Check if adminstratively disabled */
15578 			if (!ip_forward_src_routed) {
15579 				BUMP_MIB(&ip_mib, ipForwProhibits);
15580 				if (ire->ire_stq)
15581 					icmp_unreachable(ire->ire_stq, mp,
15582 					    ICMP_SOURCE_ROUTE_FAILED);
15583 				else {
15584 					ip0dbg(("ip_rput_forward_options: "
15585 					    "unable to send unreach\n"));
15586 					freemsg(mp);
15587 				}
15588 				return (-1);
15589 			}
15590 
15591 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15592 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15593 			if (dst_ire == NULL) {
15594 				/*
15595 				 * Must be partial since ip_rput_options
15596 				 * checked for strict.
15597 				 */
15598 				break;
15599 			}
15600 			off = opt[IPOPT_OFFSET];
15601 			off--;
15602 		redo_srr:
15603 			if (optlen < IP_ADDR_LEN ||
15604 			    off > optlen - IP_ADDR_LEN) {
15605 				/* End of source route */
15606 				ip1dbg((
15607 				    "ip_rput_forward_options: end of SR\n"));
15608 				ire_refrele(dst_ire);
15609 				break;
15610 			}
15611 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15612 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15613 			    IP_ADDR_LEN);
15614 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15615 			    ntohl(dst)));
15616 
15617 			/*
15618 			 * Check if our address is present more than
15619 			 * once as consecutive hops in source route.
15620 			 */
15621 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15622 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15623 			if (tmp_ire != NULL) {
15624 				ire_refrele(tmp_ire);
15625 				off += IP_ADDR_LEN;
15626 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15627 				goto redo_srr;
15628 			}
15629 			ipha->ipha_dst = dst;
15630 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15631 			ire_refrele(dst_ire);
15632 			break;
15633 		case IPOPT_RR:
15634 			off = opt[IPOPT_OFFSET];
15635 			off--;
15636 			if (optlen < IP_ADDR_LEN ||
15637 			    off > optlen - IP_ADDR_LEN) {
15638 				/* No more room - ignore */
15639 				ip1dbg((
15640 				    "ip_rput_forward_options: end of RR\n"));
15641 				break;
15642 			}
15643 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15644 			    IP_ADDR_LEN);
15645 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15646 			break;
15647 		case IPOPT_TS:
15648 			/* Insert timestamp if there is room */
15649 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15650 			case IPOPT_TS_TSONLY:
15651 				off = IPOPT_TS_TIMELEN;
15652 				break;
15653 			case IPOPT_TS_PRESPEC:
15654 			case IPOPT_TS_PRESPEC_RFC791:
15655 				/* Verify that the address matched */
15656 				off = opt[IPOPT_OFFSET] - 1;
15657 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15658 				dst_ire = ire_ctable_lookup(dst, 0,
15659 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
15660 				    MATCH_IRE_TYPE);
15661 
15662 				if (dst_ire == NULL) {
15663 					/* Not for us */
15664 					break;
15665 				}
15666 				ire_refrele(dst_ire);
15667 				/* FALLTHRU */
15668 			case IPOPT_TS_TSANDADDR:
15669 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15670 				break;
15671 			default:
15672 				/*
15673 				 * ip_*put_options should have already
15674 				 * dropped this packet.
15675 				 */
15676 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15677 				    "unknown IT - bug in ip_rput_options?\n");
15678 				return (0);	/* Keep "lint" happy */
15679 			}
15680 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15681 				/* Increase overflow counter */
15682 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15683 				opt[IPOPT_POS_OV_FLG] =
15684 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15685 				    (off << 4));
15686 				break;
15687 			}
15688 			off = opt[IPOPT_OFFSET] - 1;
15689 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15690 			case IPOPT_TS_PRESPEC:
15691 			case IPOPT_TS_PRESPEC_RFC791:
15692 			case IPOPT_TS_TSANDADDR:
15693 				bcopy(&ire->ire_src_addr,
15694 				    (char *)opt + off, IP_ADDR_LEN);
15695 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15696 				/* FALLTHRU */
15697 			case IPOPT_TS_TSONLY:
15698 				off = opt[IPOPT_OFFSET] - 1;
15699 				/* Compute # of milliseconds since midnight */
15700 				gethrestime(&now);
15701 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15702 				    now.tv_nsec / (NANOSEC / MILLISEC);
15703 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15704 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15705 				break;
15706 			}
15707 			break;
15708 		}
15709 	}
15710 	return (0);
15711 }
15712 
15713 /*
15714  * This is called after processing at least one of AH/ESP headers.
15715  *
15716  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15717  * the actual, physical interface on which the packet was received,
15718  * but, when ip_strict_dst_multihoming is set to 1, could be the
15719  * interface which had the ipha_dst configured when the packet went
15720  * through ip_rput. The ill_index corresponding to the recv_ill
15721  * is saved in ipsec_in_rill_index
15722  */
15723 void
15724 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15725 {
15726 	mblk_t *mp;
15727 	ipaddr_t dst;
15728 	in6_addr_t *v6dstp;
15729 	ipha_t *ipha;
15730 	ip6_t *ip6h;
15731 	ipsec_in_t *ii;
15732 	boolean_t ill_need_rele = B_FALSE;
15733 	boolean_t rill_need_rele = B_FALSE;
15734 	boolean_t ire_need_rele = B_FALSE;
15735 
15736 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15737 	ASSERT(ii->ipsec_in_ill_index != 0);
15738 
15739 	mp = ipsec_mp->b_cont;
15740 	ASSERT(mp != NULL);
15741 
15742 
15743 	if (ill == NULL) {
15744 		ASSERT(recv_ill == NULL);
15745 		/*
15746 		 * We need to get the original queue on which ip_rput_local
15747 		 * or ip_rput_data_v6 was called.
15748 		 */
15749 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15750 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15751 		ill_need_rele = B_TRUE;
15752 
15753 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15754 			recv_ill = ill_lookup_on_ifindex(
15755 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15756 			    NULL, NULL, NULL, NULL);
15757 			rill_need_rele = B_TRUE;
15758 		} else {
15759 			recv_ill = ill;
15760 		}
15761 
15762 		if ((ill == NULL) || (recv_ill == NULL)) {
15763 			ip0dbg(("ip_fanout_proto_again: interface "
15764 			    "disappeared\n"));
15765 			if (ill != NULL)
15766 				ill_refrele(ill);
15767 			if (recv_ill != NULL)
15768 				ill_refrele(recv_ill);
15769 			freemsg(ipsec_mp);
15770 			return;
15771 		}
15772 	}
15773 
15774 	ASSERT(ill != NULL && recv_ill != NULL);
15775 
15776 	if (mp->b_datap->db_type == M_CTL) {
15777 		/*
15778 		 * AH/ESP is returning the ICMP message after
15779 		 * removing their headers. Fanout again till
15780 		 * it gets to the right protocol.
15781 		 */
15782 		if (ii->ipsec_in_v4) {
15783 			icmph_t *icmph;
15784 			int iph_hdr_length;
15785 			int hdr_length;
15786 
15787 			ipha = (ipha_t *)mp->b_rptr;
15788 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15789 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15790 			ipha = (ipha_t *)&icmph[1];
15791 			hdr_length = IPH_HDR_LENGTH(ipha);
15792 			/*
15793 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15794 			 * Reset the type to M_DATA.
15795 			 */
15796 			mp->b_datap->db_type = M_DATA;
15797 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15798 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15799 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15800 		} else {
15801 			icmp6_t *icmp6;
15802 			int hdr_length;
15803 
15804 			ip6h = (ip6_t *)mp->b_rptr;
15805 			/* Don't call hdr_length_v6() unless you have to. */
15806 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15807 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15808 			else
15809 				hdr_length = IPV6_HDR_LEN;
15810 
15811 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15812 			/*
15813 			 * icmp_inbound_error_fanout_v6 may need to do
15814 			 * pullupmsg.  Reset the type to M_DATA.
15815 			 */
15816 			mp->b_datap->db_type = M_DATA;
15817 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15818 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15819 		}
15820 		if (ill_need_rele)
15821 			ill_refrele(ill);
15822 		if (rill_need_rele)
15823 			ill_refrele(recv_ill);
15824 		return;
15825 	}
15826 
15827 	if (ii->ipsec_in_v4) {
15828 		ipha = (ipha_t *)mp->b_rptr;
15829 		dst = ipha->ipha_dst;
15830 		if (CLASSD(dst)) {
15831 			/*
15832 			 * Multicast has to be delivered to all streams.
15833 			 */
15834 			dst = INADDR_BROADCAST;
15835 		}
15836 
15837 		if (ire == NULL) {
15838 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
15839 			    MBLK_GETLABEL(mp));
15840 			if (ire == NULL) {
15841 				if (ill_need_rele)
15842 					ill_refrele(ill);
15843 				if (rill_need_rele)
15844 					ill_refrele(recv_ill);
15845 				ip1dbg(("ip_fanout_proto_again: "
15846 				    "IRE not found"));
15847 				freemsg(ipsec_mp);
15848 				return;
15849 			}
15850 			ire_need_rele = B_TRUE;
15851 		}
15852 
15853 		switch (ipha->ipha_protocol) {
15854 			case IPPROTO_UDP:
15855 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15856 				    recv_ill);
15857 				if (ire_need_rele)
15858 					ire_refrele(ire);
15859 				break;
15860 			case IPPROTO_TCP:
15861 				if (!ire_need_rele)
15862 					IRE_REFHOLD(ire);
15863 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15864 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15865 				IRE_REFRELE(ire);
15866 				if (mp != NULL)
15867 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15868 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15869 				break;
15870 			case IPPROTO_SCTP:
15871 				if (!ire_need_rele)
15872 					IRE_REFHOLD(ire);
15873 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15874 				    ipsec_mp, 0, ill->ill_rq, dst);
15875 				break;
15876 			default:
15877 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15878 				    recv_ill);
15879 				if (ire_need_rele)
15880 					ire_refrele(ire);
15881 				break;
15882 		}
15883 	} else {
15884 		uint32_t rput_flags = 0;
15885 
15886 		ip6h = (ip6_t *)mp->b_rptr;
15887 		v6dstp = &ip6h->ip6_dst;
15888 		/*
15889 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15890 		 * address.
15891 		 *
15892 		 * Currently, we don't store that state in the IPSEC_IN
15893 		 * message, and we may need to.
15894 		 */
15895 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15896 		    IP6_IN_LLMCAST : 0);
15897 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15898 		    NULL);
15899 	}
15900 	if (ill_need_rele)
15901 		ill_refrele(ill);
15902 	if (rill_need_rele)
15903 		ill_refrele(recv_ill);
15904 }
15905 
15906 /*
15907  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15908  * returns 'true' if there are still fragments left on the queue, in
15909  * which case we restart the timer.
15910  */
15911 void
15912 ill_frag_timer(void *arg)
15913 {
15914 	ill_t	*ill = (ill_t *)arg;
15915 	boolean_t frag_pending;
15916 
15917 	mutex_enter(&ill->ill_lock);
15918 	ASSERT(!ill->ill_fragtimer_executing);
15919 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15920 		ill->ill_frag_timer_id = 0;
15921 		mutex_exit(&ill->ill_lock);
15922 		return;
15923 	}
15924 	ill->ill_fragtimer_executing = 1;
15925 	mutex_exit(&ill->ill_lock);
15926 
15927 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15928 
15929 	/*
15930 	 * Restart the timer, if we have fragments pending or if someone
15931 	 * wanted us to be scheduled again.
15932 	 */
15933 	mutex_enter(&ill->ill_lock);
15934 	ill->ill_fragtimer_executing = 0;
15935 	ill->ill_frag_timer_id = 0;
15936 	if (frag_pending || ill->ill_fragtimer_needrestart)
15937 		ill_frag_timer_start(ill);
15938 	mutex_exit(&ill->ill_lock);
15939 }
15940 
15941 void
15942 ill_frag_timer_start(ill_t *ill)
15943 {
15944 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15945 
15946 	/* If the ill is closing or opening don't proceed */
15947 	if (ill->ill_state_flags & ILL_CONDEMNED)
15948 		return;
15949 
15950 	if (ill->ill_fragtimer_executing) {
15951 		/*
15952 		 * ill_frag_timer is currently executing. Just record the
15953 		 * the fact that we want the timer to be restarted.
15954 		 * ill_frag_timer will post a timeout before it returns,
15955 		 * ensuring it will be called again.
15956 		 */
15957 		ill->ill_fragtimer_needrestart = 1;
15958 		return;
15959 	}
15960 
15961 	if (ill->ill_frag_timer_id == 0) {
15962 		/*
15963 		 * The timer is neither running nor is the timeout handler
15964 		 * executing. Post a timeout so that ill_frag_timer will be
15965 		 * called
15966 		 */
15967 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15968 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15969 		ill->ill_fragtimer_needrestart = 0;
15970 	}
15971 }
15972 
15973 /*
15974  * This routine is needed for loopback when forwarding multicasts.
15975  *
15976  * IPQoS Notes:
15977  * IPPF processing is done in fanout routines.
15978  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15979  * processing for IPSec packets is done when it comes back in clear.
15980  * NOTE : The callers of this function need to do the ire_refrele for the
15981  *	  ire that is being passed in.
15982  */
15983 void
15984 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15985     ill_t *recv_ill)
15986 {
15987 	ill_t	*ill = (ill_t *)q->q_ptr;
15988 	uint32_t	sum;
15989 	uint32_t	u1;
15990 	uint32_t	u2;
15991 	int		hdr_length;
15992 	boolean_t	mctl_present;
15993 	mblk_t		*first_mp = mp;
15994 	mblk_t		*hada_mp = NULL;
15995 	ipha_t		*inner_ipha;
15996 
15997 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
15998 	    "ip_rput_locl_start: q %p", q);
15999 
16000 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16001 
16002 
16003 #define	rptr	((uchar_t *)ipha)
16004 #define	iphs	((uint16_t *)ipha)
16005 
16006 	/*
16007 	 * no UDP or TCP packet should come here anymore.
16008 	 */
16009 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16010 	    (ipha->ipha_protocol != IPPROTO_UDP));
16011 
16012 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16013 	if (mctl_present &&
16014 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16015 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16016 
16017 		/*
16018 		 * It's an IPsec accelerated packet.
16019 		 * Keep a pointer to the data attributes around until
16020 		 * we allocate the ipsec_info_t.
16021 		 */
16022 		IPSECHW_DEBUG(IPSECHW_PKT,
16023 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16024 		hada_mp = first_mp;
16025 		hada_mp->b_cont = NULL;
16026 		/*
16027 		 * Since it is accelerated, it comes directly from
16028 		 * the ill and the data attributes is followed by
16029 		 * the packet data.
16030 		 */
16031 		ASSERT(mp->b_datap->db_type != M_CTL);
16032 		first_mp = mp;
16033 		mctl_present = B_FALSE;
16034 	}
16035 
16036 	/*
16037 	 * IF M_CTL is not present, then ipsec_in_is_secure
16038 	 * should return B_TRUE. There is a case where loopback
16039 	 * packets has an M_CTL in the front with all the
16040 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16041 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16042 	 * packets never comes here, it is safe to ASSERT the
16043 	 * following.
16044 	 */
16045 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16046 
16047 
16048 	/* u1 is # words of IP options */
16049 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16050 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16051 
16052 	if (u1) {
16053 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16054 			if (hada_mp != NULL)
16055 				freemsg(hada_mp);
16056 			return;
16057 		}
16058 	} else {
16059 		/* Check the IP header checksum.  */
16060 #define	uph	((uint16_t *)ipha)
16061 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16062 		    uph[6] + uph[7] + uph[8] + uph[9];
16063 #undef  uph
16064 		/* finish doing IP checksum */
16065 		sum = (sum & 0xFFFF) + (sum >> 16);
16066 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16067 		/*
16068 		 * Don't verify header checksum if this packet is coming
16069 		 * back from AH/ESP as we already did it.
16070 		 */
16071 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16072 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16073 			goto drop_pkt;
16074 		}
16075 	}
16076 
16077 	/*
16078 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16079 	 * might be called more than once for secure packets, count only
16080 	 * the first time.
16081 	 */
16082 	if (!mctl_present) {
16083 		UPDATE_IB_PKT_COUNT(ire);
16084 		ire->ire_last_used_time = lbolt;
16085 	}
16086 
16087 	/* Check for fragmentation offset. */
16088 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16089 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16090 	if (u1) {
16091 		/*
16092 		 * We re-assemble fragments before we do the AH/ESP
16093 		 * processing. Thus, M_CTL should not be present
16094 		 * while we are re-assembling.
16095 		 */
16096 		ASSERT(!mctl_present);
16097 		ASSERT(first_mp == mp);
16098 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16099 			return;
16100 		}
16101 		/*
16102 		 * Make sure that first_mp points back to mp as
16103 		 * the mp we came in with could have changed in
16104 		 * ip_rput_fragment().
16105 		 */
16106 		ipha = (ipha_t *)mp->b_rptr;
16107 		first_mp = mp;
16108 	}
16109 
16110 	/*
16111 	 * Clear hardware checksumming flag as it is currently only
16112 	 * used by TCP and UDP.
16113 	 */
16114 	DB_CKSUMFLAGS(mp) = 0;
16115 
16116 	/* Now we have a complete datagram, destined for this machine. */
16117 	u1 = IPH_HDR_LENGTH(ipha);
16118 	switch (ipha->ipha_protocol) {
16119 	case IPPROTO_ICMP: {
16120 		ire_t		*ire_zone;
16121 		ilm_t		*ilm;
16122 		mblk_t		*mp1;
16123 		zoneid_t	last_zoneid;
16124 
16125 		if (CLASSD(ipha->ipha_dst) &&
16126 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16127 			ASSERT(ire->ire_type == IRE_BROADCAST);
16128 			/*
16129 			 * In the multicast case, applications may have joined
16130 			 * the group from different zones, so we need to deliver
16131 			 * the packet to each of them. Loop through the
16132 			 * multicast memberships structures (ilm) on the receive
16133 			 * ill and send a copy of the packet up each matching
16134 			 * one. However, we don't do this for multicasts sent on
16135 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16136 			 * they must stay in the sender's zone.
16137 			 *
16138 			 * ilm_add_v6() ensures that ilms in the same zone are
16139 			 * contiguous in the ill_ilm list. We use this property
16140 			 * to avoid sending duplicates needed when two
16141 			 * applications in the same zone join the same group on
16142 			 * different logical interfaces: we ignore the ilm if
16143 			 * its zoneid is the same as the last matching one.
16144 			 * In addition, the sending of the packet for
16145 			 * ire_zoneid is delayed until all of the other ilms
16146 			 * have been exhausted.
16147 			 */
16148 			last_zoneid = -1;
16149 			ILM_WALKER_HOLD(recv_ill);
16150 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16151 			    ilm = ilm->ilm_next) {
16152 				if ((ilm->ilm_flags & ILM_DELETED) ||
16153 				    ipha->ipha_dst != ilm->ilm_addr ||
16154 				    ilm->ilm_zoneid == last_zoneid ||
16155 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16156 				    ilm->ilm_zoneid == ALL_ZONES ||
16157 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16158 					continue;
16159 				mp1 = ip_copymsg(first_mp);
16160 				if (mp1 == NULL)
16161 					continue;
16162 				icmp_inbound(q, mp1, B_TRUE, ill,
16163 				    0, sum, mctl_present, B_TRUE,
16164 				    recv_ill, ilm->ilm_zoneid);
16165 				last_zoneid = ilm->ilm_zoneid;
16166 			}
16167 			ILM_WALKER_RELE(recv_ill);
16168 		} else if (ire->ire_type == IRE_BROADCAST) {
16169 			/*
16170 			 * In the broadcast case, there may be many zones
16171 			 * which need a copy of the packet delivered to them.
16172 			 * There is one IRE_BROADCAST per broadcast address
16173 			 * and per zone; we walk those using a helper function.
16174 			 * In addition, the sending of the packet for ire is
16175 			 * delayed until all of the other ires have been
16176 			 * processed.
16177 			 */
16178 			IRB_REFHOLD(ire->ire_bucket);
16179 			ire_zone = NULL;
16180 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16181 			    ire)) != NULL) {
16182 				mp1 = ip_copymsg(first_mp);
16183 				if (mp1 == NULL)
16184 					continue;
16185 
16186 				UPDATE_IB_PKT_COUNT(ire_zone);
16187 				ire_zone->ire_last_used_time = lbolt;
16188 				icmp_inbound(q, mp1, B_TRUE, ill,
16189 				    0, sum, mctl_present, B_TRUE,
16190 				    recv_ill, ire_zone->ire_zoneid);
16191 			}
16192 			IRB_REFRELE(ire->ire_bucket);
16193 		}
16194 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16195 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16196 		    ire->ire_zoneid);
16197 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16198 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16199 		return;
16200 	}
16201 	case IPPROTO_IGMP:
16202 		/*
16203 		 * If we are not willing to accept IGMP packets in clear,
16204 		 * then check with global policy.
16205 		 */
16206 		if (igmp_accept_clear_messages == 0) {
16207 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16208 			    ipha, NULL, mctl_present);
16209 			if (first_mp == NULL)
16210 				return;
16211 		}
16212 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16213 			freemsg(first_mp);
16214 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16215 			BUMP_MIB(&ip_mib, ipInDiscards);
16216 			return;
16217 		}
16218 		if (igmp_input(q, mp, ill)) {
16219 			/* Bad packet - discarded by igmp_input */
16220 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16221 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16222 			if (mctl_present)
16223 				freeb(first_mp);
16224 			return;
16225 		}
16226 		/*
16227 		 * igmp_input() may have pulled up the message so ipha needs to
16228 		 * be reinitialized.
16229 		 */
16230 		ipha = (ipha_t *)mp->b_rptr;
16231 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16232 			/* No user-level listener for IGMP packets */
16233 			goto drop_pkt;
16234 		}
16235 		/* deliver to local raw users */
16236 		break;
16237 	case IPPROTO_PIM:
16238 		/*
16239 		 * If we are not willing to accept PIM packets in clear,
16240 		 * then check with global policy.
16241 		 */
16242 		if (pim_accept_clear_messages == 0) {
16243 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16244 			    ipha, NULL, mctl_present);
16245 			if (first_mp == NULL)
16246 				return;
16247 		}
16248 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16249 			freemsg(first_mp);
16250 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16251 			BUMP_MIB(&ip_mib, ipInDiscards);
16252 			return;
16253 		}
16254 		if (pim_input(q, mp) != 0) {
16255 			/* Bad packet - discarded by pim_input */
16256 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16257 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16258 			if (mctl_present)
16259 				freeb(first_mp);
16260 			return;
16261 		}
16262 
16263 		/*
16264 		 * pim_input() may have pulled up the message so ipha needs to
16265 		 * be reinitialized.
16266 		 */
16267 		ipha = (ipha_t *)mp->b_rptr;
16268 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16269 			/* No user-level listener for PIM packets */
16270 			goto drop_pkt;
16271 		}
16272 		/* deliver to local raw users */
16273 		break;
16274 	case IPPROTO_ENCAP:
16275 		/*
16276 		 * Handle self-encapsulated packets (IP-in-IP where
16277 		 * the inner addresses == the outer addresses).
16278 		 */
16279 		hdr_length = IPH_HDR_LENGTH(ipha);
16280 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16281 		    mp->b_wptr) {
16282 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16283 			    sizeof (ipha_t) - mp->b_rptr)) {
16284 				BUMP_MIB(&ip_mib, ipInDiscards);
16285 				freemsg(first_mp);
16286 				return;
16287 			}
16288 			ipha = (ipha_t *)mp->b_rptr;
16289 		}
16290 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16291 		/*
16292 		 * Check the sanity of the inner IP header.
16293 		 */
16294 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16295 			BUMP_MIB(&ip_mib, ipInDiscards);
16296 			freemsg(first_mp);
16297 			return;
16298 		}
16299 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16300 			BUMP_MIB(&ip_mib, ipInDiscards);
16301 			freemsg(first_mp);
16302 			return;
16303 		}
16304 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16305 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16306 			ipsec_in_t *ii;
16307 
16308 			/*
16309 			 * Self-encapsulated tunnel packet. Remove
16310 			 * the outer IP header and fanout again.
16311 			 * We also need to make sure that the inner
16312 			 * header is pulled up until options.
16313 			 */
16314 			mp->b_rptr = (uchar_t *)inner_ipha;
16315 			ipha = inner_ipha;
16316 			hdr_length = IPH_HDR_LENGTH(ipha);
16317 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16318 				if (!pullupmsg(mp, (uchar_t *)ipha +
16319 				    + hdr_length - mp->b_rptr)) {
16320 					freemsg(first_mp);
16321 					return;
16322 				}
16323 				ipha = (ipha_t *)mp->b_rptr;
16324 			}
16325 			if (!mctl_present) {
16326 				ASSERT(first_mp == mp);
16327 				/*
16328 				 * This means that somebody is sending
16329 				 * Self-encapsualted packets without AH/ESP.
16330 				 * If AH/ESP was present, we would have already
16331 				 * allocated the first_mp.
16332 				 */
16333 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16334 				    NULL) {
16335 					ip1dbg(("ip_proto_input: IPSEC_IN "
16336 					    "allocation failure.\n"));
16337 					BUMP_MIB(&ip_mib, ipInDiscards);
16338 					freemsg(mp);
16339 					return;
16340 				}
16341 				first_mp->b_cont = mp;
16342 			}
16343 			/*
16344 			 * We generally store the ill_index if we need to
16345 			 * do IPSEC processing as we lose the ill queue when
16346 			 * we come back. But in this case, we never should
16347 			 * have to store the ill_index here as it should have
16348 			 * been stored previously when we processed the
16349 			 * AH/ESP header in this routine or for non-ipsec
16350 			 * cases, we still have the queue. But for some bad
16351 			 * packets from the wire, we can get to IPSEC after
16352 			 * this and we better store the index for that case.
16353 			 */
16354 			ill = (ill_t *)q->q_ptr;
16355 			ii = (ipsec_in_t *)first_mp->b_rptr;
16356 			ii->ipsec_in_ill_index =
16357 			    ill->ill_phyint->phyint_ifindex;
16358 			ii->ipsec_in_rill_index =
16359 			    recv_ill->ill_phyint->phyint_ifindex;
16360 			if (ii->ipsec_in_decaps) {
16361 				/*
16362 				 * This packet is self-encapsulated multiple
16363 				 * times. We don't want to recurse infinitely.
16364 				 * To keep it simple, drop the packet.
16365 				 */
16366 				BUMP_MIB(&ip_mib, ipInDiscards);
16367 				freemsg(first_mp);
16368 				return;
16369 			}
16370 			ii->ipsec_in_decaps = B_TRUE;
16371 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16372 			return;
16373 		}
16374 		break;
16375 	case IPPROTO_AH:
16376 	case IPPROTO_ESP: {
16377 		/*
16378 		 * Fast path for AH/ESP. If this is the first time
16379 		 * we are sending a datagram to AH/ESP, allocate
16380 		 * a IPSEC_IN message and prepend it. Otherwise,
16381 		 * just fanout.
16382 		 */
16383 
16384 		int ipsec_rc;
16385 		ipsec_in_t *ii;
16386 
16387 		IP_STAT(ipsec_proto_ahesp);
16388 		if (!mctl_present) {
16389 			ASSERT(first_mp == mp);
16390 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16391 				ip1dbg(("ip_proto_input: IPSEC_IN "
16392 				    "allocation failure.\n"));
16393 				freemsg(hada_mp); /* okay ifnull */
16394 				BUMP_MIB(&ip_mib, ipInDiscards);
16395 				freemsg(mp);
16396 				return;
16397 			}
16398 			/*
16399 			 * Store the ill_index so that when we come back
16400 			 * from IPSEC we ride on the same queue.
16401 			 */
16402 			ill = (ill_t *)q->q_ptr;
16403 			ii = (ipsec_in_t *)first_mp->b_rptr;
16404 			ii->ipsec_in_ill_index =
16405 			    ill->ill_phyint->phyint_ifindex;
16406 			ii->ipsec_in_rill_index =
16407 			    recv_ill->ill_phyint->phyint_ifindex;
16408 			first_mp->b_cont = mp;
16409 			/*
16410 			 * Cache hardware acceleration info.
16411 			 */
16412 			if (hada_mp != NULL) {
16413 				IPSECHW_DEBUG(IPSECHW_PKT,
16414 				    ("ip_rput_local: caching data attr.\n"));
16415 				ii->ipsec_in_accelerated = B_TRUE;
16416 				ii->ipsec_in_da = hada_mp;
16417 				hada_mp = NULL;
16418 			}
16419 		} else {
16420 			ii = (ipsec_in_t *)first_mp->b_rptr;
16421 		}
16422 
16423 		if (!ipsec_loaded()) {
16424 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
16425 			    ire->ire_zoneid);
16426 			return;
16427 		}
16428 
16429 		/* select inbound SA and have IPsec process the pkt */
16430 		if (ipha->ipha_protocol == IPPROTO_ESP) {
16431 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
16432 			if (esph == NULL)
16433 				return;
16434 			ASSERT(ii->ipsec_in_esp_sa != NULL);
16435 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
16436 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
16437 			    first_mp, esph);
16438 		} else {
16439 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
16440 			if (ah == NULL)
16441 				return;
16442 			ASSERT(ii->ipsec_in_ah_sa != NULL);
16443 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
16444 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
16445 			    first_mp, ah);
16446 		}
16447 
16448 		switch (ipsec_rc) {
16449 		case IPSEC_STATUS_SUCCESS:
16450 			break;
16451 		case IPSEC_STATUS_FAILED:
16452 			BUMP_MIB(&ip_mib, ipInDiscards);
16453 			/* FALLTHRU */
16454 		case IPSEC_STATUS_PENDING:
16455 			return;
16456 		}
16457 		/* we're done with IPsec processing, send it up */
16458 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
16459 		return;
16460 	}
16461 	default:
16462 		break;
16463 	}
16464 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
16465 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
16466 		    ire->ire_zoneid));
16467 		goto drop_pkt;
16468 	}
16469 	/*
16470 	 * Handle protocols with which IP is less intimate.  There
16471 	 * can be more than one stream bound to a particular
16472 	 * protocol.  When this is the case, each one gets a copy
16473 	 * of any incoming packets.
16474 	 */
16475 	ip_fanout_proto(q, first_mp, ill, ipha,
16476 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
16477 	    B_TRUE, recv_ill, ire->ire_zoneid);
16478 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16479 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
16480 	return;
16481 
16482 drop_pkt:
16483 	freemsg(first_mp);
16484 	if (hada_mp != NULL)
16485 		freeb(hada_mp);
16486 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16487 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
16488 #undef	rptr
16489 #undef  iphs
16490 
16491 }
16492 
16493 /*
16494  * Update any source route, record route or timestamp options.
16495  * Check that we are at end of strict source route.
16496  * The options have already been checked for sanity in ip_rput_options().
16497  */
16498 static boolean_t
16499 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
16500 {
16501 	ipoptp_t	opts;
16502 	uchar_t		*opt;
16503 	uint8_t		optval;
16504 	uint8_t		optlen;
16505 	ipaddr_t	dst;
16506 	uint32_t	ts;
16507 	ire_t		*dst_ire;
16508 	timestruc_t	now;
16509 
16510 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16511 
16512 	ip2dbg(("ip_rput_local_options\n"));
16513 
16514 	for (optval = ipoptp_first(&opts, ipha);
16515 	    optval != IPOPT_EOL;
16516 	    optval = ipoptp_next(&opts)) {
16517 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16518 		opt = opts.ipoptp_cur;
16519 		optlen = opts.ipoptp_len;
16520 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
16521 		    optval, optlen));
16522 		switch (optval) {
16523 			uint32_t off;
16524 		case IPOPT_SSRR:
16525 		case IPOPT_LSRR:
16526 			off = opt[IPOPT_OFFSET];
16527 			off--;
16528 			if (optlen < IP_ADDR_LEN ||
16529 			    off > optlen - IP_ADDR_LEN) {
16530 				/* End of source route */
16531 				ip1dbg(("ip_rput_local_options: end of SR\n"));
16532 				break;
16533 			}
16534 			/*
16535 			 * This will only happen if two consecutive entries
16536 			 * in the source route contains our address or if
16537 			 * it is a packet with a loose source route which
16538 			 * reaches us before consuming the whole source route
16539 			 */
16540 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
16541 			if (optval == IPOPT_SSRR) {
16542 				goto bad_src_route;
16543 			}
16544 			/*
16545 			 * Hack: instead of dropping the packet truncate the
16546 			 * source route to what has been used by filling the
16547 			 * rest with IPOPT_NOP.
16548 			 */
16549 			opt[IPOPT_OLEN] = (uint8_t)off;
16550 			while (off < optlen) {
16551 				opt[off++] = IPOPT_NOP;
16552 			}
16553 			break;
16554 		case IPOPT_RR:
16555 			off = opt[IPOPT_OFFSET];
16556 			off--;
16557 			if (optlen < IP_ADDR_LEN ||
16558 			    off > optlen - IP_ADDR_LEN) {
16559 				/* No more room - ignore */
16560 				ip1dbg((
16561 				    "ip_rput_local_options: end of RR\n"));
16562 				break;
16563 			}
16564 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16565 			    IP_ADDR_LEN);
16566 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16567 			break;
16568 		case IPOPT_TS:
16569 			/* Insert timestamp if there is romm */
16570 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16571 			case IPOPT_TS_TSONLY:
16572 				off = IPOPT_TS_TIMELEN;
16573 				break;
16574 			case IPOPT_TS_PRESPEC:
16575 			case IPOPT_TS_PRESPEC_RFC791:
16576 				/* Verify that the address matched */
16577 				off = opt[IPOPT_OFFSET] - 1;
16578 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16579 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16580 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16581 				if (dst_ire == NULL) {
16582 					/* Not for us */
16583 					break;
16584 				}
16585 				ire_refrele(dst_ire);
16586 				/* FALLTHRU */
16587 			case IPOPT_TS_TSANDADDR:
16588 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16589 				break;
16590 			default:
16591 				/*
16592 				 * ip_*put_options should have already
16593 				 * dropped this packet.
16594 				 */
16595 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16596 				    "unknown IT - bug in ip_rput_options?\n");
16597 				return (B_TRUE);	/* Keep "lint" happy */
16598 			}
16599 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16600 				/* Increase overflow counter */
16601 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16602 				opt[IPOPT_POS_OV_FLG] =
16603 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16604 				    (off << 4));
16605 				break;
16606 			}
16607 			off = opt[IPOPT_OFFSET] - 1;
16608 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16609 			case IPOPT_TS_PRESPEC:
16610 			case IPOPT_TS_PRESPEC_RFC791:
16611 			case IPOPT_TS_TSANDADDR:
16612 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16613 				    IP_ADDR_LEN);
16614 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16615 				/* FALLTHRU */
16616 			case IPOPT_TS_TSONLY:
16617 				off = opt[IPOPT_OFFSET] - 1;
16618 				/* Compute # of milliseconds since midnight */
16619 				gethrestime(&now);
16620 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16621 				    now.tv_nsec / (NANOSEC / MILLISEC);
16622 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16623 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16624 				break;
16625 			}
16626 			break;
16627 		}
16628 	}
16629 	return (B_TRUE);
16630 
16631 bad_src_route:
16632 	q = WR(q);
16633 	/* make sure we clear any indication of a hardware checksum */
16634 	DB_CKSUMFLAGS(mp) = 0;
16635 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16636 	return (B_FALSE);
16637 
16638 }
16639 
16640 /*
16641  * Process IP options in an inbound packet.  If an option affects the
16642  * effective destination address, return the next hop address via dstp.
16643  * Returns -1 if something fails in which case an ICMP error has been sent
16644  * and mp freed.
16645  */
16646 static int
16647 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16648 {
16649 	ipoptp_t	opts;
16650 	uchar_t		*opt;
16651 	uint8_t		optval;
16652 	uint8_t		optlen;
16653 	ipaddr_t	dst;
16654 	intptr_t	code = 0;
16655 	ire_t		*ire = NULL;
16656 
16657 	ip2dbg(("ip_rput_options\n"));
16658 	dst = ipha->ipha_dst;
16659 	for (optval = ipoptp_first(&opts, ipha);
16660 	    optval != IPOPT_EOL;
16661 	    optval = ipoptp_next(&opts)) {
16662 		opt = opts.ipoptp_cur;
16663 		optlen = opts.ipoptp_len;
16664 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16665 		    optval, optlen));
16666 		/*
16667 		 * Note: we need to verify the checksum before we
16668 		 * modify anything thus this routine only extracts the next
16669 		 * hop dst from any source route.
16670 		 */
16671 		switch (optval) {
16672 			uint32_t off;
16673 		case IPOPT_SSRR:
16674 		case IPOPT_LSRR:
16675 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16676 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16677 			if (ire == NULL) {
16678 				if (optval == IPOPT_SSRR) {
16679 					ip1dbg(("ip_rput_options: not next"
16680 					    " strict source route 0x%x\n",
16681 					    ntohl(dst)));
16682 					code = (char *)&ipha->ipha_dst -
16683 					    (char *)ipha;
16684 					goto param_prob; /* RouterReq's */
16685 				}
16686 				ip2dbg(("ip_rput_options: "
16687 				    "not next source route 0x%x\n",
16688 				    ntohl(dst)));
16689 				break;
16690 			}
16691 			ire_refrele(ire);
16692 
16693 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16694 				ip1dbg((
16695 				    "ip_rput_options: bad option offset\n"));
16696 				code = (char *)&opt[IPOPT_OLEN] -
16697 				    (char *)ipha;
16698 				goto param_prob;
16699 			}
16700 			off = opt[IPOPT_OFFSET];
16701 			off--;
16702 		redo_srr:
16703 			if (optlen < IP_ADDR_LEN ||
16704 			    off > optlen - IP_ADDR_LEN) {
16705 				/* End of source route */
16706 				ip1dbg(("ip_rput_options: end of SR\n"));
16707 				break;
16708 			}
16709 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16710 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16711 			    ntohl(dst)));
16712 
16713 			/*
16714 			 * Check if our address is present more than
16715 			 * once as consecutive hops in source route.
16716 			 * XXX verify per-interface ip_forwarding
16717 			 * for source route?
16718 			 */
16719 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16720 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16721 
16722 			if (ire != NULL) {
16723 				ire_refrele(ire);
16724 				off += IP_ADDR_LEN;
16725 				goto redo_srr;
16726 			}
16727 
16728 			if (dst == htonl(INADDR_LOOPBACK)) {
16729 				ip1dbg(("ip_rput_options: loopback addr in "
16730 				    "source route!\n"));
16731 				goto bad_src_route;
16732 			}
16733 			/*
16734 			 * For strict: verify that dst is directly
16735 			 * reachable.
16736 			 */
16737 			if (optval == IPOPT_SSRR) {
16738 				ire = ire_ftable_lookup(dst, 0, 0,
16739 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16740 				    MBLK_GETLABEL(mp),
16741 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
16742 				if (ire == NULL) {
16743 					ip1dbg(("ip_rput_options: SSRR not "
16744 					    "directly reachable: 0x%x\n",
16745 					    ntohl(dst)));
16746 					goto bad_src_route;
16747 				}
16748 				ire_refrele(ire);
16749 			}
16750 			/*
16751 			 * Defer update of the offset and the record route
16752 			 * until the packet is forwarded.
16753 			 */
16754 			break;
16755 		case IPOPT_RR:
16756 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16757 				ip1dbg((
16758 				    "ip_rput_options: bad option offset\n"));
16759 				code = (char *)&opt[IPOPT_OLEN] -
16760 				    (char *)ipha;
16761 				goto param_prob;
16762 			}
16763 			break;
16764 		case IPOPT_TS:
16765 			/*
16766 			 * Verify that length >= 5 and that there is either
16767 			 * room for another timestamp or that the overflow
16768 			 * counter is not maxed out.
16769 			 */
16770 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16771 			if (optlen < IPOPT_MINLEN_IT) {
16772 				goto param_prob;
16773 			}
16774 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16775 				ip1dbg((
16776 				    "ip_rput_options: bad option offset\n"));
16777 				code = (char *)&opt[IPOPT_OFFSET] -
16778 				    (char *)ipha;
16779 				goto param_prob;
16780 			}
16781 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16782 			case IPOPT_TS_TSONLY:
16783 				off = IPOPT_TS_TIMELEN;
16784 				break;
16785 			case IPOPT_TS_TSANDADDR:
16786 			case IPOPT_TS_PRESPEC:
16787 			case IPOPT_TS_PRESPEC_RFC791:
16788 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16789 				break;
16790 			default:
16791 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16792 				    (char *)ipha;
16793 				goto param_prob;
16794 			}
16795 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16796 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16797 				/*
16798 				 * No room and the overflow counter is 15
16799 				 * already.
16800 				 */
16801 				goto param_prob;
16802 			}
16803 			break;
16804 		}
16805 	}
16806 
16807 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16808 		*dstp = dst;
16809 		return (0);
16810 	}
16811 
16812 	ip1dbg(("ip_rput_options: error processing IP options."));
16813 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16814 
16815 param_prob:
16816 	q = WR(q);
16817 	/* make sure we clear any indication of a hardware checksum */
16818 	DB_CKSUMFLAGS(mp) = 0;
16819 	icmp_param_problem(q, mp, (uint8_t)code);
16820 	return (-1);
16821 
16822 bad_src_route:
16823 	q = WR(q);
16824 	/* make sure we clear any indication of a hardware checksum */
16825 	DB_CKSUMFLAGS(mp) = 0;
16826 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16827 	return (-1);
16828 }
16829 
16830 /*
16831  * IP & ICMP info in >=14 msg's ...
16832  *  - ip fixed part (mib2_ip_t)
16833  *  - icmp fixed part (mib2_icmp_t)
16834  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16835  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16836  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16837  *  - ipRouteAttributeTable (ip 102)	labeled routes
16838  *  - ip multicast membership (ip_member_t)
16839  *  - ip multicast source filtering (ip_grpsrc_t)
16840  *  - igmp fixed part (struct igmpstat)
16841  *  - multicast routing stats (struct mrtstat)
16842  *  - multicast routing vifs (array of struct vifctl)
16843  *  - multicast routing routes (array of struct mfcctl)
16844  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16845  *					One per ill plus one generic
16846  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16847  *					One per ill plus one generic
16848  *  - ipv6RouteEntry			all IPv6 IREs
16849  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
16850  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16851  *  - ipv6AddrEntry			all IPv6 ipifs
16852  *  - ipv6 multicast membership (ipv6_member_t)
16853  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16854  *
16855  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16856  * already present.
16857  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
16858  * already filled in by the caller.
16859  * Return value of 0 indicates that no messages were sent and caller
16860  * should free mpctl.
16861  */
16862 int
16863 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16864 {
16865 
16866 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16867 		return (0);
16868 	}
16869 
16870 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16871 		return (1);
16872 	}
16873 
16874 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16875 		return (1);
16876 	}
16877 
16878 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16879 		return (1);
16880 	}
16881 
16882 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16883 		return (1);
16884 	}
16885 
16886 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16887 		return (1);
16888 	}
16889 
16890 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16891 		return (1);
16892 	}
16893 
16894 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16895 		return (1);
16896 	}
16897 
16898 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16899 		return (1);
16900 	}
16901 
16902 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16903 		return (1);
16904 	}
16905 
16906 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16907 		return (1);
16908 	}
16909 
16910 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16911 		return (1);
16912 	}
16913 
16914 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16915 		return (1);
16916 	}
16917 
16918 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16919 		return (1);
16920 	}
16921 
16922 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16923 		return (1);
16924 	}
16925 
16926 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16927 		return (1);
16928 	}
16929 
16930 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16931 		return (1);
16932 	}
16933 
16934 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16935 		return (1);
16936 	}
16937 	freemsg(mpctl);
16938 	return (1);
16939 }
16940 
16941 
16942 /* Get global IPv4 statistics */
16943 static mblk_t *
16944 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16945 {
16946 	struct opthdr		*optp;
16947 	mblk_t			*mp2ctl;
16948 
16949 	/*
16950 	 * make a copy of the original message
16951 	 */
16952 	mp2ctl = copymsg(mpctl);
16953 
16954 	/* fixed length IP structure... */
16955 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16956 	optp->level = MIB2_IP;
16957 	optp->name = 0;
16958 	SET_MIB(ip_mib.ipForwarding,
16959 	    (WE_ARE_FORWARDING ? 1 : 2));
16960 	SET_MIB(ip_mib.ipDefaultTTL,
16961 	    (uint32_t)ip_def_ttl);
16962 	SET_MIB(ip_mib.ipReasmTimeout,
16963 	    ip_g_frag_timeout);
16964 	SET_MIB(ip_mib.ipAddrEntrySize,
16965 	    sizeof (mib2_ipAddrEntry_t));
16966 	SET_MIB(ip_mib.ipRouteEntrySize,
16967 	    sizeof (mib2_ipRouteEntry_t));
16968 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16969 	    sizeof (mib2_ipNetToMediaEntry_t));
16970 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16971 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16972 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
16973 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
16974 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16975 	    (int)sizeof (ip_mib))) {
16976 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16977 		    (uint_t)sizeof (ip_mib)));
16978 	}
16979 
16980 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16981 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16982 	    (int)optp->level, (int)optp->name, (int)optp->len));
16983 	qreply(q, mpctl);
16984 	return (mp2ctl);
16985 }
16986 
16987 /* Global IPv4 ICMP statistics */
16988 static mblk_t *
16989 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
16990 {
16991 	struct opthdr		*optp;
16992 	mblk_t			*mp2ctl;
16993 
16994 	/*
16995 	 * Make a copy of the original message
16996 	 */
16997 	mp2ctl = copymsg(mpctl);
16998 
16999 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17000 	optp->level = MIB2_ICMP;
17001 	optp->name = 0;
17002 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17003 	    (int)sizeof (icmp_mib))) {
17004 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17005 		    (uint_t)sizeof (icmp_mib)));
17006 	}
17007 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17008 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17009 	    (int)optp->level, (int)optp->name, (int)optp->len));
17010 	qreply(q, mpctl);
17011 	return (mp2ctl);
17012 }
17013 
17014 /* Global IPv4 IGMP statistics */
17015 static mblk_t *
17016 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17017 {
17018 	struct opthdr		*optp;
17019 	mblk_t			*mp2ctl;
17020 
17021 	/*
17022 	 * make a copy of the original message
17023 	 */
17024 	mp2ctl = copymsg(mpctl);
17025 
17026 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17027 	optp->level = EXPER_IGMP;
17028 	optp->name = 0;
17029 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17030 	    (int)sizeof (igmpstat))) {
17031 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17032 		    (uint_t)sizeof (igmpstat)));
17033 	}
17034 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17035 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17036 	    (int)optp->level, (int)optp->name, (int)optp->len));
17037 	qreply(q, mpctl);
17038 	return (mp2ctl);
17039 }
17040 
17041 /* Global IPv4 Multicast Routing statistics */
17042 static mblk_t *
17043 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17044 {
17045 	struct opthdr		*optp;
17046 	mblk_t			*mp2ctl;
17047 
17048 	/*
17049 	 * make a copy of the original message
17050 	 */
17051 	mp2ctl = copymsg(mpctl);
17052 
17053 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17054 	optp->level = EXPER_DVMRP;
17055 	optp->name = 0;
17056 	if (!ip_mroute_stats(mpctl->b_cont)) {
17057 		ip0dbg(("ip_mroute_stats: failed\n"));
17058 	}
17059 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17060 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17061 	    (int)optp->level, (int)optp->name, (int)optp->len));
17062 	qreply(q, mpctl);
17063 	return (mp2ctl);
17064 }
17065 
17066 /* IPv4 address information */
17067 static mblk_t *
17068 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17069 {
17070 	struct opthdr		*optp;
17071 	mblk_t			*mp2ctl;
17072 	mblk_t			*mp_tail = NULL;
17073 	ill_t			*ill;
17074 	ipif_t			*ipif;
17075 	uint_t			bitval;
17076 	mib2_ipAddrEntry_t	mae;
17077 	zoneid_t		zoneid;
17078 	ill_walk_context_t ctx;
17079 
17080 	/*
17081 	 * make a copy of the original message
17082 	 */
17083 	mp2ctl = copymsg(mpctl);
17084 
17085 	/* ipAddrEntryTable */
17086 
17087 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17088 	optp->level = MIB2_IP;
17089 	optp->name = MIB2_IP_ADDR;
17090 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17091 
17092 	rw_enter(&ill_g_lock, RW_READER);
17093 	ill = ILL_START_WALK_V4(&ctx);
17094 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17095 		for (ipif = ill->ill_ipif; ipif != NULL;
17096 		    ipif = ipif->ipif_next) {
17097 			if (ipif->ipif_zoneid != zoneid &&
17098 			    ipif->ipif_zoneid != ALL_ZONES)
17099 				continue;
17100 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17101 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17102 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17103 
17104 			(void) ipif_get_name(ipif,
17105 			    mae.ipAdEntIfIndex.o_bytes,
17106 			    OCTET_LENGTH);
17107 			mae.ipAdEntIfIndex.o_length =
17108 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17109 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17110 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17111 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17112 			mae.ipAdEntInfo.ae_subnet_len =
17113 			    ip_mask_to_plen(ipif->ipif_net_mask);
17114 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17115 			for (bitval = 1;
17116 			    bitval &&
17117 			    !(bitval & ipif->ipif_brd_addr);
17118 			    bitval <<= 1)
17119 				noop;
17120 			mae.ipAdEntBcastAddr = bitval;
17121 			mae.ipAdEntReasmMaxSize = 65535;
17122 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17123 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17124 			mae.ipAdEntInfo.ae_broadcast_addr =
17125 			    ipif->ipif_brd_addr;
17126 			mae.ipAdEntInfo.ae_pp_dst_addr =
17127 			    ipif->ipif_pp_dst_addr;
17128 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17129 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17130 
17131 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17132 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17133 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17134 				    "allocate %u bytes\n",
17135 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17136 			}
17137 		}
17138 	}
17139 	rw_exit(&ill_g_lock);
17140 
17141 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17142 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17143 	    (int)optp->level, (int)optp->name, (int)optp->len));
17144 	qreply(q, mpctl);
17145 	return (mp2ctl);
17146 }
17147 
17148 /* IPv6 address information */
17149 static mblk_t *
17150 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17151 {
17152 	struct opthdr		*optp;
17153 	mblk_t			*mp2ctl;
17154 	mblk_t			*mp_tail = NULL;
17155 	ill_t			*ill;
17156 	ipif_t			*ipif;
17157 	mib2_ipv6AddrEntry_t	mae6;
17158 	zoneid_t		zoneid;
17159 	ill_walk_context_t	ctx;
17160 
17161 	/*
17162 	 * make a copy of the original message
17163 	 */
17164 	mp2ctl = copymsg(mpctl);
17165 
17166 	/* ipv6AddrEntryTable */
17167 
17168 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17169 	optp->level = MIB2_IP6;
17170 	optp->name = MIB2_IP6_ADDR;
17171 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17172 
17173 	rw_enter(&ill_g_lock, RW_READER);
17174 	ill = ILL_START_WALK_V6(&ctx);
17175 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17176 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17177 			if (ipif->ipif_zoneid != zoneid &&
17178 			    ipif->ipif_zoneid != ALL_ZONES)
17179 				continue;
17180 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17181 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17182 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17183 
17184 			(void) ipif_get_name(ipif,
17185 			    mae6.ipv6AddrIfIndex.o_bytes,
17186 			    OCTET_LENGTH);
17187 			mae6.ipv6AddrIfIndex.o_length =
17188 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17189 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17190 			mae6.ipv6AddrPfxLength =
17191 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17192 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17193 			mae6.ipv6AddrInfo.ae_subnet_len =
17194 			    mae6.ipv6AddrPfxLength;
17195 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17196 
17197 			/* Type: stateless(1), stateful(2), unknown(3) */
17198 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17199 				mae6.ipv6AddrType = 1;
17200 			else
17201 				mae6.ipv6AddrType = 2;
17202 			/* Anycast: true(1), false(2) */
17203 			if (ipif->ipif_flags & IPIF_ANYCAST)
17204 				mae6.ipv6AddrAnycastFlag = 1;
17205 			else
17206 				mae6.ipv6AddrAnycastFlag = 2;
17207 
17208 			/*
17209 			 * Address status: preferred(1), deprecated(2),
17210 			 * invalid(3), inaccessible(4), unknown(5)
17211 			 */
17212 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17213 				mae6.ipv6AddrStatus = 3;
17214 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17215 				mae6.ipv6AddrStatus = 2;
17216 			else
17217 				mae6.ipv6AddrStatus = 1;
17218 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17219 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17220 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17221 						ipif->ipif_v6pp_dst_addr;
17222 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17223 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17224 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17225 				(char *)&mae6,
17226 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17227 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17228 				    "allocate %u bytes\n",
17229 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17230 			}
17231 		}
17232 	}
17233 	rw_exit(&ill_g_lock);
17234 
17235 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17236 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17237 	    (int)optp->level, (int)optp->name, (int)optp->len));
17238 	qreply(q, mpctl);
17239 	return (mp2ctl);
17240 }
17241 
17242 /* IPv4 multicast group membership. */
17243 static mblk_t *
17244 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17245 {
17246 	struct opthdr		*optp;
17247 	mblk_t			*mp2ctl;
17248 	ill_t			*ill;
17249 	ipif_t			*ipif;
17250 	ilm_t			*ilm;
17251 	ip_member_t		ipm;
17252 	mblk_t			*mp_tail = NULL;
17253 	ill_walk_context_t	ctx;
17254 	zoneid_t		zoneid;
17255 
17256 	/*
17257 	 * make a copy of the original message
17258 	 */
17259 	mp2ctl = copymsg(mpctl);
17260 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17261 
17262 	/* ipGroupMember table */
17263 	optp = (struct opthdr *)&mpctl->b_rptr[
17264 	    sizeof (struct T_optmgmt_ack)];
17265 	optp->level = MIB2_IP;
17266 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17267 
17268 	rw_enter(&ill_g_lock, RW_READER);
17269 	ill = ILL_START_WALK_V4(&ctx);
17270 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17271 		ILM_WALKER_HOLD(ill);
17272 		for (ipif = ill->ill_ipif; ipif != NULL;
17273 		    ipif = ipif->ipif_next) {
17274 			if (ipif->ipif_zoneid != zoneid &&
17275 			    ipif->ipif_zoneid != ALL_ZONES)
17276 				continue;	/* not this zone */
17277 			(void) ipif_get_name(ipif,
17278 			    ipm.ipGroupMemberIfIndex.o_bytes,
17279 			    OCTET_LENGTH);
17280 			ipm.ipGroupMemberIfIndex.o_length =
17281 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17282 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17283 				ASSERT(ilm->ilm_ipif != NULL);
17284 				ASSERT(ilm->ilm_ill == NULL);
17285 				if (ilm->ilm_ipif != ipif)
17286 					continue;
17287 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17288 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17289 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17290 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17291 				    (char *)&ipm, (int)sizeof (ipm))) {
17292 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17293 					    "failed to allocate %u bytes\n",
17294 						(uint_t)sizeof (ipm)));
17295 				}
17296 			}
17297 		}
17298 		ILM_WALKER_RELE(ill);
17299 	}
17300 	rw_exit(&ill_g_lock);
17301 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17302 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17303 	    (int)optp->level, (int)optp->name, (int)optp->len));
17304 	qreply(q, mpctl);
17305 	return (mp2ctl);
17306 }
17307 
17308 /* IPv6 multicast group membership. */
17309 static mblk_t *
17310 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17311 {
17312 	struct opthdr		*optp;
17313 	mblk_t			*mp2ctl;
17314 	ill_t			*ill;
17315 	ilm_t			*ilm;
17316 	ipv6_member_t		ipm6;
17317 	mblk_t			*mp_tail = NULL;
17318 	ill_walk_context_t	ctx;
17319 	zoneid_t		zoneid;
17320 
17321 	/*
17322 	 * make a copy of the original message
17323 	 */
17324 	mp2ctl = copymsg(mpctl);
17325 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17326 
17327 	/* ip6GroupMember table */
17328 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17329 	optp->level = MIB2_IP6;
17330 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17331 
17332 	rw_enter(&ill_g_lock, RW_READER);
17333 	ill = ILL_START_WALK_V6(&ctx);
17334 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17335 		ILM_WALKER_HOLD(ill);
17336 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17337 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17338 			ASSERT(ilm->ilm_ipif == NULL);
17339 			ASSERT(ilm->ilm_ill != NULL);
17340 			if (ilm->ilm_zoneid != zoneid)
17341 				continue;	/* not this zone */
17342 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17343 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17344 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17345 			if (!snmp_append_data2(mpctl->b_cont,
17346 			    &mp_tail,
17347 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17348 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17349 				    "failed to allocate %u bytes\n",
17350 				    (uint_t)sizeof (ipm6)));
17351 			}
17352 		}
17353 		ILM_WALKER_RELE(ill);
17354 	}
17355 	rw_exit(&ill_g_lock);
17356 
17357 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17358 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17359 	    (int)optp->level, (int)optp->name, (int)optp->len));
17360 	qreply(q, mpctl);
17361 	return (mp2ctl);
17362 }
17363 
17364 /* IP multicast filtered sources */
17365 static mblk_t *
17366 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17367 {
17368 	struct opthdr		*optp;
17369 	mblk_t			*mp2ctl;
17370 	ill_t			*ill;
17371 	ipif_t			*ipif;
17372 	ilm_t			*ilm;
17373 	ip_grpsrc_t		ips;
17374 	mblk_t			*mp_tail = NULL;
17375 	ill_walk_context_t	ctx;
17376 	zoneid_t		zoneid;
17377 	int			i;
17378 	slist_t			*sl;
17379 
17380 	/*
17381 	 * make a copy of the original message
17382 	 */
17383 	mp2ctl = copymsg(mpctl);
17384 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17385 
17386 	/* ipGroupSource table */
17387 	optp = (struct opthdr *)&mpctl->b_rptr[
17388 	    sizeof (struct T_optmgmt_ack)];
17389 	optp->level = MIB2_IP;
17390 	optp->name = EXPER_IP_GROUP_SOURCES;
17391 
17392 	rw_enter(&ill_g_lock, RW_READER);
17393 	ill = ILL_START_WALK_V4(&ctx);
17394 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17395 		ILM_WALKER_HOLD(ill);
17396 		for (ipif = ill->ill_ipif; ipif != NULL;
17397 		    ipif = ipif->ipif_next) {
17398 			if (ipif->ipif_zoneid != zoneid)
17399 				continue;	/* not this zone */
17400 			(void) ipif_get_name(ipif,
17401 			    ips.ipGroupSourceIfIndex.o_bytes,
17402 			    OCTET_LENGTH);
17403 			ips.ipGroupSourceIfIndex.o_length =
17404 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17405 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17406 				ASSERT(ilm->ilm_ipif != NULL);
17407 				ASSERT(ilm->ilm_ill == NULL);
17408 				sl = ilm->ilm_filter;
17409 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17410 					continue;
17411 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17412 				for (i = 0; i < sl->sl_numsrc; i++) {
17413 					if (!IN6_IS_ADDR_V4MAPPED(
17414 					    &sl->sl_addr[i]))
17415 						continue;
17416 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
17417 					    ips.ipGroupSourceAddress);
17418 					if (snmp_append_data2(mpctl->b_cont,
17419 					    &mp_tail, (char *)&ips,
17420 					    (int)sizeof (ips)) == 0) {
17421 						ip1dbg(("ip_snmp_get_mib2_"
17422 						    "ip_group_src: failed to "
17423 						    "allocate %u bytes\n",
17424 						    (uint_t)sizeof (ips)));
17425 					}
17426 				}
17427 			}
17428 		}
17429 		ILM_WALKER_RELE(ill);
17430 	}
17431 	rw_exit(&ill_g_lock);
17432 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17433 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17434 	    (int)optp->level, (int)optp->name, (int)optp->len));
17435 	qreply(q, mpctl);
17436 	return (mp2ctl);
17437 }
17438 
17439 /* IPv6 multicast filtered sources. */
17440 static mblk_t *
17441 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
17442 {
17443 	struct opthdr		*optp;
17444 	mblk_t			*mp2ctl;
17445 	ill_t			*ill;
17446 	ilm_t			*ilm;
17447 	ipv6_grpsrc_t		ips6;
17448 	mblk_t			*mp_tail = NULL;
17449 	ill_walk_context_t	ctx;
17450 	zoneid_t		zoneid;
17451 	int			i;
17452 	slist_t			*sl;
17453 
17454 	/*
17455 	 * make a copy of the original message
17456 	 */
17457 	mp2ctl = copymsg(mpctl);
17458 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17459 
17460 	/* ip6GroupMember table */
17461 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17462 	optp->level = MIB2_IP6;
17463 	optp->name = EXPER_IP6_GROUP_SOURCES;
17464 
17465 	rw_enter(&ill_g_lock, RW_READER);
17466 	ill = ILL_START_WALK_V6(&ctx);
17467 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17468 		ILM_WALKER_HOLD(ill);
17469 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
17470 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17471 			ASSERT(ilm->ilm_ipif == NULL);
17472 			ASSERT(ilm->ilm_ill != NULL);
17473 			sl = ilm->ilm_filter;
17474 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
17475 				continue;
17476 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
17477 			for (i = 0; i < sl->sl_numsrc; i++) {
17478 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
17479 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17480 				    (char *)&ips6, (int)sizeof (ips6))) {
17481 					ip1dbg(("ip_snmp_get_mib2_ip6_"
17482 					    "group_src: failed to allocate "
17483 					    "%u bytes\n",
17484 					    (uint_t)sizeof (ips6)));
17485 				}
17486 			}
17487 		}
17488 		ILM_WALKER_RELE(ill);
17489 	}
17490 	rw_exit(&ill_g_lock);
17491 
17492 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17493 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17494 	    (int)optp->level, (int)optp->name, (int)optp->len));
17495 	qreply(q, mpctl);
17496 	return (mp2ctl);
17497 }
17498 
17499 /* Multicast routing virtual interface table. */
17500 static mblk_t *
17501 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
17502 {
17503 	struct opthdr		*optp;
17504 	mblk_t			*mp2ctl;
17505 
17506 	/*
17507 	 * make a copy of the original message
17508 	 */
17509 	mp2ctl = copymsg(mpctl);
17510 
17511 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17512 	optp->level = EXPER_DVMRP;
17513 	optp->name = EXPER_DVMRP_VIF;
17514 	if (!ip_mroute_vif(mpctl->b_cont)) {
17515 		ip0dbg(("ip_mroute_vif: failed\n"));
17516 	}
17517 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17518 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
17519 	    (int)optp->level, (int)optp->name, (int)optp->len));
17520 	qreply(q, mpctl);
17521 	return (mp2ctl);
17522 }
17523 
17524 /* Multicast routing table. */
17525 static mblk_t *
17526 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
17527 {
17528 	struct opthdr		*optp;
17529 	mblk_t			*mp2ctl;
17530 
17531 	/*
17532 	 * make a copy of the original message
17533 	 */
17534 	mp2ctl = copymsg(mpctl);
17535 
17536 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17537 	optp->level = EXPER_DVMRP;
17538 	optp->name = EXPER_DVMRP_MRT;
17539 	if (!ip_mroute_mrt(mpctl->b_cont)) {
17540 		ip0dbg(("ip_mroute_mrt: failed\n"));
17541 	}
17542 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17543 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
17544 	    (int)optp->level, (int)optp->name, (int)optp->len));
17545 	qreply(q, mpctl);
17546 	return (mp2ctl);
17547 }
17548 
17549 /*
17550  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
17551  * in one IRE walk.
17552  */
17553 static mblk_t *
17554 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
17555 {
17556 	struct opthdr	*optp;
17557 	mblk_t		*mp2ctl;	/* Returned */
17558 	mblk_t		*mp3ctl;	/* nettomedia */
17559 	mblk_t		*mp4ctl;	/* routeattrs */
17560 	iproutedata_t	ird;
17561 	zoneid_t	zoneid;
17562 
17563 	/*
17564 	 * make copies of the original message
17565 	 *	- mp2ctl is returned unchanged to the caller for his use
17566 	 *	- mpctl is sent upstream as ipRouteEntryTable
17567 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
17568 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
17569 	 */
17570 	mp2ctl = copymsg(mpctl);
17571 	mp3ctl = copymsg(mpctl);
17572 	mp4ctl = copymsg(mpctl);
17573 	if (mp3ctl == NULL || mp4ctl == NULL) {
17574 		freemsg(mp4ctl);
17575 		freemsg(mp3ctl);
17576 		freemsg(mp2ctl);
17577 		freemsg(mpctl);
17578 		return (NULL);
17579 	}
17580 
17581 	bzero(&ird, sizeof (ird));
17582 
17583 	ird.ird_route.lp_head = mpctl->b_cont;
17584 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17585 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17586 
17587 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17588 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
17589 	if (zoneid == GLOBAL_ZONEID) {
17590 		/*
17591 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17592 		 * the sys_net_config privilege, it can only run in the global
17593 		 * zone, so we don't display these IREs in the other zones.
17594 		 */
17595 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
17596 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
17597 	}
17598 
17599 	/* ipRouteEntryTable in mpctl */
17600 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17601 	optp->level = MIB2_IP;
17602 	optp->name = MIB2_IP_ROUTE;
17603 	optp->len = msgdsize(ird.ird_route.lp_head);
17604 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17605 	    (int)optp->level, (int)optp->name, (int)optp->len));
17606 	qreply(q, mpctl);
17607 
17608 	/* ipNetToMediaEntryTable in mp3ctl */
17609 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17610 	optp->level = MIB2_IP;
17611 	optp->name = MIB2_IP_MEDIA;
17612 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17613 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17614 	    (int)optp->level, (int)optp->name, (int)optp->len));
17615 	qreply(q, mp3ctl);
17616 
17617 	/* ipRouteAttributeTable in mp4ctl */
17618 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17619 	optp->level = MIB2_IP;
17620 	optp->name = EXPER_IP_RTATTR;
17621 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17622 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17623 	    (int)optp->level, (int)optp->name, (int)optp->len));
17624 	if (optp->len == 0)
17625 		freemsg(mp4ctl);
17626 	else
17627 		qreply(q, mp4ctl);
17628 
17629 	return (mp2ctl);
17630 }
17631 
17632 /*
17633  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
17634  * ipv6NetToMediaEntryTable in an NDP walk.
17635  */
17636 static mblk_t *
17637 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17638 {
17639 	struct opthdr	*optp;
17640 	mblk_t		*mp2ctl;	/* Returned */
17641 	mblk_t		*mp3ctl;	/* nettomedia */
17642 	mblk_t		*mp4ctl;	/* routeattrs */
17643 	iproutedata_t	ird;
17644 	zoneid_t	zoneid;
17645 
17646 	/*
17647 	 * make copies of the original message
17648 	 *	- mp2ctl is returned unchanged to the caller for his use
17649 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
17650 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
17651 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
17652 	 */
17653 	mp2ctl = copymsg(mpctl);
17654 	mp3ctl = copymsg(mpctl);
17655 	mp4ctl = copymsg(mpctl);
17656 	if (mp3ctl == NULL || mp4ctl == NULL) {
17657 		freemsg(mp4ctl);
17658 		freemsg(mp3ctl);
17659 		freemsg(mp2ctl);
17660 		freemsg(mpctl);
17661 		return (NULL);
17662 	}
17663 
17664 	bzero(&ird, sizeof (ird));
17665 
17666 	ird.ird_route.lp_head = mpctl->b_cont;
17667 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17668 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17669 
17670 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17671 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
17672 
17673 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17674 	optp->level = MIB2_IP6;
17675 	optp->name = MIB2_IP6_ROUTE;
17676 	optp->len = msgdsize(ird.ird_route.lp_head);
17677 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17678 	    (int)optp->level, (int)optp->name, (int)optp->len));
17679 	qreply(q, mpctl);
17680 
17681 	/* ipv6NetToMediaEntryTable in mp3ctl */
17682 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
17683 
17684 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17685 	optp->level = MIB2_IP6;
17686 	optp->name = MIB2_IP6_MEDIA;
17687 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17688 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17689 	    (int)optp->level, (int)optp->name, (int)optp->len));
17690 	qreply(q, mp3ctl);
17691 
17692 	/* ipv6RouteAttributeTable in mp4ctl */
17693 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17694 	optp->level = MIB2_IP6;
17695 	optp->name = EXPER_IP_RTATTR;
17696 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17697 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17698 	    (int)optp->level, (int)optp->name, (int)optp->len));
17699 	if (optp->len == 0)
17700 		freemsg(mp4ctl);
17701 	else
17702 		qreply(q, mp4ctl);
17703 
17704 	return (mp2ctl);
17705 }
17706 
17707 /*
17708  * ICMPv6 mib: One per ill
17709  */
17710 static mblk_t *
17711 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17712 {
17713 	struct opthdr		*optp;
17714 	mblk_t			*mp2ctl;
17715 	ill_t			*ill;
17716 	ill_walk_context_t	ctx;
17717 	mblk_t			*mp_tail = NULL;
17718 
17719 	/*
17720 	 * Make a copy of the original message
17721 	 */
17722 	mp2ctl = copymsg(mpctl);
17723 
17724 	/* fixed length IPv6 structure ... */
17725 
17726 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17727 	optp->level = MIB2_IP6;
17728 	optp->name = 0;
17729 	/* Include "unknown interface" ip6_mib */
17730 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17731 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17732 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17733 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17734 	    sizeof (mib2_ipv6IfStatsEntry_t));
17735 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17736 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17737 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17738 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17739 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17740 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17741 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17742 	    (int)sizeof (ip6_mib))) {
17743 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17744 		    (uint_t)sizeof (ip6_mib)));
17745 	}
17746 
17747 	rw_enter(&ill_g_lock, RW_READER);
17748 	ill = ILL_START_WALK_V6(&ctx);
17749 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17750 		ill->ill_ip6_mib->ipv6IfIndex =
17751 		    ill->ill_phyint->phyint_ifindex;
17752 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17753 		    ipv6_forward ? 1 : 2);
17754 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17755 		    ill->ill_max_hops);
17756 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17757 		    sizeof (mib2_ipv6IfStatsEntry_t));
17758 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17759 		    sizeof (mib2_ipv6AddrEntry_t));
17760 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17761 		    sizeof (mib2_ipv6RouteEntry_t));
17762 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17763 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17764 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17765 		    sizeof (ipv6_member_t));
17766 
17767 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17768 		    (char *)ill->ill_ip6_mib,
17769 		    (int)sizeof (*ill->ill_ip6_mib))) {
17770 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17771 				"%u bytes\n",
17772 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17773 		}
17774 	}
17775 	rw_exit(&ill_g_lock);
17776 
17777 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17778 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17779 	    (int)optp->level, (int)optp->name, (int)optp->len));
17780 	qreply(q, mpctl);
17781 	return (mp2ctl);
17782 }
17783 
17784 /*
17785  * ICMPv6 mib: One per ill
17786  */
17787 static mblk_t *
17788 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17789 {
17790 	struct opthdr		*optp;
17791 	mblk_t			*mp2ctl;
17792 	ill_t			*ill;
17793 	ill_walk_context_t	ctx;
17794 	mblk_t			*mp_tail = NULL;
17795 	/*
17796 	 * Make a copy of the original message
17797 	 */
17798 	mp2ctl = copymsg(mpctl);
17799 
17800 	/* fixed length ICMPv6 structure ... */
17801 
17802 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17803 	optp->level = MIB2_ICMP6;
17804 	optp->name = 0;
17805 	/* Include "unknown interface" icmp6_mib */
17806 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17807 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17808 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17809 	    (int)sizeof (icmp6_mib))) {
17810 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17811 		    (uint_t)sizeof (icmp6_mib)));
17812 	}
17813 
17814 	rw_enter(&ill_g_lock, RW_READER);
17815 	ill = ILL_START_WALK_V6(&ctx);
17816 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17817 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17818 		    ill->ill_phyint->phyint_ifindex;
17819 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17820 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17821 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17822 		    (char *)ill->ill_icmp6_mib,
17823 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17824 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17825 			    "%u bytes\n",
17826 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17827 		}
17828 	}
17829 	rw_exit(&ill_g_lock);
17830 
17831 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17832 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17833 	    (int)optp->level, (int)optp->name, (int)optp->len));
17834 	qreply(q, mpctl);
17835 	return (mp2ctl);
17836 }
17837 
17838 /*
17839  * ire_walk routine to create both ipRouteEntryTable and
17840  * ipNetToMediaEntryTable in one IRE walk
17841  */
17842 static void
17843 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
17844 {
17845 	ill_t				*ill;
17846 	ipif_t				*ipif;
17847 	mblk_t				*llmp;
17848 	dl_unitdata_req_t		*dlup;
17849 	mib2_ipRouteEntry_t		*re;
17850 	mib2_ipNetToMediaEntry_t	ntme;
17851 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
17852 	ipaddr_t			gw_addr;
17853 	tsol_ire_gw_secattr_t		*attrp;
17854 	tsol_gc_t			*gc = NULL;
17855 	tsol_gcgrp_t			*gcgrp = NULL;
17856 	uint_t				sacnt = 0;
17857 	int				i;
17858 
17859 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17860 
17861 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
17862 		return;
17863 
17864 	if ((attrp = ire->ire_gw_secattr) != NULL) {
17865 		mutex_enter(&attrp->igsa_lock);
17866 		if ((gc = attrp->igsa_gc) != NULL) {
17867 			gcgrp = gc->gc_grp;
17868 			ASSERT(gcgrp != NULL);
17869 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17870 			sacnt = 1;
17871 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
17872 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17873 			gc = gcgrp->gcgrp_head;
17874 			sacnt = gcgrp->gcgrp_count;
17875 		}
17876 		mutex_exit(&attrp->igsa_lock);
17877 
17878 		/* do nothing if there's no gc to report */
17879 		if (gc == NULL) {
17880 			ASSERT(sacnt == 0);
17881 			if (gcgrp != NULL) {
17882 				/* we might as well drop the lock now */
17883 				rw_exit(&gcgrp->gcgrp_rwlock);
17884 				gcgrp = NULL;
17885 			}
17886 			attrp = NULL;
17887 		}
17888 
17889 		ASSERT(gc == NULL || (gcgrp != NULL &&
17890 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
17891 	}
17892 	ASSERT(sacnt == 0 || gc != NULL);
17893 
17894 	if (sacnt != 0 &&
17895 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
17896 		kmem_free(re, sizeof (*re));
17897 		rw_exit(&gcgrp->gcgrp_rwlock);
17898 		return;
17899 	}
17900 
17901 	/*
17902 	 * Return all IRE types for route table... let caller pick and choose
17903 	 */
17904 	re->ipRouteDest = ire->ire_addr;
17905 	ipif = ire->ire_ipif;
17906 	re->ipRouteIfIndex.o_length = 0;
17907 	if (ire->ire_type == IRE_CACHE) {
17908 		ill = (ill_t *)ire->ire_stq->q_ptr;
17909 		re->ipRouteIfIndex.o_length =
17910 		    ill->ill_name_length == 0 ? 0 :
17911 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17912 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
17913 		    re->ipRouteIfIndex.o_length);
17914 	} else if (ipif != NULL) {
17915 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
17916 		    OCTET_LENGTH);
17917 		re->ipRouteIfIndex.o_length =
17918 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
17919 	}
17920 	re->ipRouteMetric1 = -1;
17921 	re->ipRouteMetric2 = -1;
17922 	re->ipRouteMetric3 = -1;
17923 	re->ipRouteMetric4 = -1;
17924 
17925 	gw_addr = ire->ire_gateway_addr;
17926 
17927 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17928 		re->ipRouteNextHop = ire->ire_src_addr;
17929 	else
17930 		re->ipRouteNextHop = gw_addr;
17931 	/* indirect(4), direct(3), or invalid(2) */
17932 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17933 		re->ipRouteType = 2;
17934 	else
17935 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
17936 	re->ipRouteProto = -1;
17937 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17938 	re->ipRouteMask = ire->ire_mask;
17939 	re->ipRouteMetric5 = -1;
17940 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
17941 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
17942 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17943 	llmp = ire->ire_dlureq_mp;
17944 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
17945 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
17946 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
17947 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17948 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17949 	re->ipRouteInfo.re_flags	= ire->ire_flags;
17950 	re->ipRouteInfo.re_in_ill.o_length = 0;
17951 	if (ire->ire_in_ill != NULL) {
17952 		re->ipRouteInfo.re_in_ill.o_length =
17953 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17954 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17955 		bcopy(ire->ire_in_ill->ill_name,
17956 		    re->ipRouteInfo.re_in_ill.o_bytes,
17957 		    re->ipRouteInfo.re_in_ill.o_length);
17958 	}
17959 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17960 
17961 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
17962 	    (char *)re, (int)sizeof (*re))) {
17963 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17964 		    (uint_t)sizeof (*re)));
17965 	}
17966 
17967 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
17968 		iaeptr->iae_routeidx = ird->ird_idx;
17969 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
17970 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
17971 	}
17972 
17973 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
17974 	    (char *)iae, sacnt * sizeof (*iae))) {
17975 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17976 		    (unsigned)(sacnt * sizeof (*iae))));
17977 	}
17978 
17979 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17980 		goto done;
17981 	/*
17982 	 * only IRE_CACHE entries that are for a directly connected subnet
17983 	 * get appended to net -> phys addr table
17984 	 * (others in arp)
17985 	 */
17986 	ntme.ipNetToMediaIfIndex.o_length = 0;
17987 	ill = ire_to_ill(ire);
17988 	ASSERT(ill != NULL);
17989 	ntme.ipNetToMediaIfIndex.o_length =
17990 	    ill->ill_name_length == 0 ? 0 :
17991 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17992 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
17993 		    ntme.ipNetToMediaIfIndex.o_length);
17994 
17995 	ntme.ipNetToMediaPhysAddress.o_length = 0;
17996 	if (llmp) {
17997 		uchar_t *addr;
17998 
17999 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18000 		/* Remove sap from  address */
18001 		if (ill->ill_sap_length < 0)
18002 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18003 		else
18004 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18005 			    ill->ill_sap_length;
18006 
18007 		ntme.ipNetToMediaPhysAddress.o_length =
18008 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18009 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18010 		    ntme.ipNetToMediaPhysAddress.o_length);
18011 	}
18012 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18013 	/* assume dynamic (may be changed in arp) */
18014 	ntme.ipNetToMediaType = 3;
18015 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18016 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18017 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18018 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18019 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18020 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18021 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18022 		    (uint_t)sizeof (ntme)));
18023 	}
18024 done:
18025 	/* bump route index for next pass */
18026 	ird->ird_idx++;
18027 
18028 	kmem_free(re, sizeof (*re));
18029 	if (sacnt != 0)
18030 		kmem_free(iae, sacnt * sizeof (*iae));
18031 
18032 	if (gcgrp != NULL)
18033 		rw_exit(&gcgrp->gcgrp_rwlock);
18034 }
18035 
18036 /*
18037  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18038  */
18039 static void
18040 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18041 {
18042 	ill_t				*ill;
18043 	ipif_t				*ipif;
18044 	mib2_ipv6RouteEntry_t		*re;
18045 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18046 	in6_addr_t			gw_addr_v6;
18047 	tsol_ire_gw_secattr_t		*attrp;
18048 	tsol_gc_t			*gc = NULL;
18049 	tsol_gcgrp_t			*gcgrp = NULL;
18050 	uint_t				sacnt = 0;
18051 	int				i;
18052 
18053 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18054 
18055 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18056 		return;
18057 
18058 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18059 		mutex_enter(&attrp->igsa_lock);
18060 		if ((gc = attrp->igsa_gc) != NULL) {
18061 			gcgrp = gc->gc_grp;
18062 			ASSERT(gcgrp != NULL);
18063 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18064 			sacnt = 1;
18065 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18066 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18067 			gc = gcgrp->gcgrp_head;
18068 			sacnt = gcgrp->gcgrp_count;
18069 		}
18070 		mutex_exit(&attrp->igsa_lock);
18071 
18072 		/* do nothing if there's no gc to report */
18073 		if (gc == NULL) {
18074 			ASSERT(sacnt == 0);
18075 			if (gcgrp != NULL) {
18076 				/* we might as well drop the lock now */
18077 				rw_exit(&gcgrp->gcgrp_rwlock);
18078 				gcgrp = NULL;
18079 			}
18080 			attrp = NULL;
18081 		}
18082 
18083 		ASSERT(gc == NULL || (gcgrp != NULL &&
18084 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18085 	}
18086 	ASSERT(sacnt == 0 || gc != NULL);
18087 
18088 	if (sacnt != 0 &&
18089 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18090 		kmem_free(re, sizeof (*re));
18091 		rw_exit(&gcgrp->gcgrp_rwlock);
18092 		return;
18093 	}
18094 
18095 	/*
18096 	 * Return all IRE types for route table... let caller pick and choose
18097 	 */
18098 	re->ipv6RouteDest = ire->ire_addr_v6;
18099 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18100 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18101 	re->ipv6RouteIfIndex.o_length = 0;
18102 	ipif = ire->ire_ipif;
18103 	if (ire->ire_type == IRE_CACHE) {
18104 		ill = (ill_t *)ire->ire_stq->q_ptr;
18105 		re->ipv6RouteIfIndex.o_length =
18106 		    ill->ill_name_length == 0 ? 0 :
18107 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18108 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18109 		    re->ipv6RouteIfIndex.o_length);
18110 	} else if (ipif != NULL) {
18111 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18112 		    OCTET_LENGTH);
18113 		re->ipv6RouteIfIndex.o_length =
18114 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18115 	}
18116 
18117 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18118 
18119 	mutex_enter(&ire->ire_lock);
18120 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18121 	mutex_exit(&ire->ire_lock);
18122 
18123 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18124 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18125 	else
18126 		re->ipv6RouteNextHop = gw_addr_v6;
18127 
18128 	/* remote(4), local(3), or discard(2) */
18129 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18130 		re->ipv6RouteType = 2;
18131 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18132 		re->ipv6RouteType = 3;
18133 	else
18134 		re->ipv6RouteType = 4;
18135 
18136 	re->ipv6RouteProtocol	= -1;
18137 	re->ipv6RoutePolicy	= 0;
18138 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18139 	re->ipv6RouteNextHopRDI	= 0;
18140 	re->ipv6RouteWeight	= 0;
18141 	re->ipv6RouteMetric	= 0;
18142 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18143 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18144 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18145 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18146 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18147 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18148 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18149 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18150 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18151 
18152 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18153 	    (char *)re, (int)sizeof (*re))) {
18154 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18155 		    (uint_t)sizeof (*re)));
18156 	}
18157 
18158 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18159 		iaeptr->iae_routeidx = ird->ird_idx;
18160 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18161 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18162 	}
18163 
18164 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18165 	    (char *)iae, sacnt * sizeof (*iae))) {
18166 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18167 		    (unsigned)(sacnt * sizeof (*iae))));
18168 	}
18169 
18170 	/* bump route index for next pass */
18171 	ird->ird_idx++;
18172 
18173 	kmem_free(re, sizeof (*re));
18174 	if (sacnt != 0)
18175 		kmem_free(iae, sacnt * sizeof (*iae));
18176 
18177 	if (gcgrp != NULL)
18178 		rw_exit(&gcgrp->gcgrp_rwlock);
18179 }
18180 
18181 /*
18182  * ndp_walk routine to create ipv6NetToMediaEntryTable
18183  */
18184 static int
18185 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18186 {
18187 	ill_t				*ill;
18188 	mib2_ipv6NetToMediaEntry_t	ntme;
18189 	dl_unitdata_req_t		*dl;
18190 
18191 	ill = nce->nce_ill;
18192 	ASSERT(ill->ill_isv6);
18193 
18194 	/*
18195 	 * Neighbor cache entry attached to IRE with on-link
18196 	 * destination.
18197 	 */
18198 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18199 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18200 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18201 	    (nce->nce_res_mp != NULL)) {
18202 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18203 		ntme.ipv6NetToMediaPhysAddress.o_length =
18204 		    dl->dl_dest_addr_length;
18205 	} else {
18206 		ntme.ipv6NetToMediaPhysAddress.o_length =
18207 		    ill->ill_phys_addr_length;
18208 	}
18209 	if (nce->nce_res_mp != NULL) {
18210 		bcopy((char *)nce->nce_res_mp->b_rptr +
18211 		    NCE_LL_ADDR_OFFSET(ill),
18212 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18213 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18214 	} else {
18215 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18216 		    ill->ill_phys_addr_length);
18217 	}
18218 	/*
18219 	 * Note: Returns ND_* states. Should be:
18220 	 * reachable(1), stale(2), delay(3), probe(4),
18221 	 * invalid(5), unknown(6)
18222 	 */
18223 	ntme.ipv6NetToMediaState = nce->nce_state;
18224 	ntme.ipv6NetToMediaLastUpdated = 0;
18225 
18226 	/* other(1), dynamic(2), static(3), local(4) */
18227 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18228 		ntme.ipv6NetToMediaType = 4;
18229 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18230 		ntme.ipv6NetToMediaType = 1;
18231 	} else {
18232 		ntme.ipv6NetToMediaType = 2;
18233 	}
18234 
18235 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18236 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18237 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18238 		    (uint_t)sizeof (ntme)));
18239 	}
18240 	return (0);
18241 }
18242 
18243 /*
18244  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18245  */
18246 /* ARGSUSED */
18247 int
18248 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18249 {
18250 	switch (level) {
18251 	case MIB2_IP:
18252 	case MIB2_ICMP:
18253 		switch (name) {
18254 		default:
18255 			break;
18256 		}
18257 		return (1);
18258 	default:
18259 		return (1);
18260 	}
18261 }
18262 
18263 /*
18264  * Called before the options are updated to check if this packet will
18265  * be source routed from here.
18266  * This routine assumes that the options are well formed i.e. that they
18267  * have already been checked.
18268  */
18269 static boolean_t
18270 ip_source_routed(ipha_t *ipha)
18271 {
18272 	ipoptp_t	opts;
18273 	uchar_t		*opt;
18274 	uint8_t		optval;
18275 	uint8_t		optlen;
18276 	ipaddr_t	dst;
18277 	ire_t		*ire;
18278 
18279 	if (IS_SIMPLE_IPH(ipha)) {
18280 		ip2dbg(("not source routed\n"));
18281 		return (B_FALSE);
18282 	}
18283 	dst = ipha->ipha_dst;
18284 	for (optval = ipoptp_first(&opts, ipha);
18285 	    optval != IPOPT_EOL;
18286 	    optval = ipoptp_next(&opts)) {
18287 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18288 		opt = opts.ipoptp_cur;
18289 		optlen = opts.ipoptp_len;
18290 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18291 		    optval, optlen));
18292 		switch (optval) {
18293 			uint32_t off;
18294 		case IPOPT_SSRR:
18295 		case IPOPT_LSRR:
18296 			/*
18297 			 * If dst is one of our addresses and there are some
18298 			 * entries left in the source route return (true).
18299 			 */
18300 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18301 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18302 			if (ire == NULL) {
18303 				ip2dbg(("ip_source_routed: not next"
18304 				    " source route 0x%x\n",
18305 				    ntohl(dst)));
18306 				return (B_FALSE);
18307 			}
18308 			ire_refrele(ire);
18309 			off = opt[IPOPT_OFFSET];
18310 			off--;
18311 			if (optlen < IP_ADDR_LEN ||
18312 			    off > optlen - IP_ADDR_LEN) {
18313 				/* End of source route */
18314 				ip1dbg(("ip_source_routed: end of SR\n"));
18315 				return (B_FALSE);
18316 			}
18317 			return (B_TRUE);
18318 		}
18319 	}
18320 	ip2dbg(("not source routed\n"));
18321 	return (B_FALSE);
18322 }
18323 
18324 /*
18325  * Check if the packet contains any source route.
18326  */
18327 static boolean_t
18328 ip_source_route_included(ipha_t *ipha)
18329 {
18330 	ipoptp_t	opts;
18331 	uint8_t		optval;
18332 
18333 	if (IS_SIMPLE_IPH(ipha))
18334 		return (B_FALSE);
18335 	for (optval = ipoptp_first(&opts, ipha);
18336 	    optval != IPOPT_EOL;
18337 	    optval = ipoptp_next(&opts)) {
18338 		switch (optval) {
18339 		case IPOPT_SSRR:
18340 		case IPOPT_LSRR:
18341 			return (B_TRUE);
18342 		}
18343 	}
18344 	return (B_FALSE);
18345 }
18346 
18347 /*
18348  * Called when the IRE expiration timer fires.
18349  */
18350 /* ARGSUSED */
18351 void
18352 ip_trash_timer_expire(void *args)
18353 {
18354 	int	flush_flag = 0;
18355 
18356 	/*
18357 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18358 	 * This lock makes sure that a new invocation of this function
18359 	 * that occurs due to an almost immediate timer firing will not
18360 	 * progress beyond this point until the current invocation is done
18361 	 */
18362 	mutex_enter(&ip_trash_timer_lock);
18363 	ip_ire_expire_id = 0;
18364 	mutex_exit(&ip_trash_timer_lock);
18365 
18366 	/* Periodic timer */
18367 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18368 		/*
18369 		 * Remove all IRE_CACHE entries since they might
18370 		 * contain arp information.
18371 		 */
18372 		flush_flag |= FLUSH_ARP_TIME;
18373 		ip_ire_arp_time_elapsed = 0;
18374 		IP_STAT(ip_ire_arp_timer_expired);
18375 	}
18376 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18377 		/* Remove all redirects */
18378 		flush_flag |= FLUSH_REDIRECT_TIME;
18379 		ip_ire_rd_time_elapsed = 0;
18380 		IP_STAT(ip_ire_redirect_timer_expired);
18381 	}
18382 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18383 		/* Increase path mtu */
18384 		flush_flag |= FLUSH_MTU_TIME;
18385 		ip_ire_pmtu_time_elapsed = 0;
18386 		IP_STAT(ip_ire_pmtu_timer_expired);
18387 	}
18388 	if (flush_flag != 0) {
18389 		/* Walk all IPv4 IRE's and update them */
18390 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
18391 		    ALL_ZONES);
18392 	}
18393 	if (flush_flag & FLUSH_MTU_TIME) {
18394 		/*
18395 		 * Walk all IPv6 IRE's and update them
18396 		 * Note that ARP and redirect timers are not
18397 		 * needed since NUD handles stale entries.
18398 		 */
18399 		flush_flag = FLUSH_MTU_TIME;
18400 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18401 		    ALL_ZONES);
18402 	}
18403 
18404 	ip_ire_arp_time_elapsed += ip_timer_interval;
18405 	ip_ire_rd_time_elapsed += ip_timer_interval;
18406 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
18407 
18408 	/*
18409 	 * Hold the lock to serialize timeout calls and prevent
18410 	 * stale values in ip_ire_expire_id. Otherwise it is possible
18411 	 * for the timer to fire and a new invocation of this function
18412 	 * to start before the return value of timeout has been stored
18413 	 * in ip_ire_expire_id by the current invocation.
18414 	 */
18415 	mutex_enter(&ip_trash_timer_lock);
18416 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
18417 	    MSEC_TO_TICK(ip_timer_interval));
18418 	mutex_exit(&ip_trash_timer_lock);
18419 }
18420 
18421 /*
18422  * Called by the memory allocator subsystem directly, when the system
18423  * is running low on memory.
18424  */
18425 /* ARGSUSED */
18426 void
18427 ip_trash_ire_reclaim(void *args)
18428 {
18429 	ire_cache_count_t icc;
18430 	ire_cache_reclaim_t icr;
18431 	ncc_cache_count_t ncc;
18432 	nce_cache_reclaim_t ncr;
18433 	uint_t delete_cnt;
18434 	/*
18435 	 * Memory reclaim call back.
18436 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
18437 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
18438 	 * entries, determine what fraction to free for
18439 	 * each category of IRE_CACHE entries giving absolute priority
18440 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
18441 	 * entry will be freed unless all offlink entries are freed).
18442 	 */
18443 	icc.icc_total = 0;
18444 	icc.icc_unused = 0;
18445 	icc.icc_offlink = 0;
18446 	icc.icc_pmtu = 0;
18447 	icc.icc_onlink = 0;
18448 	ire_walk(ire_cache_count, (char *)&icc);
18449 
18450 	/*
18451 	 * Free NCEs for IPv6 like the onlink ires.
18452 	 */
18453 	ncc.ncc_total = 0;
18454 	ncc.ncc_host = 0;
18455 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
18456 
18457 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
18458 	    icc.icc_pmtu + icc.icc_onlink);
18459 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
18460 	IP_STAT(ip_trash_ire_reclaim_calls);
18461 	if (delete_cnt == 0)
18462 		return;
18463 	IP_STAT(ip_trash_ire_reclaim_success);
18464 	/* Always delete all unused offlink entries */
18465 	icr.icr_unused = 1;
18466 	if (delete_cnt <= icc.icc_unused) {
18467 		/*
18468 		 * Only need to free unused entries.  In other words,
18469 		 * there are enough unused entries to free to meet our
18470 		 * target number of freed ire cache entries.
18471 		 */
18472 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
18473 		ncr.ncr_host = 0;
18474 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
18475 		/*
18476 		 * Only need to free unused entries, plus a fraction of offlink
18477 		 * entries.  It follows from the first if statement that
18478 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
18479 		 */
18480 		delete_cnt -= icc.icc_unused;
18481 		/* Round up # deleted by truncating fraction */
18482 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
18483 		icr.icr_pmtu = icr.icr_onlink = 0;
18484 		ncr.ncr_host = 0;
18485 	} else if (delete_cnt <=
18486 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
18487 		/*
18488 		 * Free all unused and offlink entries, plus a fraction of
18489 		 * pmtu entries.  It follows from the previous if statement
18490 		 * that icc_pmtu is non-zero, and that
18491 		 * delete_cnt != icc_unused + icc_offlink.
18492 		 */
18493 		icr.icr_offlink = 1;
18494 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
18495 		/* Round up # deleted by truncating fraction */
18496 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
18497 		icr.icr_onlink = 0;
18498 		ncr.ncr_host = 0;
18499 	} else {
18500 		/*
18501 		 * Free all unused, offlink, and pmtu entries, plus a fraction
18502 		 * of onlink entries.  If we're here, then we know that
18503 		 * icc_onlink is non-zero, and that
18504 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
18505 		 */
18506 		icr.icr_offlink = icr.icr_pmtu = 1;
18507 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
18508 		    icc.icc_pmtu;
18509 		/* Round up # deleted by truncating fraction */
18510 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
18511 		/* Using the same delete fraction as for onlink IREs */
18512 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
18513 	}
18514 #ifdef DEBUG
18515 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
18516 	    "fractions %d/%d/%d/%d\n",
18517 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
18518 	    icc.icc_unused, icc.icc_offlink,
18519 	    icc.icc_pmtu, icc.icc_onlink,
18520 	    icr.icr_unused, icr.icr_offlink,
18521 	    icr.icr_pmtu, icr.icr_onlink));
18522 #endif
18523 	ire_walk(ire_cache_reclaim, (char *)&icr);
18524 	if (ncr.ncr_host != 0)
18525 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
18526 		    (uchar_t *)&ncr);
18527 #ifdef DEBUG
18528 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
18529 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
18530 	ire_walk(ire_cache_count, (char *)&icc);
18531 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
18532 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
18533 	    icc.icc_pmtu, icc.icc_onlink));
18534 #endif
18535 }
18536 
18537 /*
18538  * ip_unbind is called when a copy of an unbind request is received from the
18539  * upper level protocol.  We remove this conn from any fanout hash list it is
18540  * on, and zero out the bind information.  No reply is expected up above.
18541  */
18542 mblk_t *
18543 ip_unbind(queue_t *q, mblk_t *mp)
18544 {
18545 	conn_t	*connp = Q_TO_CONN(q);
18546 
18547 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
18548 
18549 	if (is_system_labeled() && connp->conn_anon_port) {
18550 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
18551 		    connp->conn_mlp_type, connp->conn_ulp,
18552 		    ntohs(connp->conn_lport), B_FALSE);
18553 		connp->conn_anon_port = 0;
18554 	}
18555 	connp->conn_mlp_type = mlptSingle;
18556 
18557 	ipcl_hash_remove(connp);
18558 
18559 	ASSERT(mp->b_cont == NULL);
18560 	/*
18561 	 * Convert mp into a T_OK_ACK
18562 	 */
18563 	mp = mi_tpi_ok_ack_alloc(mp);
18564 
18565 	/*
18566 	 * should not happen in practice... T_OK_ACK is smaller than the
18567 	 * original message.
18568 	 */
18569 	if (mp == NULL)
18570 		return (NULL);
18571 
18572 	/*
18573 	 * Don't bzero the ports if its TCP since TCP still needs the
18574 	 * lport to remove it from its own bind hash. TCP will do the
18575 	 * cleanup.
18576 	 */
18577 	if (!IPCL_IS_TCP(connp))
18578 		bzero(&connp->u_port, sizeof (connp->u_port));
18579 
18580 	return (mp);
18581 }
18582 
18583 /*
18584  * Write side put procedure.  Outbound data, IOCTLs, responses from
18585  * resolvers, etc, come down through here.
18586  */
18587 void
18588 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
18589 {
18590 	conn_t		*connp = NULL;
18591 	queue_t		*q = (queue_t *)arg2;
18592 	ipha_t		*ipha;
18593 #define	rptr	((uchar_t *)ipha)
18594 	ire_t		*ire = NULL;
18595 	ire_t		*sctp_ire = NULL;
18596 	uint32_t	v_hlen_tos_len;
18597 	ipaddr_t	dst;
18598 	mblk_t		*first_mp = NULL;
18599 	boolean_t	mctl_present;
18600 	ipsec_out_t	*io;
18601 	int		match_flags;
18602 	ill_t		*attach_ill = NULL;
18603 					/* Bind to IPIF_NOFAILOVER ill etc. */
18604 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
18605 	ipif_t		*dst_ipif;
18606 	boolean_t	multirt_need_resolve = B_FALSE;
18607 	mblk_t		*copy_mp = NULL;
18608 	int		err;
18609 	zoneid_t	zoneid;
18610 	int	adjust;
18611 	uint16_t iplen;
18612 	boolean_t	need_decref = B_FALSE;
18613 	boolean_t	ignore_dontroute = B_FALSE;
18614 	boolean_t	ignore_nexthop = B_FALSE;
18615 	boolean_t	ip_nexthop = B_FALSE;
18616 	ipaddr_t	nexthop_addr;
18617 
18618 #ifdef	_BIG_ENDIAN
18619 #define	V_HLEN	(v_hlen_tos_len >> 24)
18620 #else
18621 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
18622 #endif
18623 
18624 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
18625 	    "ip_wput_start: q %p", q);
18626 
18627 	/*
18628 	 * ip_wput fast path
18629 	 */
18630 
18631 	/* is packet from ARP ? */
18632 	if (q->q_next != NULL)
18633 		goto qnext;
18634 
18635 	connp = (conn_t *)arg;
18636 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
18637 
18638 	/* is queue flow controlled? */
18639 	if ((q->q_first != NULL || connp->conn_draining) &&
18640 	    (caller == IP_WPUT)) {
18641 		ASSERT(!need_decref);
18642 		(void) putq(q, mp);
18643 		return;
18644 	}
18645 
18646 	/* Multidata transmit? */
18647 	if (DB_TYPE(mp) == M_MULTIDATA) {
18648 		/*
18649 		 * We should never get here, since all Multidata messages
18650 		 * originating from tcp should have been directed over to
18651 		 * tcp_multisend() in the first place.
18652 		 */
18653 		BUMP_MIB(&ip_mib, ipOutDiscards);
18654 		freemsg(mp);
18655 		return;
18656 	} else if (DB_TYPE(mp) != M_DATA)
18657 		goto notdata;
18658 
18659 	if (mp->b_flag & MSGHASREF) {
18660 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18661 		mp->b_flag &= ~MSGHASREF;
18662 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
18663 		need_decref = B_TRUE;
18664 	}
18665 	ipha = (ipha_t *)mp->b_rptr;
18666 
18667 	/* is IP header non-aligned or mblk smaller than basic IP header */
18668 #ifndef SAFETY_BEFORE_SPEED
18669 	if (!OK_32PTR(rptr) ||
18670 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
18671 		goto hdrtoosmall;
18672 #endif
18673 
18674 	ASSERT(OK_32PTR(ipha));
18675 
18676 	/*
18677 	 * This function assumes that mp points to an IPv4 packet.  If it's the
18678 	 * wrong version, we'll catch it again in ip_output_v6.
18679 	 *
18680 	 * Note that this is *only* locally-generated output here, and never
18681 	 * forwarded data, and that we need to deal only with transports that
18682 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
18683 	 * label.)
18684 	 */
18685 	if (is_system_labeled() &&
18686 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
18687 	    !connp->conn_ulp_labeled) {
18688 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
18689 		    connp->conn_mac_exempt);
18690 		ipha = (ipha_t *)mp->b_rptr;
18691 		if (err != 0) {
18692 			first_mp = mp;
18693 			if (err == EINVAL)
18694 				goto icmp_parameter_problem;
18695 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
18696 			goto drop_pkt;
18697 		}
18698 		iplen = ntohs(ipha->ipha_length) + adjust;
18699 		ipha->ipha_length = htons(iplen);
18700 	}
18701 
18702 	/*
18703 	 * If there is a policy, try to attach an ipsec_out in
18704 	 * the front. At the end, first_mp either points to a
18705 	 * M_DATA message or IPSEC_OUT message linked to a
18706 	 * M_DATA message. We have to do it now as we might
18707 	 * lose the "conn" if we go through ip_newroute.
18708 	 */
18709 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
18710 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
18711 		    ipha->ipha_protocol)) == NULL)) {
18712 			if (need_decref)
18713 				CONN_DEC_REF(connp);
18714 			return;
18715 		} else {
18716 			ASSERT(mp->b_datap->db_type == M_CTL);
18717 			first_mp = mp;
18718 			mp = mp->b_cont;
18719 			mctl_present = B_TRUE;
18720 		}
18721 	} else {
18722 		first_mp = mp;
18723 		mctl_present = B_FALSE;
18724 	}
18725 
18726 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18727 
18728 	/* is wrong version or IP options present */
18729 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
18730 		goto version_hdrlen_check;
18731 	dst = ipha->ipha_dst;
18732 
18733 	if (connp->conn_nofailover_ill != NULL) {
18734 		attach_ill = conn_get_held_ill(connp,
18735 		    &connp->conn_nofailover_ill, &err);
18736 		if (err == ILL_LOOKUP_FAILED) {
18737 			if (need_decref)
18738 				CONN_DEC_REF(connp);
18739 			freemsg(first_mp);
18740 			return;
18741 		}
18742 	}
18743 
18744 	/* is packet multicast? */
18745 	if (CLASSD(dst))
18746 		goto multicast;
18747 
18748 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
18749 	    (connp->conn_nexthop_set)) {
18750 		/*
18751 		 * If the destination is a broadcast or a loopback
18752 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
18753 		 * through the standard path. But in the case of local
18754 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
18755 		 * the standard path not IP_XMIT_IF.
18756 		 */
18757 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18758 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
18759 		    (ire->ire_type != IRE_LOOPBACK))) {
18760 			if ((connp->conn_dontroute ||
18761 			    connp->conn_nexthop_set) && (ire != NULL) &&
18762 			    (ire->ire_type == IRE_LOCAL))
18763 				goto standard_path;
18764 
18765 			if (ire != NULL) {
18766 				ire_refrele(ire);
18767 				/* No more access to ire */
18768 				ire = NULL;
18769 			}
18770 			/*
18771 			 * bypass routing checks and go directly to
18772 			 * interface.
18773 			 */
18774 			if (connp->conn_dontroute) {
18775 				goto dontroute;
18776 			} else if (connp->conn_nexthop_set) {
18777 				ip_nexthop = B_TRUE;
18778 				nexthop_addr = connp->conn_nexthop_v4;
18779 				goto send_from_ill;
18780 			}
18781 
18782 			/*
18783 			 * If IP_XMIT_IF socket option is set,
18784 			 * then we allow unicast and multicast
18785 			 * packets to go through the ill. It is
18786 			 * quite possible that the destination
18787 			 * is not in the ire cache table and we
18788 			 * do not want to go to ip_newroute()
18789 			 * instead we call ip_newroute_ipif.
18790 			 */
18791 			xmit_ill = conn_get_held_ill(connp,
18792 			    &connp->conn_xmit_if_ill, &err);
18793 			if (err == ILL_LOOKUP_FAILED) {
18794 				if (attach_ill != NULL)
18795 					ill_refrele(attach_ill);
18796 				if (need_decref)
18797 					CONN_DEC_REF(connp);
18798 				freemsg(first_mp);
18799 				return;
18800 			}
18801 			goto send_from_ill;
18802 		}
18803 standard_path:
18804 		/* Must be a broadcast, a loopback or a local ire */
18805 		if (ire != NULL) {
18806 			ire_refrele(ire);
18807 			/* No more access to ire */
18808 			ire = NULL;
18809 		}
18810 	}
18811 
18812 	if (attach_ill != NULL)
18813 		goto send_from_ill;
18814 
18815 	/*
18816 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18817 	 * this for the tcp global queue and listen end point
18818 	 * as it does not really have a real destination to
18819 	 * talk to.  This is also true for SCTP.
18820 	 */
18821 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18822 	    !connp->conn_fully_bound) {
18823 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18824 		if (ire == NULL)
18825 			goto noirefound;
18826 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18827 		    "ip_wput_end: q %p (%S)", q, "end");
18828 
18829 		/*
18830 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18831 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18832 		 */
18833 		if (ire->ire_flags & RTF_MULTIRT) {
18834 
18835 			/*
18836 			 * Force the TTL of multirouted packets if required.
18837 			 * The TTL of such packets is bounded by the
18838 			 * ip_multirt_ttl ndd variable.
18839 			 */
18840 			if ((ip_multirt_ttl > 0) &&
18841 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18842 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18843 				    "(was %d), dst 0x%08x\n",
18844 				    ip_multirt_ttl, ipha->ipha_ttl,
18845 				    ntohl(ire->ire_addr)));
18846 				ipha->ipha_ttl = ip_multirt_ttl;
18847 			}
18848 			/*
18849 			 * We look at this point if there are pending
18850 			 * unresolved routes. ire_multirt_resolvable()
18851 			 * checks in O(n) that all IRE_OFFSUBNET ire
18852 			 * entries for the packet's destination and
18853 			 * flagged RTF_MULTIRT are currently resolved.
18854 			 * If some remain unresolved, we make a copy
18855 			 * of the current message. It will be used
18856 			 * to initiate additional route resolutions.
18857 			 */
18858 			multirt_need_resolve =
18859 			    ire_multirt_need_resolve(ire->ire_addr,
18860 			    MBLK_GETLABEL(first_mp));
18861 			ip2dbg(("ip_wput[TCP]: ire %p, "
18862 			    "multirt_need_resolve %d, first_mp %p\n",
18863 			    (void *)ire, multirt_need_resolve,
18864 			    (void *)first_mp));
18865 			if (multirt_need_resolve) {
18866 				copy_mp = copymsg(first_mp);
18867 				if (copy_mp != NULL) {
18868 					MULTIRT_DEBUG_TAG(copy_mp);
18869 				}
18870 			}
18871 		}
18872 
18873 		ip_wput_ire(q, first_mp, ire, connp, caller);
18874 
18875 		/*
18876 		 * Try to resolve another multiroute if
18877 		 * ire_multirt_need_resolve() deemed it necessary.
18878 		 */
18879 		if (copy_mp != NULL) {
18880 			ip_newroute(q, copy_mp, dst, NULL, connp);
18881 		}
18882 		if (need_decref)
18883 			CONN_DEC_REF(connp);
18884 		return;
18885 	}
18886 
18887 	/*
18888 	 * Access to conn_ire_cache. (protected by conn_lock)
18889 	 *
18890 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18891 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18892 	 * send a packet or two with the IRE_CACHE that is going away.
18893 	 * Access to the ire requires an ire refhold on the ire prior to
18894 	 * its use since an interface unplumb thread may delete the cached
18895 	 * ire and release the refhold at any time.
18896 	 *
18897 	 * Caching an ire in the conn_ire_cache
18898 	 *
18899 	 * o Caching an ire pointer in the conn requires a strict check for
18900 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18901 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18902 	 * in the conn is done after making sure under the bucket lock that the
18903 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18904 	 * caching an ire after the unplumb thread has cleaned up the conn.
18905 	 * If the conn does not send a packet subsequently the unplumb thread
18906 	 * will be hanging waiting for the ire count to drop to zero.
18907 	 *
18908 	 * o We also need to atomically test for a null conn_ire_cache and
18909 	 * set the conn_ire_cache under the the protection of the conn_lock
18910 	 * to avoid races among concurrent threads trying to simultaneously
18911 	 * cache an ire in the conn_ire_cache.
18912 	 */
18913 	mutex_enter(&connp->conn_lock);
18914 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18915 
18916 	if (ire != NULL && ire->ire_addr == dst &&
18917 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18918 
18919 		IRE_REFHOLD(ire);
18920 		mutex_exit(&connp->conn_lock);
18921 
18922 	} else {
18923 		boolean_t cached = B_FALSE;
18924 		connp->conn_ire_cache = NULL;
18925 		mutex_exit(&connp->conn_lock);
18926 		/* Release the old ire */
18927 		if (ire != NULL && sctp_ire == NULL)
18928 			IRE_REFRELE_NOTR(ire);
18929 
18930 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18931 		if (ire == NULL)
18932 			goto noirefound;
18933 		IRE_REFHOLD_NOTR(ire);
18934 
18935 		mutex_enter(&connp->conn_lock);
18936 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18937 		    connp->conn_ire_cache == NULL) {
18938 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18939 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18940 				connp->conn_ire_cache = ire;
18941 				cached = B_TRUE;
18942 			}
18943 			rw_exit(&ire->ire_bucket->irb_lock);
18944 		}
18945 		mutex_exit(&connp->conn_lock);
18946 
18947 		/*
18948 		 * We can continue to use the ire but since it was
18949 		 * not cached, we should drop the extra reference.
18950 		 */
18951 		if (!cached)
18952 			IRE_REFRELE_NOTR(ire);
18953 	}
18954 
18955 
18956 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18957 	    "ip_wput_end: q %p (%S)", q, "end");
18958 
18959 	/*
18960 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18961 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18962 	 */
18963 	if (ire->ire_flags & RTF_MULTIRT) {
18964 
18965 		/*
18966 		 * Force the TTL of multirouted packets if required.
18967 		 * The TTL of such packets is bounded by the
18968 		 * ip_multirt_ttl ndd variable.
18969 		 */
18970 		if ((ip_multirt_ttl > 0) &&
18971 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18972 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18973 			    "(was %d), dst 0x%08x\n",
18974 			    ip_multirt_ttl, ipha->ipha_ttl,
18975 			    ntohl(ire->ire_addr)));
18976 			ipha->ipha_ttl = ip_multirt_ttl;
18977 		}
18978 
18979 		/*
18980 		 * At this point, we check to see if there are any pending
18981 		 * unresolved routes. ire_multirt_resolvable()
18982 		 * checks in O(n) that all IRE_OFFSUBNET ire
18983 		 * entries for the packet's destination and
18984 		 * flagged RTF_MULTIRT are currently resolved.
18985 		 * If some remain unresolved, we make a copy
18986 		 * of the current message. It will be used
18987 		 * to initiate additional route resolutions.
18988 		 */
18989 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
18990 		    MBLK_GETLABEL(first_mp));
18991 		ip2dbg(("ip_wput[not TCP]: ire %p, "
18992 		    "multirt_need_resolve %d, first_mp %p\n",
18993 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
18994 		if (multirt_need_resolve) {
18995 			copy_mp = copymsg(first_mp);
18996 			if (copy_mp != NULL) {
18997 				MULTIRT_DEBUG_TAG(copy_mp);
18998 			}
18999 		}
19000 	}
19001 
19002 	ip_wput_ire(q, first_mp, ire, connp, caller);
19003 
19004 	/*
19005 	 * Try to resolve another multiroute if
19006 	 * ire_multirt_resolvable() deemed it necessary
19007 	 */
19008 	if (copy_mp != NULL) {
19009 		ip_newroute(q, copy_mp, dst, NULL, connp);
19010 	}
19011 	if (need_decref)
19012 		CONN_DEC_REF(connp);
19013 	return;
19014 
19015 qnext:
19016 	/*
19017 	 * Upper Level Protocols pass down complete IP datagrams
19018 	 * as M_DATA messages.	Everything else is a sideshow.
19019 	 *
19020 	 * 1) We could be re-entering ip_wput because of ip_neworute
19021 	 *    in which case we could have a IPSEC_OUT message. We
19022 	 *    need to pass through ip_wput like other datagrams and
19023 	 *    hence cannot branch to ip_wput_nondata.
19024 	 *
19025 	 * 2) ARP, AH, ESP, and other clients who are on the module
19026 	 *    instance of IP stream, give us something to deal with.
19027 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19028 	 *
19029 	 * 3) ICMP replies also could come here.
19030 	 */
19031 	if (DB_TYPE(mp) != M_DATA) {
19032 	    notdata:
19033 		if (DB_TYPE(mp) == M_CTL) {
19034 			/*
19035 			 * M_CTL messages are used by ARP, AH and ESP to
19036 			 * communicate with IP. We deal with IPSEC_IN and
19037 			 * IPSEC_OUT here. ip_wput_nondata handles other
19038 			 * cases.
19039 			 */
19040 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19041 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19042 				first_mp = mp->b_cont;
19043 				first_mp->b_flag &= ~MSGHASREF;
19044 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19045 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19046 				CONN_DEC_REF(connp);
19047 				connp = NULL;
19048 			}
19049 			if (ii->ipsec_info_type == IPSEC_IN) {
19050 				/*
19051 				 * Either this message goes back to
19052 				 * IPSEC for further processing or to
19053 				 * ULP after policy checks.
19054 				 */
19055 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19056 				return;
19057 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19058 				io = (ipsec_out_t *)ii;
19059 				if (io->ipsec_out_proc_begin) {
19060 					/*
19061 					 * IPSEC processing has already started.
19062 					 * Complete it.
19063 					 * IPQoS notes: We don't care what is
19064 					 * in ipsec_out_ill_index since this
19065 					 * won't be processed for IPQoS policies
19066 					 * in ipsec_out_process.
19067 					 */
19068 					ipsec_out_process(q, mp, NULL,
19069 					    io->ipsec_out_ill_index);
19070 					return;
19071 				} else {
19072 					connp = (q->q_next != NULL) ?
19073 					    NULL : Q_TO_CONN(q);
19074 					first_mp = mp;
19075 					mp = mp->b_cont;
19076 					mctl_present = B_TRUE;
19077 				}
19078 				zoneid = io->ipsec_out_zoneid;
19079 				ASSERT(zoneid != ALL_ZONES);
19080 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19081 				/*
19082 				 * It's an IPsec control message requesting
19083 				 * an SADB update to be sent to the IPsec
19084 				 * hardware acceleration capable ills.
19085 				 */
19086 				ipsec_ctl_t *ipsec_ctl =
19087 				    (ipsec_ctl_t *)mp->b_rptr;
19088 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19089 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19090 				mblk_t *cmp = mp->b_cont;
19091 
19092 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19093 				ASSERT(cmp != NULL);
19094 
19095 				freeb(mp);
19096 				ill_ipsec_capab_send_all(satype, cmp, sa);
19097 				return;
19098 			} else {
19099 				/*
19100 				 * This must be ARP or special TSOL signaling.
19101 				 */
19102 				ip_wput_nondata(NULL, q, mp, NULL);
19103 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19104 				    "ip_wput_end: q %p (%S)", q, "nondata");
19105 				return;
19106 			}
19107 		} else {
19108 			/*
19109 			 * This must be non-(ARP/AH/ESP) messages.
19110 			 */
19111 			ASSERT(!need_decref);
19112 			ip_wput_nondata(NULL, q, mp, NULL);
19113 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19114 			    "ip_wput_end: q %p (%S)", q, "nondata");
19115 			return;
19116 		}
19117 	} else {
19118 		first_mp = mp;
19119 		mctl_present = B_FALSE;
19120 	}
19121 
19122 	ASSERT(first_mp != NULL);
19123 	/*
19124 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19125 	 * to make sure that this packet goes out on the same interface it
19126 	 * came in. We handle that here.
19127 	 */
19128 	if (mctl_present) {
19129 		uint_t ifindex;
19130 
19131 		io = (ipsec_out_t *)first_mp->b_rptr;
19132 		if (io->ipsec_out_attach_if ||
19133 		    io->ipsec_out_xmit_if ||
19134 		    io->ipsec_out_ip_nexthop) {
19135 			ill_t	*ill;
19136 
19137 			/*
19138 			 * We may have lost the conn context if we are
19139 			 * coming here from ip_newroute(). Copy the
19140 			 * nexthop information.
19141 			 */
19142 			if (io->ipsec_out_ip_nexthop) {
19143 				ip_nexthop = B_TRUE;
19144 				nexthop_addr = io->ipsec_out_nexthop_addr;
19145 
19146 				ipha = (ipha_t *)mp->b_rptr;
19147 				dst = ipha->ipha_dst;
19148 				goto send_from_ill;
19149 			} else {
19150 				ASSERT(io->ipsec_out_ill_index != 0);
19151 				ifindex = io->ipsec_out_ill_index;
19152 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19153 				    NULL, NULL, NULL, NULL);
19154 				/*
19155 				 * ipsec_out_xmit_if bit is used to tell
19156 				 * ip_wput to use the ill to send outgoing data
19157 				 * as we have no conn when data comes from ICMP
19158 				 * error msg routines. Currently this feature is
19159 				 * only used by ip_mrtun_forward routine.
19160 				 */
19161 				if (io->ipsec_out_xmit_if) {
19162 					xmit_ill = ill;
19163 					if (xmit_ill == NULL) {
19164 						ip1dbg(("ip_output:bad ifindex "
19165 						    "for xmit_ill %d\n",
19166 						    ifindex));
19167 						freemsg(first_mp);
19168 						BUMP_MIB(&ip_mib,
19169 						    ipOutDiscards);
19170 						ASSERT(!need_decref);
19171 						return;
19172 					}
19173 					/* Free up the ipsec_out_t mblk */
19174 					ASSERT(first_mp->b_cont == mp);
19175 					first_mp->b_cont = NULL;
19176 					freeb(first_mp);
19177 					/* Just send the IP header+ICMP+data */
19178 					first_mp = mp;
19179 					ipha = (ipha_t *)mp->b_rptr;
19180 					dst = ipha->ipha_dst;
19181 					goto send_from_ill;
19182 				} else {
19183 					attach_ill = ill;
19184 				}
19185 
19186 				if (attach_ill == NULL) {
19187 					ASSERT(xmit_ill == NULL);
19188 					ip1dbg(("ip_output: bad ifindex for "
19189 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19190 					    ifindex));
19191 					freemsg(first_mp);
19192 					BUMP_MIB(&ip_mib, ipOutDiscards);
19193 					ASSERT(!need_decref);
19194 					return;
19195 				}
19196 			}
19197 		}
19198 	}
19199 
19200 	ASSERT(xmit_ill == NULL);
19201 
19202 	/* We have a complete IP datagram heading outbound. */
19203 	ipha = (ipha_t *)mp->b_rptr;
19204 
19205 #ifndef SPEED_BEFORE_SAFETY
19206 	/*
19207 	 * Make sure we have a full-word aligned message and that at least
19208 	 * a simple IP header is accessible in the first message.  If not,
19209 	 * try a pullup.
19210 	 */
19211 	if (!OK_32PTR(rptr) ||
19212 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19213 	    hdrtoosmall:
19214 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19215 			BUMP_MIB(&ip_mib, ipOutDiscards);
19216 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19217 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19218 			if (first_mp == NULL)
19219 				first_mp = mp;
19220 			goto drop_pkt;
19221 		}
19222 
19223 		/* This function assumes that mp points to an IPv4 packet. */
19224 		if (is_system_labeled() && q->q_next == NULL &&
19225 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19226 		    !connp->conn_ulp_labeled) {
19227 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19228 			    &adjust, connp->conn_mac_exempt);
19229 			ipha = (ipha_t *)mp->b_rptr;
19230 			if (first_mp != NULL)
19231 				first_mp->b_cont = mp;
19232 			if (err != 0) {
19233 				if (first_mp == NULL)
19234 					first_mp = mp;
19235 				if (err == EINVAL)
19236 					goto icmp_parameter_problem;
19237 				ip2dbg(("ip_wput: label check failed (%d)\n",
19238 				    err));
19239 				goto drop_pkt;
19240 			}
19241 			iplen = ntohs(ipha->ipha_length) + adjust;
19242 			ipha->ipha_length = htons(iplen);
19243 		}
19244 
19245 		ipha = (ipha_t *)mp->b_rptr;
19246 		if (first_mp == NULL) {
19247 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19248 			/*
19249 			 * If we got here because of "goto hdrtoosmall"
19250 			 * We need to attach a IPSEC_OUT.
19251 			 */
19252 			if (connp->conn_out_enforce_policy) {
19253 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19254 				    NULL, ipha->ipha_protocol)) == NULL)) {
19255 					if (need_decref)
19256 						CONN_DEC_REF(connp);
19257 					return;
19258 				} else {
19259 					ASSERT(mp->b_datap->db_type == M_CTL);
19260 					first_mp = mp;
19261 					mp = mp->b_cont;
19262 					mctl_present = B_TRUE;
19263 				}
19264 			} else {
19265 				first_mp = mp;
19266 				mctl_present = B_FALSE;
19267 			}
19268 		}
19269 	}
19270 #endif
19271 
19272 	/* Most of the code below is written for speed, not readability */
19273 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19274 
19275 	/*
19276 	 * If ip_newroute() fails, we're going to need a full
19277 	 * header for the icmp wraparound.
19278 	 */
19279 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19280 		uint_t	v_hlen;
19281 	    version_hdrlen_check:
19282 		ASSERT(first_mp != NULL);
19283 		v_hlen = V_HLEN;
19284 		/*
19285 		 * siphon off IPv6 packets coming down from transport
19286 		 * layer modules here.
19287 		 * Note: high-order bit carries NUD reachability confirmation
19288 		 */
19289 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19290 			/*
19291 			 * XXX implement a IPv4 and IPv6 packet counter per
19292 			 * conn and switch when ratio exceeds e.g. 10:1
19293 			 */
19294 #ifdef notyet
19295 			if (q->q_next == NULL) /* Avoid ill queue */
19296 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19297 #endif
19298 			BUMP_MIB(&ip_mib, ipOutIPv6);
19299 			ASSERT(xmit_ill == NULL);
19300 			if (attach_ill != NULL)
19301 				ill_refrele(attach_ill);
19302 			if (need_decref)
19303 				mp->b_flag |= MSGHASREF;
19304 			(void) ip_output_v6(connp, first_mp, q, caller);
19305 			return;
19306 		}
19307 
19308 		if ((v_hlen >> 4) != IP_VERSION) {
19309 			BUMP_MIB(&ip_mib, ipOutDiscards);
19310 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19311 			    "ip_wput_end: q %p (%S)", q, "badvers");
19312 			goto drop_pkt;
19313 		}
19314 		/*
19315 		 * Is the header length at least 20 bytes?
19316 		 *
19317 		 * Are there enough bytes accessible in the header?  If
19318 		 * not, try a pullup.
19319 		 */
19320 		v_hlen &= 0xF;
19321 		v_hlen <<= 2;
19322 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19323 			BUMP_MIB(&ip_mib, ipOutDiscards);
19324 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19325 			    "ip_wput_end: q %p (%S)", q, "badlen");
19326 			goto drop_pkt;
19327 		}
19328 		if (v_hlen > (mp->b_wptr - rptr)) {
19329 			if (!pullupmsg(mp, v_hlen)) {
19330 				BUMP_MIB(&ip_mib, ipOutDiscards);
19331 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19332 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19333 				goto drop_pkt;
19334 			}
19335 			ipha = (ipha_t *)mp->b_rptr;
19336 		}
19337 		/*
19338 		 * Move first entry from any source route into ipha_dst and
19339 		 * verify the options
19340 		 */
19341 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19342 			ASSERT(xmit_ill == NULL);
19343 			if (attach_ill != NULL)
19344 				ill_refrele(attach_ill);
19345 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19346 			    "ip_wput_end: q %p (%S)", q, "badopts");
19347 			if (need_decref)
19348 				CONN_DEC_REF(connp);
19349 			return;
19350 		}
19351 	}
19352 	dst = ipha->ipha_dst;
19353 
19354 	/*
19355 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19356 	 * we have to run the packet through ip_newroute which will take
19357 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19358 	 * a resolver, or assigning a default gateway, etc.
19359 	 */
19360 	if (CLASSD(dst)) {
19361 		ipif_t	*ipif;
19362 		uint32_t setsrc = 0;
19363 
19364 	    multicast:
19365 		ASSERT(first_mp != NULL);
19366 		ASSERT(xmit_ill == NULL);
19367 		ip2dbg(("ip_wput: CLASSD\n"));
19368 		if (connp == NULL) {
19369 			/*
19370 			 * Use the first good ipif on the ill.
19371 			 * XXX Should this ever happen? (Appears
19372 			 * to show up with just ppp and no ethernet due
19373 			 * to in.rdisc.)
19374 			 * However, ire_send should be able to
19375 			 * call ip_wput_ire directly.
19376 			 *
19377 			 * XXX Also, this can happen for ICMP and other packets
19378 			 * with multicast source addresses.  Perhaps we should
19379 			 * fix things so that we drop the packet in question,
19380 			 * but for now, just run with it.
19381 			 */
19382 			ill_t *ill = (ill_t *)q->q_ptr;
19383 
19384 			/*
19385 			 * Don't honor attach_if for this case. If ill
19386 			 * is part of the group, ipif could belong to
19387 			 * any ill and we cannot maintain attach_ill
19388 			 * and ipif_ill same anymore and the assert
19389 			 * below would fail.
19390 			 */
19391 			if (mctl_present) {
19392 				io->ipsec_out_ill_index = 0;
19393 				io->ipsec_out_attach_if = B_FALSE;
19394 				ASSERT(attach_ill != NULL);
19395 				ill_refrele(attach_ill);
19396 				attach_ill = NULL;
19397 			}
19398 
19399 			ASSERT(attach_ill == NULL);
19400 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19401 			if (ipif == NULL) {
19402 				if (need_decref)
19403 					CONN_DEC_REF(connp);
19404 				freemsg(first_mp);
19405 				return;
19406 			}
19407 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
19408 			    ntohl(dst), ill->ill_name));
19409 		} else {
19410 			/*
19411 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
19412 			 * IP_XMIT_IF is honoured.
19413 			 * Block comment above this function explains the
19414 			 * locking mechanism used here
19415 			 */
19416 			xmit_ill = conn_get_held_ill(connp,
19417 			    &connp->conn_xmit_if_ill, &err);
19418 			if (err == ILL_LOOKUP_FAILED) {
19419 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
19420 				goto drop_pkt;
19421 			}
19422 			if (xmit_ill == NULL) {
19423 				ipif = conn_get_held_ipif(connp,
19424 				    &connp->conn_multicast_ipif, &err);
19425 				if (err == IPIF_LOOKUP_FAILED) {
19426 					ip1dbg(("ip_wput: No ipif for "
19427 					    "multicast\n"));
19428 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19429 					goto drop_pkt;
19430 				}
19431 			}
19432 			if (xmit_ill != NULL) {
19433 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19434 				if (ipif == NULL) {
19435 					ip1dbg(("ip_wput: No ipif for "
19436 					    "IP_XMIT_IF\n"));
19437 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19438 					goto drop_pkt;
19439 				}
19440 			} else if (ipif == NULL || ipif->ipif_isv6) {
19441 				/*
19442 				 * We must do this ipif determination here
19443 				 * else we could pass through ip_newroute
19444 				 * and come back here without the conn context.
19445 				 *
19446 				 * Note: we do late binding i.e. we bind to
19447 				 * the interface when the first packet is sent.
19448 				 * For performance reasons we do not rebind on
19449 				 * each packet but keep the binding until the
19450 				 * next IP_MULTICAST_IF option.
19451 				 *
19452 				 * conn_multicast_{ipif,ill} are shared between
19453 				 * IPv4 and IPv6 and AF_INET6 sockets can
19454 				 * send both IPv4 and IPv6 packets. Hence
19455 				 * we have to check that "isv6" matches above.
19456 				 */
19457 				if (ipif != NULL)
19458 					ipif_refrele(ipif);
19459 				ipif = ipif_lookup_group(dst, zoneid);
19460 				if (ipif == NULL) {
19461 					ip1dbg(("ip_wput: No ipif for "
19462 					    "multicast\n"));
19463 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19464 					goto drop_pkt;
19465 				}
19466 				err = conn_set_held_ipif(connp,
19467 				    &connp->conn_multicast_ipif, ipif);
19468 				if (err == IPIF_LOOKUP_FAILED) {
19469 					ipif_refrele(ipif);
19470 					ip1dbg(("ip_wput: No ipif for "
19471 					    "multicast\n"));
19472 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19473 					goto drop_pkt;
19474 				}
19475 			}
19476 		}
19477 		ASSERT(!ipif->ipif_isv6);
19478 		/*
19479 		 * As we may lose the conn by the time we reach ip_wput_ire,
19480 		 * we copy conn_multicast_loop and conn_dontroute on to an
19481 		 * ipsec_out. In case if this datagram goes out secure,
19482 		 * we need the ill_index also. Copy that also into the
19483 		 * ipsec_out.
19484 		 */
19485 		if (mctl_present) {
19486 			io = (ipsec_out_t *)first_mp->b_rptr;
19487 			ASSERT(first_mp->b_datap->db_type == M_CTL);
19488 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
19489 		} else {
19490 			ASSERT(mp == first_mp);
19491 			if ((first_mp = allocb(sizeof (ipsec_info_t),
19492 			    BPRI_HI)) == NULL) {
19493 				ipif_refrele(ipif);
19494 				first_mp = mp;
19495 				goto drop_pkt;
19496 			}
19497 			first_mp->b_datap->db_type = M_CTL;
19498 			first_mp->b_wptr += sizeof (ipsec_info_t);
19499 			/* ipsec_out_secure is B_FALSE now */
19500 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
19501 			io = (ipsec_out_t *)first_mp->b_rptr;
19502 			io->ipsec_out_type = IPSEC_OUT;
19503 			io->ipsec_out_len = sizeof (ipsec_out_t);
19504 			io->ipsec_out_use_global_policy = B_TRUE;
19505 			first_mp->b_cont = mp;
19506 			mctl_present = B_TRUE;
19507 		}
19508 		if (attach_ill != NULL) {
19509 			ASSERT(attach_ill == ipif->ipif_ill);
19510 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19511 
19512 			/*
19513 			 * Check if we need an ire that will not be
19514 			 * looked up by anybody else i.e. HIDDEN.
19515 			 */
19516 			if (ill_is_probeonly(attach_ill)) {
19517 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19518 			}
19519 			io->ipsec_out_ill_index =
19520 			    attach_ill->ill_phyint->phyint_ifindex;
19521 			io->ipsec_out_attach_if = B_TRUE;
19522 		} else {
19523 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
19524 			io->ipsec_out_ill_index =
19525 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
19526 		}
19527 		if (connp != NULL) {
19528 			io->ipsec_out_multicast_loop =
19529 			    connp->conn_multicast_loop;
19530 			io->ipsec_out_dontroute = connp->conn_dontroute;
19531 			io->ipsec_out_zoneid = connp->conn_zoneid;
19532 		}
19533 		/*
19534 		 * If the application uses IP_MULTICAST_IF with
19535 		 * different logical addresses of the same ILL, we
19536 		 * need to make sure that the soruce address of
19537 		 * the packet matches the logical IP address used
19538 		 * in the option. We do it by initializing ipha_src
19539 		 * here. This should keep IPSEC also happy as
19540 		 * when we return from IPSEC processing, we don't
19541 		 * have to worry about getting the right address on
19542 		 * the packet. Thus it is sufficient to look for
19543 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
19544 		 * MATCH_IRE_IPIF.
19545 		 *
19546 		 * NOTE : We need to do it for non-secure case also as
19547 		 * this might go out secure if there is a global policy
19548 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
19549 		 * address, the source should be initialized already and
19550 		 * hence we won't be initializing here.
19551 		 *
19552 		 * As we do not have the ire yet, it is possible that
19553 		 * we set the source address here and then later discover
19554 		 * that the ire implies the source address to be assigned
19555 		 * through the RTF_SETSRC flag.
19556 		 * In that case, the setsrc variable will remind us
19557 		 * that overwritting the source address by the one
19558 		 * of the RTF_SETSRC-flagged ire is allowed.
19559 		 */
19560 		if (ipha->ipha_src == INADDR_ANY &&
19561 		    (connp == NULL || !connp->conn_unspec_src)) {
19562 			ipha->ipha_src = ipif->ipif_src_addr;
19563 			setsrc = RTF_SETSRC;
19564 		}
19565 		/*
19566 		 * Find an IRE which matches the destination and the outgoing
19567 		 * queue (i.e. the outgoing interface.)
19568 		 * For loopback use a unicast IP address for
19569 		 * the ire lookup.
19570 		 */
19571 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
19572 		    PHYI_LOOPBACK) {
19573 			dst = ipif->ipif_lcl_addr;
19574 		}
19575 		/*
19576 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
19577 		 * We don't need to lookup ire in ctable as the packet
19578 		 * needs to be sent to the destination through the specified
19579 		 * ill irrespective of ires in the cache table.
19580 		 */
19581 		ire = NULL;
19582 		if (xmit_ill == NULL) {
19583 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
19584 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19585 		}
19586 
19587 		/*
19588 		 * refrele attach_ill as its not needed anymore.
19589 		 */
19590 		if (attach_ill != NULL) {
19591 			ill_refrele(attach_ill);
19592 			attach_ill = NULL;
19593 		}
19594 
19595 		if (ire == NULL) {
19596 			/*
19597 			 * Multicast loopback and multicast forwarding is
19598 			 * done in ip_wput_ire.
19599 			 *
19600 			 * Mark this packet to make it be delivered to
19601 			 * ip_wput_ire after the new ire has been
19602 			 * created.
19603 			 *
19604 			 * The call to ip_newroute_ipif takes into account
19605 			 * the setsrc reminder. In any case, we take care
19606 			 * of the RTF_MULTIRT flag.
19607 			 */
19608 			mp->b_prev = mp->b_next = NULL;
19609 			if (xmit_ill == NULL ||
19610 			    xmit_ill->ill_ipif_up_count > 0) {
19611 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
19612 				    setsrc | RTF_MULTIRT);
19613 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19614 				    "ip_wput_end: q %p (%S)", q, "noire");
19615 			} else {
19616 				freemsg(first_mp);
19617 			}
19618 			ipif_refrele(ipif);
19619 			if (xmit_ill != NULL)
19620 				ill_refrele(xmit_ill);
19621 			if (need_decref)
19622 				CONN_DEC_REF(connp);
19623 			return;
19624 		}
19625 
19626 		ipif_refrele(ipif);
19627 		ipif = NULL;
19628 		ASSERT(xmit_ill == NULL);
19629 
19630 		/*
19631 		 * Honor the RTF_SETSRC flag for multicast packets,
19632 		 * if allowed by the setsrc reminder.
19633 		 */
19634 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
19635 			ipha->ipha_src = ire->ire_src_addr;
19636 		}
19637 
19638 		/*
19639 		 * Unconditionally force the TTL to 1 for
19640 		 * multirouted multicast packets:
19641 		 * multirouted multicast should not cross
19642 		 * multicast routers.
19643 		 */
19644 		if (ire->ire_flags & RTF_MULTIRT) {
19645 			if (ipha->ipha_ttl > 1) {
19646 				ip2dbg(("ip_wput: forcing multicast "
19647 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
19648 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
19649 				ipha->ipha_ttl = 1;
19650 			}
19651 		}
19652 	} else {
19653 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19654 		if ((ire != NULL) && (ire->ire_type &
19655 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
19656 			ignore_dontroute = B_TRUE;
19657 			ignore_nexthop = B_TRUE;
19658 		}
19659 		if (ire != NULL) {
19660 			ire_refrele(ire);
19661 			ire = NULL;
19662 		}
19663 		/*
19664 		 * Guard against coming in from arp in which case conn is NULL.
19665 		 * Also guard against non M_DATA with dontroute set but
19666 		 * destined to local, loopback or broadcast addresses.
19667 		 */
19668 		if (connp != NULL && connp->conn_dontroute &&
19669 		    !ignore_dontroute) {
19670 dontroute:
19671 			/*
19672 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
19673 			 * routing protocols from seeing false direct
19674 			 * connectivity.
19675 			 */
19676 			ipha->ipha_ttl = 1;
19677 			/*
19678 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
19679 			 * along with SO_DONTROUTE, higher precedence is
19680 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
19681 			 */
19682 			if (connp->conn_xmit_if_ill == NULL) {
19683 				/* If suitable ipif not found, drop packet */
19684 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
19685 				if (dst_ipif == NULL) {
19686 					ip1dbg(("ip_wput: no route for "
19687 					    "dst using SO_DONTROUTE\n"));
19688 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19689 					mp->b_prev = mp->b_next = NULL;
19690 					if (first_mp == NULL)
19691 						first_mp = mp;
19692 					goto drop_pkt;
19693 				} else {
19694 					/*
19695 					 * If suitable ipif has been found, set
19696 					 * xmit_ill to the corresponding
19697 					 * ipif_ill because we'll be following
19698 					 * the IP_XMIT_IF logic.
19699 					 */
19700 					ASSERT(xmit_ill == NULL);
19701 					xmit_ill = dst_ipif->ipif_ill;
19702 					mutex_enter(&xmit_ill->ill_lock);
19703 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
19704 						mutex_exit(&xmit_ill->ill_lock);
19705 						xmit_ill = NULL;
19706 						ipif_refrele(dst_ipif);
19707 						ip1dbg(("ip_wput: no route for"
19708 						    " dst using"
19709 						    " SO_DONTROUTE\n"));
19710 						BUMP_MIB(&ip_mib,
19711 						    ipOutNoRoutes);
19712 						mp->b_prev = mp->b_next = NULL;
19713 						if (first_mp == NULL)
19714 							first_mp = mp;
19715 						goto drop_pkt;
19716 					}
19717 					ill_refhold_locked(xmit_ill);
19718 					mutex_exit(&xmit_ill->ill_lock);
19719 					ipif_refrele(dst_ipif);
19720 				}
19721 			}
19722 
19723 		}
19724 		/*
19725 		 * If we are bound to IPIF_NOFAILOVER address, look for
19726 		 * an IRE_CACHE matching the ill.
19727 		 */
19728 send_from_ill:
19729 		if (attach_ill != NULL) {
19730 			ipif_t	*attach_ipif;
19731 
19732 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19733 
19734 			/*
19735 			 * Check if we need an ire that will not be
19736 			 * looked up by anybody else i.e. HIDDEN.
19737 			 */
19738 			if (ill_is_probeonly(attach_ill)) {
19739 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19740 			}
19741 
19742 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
19743 			if (attach_ipif == NULL) {
19744 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
19745 				goto drop_pkt;
19746 			}
19747 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
19748 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19749 			ipif_refrele(attach_ipif);
19750 		} else if (xmit_ill != NULL || (connp != NULL &&
19751 			    connp->conn_xmit_if_ill != NULL)) {
19752 			/*
19753 			 * Mark this packet as originated locally
19754 			 */
19755 			mp->b_prev = mp->b_next = NULL;
19756 			/*
19757 			 * xmit_ill could be NULL if SO_DONTROUTE
19758 			 * is also set.
19759 			 */
19760 			if (xmit_ill == NULL) {
19761 				xmit_ill = conn_get_held_ill(connp,
19762 				    &connp->conn_xmit_if_ill, &err);
19763 				if (err == ILL_LOOKUP_FAILED) {
19764 					if (need_decref)
19765 						CONN_DEC_REF(connp);
19766 					freemsg(first_mp);
19767 					return;
19768 				}
19769 				if (xmit_ill == NULL) {
19770 					if (connp->conn_dontroute)
19771 						goto dontroute;
19772 					goto send_from_ill;
19773 				}
19774 			}
19775 			/*
19776 			 * could be SO_DONTROUTE case also.
19777 			 * check at least one interface is UP as
19778 			 * spcified by this ILL, and then call
19779 			 * ip_newroute_ipif()
19780 			 */
19781 			if (xmit_ill->ill_ipif_up_count > 0) {
19782 				ipif_t *ipif;
19783 
19784 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19785 				if (ipif != NULL) {
19786 					ip_newroute_ipif(q, first_mp, ipif,
19787 					    dst, connp, 0);
19788 					ipif_refrele(ipif);
19789 					ip1dbg(("ip_wput: ip_unicast_if\n"));
19790 				}
19791 			} else {
19792 				freemsg(first_mp);
19793 			}
19794 			ill_refrele(xmit_ill);
19795 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19796 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
19797 			if (need_decref)
19798 				CONN_DEC_REF(connp);
19799 			return;
19800 		} else if (ip_nexthop || (connp != NULL &&
19801 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
19802 			if (!ip_nexthop) {
19803 				ip_nexthop = B_TRUE;
19804 				nexthop_addr = connp->conn_nexthop_v4;
19805 			}
19806 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
19807 			    MATCH_IRE_GW;
19808 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19809 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
19810 		} else {
19811 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19812 		}
19813 		if (!ire) {
19814 			/*
19815 			 * Make sure we don't load spread if this
19816 			 * is IPIF_NOFAILOVER case.
19817 			 */
19818 			if ((attach_ill != NULL) ||
19819 			    (ip_nexthop && !ignore_nexthop)) {
19820 				if (mctl_present) {
19821 					io = (ipsec_out_t *)first_mp->b_rptr;
19822 					ASSERT(first_mp->b_datap->db_type ==
19823 					    M_CTL);
19824 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19825 				} else {
19826 					ASSERT(mp == first_mp);
19827 					first_mp = allocb(
19828 					    sizeof (ipsec_info_t), BPRI_HI);
19829 					if (first_mp == NULL) {
19830 						first_mp = mp;
19831 						goto drop_pkt;
19832 					}
19833 					first_mp->b_datap->db_type = M_CTL;
19834 					first_mp->b_wptr +=
19835 					    sizeof (ipsec_info_t);
19836 					/* ipsec_out_secure is B_FALSE now */
19837 					bzero(first_mp->b_rptr,
19838 					    sizeof (ipsec_info_t));
19839 					io = (ipsec_out_t *)first_mp->b_rptr;
19840 					io->ipsec_out_type = IPSEC_OUT;
19841 					io->ipsec_out_len =
19842 					    sizeof (ipsec_out_t);
19843 					io->ipsec_out_use_global_policy =
19844 					    B_TRUE;
19845 					first_mp->b_cont = mp;
19846 					mctl_present = B_TRUE;
19847 				}
19848 				if (attach_ill != NULL) {
19849 					io->ipsec_out_ill_index = attach_ill->
19850 					    ill_phyint->phyint_ifindex;
19851 					io->ipsec_out_attach_if = B_TRUE;
19852 				} else {
19853 					io->ipsec_out_ip_nexthop = ip_nexthop;
19854 					io->ipsec_out_nexthop_addr =
19855 					    nexthop_addr;
19856 				}
19857 			}
19858 noirefound:
19859 			/*
19860 			 * Mark this packet as having originated on
19861 			 * this machine.  This will be noted in
19862 			 * ire_add_then_send, which needs to know
19863 			 * whether to run it back through ip_wput or
19864 			 * ip_rput following successful resolution.
19865 			 */
19866 			mp->b_prev = NULL;
19867 			mp->b_next = NULL;
19868 			ip_newroute(q, first_mp, dst, NULL, connp);
19869 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19870 			    "ip_wput_end: q %p (%S)", q, "newroute");
19871 			if (attach_ill != NULL)
19872 				ill_refrele(attach_ill);
19873 			if (xmit_ill != NULL)
19874 				ill_refrele(xmit_ill);
19875 			if (need_decref)
19876 				CONN_DEC_REF(connp);
19877 			return;
19878 		}
19879 	}
19880 
19881 	/* We now know where we are going with it. */
19882 
19883 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19884 	    "ip_wput_end: q %p (%S)", q, "end");
19885 
19886 	/*
19887 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19888 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19889 	 */
19890 	if (ire->ire_flags & RTF_MULTIRT) {
19891 		/*
19892 		 * Force the TTL of multirouted packets if required.
19893 		 * The TTL of such packets is bounded by the
19894 		 * ip_multirt_ttl ndd variable.
19895 		 */
19896 		if ((ip_multirt_ttl > 0) &&
19897 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19898 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19899 			    "(was %d), dst 0x%08x\n",
19900 			    ip_multirt_ttl, ipha->ipha_ttl,
19901 			    ntohl(ire->ire_addr)));
19902 			ipha->ipha_ttl = ip_multirt_ttl;
19903 		}
19904 		/*
19905 		 * At this point, we check to see if there are any pending
19906 		 * unresolved routes. ire_multirt_resolvable()
19907 		 * checks in O(n) that all IRE_OFFSUBNET ire
19908 		 * entries for the packet's destination and
19909 		 * flagged RTF_MULTIRT are currently resolved.
19910 		 * If some remain unresolved, we make a copy
19911 		 * of the current message. It will be used
19912 		 * to initiate additional route resolutions.
19913 		 */
19914 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19915 		    MBLK_GETLABEL(first_mp));
19916 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19917 		    "multirt_need_resolve %d, first_mp %p\n",
19918 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19919 		if (multirt_need_resolve) {
19920 			copy_mp = copymsg(first_mp);
19921 			if (copy_mp != NULL) {
19922 				MULTIRT_DEBUG_TAG(copy_mp);
19923 			}
19924 		}
19925 	}
19926 
19927 	ip_wput_ire(q, first_mp, ire, connp, caller);
19928 	/*
19929 	 * Try to resolve another multiroute if
19930 	 * ire_multirt_resolvable() deemed it necessary.
19931 	 * At this point, we need to distinguish
19932 	 * multicasts from other packets. For multicasts,
19933 	 * we call ip_newroute_ipif() and request that both
19934 	 * multirouting and setsrc flags are checked.
19935 	 */
19936 	if (copy_mp != NULL) {
19937 		if (CLASSD(dst)) {
19938 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19939 			if (ipif) {
19940 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19941 				    RTF_SETSRC | RTF_MULTIRT);
19942 				ipif_refrele(ipif);
19943 			} else {
19944 				MULTIRT_DEBUG_UNTAG(copy_mp);
19945 				freemsg(copy_mp);
19946 				copy_mp = NULL;
19947 			}
19948 		} else {
19949 			ip_newroute(q, copy_mp, dst, NULL, connp);
19950 		}
19951 	}
19952 	if (attach_ill != NULL)
19953 		ill_refrele(attach_ill);
19954 	if (xmit_ill != NULL)
19955 		ill_refrele(xmit_ill);
19956 	if (need_decref)
19957 		CONN_DEC_REF(connp);
19958 	return;
19959 
19960 icmp_parameter_problem:
19961 	/* could not have originated externally */
19962 	ASSERT(mp->b_prev == NULL);
19963 	if (ip_hdr_complete(ipha, zoneid) == 0) {
19964 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
19965 		/* it's the IP header length that's in trouble */
19966 		icmp_param_problem(q, first_mp, 0);
19967 		first_mp = NULL;
19968 	}
19969 
19970 drop_pkt:
19971 	ip1dbg(("ip_wput: dropped packet\n"));
19972 	if (ire != NULL)
19973 		ire_refrele(ire);
19974 	if (need_decref)
19975 		CONN_DEC_REF(connp);
19976 	freemsg(first_mp);
19977 	if (attach_ill != NULL)
19978 		ill_refrele(attach_ill);
19979 	if (xmit_ill != NULL)
19980 		ill_refrele(xmit_ill);
19981 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19982 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19983 }
19984 
19985 void
19986 ip_wput(queue_t *q, mblk_t *mp)
19987 {
19988 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
19989 }
19990 
19991 /*
19992  *
19993  * The following rules must be observed when accessing any ipif or ill
19994  * that has been cached in the conn. Typically conn_nofailover_ill,
19995  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
19996  *
19997  * Access: The ipif or ill pointed to from the conn can be accessed under
19998  * the protection of the conn_lock or after it has been refheld under the
19999  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20000  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20001  * The reason for this is that a concurrent unplumb could actually be
20002  * cleaning up these cached pointers by walking the conns and might have
20003  * finished cleaning up the conn in question. The macros check that an
20004  * unplumb has not yet started on the ipif or ill.
20005  *
20006  * Caching: An ipif or ill pointer may be cached in the conn only after
20007  * making sure that an unplumb has not started. So the caching is done
20008  * while holding both the conn_lock and the ill_lock and after using the
20009  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20010  * flag before starting the cleanup of conns.
20011  *
20012  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20013  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20014  * or a reference to the ipif or a reference to an ire that references the
20015  * ipif. An ipif does not change its ill except for failover/failback. Since
20016  * failover/failback happens only after bringing down the ipif and making sure
20017  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20018  * the above holds.
20019  */
20020 ipif_t *
20021 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20022 {
20023 	ipif_t	*ipif;
20024 	ill_t	*ill;
20025 
20026 	*err = 0;
20027 	rw_enter(&ill_g_lock, RW_READER);
20028 	mutex_enter(&connp->conn_lock);
20029 	ipif = *ipifp;
20030 	if (ipif != NULL) {
20031 		ill = ipif->ipif_ill;
20032 		mutex_enter(&ill->ill_lock);
20033 		if (IPIF_CAN_LOOKUP(ipif)) {
20034 			ipif_refhold_locked(ipif);
20035 			mutex_exit(&ill->ill_lock);
20036 			mutex_exit(&connp->conn_lock);
20037 			rw_exit(&ill_g_lock);
20038 			return (ipif);
20039 		} else {
20040 			*err = IPIF_LOOKUP_FAILED;
20041 		}
20042 		mutex_exit(&ill->ill_lock);
20043 	}
20044 	mutex_exit(&connp->conn_lock);
20045 	rw_exit(&ill_g_lock);
20046 	return (NULL);
20047 }
20048 
20049 ill_t *
20050 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20051 {
20052 	ill_t	*ill;
20053 
20054 	*err = 0;
20055 	mutex_enter(&connp->conn_lock);
20056 	ill = *illp;
20057 	if (ill != NULL) {
20058 		mutex_enter(&ill->ill_lock);
20059 		if (ILL_CAN_LOOKUP(ill)) {
20060 			ill_refhold_locked(ill);
20061 			mutex_exit(&ill->ill_lock);
20062 			mutex_exit(&connp->conn_lock);
20063 			return (ill);
20064 		} else {
20065 			*err = ILL_LOOKUP_FAILED;
20066 		}
20067 		mutex_exit(&ill->ill_lock);
20068 	}
20069 	mutex_exit(&connp->conn_lock);
20070 	return (NULL);
20071 }
20072 
20073 static int
20074 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20075 {
20076 	ill_t	*ill;
20077 
20078 	ill = ipif->ipif_ill;
20079 	mutex_enter(&connp->conn_lock);
20080 	mutex_enter(&ill->ill_lock);
20081 	if (IPIF_CAN_LOOKUP(ipif)) {
20082 		*ipifp = ipif;
20083 		mutex_exit(&ill->ill_lock);
20084 		mutex_exit(&connp->conn_lock);
20085 		return (0);
20086 	}
20087 	mutex_exit(&ill->ill_lock);
20088 	mutex_exit(&connp->conn_lock);
20089 	return (IPIF_LOOKUP_FAILED);
20090 }
20091 
20092 /*
20093  * This is called if the outbound datagram needs fragmentation.
20094  *
20095  * NOTE : This function does not ire_refrele the ire argument passed in.
20096  */
20097 static void
20098 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20099 {
20100 	ipha_t		*ipha;
20101 	mblk_t		*mp;
20102 	uint32_t	v_hlen_tos_len;
20103 	uint32_t	max_frag;
20104 	uint32_t	frag_flag;
20105 	boolean_t	dont_use;
20106 
20107 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20108 		mp = ipsec_mp->b_cont;
20109 	} else {
20110 		mp = ipsec_mp;
20111 	}
20112 
20113 	ipha = (ipha_t *)mp->b_rptr;
20114 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20115 
20116 #ifdef	_BIG_ENDIAN
20117 #define	V_HLEN	(v_hlen_tos_len >> 24)
20118 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20119 #else
20120 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20121 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20122 #endif
20123 
20124 #ifndef SPEED_BEFORE_SAFETY
20125 	/*
20126 	 * Check that ipha_length is consistent with
20127 	 * the mblk length
20128 	 */
20129 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20130 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20131 		    LENGTH, msgdsize(mp)));
20132 		freemsg(ipsec_mp);
20133 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20134 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20135 		    "packet length mismatch");
20136 		return;
20137 	}
20138 #endif
20139 	/*
20140 	 * Don't use frag_flag if pre-built packet or source
20141 	 * routed or if multicast (since multicast packets do not solicit
20142 	 * ICMP "packet too big" messages). Get the values of
20143 	 * max_frag and frag_flag atomically by acquiring the
20144 	 * ire_lock.
20145 	 */
20146 	mutex_enter(&ire->ire_lock);
20147 	max_frag = ire->ire_max_frag;
20148 	frag_flag = ire->ire_frag_flag;
20149 	mutex_exit(&ire->ire_lock);
20150 
20151 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20152 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20153 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20154 
20155 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20156 	    (dont_use ? 0 : frag_flag));
20157 }
20158 
20159 /*
20160  * Used for deciding the MSS size for the upper layer. Thus
20161  * we need to check the outbound policy values in the conn.
20162  */
20163 int
20164 conn_ipsec_length(conn_t *connp)
20165 {
20166 	ipsec_latch_t *ipl;
20167 
20168 	ipl = connp->conn_latch;
20169 	if (ipl == NULL)
20170 		return (0);
20171 
20172 	if (ipl->ipl_out_policy == NULL)
20173 		return (0);
20174 
20175 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20176 }
20177 
20178 /*
20179  * Returns an estimate of the IPSEC headers size. This is used if
20180  * we don't want to call into IPSEC to get the exact size.
20181  */
20182 int
20183 ipsec_out_extra_length(mblk_t *ipsec_mp)
20184 {
20185 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20186 	ipsec_action_t *a;
20187 
20188 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20189 	if (!io->ipsec_out_secure)
20190 		return (0);
20191 
20192 	a = io->ipsec_out_act;
20193 
20194 	if (a == NULL) {
20195 		ASSERT(io->ipsec_out_policy != NULL);
20196 		a = io->ipsec_out_policy->ipsp_act;
20197 	}
20198 	ASSERT(a != NULL);
20199 
20200 	return (a->ipa_ovhd);
20201 }
20202 
20203 /*
20204  * Returns an estimate of the IPSEC headers size. This is used if
20205  * we don't want to call into IPSEC to get the exact size.
20206  */
20207 int
20208 ipsec_in_extra_length(mblk_t *ipsec_mp)
20209 {
20210 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20211 	ipsec_action_t *a;
20212 
20213 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20214 
20215 	a = ii->ipsec_in_action;
20216 	return (a == NULL ? 0 : a->ipa_ovhd);
20217 }
20218 
20219 /*
20220  * If there are any source route options, return the true final
20221  * destination. Otherwise, return the destination.
20222  */
20223 ipaddr_t
20224 ip_get_dst(ipha_t *ipha)
20225 {
20226 	ipoptp_t	opts;
20227 	uchar_t		*opt;
20228 	uint8_t		optval;
20229 	uint8_t		optlen;
20230 	ipaddr_t	dst;
20231 	uint32_t off;
20232 
20233 	dst = ipha->ipha_dst;
20234 
20235 	if (IS_SIMPLE_IPH(ipha))
20236 		return (dst);
20237 
20238 	for (optval = ipoptp_first(&opts, ipha);
20239 	    optval != IPOPT_EOL;
20240 	    optval = ipoptp_next(&opts)) {
20241 		opt = opts.ipoptp_cur;
20242 		optlen = opts.ipoptp_len;
20243 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20244 		switch (optval) {
20245 		case IPOPT_SSRR:
20246 		case IPOPT_LSRR:
20247 			off = opt[IPOPT_OFFSET];
20248 			/*
20249 			 * If one of the conditions is true, it means
20250 			 * end of options and dst already has the right
20251 			 * value.
20252 			 */
20253 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20254 				off = optlen - IP_ADDR_LEN;
20255 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20256 			}
20257 			return (dst);
20258 		default:
20259 			break;
20260 		}
20261 	}
20262 
20263 	return (dst);
20264 }
20265 
20266 mblk_t *
20267 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20268     conn_t *connp, boolean_t unspec_src)
20269 {
20270 	ipsec_out_t	*io;
20271 	mblk_t		*first_mp;
20272 	boolean_t policy_present;
20273 
20274 	first_mp = mp;
20275 	if (mp->b_datap->db_type == M_CTL) {
20276 		io = (ipsec_out_t *)first_mp->b_rptr;
20277 		/*
20278 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20279 		 *
20280 		 * 1) There is per-socket policy (including cached global
20281 		 *    policy).
20282 		 * 2) There is no per-socket policy, but it is
20283 		 *    a multicast packet that needs to go out
20284 		 *    on a specific interface. This is the case
20285 		 *    where (ip_wput and ip_wput_multicast) attaches
20286 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20287 		 *
20288 		 * In case (2) we check with global policy to
20289 		 * see if there is a match and set the ill_index
20290 		 * appropriately so that we can lookup the ire
20291 		 * properly in ip_wput_ipsec_out.
20292 		 */
20293 
20294 		/*
20295 		 * ipsec_out_use_global_policy is set to B_FALSE
20296 		 * in ipsec_in_to_out(). Refer to that function for
20297 		 * details.
20298 		 */
20299 		if ((io->ipsec_out_latch == NULL) &&
20300 		    (io->ipsec_out_use_global_policy)) {
20301 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20302 			    ire, connp, unspec_src));
20303 		}
20304 		if (!io->ipsec_out_secure) {
20305 			/*
20306 			 * If this is not a secure packet, drop
20307 			 * the IPSEC_OUT mp and treat it as a clear
20308 			 * packet. This happens when we are sending
20309 			 * a ICMP reply back to a clear packet. See
20310 			 * ipsec_in_to_out() for details.
20311 			 */
20312 			mp = first_mp->b_cont;
20313 			freeb(first_mp);
20314 		}
20315 		return (mp);
20316 	}
20317 	/*
20318 	 * See whether we need to attach a global policy here. We
20319 	 * don't depend on the conn (as it could be null) for deciding
20320 	 * what policy this datagram should go through because it
20321 	 * should have happened in ip_wput if there was some
20322 	 * policy. This normally happens for connections which are not
20323 	 * fully bound preventing us from caching policies in
20324 	 * ip_bind. Packets coming from the TCP listener/global queue
20325 	 * - which are non-hard_bound - could also be affected by
20326 	 * applying policy here.
20327 	 *
20328 	 * If this packet is coming from tcp global queue or listener,
20329 	 * we will be applying policy here.  This may not be *right*
20330 	 * if these packets are coming from the detached connection as
20331 	 * it could have gone in clear before. This happens only if a
20332 	 * TCP connection started when there is no policy and somebody
20333 	 * added policy before it became detached. Thus packets of the
20334 	 * detached connection could go out secure and the other end
20335 	 * would drop it because it will be expecting in clear. The
20336 	 * converse is not true i.e if somebody starts a TCP
20337 	 * connection and deletes the policy, all the packets will
20338 	 * still go out with the policy that existed before deleting
20339 	 * because ip_unbind sends up policy information which is used
20340 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20341 	 * TCP to attach a dummy IPSEC_OUT and set
20342 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20343 	 * affect performance for normal cases, we are not doing it.
20344 	 * Thus, set policy before starting any TCP connections.
20345 	 *
20346 	 * NOTE - We might apply policy even for a hard bound connection
20347 	 * - for which we cached policy in ip_bind - if somebody added
20348 	 * global policy after we inherited the policy in ip_bind.
20349 	 * This means that the packets that were going out in clear
20350 	 * previously would start going secure and hence get dropped
20351 	 * on the other side. To fix this, TCP attaches a dummy
20352 	 * ipsec_out and make sure that we don't apply global policy.
20353 	 */
20354 	if (ipha != NULL)
20355 		policy_present = ipsec_outbound_v4_policy_present;
20356 	else
20357 		policy_present = ipsec_outbound_v6_policy_present;
20358 	if (!policy_present)
20359 		return (mp);
20360 
20361 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20362 }
20363 
20364 ire_t *
20365 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20366 {
20367 	ipaddr_t addr;
20368 	ire_t *save_ire;
20369 	irb_t *irb;
20370 	ill_group_t *illgrp;
20371 	int	err;
20372 
20373 	save_ire = ire;
20374 	addr = ire->ire_addr;
20375 
20376 	ASSERT(ire->ire_type == IRE_BROADCAST);
20377 
20378 	illgrp = connp->conn_outgoing_ill->ill_group;
20379 	if (illgrp == NULL) {
20380 		*conn_outgoing_ill = conn_get_held_ill(connp,
20381 		    &connp->conn_outgoing_ill, &err);
20382 		if (err == ILL_LOOKUP_FAILED) {
20383 			ire_refrele(save_ire);
20384 			return (NULL);
20385 		}
20386 		return (save_ire);
20387 	}
20388 	/*
20389 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20390 	 * If it is part of the group, we need to send on the ire
20391 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20392 	 * to this group. This is okay as IP_BOUND_IF really means
20393 	 * any ill in the group. We depend on the fact that the
20394 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20395 	 * if such an ire exists. This is possible only if you have
20396 	 * at least one ill in the group that has not failed.
20397 	 *
20398 	 * First get to the ire that matches the address and group.
20399 	 *
20400 	 * We don't look for an ire with a matching zoneid because a given zone
20401 	 * won't always have broadcast ires on all ills in the group.
20402 	 */
20403 	irb = ire->ire_bucket;
20404 	rw_enter(&irb->irb_lock, RW_READER);
20405 	if (ire->ire_marks & IRE_MARK_NORECV) {
20406 		/*
20407 		 * If the current zone only has an ire broadcast for this
20408 		 * address marked NORECV, the ire we want is ahead in the
20409 		 * bucket, so we look it up deliberately ignoring the zoneid.
20410 		 */
20411 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
20412 			if (ire->ire_addr != addr)
20413 				continue;
20414 			/* skip over deleted ires */
20415 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
20416 				continue;
20417 		}
20418 	}
20419 	while (ire != NULL) {
20420 		/*
20421 		 * If a new interface is coming up, we could end up
20422 		 * seeing the loopback ire and the non-loopback ire
20423 		 * may not have been added yet. So check for ire_stq
20424 		 */
20425 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
20426 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
20427 			break;
20428 		}
20429 		ire = ire->ire_next;
20430 	}
20431 	if (ire != NULL && ire->ire_addr == addr &&
20432 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
20433 		IRE_REFHOLD(ire);
20434 		rw_exit(&irb->irb_lock);
20435 		ire_refrele(save_ire);
20436 		*conn_outgoing_ill = ire_to_ill(ire);
20437 		/*
20438 		 * Refhold the ill to make the conn_outgoing_ill
20439 		 * independent of the ire. ip_wput_ire goes in a loop
20440 		 * and may refrele the ire. Since we have an ire at this
20441 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
20442 		 */
20443 		ill_refhold(*conn_outgoing_ill);
20444 		return (ire);
20445 	}
20446 	rw_exit(&irb->irb_lock);
20447 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
20448 	/*
20449 	 * If we can't find a suitable ire, return the original ire.
20450 	 */
20451 	return (save_ire);
20452 }
20453 
20454 /*
20455  * This function does the ire_refrele of the ire passed in as the
20456  * argument. As this function looks up more ires i.e broadcast ires,
20457  * it needs to REFRELE them. Currently, for simplicity we don't
20458  * differentiate the one passed in and looked up here. We always
20459  * REFRELE.
20460  * IPQoS Notes:
20461  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
20462  * IPSec packets are done in ipsec_out_process.
20463  *
20464  */
20465 void
20466 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
20467 {
20468 	ipha_t		*ipha;
20469 #define	rptr	((uchar_t *)ipha)
20470 	mblk_t		*mp1;
20471 	queue_t		*stq;
20472 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
20473 	uint32_t	v_hlen_tos_len;
20474 	uint32_t	ttl_protocol;
20475 	ipaddr_t	src;
20476 	ipaddr_t	dst;
20477 	uint32_t	cksum;
20478 	ipaddr_t	orig_src;
20479 	ire_t		*ire1;
20480 	mblk_t		*next_mp;
20481 	uint_t		hlen;
20482 	uint16_t	*up;
20483 	uint32_t	max_frag = ire->ire_max_frag;
20484 	ill_t		*ill = ire_to_ill(ire);
20485 	int		clusterwide;
20486 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
20487 	int		ipsec_len;
20488 	mblk_t		*first_mp;
20489 	ipsec_out_t	*io;
20490 	boolean_t	conn_dontroute;		/* conn value for multicast */
20491 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
20492 	boolean_t	multicast_forward;	/* Should we forward ? */
20493 	boolean_t	unspec_src;
20494 	ill_t		*conn_outgoing_ill = NULL;
20495 	ill_t		*ire_ill;
20496 	ill_t		*ire1_ill;
20497 	uint32_t 	ill_index = 0;
20498 	boolean_t	multirt_send = B_FALSE;
20499 	int		err;
20500 	zoneid_t	zoneid;
20501 
20502 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
20503 	    "ip_wput_ire_start: q %p", q);
20504 
20505 	multicast_forward = B_FALSE;
20506 	unspec_src = (connp != NULL && connp->conn_unspec_src);
20507 
20508 	if (ire->ire_flags & RTF_MULTIRT) {
20509 		/*
20510 		 * Multirouting case. The bucket where ire is stored
20511 		 * probably holds other RTF_MULTIRT flagged ire
20512 		 * to the destination. In this call to ip_wput_ire,
20513 		 * we attempt to send the packet through all
20514 		 * those ires. Thus, we first ensure that ire is the
20515 		 * first RTF_MULTIRT ire in the bucket,
20516 		 * before walking the ire list.
20517 		 */
20518 		ire_t *first_ire;
20519 		irb_t *irb = ire->ire_bucket;
20520 		ASSERT(irb != NULL);
20521 
20522 		/* Make sure we do not omit any multiroute ire. */
20523 		IRB_REFHOLD(irb);
20524 		for (first_ire = irb->irb_ire;
20525 		    first_ire != NULL;
20526 		    first_ire = first_ire->ire_next) {
20527 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
20528 			    (first_ire->ire_addr == ire->ire_addr) &&
20529 			    !(first_ire->ire_marks &
20530 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
20531 				break;
20532 		}
20533 
20534 		if ((first_ire != NULL) && (first_ire != ire)) {
20535 			IRE_REFHOLD(first_ire);
20536 			ire_refrele(ire);
20537 			ire = first_ire;
20538 			ill = ire_to_ill(ire);
20539 		}
20540 		IRB_REFRELE(irb);
20541 	}
20542 
20543 	/*
20544 	 * conn_outgoing_ill is used only in the broadcast loop.
20545 	 * for performance we don't grab the mutexs in the fastpath
20546 	 */
20547 	if ((connp != NULL) &&
20548 	    (connp->conn_xmit_if_ill == NULL) &&
20549 	    (ire->ire_type == IRE_BROADCAST) &&
20550 	    ((connp->conn_nofailover_ill != NULL) ||
20551 	    (connp->conn_outgoing_ill != NULL))) {
20552 		/*
20553 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
20554 		 * option. So, see if this endpoint is bound to a
20555 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
20556 		 * that if the interface is failed, we will still send
20557 		 * the packet on the same ill which is what we want.
20558 		 */
20559 		conn_outgoing_ill = conn_get_held_ill(connp,
20560 		    &connp->conn_nofailover_ill, &err);
20561 		if (err == ILL_LOOKUP_FAILED) {
20562 			ire_refrele(ire);
20563 			freemsg(mp);
20564 			return;
20565 		}
20566 		if (conn_outgoing_ill == NULL) {
20567 			/*
20568 			 * Choose a good ill in the group to send the
20569 			 * packets on.
20570 			 */
20571 			ire = conn_set_outgoing_ill(connp, ire,
20572 			    &conn_outgoing_ill);
20573 			if (ire == NULL) {
20574 				freemsg(mp);
20575 				return;
20576 			}
20577 		}
20578 	}
20579 
20580 	if (mp->b_datap->db_type != M_CTL) {
20581 		ipha = (ipha_t *)mp->b_rptr;
20582 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
20583 	} else {
20584 		io = (ipsec_out_t *)mp->b_rptr;
20585 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20586 		zoneid = io->ipsec_out_zoneid;
20587 		ASSERT(zoneid != ALL_ZONES);
20588 		ipha = (ipha_t *)mp->b_cont->b_rptr;
20589 		dst = ipha->ipha_dst;
20590 		/*
20591 		 * For the multicast case, ipsec_out carries conn_dontroute and
20592 		 * conn_multicast_loop as conn may not be available here. We
20593 		 * need this for multicast loopback and forwarding which is done
20594 		 * later in the code.
20595 		 */
20596 		if (CLASSD(dst)) {
20597 			conn_dontroute = io->ipsec_out_dontroute;
20598 			conn_multicast_loop = io->ipsec_out_multicast_loop;
20599 			/*
20600 			 * If conn_dontroute is not set or conn_multicast_loop
20601 			 * is set, we need to do forwarding/loopback. For
20602 			 * datagrams from ip_wput_multicast, conn_dontroute is
20603 			 * set to B_TRUE and conn_multicast_loop is set to
20604 			 * B_FALSE so that we neither do forwarding nor
20605 			 * loopback.
20606 			 */
20607 			if (!conn_dontroute || conn_multicast_loop)
20608 				multicast_forward = B_TRUE;
20609 		}
20610 	}
20611 
20612 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
20613 	    ire->ire_zoneid != ALL_ZONES) {
20614 		/*
20615 		 * When a zone sends a packet to another zone, we try to deliver
20616 		 * the packet under the same conditions as if the destination
20617 		 * was a real node on the network. To do so, we look for a
20618 		 * matching route in the forwarding table.
20619 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
20620 		 * ip_newroute() does.
20621 		 */
20622 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
20623 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
20624 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
20625 		if (src_ire != NULL &&
20626 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
20627 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
20628 				ipha->ipha_src = src_ire->ire_src_addr;
20629 			ire_refrele(src_ire);
20630 		} else {
20631 			ire_refrele(ire);
20632 			if (conn_outgoing_ill != NULL)
20633 				ill_refrele(conn_outgoing_ill);
20634 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
20635 			if (src_ire != NULL) {
20636 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
20637 					ire_refrele(src_ire);
20638 					freemsg(mp);
20639 					return;
20640 				}
20641 				ire_refrele(src_ire);
20642 			}
20643 			if (ip_hdr_complete(ipha, zoneid)) {
20644 				/* Failed */
20645 				freemsg(mp);
20646 				return;
20647 			}
20648 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
20649 			return;
20650 		}
20651 	}
20652 
20653 	if (mp->b_datap->db_type == M_CTL ||
20654 	    ipsec_outbound_v4_policy_present) {
20655 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
20656 		    unspec_src);
20657 		if (mp == NULL) {
20658 			ire_refrele(ire);
20659 			if (conn_outgoing_ill != NULL)
20660 				ill_refrele(conn_outgoing_ill);
20661 			return;
20662 		}
20663 	}
20664 
20665 	first_mp = mp;
20666 	ipsec_len = 0;
20667 
20668 	if (first_mp->b_datap->db_type == M_CTL) {
20669 		io = (ipsec_out_t *)first_mp->b_rptr;
20670 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20671 		mp = first_mp->b_cont;
20672 		ipsec_len = ipsec_out_extra_length(first_mp);
20673 		ASSERT(ipsec_len >= 0);
20674 		zoneid = io->ipsec_out_zoneid;
20675 		ASSERT(zoneid != ALL_ZONES);
20676 
20677 		/*
20678 		 * Drop M_CTL here if IPsec processing is not needed.
20679 		 * (Non-IPsec use of M_CTL extracted any information it
20680 		 * needed above).
20681 		 */
20682 		if (ipsec_len == 0) {
20683 			freeb(first_mp);
20684 			first_mp = mp;
20685 		}
20686 	}
20687 
20688 	/*
20689 	 * Fast path for ip_wput_ire
20690 	 */
20691 
20692 	ipha = (ipha_t *)mp->b_rptr;
20693 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20694 	dst = ipha->ipha_dst;
20695 
20696 	/*
20697 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
20698 	 * if the socket is a SOCK_RAW type. The transport checksum should
20699 	 * be provided in the pre-built packet, so we don't need to compute it.
20700 	 * Also, other application set flags, like DF, should not be altered.
20701 	 * Other transport MUST pass down zero.
20702 	 */
20703 	ip_hdr_included = ipha->ipha_ident;
20704 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20705 
20706 	if (CLASSD(dst)) {
20707 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
20708 		    ntohl(dst),
20709 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
20710 		    ntohl(ire->ire_addr)));
20711 	}
20712 
20713 /* Macros to extract header fields from data already in registers */
20714 #ifdef	_BIG_ENDIAN
20715 #define	V_HLEN	(v_hlen_tos_len >> 24)
20716 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20717 #define	PROTO	(ttl_protocol & 0xFF)
20718 #else
20719 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20720 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20721 #define	PROTO	(ttl_protocol >> 8)
20722 #endif
20723 
20724 
20725 	orig_src = src = ipha->ipha_src;
20726 	/* (The loop back to "another" is explained down below.) */
20727 another:;
20728 	/*
20729 	 * Assign an ident value for this packet.  We assign idents on
20730 	 * a per destination basis out of the IRE.  There could be
20731 	 * other threads targeting the same destination, so we have to
20732 	 * arrange for a atomic increment.  Note that we use a 32-bit
20733 	 * atomic add because it has better performance than its
20734 	 * 16-bit sibling.
20735 	 *
20736 	 * If running in cluster mode and if the source address
20737 	 * belongs to a replicated service then vector through
20738 	 * cl_inet_ipident vector to allocate ip identifier
20739 	 * NOTE: This is a contract private interface with the
20740 	 * clustering group.
20741 	 */
20742 	clusterwide = 0;
20743 	if (cl_inet_ipident) {
20744 		ASSERT(cl_inet_isclusterwide);
20745 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20746 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
20747 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
20748 			    AF_INET, (uint8_t *)(uintptr_t)src,
20749 			    (uint8_t *)(uintptr_t)dst);
20750 			clusterwide = 1;
20751 		}
20752 	}
20753 	if (!clusterwide) {
20754 		ipha->ipha_ident =
20755 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
20756 	}
20757 
20758 #ifndef _BIG_ENDIAN
20759 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20760 #endif
20761 
20762 	/*
20763 	 * Set source address unless sent on an ill or conn_unspec_src is set.
20764 	 * This is needed to obey conn_unspec_src when packets go through
20765 	 * ip_newroute + arp.
20766 	 * Assumes ip_newroute{,_multi} sets the source address as well.
20767 	 */
20768 	if (src == INADDR_ANY && !unspec_src) {
20769 		/*
20770 		 * Assign the appropriate source address from the IRE if none
20771 		 * was specified.
20772 		 */
20773 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
20774 
20775 		/*
20776 		 * With IP multipathing, broadcast packets are sent on the ire
20777 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
20778 		 * the group. However, this ire might not be in the same zone so
20779 		 * we can't always use its source address. We look for a
20780 		 * broadcast ire in the same group and in the right zone.
20781 		 */
20782 		if (ire->ire_type == IRE_BROADCAST &&
20783 		    ire->ire_zoneid != zoneid) {
20784 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
20785 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
20786 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
20787 			if (src_ire != NULL) {
20788 				src = src_ire->ire_src_addr;
20789 				ire_refrele(src_ire);
20790 			} else {
20791 				ire_refrele(ire);
20792 				if (conn_outgoing_ill != NULL)
20793 					ill_refrele(conn_outgoing_ill);
20794 				freemsg(first_mp);
20795 				BUMP_MIB(&ip_mib, ipOutDiscards);
20796 				return;
20797 			}
20798 		} else {
20799 			src = ire->ire_src_addr;
20800 		}
20801 
20802 		if (connp == NULL) {
20803 			ip1dbg(("ip_wput_ire: no connp and no src "
20804 			    "address for dst 0x%x, using src 0x%x\n",
20805 			    ntohl(dst),
20806 			    ntohl(src)));
20807 		}
20808 		ipha->ipha_src = src;
20809 	}
20810 	stq = ire->ire_stq;
20811 
20812 	/*
20813 	 * We only allow ire chains for broadcasts since there will
20814 	 * be multiple IRE_CACHE entries for the same multicast
20815 	 * address (one per ipif).
20816 	 */
20817 	next_mp = NULL;
20818 
20819 	/* broadcast packet */
20820 	if (ire->ire_type == IRE_BROADCAST)
20821 		goto broadcast;
20822 
20823 	/* loopback ? */
20824 	if (stq == NULL)
20825 		goto nullstq;
20826 
20827 	/* The ill_index for outbound ILL */
20828 	ill_index = Q_TO_INDEX(stq);
20829 
20830 	BUMP_MIB(&ip_mib, ipOutRequests);
20831 	ttl_protocol = ((uint16_t *)ipha)[4];
20832 
20833 	/* pseudo checksum (do it in parts for IP header checksum) */
20834 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20835 
20836 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20837 		queue_t *dev_q = stq->q_next;
20838 
20839 		/* flow controlled */
20840 		if ((dev_q->q_next || dev_q->q_first) &&
20841 		    !canput(dev_q))
20842 			goto blocked;
20843 		if ((PROTO == IPPROTO_UDP) &&
20844 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20845 			hlen = (V_HLEN & 0xF) << 2;
20846 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20847 			if (*up != 0) {
20848 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20849 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20850 				/* Software checksum? */
20851 				if (DB_CKSUMFLAGS(mp) == 0) {
20852 					IP_STAT(ip_out_sw_cksum);
20853 					IP_STAT_UPDATE(
20854 					    ip_udp_out_sw_cksum_bytes,
20855 					    LENGTH - hlen);
20856 				}
20857 			}
20858 		}
20859 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20860 		hlen = (V_HLEN & 0xF) << 2;
20861 		if (PROTO == IPPROTO_TCP) {
20862 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20863 			/*
20864 			 * The packet header is processed once and for all, even
20865 			 * in the multirouting case. We disable hardware
20866 			 * checksum if the packet is multirouted, as it will be
20867 			 * replicated via several interfaces, and not all of
20868 			 * them may have this capability.
20869 			 */
20870 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20871 			    LENGTH, max_frag, ipsec_len, cksum);
20872 			/* Software checksum? */
20873 			if (DB_CKSUMFLAGS(mp) == 0) {
20874 				IP_STAT(ip_out_sw_cksum);
20875 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20876 				    LENGTH - hlen);
20877 			}
20878 		} else {
20879 			sctp_hdr_t	*sctph;
20880 
20881 			ASSERT(PROTO == IPPROTO_SCTP);
20882 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20883 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20884 			/*
20885 			 * Zero out the checksum field to ensure proper
20886 			 * checksum calculation.
20887 			 */
20888 			sctph->sh_chksum = 0;
20889 #ifdef	DEBUG
20890 			if (!skip_sctp_cksum)
20891 #endif
20892 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20893 		}
20894 	}
20895 
20896 	/*
20897 	 * If this is a multicast packet and originated from ip_wput
20898 	 * we need to do loopback and forwarding checks. If it comes
20899 	 * from ip_wput_multicast, we SHOULD not do this.
20900 	 */
20901 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20902 
20903 	/* checksum */
20904 	cksum += ttl_protocol;
20905 
20906 	/* fragment the packet */
20907 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20908 		goto fragmentit;
20909 	/*
20910 	 * Don't use frag_flag if packet is pre-built or source
20911 	 * routed or if multicast (since multicast packets do
20912 	 * not solicit ICMP "packet too big" messages).
20913 	 */
20914 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20915 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20916 	    !ip_source_route_included(ipha)) &&
20917 	    !CLASSD(ipha->ipha_dst))
20918 		ipha->ipha_fragment_offset_and_flags |=
20919 		    htons(ire->ire_frag_flag);
20920 
20921 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20922 		/* calculate IP header checksum */
20923 		cksum += ipha->ipha_ident;
20924 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20925 		cksum += ipha->ipha_fragment_offset_and_flags;
20926 
20927 		/* IP options present */
20928 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20929 		if (hlen)
20930 			goto checksumoptions;
20931 
20932 		/* calculate hdr checksum */
20933 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20934 		cksum = ~(cksum + (cksum >> 16));
20935 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20936 	}
20937 	if (ipsec_len != 0) {
20938 		/*
20939 		 * We will do the rest of the processing after
20940 		 * we come back from IPSEC in ip_wput_ipsec_out().
20941 		 */
20942 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20943 
20944 		io = (ipsec_out_t *)first_mp->b_rptr;
20945 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20946 				ill_phyint->phyint_ifindex;
20947 
20948 		ipsec_out_process(q, first_mp, ire, ill_index);
20949 		ire_refrele(ire);
20950 		if (conn_outgoing_ill != NULL)
20951 			ill_refrele(conn_outgoing_ill);
20952 		return;
20953 	}
20954 
20955 	/*
20956 	 * In most cases, the emission loop below is entered only
20957 	 * once. Only in the case where the ire holds the
20958 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20959 	 * flagged ires in the bucket, and send the packet
20960 	 * through all crossed RTF_MULTIRT routes.
20961 	 */
20962 	if (ire->ire_flags & RTF_MULTIRT) {
20963 		multirt_send = B_TRUE;
20964 	}
20965 	do {
20966 		if (multirt_send) {
20967 			irb_t *irb;
20968 			/*
20969 			 * We are in a multiple send case, need to get
20970 			 * the next ire and make a duplicate of the packet.
20971 			 * ire1 holds here the next ire to process in the
20972 			 * bucket. If multirouting is expected,
20973 			 * any non-RTF_MULTIRT ire that has the
20974 			 * right destination address is ignored.
20975 			 */
20976 			irb = ire->ire_bucket;
20977 			ASSERT(irb != NULL);
20978 
20979 			IRB_REFHOLD(irb);
20980 			for (ire1 = ire->ire_next;
20981 			    ire1 != NULL;
20982 			    ire1 = ire1->ire_next) {
20983 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20984 					continue;
20985 				if (ire1->ire_addr != ire->ire_addr)
20986 					continue;
20987 				if (ire1->ire_marks &
20988 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
20989 					continue;
20990 
20991 				/* Got one */
20992 				IRE_REFHOLD(ire1);
20993 				break;
20994 			}
20995 			IRB_REFRELE(irb);
20996 
20997 			if (ire1 != NULL) {
20998 				next_mp = copyb(mp);
20999 				if ((next_mp == NULL) ||
21000 				    ((mp->b_cont != NULL) &&
21001 				    ((next_mp->b_cont =
21002 				    dupmsg(mp->b_cont)) == NULL))) {
21003 					freemsg(next_mp);
21004 					next_mp = NULL;
21005 					ire_refrele(ire1);
21006 					ire1 = NULL;
21007 				}
21008 			}
21009 
21010 			/* Last multiroute ire; don't loop anymore. */
21011 			if (ire1 == NULL) {
21012 				multirt_send = B_FALSE;
21013 			}
21014 		}
21015 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
21016 		if (mp == NULL) {
21017 			BUMP_MIB(&ip_mib, ipOutDiscards);
21018 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
21019 			    "during IPPF processing\n"));
21020 			ire_refrele(ire);
21021 			if (next_mp != NULL) {
21022 				freemsg(next_mp);
21023 				ire_refrele(ire1);
21024 			}
21025 			if (conn_outgoing_ill != NULL)
21026 				ill_refrele(conn_outgoing_ill);
21027 			return;
21028 		}
21029 		UPDATE_OB_PKT_COUNT(ire);
21030 		ire->ire_last_used_time = lbolt;
21031 
21032 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21033 		    "ip_wput_ire_end: q %p (%S)",
21034 		    q, "last copy out");
21035 		putnext(stq, mp);
21036 		IRE_REFRELE(ire);
21037 
21038 		if (multirt_send) {
21039 			ASSERT(ire1);
21040 			/*
21041 			 * Proceed with the next RTF_MULTIRT ire,
21042 			 * Also set up the send-to queue accordingly.
21043 			 */
21044 			ire = ire1;
21045 			ire1 = NULL;
21046 			stq = ire->ire_stq;
21047 			mp = next_mp;
21048 			next_mp = NULL;
21049 			ipha = (ipha_t *)mp->b_rptr;
21050 			ill_index = Q_TO_INDEX(stq);
21051 		}
21052 	} while (multirt_send);
21053 	if (conn_outgoing_ill != NULL)
21054 		ill_refrele(conn_outgoing_ill);
21055 	return;
21056 
21057 	/*
21058 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21059 	 */
21060 broadcast:
21061 	{
21062 		/*
21063 		 * Avoid broadcast storms by setting the ttl to 1
21064 		 * for broadcasts. This parameter can be set
21065 		 * via ndd, so make sure that for the SO_DONTROUTE
21066 		 * case that ipha_ttl is always set to 1.
21067 		 * In the event that we are replying to incoming
21068 		 * ICMP packets, conn could be NULL.
21069 		 */
21070 		if ((connp != NULL) && connp->conn_dontroute)
21071 			ipha->ipha_ttl = 1;
21072 		else
21073 			ipha->ipha_ttl = ip_broadcast_ttl;
21074 
21075 		/*
21076 		 * Note that we are not doing a IRB_REFHOLD here.
21077 		 * Actually we don't care if the list changes i.e
21078 		 * if somebody deletes an IRE from the list while
21079 		 * we drop the lock, the next time we come around
21080 		 * ire_next will be NULL and hence we won't send
21081 		 * out multiple copies which is fine.
21082 		 */
21083 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21084 		ire1 = ire->ire_next;
21085 		if (conn_outgoing_ill != NULL) {
21086 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21087 				ASSERT(ire1 == ire->ire_next);
21088 				if (ire1 != NULL && ire1->ire_addr == dst) {
21089 					ire_refrele(ire);
21090 					ire = ire1;
21091 					IRE_REFHOLD(ire);
21092 					ire1 = ire->ire_next;
21093 					continue;
21094 				}
21095 				rw_exit(&ire->ire_bucket->irb_lock);
21096 				/* Did not find a matching ill */
21097 				ip1dbg(("ip_wput_ire: broadcast with no "
21098 				    "matching IP_BOUND_IF ill %s\n",
21099 				    conn_outgoing_ill->ill_name));
21100 				freemsg(first_mp);
21101 				if (ire != NULL)
21102 					ire_refrele(ire);
21103 				ill_refrele(conn_outgoing_ill);
21104 				return;
21105 			}
21106 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21107 			/*
21108 			 * If the next IRE has the same address and is not one
21109 			 * of the two copies that we need to send, try to see
21110 			 * whether this copy should be sent at all. This
21111 			 * assumes that we insert loopbacks first and then
21112 			 * non-loopbacks. This is acheived by inserting the
21113 			 * loopback always before non-loopback.
21114 			 * This is used to send a single copy of a broadcast
21115 			 * packet out all physical interfaces that have an
21116 			 * matching IRE_BROADCAST while also looping
21117 			 * back one copy (to ip_wput_local) for each
21118 			 * matching physical interface. However, we avoid
21119 			 * sending packets out different logical that match by
21120 			 * having ipif_up/ipif_down supress duplicate
21121 			 * IRE_BROADCASTS.
21122 			 *
21123 			 * This feature is currently used to get broadcasts
21124 			 * sent to multiple interfaces, when the broadcast
21125 			 * address being used applies to multiple interfaces.
21126 			 * For example, a whole net broadcast will be
21127 			 * replicated on every connected subnet of
21128 			 * the target net.
21129 			 *
21130 			 * Each zone has its own set of IRE_BROADCASTs, so that
21131 			 * we're able to distribute inbound packets to multiple
21132 			 * zones who share a broadcast address. We avoid looping
21133 			 * back outbound packets in different zones but on the
21134 			 * same ill, as the application would see duplicates.
21135 			 *
21136 			 * If the interfaces are part of the same group,
21137 			 * we would want to send only one copy out for
21138 			 * whole group.
21139 			 *
21140 			 * This logic assumes that ire_add_v4() groups the
21141 			 * IRE_BROADCAST entries so that those with the same
21142 			 * ire_addr and ill_group are kept together.
21143 			 */
21144 			ire_ill = ire->ire_ipif->ipif_ill;
21145 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21146 				if (ire_ill->ill_group != NULL &&
21147 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21148 					/*
21149 					 * If the current zone only has an ire
21150 					 * broadcast for this address marked
21151 					 * NORECV, the ire we want is ahead in
21152 					 * the bucket, so we look it up
21153 					 * deliberately ignoring the zoneid.
21154 					 */
21155 					for (ire1 = ire->ire_bucket->irb_ire;
21156 					    ire1 != NULL;
21157 					    ire1 = ire1->ire_next) {
21158 						ire1_ill =
21159 						    ire1->ire_ipif->ipif_ill;
21160 						if (ire1->ire_addr != dst)
21161 							continue;
21162 						/* skip over the current ire */
21163 						if (ire1 == ire)
21164 							continue;
21165 						/* skip over deleted ires */
21166 						if (ire1->ire_marks &
21167 						    IRE_MARK_CONDEMNED)
21168 							continue;
21169 						/*
21170 						 * non-loopback ire in our
21171 						 * group: use it for the next
21172 						 * pass in the loop
21173 						 */
21174 						if (ire1->ire_stq != NULL &&
21175 						    ire1_ill->ill_group ==
21176 						    ire_ill->ill_group)
21177 							break;
21178 					}
21179 				}
21180 			} else {
21181 				while (ire1 != NULL && ire1->ire_addr == dst) {
21182 					ire1_ill = ire1->ire_ipif->ipif_ill;
21183 					/*
21184 					 * We can have two broadcast ires on the
21185 					 * same ill in different zones; here
21186 					 * we'll send a copy of the packet on
21187 					 * each ill and the fanout code will
21188 					 * call conn_wantpacket() to check that
21189 					 * the zone has the broadcast address
21190 					 * configured on the ill. If the two
21191 					 * ires are in the same group we only
21192 					 * send one copy up.
21193 					 */
21194 					if (ire1_ill != ire_ill &&
21195 					    (ire1_ill->ill_group == NULL ||
21196 					    ire_ill->ill_group == NULL ||
21197 					    ire1_ill->ill_group !=
21198 					    ire_ill->ill_group)) {
21199 						break;
21200 					}
21201 					ire1 = ire1->ire_next;
21202 				}
21203 			}
21204 		}
21205 		ASSERT(multirt_send == B_FALSE);
21206 		if (ire1 != NULL && ire1->ire_addr == dst) {
21207 			if ((ire->ire_flags & RTF_MULTIRT) &&
21208 			    (ire1->ire_flags & RTF_MULTIRT)) {
21209 				/*
21210 				 * We are in the multirouting case.
21211 				 * The message must be sent at least
21212 				 * on both ires. These ires have been
21213 				 * inserted AFTER the standard ones
21214 				 * in ip_rt_add(). There are thus no
21215 				 * other ire entries for the destination
21216 				 * address in the rest of the bucket
21217 				 * that do not have the RTF_MULTIRT
21218 				 * flag. We don't process a copy
21219 				 * of the message here. This will be
21220 				 * done in the final sending loop.
21221 				 */
21222 				multirt_send = B_TRUE;
21223 			} else {
21224 				next_mp = ip_copymsg(first_mp);
21225 				if (next_mp != NULL)
21226 					IRE_REFHOLD(ire1);
21227 			}
21228 		}
21229 		rw_exit(&ire->ire_bucket->irb_lock);
21230 	}
21231 
21232 	if (stq) {
21233 		/*
21234 		 * A non-NULL send-to queue means this packet is going
21235 		 * out of this machine.
21236 		 */
21237 
21238 		BUMP_MIB(&ip_mib, ipOutRequests);
21239 		ttl_protocol = ((uint16_t *)ipha)[4];
21240 		/*
21241 		 * We accumulate the pseudo header checksum in cksum.
21242 		 * This is pretty hairy code, so watch close.  One
21243 		 * thing to keep in mind is that UDP and TCP have
21244 		 * stored their respective datagram lengths in their
21245 		 * checksum fields.  This lines things up real nice.
21246 		 */
21247 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21248 		    (src >> 16) + (src & 0xFFFF);
21249 		/*
21250 		 * We assume the udp checksum field contains the
21251 		 * length, so to compute the pseudo header checksum,
21252 		 * all we need is the protocol number and src/dst.
21253 		 */
21254 		/* Provide the checksums for UDP and TCP. */
21255 		if ((PROTO == IPPROTO_TCP) &&
21256 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21257 			/* hlen gets the number of uchar_ts in the IP header */
21258 			hlen = (V_HLEN & 0xF) << 2;
21259 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21260 			IP_STAT(ip_out_sw_cksum);
21261 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21262 			    LENGTH - hlen);
21263 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21264 			if (*up == 0)
21265 				*up = 0xFFFF;
21266 		} else if (PROTO == IPPROTO_SCTP &&
21267 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21268 			sctp_hdr_t	*sctph;
21269 
21270 			hlen = (V_HLEN & 0xF) << 2;
21271 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21272 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21273 			sctph->sh_chksum = 0;
21274 #ifdef	DEBUG
21275 			if (!skip_sctp_cksum)
21276 #endif
21277 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21278 		} else {
21279 			queue_t *dev_q = stq->q_next;
21280 
21281 			if ((dev_q->q_next || dev_q->q_first) &&
21282 			    !canput(dev_q)) {
21283 			    blocked:
21284 				ipha->ipha_ident = ip_hdr_included;
21285 				/*
21286 				 * If we don't have a conn to apply
21287 				 * backpressure, free the message.
21288 				 * In the ire_send path, we don't know
21289 				 * the position to requeue the packet. Rather
21290 				 * than reorder packets, we just drop this
21291 				 * packet.
21292 				 */
21293 				if (ip_output_queue && connp != NULL &&
21294 				    caller != IRE_SEND) {
21295 					if (caller == IP_WSRV) {
21296 						connp->conn_did_putbq = 1;
21297 						(void) putbq(connp->conn_wq,
21298 						    first_mp);
21299 						conn_drain_insert(connp);
21300 						/*
21301 						 * This is the service thread,
21302 						 * and the queue is already
21303 						 * noenabled. The check for
21304 						 * canput and the putbq is not
21305 						 * atomic. So we need to check
21306 						 * again.
21307 						 */
21308 						if (canput(stq->q_next))
21309 							connp->conn_did_putbq
21310 							    = 0;
21311 						IP_STAT(ip_conn_flputbq);
21312 					} else {
21313 						/*
21314 						 * We are not the service proc.
21315 						 * ip_wsrv will be scheduled or
21316 						 * is already running.
21317 						 */
21318 						(void) putq(connp->conn_wq,
21319 						    first_mp);
21320 					}
21321 				} else {
21322 					BUMP_MIB(&ip_mib, ipOutDiscards);
21323 					freemsg(first_mp);
21324 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21325 					    "ip_wput_ire_end: q %p (%S)",
21326 					    q, "discard");
21327 				}
21328 				ire_refrele(ire);
21329 				if (next_mp) {
21330 					ire_refrele(ire1);
21331 					freemsg(next_mp);
21332 				}
21333 				if (conn_outgoing_ill != NULL)
21334 					ill_refrele(conn_outgoing_ill);
21335 				return;
21336 			}
21337 			if ((PROTO == IPPROTO_UDP) &&
21338 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21339 				/*
21340 				 * hlen gets the number of uchar_ts in the
21341 				 * IP header
21342 				 */
21343 				hlen = (V_HLEN & 0xF) << 2;
21344 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21345 				max_frag = ire->ire_max_frag;
21346 				if (*up != 0) {
21347 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21348 					    up, PROTO, hlen, LENGTH, max_frag,
21349 					    ipsec_len, cksum);
21350 					/* Software checksum? */
21351 					if (DB_CKSUMFLAGS(mp) == 0) {
21352 						IP_STAT(ip_out_sw_cksum);
21353 						IP_STAT_UPDATE(
21354 						    ip_udp_out_sw_cksum_bytes,
21355 						    LENGTH - hlen);
21356 					}
21357 				}
21358 			}
21359 		}
21360 		/*
21361 		 * Need to do this even when fragmenting. The local
21362 		 * loopback can be done without computing checksums
21363 		 * but forwarding out other interface must be done
21364 		 * after the IP checksum (and ULP checksums) have been
21365 		 * computed.
21366 		 *
21367 		 * NOTE : multicast_forward is set only if this packet
21368 		 * originated from ip_wput. For packets originating from
21369 		 * ip_wput_multicast, it is not set.
21370 		 */
21371 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21372 		    multi_loopback:
21373 			ip2dbg(("ip_wput: multicast, loop %d\n",
21374 			    conn_multicast_loop));
21375 
21376 			/*  Forget header checksum offload */
21377 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21378 
21379 			/*
21380 			 * Local loopback of multicasts?  Check the
21381 			 * ill.
21382 			 *
21383 			 * Note that the loopback function will not come
21384 			 * in through ip_rput - it will only do the
21385 			 * client fanout thus we need to do an mforward
21386 			 * as well.  The is different from the BSD
21387 			 * logic.
21388 			 */
21389 			if (ill != NULL) {
21390 				ilm_t	*ilm;
21391 
21392 				ILM_WALKER_HOLD(ill);
21393 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21394 				    ALL_ZONES);
21395 				ILM_WALKER_RELE(ill);
21396 				if (ilm != NULL) {
21397 					/*
21398 					 * Pass along the virtual output q.
21399 					 * ip_wput_local() will distribute the
21400 					 * packet to all the matching zones,
21401 					 * except the sending zone when
21402 					 * IP_MULTICAST_LOOP is false.
21403 					 */
21404 					ip_multicast_loopback(q, ill, first_mp,
21405 					    conn_multicast_loop ? 0 :
21406 					    IP_FF_NO_MCAST_LOOP, zoneid);
21407 				}
21408 			}
21409 			if (ipha->ipha_ttl == 0) {
21410 				/*
21411 				 * 0 => only to this host i.e. we are
21412 				 * done. We are also done if this was the
21413 				 * loopback interface since it is sufficient
21414 				 * to loopback one copy of a multicast packet.
21415 				 */
21416 				freemsg(first_mp);
21417 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21418 				    "ip_wput_ire_end: q %p (%S)",
21419 				    q, "loopback");
21420 				ire_refrele(ire);
21421 				if (conn_outgoing_ill != NULL)
21422 					ill_refrele(conn_outgoing_ill);
21423 				return;
21424 			}
21425 			/*
21426 			 * ILLF_MULTICAST is checked in ip_newroute
21427 			 * i.e. we don't need to check it here since
21428 			 * all IRE_CACHEs come from ip_newroute.
21429 			 * For multicast traffic, SO_DONTROUTE is interpreted
21430 			 * to mean only send the packet out the interface
21431 			 * (optionally specified with IP_MULTICAST_IF)
21432 			 * and do not forward it out additional interfaces.
21433 			 * RSVP and the rsvp daemon is an example of a
21434 			 * protocol and user level process that
21435 			 * handles it's own routing. Hence, it uses the
21436 			 * SO_DONTROUTE option to accomplish this.
21437 			 */
21438 
21439 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
21440 				/* Unconditionally redo the checksum */
21441 				ipha->ipha_hdr_checksum = 0;
21442 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21443 
21444 				/*
21445 				 * If this needs to go out secure, we need
21446 				 * to wait till we finish the IPSEC
21447 				 * processing.
21448 				 */
21449 				if (ipsec_len == 0 &&
21450 				    ip_mforward(ill, ipha, mp)) {
21451 					freemsg(first_mp);
21452 					ip1dbg(("ip_wput: mforward failed\n"));
21453 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21454 					    "ip_wput_ire_end: q %p (%S)",
21455 					    q, "mforward failed");
21456 					ire_refrele(ire);
21457 					if (conn_outgoing_ill != NULL)
21458 						ill_refrele(conn_outgoing_ill);
21459 					return;
21460 				}
21461 			}
21462 		}
21463 		max_frag = ire->ire_max_frag;
21464 		cksum += ttl_protocol;
21465 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
21466 			/* No fragmentation required for this one. */
21467 			/*
21468 			 * Don't use frag_flag if packet is pre-built or source
21469 			 * routed or if multicast (since multicast packets do
21470 			 * not solicit ICMP "packet too big" messages).
21471 			 */
21472 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21473 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21474 			    !ip_source_route_included(ipha)) &&
21475 			    !CLASSD(ipha->ipha_dst))
21476 				ipha->ipha_fragment_offset_and_flags |=
21477 				    htons(ire->ire_frag_flag);
21478 
21479 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21480 				/* Complete the IP header checksum. */
21481 				cksum += ipha->ipha_ident;
21482 				cksum += (v_hlen_tos_len >> 16)+
21483 				    (v_hlen_tos_len & 0xFFFF);
21484 				cksum += ipha->ipha_fragment_offset_and_flags;
21485 				hlen = (V_HLEN & 0xF) -
21486 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21487 				if (hlen) {
21488 				    checksumoptions:
21489 					/*
21490 					 * Account for the IP Options in the IP
21491 					 * header checksum.
21492 					 */
21493 					up = (uint16_t *)(rptr+
21494 					    IP_SIMPLE_HDR_LENGTH);
21495 					do {
21496 						cksum += up[0];
21497 						cksum += up[1];
21498 						up += 2;
21499 					} while (--hlen);
21500 				}
21501 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21502 				cksum = ~(cksum + (cksum >> 16));
21503 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
21504 			}
21505 			if (ipsec_len != 0) {
21506 				ipsec_out_process(q, first_mp, ire, ill_index);
21507 				if (!next_mp) {
21508 					ire_refrele(ire);
21509 					if (conn_outgoing_ill != NULL)
21510 						ill_refrele(conn_outgoing_ill);
21511 					return;
21512 				}
21513 				goto next;
21514 			}
21515 
21516 			/*
21517 			 * multirt_send has already been handled
21518 			 * for broadcast, but not yet for multicast
21519 			 * or IP options.
21520 			 */
21521 			if (next_mp == NULL) {
21522 				if (ire->ire_flags & RTF_MULTIRT) {
21523 					multirt_send = B_TRUE;
21524 				}
21525 			}
21526 
21527 			/*
21528 			 * In most cases, the emission loop below is
21529 			 * entered only once. Only in the case where
21530 			 * the ire holds the RTF_MULTIRT flag, do we loop
21531 			 * to process all RTF_MULTIRT ires in the bucket,
21532 			 * and send the packet through all crossed
21533 			 * RTF_MULTIRT routes.
21534 			 */
21535 			do {
21536 				if (multirt_send) {
21537 					irb_t *irb;
21538 
21539 					irb = ire->ire_bucket;
21540 					ASSERT(irb != NULL);
21541 					/*
21542 					 * We are in a multiple send case,
21543 					 * need to get the next IRE and make
21544 					 * a duplicate of the packet.
21545 					 */
21546 					IRB_REFHOLD(irb);
21547 					for (ire1 = ire->ire_next;
21548 					    ire1 != NULL;
21549 					    ire1 = ire1->ire_next) {
21550 						if (!(ire1->ire_flags &
21551 						    RTF_MULTIRT))
21552 							continue;
21553 						if (ire1->ire_addr !=
21554 						    ire->ire_addr)
21555 							continue;
21556 						if (ire1->ire_marks &
21557 						    (IRE_MARK_CONDEMNED|
21558 							IRE_MARK_HIDDEN))
21559 							continue;
21560 
21561 						/* Got one */
21562 						IRE_REFHOLD(ire1);
21563 						break;
21564 					}
21565 					IRB_REFRELE(irb);
21566 
21567 					if (ire1 != NULL) {
21568 						next_mp = copyb(mp);
21569 						if ((next_mp == NULL) ||
21570 						    ((mp->b_cont != NULL) &&
21571 						    ((next_mp->b_cont =
21572 						    dupmsg(mp->b_cont))
21573 						    == NULL))) {
21574 							freemsg(next_mp);
21575 							next_mp = NULL;
21576 							ire_refrele(ire1);
21577 							ire1 = NULL;
21578 						}
21579 					}
21580 
21581 					/*
21582 					 * Last multiroute ire; don't loop
21583 					 * anymore. The emission is over
21584 					 * and next_mp is NULL.
21585 					 */
21586 					if (ire1 == NULL) {
21587 						multirt_send = B_FALSE;
21588 					}
21589 				}
21590 
21591 				ASSERT(ipsec_len == 0);
21592 				mp1 = ip_wput_attach_llhdr(mp, ire,
21593 				    IPP_LOCAL_OUT, ill_index);
21594 				if (mp1 == NULL) {
21595 					BUMP_MIB(&ip_mib, ipOutDiscards);
21596 					if (next_mp) {
21597 						freemsg(next_mp);
21598 						ire_refrele(ire1);
21599 					}
21600 					ire_refrele(ire);
21601 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21602 					    "ip_wput_ire_end: q %p (%S)",
21603 					    q, "discard MDATA");
21604 					if (conn_outgoing_ill != NULL)
21605 						ill_refrele(conn_outgoing_ill);
21606 					return;
21607 				}
21608 				UPDATE_OB_PKT_COUNT(ire);
21609 				ire->ire_last_used_time = lbolt;
21610 
21611 				if (multirt_send) {
21612 					/*
21613 					 * We are in a multiple send case,
21614 					 * need to re-enter the sending loop
21615 					 * using the next ire.
21616 					 */
21617 					putnext(stq, mp1);
21618 					ire_refrele(ire);
21619 					ire = ire1;
21620 					stq = ire->ire_stq;
21621 					mp = next_mp;
21622 					next_mp = NULL;
21623 					ipha = (ipha_t *)mp->b_rptr;
21624 					ill_index = Q_TO_INDEX(stq);
21625 				}
21626 			} while (multirt_send);
21627 
21628 			if (!next_mp) {
21629 				/*
21630 				 * Last copy going out (the ultra-common
21631 				 * case).  Note that we intentionally replicate
21632 				 * the putnext rather than calling it before
21633 				 * the next_mp check in hopes of a little
21634 				 * tail-call action out of the compiler.
21635 				 */
21636 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21637 				    "ip_wput_ire_end: q %p (%S)",
21638 				    q, "last copy out(1)");
21639 				putnext(stq, mp1);
21640 				ire_refrele(ire);
21641 				if (conn_outgoing_ill != NULL)
21642 					ill_refrele(conn_outgoing_ill);
21643 				return;
21644 			}
21645 			/* More copies going out below. */
21646 			putnext(stq, mp1);
21647 		} else {
21648 			int offset;
21649 		    fragmentit:
21650 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21651 			/*
21652 			 * If this would generate a icmp_frag_needed message,
21653 			 * we need to handle it before we do the IPSEC
21654 			 * processing. Otherwise, we need to strip the IPSEC
21655 			 * headers before we send up the message to the ULPs
21656 			 * which becomes messy and difficult.
21657 			 */
21658 			if (ipsec_len != 0) {
21659 				if ((max_frag < (unsigned int)(LENGTH +
21660 				    ipsec_len)) && (offset & IPH_DF)) {
21661 
21662 					BUMP_MIB(&ip_mib, ipFragFails);
21663 					ipha->ipha_hdr_checksum = 0;
21664 					ipha->ipha_hdr_checksum =
21665 					    (uint16_t)ip_csum_hdr(ipha);
21666 					icmp_frag_needed(ire->ire_stq, first_mp,
21667 					    max_frag);
21668 					if (!next_mp) {
21669 						ire_refrele(ire);
21670 						if (conn_outgoing_ill != NULL) {
21671 							ill_refrele(
21672 							    conn_outgoing_ill);
21673 						}
21674 						return;
21675 					}
21676 				} else {
21677 					/*
21678 					 * This won't cause a icmp_frag_needed
21679 					 * message. to be gnerated. Send it on
21680 					 * the wire. Note that this could still
21681 					 * cause fragmentation and all we
21682 					 * do is the generation of the message
21683 					 * to the ULP if needed before IPSEC.
21684 					 */
21685 					if (!next_mp) {
21686 						ipsec_out_process(q, first_mp,
21687 						    ire, ill_index);
21688 						TRACE_2(TR_FAC_IP,
21689 						    TR_IP_WPUT_IRE_END,
21690 						    "ip_wput_ire_end: q %p "
21691 						    "(%S)", q,
21692 						    "last ipsec_out_process");
21693 						ire_refrele(ire);
21694 						if (conn_outgoing_ill != NULL) {
21695 							ill_refrele(
21696 							    conn_outgoing_ill);
21697 						}
21698 						return;
21699 					}
21700 					ipsec_out_process(q, first_mp,
21701 					    ire, ill_index);
21702 				}
21703 			} else {
21704 				/* Initiate IPPF processing */
21705 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21706 					ip_process(IPP_LOCAL_OUT, &mp,
21707 					    ill_index);
21708 					if (mp == NULL) {
21709 						BUMP_MIB(&ip_mib,
21710 						    ipOutDiscards);
21711 						if (next_mp != NULL) {
21712 							freemsg(next_mp);
21713 							ire_refrele(ire1);
21714 						}
21715 						ire_refrele(ire);
21716 						TRACE_2(TR_FAC_IP,
21717 						    TR_IP_WPUT_IRE_END,
21718 						    "ip_wput_ire: q %p (%S)",
21719 						    q, "discard MDATA");
21720 						if (conn_outgoing_ill != NULL) {
21721 							ill_refrele(
21722 							    conn_outgoing_ill);
21723 						}
21724 						return;
21725 					}
21726 				}
21727 				if (!next_mp) {
21728 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21729 					    "ip_wput_ire_end: q %p (%S)",
21730 					    q, "last fragmentation");
21731 					ip_wput_ire_fragmentit(mp, ire);
21732 					ire_refrele(ire);
21733 					if (conn_outgoing_ill != NULL)
21734 						ill_refrele(conn_outgoing_ill);
21735 					return;
21736 				}
21737 				ip_wput_ire_fragmentit(mp, ire);
21738 			}
21739 		}
21740 	} else {
21741 	    nullstq:
21742 		/* A NULL stq means the destination address is local. */
21743 		UPDATE_OB_PKT_COUNT(ire);
21744 		ire->ire_last_used_time = lbolt;
21745 		ASSERT(ire->ire_ipif != NULL);
21746 		if (!next_mp) {
21747 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21748 			    "ip_wput_ire_end: q %p (%S)",
21749 			    q, "local address");
21750 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
21751 			    first_mp, ire, 0, ire->ire_zoneid);
21752 			ire_refrele(ire);
21753 			if (conn_outgoing_ill != NULL)
21754 				ill_refrele(conn_outgoing_ill);
21755 			return;
21756 		}
21757 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
21758 		    ire, 0, ire->ire_zoneid);
21759 	}
21760 next:
21761 	/*
21762 	 * More copies going out to additional interfaces.
21763 	 * ire1 has already been held. We don't need the
21764 	 * "ire" anymore.
21765 	 */
21766 	ire_refrele(ire);
21767 	ire = ire1;
21768 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
21769 	mp = next_mp;
21770 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
21771 	ill = ire_to_ill(ire);
21772 	first_mp = mp;
21773 	if (ipsec_len != 0) {
21774 		ASSERT(first_mp->b_datap->db_type == M_CTL);
21775 		mp = mp->b_cont;
21776 	}
21777 	dst = ire->ire_addr;
21778 	ipha = (ipha_t *)mp->b_rptr;
21779 	/*
21780 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
21781 	 * Restore ipha_ident "no checksum" flag.
21782 	 */
21783 	src = orig_src;
21784 	ipha->ipha_ident = ip_hdr_included;
21785 	goto another;
21786 
21787 #undef	rptr
21788 #undef	Q_TO_INDEX
21789 }
21790 
21791 /*
21792  * Routine to allocate a message that is used to notify the ULP about MDT.
21793  * The caller may provide a pointer to the link-layer MDT capabilities,
21794  * or NULL if MDT is to be disabled on the stream.
21795  */
21796 mblk_t *
21797 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
21798 {
21799 	mblk_t *mp;
21800 	ip_mdt_info_t *mdti;
21801 	ill_mdt_capab_t *idst;
21802 
21803 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
21804 		DB_TYPE(mp) = M_CTL;
21805 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
21806 		mdti = (ip_mdt_info_t *)mp->b_rptr;
21807 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
21808 		idst = &(mdti->mdt_capab);
21809 
21810 		/*
21811 		 * If the caller provides us with the capability, copy
21812 		 * it over into our notification message; otherwise
21813 		 * we zero out the capability portion.
21814 		 */
21815 		if (isrc != NULL)
21816 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
21817 		else
21818 			bzero((caddr_t)idst, sizeof (*idst));
21819 	}
21820 	return (mp);
21821 }
21822 
21823 /*
21824  * Routine which determines whether MDT can be enabled on the destination
21825  * IRE and IPC combination, and if so, allocates and returns the MDT
21826  * notification mblk that may be used by ULP.  We also check if we need to
21827  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21828  * MDT usage in the past have been lifted.  This gets called during IP
21829  * and ULP binding.
21830  */
21831 mblk_t *
21832 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21833     ill_mdt_capab_t *mdt_cap)
21834 {
21835 	mblk_t *mp;
21836 	boolean_t rc = B_FALSE;
21837 
21838 	ASSERT(dst_ire != NULL);
21839 	ASSERT(connp != NULL);
21840 	ASSERT(mdt_cap != NULL);
21841 
21842 	/*
21843 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21844 	 * Multidata, which is handled in tcp_multisend().  This
21845 	 * is the reason why we do all these checks here, to ensure
21846 	 * that we don't enable Multidata for the cases which we
21847 	 * can't handle at the moment.
21848 	 */
21849 	do {
21850 		/* Only do TCP at the moment */
21851 		if (connp->conn_ulp != IPPROTO_TCP)
21852 			break;
21853 
21854 		/*
21855 		 * IPSEC outbound policy present?  Note that we get here
21856 		 * after calling ipsec_conn_cache_policy() where the global
21857 		 * policy checking is performed.  conn_latch will be
21858 		 * non-NULL as long as there's a policy defined,
21859 		 * i.e. conn_out_enforce_policy may be NULL in such case
21860 		 * when the connection is non-secure, and hence we check
21861 		 * further if the latch refers to an outbound policy.
21862 		 */
21863 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21864 			break;
21865 
21866 		/* CGTP (multiroute) is enabled? */
21867 		if (dst_ire->ire_flags & RTF_MULTIRT)
21868 			break;
21869 
21870 		/* Outbound IPQoS enabled? */
21871 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21872 			/*
21873 			 * In this case, we disable MDT for this and all
21874 			 * future connections going over the interface.
21875 			 */
21876 			mdt_cap->ill_mdt_on = 0;
21877 			break;
21878 		}
21879 
21880 		/* socket option(s) present? */
21881 		if (!CONN_IS_MD_FASTPATH(connp))
21882 			break;
21883 
21884 		rc = B_TRUE;
21885 	/* CONSTCOND */
21886 	} while (0);
21887 
21888 	/* Remember the result */
21889 	connp->conn_mdt_ok = rc;
21890 
21891 	if (!rc)
21892 		return (NULL);
21893 	else if (!mdt_cap->ill_mdt_on) {
21894 		/*
21895 		 * If MDT has been previously turned off in the past, and we
21896 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21897 		 * then enable it for this interface.
21898 		 */
21899 		mdt_cap->ill_mdt_on = 1;
21900 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21901 		    "interface %s\n", ill_name));
21902 	}
21903 
21904 	/* Allocate the MDT info mblk */
21905 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21906 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21907 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21908 		return (NULL);
21909 	}
21910 	return (mp);
21911 }
21912 
21913 /*
21914  * Create destination address attribute, and fill it with the physical
21915  * destination address and SAP taken from the template DL_UNITDATA_REQ
21916  * message block.
21917  */
21918 boolean_t
21919 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21920 {
21921 	dl_unitdata_req_t *dlurp;
21922 	pattr_t *pa;
21923 	pattrinfo_t pa_info;
21924 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21925 	uint_t das_len, das_off;
21926 
21927 	ASSERT(dlmp != NULL);
21928 
21929 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21930 	das_len = dlurp->dl_dest_addr_length;
21931 	das_off = dlurp->dl_dest_addr_offset;
21932 
21933 	pa_info.type = PATTR_DSTADDRSAP;
21934 	pa_info.len = sizeof (**das) + das_len - 1;
21935 
21936 	/* create and associate the attribute */
21937 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21938 	if (pa != NULL) {
21939 		ASSERT(*das != NULL);
21940 		(*das)->addr_is_group = 0;
21941 		(*das)->addr_len = (uint8_t)das_len;
21942 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21943 	}
21944 
21945 	return (pa != NULL);
21946 }
21947 
21948 /*
21949  * Create hardware checksum attribute and fill it with the values passed.
21950  */
21951 boolean_t
21952 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21953     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21954 {
21955 	pattr_t *pa;
21956 	pattrinfo_t pa_info;
21957 
21958 	ASSERT(mmd != NULL);
21959 
21960 	pa_info.type = PATTR_HCKSUM;
21961 	pa_info.len = sizeof (pattr_hcksum_t);
21962 
21963 	/* create and associate the attribute */
21964 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21965 	if (pa != NULL) {
21966 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21967 
21968 		hck->hcksum_start_offset = start_offset;
21969 		hck->hcksum_stuff_offset = stuff_offset;
21970 		hck->hcksum_end_offset = end_offset;
21971 		hck->hcksum_flags = flags;
21972 	}
21973 	return (pa != NULL);
21974 }
21975 
21976 /*
21977  * Create zerocopy attribute and fill it with the specified flags
21978  */
21979 boolean_t
21980 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21981 {
21982 	pattr_t *pa;
21983 	pattrinfo_t pa_info;
21984 
21985 	ASSERT(mmd != NULL);
21986 	pa_info.type = PATTR_ZCOPY;
21987 	pa_info.len = sizeof (pattr_zcopy_t);
21988 
21989 	/* create and associate the attribute */
21990 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21991 	if (pa != NULL) {
21992 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
21993 
21994 		zcopy->zcopy_flags = flags;
21995 	}
21996 	return (pa != NULL);
21997 }
21998 
21999 /*
22000  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22001  * block chain. We could rewrite to handle arbitrary message block chains but
22002  * that would make the code complicated and slow. Right now there three
22003  * restrictions:
22004  *
22005  *   1. The first message block must contain the complete IP header and
22006  *	at least 1 byte of payload data.
22007  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22008  *	so that we can use a single Multidata message.
22009  *   3. No frag must be distributed over two or more message blocks so
22010  *	that we don't need more than two packet descriptors per frag.
22011  *
22012  * The above restrictions allow us to support userland applications (which
22013  * will send down a single message block) and NFS over UDP (which will
22014  * send down a chain of at most three message blocks).
22015  *
22016  * We also don't use MDT for payloads with less than or equal to
22017  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22018  */
22019 boolean_t
22020 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22021 {
22022 	int	blocks;
22023 	ssize_t	total, missing, size;
22024 
22025 	ASSERT(mp != NULL);
22026 	ASSERT(hdr_len > 0);
22027 
22028 	size = MBLKL(mp) - hdr_len;
22029 	if (size <= 0)
22030 		return (B_FALSE);
22031 
22032 	/* The first mblk contains the header and some payload. */
22033 	blocks = 1;
22034 	total = size;
22035 	size %= len;
22036 	missing = (size == 0) ? 0 : (len - size);
22037 	mp = mp->b_cont;
22038 
22039 	while (mp != NULL) {
22040 		/*
22041 		 * Give up if we encounter a zero length message block.
22042 		 * In practice, this should rarely happen and therefore
22043 		 * not worth the trouble of freeing and re-linking the
22044 		 * mblk from the chain to handle such case.
22045 		 */
22046 		if ((size = MBLKL(mp)) == 0)
22047 			return (B_FALSE);
22048 
22049 		/* Too many payload buffers for a single Multidata message? */
22050 		if (++blocks > MULTIDATA_MAX_PBUFS)
22051 			return (B_FALSE);
22052 
22053 		total += size;
22054 		/* Is a frag distributed over two or more message blocks? */
22055 		if (missing > size)
22056 			return (B_FALSE);
22057 		size -= missing;
22058 
22059 		size %= len;
22060 		missing = (size == 0) ? 0 : (len - size);
22061 
22062 		mp = mp->b_cont;
22063 	}
22064 
22065 	return (total > ip_wput_frag_mdt_min);
22066 }
22067 
22068 /*
22069  * Outbound IPv4 fragmentation routine using MDT.
22070  */
22071 static void
22072 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22073     uint32_t frag_flag, int offset)
22074 {
22075 	ipha_t		*ipha_orig;
22076 	int		i1, ip_data_end;
22077 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22078 	mblk_t		*hdr_mp, *md_mp = NULL;
22079 	unsigned char	*hdr_ptr, *pld_ptr;
22080 	multidata_t	*mmd;
22081 	ip_pdescinfo_t	pdi;
22082 
22083 	ASSERT(DB_TYPE(mp) == M_DATA);
22084 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22085 
22086 	ipha_orig = (ipha_t *)mp->b_rptr;
22087 	mp->b_rptr += sizeof (ipha_t);
22088 
22089 	/* Calculate how many packets we will send out */
22090 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22091 	pkts = (i1 + len - 1) / len;
22092 	ASSERT(pkts > 1);
22093 
22094 	/* Allocate a message block which will hold all the IP Headers. */
22095 	wroff = ip_wroff_extra;
22096 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22097 
22098 	i1 = pkts * hdr_chunk_len;
22099 	/*
22100 	 * Create the header buffer, Multidata and destination address
22101 	 * and SAP attribute that should be associated with it.
22102 	 */
22103 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22104 	    ((hdr_mp->b_wptr += i1),
22105 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22106 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
22107 		freemsg(mp);
22108 		if (md_mp == NULL) {
22109 			freemsg(hdr_mp);
22110 		} else {
22111 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22112 			freemsg(md_mp);
22113 		}
22114 		IP_STAT(ip_frag_mdt_allocfail);
22115 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22116 		return;
22117 	}
22118 	IP_STAT(ip_frag_mdt_allocd);
22119 
22120 	/*
22121 	 * Add a payload buffer to the Multidata; this operation must not
22122 	 * fail, or otherwise our logic in this routine is broken.  There
22123 	 * is no memory allocation done by the routine, so any returned
22124 	 * failure simply tells us that we've done something wrong.
22125 	 *
22126 	 * A failure tells us that either we're adding the same payload
22127 	 * buffer more than once, or we're trying to add more buffers than
22128 	 * allowed.  None of the above cases should happen, and we panic
22129 	 * because either there's horrible heap corruption, and/or
22130 	 * programming mistake.
22131 	 */
22132 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22133 		goto pbuf_panic;
22134 
22135 	hdr_ptr = hdr_mp->b_rptr;
22136 	pld_ptr = mp->b_rptr;
22137 
22138 	/* Establish the ending byte offset, based on the starting offset. */
22139 	offset <<= 3;
22140 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22141 	    IP_SIMPLE_HDR_LENGTH;
22142 
22143 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22144 
22145 	while (pld_ptr < mp->b_wptr) {
22146 		ipha_t		*ipha;
22147 		uint16_t	offset_and_flags;
22148 		uint16_t	ip_len;
22149 		int		error;
22150 
22151 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22152 		ipha = (ipha_t *)(hdr_ptr + wroff);
22153 		ASSERT(OK_32PTR(ipha));
22154 		*ipha = *ipha_orig;
22155 
22156 		if (ip_data_end - offset > len) {
22157 			offset_and_flags = IPH_MF;
22158 		} else {
22159 			/*
22160 			 * Last frag. Set len to the length of this last piece.
22161 			 */
22162 			len = ip_data_end - offset;
22163 			/* A frag of a frag might have IPH_MF non-zero */
22164 			offset_and_flags =
22165 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22166 			    IPH_MF;
22167 		}
22168 		offset_and_flags |= (uint16_t)(offset >> 3);
22169 		offset_and_flags |= (uint16_t)frag_flag;
22170 		/* Store the offset and flags in the IP header. */
22171 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22172 
22173 		/* Store the length in the IP header. */
22174 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22175 		ipha->ipha_length = htons(ip_len);
22176 
22177 		/*
22178 		 * Set the IP header checksum.  Note that mp is just
22179 		 * the header, so this is easy to pass to ip_csum.
22180 		 */
22181 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22182 
22183 		/*
22184 		 * Record offset and size of header and data of the next packet
22185 		 * in the multidata message.
22186 		 */
22187 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22188 		PDESC_PLD_INIT(&pdi);
22189 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22190 		ASSERT(i1 > 0);
22191 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22192 		if (i1 == len) {
22193 			pld_ptr += len;
22194 		} else {
22195 			i1 = len - i1;
22196 			mp = mp->b_cont;
22197 			ASSERT(mp != NULL);
22198 			ASSERT(MBLKL(mp) >= i1);
22199 			/*
22200 			 * Attach the next payload message block to the
22201 			 * multidata message.
22202 			 */
22203 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22204 				goto pbuf_panic;
22205 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22206 			pld_ptr = mp->b_rptr + i1;
22207 		}
22208 
22209 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22210 		    KM_NOSLEEP)) == NULL) {
22211 			/*
22212 			 * Any failure other than ENOMEM indicates that we
22213 			 * have passed in invalid pdesc info or parameters
22214 			 * to mmd_addpdesc, which must not happen.
22215 			 *
22216 			 * EINVAL is a result of failure on boundary checks
22217 			 * against the pdesc info contents.  It should not
22218 			 * happen, and we panic because either there's
22219 			 * horrible heap corruption, and/or programming
22220 			 * mistake.
22221 			 */
22222 			if (error != ENOMEM) {
22223 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22224 				    "pdesc logic error detected for "
22225 				    "mmd %p pinfo %p (%d)\n",
22226 				    (void *)mmd, (void *)&pdi, error);
22227 				/* NOTREACHED */
22228 			}
22229 			IP_STAT(ip_frag_mdt_addpdescfail);
22230 			/* Free unattached payload message blocks as well */
22231 			md_mp->b_cont = mp->b_cont;
22232 			goto free_mmd;
22233 		}
22234 
22235 		/* Advance fragment offset. */
22236 		offset += len;
22237 
22238 		/* Advance to location for next header in the buffer. */
22239 		hdr_ptr += hdr_chunk_len;
22240 
22241 		/* Did we reach the next payload message block? */
22242 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22243 			mp = mp->b_cont;
22244 			/*
22245 			 * Attach the next message block with payload
22246 			 * data to the multidata message.
22247 			 */
22248 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22249 				goto pbuf_panic;
22250 			pld_ptr = mp->b_rptr;
22251 		}
22252 	}
22253 
22254 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22255 	ASSERT(mp->b_wptr == pld_ptr);
22256 
22257 	/* Update IP statistics */
22258 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22259 	BUMP_MIB(&ip_mib, ipFragOKs);
22260 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22261 
22262 	if (pkt_type == OB_PKT) {
22263 		ire->ire_ob_pkt_count += pkts;
22264 		if (ire->ire_ipif != NULL)
22265 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22266 	} else {
22267 		/*
22268 		 * The type is IB_PKT in the forwarding path and in
22269 		 * the mobile IP case when the packet is being reverse-
22270 		 * tunneled to the home agent.
22271 		 */
22272 		ire->ire_ib_pkt_count += pkts;
22273 		ASSERT(!IRE_IS_LOCAL(ire));
22274 		if (ire->ire_type & IRE_BROADCAST)
22275 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22276 		else
22277 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22278 	}
22279 	ire->ire_last_used_time = lbolt;
22280 	/* Send it down */
22281 	putnext(ire->ire_stq, md_mp);
22282 	return;
22283 
22284 pbuf_panic:
22285 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22286 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22287 	    pbuf_idx);
22288 	/* NOTREACHED */
22289 }
22290 
22291 /*
22292  * Outbound IP fragmentation routine.
22293  *
22294  * NOTE : This routine does not ire_refrele the ire that is passed in
22295  * as the argument.
22296  */
22297 static void
22298 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22299     uint32_t frag_flag)
22300 {
22301 	int		i1;
22302 	mblk_t		*ll_hdr_mp;
22303 	int 		ll_hdr_len;
22304 	int		hdr_len;
22305 	mblk_t		*hdr_mp;
22306 	ipha_t		*ipha;
22307 	int		ip_data_end;
22308 	int		len;
22309 	mblk_t		*mp = mp_orig;
22310 	int		offset;
22311 	queue_t		*q;
22312 	uint32_t	v_hlen_tos_len;
22313 	mblk_t		*first_mp;
22314 	boolean_t	mctl_present;
22315 	ill_t		*ill;
22316 	mblk_t		*xmit_mp;
22317 	mblk_t		*carve_mp;
22318 	ire_t		*ire1 = NULL;
22319 	ire_t		*save_ire = NULL;
22320 	mblk_t  	*next_mp = NULL;
22321 	boolean_t	last_frag = B_FALSE;
22322 	boolean_t	multirt_send = B_FALSE;
22323 	ire_t		*first_ire = NULL;
22324 	irb_t		*irb = NULL;
22325 
22326 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22327 	    "ip_wput_frag_start:");
22328 
22329 	if (mp->b_datap->db_type == M_CTL) {
22330 		first_mp = mp;
22331 		mp_orig = mp = mp->b_cont;
22332 		mctl_present = B_TRUE;
22333 	} else {
22334 		first_mp = mp;
22335 		mctl_present = B_FALSE;
22336 	}
22337 
22338 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22339 	ipha = (ipha_t *)mp->b_rptr;
22340 
22341 	/*
22342 	 * If the Don't Fragment flag is on, generate an ICMP destination
22343 	 * unreachable, fragmentation needed.
22344 	 */
22345 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22346 	if (offset & IPH_DF) {
22347 		BUMP_MIB(&ip_mib, ipFragFails);
22348 		/*
22349 		 * Need to compute hdr checksum if called from ip_wput_ire.
22350 		 * Note that ip_rput_forward verifies the checksum before
22351 		 * calling this routine so in that case this is a noop.
22352 		 */
22353 		ipha->ipha_hdr_checksum = 0;
22354 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22355 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22356 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22357 		    "ip_wput_frag_end:(%S)",
22358 		    "don't fragment");
22359 		return;
22360 	}
22361 	if (mctl_present)
22362 		freeb(first_mp);
22363 	/*
22364 	 * Establish the starting offset.  May not be zero if we are fragging
22365 	 * a fragment that is being forwarded.
22366 	 */
22367 	offset = offset & IPH_OFFSET;
22368 
22369 	/* TODO why is this test needed? */
22370 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22371 	if (((max_frag - LENGTH) & ~7) < 8) {
22372 		/* TODO: notify ulp somehow */
22373 		BUMP_MIB(&ip_mib, ipFragFails);
22374 		freemsg(mp);
22375 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22376 		    "ip_wput_frag_end:(%S)",
22377 		    "len < 8");
22378 		return;
22379 	}
22380 
22381 	hdr_len = (V_HLEN & 0xF) << 2;
22382 
22383 	ipha->ipha_hdr_checksum = 0;
22384 
22385 	/*
22386 	 * Establish the number of bytes maximum per frag, after putting
22387 	 * in the header.
22388 	 */
22389 	len = (max_frag - hdr_len) & ~7;
22390 
22391 	/* Check if we can use MDT to send out the frags. */
22392 	ASSERT(!IRE_IS_LOCAL(ire));
22393 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
22394 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
22395 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
22396 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
22397 		ASSERT(ill->ill_mdt_capab != NULL);
22398 		if (!ill->ill_mdt_capab->ill_mdt_on) {
22399 			/*
22400 			 * If MDT has been previously turned off in the past,
22401 			 * and we currently can do MDT (due to IPQoS policy
22402 			 * removal, etc.) then enable it for this interface.
22403 			 */
22404 			ill->ill_mdt_capab->ill_mdt_on = 1;
22405 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
22406 			    ill->ill_name));
22407 		}
22408 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
22409 		    offset);
22410 		return;
22411 	}
22412 
22413 	/* Get a copy of the header for the trailing frags */
22414 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
22415 	if (!hdr_mp) {
22416 		BUMP_MIB(&ip_mib, ipOutDiscards);
22417 		freemsg(mp);
22418 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22419 		    "ip_wput_frag_end:(%S)",
22420 		    "couldn't copy hdr");
22421 		return;
22422 	}
22423 	if (DB_CRED(mp) != NULL)
22424 		mblk_setcred(hdr_mp, DB_CRED(mp));
22425 
22426 	/* Store the starting offset, with the MoreFrags flag. */
22427 	i1 = offset | IPH_MF | frag_flag;
22428 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
22429 
22430 	/* Establish the ending byte offset, based on the starting offset. */
22431 	offset <<= 3;
22432 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
22433 
22434 	/* Store the length of the first fragment in the IP header. */
22435 	i1 = len + hdr_len;
22436 	ASSERT(i1 <= IP_MAXPACKET);
22437 	ipha->ipha_length = htons((uint16_t)i1);
22438 
22439 	/*
22440 	 * Compute the IP header checksum for the first frag.  We have to
22441 	 * watch out that we stop at the end of the header.
22442 	 */
22443 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22444 
22445 	/*
22446 	 * Now carve off the first frag.  Note that this will include the
22447 	 * original IP header.
22448 	 */
22449 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
22450 		BUMP_MIB(&ip_mib, ipOutDiscards);
22451 		freeb(hdr_mp);
22452 		freemsg(mp_orig);
22453 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22454 		    "ip_wput_frag_end:(%S)",
22455 		    "couldn't carve first");
22456 		return;
22457 	}
22458 
22459 	/*
22460 	 * Multirouting case. Each fragment is replicated
22461 	 * via all non-condemned RTF_MULTIRT routes
22462 	 * currently resolved.
22463 	 * We ensure that first_ire is the first RTF_MULTIRT
22464 	 * ire in the bucket.
22465 	 */
22466 	if (ire->ire_flags & RTF_MULTIRT) {
22467 		irb = ire->ire_bucket;
22468 		ASSERT(irb != NULL);
22469 
22470 		multirt_send = B_TRUE;
22471 
22472 		/* Make sure we do not omit any multiroute ire. */
22473 		IRB_REFHOLD(irb);
22474 		for (first_ire = irb->irb_ire;
22475 		    first_ire != NULL;
22476 		    first_ire = first_ire->ire_next) {
22477 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22478 			    (first_ire->ire_addr == ire->ire_addr) &&
22479 			    !(first_ire->ire_marks &
22480 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22481 				break;
22482 		}
22483 
22484 		if (first_ire != NULL) {
22485 			if (first_ire != ire) {
22486 				IRE_REFHOLD(first_ire);
22487 				/*
22488 				 * Do not release the ire passed in
22489 				 * as the argument.
22490 				 */
22491 				ire = first_ire;
22492 			} else {
22493 				first_ire = NULL;
22494 			}
22495 		}
22496 		IRB_REFRELE(irb);
22497 
22498 		/*
22499 		 * Save the first ire; we will need to restore it
22500 		 * for the trailing frags.
22501 		 * We REFHOLD save_ire, as each iterated ire will be
22502 		 * REFRELEd.
22503 		 */
22504 		save_ire = ire;
22505 		IRE_REFHOLD(save_ire);
22506 	}
22507 
22508 	/*
22509 	 * First fragment emission loop.
22510 	 * In most cases, the emission loop below is entered only
22511 	 * once. Only in the case where the ire holds the RTF_MULTIRT
22512 	 * flag, do we loop to process all RTF_MULTIRT ires in the
22513 	 * bucket, and send the fragment through all crossed
22514 	 * RTF_MULTIRT routes.
22515 	 */
22516 	do {
22517 		if (ire->ire_flags & RTF_MULTIRT) {
22518 			/*
22519 			 * We are in a multiple send case, need to get
22520 			 * the next ire and make a copy of the packet.
22521 			 * ire1 holds here the next ire to process in the
22522 			 * bucket. If multirouting is expected,
22523 			 * any non-RTF_MULTIRT ire that has the
22524 			 * right destination address is ignored.
22525 			 *
22526 			 * We have to take into account the MTU of
22527 			 * each walked ire. max_frag is set by the
22528 			 * the caller and generally refers to
22529 			 * the primary ire entry. Here we ensure that
22530 			 * no route with a lower MTU will be used, as
22531 			 * fragments are carved once for all ires,
22532 			 * then replicated.
22533 			 */
22534 			ASSERT(irb != NULL);
22535 			IRB_REFHOLD(irb);
22536 			for (ire1 = ire->ire_next;
22537 			    ire1 != NULL;
22538 			    ire1 = ire1->ire_next) {
22539 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22540 					continue;
22541 				if (ire1->ire_addr != ire->ire_addr)
22542 					continue;
22543 				if (ire1->ire_marks &
22544 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22545 					continue;
22546 				/*
22547 				 * Ensure we do not exceed the MTU
22548 				 * of the next route.
22549 				 */
22550 				if (ire1->ire_max_frag < max_frag) {
22551 					ip_multirt_bad_mtu(ire1, max_frag);
22552 					continue;
22553 				}
22554 
22555 				/* Got one. */
22556 				IRE_REFHOLD(ire1);
22557 				break;
22558 			}
22559 			IRB_REFRELE(irb);
22560 
22561 			if (ire1 != NULL) {
22562 				next_mp = copyb(mp);
22563 				if ((next_mp == NULL) ||
22564 				    ((mp->b_cont != NULL) &&
22565 				    ((next_mp->b_cont =
22566 				    dupmsg(mp->b_cont)) == NULL))) {
22567 					freemsg(next_mp);
22568 					next_mp = NULL;
22569 					ire_refrele(ire1);
22570 					ire1 = NULL;
22571 				}
22572 			}
22573 
22574 			/* Last multiroute ire; don't loop anymore. */
22575 			if (ire1 == NULL) {
22576 				multirt_send = B_FALSE;
22577 			}
22578 		}
22579 
22580 		ll_hdr_len = 0;
22581 		LOCK_IRE_FP_MP(ire);
22582 		ll_hdr_mp = ire->ire_fp_mp;
22583 		if (ll_hdr_mp != NULL) {
22584 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22585 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
22586 		} else {
22587 			ll_hdr_mp = ire->ire_dlureq_mp;
22588 		}
22589 
22590 		/* If there is a transmit header, get a copy for this frag. */
22591 		/*
22592 		 * TODO: should check db_ref before calling ip_carve_mp since
22593 		 * it might give us a dup.
22594 		 */
22595 		if (!ll_hdr_mp) {
22596 			/* No xmit header. */
22597 			xmit_mp = mp;
22598 		} else if (mp->b_datap->db_ref == 1 &&
22599 		    ll_hdr_len != 0 &&
22600 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22601 			/* M_DATA fastpath */
22602 			mp->b_rptr -= ll_hdr_len;
22603 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
22604 			xmit_mp = mp;
22605 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
22606 			UNLOCK_IRE_FP_MP(ire);
22607 			BUMP_MIB(&ip_mib, ipOutDiscards);
22608 			freeb(hdr_mp);
22609 			freemsg(mp);
22610 			freemsg(mp_orig);
22611 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22612 			    "ip_wput_frag_end:(%S)",
22613 			    "discard");
22614 
22615 			if (multirt_send) {
22616 				ASSERT(ire1);
22617 				ASSERT(next_mp);
22618 
22619 				freemsg(next_mp);
22620 				ire_refrele(ire1);
22621 			}
22622 			if (save_ire != NULL)
22623 				IRE_REFRELE(save_ire);
22624 
22625 			if (first_ire != NULL)
22626 				ire_refrele(first_ire);
22627 			return;
22628 		} else {
22629 			xmit_mp->b_cont = mp;
22630 			if (DB_CRED(mp) != NULL)
22631 				mblk_setcred(xmit_mp, DB_CRED(mp));
22632 			/* Get priority marking, if any. */
22633 			if (DB_TYPE(xmit_mp) == M_DATA)
22634 				xmit_mp->b_band = mp->b_band;
22635 		}
22636 		UNLOCK_IRE_FP_MP(ire);
22637 		q = ire->ire_stq;
22638 		BUMP_MIB(&ip_mib, ipFragCreates);
22639 		putnext(q, xmit_mp);
22640 		if (pkt_type != OB_PKT) {
22641 			/*
22642 			 * Update the packet count of trailing
22643 			 * RTF_MULTIRT ires.
22644 			 */
22645 			UPDATE_OB_PKT_COUNT(ire);
22646 		}
22647 
22648 		if (multirt_send) {
22649 			/*
22650 			 * We are in a multiple send case; look for
22651 			 * the next ire and re-enter the loop.
22652 			 */
22653 			ASSERT(ire1);
22654 			ASSERT(next_mp);
22655 			/* REFRELE the current ire before looping */
22656 			ire_refrele(ire);
22657 			ire = ire1;
22658 			ire1 = NULL;
22659 			mp = next_mp;
22660 			next_mp = NULL;
22661 		}
22662 	} while (multirt_send);
22663 
22664 	ASSERT(ire1 == NULL);
22665 
22666 	/* Restore the original ire; we need it for the trailing frags */
22667 	if (save_ire != NULL) {
22668 		/* REFRELE the last iterated ire */
22669 		ire_refrele(ire);
22670 		/* save_ire has been REFHOLDed */
22671 		ire = save_ire;
22672 		save_ire = NULL;
22673 		q = ire->ire_stq;
22674 	}
22675 
22676 	if (pkt_type == OB_PKT) {
22677 		UPDATE_OB_PKT_COUNT(ire);
22678 	} else {
22679 		UPDATE_IB_PKT_COUNT(ire);
22680 	}
22681 
22682 	/* Advance the offset to the second frag starting point. */
22683 	offset += len;
22684 	/*
22685 	 * Update hdr_len from the copied header - there might be less options
22686 	 * in the later fragments.
22687 	 */
22688 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
22689 	/* Loop until done. */
22690 	for (;;) {
22691 		uint16_t	offset_and_flags;
22692 		uint16_t	ip_len;
22693 
22694 		if (ip_data_end - offset > len) {
22695 			/*
22696 			 * Carve off the appropriate amount from the original
22697 			 * datagram.
22698 			 */
22699 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22700 				mp = NULL;
22701 				break;
22702 			}
22703 			/*
22704 			 * More frags after this one.  Get another copy
22705 			 * of the header.
22706 			 */
22707 			if (carve_mp->b_datap->db_ref == 1 &&
22708 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22709 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22710 				/* Inline IP header */
22711 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22712 				    hdr_mp->b_rptr;
22713 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22714 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22715 				mp = carve_mp;
22716 			} else {
22717 				if (!(mp = copyb(hdr_mp))) {
22718 					freemsg(carve_mp);
22719 					break;
22720 				}
22721 				/* Get priority marking, if any. */
22722 				mp->b_band = carve_mp->b_band;
22723 				mp->b_cont = carve_mp;
22724 			}
22725 			ipha = (ipha_t *)mp->b_rptr;
22726 			offset_and_flags = IPH_MF;
22727 		} else {
22728 			/*
22729 			 * Last frag.  Consume the header. Set len to
22730 			 * the length of this last piece.
22731 			 */
22732 			len = ip_data_end - offset;
22733 
22734 			/*
22735 			 * Carve off the appropriate amount from the original
22736 			 * datagram.
22737 			 */
22738 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22739 				mp = NULL;
22740 				break;
22741 			}
22742 			if (carve_mp->b_datap->db_ref == 1 &&
22743 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22744 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22745 				/* Inline IP header */
22746 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22747 				    hdr_mp->b_rptr;
22748 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22749 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22750 				mp = carve_mp;
22751 				freeb(hdr_mp);
22752 				hdr_mp = mp;
22753 			} else {
22754 				mp = hdr_mp;
22755 				/* Get priority marking, if any. */
22756 				mp->b_band = carve_mp->b_band;
22757 				mp->b_cont = carve_mp;
22758 			}
22759 			ipha = (ipha_t *)mp->b_rptr;
22760 			/* A frag of a frag might have IPH_MF non-zero */
22761 			offset_and_flags =
22762 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22763 			    IPH_MF;
22764 		}
22765 		offset_and_flags |= (uint16_t)(offset >> 3);
22766 		offset_and_flags |= (uint16_t)frag_flag;
22767 		/* Store the offset and flags in the IP header. */
22768 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22769 
22770 		/* Store the length in the IP header. */
22771 		ip_len = (uint16_t)(len + hdr_len);
22772 		ipha->ipha_length = htons(ip_len);
22773 
22774 		/*
22775 		 * Set the IP header checksum.	Note that mp is just
22776 		 * the header, so this is easy to pass to ip_csum.
22777 		 */
22778 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22779 
22780 		/* Attach a transmit header, if any, and ship it. */
22781 		if (pkt_type == OB_PKT) {
22782 			UPDATE_OB_PKT_COUNT(ire);
22783 		} else {
22784 			UPDATE_IB_PKT_COUNT(ire);
22785 		}
22786 
22787 		if (ire->ire_flags & RTF_MULTIRT) {
22788 			irb = ire->ire_bucket;
22789 			ASSERT(irb != NULL);
22790 
22791 			multirt_send = B_TRUE;
22792 
22793 			/*
22794 			 * Save the original ire; we will need to restore it
22795 			 * for the tailing frags.
22796 			 */
22797 			save_ire = ire;
22798 			IRE_REFHOLD(save_ire);
22799 		}
22800 		/*
22801 		 * Emission loop for this fragment, similar
22802 		 * to what is done for the first fragment.
22803 		 */
22804 		do {
22805 			if (multirt_send) {
22806 				/*
22807 				 * We are in a multiple send case, need to get
22808 				 * the next ire and make a copy of the packet.
22809 				 */
22810 				ASSERT(irb != NULL);
22811 				IRB_REFHOLD(irb);
22812 				for (ire1 = ire->ire_next;
22813 				    ire1 != NULL;
22814 				    ire1 = ire1->ire_next) {
22815 					if (!(ire1->ire_flags & RTF_MULTIRT))
22816 						continue;
22817 					if (ire1->ire_addr != ire->ire_addr)
22818 						continue;
22819 					if (ire1->ire_marks &
22820 					    (IRE_MARK_CONDEMNED|
22821 						IRE_MARK_HIDDEN))
22822 						continue;
22823 					/*
22824 					 * Ensure we do not exceed the MTU
22825 					 * of the next route.
22826 					 */
22827 					if (ire1->ire_max_frag < max_frag) {
22828 						ip_multirt_bad_mtu(ire1,
22829 						    max_frag);
22830 						continue;
22831 					}
22832 
22833 					/* Got one. */
22834 					IRE_REFHOLD(ire1);
22835 					break;
22836 				}
22837 				IRB_REFRELE(irb);
22838 
22839 				if (ire1 != NULL) {
22840 					next_mp = copyb(mp);
22841 					if ((next_mp == NULL) ||
22842 					    ((mp->b_cont != NULL) &&
22843 					    ((next_mp->b_cont =
22844 					    dupmsg(mp->b_cont)) == NULL))) {
22845 						freemsg(next_mp);
22846 						next_mp = NULL;
22847 						ire_refrele(ire1);
22848 						ire1 = NULL;
22849 					}
22850 				}
22851 
22852 				/* Last multiroute ire; don't loop anymore. */
22853 				if (ire1 == NULL) {
22854 					multirt_send = B_FALSE;
22855 				}
22856 			}
22857 
22858 			/* Update transmit header */
22859 			ll_hdr_len = 0;
22860 			LOCK_IRE_FP_MP(ire);
22861 			ll_hdr_mp = ire->ire_fp_mp;
22862 			if (ll_hdr_mp != NULL) {
22863 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22864 				ll_hdr_len = MBLKL(ll_hdr_mp);
22865 			} else {
22866 				ll_hdr_mp = ire->ire_dlureq_mp;
22867 			}
22868 
22869 			if (!ll_hdr_mp) {
22870 				xmit_mp = mp;
22871 			} else if (mp->b_datap->db_ref == 1 &&
22872 			    ll_hdr_len != 0 &&
22873 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22874 				/* M_DATA fastpath */
22875 				mp->b_rptr -= ll_hdr_len;
22876 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22877 				    ll_hdr_len);
22878 				xmit_mp = mp;
22879 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22880 				xmit_mp->b_cont = mp;
22881 				if (DB_CRED(mp) != NULL)
22882 					mblk_setcred(xmit_mp, DB_CRED(mp));
22883 				/* Get priority marking, if any. */
22884 				if (DB_TYPE(xmit_mp) == M_DATA)
22885 					xmit_mp->b_band = mp->b_band;
22886 			} else {
22887 				/*
22888 				 * Exit both the replication and
22889 				 * fragmentation loops.
22890 				 */
22891 				UNLOCK_IRE_FP_MP(ire);
22892 				goto drop_pkt;
22893 			}
22894 			UNLOCK_IRE_FP_MP(ire);
22895 			BUMP_MIB(&ip_mib, ipFragCreates);
22896 			putnext(q, xmit_mp);
22897 
22898 			if (pkt_type != OB_PKT) {
22899 				/*
22900 				 * Update the packet count of trailing
22901 				 * RTF_MULTIRT ires.
22902 				 */
22903 				UPDATE_OB_PKT_COUNT(ire);
22904 			}
22905 
22906 			/* All done if we just consumed the hdr_mp. */
22907 			if (mp == hdr_mp) {
22908 				last_frag = B_TRUE;
22909 			}
22910 
22911 			if (multirt_send) {
22912 				/*
22913 				 * We are in a multiple send case; look for
22914 				 * the next ire and re-enter the loop.
22915 				 */
22916 				ASSERT(ire1);
22917 				ASSERT(next_mp);
22918 				/* REFRELE the current ire before looping */
22919 				ire_refrele(ire);
22920 				ire = ire1;
22921 				ire1 = NULL;
22922 				q = ire->ire_stq;
22923 				mp = next_mp;
22924 				next_mp = NULL;
22925 			}
22926 		} while (multirt_send);
22927 		/*
22928 		 * Restore the original ire; we need it for the
22929 		 * trailing frags
22930 		 */
22931 		if (save_ire != NULL) {
22932 			ASSERT(ire1 == NULL);
22933 			/* REFRELE the last iterated ire */
22934 			ire_refrele(ire);
22935 			/* save_ire has been REFHOLDed */
22936 			ire = save_ire;
22937 			q = ire->ire_stq;
22938 			save_ire = NULL;
22939 		}
22940 
22941 		if (last_frag) {
22942 			BUMP_MIB(&ip_mib, ipFragOKs);
22943 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22944 			    "ip_wput_frag_end:(%S)",
22945 			    "consumed hdr_mp");
22946 
22947 			if (first_ire != NULL)
22948 				ire_refrele(first_ire);
22949 			return;
22950 		}
22951 		/* Otherwise, advance and loop. */
22952 		offset += len;
22953 	}
22954 
22955 drop_pkt:
22956 	/* Clean up following allocation failure. */
22957 	BUMP_MIB(&ip_mib, ipOutDiscards);
22958 	freemsg(mp);
22959 	if (mp != hdr_mp)
22960 		freeb(hdr_mp);
22961 	if (mp != mp_orig)
22962 		freemsg(mp_orig);
22963 
22964 	if (save_ire != NULL)
22965 		IRE_REFRELE(save_ire);
22966 	if (first_ire != NULL)
22967 		ire_refrele(first_ire);
22968 
22969 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22970 	    "ip_wput_frag_end:(%S)",
22971 	    "end--alloc failure");
22972 }
22973 
22974 /*
22975  * Copy the header plus those options which have the copy bit set
22976  */
22977 static mblk_t *
22978 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22979 {
22980 	mblk_t	*mp;
22981 	uchar_t	*up;
22982 
22983 	/*
22984 	 * Quick check if we need to look for options without the copy bit
22985 	 * set
22986 	 */
22987 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
22988 	if (!mp)
22989 		return (mp);
22990 	mp->b_rptr += ip_wroff_extra;
22991 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
22992 		bcopy(rptr, mp->b_rptr, hdr_len);
22993 		mp->b_wptr += hdr_len + ip_wroff_extra;
22994 		return (mp);
22995 	}
22996 	up  = mp->b_rptr;
22997 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
22998 	up += IP_SIMPLE_HDR_LENGTH;
22999 	rptr += IP_SIMPLE_HDR_LENGTH;
23000 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23001 	while (hdr_len > 0) {
23002 		uint32_t optval;
23003 		uint32_t optlen;
23004 
23005 		optval = *rptr;
23006 		if (optval == IPOPT_EOL)
23007 			break;
23008 		if (optval == IPOPT_NOP)
23009 			optlen = 1;
23010 		else
23011 			optlen = rptr[1];
23012 		if (optval & IPOPT_COPY) {
23013 			bcopy(rptr, up, optlen);
23014 			up += optlen;
23015 		}
23016 		rptr += optlen;
23017 		hdr_len -= optlen;
23018 	}
23019 	/*
23020 	 * Make sure that we drop an even number of words by filling
23021 	 * with EOL to the next word boundary.
23022 	 */
23023 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23024 	    hdr_len & 0x3; hdr_len++)
23025 		*up++ = IPOPT_EOL;
23026 	mp->b_wptr = up;
23027 	/* Update header length */
23028 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23029 	return (mp);
23030 }
23031 
23032 /*
23033  * Delivery to local recipients including fanout to multiple recipients.
23034  * Does not do checksumming of UDP/TCP.
23035  * Note: q should be the read side queue for either the ill or conn.
23036  * Note: rq should be the read side q for the lower (ill) stream.
23037  * We don't send packets to IPPF processing, thus the last argument
23038  * to all the fanout calls are B_FALSE.
23039  */
23040 void
23041 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23042     int fanout_flags, zoneid_t zoneid)
23043 {
23044 	uint32_t	protocol;
23045 	mblk_t		*first_mp;
23046 	boolean_t	mctl_present;
23047 	int		ire_type;
23048 #define	rptr	((uchar_t *)ipha)
23049 
23050 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23051 	    "ip_wput_local_start: q %p", q);
23052 
23053 	if (ire != NULL) {
23054 		ire_type = ire->ire_type;
23055 	} else {
23056 		/*
23057 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23058 		 * packet is not multicast, we can't tell the ire type.
23059 		 */
23060 		ASSERT(CLASSD(ipha->ipha_dst));
23061 		ire_type = IRE_BROADCAST;
23062 	}
23063 
23064 	first_mp = mp;
23065 	if (first_mp->b_datap->db_type == M_CTL) {
23066 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23067 		if (!io->ipsec_out_secure) {
23068 			/*
23069 			 * This ipsec_out_t was allocated in ip_wput
23070 			 * for multicast packets to store the ill_index.
23071 			 * As this is being delivered locally, we don't
23072 			 * need this anymore.
23073 			 */
23074 			mp = first_mp->b_cont;
23075 			freeb(first_mp);
23076 			first_mp = mp;
23077 			mctl_present = B_FALSE;
23078 		} else {
23079 			mctl_present = B_TRUE;
23080 			mp = first_mp->b_cont;
23081 			ASSERT(mp != NULL);
23082 			ipsec_out_to_in(first_mp);
23083 		}
23084 	} else {
23085 		mctl_present = B_FALSE;
23086 	}
23087 
23088 	loopback_packets++;
23089 
23090 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23091 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23092 	if (!IS_SIMPLE_IPH(ipha)) {
23093 		ip_wput_local_options(ipha);
23094 	}
23095 
23096 	protocol = ipha->ipha_protocol;
23097 	switch (protocol) {
23098 	case IPPROTO_ICMP: {
23099 		ire_t		*ire_zone;
23100 		ilm_t		*ilm;
23101 		mblk_t		*mp1;
23102 		zoneid_t	last_zoneid;
23103 
23104 		if (CLASSD(ipha->ipha_dst) &&
23105 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23106 			ASSERT(ire_type == IRE_BROADCAST);
23107 			/*
23108 			 * In the multicast case, applications may have joined
23109 			 * the group from different zones, so we need to deliver
23110 			 * the packet to each of them. Loop through the
23111 			 * multicast memberships structures (ilm) on the receive
23112 			 * ill and send a copy of the packet up each matching
23113 			 * one. However, we don't do this for multicasts sent on
23114 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23115 			 * they must stay in the sender's zone.
23116 			 *
23117 			 * ilm_add_v6() ensures that ilms in the same zone are
23118 			 * contiguous in the ill_ilm list. We use this property
23119 			 * to avoid sending duplicates needed when two
23120 			 * applications in the same zone join the same group on
23121 			 * different logical interfaces: we ignore the ilm if
23122 			 * its zoneid is the same as the last matching one.
23123 			 * In addition, the sending of the packet for
23124 			 * ire_zoneid is delayed until all of the other ilms
23125 			 * have been exhausted.
23126 			 */
23127 			last_zoneid = -1;
23128 			ILM_WALKER_HOLD(ill);
23129 			for (ilm = ill->ill_ilm; ilm != NULL;
23130 			    ilm = ilm->ilm_next) {
23131 				if ((ilm->ilm_flags & ILM_DELETED) ||
23132 				    ipha->ipha_dst != ilm->ilm_addr ||
23133 				    ilm->ilm_zoneid == last_zoneid ||
23134 				    ilm->ilm_zoneid == zoneid ||
23135 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23136 					continue;
23137 				mp1 = ip_copymsg(first_mp);
23138 				if (mp1 == NULL)
23139 					continue;
23140 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23141 				    mctl_present, B_FALSE, ill,
23142 				    ilm->ilm_zoneid);
23143 				last_zoneid = ilm->ilm_zoneid;
23144 			}
23145 			ILM_WALKER_RELE(ill);
23146 			/*
23147 			 * Loopback case: the sending endpoint has
23148 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23149 			 * dispatch the multicast packet to the sending zone.
23150 			 */
23151 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23152 				freemsg(first_mp);
23153 				return;
23154 			}
23155 		} else if (ire_type == IRE_BROADCAST) {
23156 			/*
23157 			 * In the broadcast case, there may be many zones
23158 			 * which need a copy of the packet delivered to them.
23159 			 * There is one IRE_BROADCAST per broadcast address
23160 			 * and per zone; we walk those using a helper function.
23161 			 * In addition, the sending of the packet for zoneid is
23162 			 * delayed until all of the other ires have been
23163 			 * processed.
23164 			 */
23165 			IRB_REFHOLD(ire->ire_bucket);
23166 			ire_zone = NULL;
23167 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23168 			    ire)) != NULL) {
23169 				mp1 = ip_copymsg(first_mp);
23170 				if (mp1 == NULL)
23171 					continue;
23172 
23173 				UPDATE_IB_PKT_COUNT(ire_zone);
23174 				ire_zone->ire_last_used_time = lbolt;
23175 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23176 				    mctl_present, B_FALSE, ill,
23177 				    ire_zone->ire_zoneid);
23178 			}
23179 			IRB_REFRELE(ire->ire_bucket);
23180 		}
23181 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23182 		    0, mctl_present, B_FALSE, ill, zoneid);
23183 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23184 		    "ip_wput_local_end: q %p (%S)",
23185 		    q, "icmp");
23186 		return;
23187 	}
23188 	case IPPROTO_IGMP:
23189 		if (igmp_input(q, mp, ill)) {
23190 			/* Bad packet - discarded by igmp_input */
23191 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23192 			    "ip_wput_local_end: q %p (%S)",
23193 			    q, "igmp_input--bad packet");
23194 			if (mctl_present)
23195 				freeb(first_mp);
23196 			return;
23197 		}
23198 		/*
23199 		 * igmp_input() may have pulled up the message so ipha needs to
23200 		 * be reinitialized.
23201 		 */
23202 		ipha = (ipha_t *)mp->b_rptr;
23203 		/* deliver to local raw users */
23204 		break;
23205 	case IPPROTO_ENCAP:
23206 		/*
23207 		 * This case is covered by either ip_fanout_proto, or by
23208 		 * the above security processing for self-tunneled packets.
23209 		 */
23210 		break;
23211 	case IPPROTO_UDP: {
23212 		uint16_t	*up;
23213 		uint32_t	ports;
23214 
23215 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23216 		    UDP_PORTS_OFFSET);
23217 		/* Force a 'valid' checksum. */
23218 		up[3] = 0;
23219 
23220 		ports = *(uint32_t *)up;
23221 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23222 		    (ire_type == IRE_BROADCAST),
23223 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23224 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23225 		    ill, zoneid);
23226 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23227 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23228 		return;
23229 	}
23230 	case IPPROTO_TCP: {
23231 
23232 		/*
23233 		 * For TCP, discard broadcast packets.
23234 		 */
23235 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23236 			freemsg(first_mp);
23237 			BUMP_MIB(&ip_mib, ipInDiscards);
23238 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23239 			return;
23240 		}
23241 
23242 		if (mp->b_datap->db_type == M_DATA) {
23243 			/*
23244 			 * M_DATA mblk, so init mblk (chain) for no struio().
23245 			 */
23246 			mblk_t	*mp1 = mp;
23247 
23248 			do
23249 				mp1->b_datap->db_struioflag = 0;
23250 			while ((mp1 = mp1->b_cont) != NULL);
23251 		}
23252 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23253 		    <= mp->b_wptr);
23254 		ip_fanout_tcp(q, first_mp, ill, ipha,
23255 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23256 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23257 		    mctl_present, B_FALSE, zoneid);
23258 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23259 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23260 		return;
23261 	}
23262 	case IPPROTO_SCTP:
23263 	{
23264 		uint32_t	ports;
23265 
23266 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23267 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23268 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23269 		    IP_FF_IP6INFO,
23270 		    mctl_present, B_FALSE, 0, zoneid);
23271 		return;
23272 	}
23273 
23274 	default:
23275 		break;
23276 	}
23277 	/*
23278 	 * Find a client for some other protocol.  We give
23279 	 * copies to multiple clients, if more than one is
23280 	 * bound.
23281 	 */
23282 	ip_fanout_proto(q, first_mp, ill, ipha,
23283 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23284 	    mctl_present, B_FALSE, ill, zoneid);
23285 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23286 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23287 #undef	rptr
23288 }
23289 
23290 /*
23291  * Update any source route, record route, or timestamp options.
23292  * Check that we are at end of strict source route.
23293  * The options have been sanity checked by ip_wput_options().
23294  */
23295 static void
23296 ip_wput_local_options(ipha_t *ipha)
23297 {
23298 	ipoptp_t	opts;
23299 	uchar_t		*opt;
23300 	uint8_t		optval;
23301 	uint8_t		optlen;
23302 	ipaddr_t	dst;
23303 	uint32_t	ts;
23304 	ire_t		*ire;
23305 	timestruc_t	now;
23306 
23307 	ip2dbg(("ip_wput_local_options\n"));
23308 	for (optval = ipoptp_first(&opts, ipha);
23309 	    optval != IPOPT_EOL;
23310 	    optval = ipoptp_next(&opts)) {
23311 		opt = opts.ipoptp_cur;
23312 		optlen = opts.ipoptp_len;
23313 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23314 		switch (optval) {
23315 			uint32_t off;
23316 		case IPOPT_SSRR:
23317 		case IPOPT_LSRR:
23318 			off = opt[IPOPT_OFFSET];
23319 			off--;
23320 			if (optlen < IP_ADDR_LEN ||
23321 			    off > optlen - IP_ADDR_LEN) {
23322 				/* End of source route */
23323 				break;
23324 			}
23325 			/*
23326 			 * This will only happen if two consecutive entries
23327 			 * in the source route contains our address or if
23328 			 * it is a packet with a loose source route which
23329 			 * reaches us before consuming the whole source route
23330 			 */
23331 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23332 			if (optval == IPOPT_SSRR) {
23333 				return;
23334 			}
23335 			/*
23336 			 * Hack: instead of dropping the packet truncate the
23337 			 * source route to what has been used by filling the
23338 			 * rest with IPOPT_NOP.
23339 			 */
23340 			opt[IPOPT_OLEN] = (uint8_t)off;
23341 			while (off < optlen) {
23342 				opt[off++] = IPOPT_NOP;
23343 			}
23344 			break;
23345 		case IPOPT_RR:
23346 			off = opt[IPOPT_OFFSET];
23347 			off--;
23348 			if (optlen < IP_ADDR_LEN ||
23349 			    off > optlen - IP_ADDR_LEN) {
23350 				/* No more room - ignore */
23351 				ip1dbg((
23352 				    "ip_wput_forward_options: end of RR\n"));
23353 				break;
23354 			}
23355 			dst = htonl(INADDR_LOOPBACK);
23356 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23357 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23358 			break;
23359 		case IPOPT_TS:
23360 			/* Insert timestamp if there is romm */
23361 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23362 			case IPOPT_TS_TSONLY:
23363 				off = IPOPT_TS_TIMELEN;
23364 				break;
23365 			case IPOPT_TS_PRESPEC:
23366 			case IPOPT_TS_PRESPEC_RFC791:
23367 				/* Verify that the address matched */
23368 				off = opt[IPOPT_OFFSET] - 1;
23369 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
23370 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
23371 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
23372 				if (ire == NULL) {
23373 					/* Not for us */
23374 					break;
23375 				}
23376 				ire_refrele(ire);
23377 				/* FALLTHRU */
23378 			case IPOPT_TS_TSANDADDR:
23379 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
23380 				break;
23381 			default:
23382 				/*
23383 				 * ip_*put_options should have already
23384 				 * dropped this packet.
23385 				 */
23386 				cmn_err(CE_PANIC, "ip_wput_local_options: "
23387 				    "unknown IT - bug in ip_wput_options?\n");
23388 				return;	/* Keep "lint" happy */
23389 			}
23390 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
23391 				/* Increase overflow counter */
23392 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
23393 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
23394 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
23395 				    (off << 4);
23396 				break;
23397 			}
23398 			off = opt[IPOPT_OFFSET] - 1;
23399 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23400 			case IPOPT_TS_PRESPEC:
23401 			case IPOPT_TS_PRESPEC_RFC791:
23402 			case IPOPT_TS_TSANDADDR:
23403 				dst = htonl(INADDR_LOOPBACK);
23404 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23405 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23406 				/* FALLTHRU */
23407 			case IPOPT_TS_TSONLY:
23408 				off = opt[IPOPT_OFFSET] - 1;
23409 				/* Compute # of milliseconds since midnight */
23410 				gethrestime(&now);
23411 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
23412 				    now.tv_nsec / (NANOSEC / MILLISEC);
23413 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
23414 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
23415 				break;
23416 			}
23417 			break;
23418 		}
23419 	}
23420 }
23421 
23422 /*
23423  * Send out a multicast packet on interface ipif.
23424  * The sender does not have an conn.
23425  * Caller verifies that this isn't a PHYI_LOOPBACK.
23426  */
23427 void
23428 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
23429 {
23430 	ipha_t	*ipha;
23431 	ire_t	*ire;
23432 	ipaddr_t	dst;
23433 	mblk_t		*first_mp;
23434 
23435 	/* igmp_sendpkt always allocates a ipsec_out_t */
23436 	ASSERT(mp->b_datap->db_type == M_CTL);
23437 	ASSERT(!ipif->ipif_isv6);
23438 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
23439 
23440 	first_mp = mp;
23441 	mp = first_mp->b_cont;
23442 	ASSERT(mp->b_datap->db_type == M_DATA);
23443 	ipha = (ipha_t *)mp->b_rptr;
23444 
23445 	/*
23446 	 * Find an IRE which matches the destination and the outgoing
23447 	 * queue (i.e. the outgoing interface.)
23448 	 */
23449 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
23450 		dst = ipif->ipif_pp_dst_addr;
23451 	else
23452 		dst = ipha->ipha_dst;
23453 	/*
23454 	 * The source address has already been initialized by the
23455 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
23456 	 * be sufficient rather than MATCH_IRE_IPIF.
23457 	 *
23458 	 * This function is used for sending IGMP packets. We need
23459 	 * to make sure that we send the packet out of the interface
23460 	 * (ipif->ipif_ill) where we joined the group. This is to
23461 	 * prevent from switches doing IGMP snooping to send us multicast
23462 	 * packets for a given group on the interface we have joined.
23463 	 * If we can't find an ire, igmp_sendpkt has already initialized
23464 	 * ipsec_out_attach_if so that this will not be load spread in
23465 	 * ip_newroute_ipif.
23466 	 */
23467 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
23468 	    MATCH_IRE_ILL);
23469 	if (!ire) {
23470 		/*
23471 		 * Mark this packet to make it be delivered to
23472 		 * ip_wput_ire after the new ire has been
23473 		 * created.
23474 		 */
23475 		mp->b_prev = NULL;
23476 		mp->b_next = NULL;
23477 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
23478 		return;
23479 	}
23480 
23481 	/*
23482 	 * Honor the RTF_SETSRC flag; this is the only case
23483 	 * where we force this addr whatever the current src addr is,
23484 	 * because this address is set by igmp_sendpkt(), and
23485 	 * cannot be specified by any user.
23486 	 */
23487 	if (ire->ire_flags & RTF_SETSRC) {
23488 		ipha->ipha_src = ire->ire_src_addr;
23489 	}
23490 
23491 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
23492 }
23493 
23494 /*
23495  * NOTE : This function does not ire_refrele the ire argument passed in.
23496  *
23497  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
23498  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
23499  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
23500  * the ire_lock to access the ire_fp_mp in this case.
23501  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
23502  * prepending a fastpath message IPQoS processing must precede it, we also set
23503  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
23504  * (IPQoS might have set the b_band for CoS marking).
23505  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
23506  * must follow it so that IPQoS can mark the dl_priority field for CoS
23507  * marking, if needed.
23508  */
23509 static mblk_t *
23510 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
23511 {
23512 	uint_t	hlen;
23513 	ipha_t *ipha;
23514 	mblk_t *mp1;
23515 	boolean_t qos_done = B_FALSE;
23516 	uchar_t	*ll_hdr;
23517 
23518 #define	rptr	((uchar_t *)ipha)
23519 
23520 	ipha = (ipha_t *)mp->b_rptr;
23521 	hlen = 0;
23522 	LOCK_IRE_FP_MP(ire);
23523 	if ((mp1 = ire->ire_fp_mp) != NULL) {
23524 		ASSERT(DB_TYPE(mp1) == M_DATA);
23525 		/* Initiate IPPF processing */
23526 		if ((proc != 0) && IPP_ENABLED(proc)) {
23527 			UNLOCK_IRE_FP_MP(ire);
23528 			ip_process(proc, &mp, ill_index);
23529 			if (mp == NULL)
23530 				return (NULL);
23531 
23532 			ipha = (ipha_t *)mp->b_rptr;
23533 			LOCK_IRE_FP_MP(ire);
23534 			if ((mp1 = ire->ire_fp_mp) == NULL) {
23535 				qos_done = B_TRUE;
23536 				goto no_fp_mp;
23537 			}
23538 			ASSERT(DB_TYPE(mp1) == M_DATA);
23539 		}
23540 		hlen = MBLKL(mp1);
23541 		/*
23542 		 * Check if we have enough room to prepend fastpath
23543 		 * header
23544 		 */
23545 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
23546 			ll_hdr = rptr - hlen;
23547 			bcopy(mp1->b_rptr, ll_hdr, hlen);
23548 			/* XXX ipha is not aligned here */
23549 			ipha = (ipha_t *)(rptr - hlen);
23550 			/*
23551 			 * Set the b_rptr to the start of the link layer
23552 			 * header
23553 			 */
23554 			mp->b_rptr = rptr;
23555 			mp1 = mp;
23556 		} else {
23557 			mp1 = copyb(mp1);
23558 			if (mp1 == NULL)
23559 				goto unlock_err;
23560 			mp1->b_band = mp->b_band;
23561 			mp1->b_cont = mp;
23562 			/*
23563 			 * certain system generated traffic may not
23564 			 * have cred/label in ip header block. This
23565 			 * is true even for a labeled system. But for
23566 			 * labeled traffic, inherit the label in the
23567 			 * new header.
23568 			 */
23569 			if (DB_CRED(mp) != NULL)
23570 				mblk_setcred(mp1, DB_CRED(mp));
23571 			/*
23572 			 * XXX disable ICK_VALID and compute checksum
23573 			 * here; can happen if ire_fp_mp changes and
23574 			 * it can't be copied now due to insufficient
23575 			 * space. (unlikely, fp mp can change, but it
23576 			 * does not increase in length)
23577 			 */
23578 		}
23579 		UNLOCK_IRE_FP_MP(ire);
23580 	} else {
23581 no_fp_mp:
23582 		mp1 = copyb(ire->ire_dlureq_mp);
23583 		if (mp1 == NULL) {
23584 unlock_err:
23585 			UNLOCK_IRE_FP_MP(ire);
23586 			freemsg(mp);
23587 			return (NULL);
23588 		}
23589 		UNLOCK_IRE_FP_MP(ire);
23590 		mp1->b_cont = mp;
23591 		/*
23592 		 * certain system generated traffic may not
23593 		 * have cred/label in ip header block. This
23594 		 * is true even for a labeled system. But for
23595 		 * labeled traffic, inherit the label in the
23596 		 * new header.
23597 		 */
23598 		if (DB_CRED(mp) != NULL)
23599 			mblk_setcred(mp1, DB_CRED(mp));
23600 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
23601 			ip_process(proc, &mp1, ill_index);
23602 			if (mp1 == NULL)
23603 				return (NULL);
23604 		}
23605 	}
23606 	return (mp1);
23607 #undef rptr
23608 }
23609 
23610 /*
23611  * Finish the outbound IPsec processing for an IPv6 packet. This function
23612  * is called from ipsec_out_process() if the IPsec packet was processed
23613  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23614  * asynchronously.
23615  */
23616 void
23617 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
23618     ire_t *ire_arg)
23619 {
23620 	in6_addr_t *v6dstp;
23621 	ire_t *ire;
23622 	mblk_t *mp;
23623 	uint_t	ill_index;
23624 	ipsec_out_t *io;
23625 	boolean_t attach_if, hwaccel;
23626 	uint32_t flags = IP6_NO_IPPOLICY;
23627 	int match_flags;
23628 	zoneid_t zoneid;
23629 	boolean_t ill_need_rele = B_FALSE;
23630 	boolean_t ire_need_rele = B_FALSE;
23631 
23632 	mp = ipsec_mp->b_cont;
23633 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23634 	ill_index = io->ipsec_out_ill_index;
23635 	if (io->ipsec_out_reachable) {
23636 		flags |= IPV6_REACHABILITY_CONFIRMATION;
23637 	}
23638 	attach_if = io->ipsec_out_attach_if;
23639 	hwaccel = io->ipsec_out_accelerated;
23640 	zoneid = io->ipsec_out_zoneid;
23641 	ASSERT(zoneid != ALL_ZONES);
23642 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23643 	/* Multicast addresses should have non-zero ill_index. */
23644 	v6dstp = &ip6h->ip6_dst;
23645 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
23646 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
23647 	ASSERT(!attach_if || ill_index != 0);
23648 	if (ill_index != 0) {
23649 		if (ill == NULL) {
23650 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
23651 			    B_TRUE);
23652 
23653 			/* Failure case frees things for us. */
23654 			if (ill == NULL)
23655 				return;
23656 
23657 			ill_need_rele = B_TRUE;
23658 		}
23659 		/*
23660 		 * If this packet needs to go out on a particular interface
23661 		 * honor it.
23662 		 */
23663 		if (attach_if) {
23664 			match_flags = MATCH_IRE_ILL;
23665 
23666 			/*
23667 			 * Check if we need an ire that will not be
23668 			 * looked up by anybody else i.e. HIDDEN.
23669 			 */
23670 			if (ill_is_probeonly(ill)) {
23671 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23672 			}
23673 		}
23674 	}
23675 	ASSERT(mp != NULL);
23676 
23677 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
23678 		boolean_t unspec_src;
23679 		ipif_t	*ipif;
23680 
23681 		/*
23682 		 * Use the ill_index to get the right ill.
23683 		 */
23684 		unspec_src = io->ipsec_out_unspec_src;
23685 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23686 		if (ipif == NULL) {
23687 			if (ill_need_rele)
23688 				ill_refrele(ill);
23689 			freemsg(ipsec_mp);
23690 			return;
23691 		}
23692 
23693 		if (ire_arg != NULL) {
23694 			ire = ire_arg;
23695 		} else {
23696 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23697 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23698 			ire_need_rele = B_TRUE;
23699 		}
23700 		if (ire != NULL) {
23701 			ipif_refrele(ipif);
23702 			/*
23703 			 * XXX Do the multicast forwarding now, as the IPSEC
23704 			 * processing has been done.
23705 			 */
23706 			goto send;
23707 		}
23708 
23709 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
23710 		mp->b_prev = NULL;
23711 		mp->b_next = NULL;
23712 
23713 		/*
23714 		 * If the IPsec packet was processed asynchronously,
23715 		 * drop it now.
23716 		 */
23717 		if (q == NULL) {
23718 			if (ill_need_rele)
23719 				ill_refrele(ill);
23720 			freemsg(ipsec_mp);
23721 			return;
23722 		}
23723 
23724 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
23725 		    unspec_src, zoneid);
23726 		ipif_refrele(ipif);
23727 	} else {
23728 		if (attach_if) {
23729 			ipif_t	*ipif;
23730 
23731 			ipif = ipif_get_next_ipif(NULL, ill);
23732 			if (ipif == NULL) {
23733 				if (ill_need_rele)
23734 					ill_refrele(ill);
23735 				freemsg(ipsec_mp);
23736 				return;
23737 			}
23738 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23739 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23740 			ire_need_rele = B_TRUE;
23741 			ipif_refrele(ipif);
23742 		} else {
23743 			if (ire_arg != NULL) {
23744 				ire = ire_arg;
23745 			} else {
23746 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
23747 				ire_need_rele = B_TRUE;
23748 			}
23749 		}
23750 		if (ire != NULL)
23751 			goto send;
23752 		/*
23753 		 * ire disappeared underneath.
23754 		 *
23755 		 * What we need to do here is the ip_newroute
23756 		 * logic to get the ire without doing the IPSEC
23757 		 * processing. Follow the same old path. But this
23758 		 * time, ip_wput or ire_add_then_send will call us
23759 		 * directly as all the IPSEC operations are done.
23760 		 */
23761 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
23762 		mp->b_prev = NULL;
23763 		mp->b_next = NULL;
23764 
23765 		/*
23766 		 * If the IPsec packet was processed asynchronously,
23767 		 * drop it now.
23768 		 */
23769 		if (q == NULL) {
23770 			if (ill_need_rele)
23771 				ill_refrele(ill);
23772 			freemsg(ipsec_mp);
23773 			return;
23774 		}
23775 
23776 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
23777 		    zoneid);
23778 	}
23779 	if (ill != NULL && ill_need_rele)
23780 		ill_refrele(ill);
23781 	return;
23782 send:
23783 	if (ill != NULL && ill_need_rele)
23784 		ill_refrele(ill);
23785 
23786 	/* Local delivery */
23787 	if (ire->ire_stq == NULL) {
23788 		ASSERT(q != NULL);
23789 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
23790 		    ire, 0);
23791 		if (ire_need_rele)
23792 			ire_refrele(ire);
23793 		return;
23794 	}
23795 	/*
23796 	 * Everything is done. Send it out on the wire.
23797 	 * We force the insertion of a fragment header using the
23798 	 * IPH_FRAG_HDR flag in two cases:
23799 	 * - after reception of an ICMPv6 "packet too big" message
23800 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
23801 	 * - for multirouted IPv6 packets, so that the receiver can
23802 	 *   discard duplicates according to their fragment identifier
23803 	 */
23804 	/* XXX fix flow control problems. */
23805 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
23806 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
23807 		if (hwaccel) {
23808 			/*
23809 			 * hardware acceleration does not handle these
23810 			 * "slow path" cases.
23811 			 */
23812 			/* IPsec KSTATS: should bump bean counter here. */
23813 			if (ire_need_rele)
23814 				ire_refrele(ire);
23815 			freemsg(ipsec_mp);
23816 			return;
23817 		}
23818 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
23819 		    (mp->b_cont ? msgdsize(mp) :
23820 		    mp->b_wptr - (uchar_t *)ip6h)) {
23821 			/* IPsec KSTATS: should bump bean counter here. */
23822 			ip0dbg(("Packet length mismatch: %d, %ld\n",
23823 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
23824 			    msgdsize(mp)));
23825 			if (ire_need_rele)
23826 				ire_refrele(ire);
23827 			freemsg(ipsec_mp);
23828 			return;
23829 		}
23830 		ASSERT(mp->b_prev == NULL);
23831 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
23832 		    ntohs(ip6h->ip6_plen) +
23833 		    IPV6_HDR_LEN, ire->ire_max_frag));
23834 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
23835 		    ire->ire_max_frag);
23836 	} else {
23837 		UPDATE_OB_PKT_COUNT(ire);
23838 		ire->ire_last_used_time = lbolt;
23839 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
23840 	}
23841 	if (ire_need_rele)
23842 		ire_refrele(ire);
23843 	freeb(ipsec_mp);
23844 }
23845 
23846 void
23847 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23848 {
23849 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23850 	da_ipsec_t *hada;	/* data attributes */
23851 	ill_t *ill = (ill_t *)q->q_ptr;
23852 
23853 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23854 
23855 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23856 		/* IPsec KSTATS: Bump lose counter here! */
23857 		freemsg(mp);
23858 		return;
23859 	}
23860 
23861 	/*
23862 	 * It's an IPsec packet that must be
23863 	 * accelerated by the Provider, and the
23864 	 * outbound ill is IPsec acceleration capable.
23865 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23866 	 * to the ill.
23867 	 * IPsec KSTATS: should bump packet counter here.
23868 	 */
23869 
23870 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23871 	if (hada_mp == NULL) {
23872 		/* IPsec KSTATS: should bump packet counter here. */
23873 		freemsg(mp);
23874 		return;
23875 	}
23876 
23877 	hada_mp->b_datap->db_type = M_CTL;
23878 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23879 	hada_mp->b_cont = mp;
23880 
23881 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23882 	bzero(hada, sizeof (da_ipsec_t));
23883 	hada->da_type = IPHADA_M_CTL;
23884 
23885 	putnext(q, hada_mp);
23886 }
23887 
23888 /*
23889  * Finish the outbound IPsec processing. This function is called from
23890  * ipsec_out_process() if the IPsec packet was processed
23891  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23892  * asynchronously.
23893  */
23894 void
23895 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23896     ire_t *ire_arg)
23897 {
23898 	uint32_t v_hlen_tos_len;
23899 	ipaddr_t	dst;
23900 	ipif_t	*ipif = NULL;
23901 	ire_t *ire;
23902 	ire_t *ire1 = NULL;
23903 	mblk_t *next_mp = NULL;
23904 	uint32_t max_frag;
23905 	boolean_t multirt_send = B_FALSE;
23906 	mblk_t *mp;
23907 	mblk_t *mp1;
23908 	uint_t	ill_index;
23909 	ipsec_out_t *io;
23910 	boolean_t attach_if;
23911 	int match_flags, offset;
23912 	irb_t *irb = NULL;
23913 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23914 	zoneid_t zoneid;
23915 	uint32_t cksum;
23916 	uint16_t *up;
23917 #ifdef	_BIG_ENDIAN
23918 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23919 #else
23920 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23921 #endif
23922 
23923 	mp = ipsec_mp->b_cont;
23924 	ASSERT(mp != NULL);
23925 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23926 	dst = ipha->ipha_dst;
23927 
23928 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23929 	ill_index = io->ipsec_out_ill_index;
23930 	attach_if = io->ipsec_out_attach_if;
23931 	zoneid = io->ipsec_out_zoneid;
23932 	ASSERT(zoneid != ALL_ZONES);
23933 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23934 	if (ill_index != 0) {
23935 		if (ill == NULL) {
23936 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23937 			    ill_index, B_FALSE);
23938 
23939 			/* Failure case frees things for us. */
23940 			if (ill == NULL)
23941 				return;
23942 
23943 			ill_need_rele = B_TRUE;
23944 		}
23945 		/*
23946 		 * If this packet needs to go out on a particular interface
23947 		 * honor it.
23948 		 */
23949 		if (attach_if) {
23950 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
23951 
23952 			/*
23953 			 * Check if we need an ire that will not be
23954 			 * looked up by anybody else i.e. HIDDEN.
23955 			 */
23956 			if (ill_is_probeonly(ill)) {
23957 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23958 			}
23959 		}
23960 	}
23961 
23962 	if (CLASSD(dst)) {
23963 		boolean_t conn_dontroute;
23964 		/*
23965 		 * Use the ill_index to get the right ipif.
23966 		 */
23967 		conn_dontroute = io->ipsec_out_dontroute;
23968 		if (ill_index == 0)
23969 			ipif = ipif_lookup_group(dst, zoneid);
23970 		else
23971 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23972 		if (ipif == NULL) {
23973 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23974 			    " multicast\n"));
23975 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23976 			freemsg(ipsec_mp);
23977 			goto done;
23978 		}
23979 		/*
23980 		 * ipha_src has already been intialized with the
23981 		 * value of the ipif in ip_wput. All we need now is
23982 		 * an ire to send this downstream.
23983 		 */
23984 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
23985 		    MBLK_GETLABEL(mp), match_flags);
23986 		if (ire != NULL) {
23987 			ill_t *ill1;
23988 			/*
23989 			 * Do the multicast forwarding now, as the IPSEC
23990 			 * processing has been done.
23991 			 */
23992 			if (ip_g_mrouter && !conn_dontroute &&
23993 			    (ill1 = ire_to_ill(ire))) {
23994 				if (ip_mforward(ill1, ipha, mp)) {
23995 					freemsg(ipsec_mp);
23996 					ip1dbg(("ip_wput_ipsec_out: mforward "
23997 					    "failed\n"));
23998 					ire_refrele(ire);
23999 					goto done;
24000 				}
24001 			}
24002 			goto send;
24003 		}
24004 
24005 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24006 		mp->b_prev = NULL;
24007 		mp->b_next = NULL;
24008 
24009 		/*
24010 		 * If the IPsec packet was processed asynchronously,
24011 		 * drop it now.
24012 		 */
24013 		if (q == NULL) {
24014 			freemsg(ipsec_mp);
24015 			goto done;
24016 		}
24017 
24018 		/*
24019 		 * We may be using a wrong ipif to create the ire.
24020 		 * But it is okay as the source address is assigned
24021 		 * for the packet already. Next outbound packet would
24022 		 * create the IRE with the right IPIF in ip_wput.
24023 		 *
24024 		 * Also handle RTF_MULTIRT routes.
24025 		 */
24026 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24027 	} else {
24028 		if (attach_if) {
24029 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24030 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24031 		} else {
24032 			if (ire_arg != NULL) {
24033 				ire = ire_arg;
24034 				ire_need_rele = B_FALSE;
24035 			} else {
24036 				ire = ire_cache_lookup(dst, zoneid,
24037 				    MBLK_GETLABEL(mp));
24038 			}
24039 		}
24040 		if (ire != NULL) {
24041 			goto send;
24042 		}
24043 
24044 		/*
24045 		 * ire disappeared underneath.
24046 		 *
24047 		 * What we need to do here is the ip_newroute
24048 		 * logic to get the ire without doing the IPSEC
24049 		 * processing. Follow the same old path. But this
24050 		 * time, ip_wput or ire_add_then_put will call us
24051 		 * directly as all the IPSEC operations are done.
24052 		 */
24053 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24054 		mp->b_prev = NULL;
24055 		mp->b_next = NULL;
24056 
24057 		/*
24058 		 * If the IPsec packet was processed asynchronously,
24059 		 * drop it now.
24060 		 */
24061 		if (q == NULL) {
24062 			freemsg(ipsec_mp);
24063 			goto done;
24064 		}
24065 
24066 		/*
24067 		 * Since we're going through ip_newroute() again, we
24068 		 * need to make sure we don't:
24069 		 *
24070 		 *	1.) Trigger the ASSERT() with the ipha_ident
24071 		 *	    overloading.
24072 		 *	2.) Redo transport-layer checksumming, since we've
24073 		 *	    already done all that to get this far.
24074 		 *
24075 		 * The easiest way not do either of the above is to set
24076 		 * the ipha_ident field to IP_HDR_INCLUDED.
24077 		 */
24078 		ipha->ipha_ident = IP_HDR_INCLUDED;
24079 		ip_newroute(q, ipsec_mp, dst, NULL,
24080 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24081 	}
24082 	goto done;
24083 send:
24084 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24085 		/*
24086 		 * ESP NAT-Traversal packet.
24087 		 *
24088 		 * Just do software checksum for now.
24089 		 */
24090 
24091 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24092 		IP_STAT(ip_out_sw_cksum);
24093 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24094 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24095 #define	iphs	((uint16_t *)ipha)
24096 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24097 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24098 		    IP_SIMPLE_HDR_LENGTH);
24099 #undef iphs
24100 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24101 			cksum = 0xFFFF;
24102 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24103 			if (mp1->b_wptr - mp1->b_rptr >=
24104 			    offset + sizeof (uint16_t)) {
24105 				up = (uint16_t *)(mp1->b_rptr + offset);
24106 				*up = cksum;
24107 				break;	/* out of for loop */
24108 			} else {
24109 				offset -= (mp->b_wptr - mp->b_rptr);
24110 			}
24111 	} /* Otherwise, just keep the all-zero checksum. */
24112 
24113 	if (ire->ire_stq == NULL) {
24114 		/*
24115 		 * Loopbacks go through ip_wput_local except for one case.
24116 		 * We come here if we generate a icmp_frag_needed message
24117 		 * after IPSEC processing is over. When this function calls
24118 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24119 		 * icmp_frag_needed. The message generated comes back here
24120 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24121 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24122 		 * source address as it is usually set in ip_wput_ire. As
24123 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24124 		 * and we end up here. We can't enter ip_wput_ire once the
24125 		 * IPSEC processing is over and hence we need to do it here.
24126 		 */
24127 		ASSERT(q != NULL);
24128 		UPDATE_OB_PKT_COUNT(ire);
24129 		ire->ire_last_used_time = lbolt;
24130 		if (ipha->ipha_src == 0)
24131 			ipha->ipha_src = ire->ire_src_addr;
24132 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24133 		    ire, 0, zoneid);
24134 		if (ire_need_rele)
24135 			ire_refrele(ire);
24136 		goto done;
24137 	}
24138 
24139 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24140 		/*
24141 		 * We are through with IPSEC processing.
24142 		 * Fragment this and send it on the wire.
24143 		 */
24144 		if (io->ipsec_out_accelerated) {
24145 			/*
24146 			 * The packet has been accelerated but must
24147 			 * be fragmented. This should not happen
24148 			 * since AH and ESP must not accelerate
24149 			 * packets that need fragmentation, however
24150 			 * the configuration could have changed
24151 			 * since the AH or ESP processing.
24152 			 * Drop packet.
24153 			 * IPsec KSTATS: bump bean counter here.
24154 			 */
24155 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24156 			    "fragmented accelerated packet!\n"));
24157 			freemsg(ipsec_mp);
24158 		} else {
24159 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24160 		}
24161 		if (ire_need_rele)
24162 			ire_refrele(ire);
24163 		goto done;
24164 	}
24165 
24166 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24167 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24168 	    (void *)ire->ire_ipif, (void *)ipif));
24169 
24170 	/*
24171 	 * Multiroute the secured packet, unless IPsec really
24172 	 * requires the packet to go out only through a particular
24173 	 * interface.
24174 	 */
24175 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24176 		ire_t *first_ire;
24177 		irb = ire->ire_bucket;
24178 		ASSERT(irb != NULL);
24179 		/*
24180 		 * This ire has been looked up as the one that
24181 		 * goes through the given ipif;
24182 		 * make sure we do not omit any other multiroute ire
24183 		 * that may be present in the bucket before this one.
24184 		 */
24185 		IRB_REFHOLD(irb);
24186 		for (first_ire = irb->irb_ire;
24187 		    first_ire != NULL;
24188 		    first_ire = first_ire->ire_next) {
24189 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24190 			    (first_ire->ire_addr == ire->ire_addr) &&
24191 			    !(first_ire->ire_marks &
24192 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24193 				break;
24194 		}
24195 
24196 		if ((first_ire != NULL) && (first_ire != ire)) {
24197 			/*
24198 			 * Don't change the ire if the packet must
24199 			 * be fragmented if sent via this new one.
24200 			 */
24201 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24202 				IRE_REFHOLD(first_ire);
24203 				if (ire_need_rele)
24204 					ire_refrele(ire);
24205 				else
24206 					ire_need_rele = B_TRUE;
24207 				ire = first_ire;
24208 			}
24209 		}
24210 		IRB_REFRELE(irb);
24211 
24212 		multirt_send = B_TRUE;
24213 		max_frag = ire->ire_max_frag;
24214 	} else {
24215 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24216 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24217 			    "flag, attach_if %d\n", attach_if));
24218 		}
24219 	}
24220 
24221 	/*
24222 	 * In most cases, the emission loop below is entered only once.
24223 	 * Only in the case where the ire holds the RTF_MULTIRT
24224 	 * flag, we loop to process all RTF_MULTIRT ires in the
24225 	 * bucket, and send the packet through all crossed
24226 	 * RTF_MULTIRT routes.
24227 	 */
24228 	do {
24229 		if (multirt_send) {
24230 			/*
24231 			 * ire1 holds here the next ire to process in the
24232 			 * bucket. If multirouting is expected,
24233 			 * any non-RTF_MULTIRT ire that has the
24234 			 * right destination address is ignored.
24235 			 */
24236 			ASSERT(irb != NULL);
24237 			IRB_REFHOLD(irb);
24238 			for (ire1 = ire->ire_next;
24239 			    ire1 != NULL;
24240 			    ire1 = ire1->ire_next) {
24241 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24242 					continue;
24243 				if (ire1->ire_addr != ire->ire_addr)
24244 					continue;
24245 				if (ire1->ire_marks &
24246 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24247 					continue;
24248 				/* No loopback here */
24249 				if (ire1->ire_stq == NULL)
24250 					continue;
24251 				/*
24252 				 * Ensure we do not exceed the MTU
24253 				 * of the next route.
24254 				 */
24255 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24256 					ip_multirt_bad_mtu(ire1, max_frag);
24257 					continue;
24258 				}
24259 
24260 				IRE_REFHOLD(ire1);
24261 				break;
24262 			}
24263 			IRB_REFRELE(irb);
24264 			if (ire1 != NULL) {
24265 				/*
24266 				 * We are in a multiple send case, need to
24267 				 * make a copy of the packet.
24268 				 */
24269 				next_mp = copymsg(ipsec_mp);
24270 				if (next_mp == NULL) {
24271 					ire_refrele(ire1);
24272 					ire1 = NULL;
24273 				}
24274 			}
24275 		}
24276 
24277 		/* Everything is done. Send it out on the wire */
24278 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
24279 		if (mp1 == NULL) {
24280 			BUMP_MIB(&ip_mib, ipOutDiscards);
24281 			freemsg(ipsec_mp);
24282 			if (ire_need_rele)
24283 				ire_refrele(ire);
24284 			if (ire1 != NULL) {
24285 				ire_refrele(ire1);
24286 				freemsg(next_mp);
24287 			}
24288 			goto done;
24289 		}
24290 		UPDATE_OB_PKT_COUNT(ire);
24291 		ire->ire_last_used_time = lbolt;
24292 		if (!io->ipsec_out_accelerated) {
24293 			putnext(ire->ire_stq, mp1);
24294 		} else {
24295 			/*
24296 			 * Safety Pup says: make sure this is going to
24297 			 * the right interface!
24298 			 */
24299 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
24300 			int ifindex = ill1->ill_phyint->phyint_ifindex;
24301 
24302 			if (ifindex != io->ipsec_out_capab_ill_index) {
24303 				/* IPsec kstats: bump lose counter */
24304 				freemsg(mp1);
24305 			} else {
24306 				ipsec_hw_putnext(ire->ire_stq, mp1);
24307 			}
24308 		}
24309 
24310 		freeb(ipsec_mp);
24311 		if (ire_need_rele)
24312 			ire_refrele(ire);
24313 
24314 		if (ire1 != NULL) {
24315 			ire = ire1;
24316 			ire_need_rele = B_TRUE;
24317 			ASSERT(next_mp);
24318 			ipsec_mp = next_mp;
24319 			mp = ipsec_mp->b_cont;
24320 			ire1 = NULL;
24321 			next_mp = NULL;
24322 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
24323 		} else {
24324 			multirt_send = B_FALSE;
24325 		}
24326 	} while (multirt_send);
24327 done:
24328 	if (ill != NULL && ill_need_rele)
24329 		ill_refrele(ill);
24330 	if (ipif != NULL)
24331 		ipif_refrele(ipif);
24332 }
24333 
24334 /*
24335  * Get the ill corresponding to the specified ire, and compare its
24336  * capabilities with the protocol and algorithms specified by the
24337  * the SA obtained from ipsec_out. If they match, annotate the
24338  * ipsec_out structure to indicate that the packet needs acceleration.
24339  *
24340  *
24341  * A packet is eligible for outbound hardware acceleration if the
24342  * following conditions are satisfied:
24343  *
24344  * 1. the packet will not be fragmented
24345  * 2. the provider supports the algorithm
24346  * 3. there is no pending control message being exchanged
24347  * 4. snoop is not attached
24348  * 5. the destination address is not a broadcast or multicast address.
24349  *
24350  * Rationale:
24351  *	- Hardware drivers do not support fragmentation with
24352  *	  the current interface.
24353  *	- snoop, multicast, and broadcast may result in exposure of
24354  *	  a cleartext datagram.
24355  * We check all five of these conditions here.
24356  *
24357  * XXX would like to nuke "ire_t *" parameter here; problem is that
24358  * IRE is only way to figure out if a v4 address is a broadcast and
24359  * thus ineligible for acceleration...
24360  */
24361 static void
24362 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
24363 {
24364 	ipsec_out_t *io;
24365 	mblk_t *data_mp;
24366 	uint_t plen, overhead;
24367 
24368 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
24369 		return;
24370 
24371 	if (ill == NULL)
24372 		return;
24373 
24374 	/*
24375 	 * Destination address is a broadcast or multicast.  Punt.
24376 	 */
24377 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
24378 	    IRE_LOCAL)))
24379 		return;
24380 
24381 	data_mp = ipsec_mp->b_cont;
24382 
24383 	if (ill->ill_isv6) {
24384 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
24385 
24386 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
24387 			return;
24388 
24389 		plen = ip6h->ip6_plen;
24390 	} else {
24391 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
24392 
24393 		if (CLASSD(ipha->ipha_dst))
24394 			return;
24395 
24396 		plen = ipha->ipha_length;
24397 	}
24398 	/*
24399 	 * Is there a pending DLPI control message being exchanged
24400 	 * between IP/IPsec and the DLS Provider? If there is, it
24401 	 * could be a SADB update, and the state of the DLS Provider
24402 	 * SADB might not be in sync with the SADB maintained by
24403 	 * IPsec. To avoid dropping packets or using the wrong keying
24404 	 * material, we do not accelerate this packet.
24405 	 */
24406 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
24407 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24408 		    "ill_dlpi_pending! don't accelerate packet\n"));
24409 		return;
24410 	}
24411 
24412 	/*
24413 	 * Is the Provider in promiscous mode? If it does, we don't
24414 	 * accelerate the packet since it will bounce back up to the
24415 	 * listeners in the clear.
24416 	 */
24417 	if (ill->ill_promisc_on_phys) {
24418 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24419 		    "ill in promiscous mode, don't accelerate packet\n"));
24420 		return;
24421 	}
24422 
24423 	/*
24424 	 * Will the packet require fragmentation?
24425 	 */
24426 
24427 	/*
24428 	 * IPsec ESP note: this is a pessimistic estimate, but the same
24429 	 * as is used elsewhere.
24430 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
24431 	 *	+ 2-byte trailer
24432 	 */
24433 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
24434 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
24435 
24436 	if ((plen + overhead) > ill->ill_max_mtu)
24437 		return;
24438 
24439 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24440 
24441 	/*
24442 	 * Can the ill accelerate this IPsec protocol and algorithm
24443 	 * specified by the SA?
24444 	 */
24445 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
24446 	    ill->ill_isv6, sa)) {
24447 		return;
24448 	}
24449 
24450 	/*
24451 	 * Tell AH or ESP that the outbound ill is capable of
24452 	 * accelerating this packet.
24453 	 */
24454 	io->ipsec_out_is_capab_ill = B_TRUE;
24455 }
24456 
24457 /*
24458  * Select which AH & ESP SA's to use (if any) for the outbound packet.
24459  *
24460  * If this function returns B_TRUE, the requested SA's have been filled
24461  * into the ipsec_out_*_sa pointers.
24462  *
24463  * If the function returns B_FALSE, the packet has been "consumed", most
24464  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
24465  *
24466  * The SA references created by the protocol-specific "select"
24467  * function will be released when the ipsec_mp is freed, thanks to the
24468  * ipsec_out_free destructor -- see spd.c.
24469  */
24470 static boolean_t
24471 ipsec_out_select_sa(mblk_t *ipsec_mp)
24472 {
24473 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
24474 	ipsec_out_t *io;
24475 	ipsec_policy_t *pp;
24476 	ipsec_action_t *ap;
24477 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24478 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24479 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24480 
24481 	if (!io->ipsec_out_secure) {
24482 		/*
24483 		 * We came here by mistake.
24484 		 * Don't bother with ipsec processing
24485 		 * We should "discourage" this path in the future.
24486 		 */
24487 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24488 		return (B_FALSE);
24489 	}
24490 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24491 	ASSERT((io->ipsec_out_policy != NULL) ||
24492 	    (io->ipsec_out_act != NULL));
24493 
24494 	ASSERT(io->ipsec_out_failed == B_FALSE);
24495 
24496 	/*
24497 	 * IPSEC processing has started.
24498 	 */
24499 	io->ipsec_out_proc_begin = B_TRUE;
24500 	ap = io->ipsec_out_act;
24501 	if (ap == NULL) {
24502 		pp = io->ipsec_out_policy;
24503 		ASSERT(pp != NULL);
24504 		ap = pp->ipsp_act;
24505 		ASSERT(ap != NULL);
24506 	}
24507 
24508 	/*
24509 	 * We have an action.  now, let's select SA's.
24510 	 * (In the future, we can cache this in the conn_t..)
24511 	 */
24512 	if (ap->ipa_want_esp) {
24513 		if (io->ipsec_out_esp_sa == NULL) {
24514 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
24515 			    IPPROTO_ESP);
24516 		}
24517 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
24518 	}
24519 
24520 	if (ap->ipa_want_ah) {
24521 		if (io->ipsec_out_ah_sa == NULL) {
24522 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
24523 			    IPPROTO_AH);
24524 		}
24525 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
24526 		/*
24527 		 * The ESP and AH processing order needs to be preserved
24528 		 * when both protocols are required (ESP should be applied
24529 		 * before AH for an outbound packet). Force an ESP ACQUIRE
24530 		 * when both ESP and AH are required, and an AH ACQUIRE
24531 		 * is needed.
24532 		 */
24533 		if (ap->ipa_want_esp && need_ah_acquire)
24534 			need_esp_acquire = B_TRUE;
24535 	}
24536 
24537 	/*
24538 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
24539 	 * Release SAs that got referenced, but will not be used until we
24540 	 * acquire _all_ of the SAs we need.
24541 	 */
24542 	if (need_ah_acquire || need_esp_acquire) {
24543 		if (io->ipsec_out_ah_sa != NULL) {
24544 			IPSA_REFRELE(io->ipsec_out_ah_sa);
24545 			io->ipsec_out_ah_sa = NULL;
24546 		}
24547 		if (io->ipsec_out_esp_sa != NULL) {
24548 			IPSA_REFRELE(io->ipsec_out_esp_sa);
24549 			io->ipsec_out_esp_sa = NULL;
24550 		}
24551 
24552 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
24553 		return (B_FALSE);
24554 	}
24555 
24556 	return (B_TRUE);
24557 }
24558 
24559 /*
24560  * Process an IPSEC_OUT message and see what you can
24561  * do with it.
24562  * IPQoS Notes:
24563  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
24564  * IPSec.
24565  * XXX would like to nuke ire_t.
24566  * XXX ill_index better be "real"
24567  */
24568 void
24569 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
24570 {
24571 	ipsec_out_t *io;
24572 	ipsec_policy_t *pp;
24573 	ipsec_action_t *ap;
24574 	ipha_t *ipha;
24575 	ip6_t *ip6h;
24576 	mblk_t *mp;
24577 	ill_t *ill;
24578 	zoneid_t zoneid;
24579 	ipsec_status_t ipsec_rc;
24580 	boolean_t ill_need_rele = B_FALSE;
24581 
24582 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24583 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24584 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24585 	mp = ipsec_mp->b_cont;
24586 
24587 	/*
24588 	 * Initiate IPPF processing. We do it here to account for packets
24589 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
24590 	 * We can check for ipsec_out_proc_begin even for such packets, as
24591 	 * they will always be false (asserted below).
24592 	 */
24593 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
24594 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
24595 		    io->ipsec_out_ill_index : ill_index);
24596 		if (mp == NULL) {
24597 			ip2dbg(("ipsec_out_process: packet dropped "\
24598 			    "during IPPF processing\n"));
24599 			freeb(ipsec_mp);
24600 			BUMP_MIB(&ip_mib, ipOutDiscards);
24601 			return;
24602 		}
24603 	}
24604 
24605 	if (!io->ipsec_out_secure) {
24606 		/*
24607 		 * We came here by mistake.
24608 		 * Don't bother with ipsec processing
24609 		 * Should "discourage" this path in the future.
24610 		 */
24611 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24612 		goto done;
24613 	}
24614 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24615 	ASSERT((io->ipsec_out_policy != NULL) ||
24616 	    (io->ipsec_out_act != NULL));
24617 	ASSERT(io->ipsec_out_failed == B_FALSE);
24618 
24619 	if (!ipsec_loaded()) {
24620 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
24621 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24622 			BUMP_MIB(&ip_mib, ipOutDiscards);
24623 		} else {
24624 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
24625 		}
24626 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
24627 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
24628 		return;
24629 	}
24630 
24631 	/*
24632 	 * IPSEC processing has started.
24633 	 */
24634 	io->ipsec_out_proc_begin = B_TRUE;
24635 	ap = io->ipsec_out_act;
24636 	if (ap == NULL) {
24637 		pp = io->ipsec_out_policy;
24638 		ASSERT(pp != NULL);
24639 		ap = pp->ipsp_act;
24640 		ASSERT(ap != NULL);
24641 	}
24642 
24643 	/*
24644 	 * Save the outbound ill index. When the packet comes back
24645 	 * from IPsec, we make sure the ill hasn't changed or disappeared
24646 	 * before sending it the accelerated packet.
24647 	 */
24648 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
24649 		int ifindex;
24650 		ill = ire_to_ill(ire);
24651 		ifindex = ill->ill_phyint->phyint_ifindex;
24652 		io->ipsec_out_capab_ill_index = ifindex;
24653 	}
24654 
24655 	/*
24656 	 * The order of processing is first insert a IP header if needed.
24657 	 * Then insert the ESP header and then the AH header.
24658 	 */
24659 	if ((io->ipsec_out_se_done == B_FALSE) &&
24660 	    (ap->ipa_want_se)) {
24661 		/*
24662 		 * First get the outer IP header before sending
24663 		 * it to ESP.
24664 		 */
24665 		ipha_t *oipha, *iipha;
24666 		mblk_t *outer_mp, *inner_mp;
24667 
24668 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
24669 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
24670 			    "ipsec_out_process: "
24671 			    "Self-Encapsulation failed: Out of memory\n");
24672 			freemsg(ipsec_mp);
24673 			BUMP_MIB(&ip_mib, ipOutDiscards);
24674 			return;
24675 		}
24676 		inner_mp = ipsec_mp->b_cont;
24677 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
24678 		oipha = (ipha_t *)outer_mp->b_rptr;
24679 		iipha = (ipha_t *)inner_mp->b_rptr;
24680 		*oipha = *iipha;
24681 		outer_mp->b_wptr += sizeof (ipha_t);
24682 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
24683 		    sizeof (ipha_t));
24684 		oipha->ipha_protocol = IPPROTO_ENCAP;
24685 		oipha->ipha_version_and_hdr_length =
24686 		    IP_SIMPLE_HDR_VERSION;
24687 		oipha->ipha_hdr_checksum = 0;
24688 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
24689 		outer_mp->b_cont = inner_mp;
24690 		ipsec_mp->b_cont = outer_mp;
24691 
24692 		io->ipsec_out_se_done = B_TRUE;
24693 		io->ipsec_out_encaps = B_TRUE;
24694 	}
24695 
24696 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
24697 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
24698 	    !ipsec_out_select_sa(ipsec_mp))
24699 		return;
24700 
24701 	/*
24702 	 * By now, we know what SA's to use.  Toss over to ESP & AH
24703 	 * to do the heavy lifting.
24704 	 */
24705 	zoneid = io->ipsec_out_zoneid;
24706 	ASSERT(zoneid != ALL_ZONES);
24707 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
24708 		ASSERT(io->ipsec_out_esp_sa != NULL);
24709 		io->ipsec_out_esp_done = B_TRUE;
24710 		/*
24711 		 * Note that since hw accel can only apply one transform,
24712 		 * not two, we skip hw accel for ESP if we also have AH
24713 		 * This is an design limitation of the interface
24714 		 * which should be revisited.
24715 		 */
24716 		ASSERT(ire != NULL);
24717 		if (io->ipsec_out_ah_sa == NULL) {
24718 			ill = (ill_t *)ire->ire_stq->q_ptr;
24719 			ipsec_out_is_accelerated(ipsec_mp,
24720 			    io->ipsec_out_esp_sa, ill, ire);
24721 		}
24722 
24723 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
24724 		switch (ipsec_rc) {
24725 		case IPSEC_STATUS_SUCCESS:
24726 			break;
24727 		case IPSEC_STATUS_FAILED:
24728 			BUMP_MIB(&ip_mib, ipOutDiscards);
24729 			/* FALLTHRU */
24730 		case IPSEC_STATUS_PENDING:
24731 			return;
24732 		}
24733 	}
24734 
24735 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
24736 		ASSERT(io->ipsec_out_ah_sa != NULL);
24737 		io->ipsec_out_ah_done = B_TRUE;
24738 		if (ire == NULL) {
24739 			int idx = io->ipsec_out_capab_ill_index;
24740 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
24741 			    NULL, NULL, NULL, NULL);
24742 			ill_need_rele = B_TRUE;
24743 		} else {
24744 			ill = (ill_t *)ire->ire_stq->q_ptr;
24745 		}
24746 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
24747 		    ire);
24748 
24749 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
24750 		switch (ipsec_rc) {
24751 		case IPSEC_STATUS_SUCCESS:
24752 			break;
24753 		case IPSEC_STATUS_FAILED:
24754 			BUMP_MIB(&ip_mib, ipOutDiscards);
24755 			/* FALLTHRU */
24756 		case IPSEC_STATUS_PENDING:
24757 			if (ill != NULL && ill_need_rele)
24758 				ill_refrele(ill);
24759 			return;
24760 		}
24761 	}
24762 	/*
24763 	 * We are done with IPSEC processing. Send it over
24764 	 * the wire.
24765 	 */
24766 done:
24767 	mp = ipsec_mp->b_cont;
24768 	ipha = (ipha_t *)mp->b_rptr;
24769 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24770 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
24771 	} else {
24772 		ip6h = (ip6_t *)ipha;
24773 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
24774 	}
24775 	if (ill != NULL && ill_need_rele)
24776 		ill_refrele(ill);
24777 }
24778 
24779 /* ARGSUSED */
24780 void
24781 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
24782 {
24783 	opt_restart_t	*or;
24784 	int	err;
24785 	conn_t	*connp;
24786 
24787 	ASSERT(CONN_Q(q));
24788 	connp = Q_TO_CONN(q);
24789 
24790 	ASSERT(first_mp->b_datap->db_type == M_CTL);
24791 	or = (opt_restart_t *)first_mp->b_rptr;
24792 	/*
24793 	 * We don't need to pass any credentials here since this is just
24794 	 * a restart. The credentials are passed in when svr4_optcom_req
24795 	 * is called the first time (from ip_wput_nondata).
24796 	 */
24797 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
24798 		err = svr4_optcom_req(q, first_mp, NULL,
24799 		    &ip_opt_obj);
24800 	} else {
24801 		ASSERT(or->or_type == T_OPTMGMT_REQ);
24802 		err = tpi_optcom_req(q, first_mp, NULL,
24803 		    &ip_opt_obj);
24804 	}
24805 	if (err != EINPROGRESS) {
24806 		/* operation is done */
24807 		CONN_OPER_PENDING_DONE(connp);
24808 	}
24809 }
24810 
24811 /*
24812  * ioctls that go through a down/up sequence may need to wait for the down
24813  * to complete. This involves waiting for the ire and ipif refcnts to go down
24814  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
24815  */
24816 /* ARGSUSED */
24817 void
24818 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24819 {
24820 	struct iocblk *iocp;
24821 	mblk_t *mp1;
24822 	ipif_t	*ipif;
24823 	ip_ioctl_cmd_t *ipip;
24824 	int err;
24825 	sin_t	*sin;
24826 	struct lifreq *lifr;
24827 	struct ifreq *ifr;
24828 
24829 	iocp = (struct iocblk *)mp->b_rptr;
24830 	ASSERT(ipsq != NULL);
24831 	/* Existence of mp1 verified in ip_wput_nondata */
24832 	mp1 = mp->b_cont->b_cont;
24833 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24834 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
24835 		ill_t *ill;
24836 		/*
24837 		 * Special case where ipsq_current_ipif may not be set.
24838 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
24839 		 * ill could also have become part of a ipmp group in the
24840 		 * process, we are here as were not able to complete the
24841 		 * operation in ipif_set_values because we could not become
24842 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
24843 		 * will not be set so we need to set it.
24844 		 */
24845 		ill = (ill_t *)q->q_ptr;
24846 		ipsq->ipsq_current_ipif = ill->ill_ipif;
24847 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24848 	}
24849 
24850 	ipif = ipsq->ipsq_current_ipif;
24851 	ASSERT(ipif != NULL);
24852 	if (ipip->ipi_cmd_type == IF_CMD) {
24853 		/* This a old style SIOC[GS]IF* command */
24854 		ifr = (struct ifreq *)mp1->b_rptr;
24855 		sin = (sin_t *)&ifr->ifr_addr;
24856 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24857 		/* This a new style SIOC[GS]LIF* command */
24858 		lifr = (struct lifreq *)mp1->b_rptr;
24859 		sin = (sin_t *)&lifr->lifr_addr;
24860 	} else {
24861 		sin = NULL;
24862 	}
24863 
24864 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24865 	    (void *)mp1->b_rptr);
24866 
24867 	/* SIOCLIFREMOVEIF could have removed the ipif */
24868 	ip_ioctl_finish(q, mp, err,
24869 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24870 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24871 }
24872 
24873 /*
24874  * ioctl processing
24875  *
24876  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24877  * the ioctl command in the ioctl tables and determines the copyin data size
24878  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24879  * size.
24880  *
24881  * ioctl processing then continues when the M_IOCDATA makes its way down.
24882  * Now the ioctl is looked up again in the ioctl table, and its properties are
24883  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24884  * and the general ioctl processing function ip_process_ioctl is called.
24885  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24886  * so goes thru the serialization primitive ipsq_try_enter. Then the
24887  * appropriate function to handle the ioctl is called based on the entry in
24888  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24889  * which also refreleases the 'conn' that was refheld at the start of the
24890  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24891  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24892  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24893  *
24894  * Many exclusive ioctls go thru an internal down up sequence as part of
24895  * the operation. For example an attempt to change the IP address of an
24896  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24897  * does all the cleanup such as deleting all ires that use this address.
24898  * Then we need to wait till all references to the interface go away.
24899  */
24900 void
24901 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24902 {
24903 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24904 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24905 	cmd_info_t ci;
24906 	int err;
24907 	boolean_t entered_ipsq = B_FALSE;
24908 
24909 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24910 
24911 	if (ipip == NULL)
24912 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24913 
24914 	/*
24915 	 * SIOCLIFADDIF needs to go thru a special path since the
24916 	 * ill may not exist yet. This happens in the case of lo0
24917 	 * which is created using this ioctl.
24918 	 */
24919 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24920 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24921 		ip_ioctl_finish(q, mp, err,
24922 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24923 		    NULL, NULL);
24924 		return;
24925 	}
24926 
24927 	ci.ci_ipif = NULL;
24928 	switch (ipip->ipi_cmd_type) {
24929 	case IF_CMD:
24930 	case LIF_CMD:
24931 		/*
24932 		 * ioctls that pass in a [l]ifreq appear here.
24933 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24934 		 * ci.ci_ipif
24935 		 */
24936 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24937 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24938 		if (err != 0) {
24939 			ip_ioctl_finish(q, mp, err,
24940 			    ipip->ipi_flags & IPI_GET_CMD ?
24941 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24942 			return;
24943 		}
24944 		ASSERT(ci.ci_ipif != NULL);
24945 		break;
24946 
24947 	case TUN_CMD:
24948 		/*
24949 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24950 		 * a refheld ipif in ci.ci_ipif
24951 		 */
24952 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24953 		if (err != 0) {
24954 			ip_ioctl_finish(q, mp, err,
24955 			    ipip->ipi_flags & IPI_GET_CMD ?
24956 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24957 			return;
24958 		}
24959 		ASSERT(ci.ci_ipif != NULL);
24960 		break;
24961 
24962 	case MISC_CMD:
24963 		/*
24964 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24965 		 * For eg. SIOCGLIFCONF will appear here.
24966 		 */
24967 		switch (ipip->ipi_cmd) {
24968 		case IF_UNITSEL:
24969 			/* ioctl comes down the ill */
24970 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24971 			ipif_refhold(ci.ci_ipif);
24972 			break;
24973 		case SIOCGMSFILTER:
24974 		case SIOCSMSFILTER:
24975 		case SIOCGIPMSFILTER:
24976 		case SIOCSIPMSFILTER:
24977 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24978 			    ip_process_ioctl);
24979 			if (err != 0) {
24980 				ip_ioctl_finish(q, mp, err,
24981 				    ipip->ipi_flags & IPI_GET_CMD ?
24982 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24983 				return;
24984 			}
24985 			break;
24986 		}
24987 		err = 0;
24988 		ci.ci_sin = NULL;
24989 		ci.ci_sin6 = NULL;
24990 		ci.ci_lifr = NULL;
24991 		break;
24992 	}
24993 
24994 	/*
24995 	 * If ipsq is non-null, we are already being called exclusively
24996 	 */
24997 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
24998 	if (!(ipip->ipi_flags & IPI_WR)) {
24999 		/*
25000 		 * A return value of EINPROGRESS means the ioctl is
25001 		 * either queued and waiting for some reason or has
25002 		 * already completed.
25003 		 */
25004 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25005 		    ci.ci_lifr);
25006 		if (ci.ci_ipif != NULL)
25007 			ipif_refrele(ci.ci_ipif);
25008 		ip_ioctl_finish(q, mp, err,
25009 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25010 		    NULL, NULL);
25011 		return;
25012 	}
25013 
25014 	ASSERT(ci.ci_ipif != NULL);
25015 
25016 	if (ipsq == NULL) {
25017 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25018 		    ip_process_ioctl, NEW_OP, B_TRUE);
25019 		entered_ipsq = B_TRUE;
25020 	}
25021 	/*
25022 	 * Release the ipif so that ipif_down and friends that wait for
25023 	 * references to go away are not misled about the current ipif_refcnt
25024 	 * values. We are writer so we can access the ipif even after releasing
25025 	 * the ipif.
25026 	 */
25027 	ipif_refrele(ci.ci_ipif);
25028 	if (ipsq == NULL)
25029 		return;
25030 
25031 	mutex_enter(&ipsq->ipsq_lock);
25032 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25033 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25034 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25035 	mutex_exit(&ipsq->ipsq_lock);
25036 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25037 	/*
25038 	 * For most set ioctls that come here, this serves as a single point
25039 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25040 	 * be any new references to the ipif. This helps functions that go
25041 	 * through this path and end up trying to wait for the refcnts
25042 	 * associated with the ipif to go down to zero. Some exceptions are
25043 	 * Failover, Failback, and Groupname commands that operate on more than
25044 	 * just the ci.ci_ipif. These commands internally determine the
25045 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25046 	 * flags on that set. Another exception is the Removeif command that
25047 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25048 	 * ipif to operate on.
25049 	 */
25050 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25051 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25052 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25053 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25054 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25055 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25056 
25057 	/*
25058 	 * A return value of EINPROGRESS means the ioctl is
25059 	 * either queued and waiting for some reason or has
25060 	 * already completed.
25061 	 */
25062 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25063 	    ci.ci_lifr);
25064 
25065 	/* SIOCLIFREMOVEIF could have removed the ipif */
25066 	ip_ioctl_finish(q, mp, err,
25067 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25068 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25069 
25070 	if (entered_ipsq)
25071 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25072 }
25073 
25074 /*
25075  * Complete the ioctl. Typically ioctls use the mi package and need to
25076  * do mi_copyout/mi_copy_done.
25077  */
25078 void
25079 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25080     ipif_t *ipif, ipsq_t *ipsq)
25081 {
25082 	conn_t	*connp = NULL;
25083 
25084 	if (err == EINPROGRESS)
25085 		return;
25086 
25087 	if (CONN_Q(q)) {
25088 		connp = Q_TO_CONN(q);
25089 		ASSERT(connp->conn_ref >= 2);
25090 	}
25091 
25092 	switch (mode) {
25093 	case COPYOUT:
25094 		if (err == 0)
25095 			mi_copyout(q, mp);
25096 		else
25097 			mi_copy_done(q, mp, err);
25098 		break;
25099 
25100 	case NO_COPYOUT:
25101 		mi_copy_done(q, mp, err);
25102 		break;
25103 
25104 	default:
25105 		/* An ioctl aborted through a conn close would take this path */
25106 		break;
25107 	}
25108 
25109 	/*
25110 	 * The refhold placed at the start of the ioctl is released here.
25111 	 */
25112 	if (connp != NULL)
25113 		CONN_OPER_PENDING_DONE(connp);
25114 
25115 	/*
25116 	 * If the ioctl were an exclusive ioctl it would have set
25117 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25118 	 */
25119 	if (ipif != NULL) {
25120 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25121 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25122 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25123 	}
25124 
25125 	/*
25126 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25127 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25128 	 * entering the ipsq
25129 	 */
25130 	if (ipsq != NULL) {
25131 		mutex_enter(&ipsq->ipsq_lock);
25132 		ipsq->ipsq_current_ipif = NULL;
25133 		mutex_exit(&ipsq->ipsq_lock);
25134 	}
25135 }
25136 
25137 /*
25138  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25139  */
25140 /* ARGSUSED */
25141 void
25142 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25143 {
25144 	conn_t *connp = arg;
25145 	tcp_t	*tcp;
25146 
25147 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25148 	tcp = connp->conn_tcp;
25149 
25150 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25151 		freemsg(mp);
25152 	else
25153 		tcp_rput_other(tcp, mp);
25154 	CONN_OPER_PENDING_DONE(connp);
25155 }
25156 
25157 /* Called from ip_wput for all non data messages */
25158 /* ARGSUSED */
25159 void
25160 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25161 {
25162 	mblk_t		*mp1;
25163 	ire_t		*ire;
25164 	ill_t		*ill;
25165 	struct iocblk	*iocp;
25166 	ip_ioctl_cmd_t	*ipip;
25167 	cred_t		*cr;
25168 	conn_t		*connp = NULL;
25169 	int		cmd, err;
25170 
25171 	if (CONN_Q(q))
25172 		connp = Q_TO_CONN(q);
25173 
25174 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25175 
25176 	/* Check if it is a queue to /dev/sctp. */
25177 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25178 	    connp->conn_rq == NULL) {
25179 		sctp_wput(q, mp);
25180 		return;
25181 	}
25182 
25183 	switch (DB_TYPE(mp)) {
25184 	case M_IOCTL:
25185 		/*
25186 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25187 		 * will arrange to copy in associated control structures.
25188 		 */
25189 		ip_sioctl_copyin_setup(q, mp);
25190 		return;
25191 	case M_IOCDATA:
25192 		/*
25193 		 * Ensure that this is associated with one of our trans-
25194 		 * parent ioctls.  If it's not ours, discard it if we're
25195 		 * running as a driver, or pass it on if we're a module.
25196 		 */
25197 		iocp = (struct iocblk *)mp->b_rptr;
25198 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25199 		if (ipip == NULL) {
25200 			if (q->q_next == NULL) {
25201 				goto nak;
25202 			} else {
25203 				putnext(q, mp);
25204 			}
25205 			return;
25206 		} else if ((q->q_next != NULL) &&
25207 		    !(ipip->ipi_flags & IPI_MODOK)) {
25208 			/*
25209 			 * the ioctl is one we recognise, but is not
25210 			 * consumed by IP as a module, pass M_IOCDATA
25211 			 * for processing downstream, but only for
25212 			 * common Streams ioctls.
25213 			 */
25214 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25215 				putnext(q, mp);
25216 				return;
25217 			} else {
25218 				goto nak;
25219 			}
25220 		}
25221 
25222 		/* IOCTL continuation following copyin or copyout. */
25223 		if (mi_copy_state(q, mp, NULL) == -1) {
25224 			/*
25225 			 * The copy operation failed.  mi_copy_state already
25226 			 * cleaned up, so we're out of here.
25227 			 */
25228 			return;
25229 		}
25230 		/*
25231 		 * If we just completed a copy in, we become writer and
25232 		 * continue processing in ip_sioctl_copyin_done.  If it
25233 		 * was a copy out, we call mi_copyout again.  If there is
25234 		 * nothing more to copy out, it will complete the IOCTL.
25235 		 */
25236 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25237 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25238 				mi_copy_done(q, mp, EPROTO);
25239 				return;
25240 			}
25241 			/*
25242 			 * Check for cases that need more copying.  A return
25243 			 * value of 0 means a second copyin has been started,
25244 			 * so we return; a return value of 1 means no more
25245 			 * copying is needed, so we continue.
25246 			 */
25247 			cmd = iocp->ioc_cmd;
25248 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25249 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25250 			    MI_COPY_COUNT(mp) == 1) {
25251 				if (ip_copyin_msfilter(q, mp) == 0)
25252 					return;
25253 			}
25254 			/*
25255 			 * Refhold the conn, till the ioctl completes. This is
25256 			 * needed in case the ioctl ends up in the pending mp
25257 			 * list. Every mp in the ill_pending_mp list and
25258 			 * the ipsq_pending_mp must have a refhold on the conn
25259 			 * to resume processing. The refhold is released when
25260 			 * the ioctl completes. (normally or abnormally)
25261 			 * In all cases ip_ioctl_finish is called to finish
25262 			 * the ioctl.
25263 			 */
25264 			if (connp != NULL) {
25265 				/* This is not a reentry */
25266 				ASSERT(ipsq == NULL);
25267 				CONN_INC_REF(connp);
25268 			} else {
25269 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25270 					mi_copy_done(q, mp, EINVAL);
25271 					return;
25272 				}
25273 			}
25274 
25275 			ip_process_ioctl(ipsq, q, mp, ipip);
25276 
25277 		} else {
25278 			mi_copyout(q, mp);
25279 		}
25280 		return;
25281 nak:
25282 		iocp->ioc_error = EINVAL;
25283 		mp->b_datap->db_type = M_IOCNAK;
25284 		iocp->ioc_count = 0;
25285 		qreply(q, mp);
25286 		return;
25287 
25288 	case M_IOCNAK:
25289 		/*
25290 		 * The only way we could get here is if a resolver didn't like
25291 		 * an IOCTL we sent it.	 This shouldn't happen.
25292 		 */
25293 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25294 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25295 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25296 		freemsg(mp);
25297 		return;
25298 	case M_IOCACK:
25299 		/* Finish socket ioctls passed through to ARP. */
25300 		ip_sioctl_iocack(q, mp);
25301 		return;
25302 	case M_FLUSH:
25303 		if (*mp->b_rptr & FLUSHW)
25304 			flushq(q, FLUSHALL);
25305 		if (q->q_next) {
25306 			/*
25307 			 * M_FLUSH is sent up to IP by some drivers during
25308 			 * unbind. ip_rput has already replied to it. We are
25309 			 * here for the M_FLUSH that we originated in IP
25310 			 * before sending the unbind request to the driver.
25311 			 * Just free it as we don't queue packets in IP
25312 			 * on the write side of the device instance.
25313 			 */
25314 			freemsg(mp);
25315 			return;
25316 		}
25317 		if (*mp->b_rptr & FLUSHR) {
25318 			*mp->b_rptr &= ~FLUSHW;
25319 			qreply(q, mp);
25320 			return;
25321 		}
25322 		freemsg(mp);
25323 		return;
25324 	case IRE_DB_REQ_TYPE:
25325 		/* An Upper Level Protocol wants a copy of an IRE. */
25326 		ip_ire_req(q, mp);
25327 		return;
25328 	case M_CTL:
25329 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
25330 			break;
25331 
25332 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
25333 		    IP_ULP_OUT_LABELED) {
25334 			out_labeled_t *olp;
25335 
25336 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
25337 				break;
25338 			olp = (out_labeled_t *)mp->b_rptr;
25339 			connp->conn_ulp_labeled = olp->out_qnext == q;
25340 			freemsg(mp);
25341 			return;
25342 		}
25343 
25344 		/* M_CTL messages are used by ARP to tell us things. */
25345 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
25346 			break;
25347 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
25348 		case AR_ENTRY_SQUERY:
25349 			ip_wput_ctl(q, mp);
25350 			return;
25351 		case AR_CLIENT_NOTIFY:
25352 			ip_arp_news(q, mp);
25353 			return;
25354 		case AR_DLPIOP_DONE:
25355 			ASSERT(q->q_next != NULL);
25356 			ill = (ill_t *)q->q_ptr;
25357 			/* qwriter_ip releases the refhold */
25358 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
25359 			ill_refhold(ill);
25360 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
25361 			    CUR_OP, B_FALSE);
25362 			return;
25363 		case AR_ARP_CLOSING:
25364 			/*
25365 			 * ARP (above us) is closing. If no ARP bringup is
25366 			 * currently pending, ack the message so that ARP
25367 			 * can complete its close. Also mark ill_arp_closing
25368 			 * so that new ARP bringups will fail. If any
25369 			 * ARP bringup is currently in progress, we will
25370 			 * ack this when the current ARP bringup completes.
25371 			 */
25372 			ASSERT(q->q_next != NULL);
25373 			ill = (ill_t *)q->q_ptr;
25374 			mutex_enter(&ill->ill_lock);
25375 			ill->ill_arp_closing = 1;
25376 			if (!ill->ill_arp_bringup_pending) {
25377 				mutex_exit(&ill->ill_lock);
25378 				qreply(q, mp);
25379 			} else {
25380 				mutex_exit(&ill->ill_lock);
25381 				freemsg(mp);
25382 			}
25383 			return;
25384 		default:
25385 			break;
25386 		}
25387 		break;
25388 	case M_PROTO:
25389 	case M_PCPROTO:
25390 		/*
25391 		 * The only PROTO messages we expect are ULP binds and
25392 		 * copies of option negotiation acknowledgements.
25393 		 */
25394 		switch (((union T_primitives *)mp->b_rptr)->type) {
25395 		case O_T_BIND_REQ:
25396 		case T_BIND_REQ: {
25397 			/* Request can get queued in bind */
25398 			ASSERT(connp != NULL);
25399 			/*
25400 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
25401 			 * instead of going through this path.  We only get
25402 			 * here in the following cases:
25403 			 *
25404 			 * a. Bind retries, where ipsq is non-NULL.
25405 			 * b. T_BIND_REQ is issued from non TCP/UDP
25406 			 *    transport, e.g. icmp for raw socket,
25407 			 *    in which case ipsq will be NULL.
25408 			 */
25409 			ASSERT(ipsq != NULL ||
25410 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
25411 
25412 			/* Don't increment refcnt if this is a re-entry */
25413 			if (ipsq == NULL)
25414 				CONN_INC_REF(connp);
25415 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
25416 			    connp, NULL) : ip_bind_v4(q, mp, connp);
25417 			if (mp == NULL)
25418 				return;
25419 			if (IPCL_IS_TCP(connp)) {
25420 				/*
25421 				 * In the case of TCP endpoint we
25422 				 * come here only for bind retries
25423 				 */
25424 				ASSERT(ipsq != NULL);
25425 				CONN_INC_REF(connp);
25426 				squeue_fill(connp->conn_sqp, mp,
25427 				    ip_resume_tcp_bind, connp,
25428 				    SQTAG_BIND_RETRY);
25429 				return;
25430 			} else if (IPCL_IS_UDP(connp)) {
25431 				/*
25432 				 * In the case of UDP endpoint we
25433 				 * come here only for bind retries
25434 				 */
25435 				ASSERT(ipsq != NULL);
25436 				udp_resume_bind(connp, mp);
25437 				return;
25438 			}
25439 			qreply(q, mp);
25440 			CONN_OPER_PENDING_DONE(connp);
25441 			return;
25442 		}
25443 		case T_SVR4_OPTMGMT_REQ:
25444 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
25445 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
25446 
25447 			ASSERT(connp != NULL);
25448 			if (!snmpcom_req(q, mp, ip_snmp_set,
25449 			    ip_snmp_get, cr)) {
25450 				/*
25451 				 * Call svr4_optcom_req so that it can
25452 				 * generate the ack. We don't come here
25453 				 * if this operation is being restarted.
25454 				 * ip_restart_optmgmt will drop the conn ref.
25455 				 * In the case of ipsec option after the ipsec
25456 				 * load is complete conn_restart_ipsec_waiter
25457 				 * drops the conn ref.
25458 				 */
25459 				ASSERT(ipsq == NULL);
25460 				CONN_INC_REF(connp);
25461 				if (ip_check_for_ipsec_opt(q, mp))
25462 					return;
25463 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
25464 				if (err != EINPROGRESS) {
25465 					/* Operation is done */
25466 					CONN_OPER_PENDING_DONE(connp);
25467 				}
25468 			}
25469 			return;
25470 		case T_OPTMGMT_REQ:
25471 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
25472 			/*
25473 			 * Note: No snmpcom_req support through new
25474 			 * T_OPTMGMT_REQ.
25475 			 * Call tpi_optcom_req so that it can
25476 			 * generate the ack.
25477 			 */
25478 			ASSERT(connp != NULL);
25479 			ASSERT(ipsq == NULL);
25480 			/*
25481 			 * We don't come here for restart. ip_restart_optmgmt
25482 			 * will drop the conn ref. In the case of ipsec option
25483 			 * after the ipsec load is complete
25484 			 * conn_restart_ipsec_waiter drops the conn ref.
25485 			 */
25486 			CONN_INC_REF(connp);
25487 			if (ip_check_for_ipsec_opt(q, mp))
25488 				return;
25489 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
25490 			if (err != EINPROGRESS) {
25491 				/* Operation is done */
25492 				CONN_OPER_PENDING_DONE(connp);
25493 			}
25494 			return;
25495 		case T_UNBIND_REQ:
25496 			mp = ip_unbind(q, mp);
25497 			qreply(q, mp);
25498 			return;
25499 		default:
25500 			/*
25501 			 * Have to drop any DLPI messages coming down from
25502 			 * arp (such as an info_req which would cause ip
25503 			 * to receive an extra info_ack if it was passed
25504 			 * through.
25505 			 */
25506 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
25507 			    (int)*(uint_t *)mp->b_rptr));
25508 			freemsg(mp);
25509 			return;
25510 		}
25511 		/* NOTREACHED */
25512 	case IRE_DB_TYPE: {
25513 		nce_t		*nce;
25514 		ill_t		*ill;
25515 		in6_addr_t	gw_addr_v6;
25516 
25517 
25518 		/*
25519 		 * This is a response back from a resolver.  It
25520 		 * consists of a message chain containing:
25521 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
25522 		 * The IRE_MBLK is the one we allocated in ip_newroute.
25523 		 * The LL_HDR_MBLK is the DLPI header to use to get
25524 		 * the attached packet, and subsequent ones for the
25525 		 * same destination, transmitted.
25526 		 */
25527 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
25528 			break;
25529 		/*
25530 		 * First, check to make sure the resolution succeeded.
25531 		 * If it failed, the second mblk will be empty.
25532 		 * If it is, free the chain, dropping the packet.
25533 		 * (We must ire_delete the ire; that frees the ire mblk)
25534 		 * We're doing this now to support PVCs for ATM; it's
25535 		 * a partial xresolv implementation. When we fully implement
25536 		 * xresolv interfaces, instead of freeing everything here
25537 		 * we'll initiate neighbor discovery.
25538 		 *
25539 		 * For v4 (ARP and other external resolvers) the resolver
25540 		 * frees the message, so no check is needed. This check
25541 		 * is required, though, for a full xresolve implementation.
25542 		 * Including this code here now both shows how external
25543 		 * resolvers can NACK a resolution request using an
25544 		 * existing design that has no specific provisions for NACKs,
25545 		 * and also takes into account that the current non-ARP
25546 		 * external resolver has been coded to use this method of
25547 		 * NACKing for all IPv6 (xresolv) cases,
25548 		 * whether our xresolv implementation is complete or not.
25549 		 *
25550 		 */
25551 		ire = (ire_t *)mp->b_rptr;
25552 		ill = ire_to_ill(ire);
25553 		mp1 = mp->b_cont;		/* dl_unitdata_req */
25554 		if (mp1->b_rptr == mp1->b_wptr) {
25555 			if (ire->ire_ipversion == IPV6_VERSION) {
25556 				/*
25557 				 * XRESOLV interface.
25558 				 */
25559 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
25560 				mutex_enter(&ire->ire_lock);
25561 				gw_addr_v6 = ire->ire_gateway_addr_v6;
25562 				mutex_exit(&ire->ire_lock);
25563 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25564 					nce = ndp_lookup(ill,
25565 					    &ire->ire_addr_v6, B_FALSE);
25566 				} else {
25567 					nce = ndp_lookup(ill, &gw_addr_v6,
25568 					    B_FALSE);
25569 				}
25570 				if (nce != NULL) {
25571 					nce_resolv_failed(nce);
25572 					ndp_delete(nce);
25573 					NCE_REFRELE(nce);
25574 				}
25575 			}
25576 			mp->b_cont = NULL;
25577 			freemsg(mp1);		/* frees the pkt as well */
25578 			ire_delete((ire_t *)mp->b_rptr);
25579 			return;
25580 		}
25581 		/*
25582 		 * Split them into IRE_MBLK and pkt and feed it into
25583 		 * ire_add_then_send. Then in ire_add_then_send
25584 		 * the IRE will be added, and then the packet will be
25585 		 * run back through ip_wput. This time it will make
25586 		 * it to the wire.
25587 		 */
25588 		mp->b_cont = NULL;
25589 		mp = mp1->b_cont;		/* now, mp points to pkt */
25590 		mp1->b_cont = NULL;
25591 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
25592 		if (ire->ire_ipversion == IPV6_VERSION) {
25593 			/*
25594 			 * XRESOLV interface. Find the nce and put a copy
25595 			 * of the dl_unitdata_req in nce_res_mp
25596 			 */
25597 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
25598 			mutex_enter(&ire->ire_lock);
25599 			gw_addr_v6 = ire->ire_gateway_addr_v6;
25600 			mutex_exit(&ire->ire_lock);
25601 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25602 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
25603 				    B_FALSE);
25604 			} else {
25605 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
25606 			}
25607 			if (nce != NULL) {
25608 				/*
25609 				 * We have to protect nce_res_mp here
25610 				 * from being accessed by other threads
25611 				 * while we change the mblk pointer.
25612 				 * Other functions will also lock the nce when
25613 				 * accessing nce_res_mp.
25614 				 *
25615 				 * The reason we change the mblk pointer
25616 				 * here rather than copying the resolved address
25617 				 * into the template is that, unlike with
25618 				 * ethernet, we have no guarantee that the
25619 				 * resolved address length will be
25620 				 * smaller than or equal to the lla length
25621 				 * with which the template was allocated,
25622 				 * (for ethernet, they're equal)
25623 				 * so we have to use the actual resolved
25624 				 * address mblk - which holds the real
25625 				 * dl_unitdata_req with the resolved address.
25626 				 *
25627 				 * Doing this is the same behavior as was
25628 				 * previously used in the v4 ARP case.
25629 				 */
25630 				mutex_enter(&nce->nce_lock);
25631 				if (nce->nce_res_mp != NULL)
25632 					freemsg(nce->nce_res_mp);
25633 				nce->nce_res_mp = mp1;
25634 				mutex_exit(&nce->nce_lock);
25635 				/*
25636 				 * We do a fastpath probe here because
25637 				 * we have resolved the address without
25638 				 * using Neighbor Discovery.
25639 				 * In the non-XRESOLV v6 case, the fastpath
25640 				 * probe is done right after neighbor
25641 				 * discovery completes.
25642 				 */
25643 				if (nce->nce_res_mp != NULL) {
25644 					int res;
25645 					nce_fastpath_list_add(nce);
25646 					res = ill_fastpath_probe(ill,
25647 					    nce->nce_res_mp);
25648 					if (res != 0 && res != EAGAIN)
25649 						nce_fastpath_list_delete(nce);
25650 				}
25651 
25652 				ire_add_then_send(q, ire, mp);
25653 				/*
25654 				 * Now we have to clean out any packets
25655 				 * that may have been queued on the nce
25656 				 * while it was waiting for address resolution
25657 				 * to complete.
25658 				 */
25659 				mutex_enter(&nce->nce_lock);
25660 				mp1 = nce->nce_qd_mp;
25661 				nce->nce_qd_mp = NULL;
25662 				mutex_exit(&nce->nce_lock);
25663 				while (mp1 != NULL) {
25664 					mblk_t *nxt_mp;
25665 					queue_t *fwdq = NULL;
25666 					ill_t   *inbound_ill;
25667 					uint_t ifindex;
25668 
25669 					nxt_mp = mp1->b_next;
25670 					mp1->b_next = NULL;
25671 					/*
25672 					 * Retrieve ifindex stored in
25673 					 * ip_rput_data_v6()
25674 					 */
25675 					ifindex =
25676 					    (uint_t)(uintptr_t)mp1->b_prev;
25677 					inbound_ill =
25678 						ill_lookup_on_ifindex(ifindex,
25679 						    B_TRUE, NULL, NULL, NULL,
25680 						    NULL);
25681 					mp1->b_prev = NULL;
25682 					if (inbound_ill != NULL)
25683 						fwdq = inbound_ill->ill_rq;
25684 
25685 					if (fwdq != NULL) {
25686 						put(fwdq, mp1);
25687 						ill_refrele(inbound_ill);
25688 					} else
25689 						put(WR(ill->ill_rq), mp1);
25690 					mp1 = nxt_mp;
25691 				}
25692 				NCE_REFRELE(nce);
25693 			} else {	/* nce is NULL; clean up */
25694 				ire_delete(ire);
25695 				freemsg(mp);
25696 				freemsg(mp1);
25697 				return;
25698 			}
25699 		} else {
25700 			ire->ire_dlureq_mp = mp1;
25701 			ire_add_then_send(q, ire, mp);
25702 		}
25703 		return;	/* All is well, the packet has been sent. */
25704 	}
25705 	default:
25706 		break;
25707 	}
25708 	if (q->q_next) {
25709 		putnext(q, mp);
25710 	} else
25711 		freemsg(mp);
25712 }
25713 
25714 /*
25715  * Process IP options in an outbound packet.  Modify the destination if there
25716  * is a source route option.
25717  * Returns non-zero if something fails in which case an ICMP error has been
25718  * sent and mp freed.
25719  */
25720 static int
25721 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
25722     boolean_t mctl_present, zoneid_t zoneid)
25723 {
25724 	ipoptp_t	opts;
25725 	uchar_t		*opt;
25726 	uint8_t		optval;
25727 	uint8_t		optlen;
25728 	ipaddr_t	dst;
25729 	intptr_t	code = 0;
25730 	mblk_t		*mp;
25731 	ire_t		*ire = NULL;
25732 
25733 	ip2dbg(("ip_wput_options\n"));
25734 	mp = ipsec_mp;
25735 	if (mctl_present) {
25736 		mp = ipsec_mp->b_cont;
25737 	}
25738 
25739 	dst = ipha->ipha_dst;
25740 	for (optval = ipoptp_first(&opts, ipha);
25741 	    optval != IPOPT_EOL;
25742 	    optval = ipoptp_next(&opts)) {
25743 		opt = opts.ipoptp_cur;
25744 		optlen = opts.ipoptp_len;
25745 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
25746 		    optval, optlen));
25747 		switch (optval) {
25748 			uint32_t off;
25749 		case IPOPT_SSRR:
25750 		case IPOPT_LSRR:
25751 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25752 				ip1dbg((
25753 				    "ip_wput_options: bad option offset\n"));
25754 				code = (char *)&opt[IPOPT_OLEN] -
25755 				    (char *)ipha;
25756 				goto param_prob;
25757 			}
25758 			off = opt[IPOPT_OFFSET];
25759 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
25760 			    ntohl(dst)));
25761 			/*
25762 			 * For strict: verify that dst is directly
25763 			 * reachable.
25764 			 */
25765 			if (optval == IPOPT_SSRR) {
25766 				ire = ire_ftable_lookup(dst, 0, 0,
25767 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25768 				    MBLK_GETLABEL(mp),
25769 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
25770 				if (ire == NULL) {
25771 					ip1dbg(("ip_wput_options: SSRR not"
25772 					    " directly reachable: 0x%x\n",
25773 					    ntohl(dst)));
25774 					goto bad_src_route;
25775 				}
25776 				ire_refrele(ire);
25777 			}
25778 			break;
25779 		case IPOPT_RR:
25780 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25781 				ip1dbg((
25782 				    "ip_wput_options: bad option offset\n"));
25783 				code = (char *)&opt[IPOPT_OLEN] -
25784 				    (char *)ipha;
25785 				goto param_prob;
25786 			}
25787 			break;
25788 		case IPOPT_TS:
25789 			/*
25790 			 * Verify that length >=5 and that there is either
25791 			 * room for another timestamp or that the overflow
25792 			 * counter is not maxed out.
25793 			 */
25794 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
25795 			if (optlen < IPOPT_MINLEN_IT) {
25796 				goto param_prob;
25797 			}
25798 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25799 				ip1dbg((
25800 				    "ip_wput_options: bad option offset\n"));
25801 				code = (char *)&opt[IPOPT_OFFSET] -
25802 				    (char *)ipha;
25803 				goto param_prob;
25804 			}
25805 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25806 			case IPOPT_TS_TSONLY:
25807 				off = IPOPT_TS_TIMELEN;
25808 				break;
25809 			case IPOPT_TS_TSANDADDR:
25810 			case IPOPT_TS_PRESPEC:
25811 			case IPOPT_TS_PRESPEC_RFC791:
25812 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25813 				break;
25814 			default:
25815 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
25816 				    (char *)ipha;
25817 				goto param_prob;
25818 			}
25819 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
25820 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
25821 				/*
25822 				 * No room and the overflow counter is 15
25823 				 * already.
25824 				 */
25825 				goto param_prob;
25826 			}
25827 			break;
25828 		}
25829 	}
25830 
25831 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
25832 		return (0);
25833 
25834 	ip1dbg(("ip_wput_options: error processing IP options."));
25835 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
25836 
25837 param_prob:
25838 	/*
25839 	 * Since ip_wput() isn't close to finished, we fill
25840 	 * in enough of the header for credible error reporting.
25841 	 */
25842 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25843 		/* Failed */
25844 		freemsg(ipsec_mp);
25845 		return (-1);
25846 	}
25847 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
25848 	return (-1);
25849 
25850 bad_src_route:
25851 	/*
25852 	 * Since ip_wput() isn't close to finished, we fill
25853 	 * in enough of the header for credible error reporting.
25854 	 */
25855 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25856 		/* Failed */
25857 		freemsg(ipsec_mp);
25858 		return (-1);
25859 	}
25860 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
25861 	return (-1);
25862 }
25863 
25864 /*
25865  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25866  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25867  * thru /etc/system.
25868  */
25869 #define	CONN_MAXDRAINCNT	64
25870 
25871 static void
25872 conn_drain_init(void)
25873 {
25874 	int i;
25875 
25876 	conn_drain_list_cnt = conn_drain_nthreads;
25877 
25878 	if ((conn_drain_list_cnt == 0) ||
25879 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25880 		/*
25881 		 * Default value of the number of drainers is the
25882 		 * number of cpus, subject to maximum of 8 drainers.
25883 		 */
25884 		if (boot_max_ncpus != -1)
25885 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25886 		else
25887 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25888 	}
25889 
25890 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25891 	    KM_SLEEP);
25892 
25893 	for (i = 0; i < conn_drain_list_cnt; i++) {
25894 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25895 		    MUTEX_DEFAULT, NULL);
25896 	}
25897 }
25898 
25899 static void
25900 conn_drain_fini(void)
25901 {
25902 	int i;
25903 
25904 	for (i = 0; i < conn_drain_list_cnt; i++)
25905 		mutex_destroy(&conn_drain_list[i].idl_lock);
25906 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25907 	conn_drain_list = NULL;
25908 }
25909 
25910 /*
25911  * Note: For an overview of how flowcontrol is handled in IP please see the
25912  * IP Flowcontrol notes at the top of this file.
25913  *
25914  * Flow control has blocked us from proceeding. Insert the given conn in one
25915  * of the conn drain lists. These conn wq's will be qenabled later on when
25916  * STREAMS flow control does a backenable. conn_walk_drain will enable
25917  * the first conn in each of these drain lists. Each of these qenabled conns
25918  * in turn enables the next in the list, after it runs, or when it closes,
25919  * thus sustaining the drain process.
25920  *
25921  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25922  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25923  * running at any time, on a given conn, since there can be only 1 service proc
25924  * running on a queue at any time.
25925  */
25926 void
25927 conn_drain_insert(conn_t *connp)
25928 {
25929 	idl_t	*idl;
25930 	uint_t	index;
25931 
25932 	mutex_enter(&connp->conn_lock);
25933 	if (connp->conn_state_flags & CONN_CLOSING) {
25934 		/*
25935 		 * The conn is closing as a result of which CONN_CLOSING
25936 		 * is set. Return.
25937 		 */
25938 		mutex_exit(&connp->conn_lock);
25939 		return;
25940 	} else if (connp->conn_idl == NULL) {
25941 		/*
25942 		 * Assign the next drain list round robin. We dont' use
25943 		 * a lock, and thus it may not be strictly round robin.
25944 		 * Atomicity of load/stores is enough to make sure that
25945 		 * conn_drain_list_index is always within bounds.
25946 		 */
25947 		index = conn_drain_list_index;
25948 		ASSERT(index < conn_drain_list_cnt);
25949 		connp->conn_idl = &conn_drain_list[index];
25950 		index++;
25951 		if (index == conn_drain_list_cnt)
25952 			index = 0;
25953 		conn_drain_list_index = index;
25954 	}
25955 	mutex_exit(&connp->conn_lock);
25956 
25957 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25958 	if ((connp->conn_drain_prev != NULL) ||
25959 	    (connp->conn_state_flags & CONN_CLOSING)) {
25960 		/*
25961 		 * The conn is already in the drain list, OR
25962 		 * the conn is closing. We need to check again for
25963 		 * the closing case again since close can happen
25964 		 * after we drop the conn_lock, and before we
25965 		 * acquire the CONN_DRAIN_LIST_LOCK.
25966 		 */
25967 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25968 		return;
25969 	} else {
25970 		idl = connp->conn_idl;
25971 	}
25972 
25973 	/*
25974 	 * The conn is not in the drain list. Insert it at the
25975 	 * tail of the drain list. The drain list is circular
25976 	 * and doubly linked. idl_conn points to the 1st element
25977 	 * in the list.
25978 	 */
25979 	if (idl->idl_conn == NULL) {
25980 		idl->idl_conn = connp;
25981 		connp->conn_drain_next = connp;
25982 		connp->conn_drain_prev = connp;
25983 	} else {
25984 		conn_t *head = idl->idl_conn;
25985 
25986 		connp->conn_drain_next = head;
25987 		connp->conn_drain_prev = head->conn_drain_prev;
25988 		head->conn_drain_prev->conn_drain_next = connp;
25989 		head->conn_drain_prev = connp;
25990 	}
25991 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25992 }
25993 
25994 /*
25995  * This conn is closing, and we are called from ip_close. OR
25996  * This conn has been serviced by ip_wsrv, and we need to do the tail
25997  * processing.
25998  * If this conn is part of the drain list, we may need to sustain the drain
25999  * process by qenabling the next conn in the drain list. We may also need to
26000  * remove this conn from the list, if it is done.
26001  */
26002 static void
26003 conn_drain_tail(conn_t *connp, boolean_t closing)
26004 {
26005 	idl_t *idl;
26006 
26007 	/*
26008 	 * connp->conn_idl is stable at this point, and no lock is needed
26009 	 * to check it. If we are called from ip_close, close has already
26010 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26011 	 * called us only because conn_idl is non-null. If we are called thru
26012 	 * service, conn_idl could be null, but it cannot change because
26013 	 * service is single-threaded per queue, and there cannot be another
26014 	 * instance of service trying to call conn_drain_insert on this conn
26015 	 * now.
26016 	 */
26017 	ASSERT(!closing || (connp->conn_idl != NULL));
26018 
26019 	/*
26020 	 * If connp->conn_idl is null, the conn has not been inserted into any
26021 	 * drain list even once since creation of the conn. Just return.
26022 	 */
26023 	if (connp->conn_idl == NULL)
26024 		return;
26025 
26026 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26027 
26028 	if (connp->conn_drain_prev == NULL) {
26029 		/* This conn is currently not in the drain list.  */
26030 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26031 		return;
26032 	}
26033 	idl = connp->conn_idl;
26034 	if (idl->idl_conn_draining == connp) {
26035 		/*
26036 		 * This conn is the current drainer. If this is the last conn
26037 		 * in the drain list, we need to do more checks, in the 'if'
26038 		 * below. Otherwwise we need to just qenable the next conn,
26039 		 * to sustain the draining, and is handled in the 'else'
26040 		 * below.
26041 		 */
26042 		if (connp->conn_drain_next == idl->idl_conn) {
26043 			/*
26044 			 * This conn is the last in this list. This round
26045 			 * of draining is complete. If idl_repeat is set,
26046 			 * it means another flow enabling has happened from
26047 			 * the driver/streams and we need to another round
26048 			 * of draining.
26049 			 * If there are more than 2 conns in the drain list,
26050 			 * do a left rotate by 1, so that all conns except the
26051 			 * conn at the head move towards the head by 1, and the
26052 			 * the conn at the head goes to the tail. This attempts
26053 			 * a more even share for all queues that are being
26054 			 * drained.
26055 			 */
26056 			if ((connp->conn_drain_next != connp) &&
26057 			    (idl->idl_conn->conn_drain_next != connp)) {
26058 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26059 			}
26060 			if (idl->idl_repeat) {
26061 				qenable(idl->idl_conn->conn_wq);
26062 				idl->idl_conn_draining = idl->idl_conn;
26063 				idl->idl_repeat = 0;
26064 			} else {
26065 				idl->idl_conn_draining = NULL;
26066 			}
26067 		} else {
26068 			/*
26069 			 * If the next queue that we are now qenable'ing,
26070 			 * is closing, it will remove itself from this list
26071 			 * and qenable the subsequent queue in ip_close().
26072 			 * Serialization is acheived thru idl_lock.
26073 			 */
26074 			qenable(connp->conn_drain_next->conn_wq);
26075 			idl->idl_conn_draining = connp->conn_drain_next;
26076 		}
26077 	}
26078 	if (!connp->conn_did_putbq || closing) {
26079 		/*
26080 		 * Remove ourself from the drain list, if we did not do
26081 		 * a putbq, or if the conn is closing.
26082 		 * Note: It is possible that q->q_first is non-null. It means
26083 		 * that these messages landed after we did a enableok() in
26084 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26085 		 * service them.
26086 		 */
26087 		if (connp->conn_drain_next == connp) {
26088 			/* Singleton in the list */
26089 			ASSERT(connp->conn_drain_prev == connp);
26090 			idl->idl_conn = NULL;
26091 			idl->idl_conn_draining = NULL;
26092 		} else {
26093 			connp->conn_drain_prev->conn_drain_next =
26094 			    connp->conn_drain_next;
26095 			connp->conn_drain_next->conn_drain_prev =
26096 			    connp->conn_drain_prev;
26097 			if (idl->idl_conn == connp)
26098 				idl->idl_conn = connp->conn_drain_next;
26099 			ASSERT(idl->idl_conn_draining != connp);
26100 
26101 		}
26102 		connp->conn_drain_next = NULL;
26103 		connp->conn_drain_prev = NULL;
26104 	}
26105 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26106 }
26107 
26108 /*
26109  * Write service routine. Shared perimeter entry point.
26110  * ip_wsrv can be called in any of the following ways.
26111  * 1. The device queue's messages has fallen below the low water mark
26112  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26113  *    the drain lists and backenable the first conn in each list.
26114  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
26115  *    qenabled non-tcp upper layers. We start dequeing messages and call
26116  *    ip_wput for each message.
26117  */
26118 
26119 void
26120 ip_wsrv(queue_t *q)
26121 {
26122 	conn_t	*connp;
26123 	ill_t	*ill;
26124 	mblk_t	*mp;
26125 
26126 	if (q->q_next) {
26127 		ill = (ill_t *)q->q_ptr;
26128 		if (ill->ill_state_flags == 0) {
26129 			/*
26130 			 * The device flow control has opened up.
26131 			 * Walk through conn drain lists and qenable the
26132 			 * first conn in each list. This makes sense only
26133 			 * if the stream is fully plumbed and setup.
26134 			 * Hence the if check above.
26135 			 */
26136 			ip1dbg(("ip_wsrv: walking\n"));
26137 			conn_walk_drain();
26138 		}
26139 		return;
26140 	}
26141 
26142 	connp = Q_TO_CONN(q);
26143 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
26144 
26145 	/*
26146 	 * 1. Set conn_draining flag to signal that service is active.
26147 	 *
26148 	 * 2. ip_output determines whether it has been called from service,
26149 	 *    based on the last parameter. If it is IP_WSRV it concludes it
26150 	 *    has been called from service.
26151 	 *
26152 	 * 3. Message ordering is preserved by the following logic.
26153 	 *    i. A directly called ip_output (i.e. not thru service) will queue
26154 	 *    the message at the tail, if conn_draining is set (i.e. service
26155 	 *    is running) or if q->q_first is non-null.
26156 	 *
26157 	 *    ii. If ip_output is called from service, and if ip_output cannot
26158 	 *    putnext due to flow control, it does a putbq.
26159 	 *
26160 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
26161 	 *    (causing an infinite loop).
26162 	 */
26163 	ASSERT(!connp->conn_did_putbq);
26164 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
26165 		connp->conn_draining = 1;
26166 		noenable(q);
26167 		while ((mp = getq(q)) != NULL) {
26168 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
26169 			if (connp->conn_did_putbq) {
26170 				/* ip_wput did a putbq */
26171 				break;
26172 			}
26173 		}
26174 		/*
26175 		 * At this point, a thread coming down from top, calling
26176 		 * ip_wput, may end up queueing the message. We have not yet
26177 		 * enabled the queue, so ip_wsrv won't be called again.
26178 		 * To avoid this race, check q->q_first again (in the loop)
26179 		 * If the other thread queued the message before we call
26180 		 * enableok(), we will catch it in the q->q_first check.
26181 		 * If the other thread queues the message after we call
26182 		 * enableok(), ip_wsrv will be called again by STREAMS.
26183 		 */
26184 		connp->conn_draining = 0;
26185 		enableok(q);
26186 	}
26187 
26188 	/* Enable the next conn for draining */
26189 	conn_drain_tail(connp, B_FALSE);
26190 
26191 	connp->conn_did_putbq = 0;
26192 }
26193 
26194 /*
26195  * Walk the list of all conn's calling the function provided with the
26196  * specified argument for each.	 Note that this only walks conn's that
26197  * have been bound.
26198  * Applies to both IPv4 and IPv6.
26199  */
26200 static void
26201 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
26202 {
26203 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
26204 	    func, arg, zoneid);
26205 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
26206 	    func, arg, zoneid);
26207 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
26208 	    func, arg, zoneid);
26209 	conn_walk_fanout_table(ipcl_proto_fanout,
26210 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
26211 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
26212 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
26213 }
26214 
26215 /*
26216  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
26217  * of conns that need to be drained, check if drain is already in progress.
26218  * If so set the idl_repeat bit, indicating that the last conn in the list
26219  * needs to reinitiate the drain once again, for the list. If drain is not
26220  * in progress for the list, initiate the draining, by qenabling the 1st
26221  * conn in the list. The drain is self-sustaining, each qenabled conn will
26222  * in turn qenable the next conn, when it is done/blocked/closing.
26223  */
26224 static void
26225 conn_walk_drain(void)
26226 {
26227 	int i;
26228 	idl_t *idl;
26229 
26230 	IP_STAT(ip_conn_walk_drain);
26231 
26232 	for (i = 0; i < conn_drain_list_cnt; i++) {
26233 		idl = &conn_drain_list[i];
26234 		mutex_enter(&idl->idl_lock);
26235 		if (idl->idl_conn == NULL) {
26236 			mutex_exit(&idl->idl_lock);
26237 			continue;
26238 		}
26239 		/*
26240 		 * If this list is not being drained currently by
26241 		 * an ip_wsrv thread, start the process.
26242 		 */
26243 		if (idl->idl_conn_draining == NULL) {
26244 			ASSERT(idl->idl_repeat == 0);
26245 			qenable(idl->idl_conn->conn_wq);
26246 			idl->idl_conn_draining = idl->idl_conn;
26247 		} else {
26248 			idl->idl_repeat = 1;
26249 		}
26250 		mutex_exit(&idl->idl_lock);
26251 	}
26252 }
26253 
26254 /*
26255  * Walk an conn hash table of `count' buckets, calling func for each entry.
26256  */
26257 static void
26258 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
26259     zoneid_t zoneid)
26260 {
26261 	conn_t	*connp;
26262 
26263 	while (count-- > 0) {
26264 		mutex_enter(&connfp->connf_lock);
26265 		for (connp = connfp->connf_head; connp != NULL;
26266 		    connp = connp->conn_next) {
26267 			if (zoneid == GLOBAL_ZONEID ||
26268 			    zoneid == connp->conn_zoneid) {
26269 				CONN_INC_REF(connp);
26270 				mutex_exit(&connfp->connf_lock);
26271 				(*func)(connp, arg);
26272 				mutex_enter(&connfp->connf_lock);
26273 				CONN_DEC_REF(connp);
26274 			}
26275 		}
26276 		mutex_exit(&connfp->connf_lock);
26277 		connfp++;
26278 	}
26279 }
26280 
26281 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
26282 static void
26283 conn_report1(conn_t *connp, void *mp)
26284 {
26285 	char	buf1[INET6_ADDRSTRLEN];
26286 	char	buf2[INET6_ADDRSTRLEN];
26287 	uint_t	print_len, buf_len;
26288 
26289 	ASSERT(connp != NULL);
26290 
26291 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
26292 	if (buf_len <= 0)
26293 		return;
26294 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
26295 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
26296 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
26297 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
26298 	    "%5d %s/%05d %s/%05d\n",
26299 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
26300 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
26301 	    buf1, connp->conn_lport,
26302 	    buf2, connp->conn_fport);
26303 	if (print_len < buf_len) {
26304 		((mblk_t *)mp)->b_wptr += print_len;
26305 	} else {
26306 		((mblk_t *)mp)->b_wptr += buf_len;
26307 	}
26308 }
26309 
26310 /*
26311  * Named Dispatch routine to produce a formatted report on all conns
26312  * that are listed in one of the fanout tables.
26313  * This report is accessed by using the ndd utility to "get" ND variable
26314  * "ip_conn_status".
26315  */
26316 /* ARGSUSED */
26317 static int
26318 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
26319 {
26320 	(void) mi_mpprintf(mp,
26321 	    "CONN      " MI_COL_HDRPAD_STR
26322 	    "rfq      " MI_COL_HDRPAD_STR
26323 	    "stq      " MI_COL_HDRPAD_STR
26324 	    " zone local                 remote");
26325 
26326 	/*
26327 	 * Because of the ndd constraint, at most we can have 64K buffer
26328 	 * to put in all conn info.  So to be more efficient, just
26329 	 * allocate a 64K buffer here, assuming we need that large buffer.
26330 	 * This should be OK as only privileged processes can do ndd /dev/ip.
26331 	 */
26332 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
26333 		/* The following may work even if we cannot get a large buf. */
26334 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
26335 		return (0);
26336 	}
26337 
26338 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
26339 	return (0);
26340 }
26341 
26342 /*
26343  * Determine if the ill and multicast aspects of that packets
26344  * "matches" the conn.
26345  */
26346 boolean_t
26347 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
26348     zoneid_t zoneid)
26349 {
26350 	ill_t *in_ill;
26351 	boolean_t found;
26352 	ipif_t *ipif;
26353 	ire_t *ire;
26354 	ipaddr_t dst, src;
26355 
26356 	dst = ipha->ipha_dst;
26357 	src = ipha->ipha_src;
26358 
26359 	/*
26360 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
26361 	 * unicast, broadcast and multicast reception to
26362 	 * conn_incoming_ill. conn_wantpacket itself is called
26363 	 * only for BROADCAST and multicast.
26364 	 *
26365 	 * 1) ip_rput supresses duplicate broadcasts if the ill
26366 	 *    is part of a group. Hence, we should be receiving
26367 	 *    just one copy of broadcast for the whole group.
26368 	 *    Thus, if it is part of the group the packet could
26369 	 *    come on any ill of the group and hence we need a
26370 	 *    match on the group. Otherwise, match on ill should
26371 	 *    be sufficient.
26372 	 *
26373 	 * 2) ip_rput does not suppress duplicate multicast packets.
26374 	 *    If there are two interfaces in a ill group and we have
26375 	 *    2 applications (conns) joined a multicast group G on
26376 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
26377 	 *    will give us two packets because we join G on both the
26378 	 *    interfaces rather than nominating just one interface
26379 	 *    for receiving multicast like broadcast above. So,
26380 	 *    we have to call ilg_lookup_ill to filter out duplicate
26381 	 *    copies, if ill is part of a group.
26382 	 */
26383 	in_ill = connp->conn_incoming_ill;
26384 	if (in_ill != NULL) {
26385 		if (in_ill->ill_group == NULL) {
26386 			if (in_ill != ill)
26387 				return (B_FALSE);
26388 		} else if (in_ill->ill_group != ill->ill_group) {
26389 			return (B_FALSE);
26390 		}
26391 	}
26392 
26393 	if (!CLASSD(dst)) {
26394 		if (IPCL_ZONE_MATCH(connp, zoneid))
26395 			return (B_TRUE);
26396 		/*
26397 		 * The conn is in a different zone; we need to check that this
26398 		 * broadcast address is configured in the application's zone and
26399 		 * on one ill in the group.
26400 		 */
26401 		ipif = ipif_get_next_ipif(NULL, ill);
26402 		if (ipif == NULL)
26403 			return (B_FALSE);
26404 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
26405 		    connp->conn_zoneid, NULL,
26406 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
26407 		ipif_refrele(ipif);
26408 		if (ire != NULL) {
26409 			ire_refrele(ire);
26410 			return (B_TRUE);
26411 		} else {
26412 			return (B_FALSE);
26413 		}
26414 	}
26415 
26416 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
26417 	    connp->conn_zoneid == zoneid) {
26418 		/*
26419 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
26420 		 * disabled, therefore we don't dispatch the multicast packet to
26421 		 * the sending zone.
26422 		 */
26423 		return (B_FALSE);
26424 	}
26425 
26426 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
26427 	    connp->conn_zoneid != zoneid) {
26428 		/*
26429 		 * Multicast packet on the loopback interface: we only match
26430 		 * conns who joined the group in the specified zone.
26431 		 */
26432 		return (B_FALSE);
26433 	}
26434 
26435 	if (connp->conn_multi_router) {
26436 		/* multicast packet and multicast router socket: send up */
26437 		return (B_TRUE);
26438 	}
26439 
26440 	mutex_enter(&connp->conn_lock);
26441 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
26442 	mutex_exit(&connp->conn_lock);
26443 	return (found);
26444 }
26445 
26446 /*
26447  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
26448  */
26449 /* ARGSUSED */
26450 static void
26451 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
26452 {
26453 	ill_t *ill = (ill_t *)q->q_ptr;
26454 	mblk_t	*mp1, *mp2;
26455 	ipif_t  *ipif;
26456 	int err = 0;
26457 	conn_t *connp = NULL;
26458 	ipsq_t	*ipsq;
26459 	arc_t	*arc;
26460 
26461 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
26462 
26463 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
26464 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
26465 
26466 	ASSERT(IAM_WRITER_ILL(ill));
26467 	mp2 = mp->b_cont;
26468 	mp->b_cont = NULL;
26469 
26470 	/*
26471 	 * We have now received the arp bringup completion message
26472 	 * from ARP. Mark the arp bringup as done. Also if the arp
26473 	 * stream has already started closing, send up the AR_ARP_CLOSING
26474 	 * ack now since ARP is waiting in close for this ack.
26475 	 */
26476 	mutex_enter(&ill->ill_lock);
26477 	ill->ill_arp_bringup_pending = 0;
26478 	if (ill->ill_arp_closing) {
26479 		mutex_exit(&ill->ill_lock);
26480 		/* Let's reuse the mp for sending the ack */
26481 		arc = (arc_t *)mp->b_rptr;
26482 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
26483 		arc->arc_cmd = AR_ARP_CLOSING;
26484 		qreply(q, mp);
26485 	} else {
26486 		mutex_exit(&ill->ill_lock);
26487 		freeb(mp);
26488 	}
26489 
26490 	/* We should have an IOCTL waiting on this. */
26491 	ipsq = ill->ill_phyint->phyint_ipsq;
26492 	ipif = ipsq->ipsq_pending_ipif;
26493 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
26494 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
26495 	if (mp1 == NULL) {
26496 		/* bringup was aborted by the user */
26497 		freemsg(mp2);
26498 		return;
26499 	}
26500 	ASSERT(connp != NULL);
26501 	q = CONNP_TO_WQ(connp);
26502 	/*
26503 	 * If the DL_BIND_REQ fails, it is noted
26504 	 * in arc_name_offset.
26505 	 */
26506 	err = *((int *)mp2->b_rptr);
26507 	if (err == 0) {
26508 		if (ipif->ipif_isv6) {
26509 			if ((err = ipif_up_done_v6(ipif)) != 0)
26510 				ip0dbg(("ip_arp_done: init failed\n"));
26511 		} else {
26512 			if ((err = ipif_up_done(ipif)) != 0)
26513 				ip0dbg(("ip_arp_done: init failed\n"));
26514 		}
26515 	} else {
26516 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
26517 	}
26518 
26519 	freemsg(mp2);
26520 
26521 	if ((err == 0) && (ill->ill_up_ipifs)) {
26522 		err = ill_up_ipifs(ill, q, mp1);
26523 		if (err == EINPROGRESS)
26524 			return;
26525 	}
26526 
26527 	if (ill->ill_up_ipifs) {
26528 		ill_group_cleanup(ill);
26529 	}
26530 
26531 	/*
26532 	 * The ioctl must complete now without EINPROGRESS
26533 	 * since ipsq_pending_mp_get has removed the ioctl mblk
26534 	 * from ipsq_pending_mp. Otherwise the ioctl will be
26535 	 * stuck for ever in the ipsq.
26536 	 */
26537 	ASSERT(err != EINPROGRESS);
26538 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
26539 }
26540 
26541 /* Allocate the private structure */
26542 static int
26543 ip_priv_alloc(void **bufp)
26544 {
26545 	void	*buf;
26546 
26547 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
26548 		return (ENOMEM);
26549 
26550 	*bufp = buf;
26551 	return (0);
26552 }
26553 
26554 /* Function to delete the private structure */
26555 void
26556 ip_priv_free(void *buf)
26557 {
26558 	ASSERT(buf != NULL);
26559 	kmem_free(buf, sizeof (ip_priv_t));
26560 }
26561 
26562 /*
26563  * The entry point for IPPF processing.
26564  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
26565  * routine just returns.
26566  *
26567  * When called, ip_process generates an ipp_packet_t structure
26568  * which holds the state information for this packet and invokes the
26569  * the classifier (via ipp_packet_process). The classification, depending on
26570  * configured filters, results in a list of actions for this packet. Invoking
26571  * an action may cause the packet to be dropped, in which case the resulting
26572  * mblk (*mpp) is NULL. proc indicates the callout position for
26573  * this packet and ill_index is the interface this packet on or will leave
26574  * on (inbound and outbound resp.).
26575  */
26576 void
26577 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
26578 {
26579 	mblk_t		*mp;
26580 	ip_priv_t	*priv;
26581 	ipp_action_id_t	aid;
26582 	int		rc = 0;
26583 	ipp_packet_t	*pp;
26584 #define	IP_CLASS	"ip"
26585 
26586 	/* If the classifier is not loaded, return  */
26587 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
26588 		return;
26589 	}
26590 
26591 	mp = *mpp;
26592 	ASSERT(mp != NULL);
26593 
26594 	/* Allocate the packet structure */
26595 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
26596 	if (rc != 0) {
26597 		*mpp = NULL;
26598 		freemsg(mp);
26599 		return;
26600 	}
26601 
26602 	/* Allocate the private structure */
26603 	rc = ip_priv_alloc((void **)&priv);
26604 	if (rc != 0) {
26605 		*mpp = NULL;
26606 		freemsg(mp);
26607 		ipp_packet_free(pp);
26608 		return;
26609 	}
26610 	priv->proc = proc;
26611 	priv->ill_index = ill_index;
26612 	ipp_packet_set_private(pp, priv, ip_priv_free);
26613 	ipp_packet_set_data(pp, mp);
26614 
26615 	/* Invoke the classifier */
26616 	rc = ipp_packet_process(&pp);
26617 	if (pp != NULL) {
26618 		mp = ipp_packet_get_data(pp);
26619 		ipp_packet_free(pp);
26620 		if (rc != 0) {
26621 			freemsg(mp);
26622 			*mpp = NULL;
26623 		}
26624 	} else {
26625 		*mpp = NULL;
26626 	}
26627 #undef	IP_CLASS
26628 }
26629 
26630 /*
26631  * Propagate a multicast group membership operation (add/drop) on
26632  * all the interfaces crossed by the related multirt routes.
26633  * The call is considered successful if the operation succeeds
26634  * on at least one interface.
26635  */
26636 static int
26637 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
26638     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
26639     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
26640     mblk_t *first_mp)
26641 {
26642 	ire_t		*ire_gw;
26643 	irb_t		*irb;
26644 	int		error = 0;
26645 	opt_restart_t	*or;
26646 
26647 	irb = ire->ire_bucket;
26648 	ASSERT(irb != NULL);
26649 
26650 	ASSERT(DB_TYPE(first_mp) == M_CTL);
26651 
26652 	or = (opt_restart_t *)first_mp->b_rptr;
26653 	IRB_REFHOLD(irb);
26654 	for (; ire != NULL; ire = ire->ire_next) {
26655 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
26656 			continue;
26657 		if (ire->ire_addr != group)
26658 			continue;
26659 
26660 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
26661 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
26662 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
26663 		/* No resolver exists for the gateway; skip this ire. */
26664 		if (ire_gw == NULL)
26665 			continue;
26666 
26667 		/*
26668 		 * This function can return EINPROGRESS. If so the operation
26669 		 * will be restarted from ip_restart_optmgmt which will
26670 		 * call ip_opt_set and option processing will restart for
26671 		 * this option. So we may end up calling 'fn' more than once.
26672 		 * This requires that 'fn' is idempotent except for the
26673 		 * return value. The operation is considered a success if
26674 		 * it succeeds at least once on any one interface.
26675 		 */
26676 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
26677 		    NULL, fmode, src, first_mp);
26678 		if (error == 0)
26679 			or->or_private = CGTP_MCAST_SUCCESS;
26680 
26681 		if (ip_debug > 0) {
26682 			ulong_t	off;
26683 			char	*ksym;
26684 			ksym = kobj_getsymname((uintptr_t)fn, &off);
26685 			ip2dbg(("ip_multirt_apply_membership: "
26686 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
26687 			    "error %d [success %u]\n",
26688 			    ksym ? ksym : "?",
26689 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
26690 			    error, or->or_private));
26691 		}
26692 
26693 		ire_refrele(ire_gw);
26694 		if (error == EINPROGRESS) {
26695 			IRB_REFRELE(irb);
26696 			return (error);
26697 		}
26698 	}
26699 	IRB_REFRELE(irb);
26700 	/*
26701 	 * Consider the call as successful if we succeeded on at least
26702 	 * one interface. Otherwise, return the last encountered error.
26703 	 */
26704 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
26705 }
26706 
26707 
26708 /*
26709  * Issue a warning regarding a route crossing an interface with an
26710  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
26711  * amount of time is logged.
26712  */
26713 static void
26714 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
26715 {
26716 	hrtime_t	current = gethrtime();
26717 	char		buf[16];
26718 
26719 	/* Convert interval in ms to hrtime in ns */
26720 	if (multirt_bad_mtu_last_time +
26721 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
26722 	    current) {
26723 		cmn_err(CE_WARN, "ip: ignoring multiroute "
26724 		    "to %s, incorrect MTU %u (expected %u)\n",
26725 		    ip_dot_addr(ire->ire_addr, buf),
26726 		    ire->ire_max_frag, max_frag);
26727 
26728 		multirt_bad_mtu_last_time = current;
26729 	}
26730 }
26731 
26732 
26733 /*
26734  * Get the CGTP (multirouting) filtering status.
26735  * If 0, the CGTP hooks are transparent.
26736  */
26737 /* ARGSUSED */
26738 static int
26739 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
26740 {
26741 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26742 
26743 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
26744 	return (0);
26745 }
26746 
26747 
26748 /*
26749  * Set the CGTP (multirouting) filtering status.
26750  * If the status is changed from active to transparent
26751  * or from transparent to active, forward the new status
26752  * to the filtering module (if loaded).
26753  */
26754 /* ARGSUSED */
26755 static int
26756 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
26757     cred_t *ioc_cr)
26758 {
26759 	long		new_value;
26760 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26761 
26762 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
26763 	    new_value < 0 || new_value > 1) {
26764 		return (EINVAL);
26765 	}
26766 
26767 	/*
26768 	 * Do not enable CGTP filtering - thus preventing the hooks
26769 	 * from being invoked - if the version number of the
26770 	 * filtering module hooks does not match.
26771 	 */
26772 	if ((ip_cgtp_filter_ops != NULL) &&
26773 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
26774 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
26775 		    "(module hooks version %d, expecting %d)\n",
26776 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
26777 		return (ENOTSUP);
26778 	}
26779 
26780 	if ((!*ip_cgtp_filter_value) && new_value) {
26781 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
26782 		    ip_cgtp_filter_ops == NULL ?
26783 		    " (module not loaded)" : "");
26784 	}
26785 	if (*ip_cgtp_filter_value && (!new_value)) {
26786 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
26787 		    ip_cgtp_filter_ops == NULL ?
26788 		    " (module not loaded)" : "");
26789 	}
26790 
26791 	if (ip_cgtp_filter_ops != NULL) {
26792 		int	res;
26793 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
26794 			return (res);
26795 		}
26796 	}
26797 
26798 	*ip_cgtp_filter_value = (boolean_t)new_value;
26799 
26800 	return (0);
26801 }
26802 
26803 
26804 /*
26805  * Return the expected CGTP hooks version number.
26806  */
26807 int
26808 ip_cgtp_filter_supported(void)
26809 {
26810 	return (ip_cgtp_filter_rev);
26811 }
26812 
26813 
26814 /*
26815  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
26816  * or by invoking this function. In the first case, the version number
26817  * of the registered structure is checked at hooks activation time
26818  * in ip_cgtp_filter_set().
26819  */
26820 int
26821 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
26822 {
26823 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
26824 		return (ENOTSUP);
26825 
26826 	ip_cgtp_filter_ops = ops;
26827 	return (0);
26828 }
26829 
26830 static squeue_func_t
26831 ip_squeue_switch(int val)
26832 {
26833 	squeue_func_t rval = squeue_fill;
26834 
26835 	switch (val) {
26836 	case IP_SQUEUE_ENTER_NODRAIN:
26837 		rval = squeue_enter_nodrain;
26838 		break;
26839 	case IP_SQUEUE_ENTER:
26840 		rval = squeue_enter;
26841 		break;
26842 	default:
26843 		break;
26844 	}
26845 	return (rval);
26846 }
26847 
26848 /* ARGSUSED */
26849 static int
26850 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
26851     caddr_t addr, cred_t *cr)
26852 {
26853 	int *v = (int *)addr;
26854 	long new_value;
26855 
26856 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26857 		return (EINVAL);
26858 
26859 	ip_input_proc = ip_squeue_switch(new_value);
26860 	*v = new_value;
26861 	return (0);
26862 }
26863 
26864 /* ARGSUSED */
26865 static int
26866 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26867     caddr_t addr, cred_t *cr)
26868 {
26869 	int *v = (int *)addr;
26870 	long new_value;
26871 
26872 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26873 		return (EINVAL);
26874 
26875 	*v = new_value;
26876 	return (0);
26877 }
26878 
26879 static void
26880 ip_kstat_init(void)
26881 {
26882 	ip_named_kstat_t template = {
26883 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26884 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26885 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26886 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26887 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26888 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26889 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26890 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26891 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26892 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26893 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26894 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26895 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26896 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26897 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26898 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26899 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26900 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26901 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26902 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26903 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26904 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26905 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26906 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26907 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26908 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26909 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26910 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26911 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26912 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26913 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26914 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26915 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26916 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26917 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26918 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26919 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26920 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26921 	};
26922 
26923 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26924 					NUM_OF_FIELDS(ip_named_kstat_t),
26925 					0);
26926 	if (!ip_mibkp)
26927 		return;
26928 
26929 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26930 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26931 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26932 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26933 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26934 
26935 	template.netToMediaEntrySize.value.i32 =
26936 		sizeof (mib2_ipNetToMediaEntry_t);
26937 
26938 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26939 
26940 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26941 
26942 	ip_mibkp->ks_update = ip_kstat_update;
26943 
26944 	kstat_install(ip_mibkp);
26945 }
26946 
26947 static void
26948 ip_kstat_fini(void)
26949 {
26950 
26951 	if (ip_mibkp != NULL) {
26952 		kstat_delete(ip_mibkp);
26953 		ip_mibkp = NULL;
26954 	}
26955 }
26956 
26957 static int
26958 ip_kstat_update(kstat_t *kp, int rw)
26959 {
26960 	ip_named_kstat_t *ipkp;
26961 
26962 	if (!kp || !kp->ks_data)
26963 		return (EIO);
26964 
26965 	if (rw == KSTAT_WRITE)
26966 		return (EACCES);
26967 
26968 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26969 
26970 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26971 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26972 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26973 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26974 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26975 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26976 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26977 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26978 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26979 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26980 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26981 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26982 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26983 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26984 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26985 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26986 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26987 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
26988 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
26989 
26990 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
26991 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
26992 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
26993 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
26994 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
26995 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
26996 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
26997 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
26998 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
26999 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
27000 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
27001 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
27002 
27003 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
27004 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
27005 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
27006 
27007 	return (0);
27008 }
27009 
27010 static void
27011 icmp_kstat_init(void)
27012 {
27013 	icmp_named_kstat_t template = {
27014 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27015 		{ "inErrors",		KSTAT_DATA_UINT32 },
27016 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27017 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27018 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27019 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27020 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27021 		{ "inEchos",		KSTAT_DATA_UINT32 },
27022 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27023 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27024 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27025 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27026 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27027 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27028 		{ "outErrors",		KSTAT_DATA_UINT32 },
27029 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27030 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27031 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27032 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27033 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27034 		{ "outEchos",		KSTAT_DATA_UINT32 },
27035 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27036 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27037 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27038 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27039 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27040 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27041 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27042 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27043 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27044 		{ "outDrops",		KSTAT_DATA_UINT32 },
27045 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27046 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27047 	};
27048 
27049 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27050 					NUM_OF_FIELDS(icmp_named_kstat_t),
27051 					0);
27052 	if (icmp_mibkp == NULL)
27053 		return;
27054 
27055 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27056 
27057 	icmp_mibkp->ks_update = icmp_kstat_update;
27058 
27059 	kstat_install(icmp_mibkp);
27060 }
27061 
27062 static void
27063 icmp_kstat_fini(void)
27064 {
27065 
27066 	if (icmp_mibkp != NULL) {
27067 		kstat_delete(icmp_mibkp);
27068 		icmp_mibkp = NULL;
27069 	}
27070 }
27071 
27072 static int
27073 icmp_kstat_update(kstat_t *kp, int rw)
27074 {
27075 	icmp_named_kstat_t *icmpkp;
27076 
27077 	if ((kp == NULL) || (kp->ks_data == NULL))
27078 		return (EIO);
27079 
27080 	if (rw == KSTAT_WRITE)
27081 		return (EACCES);
27082 
27083 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27084 
27085 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27086 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27087 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27088 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27089 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27090 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27091 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27092 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27093 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27094 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27095 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27096 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27097 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27098 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27099 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27100 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27101 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27102 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27103 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27104 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27105 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27106 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27107 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27108 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27109 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27110 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27111 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27112 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27113 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27114 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
27115 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
27116 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
27117 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
27118 
27119 	return (0);
27120 }
27121 
27122 /*
27123  * This is the fanout function for raw socket opened for SCTP.  Note
27124  * that it is called after SCTP checks that there is no socket which
27125  * wants a packet.  Then before SCTP handles this out of the blue packet,
27126  * this function is called to see if there is any raw socket for SCTP.
27127  * If there is and it is bound to the correct address, the packet will
27128  * be sent to that socket.  Note that only one raw socket can be bound to
27129  * a port.  This is assured in ipcl_sctp_hash_insert();
27130  */
27131 void
27132 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
27133     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
27134     uint_t ipif_seqid, zoneid_t zoneid)
27135 {
27136 	conn_t		*connp;
27137 	queue_t		*rq;
27138 	mblk_t		*first_mp;
27139 	boolean_t	secure;
27140 	ip6_t		*ip6h;
27141 
27142 	first_mp = mp;
27143 	if (mctl_present) {
27144 		mp = first_mp->b_cont;
27145 		secure = ipsec_in_is_secure(first_mp);
27146 		ASSERT(mp != NULL);
27147 	} else {
27148 		secure = B_FALSE;
27149 	}
27150 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
27151 
27152 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
27153 	if (connp == NULL) {
27154 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
27155 		    mctl_present);
27156 		return;
27157 	}
27158 	rq = connp->conn_rq;
27159 	if (!canputnext(rq)) {
27160 		CONN_DEC_REF(connp);
27161 		BUMP_MIB(&ip_mib, rawipInOverflows);
27162 		freemsg(first_mp);
27163 		return;
27164 	}
27165 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
27166 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
27167 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
27168 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
27169 		if (first_mp == NULL) {
27170 			CONN_DEC_REF(connp);
27171 			return;
27172 		}
27173 	}
27174 	/*
27175 	 * We probably should not send M_CTL message up to
27176 	 * raw socket.
27177 	 */
27178 	if (mctl_present)
27179 		freeb(first_mp);
27180 
27181 	/* Initiate IPPF processing here if needed. */
27182 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
27183 	    (!isv4 && IP6_IN_IPP(flags))) {
27184 		ip_process(IPP_LOCAL_IN, &mp,
27185 		    recv_ill->ill_phyint->phyint_ifindex);
27186 		if (mp == NULL) {
27187 			CONN_DEC_REF(connp);
27188 			return;
27189 		}
27190 	}
27191 
27192 	if (connp->conn_recvif || connp->conn_recvslla ||
27193 	    ((connp->conn_ipv6_recvpktinfo ||
27194 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
27195 	    (flags & IP_FF_IP6INFO))) {
27196 		int in_flags = 0;
27197 
27198 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
27199 			in_flags = IPF_RECVIF;
27200 		}
27201 		if (connp->conn_recvslla) {
27202 			in_flags |= IPF_RECVSLLA;
27203 		}
27204 		if (isv4) {
27205 			mp = ip_add_info(mp, recv_ill, in_flags);
27206 		} else {
27207 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
27208 			if (mp == NULL) {
27209 				CONN_DEC_REF(connp);
27210 				return;
27211 			}
27212 		}
27213 	}
27214 
27215 	BUMP_MIB(&ip_mib, ipInDelivers);
27216 	/*
27217 	 * We are sending the IPSEC_IN message also up. Refer
27218 	 * to comments above this function.
27219 	 */
27220 	putnext(rq, mp);
27221 	CONN_DEC_REF(connp);
27222 }
27223 
27224 /*
27225  * Martian Address Filtering [RFC 1812, Section 5.3.7]
27226  */
27227 static boolean_t
27228 ip_no_forward(ipha_t *ipha, ill_t *ill)
27229 {
27230 	ipaddr_t ip_src, ip_dst;
27231 	ire_t *src_ire = NULL;
27232 
27233 	ip_src = ntohl(ipha->ipha_src);
27234 	ip_dst = ntohl(ipha->ipha_dst);
27235 
27236 	if (ip_dst == INADDR_ANY)
27237 		goto dont_forward;
27238 
27239 	if (IN_CLASSD(ip_src))
27240 		goto dont_forward;
27241 
27242 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
27243 		goto dont_forward;
27244 
27245 	if (IN_BADCLASS(ip_dst))
27246 		goto dont_forward;
27247 
27248 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
27249 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
27250 	if (src_ire != NULL) {
27251 		ire_refrele(src_ire);
27252 		goto dont_forward;
27253 	}
27254 
27255 	return (B_FALSE);
27256 
27257 dont_forward:
27258 	if (ip_debug > 2) {
27259 		printf("ip_no_forward: dropping packet received on %s\n",
27260 		    ill->ill_name);
27261 		pr_addr_dbg("ip_no_forward: from src %s\n",
27262 		    AF_INET, &ipha->ipha_src);
27263 		pr_addr_dbg("ip_no_forward: to dst %s\n",
27264 		    AF_INET, &ipha->ipha_dst);
27265 	}
27266 	BUMP_MIB(&ip_mib, ipForwProhibits);
27267 	return (B_TRUE);
27268 }
27269 
27270 static boolean_t
27271 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
27272 {
27273 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
27274 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
27275 		if (ip_debug > 2) {
27276 			if (ill != NULL) {
27277 				printf("ip_loopback_src_or_dst: "
27278 				    "dropping packet received on %s\n",
27279 				    ill->ill_name);
27280 			} else {
27281 				printf("ip_loopback_src_or_dst: "
27282 				    "dropping packet\n");
27283 			}
27284 
27285 			pr_addr_dbg(
27286 			    "ip_loopback_src_or_dst: from src %s\n",
27287 			    AF_INET, &ipha->ipha_src);
27288 			pr_addr_dbg(
27289 			    "ip_loopback_src_or_dst: to dst %s\n",
27290 			    AF_INET, &ipha->ipha_dst);
27291 		}
27292 
27293 		BUMP_MIB(&ip_mib, ipInAddrErrors);
27294 		return (B_TRUE);
27295 	}
27296 	return (B_FALSE);
27297 }
27298 
27299 /*
27300  * Return B_TRUE if the buffers differ in length or content.
27301  * This is used for comparing extension header buffers.
27302  * Note that an extension header would be declared different
27303  * even if all that changed was the next header value in that header i.e.
27304  * what really changed is the next extension header.
27305  */
27306 boolean_t
27307 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
27308     uint_t blen)
27309 {
27310 	if (!b_valid)
27311 		blen = 0;
27312 
27313 	if (alen != blen)
27314 		return (B_TRUE);
27315 	if (alen == 0)
27316 		return (B_FALSE);	/* Both zero length */
27317 	return (bcmp(abuf, bbuf, alen));
27318 }
27319 
27320 /*
27321  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
27322  * Return B_FALSE if memory allocation fails - don't change any state!
27323  */
27324 boolean_t
27325 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27326     const void *src, uint_t srclen)
27327 {
27328 	void *dst;
27329 
27330 	if (!src_valid)
27331 		srclen = 0;
27332 
27333 	ASSERT(*dstlenp == 0);
27334 	if (src != NULL && srclen != 0) {
27335 		dst = mi_alloc(srclen, BPRI_MED);
27336 		if (dst == NULL)
27337 			return (B_FALSE);
27338 	} else {
27339 		dst = NULL;
27340 	}
27341 	if (*dstp != NULL)
27342 		mi_free(*dstp);
27343 	*dstp = dst;
27344 	*dstlenp = dst == NULL ? 0 : srclen;
27345 	return (B_TRUE);
27346 }
27347 
27348 /*
27349  * Replace what is in *dst, *dstlen with the source.
27350  * Assumes ip_allocbuf has already been called.
27351  */
27352 void
27353 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27354     const void *src, uint_t srclen)
27355 {
27356 	if (!src_valid)
27357 		srclen = 0;
27358 
27359 	ASSERT(*dstlenp == srclen);
27360 	if (src != NULL && srclen != 0)
27361 		bcopy(src, *dstp, srclen);
27362 }
27363 
27364 /*
27365  * Free the storage pointed to by the members of an ip6_pkt_t.
27366  */
27367 void
27368 ip6_pkt_free(ip6_pkt_t *ipp)
27369 {
27370 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
27371 
27372 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
27373 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
27374 		ipp->ipp_hopopts = NULL;
27375 		ipp->ipp_hopoptslen = 0;
27376 	}
27377 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
27378 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
27379 		ipp->ipp_rtdstopts = NULL;
27380 		ipp->ipp_rtdstoptslen = 0;
27381 	}
27382 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
27383 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
27384 		ipp->ipp_dstopts = NULL;
27385 		ipp->ipp_dstoptslen = 0;
27386 	}
27387 	if (ipp->ipp_fields & IPPF_RTHDR) {
27388 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
27389 		ipp->ipp_rthdr = NULL;
27390 		ipp->ipp_rthdrlen = 0;
27391 	}
27392 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
27393 	    IPPF_RTHDR);
27394 }
27395