xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 60425338a8e9a5ded7e559e227eedd42d30c8967)
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 			 * TSol note: Please see the corresponding note
8088 			 * of the IRE_IF_NORESOLVER case
8089 			 */
8090 			ga.ga_af = AF_INET;
8091 			IN6_IPADDR_TO_V4MAPPED(dst, &ga.ga_addr);
8092 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8093 
8094 			/*
8095 			 * We obtain a partial IRE_CACHE which we will pass
8096 			 * along with the resolver query.  When the response
8097 			 * comes back it will be there ready for us to add.
8098 			 * The ire_max_frag is atomically set under the
8099 			 * irebucket lock in ire_add_v[46].
8100 			 */
8101 			ire = ire_create_mp(
8102 			    (uchar_t *)&dst,		/* dest address */
8103 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8104 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8105 			    (uchar_t *)&gw,		/* gateway address */
8106 			    NULL,			/* no in_src_addr */
8107 			    NULL,			/* ire_max_frag */
8108 			    NULL,			/* Fast Path header */
8109 			    dst_ill->ill_rq,		/* recv-from queue */
8110 			    dst_ill->ill_wq,		/* send-to queue */
8111 			    IRE_CACHE,
8112 			    res_mp,
8113 			    src_ipif,			/* Interface ipif */
8114 			    in_ill,			/* Incoming ILL */
8115 			    save_ire->ire_mask,		/* Parent mask */
8116 			    0,
8117 			    save_ire->ire_ihandle,	/* Interface handle */
8118 			    0,				/* flags if any */
8119 			    &(save_ire->ire_uinfo),
8120 			    NULL,
8121 			    gcgrp);
8122 
8123 			if (ire == NULL) {
8124 				ire_refrele(save_ire);
8125 				if (gcgrp != NULL) {
8126 					GCGRP_REFRELE(gcgrp);
8127 					gcgrp = NULL;
8128 				}
8129 				break;
8130 			}
8131 
8132 			/* reference now held by IRE */
8133 			gcgrp = NULL;
8134 
8135 			if ((sire != NULL) &&
8136 			    (sire->ire_flags & RTF_MULTIRT)) {
8137 				copy_mp = copymsg(first_mp);
8138 				if (copy_mp != NULL)
8139 					MULTIRT_DEBUG_TAG(copy_mp);
8140 			}
8141 
8142 			ire->ire_marks |= ire_marks;
8143 
8144 			/*
8145 			 * Construct message chain for the resolver
8146 			 * of the form:
8147 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8148 			 * Packet could contain a IPSEC_OUT mp.
8149 			 *
8150 			 * NOTE : ire will be added later when the response
8151 			 * comes back from ARP. If the response does not
8152 			 * come back, ARP frees the packet. For this reason,
8153 			 * we can't REFHOLD the bucket of save_ire to prevent
8154 			 * deletions. We may not be able to REFRELE the bucket
8155 			 * if the response never comes back. Thus, before
8156 			 * adding the ire, ire_add_v4 will make sure that the
8157 			 * interface route does not get deleted. This is the
8158 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8159 			 * where we can always prevent deletions because of
8160 			 * the synchronous nature of adding IRES i.e
8161 			 * ire_add_then_send is called after creating the IRE.
8162 			 */
8163 			ASSERT(ire->ire_mp != NULL);
8164 			ire->ire_mp->b_cont = first_mp;
8165 			/* Have saved_mp handy, for cleanup if canput fails */
8166 			saved_mp = mp;
8167 			mp = ire->ire_dlureq_mp;
8168 			ASSERT(mp != NULL);
8169 			ire->ire_dlureq_mp = NULL;
8170 			linkb(mp, ire->ire_mp);
8171 
8172 
8173 			/*
8174 			 * Fill in the source and dest addrs for the resolver.
8175 			 * NOTE: this depends on memory layouts imposed by
8176 			 * ill_init().
8177 			 */
8178 			areq = (areq_t *)mp->b_rptr;
8179 			addrp = (ipaddr_t *)((char *)areq +
8180 			    areq->areq_sender_addr_offset);
8181 			if (do_attach_ill) {
8182 				/*
8183 				 * This is bind to no failover case.
8184 				 * arp packet also must go out on attach_ill.
8185 				 */
8186 				ASSERT(ipha->ipha_src != NULL);
8187 				*addrp = ipha->ipha_src;
8188 			} else {
8189 				*addrp = save_ire->ire_src_addr;
8190 			}
8191 
8192 			ire_refrele(save_ire);
8193 			addrp = (ipaddr_t *)((char *)areq +
8194 			    areq->areq_target_addr_offset);
8195 			*addrp = dst;
8196 			/* Up to the resolver. */
8197 			if (canputnext(dst_ill->ill_rq)) {
8198 				putnext(dst_ill->ill_rq, mp);
8199 				ire = NULL;
8200 				if (copy_mp != NULL) {
8201 					/*
8202 					 * If we found a resolver, we ignore
8203 					 * any trailing top priority IRE_CACHE
8204 					 * in the further loops. This ensures
8205 					 * that we do not omit any resolver.
8206 					 * IRE_CACHE entries, if any, will be
8207 					 * processed next time we enter
8208 					 * ip_newroute().
8209 					 */
8210 					multirt_flags &= ~MULTIRT_CACHEGW;
8211 					/*
8212 					 * Search for the next unresolved
8213 					 * multirt route.
8214 					 */
8215 					first_mp = copy_mp;
8216 					copy_mp = NULL;
8217 					/* Prepare the next resolution loop. */
8218 					mp = first_mp;
8219 					EXTRACT_PKT_MP(mp, first_mp,
8220 					    mctl_present);
8221 					if (mctl_present)
8222 						io = (ipsec_out_t *)
8223 						    first_mp->b_rptr;
8224 					ipha = (ipha_t *)mp->b_rptr;
8225 
8226 					ASSERT(sire != NULL);
8227 
8228 					dst = save_dst;
8229 					multirt_resolve_next = B_TRUE;
8230 					continue;
8231 				}
8232 
8233 				if (sire != NULL)
8234 					ire_refrele(sire);
8235 
8236 				/*
8237 				 * The response will come back in ip_wput
8238 				 * with db_type IRE_DB_TYPE.
8239 				 */
8240 				ipif_refrele(src_ipif);
8241 				ill_refrele(dst_ill);
8242 				return;
8243 			} else {
8244 				/* Prepare for cleanup */
8245 				ire->ire_dlureq_mp = mp;
8246 				mp->b_cont = NULL;
8247 				ire_delete(ire);
8248 				mp = saved_mp;
8249 				ire = NULL;
8250 				if (copy_mp != NULL) {
8251 					MULTIRT_DEBUG_UNTAG(copy_mp);
8252 					freemsg(copy_mp);
8253 					copy_mp = NULL;
8254 				}
8255 				break;
8256 			}
8257 		default:
8258 			break;
8259 		}
8260 	} while (multirt_resolve_next);
8261 
8262 	ip1dbg(("ip_newroute: dropped\n"));
8263 	/* Did this packet originate externally? */
8264 	if (mp->b_prev) {
8265 		mp->b_next = NULL;
8266 		mp->b_prev = NULL;
8267 		BUMP_MIB(&ip_mib, ipInDiscards);
8268 	} else {
8269 		BUMP_MIB(&ip_mib, ipOutDiscards);
8270 	}
8271 	ASSERT(copy_mp == NULL);
8272 	MULTIRT_DEBUG_UNTAG(first_mp);
8273 	freemsg(first_mp);
8274 	if (ire != NULL)
8275 		ire_refrele(ire);
8276 	if (sire != NULL)
8277 		ire_refrele(sire);
8278 	if (src_ipif != NULL)
8279 		ipif_refrele(src_ipif);
8280 	if (dst_ill != NULL)
8281 		ill_refrele(dst_ill);
8282 	return;
8283 
8284 icmp_err_ret:
8285 	ip1dbg(("ip_newroute: no route\n"));
8286 	if (src_ipif != NULL)
8287 		ipif_refrele(src_ipif);
8288 	if (dst_ill != NULL)
8289 		ill_refrele(dst_ill);
8290 	if (sire != NULL)
8291 		ire_refrele(sire);
8292 	/* Did this packet originate externally? */
8293 	if (mp->b_prev) {
8294 		mp->b_next = NULL;
8295 		mp->b_prev = NULL;
8296 		/* XXX ipInNoRoutes */
8297 		q = WR(q);
8298 	} else {
8299 		/*
8300 		 * Since ip_wput() isn't close to finished, we fill
8301 		 * in enough of the header for credible error reporting.
8302 		 */
8303 		if (ip_hdr_complete(ipha, zoneid)) {
8304 			/* Failed */
8305 			MULTIRT_DEBUG_UNTAG(first_mp);
8306 			freemsg(first_mp);
8307 			if (ire != NULL)
8308 				ire_refrele(ire);
8309 			return;
8310 		}
8311 	}
8312 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8313 
8314 	/*
8315 	 * At this point we will have ire only if RTF_BLACKHOLE
8316 	 * or RTF_REJECT flags are set on the IRE. It will not
8317 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8318 	 */
8319 	if (ire != NULL) {
8320 		if (ire->ire_flags & RTF_BLACKHOLE) {
8321 			ire_refrele(ire);
8322 			MULTIRT_DEBUG_UNTAG(first_mp);
8323 			freemsg(first_mp);
8324 			return;
8325 		}
8326 		ire_refrele(ire);
8327 	}
8328 	if (ip_source_routed(ipha)) {
8329 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED);
8330 		return;
8331 	}
8332 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
8333 }
8334 
8335 /*
8336  * IPv4 -
8337  * ip_newroute_ipif is called by ip_wput_multicast and
8338  * ip_rput_forward_multicast whenever we need to send
8339  * out a packet to a destination address for which we do not have specific
8340  * routing information. It is used when the packet will be sent out
8341  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8342  * socket option is set or icmp error message wants to go out on a particular
8343  * interface for a unicast packet.
8344  *
8345  * In most cases, the destination address is resolved thanks to the ipif
8346  * intrinsic resolver. However, there are some cases where the call to
8347  * ip_newroute_ipif must take into account the potential presence of
8348  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8349  * that uses the interface. This is specified through flags,
8350  * which can be a combination of:
8351  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8352  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8353  *   and flags. Additionally, the packet source address has to be set to
8354  *   the specified address. The caller is thus expected to set this flag
8355  *   if the packet has no specific source address yet.
8356  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8357  *   flag, the resulting ire will inherit the flag. All unresolved routes
8358  *   to the destination must be explored in the same call to
8359  *   ip_newroute_ipif().
8360  */
8361 static void
8362 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8363     conn_t *connp, uint32_t flags)
8364 {
8365 	areq_t	*areq;
8366 	ire_t	*ire = NULL;
8367 	mblk_t	*res_mp;
8368 	ipaddr_t *addrp;
8369 	mblk_t *first_mp;
8370 	ire_t	*save_ire = NULL;
8371 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8372 	ipif_t	*src_ipif = NULL;
8373 	ushort_t ire_marks = 0;
8374 	ill_t	*dst_ill = NULL;
8375 	boolean_t mctl_present;
8376 	ipsec_out_t *io;
8377 	ipha_t *ipha;
8378 	int	ihandle = 0;
8379 	mblk_t	*saved_mp;
8380 	ire_t   *fire = NULL;
8381 	mblk_t  *copy_mp = NULL;
8382 	boolean_t multirt_resolve_next;
8383 	ipaddr_t ipha_dst;
8384 	zoneid_t zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
8385 
8386 	/*
8387 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8388 	 * here for uniformity
8389 	 */
8390 	ipif_refhold(ipif);
8391 
8392 	/*
8393 	 * This loop is run only once in most cases.
8394 	 * We loop to resolve further routes only when the destination
8395 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8396 	 */
8397 	do {
8398 		if (dst_ill != NULL) {
8399 			ill_refrele(dst_ill);
8400 			dst_ill = NULL;
8401 		}
8402 		if (src_ipif != NULL) {
8403 			ipif_refrele(src_ipif);
8404 			src_ipif = NULL;
8405 		}
8406 		multirt_resolve_next = B_FALSE;
8407 
8408 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8409 		    ipif->ipif_ill->ill_name));
8410 
8411 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8412 		if (mctl_present)
8413 			io = (ipsec_out_t *)first_mp->b_rptr;
8414 
8415 		ipha = (ipha_t *)mp->b_rptr;
8416 
8417 		/*
8418 		 * Save the packet destination address, we may need it after
8419 		 * the packet has been consumed.
8420 		 */
8421 		ipha_dst = ipha->ipha_dst;
8422 
8423 		/*
8424 		 * If the interface is a pt-pt interface we look for an
8425 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8426 		 * local_address and the pt-pt destination address. Otherwise
8427 		 * we just match the local address.
8428 		 * NOTE: dst could be different than ipha->ipha_dst in case
8429 		 * of sending igmp multicast packets over a point-to-point
8430 		 * connection.
8431 		 * Thus we must be careful enough to check ipha_dst to be a
8432 		 * multicast address, otherwise it will take xmit_if path for
8433 		 * multicast packets resulting into kernel stack overflow by
8434 		 * repeated calls to ip_newroute_ipif from ire_send().
8435 		 */
8436 		if (CLASSD(ipha_dst) &&
8437 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8438 			goto err_ret;
8439 		}
8440 
8441 		/*
8442 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8443 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8444 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8445 		 * propagate its flags to the new ire.
8446 		 */
8447 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8448 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8449 			ip2dbg(("ip_newroute_ipif: "
8450 			    "ipif_lookup_multi_ire("
8451 			    "ipif %p, dst %08x) = fire %p\n",
8452 			    (void *)ipif, ntohl(dst), (void *)fire));
8453 		}
8454 
8455 		if (mctl_present && io->ipsec_out_attach_if) {
8456 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8457 			    io->ipsec_out_ill_index, B_FALSE);
8458 
8459 			/* Failure case frees things for us. */
8460 			if (attach_ill == NULL) {
8461 				ipif_refrele(ipif);
8462 				if (fire != NULL)
8463 					ire_refrele(fire);
8464 				return;
8465 			}
8466 
8467 			/*
8468 			 * Check if we need an ire that will not be
8469 			 * looked up by anybody else i.e. HIDDEN.
8470 			 */
8471 			if (ill_is_probeonly(attach_ill)) {
8472 				ire_marks = IRE_MARK_HIDDEN;
8473 			}
8474 			/*
8475 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8476 			 * case.
8477 			 */
8478 			dst_ill = ipif->ipif_ill;
8479 			/* attach_ill has been refheld by ip_grab_attach_ill */
8480 			ASSERT(dst_ill == attach_ill);
8481 		} else {
8482 			/*
8483 			 * If this is set by IP_XMIT_IF, then make sure that
8484 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8485 			 * specified ill.
8486 			 */
8487 			ASSERT((connp == NULL) ||
8488 			    (connp->conn_xmit_if_ill == NULL) ||
8489 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8490 			/*
8491 			 * If the interface belongs to an interface group,
8492 			 * make sure the next possible interface in the group
8493 			 * is used.  This encourages load spreading among
8494 			 * peers in an interface group.
8495 			 * Note: load spreading is disabled for RTF_MULTIRT
8496 			 * routes.
8497 			 */
8498 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8499 			    (fire->ire_flags & RTF_MULTIRT)) {
8500 				/*
8501 				 * Don't perform outbound load spreading
8502 				 * in the case of an RTF_MULTIRT issued route,
8503 				 * we actually typically want to replicate
8504 				 * outgoing packets through particular
8505 				 * interfaces.
8506 				 */
8507 				dst_ill = ipif->ipif_ill;
8508 				ill_refhold(dst_ill);
8509 			} else {
8510 				dst_ill = ip_newroute_get_dst_ill(
8511 				    ipif->ipif_ill);
8512 			}
8513 			if (dst_ill == NULL) {
8514 				if (ip_debug > 2) {
8515 					pr_addr_dbg("ip_newroute_ipif: "
8516 					    "no dst ill for dst %s\n",
8517 					    AF_INET, &dst);
8518 				}
8519 				goto err_ret;
8520 			}
8521 		}
8522 
8523 		/*
8524 		 * Pick a source address preferring non-deprecated ones.
8525 		 * Unlike ip_newroute, we don't do any source address
8526 		 * selection here since for multicast it really does not help
8527 		 * in inbound load spreading as in the unicast case.
8528 		 */
8529 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8530 		    (fire->ire_flags & RTF_SETSRC)) {
8531 			/*
8532 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8533 			 * on that interface. This ire has RTF_SETSRC flag, so
8534 			 * the source address of the packet must be changed.
8535 			 * Check that the ipif matching the requested source
8536 			 * address still exists.
8537 			 */
8538 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
8539 			    zoneid, NULL, NULL, NULL, NULL);
8540 		}
8541 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
8542 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
8543 		    ipif->ipif_zoneid != ALL_ZONES)) &&
8544 		    (src_ipif == NULL)) {
8545 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
8546 			if (src_ipif == NULL) {
8547 				if (ip_debug > 2) {
8548 					/* ip1dbg */
8549 					pr_addr_dbg("ip_newroute_ipif: "
8550 					    "no src for dst %s",
8551 					    AF_INET, &dst);
8552 				}
8553 				ip1dbg((" through interface %s\n",
8554 				    dst_ill->ill_name));
8555 				goto err_ret;
8556 			}
8557 			ipif_refrele(ipif);
8558 			ipif = src_ipif;
8559 			ipif_refhold(ipif);
8560 		}
8561 		if (src_ipif == NULL) {
8562 			src_ipif = ipif;
8563 			ipif_refhold(src_ipif);
8564 		}
8565 
8566 		/*
8567 		 * Assign a source address while we have the conn.
8568 		 * We can't have ip_wput_ire pick a source address when the
8569 		 * packet returns from arp since conn_unspec_src might be set
8570 		 * and we loose the conn when going through arp.
8571 		 */
8572 		if (ipha->ipha_src == INADDR_ANY &&
8573 		    (connp == NULL || !connp->conn_unspec_src)) {
8574 			ipha->ipha_src = src_ipif->ipif_src_addr;
8575 		}
8576 
8577 		/*
8578 		 * In case of IP_XMIT_IF, it is possible that the outgoing
8579 		 * interface does not have an interface ire.
8580 		 * Example: Thousands of mobileip PPP interfaces to mobile
8581 		 * nodes. We don't want to create interface ires because
8582 		 * packets from other mobile nodes must not take the route
8583 		 * via interface ires to the visiting mobile node without
8584 		 * going through the home agent, in absence of mobileip
8585 		 * route optimization.
8586 		 */
8587 		if (CLASSD(ipha_dst) && (connp == NULL ||
8588 		    connp->conn_xmit_if_ill == NULL)) {
8589 			/* ipif_to_ire returns an held ire */
8590 			ire = ipif_to_ire(ipif);
8591 			if (ire == NULL)
8592 				goto err_ret;
8593 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
8594 				goto err_ret;
8595 			/*
8596 			 * ihandle is needed when the ire is added to
8597 			 * cache table.
8598 			 */
8599 			save_ire = ire;
8600 			ihandle = save_ire->ire_ihandle;
8601 
8602 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
8603 			    "flags %04x\n",
8604 			    (void *)ire, (void *)ipif, flags));
8605 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8606 			    (fire->ire_flags & RTF_MULTIRT)) {
8607 				/*
8608 				 * As requested by flags, an IRE_OFFSUBNET was
8609 				 * looked up on that interface. This ire has
8610 				 * RTF_MULTIRT flag, so the resolution loop will
8611 				 * be re-entered to resolve additional routes on
8612 				 * other interfaces. For that purpose, a copy of
8613 				 * the packet is performed at this point.
8614 				 */
8615 				fire->ire_last_used_time = lbolt;
8616 				copy_mp = copymsg(first_mp);
8617 				if (copy_mp) {
8618 					MULTIRT_DEBUG_TAG(copy_mp);
8619 				}
8620 			}
8621 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
8622 			    (fire->ire_flags & RTF_SETSRC)) {
8623 				/*
8624 				 * As requested by flags, an IRE_OFFSUBET was
8625 				 * looked up on that interface. This ire has
8626 				 * RTF_SETSRC flag, so the source address of the
8627 				 * packet must be changed.
8628 				 */
8629 				ipha->ipha_src = fire->ire_src_addr;
8630 			}
8631 		} else {
8632 			ASSERT((connp == NULL) ||
8633 			    (connp->conn_xmit_if_ill != NULL) ||
8634 			    (connp->conn_dontroute));
8635 			/*
8636 			 * The only ways we can come here are:
8637 			 * 1) IP_XMIT_IF socket option is set
8638 			 * 2) ICMP error message generated from
8639 			 *    ip_mrtun_forward() routine and it needs
8640 			 *    to go through the specified ill.
8641 			 * 3) SO_DONTROUTE socket option is set
8642 			 * In all cases, the new ire will not be added
8643 			 * into cache table.
8644 			 */
8645 			ire_marks |= IRE_MARK_NOADD;
8646 		}
8647 
8648 		switch (ipif->ipif_net_type) {
8649 		case IRE_IF_NORESOLVER: {
8650 			/* We have what we need to build an IRE_CACHE. */
8651 			mblk_t	*dlureq_mp;
8652 
8653 			/*
8654 			 * Create a new dlureq_mp with the
8655 			 * IP gateway address as destination address in the
8656 			 * DLPI hdr if the physical length is exactly 4 bytes.
8657 			 */
8658 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8659 				dlureq_mp = ill_dlur_gen((uchar_t *)&dst,
8660 				    dst_ill->ill_phys_addr_length,
8661 				    dst_ill->ill_sap,
8662 				    dst_ill->ill_sap_length);
8663 			} else {
8664 				/* use the value set in ip_ll_subnet_defaults */
8665 				dlureq_mp = ill_dlur_gen(NULL,
8666 				    dst_ill->ill_phys_addr_length,
8667 				    dst_ill->ill_sap,
8668 				    dst_ill->ill_sap_length);
8669 			}
8670 
8671 			if (dlureq_mp == NULL)
8672 				break;
8673 			/*
8674 			 * The new ire inherits the IRE_OFFSUBNET flags
8675 			 * and source address, if this was requested.
8676 			 */
8677 			ire = ire_create(
8678 			    (uchar_t *)&dst,		/* dest address */
8679 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8680 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8681 			    NULL,			/* gateway address */
8682 			    NULL,
8683 			    &ipif->ipif_mtu,
8684 			    NULL,			/* Fast Path header */
8685 			    dst_ill->ill_rq,		/* recv-from queue */
8686 			    dst_ill->ill_wq,		/* send-to queue */
8687 			    IRE_CACHE,
8688 			    dlureq_mp,
8689 			    src_ipif,
8690 			    NULL,
8691 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8692 			    (fire != NULL) ?		/* Parent handle */
8693 				fire->ire_phandle : 0,
8694 			    ihandle,			/* Interface handle */
8695 			    (fire != NULL) ?
8696 				(fire->ire_flags &
8697 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8698 			    (save_ire == NULL ? &ire_uinfo_null :
8699 				&save_ire->ire_uinfo),
8700 			    NULL,
8701 			    NULL);
8702 
8703 			freeb(dlureq_mp);
8704 
8705 			if (ire == NULL) {
8706 				if (save_ire != NULL)
8707 					ire_refrele(save_ire);
8708 				break;
8709 			}
8710 
8711 			ire->ire_marks |= ire_marks;
8712 
8713 			/*
8714 			 * If IRE_MARK_NOADD is set then we need to convert
8715 			 * the max_fragp to a useable value now. This is
8716 			 * normally done in ire_add_v[46].
8717 			 */
8718 			if (ire->ire_marks & IRE_MARK_NOADD) {
8719 				uint_t  max_frag;
8720 
8721 				max_frag = *ire->ire_max_fragp;
8722 				ire->ire_max_fragp = NULL;
8723 				ire->ire_max_frag = max_frag;
8724 			}
8725 
8726 			/* Prevent save_ire from getting deleted */
8727 			if (save_ire != NULL) {
8728 				IRB_REFHOLD(save_ire->ire_bucket);
8729 				/* Has it been removed already ? */
8730 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8731 					IRB_REFRELE(save_ire->ire_bucket);
8732 					ire_refrele(save_ire);
8733 					break;
8734 				}
8735 			}
8736 
8737 			ire_add_then_send(q, ire, first_mp);
8738 
8739 			/* Assert that save_ire is not deleted yet. */
8740 			if (save_ire != NULL) {
8741 				ASSERT(save_ire->ire_ptpn != NULL);
8742 				IRB_REFRELE(save_ire->ire_bucket);
8743 				ire_refrele(save_ire);
8744 				save_ire = NULL;
8745 			}
8746 			if (fire != NULL) {
8747 				ire_refrele(fire);
8748 				fire = NULL;
8749 			}
8750 
8751 			/*
8752 			 * the resolution loop is re-entered if this
8753 			 * was requested through flags and if we
8754 			 * actually are in a multirouting case.
8755 			 */
8756 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8757 				boolean_t need_resolve =
8758 				    ire_multirt_need_resolve(ipha_dst,
8759 					MBLK_GETLABEL(copy_mp));
8760 				if (!need_resolve) {
8761 					MULTIRT_DEBUG_UNTAG(copy_mp);
8762 					freemsg(copy_mp);
8763 					copy_mp = NULL;
8764 				} else {
8765 					/*
8766 					 * ipif_lookup_group() calls
8767 					 * ire_lookup_multi() that uses
8768 					 * ire_ftable_lookup() to find
8769 					 * an IRE_INTERFACE for the group.
8770 					 * In the multirt case,
8771 					 * ire_lookup_multi() then invokes
8772 					 * ire_multirt_lookup() to find
8773 					 * the next resolvable ire.
8774 					 * As a result, we obtain an new
8775 					 * interface, derived from the
8776 					 * next ire.
8777 					 */
8778 					ipif_refrele(ipif);
8779 					ipif = ipif_lookup_group(ipha_dst,
8780 					    zoneid);
8781 					ip2dbg(("ip_newroute_ipif: "
8782 					    "multirt dst %08x, ipif %p\n",
8783 					    htonl(dst), (void *)ipif));
8784 					if (ipif != NULL) {
8785 						mp = copy_mp;
8786 						copy_mp = NULL;
8787 						multirt_resolve_next = B_TRUE;
8788 						continue;
8789 					} else {
8790 						freemsg(copy_mp);
8791 					}
8792 				}
8793 			}
8794 			if (ipif != NULL)
8795 				ipif_refrele(ipif);
8796 			ill_refrele(dst_ill);
8797 			ipif_refrele(src_ipif);
8798 			return;
8799 		}
8800 		case IRE_IF_RESOLVER:
8801 			/*
8802 			 * We can't build an IRE_CACHE yet, but at least
8803 			 * we found a resolver that can help.
8804 			 */
8805 			res_mp = dst_ill->ill_resolver_mp;
8806 			if (!OK_RESOLVER_MP(res_mp))
8807 				break;
8808 
8809 			/*
8810 			 * We obtain a partial IRE_CACHE which we will pass
8811 			 * along with the resolver query.  When the response
8812 			 * comes back it will be there ready for us to add.
8813 			 * The new ire inherits the IRE_OFFSUBNET flags
8814 			 * and source address, if this was requested.
8815 			 * The ire_max_frag is atomically set under the
8816 			 * irebucket lock in ire_add_v[46]. Only in the
8817 			 * case of IRE_MARK_NOADD, we set it here itself.
8818 			 */
8819 			ire = ire_create_mp(
8820 			    (uchar_t *)&dst,		/* dest address */
8821 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8822 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8823 			    NULL,			/* gateway address */
8824 			    NULL,			/* no in_src_addr */
8825 			    (ire_marks & IRE_MARK_NOADD) ?
8826 				ipif->ipif_mtu : 0,	/* max_frag */
8827 			    NULL,			/* Fast path header */
8828 			    dst_ill->ill_rq,		/* recv-from queue */
8829 			    dst_ill->ill_wq,		/* send-to queue */
8830 			    IRE_CACHE,
8831 			    res_mp,
8832 			    src_ipif,
8833 			    NULL,
8834 			    (save_ire != NULL ? save_ire->ire_mask : 0),
8835 			    (fire != NULL) ?		/* Parent handle */
8836 				fire->ire_phandle : 0,
8837 			    ihandle,			/* Interface handle */
8838 			    (fire != NULL) ?		/* flags if any */
8839 				(fire->ire_flags &
8840 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
8841 			    (save_ire == NULL ? &ire_uinfo_null :
8842 				&save_ire->ire_uinfo),
8843 			    NULL,
8844 			    NULL);
8845 
8846 			if (save_ire != NULL) {
8847 				ire_refrele(save_ire);
8848 				save_ire = NULL;
8849 			}
8850 			if (ire == NULL)
8851 				break;
8852 
8853 			ire->ire_marks |= ire_marks;
8854 			/*
8855 			 * Construct message chain for the resolver of the
8856 			 * form:
8857 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8858 			 *
8859 			 * NOTE : ire will be added later when the response
8860 			 * comes back from ARP. If the response does not
8861 			 * come back, ARP frees the packet. For this reason,
8862 			 * we can't REFHOLD the bucket of save_ire to prevent
8863 			 * deletions. We may not be able to REFRELE the
8864 			 * bucket if the response never comes back.
8865 			 * Thus, before adding the ire, ire_add_v4 will make
8866 			 * sure that the interface route does not get deleted.
8867 			 * This is the only case unlike ip_newroute_v6,
8868 			 * ip_newroute_ipif_v6 where we can always prevent
8869 			 * deletions because ire_add_then_send is called after
8870 			 * creating the IRE.
8871 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
8872 			 * does not add this IRE into the IRE CACHE.
8873 			 */
8874 			ASSERT(ire->ire_mp != NULL);
8875 			ire->ire_mp->b_cont = first_mp;
8876 			/* Have saved_mp handy, for cleanup if canput fails */
8877 			saved_mp = mp;
8878 			mp = ire->ire_dlureq_mp;
8879 			ASSERT(mp != NULL);
8880 			ire->ire_dlureq_mp = NULL;
8881 			linkb(mp, ire->ire_mp);
8882 
8883 			/*
8884 			 * Fill in the source and dest addrs for the resolver.
8885 			 * NOTE: this depends on memory layouts imposed by
8886 			 * ill_init().
8887 			 */
8888 			areq = (areq_t *)mp->b_rptr;
8889 			addrp = (ipaddr_t *)((char *)areq +
8890 			    areq->areq_sender_addr_offset);
8891 			*addrp = ire->ire_src_addr;
8892 			addrp = (ipaddr_t *)((char *)areq +
8893 			    areq->areq_target_addr_offset);
8894 			*addrp = dst;
8895 			/* Up to the resolver. */
8896 			if (canputnext(dst_ill->ill_rq)) {
8897 				putnext(dst_ill->ill_rq, mp);
8898 				/*
8899 				 * The response will come back in ip_wput
8900 				 * with db_type IRE_DB_TYPE.
8901 				 */
8902 			} else {
8903 				ire->ire_dlureq_mp = mp;
8904 				mp->b_cont = NULL;
8905 				ire_delete(ire);
8906 				saved_mp->b_next = NULL;
8907 				saved_mp->b_prev = NULL;
8908 				freemsg(first_mp);
8909 				ip2dbg(("ip_newroute_ipif: dropped\n"));
8910 			}
8911 
8912 			if (fire != NULL) {
8913 				ire_refrele(fire);
8914 				fire = NULL;
8915 			}
8916 
8917 
8918 			/*
8919 			 * The resolution loop is re-entered if this was
8920 			 * requested through flags and we actually are
8921 			 * in a multirouting case.
8922 			 */
8923 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
8924 				boolean_t need_resolve =
8925 				    ire_multirt_need_resolve(ipha_dst,
8926 					MBLK_GETLABEL(copy_mp));
8927 				if (!need_resolve) {
8928 					MULTIRT_DEBUG_UNTAG(copy_mp);
8929 					freemsg(copy_mp);
8930 					copy_mp = NULL;
8931 				} else {
8932 					/*
8933 					 * ipif_lookup_group() calls
8934 					 * ire_lookup_multi() that uses
8935 					 * ire_ftable_lookup() to find
8936 					 * an IRE_INTERFACE for the group.
8937 					 * In the multirt case,
8938 					 * ire_lookup_multi() then invokes
8939 					 * ire_multirt_lookup() to find
8940 					 * the next resolvable ire.
8941 					 * As a result, we obtain an new
8942 					 * interface, derived from the
8943 					 * next ire.
8944 					 */
8945 					ipif_refrele(ipif);
8946 					ipif = ipif_lookup_group(ipha_dst,
8947 					    zoneid);
8948 					if (ipif != NULL) {
8949 						mp = copy_mp;
8950 						copy_mp = NULL;
8951 						multirt_resolve_next = B_TRUE;
8952 						continue;
8953 					} else {
8954 						freemsg(copy_mp);
8955 					}
8956 				}
8957 			}
8958 			if (ipif != NULL)
8959 				ipif_refrele(ipif);
8960 			ill_refrele(dst_ill);
8961 			ipif_refrele(src_ipif);
8962 			return;
8963 		default:
8964 			break;
8965 		}
8966 	} while (multirt_resolve_next);
8967 
8968 err_ret:
8969 	ip2dbg(("ip_newroute_ipif: dropped\n"));
8970 	if (fire != NULL)
8971 		ire_refrele(fire);
8972 	ipif_refrele(ipif);
8973 	/* Did this packet originate externally? */
8974 	if (dst_ill != NULL)
8975 		ill_refrele(dst_ill);
8976 	if (src_ipif != NULL)
8977 		ipif_refrele(src_ipif);
8978 	if (mp->b_prev || mp->b_next) {
8979 		mp->b_next = NULL;
8980 		mp->b_prev = NULL;
8981 	} else {
8982 		/*
8983 		 * Since ip_wput() isn't close to finished, we fill
8984 		 * in enough of the header for credible error reporting.
8985 		 */
8986 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
8987 			/* Failed */
8988 			freemsg(first_mp);
8989 			if (ire != NULL)
8990 				ire_refrele(ire);
8991 			return;
8992 		}
8993 	}
8994 	/*
8995 	 * At this point we will have ire only if RTF_BLACKHOLE
8996 	 * or RTF_REJECT flags are set on the IRE. It will not
8997 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8998 	 */
8999 	if (ire != NULL) {
9000 		if (ire->ire_flags & RTF_BLACKHOLE) {
9001 			ire_refrele(ire);
9002 			freemsg(first_mp);
9003 			return;
9004 		}
9005 		ire_refrele(ire);
9006 	}
9007 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE);
9008 }
9009 
9010 /* Name/Value Table Lookup Routine */
9011 char *
9012 ip_nv_lookup(nv_t *nv, int value)
9013 {
9014 	if (!nv)
9015 		return (NULL);
9016 	for (; nv->nv_name; nv++) {
9017 		if (nv->nv_value == value)
9018 			return (nv->nv_name);
9019 	}
9020 	return ("unknown");
9021 }
9022 
9023 /*
9024  * one day it can be patched to 1 from /etc/system for machines that have few
9025  * fast network interfaces feeding multiple cpus.
9026  */
9027 int ill_stream_putlocks = 0;
9028 
9029 /*
9030  * This is a module open, i.e. this is a control stream for access
9031  * to a DLPI device.  We allocate an ill_t as the instance data in
9032  * this case.
9033  */
9034 int
9035 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9036 {
9037 	uint32_t mem_cnt;
9038 	uint32_t cpu_cnt;
9039 	uint32_t min_cnt;
9040 	pgcnt_t mem_avail;
9041 	extern uint32_t ip_cache_table_size, ip6_cache_table_size;
9042 	ill_t	*ill;
9043 	int	err;
9044 
9045 	/*
9046 	 * Prevent unprivileged processes from pushing IP so that
9047 	 * they can't send raw IP.
9048 	 */
9049 	if (secpolicy_net_rawaccess(credp) != 0)
9050 		return (EPERM);
9051 
9052 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9053 	q->q_ptr = WR(q)->q_ptr = ill;
9054 
9055 	/*
9056 	 * ill_init initializes the ill fields and then sends down
9057 	 * down a DL_INFO_REQ after calling qprocson.
9058 	 */
9059 	err = ill_init(q, ill);
9060 	if (err != 0) {
9061 		mi_free(ill);
9062 		q->q_ptr = NULL;
9063 		WR(q)->q_ptr = NULL;
9064 		return (err);
9065 	}
9066 
9067 	/* ill_init initializes the ipsq marking this thread as writer */
9068 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9069 	/* Wait for the DL_INFO_ACK */
9070 	mutex_enter(&ill->ill_lock);
9071 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9072 		/*
9073 		 * Return value of 0 indicates a pending signal.
9074 		 */
9075 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9076 		if (err == 0) {
9077 			mutex_exit(&ill->ill_lock);
9078 			(void) ip_close(q, 0);
9079 			return (EINTR);
9080 		}
9081 	}
9082 	mutex_exit(&ill->ill_lock);
9083 
9084 	/*
9085 	 * ip_rput_other could have set an error  in ill_error on
9086 	 * receipt of M_ERROR.
9087 	 */
9088 
9089 	err = ill->ill_error;
9090 	if (err != 0) {
9091 		(void) ip_close(q, 0);
9092 		return (err);
9093 	}
9094 
9095 	/*
9096 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9097 	 * size and the cpu speed of the machine. This is upper
9098 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9099 	 * and is lower bounded by the compile time value of
9100 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9101 	 * ip6_ire_max_bucket_cnt.
9102 	 */
9103 	mem_avail = kmem_avail();
9104 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9105 	    ip_cache_table_size / sizeof (ire_t);
9106 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9107 
9108 	min_cnt = MIN(cpu_cnt, mem_cnt);
9109 	if (min_cnt < ip_ire_min_bucket_cnt)
9110 		min_cnt = ip_ire_min_bucket_cnt;
9111 	if (ip_ire_max_bucket_cnt > min_cnt) {
9112 		ip_ire_max_bucket_cnt = min_cnt;
9113 	}
9114 
9115 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9116 	    ip6_cache_table_size / sizeof (ire_t);
9117 	min_cnt = MIN(cpu_cnt, mem_cnt);
9118 	if (min_cnt < ip6_ire_min_bucket_cnt)
9119 		min_cnt = ip6_ire_min_bucket_cnt;
9120 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9121 		ip6_ire_max_bucket_cnt = min_cnt;
9122 	}
9123 
9124 	ill->ill_credp = credp;
9125 	crhold(credp);
9126 
9127 	mutex_enter(&ip_mi_lock);
9128 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9129 	mutex_exit(&ip_mi_lock);
9130 	if (err) {
9131 		(void) ip_close(q, 0);
9132 		return (err);
9133 	}
9134 	return (0);
9135 }
9136 
9137 /* IP open routine. */
9138 int
9139 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9140 {
9141 	conn_t 		*connp;
9142 	major_t		maj;
9143 
9144 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9145 
9146 	/* Allow reopen. */
9147 	if (q->q_ptr != NULL)
9148 		return (0);
9149 
9150 	if (sflag & MODOPEN) {
9151 		/* This is a module open */
9152 		return (ip_modopen(q, devp, flag, sflag, credp));
9153 	}
9154 
9155 	/*
9156 	 * We are opening as a device. This is an IP client stream, and we
9157 	 * allocate an conn_t as the instance data.
9158 	 */
9159 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9160 	connp->conn_upq = q;
9161 	q->q_ptr = WR(q)->q_ptr = connp;
9162 
9163 	if (flag & SO_SOCKSTR)
9164 		connp->conn_flags |= IPCL_SOCKET;
9165 
9166 	/* Minor tells us which /dev entry was opened */
9167 	if (geteminor(*devp) == IPV6_MINOR) {
9168 		connp->conn_flags |= IPCL_ISV6;
9169 		connp->conn_af_isv6 = B_TRUE;
9170 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9171 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9172 	} else {
9173 		connp->conn_af_isv6 = B_FALSE;
9174 		connp->conn_pkt_isv6 = B_FALSE;
9175 	}
9176 
9177 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9178 		q->q_ptr = WR(q)->q_ptr = NULL;
9179 		CONN_DEC_REF(connp);
9180 		return (EBUSY);
9181 	}
9182 
9183 	maj = getemajor(*devp);
9184 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9185 
9186 	/*
9187 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9188 	 */
9189 	connp->conn_cred = credp;
9190 	crhold(connp->conn_cred);
9191 
9192 	/*
9193 	 * If the caller has the process-wide flag set, then default to MAC
9194 	 * exempt mode.  This allows read-down to unlabeled hosts.
9195 	 */
9196 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9197 		connp->conn_mac_exempt = B_TRUE;
9198 
9199 	connp->conn_zoneid = getzoneid();
9200 
9201 	/*
9202 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9203 	 * administrative ops.  In these cases, we just need a normal conn_t
9204 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9205 	 * an error will be returned.
9206 	 */
9207 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9208 		connp->conn_rq = q;
9209 		connp->conn_wq = WR(q);
9210 	} else {
9211 		connp->conn_ulp = IPPROTO_SCTP;
9212 		connp->conn_rq = connp->conn_wq = NULL;
9213 	}
9214 	/* Non-zero default values */
9215 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9216 
9217 	/*
9218 	 * Make the conn globally visible to walkers
9219 	 */
9220 	mutex_enter(&connp->conn_lock);
9221 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9222 	mutex_exit(&connp->conn_lock);
9223 	ASSERT(connp->conn_ref == 1);
9224 
9225 	qprocson(q);
9226 
9227 	return (0);
9228 }
9229 
9230 /*
9231  * Change q_qinfo based on the value of isv6.
9232  * This can not called on an ill queue.
9233  * Note that there is no race since either q_qinfo works for conn queues - it
9234  * is just an optimization to enter the best wput routine directly.
9235  */
9236 void
9237 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9238 {
9239 	ASSERT(q->q_flag & QREADR);
9240 	ASSERT(WR(q)->q_next == NULL);
9241 	ASSERT(q->q_ptr != NULL);
9242 
9243 	if (minor == IPV6_MINOR)  {
9244 		if (bump_mib)
9245 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9246 		q->q_qinfo = &rinit_ipv6;
9247 		WR(q)->q_qinfo = &winit_ipv6;
9248 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9249 	} else {
9250 		if (bump_mib)
9251 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9252 		q->q_qinfo = &rinit;
9253 		WR(q)->q_qinfo = &winit;
9254 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9255 	}
9256 
9257 }
9258 
9259 /*
9260  * See if IPsec needs loading because of the options in mp.
9261  */
9262 static boolean_t
9263 ipsec_opt_present(mblk_t *mp)
9264 {
9265 	uint8_t *optcp, *next_optcp, *opt_endcp;
9266 	struct opthdr *opt;
9267 	struct T_opthdr *topt;
9268 	int opthdr_len;
9269 	t_uscalar_t optname, optlevel;
9270 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9271 	ipsec_req_t *ipsr;
9272 
9273 	/*
9274 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9275 	 * return TRUE.
9276 	 */
9277 
9278 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9279 	opt_endcp = optcp + tor->OPT_length;
9280 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9281 		opthdr_len = sizeof (struct T_opthdr);
9282 	} else {		/* O_OPTMGMT_REQ */
9283 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9284 		opthdr_len = sizeof (struct opthdr);
9285 	}
9286 	for (; optcp < opt_endcp; optcp = next_optcp) {
9287 		if (optcp + opthdr_len > opt_endcp)
9288 			return (B_FALSE);	/* Not enough option header. */
9289 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9290 			topt = (struct T_opthdr *)optcp;
9291 			optlevel = topt->level;
9292 			optname = topt->name;
9293 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9294 		} else {
9295 			opt = (struct opthdr *)optcp;
9296 			optlevel = opt->level;
9297 			optname = opt->name;
9298 			next_optcp = optcp + opthdr_len +
9299 			    _TPI_ALIGN_OPT(opt->len);
9300 		}
9301 		if ((next_optcp < optcp) || /* wraparound pointer space */
9302 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9303 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9304 			return (B_FALSE); /* bad option buffer */
9305 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9306 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9307 			/*
9308 			 * Check to see if it's an all-bypass or all-zeroes
9309 			 * IPsec request.  Don't bother loading IPsec if
9310 			 * the socket doesn't want to use it.  (A good example
9311 			 * is a bypass request.)
9312 			 *
9313 			 * Basically, if any of the non-NEVER bits are set,
9314 			 * load IPsec.
9315 			 */
9316 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9317 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9318 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9319 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9320 			    != 0)
9321 				return (B_TRUE);
9322 		}
9323 	}
9324 	return (B_FALSE);
9325 }
9326 
9327 /*
9328  * If conn is is waiting for ipsec to finish loading, kick it.
9329  */
9330 /* ARGSUSED */
9331 static void
9332 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9333 {
9334 	t_scalar_t	optreq_prim;
9335 	mblk_t		*mp;
9336 	cred_t		*cr;
9337 	int		err = 0;
9338 
9339 	/*
9340 	 * This function is called, after ipsec loading is complete.
9341 	 * Since IP checks exclusively and atomically (i.e it prevents
9342 	 * ipsec load from completing until ip_optcom_req completes)
9343 	 * whether ipsec load is complete, there cannot be a race with IP
9344 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9345 	 */
9346 	mutex_enter(&connp->conn_lock);
9347 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9348 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9349 		mp = connp->conn_ipsec_opt_mp;
9350 		connp->conn_ipsec_opt_mp = NULL;
9351 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9352 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9353 		mutex_exit(&connp->conn_lock);
9354 
9355 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9356 
9357 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9358 		if (optreq_prim == T_OPTMGMT_REQ) {
9359 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9360 			    &ip_opt_obj);
9361 		} else {
9362 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9363 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9364 			    &ip_opt_obj);
9365 		}
9366 		if (err != EINPROGRESS)
9367 			CONN_OPER_PENDING_DONE(connp);
9368 		return;
9369 	}
9370 	mutex_exit(&connp->conn_lock);
9371 }
9372 
9373 /*
9374  * Called from the ipsec_loader thread, outside any perimeter, to tell
9375  * ip qenable any of the queues waiting for the ipsec loader to
9376  * complete.
9377  *
9378  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9379  * are done with this lock held, so it's guaranteed that none of the
9380  * links will change along the way.
9381  */
9382 void
9383 ip_ipsec_load_complete()
9384 {
9385 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9386 }
9387 
9388 /*
9389  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9390  * determines the grp on which it has to become exclusive, queues the mp
9391  * and sq draining restarts the optmgmt
9392  */
9393 static boolean_t
9394 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9395 {
9396 	conn_t *connp;
9397 
9398 	/*
9399 	 * Take IPsec requests and treat them special.
9400 	 */
9401 	if (ipsec_opt_present(mp)) {
9402 		/* First check if IPsec is loaded. */
9403 		mutex_enter(&ipsec_loader_lock);
9404 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9405 			mutex_exit(&ipsec_loader_lock);
9406 			return (B_FALSE);
9407 		}
9408 		connp = Q_TO_CONN(q);
9409 		mutex_enter(&connp->conn_lock);
9410 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9411 
9412 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9413 		connp->conn_ipsec_opt_mp = mp;
9414 		mutex_exit(&connp->conn_lock);
9415 		mutex_exit(&ipsec_loader_lock);
9416 
9417 		ipsec_loader_loadnow();
9418 		return (B_TRUE);
9419 	}
9420 	return (B_FALSE);
9421 }
9422 
9423 /*
9424  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9425  * all of them are copied to the conn_t. If the req is "zero", the policy is
9426  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9427  * fields.
9428  * We keep only the latest setting of the policy and thus policy setting
9429  * is not incremental/cumulative.
9430  *
9431  * Requests to set policies with multiple alternative actions will
9432  * go through a different API.
9433  */
9434 int
9435 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9436 {
9437 	uint_t ah_req = 0;
9438 	uint_t esp_req = 0;
9439 	uint_t se_req = 0;
9440 	ipsec_selkey_t sel;
9441 	ipsec_act_t *actp = NULL;
9442 	uint_t nact;
9443 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9444 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9445 	ipsec_policy_root_t *pr;
9446 	ipsec_policy_head_t *ph;
9447 	int fam;
9448 	boolean_t is_pol_reset;
9449 	int error = 0;
9450 
9451 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9452 
9453 	/*
9454 	 * The IP_SEC_OPT option does not allow variable length parameters,
9455 	 * hence a request cannot be NULL.
9456 	 */
9457 	if (req == NULL)
9458 		return (EINVAL);
9459 
9460 	ah_req = req->ipsr_ah_req;
9461 	esp_req = req->ipsr_esp_req;
9462 	se_req = req->ipsr_self_encap_req;
9463 
9464 	/*
9465 	 * Are we dealing with a request to reset the policy (i.e.
9466 	 * zero requests).
9467 	 */
9468 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9469 	    (esp_req & REQ_MASK) == 0 &&
9470 	    (se_req & REQ_MASK) == 0);
9471 
9472 	if (!is_pol_reset) {
9473 		/*
9474 		 * If we couldn't load IPsec, fail with "protocol
9475 		 * not supported".
9476 		 * IPsec may not have been loaded for a request with zero
9477 		 * policies, so we don't fail in this case.
9478 		 */
9479 		mutex_enter(&ipsec_loader_lock);
9480 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9481 			mutex_exit(&ipsec_loader_lock);
9482 			return (EPROTONOSUPPORT);
9483 		}
9484 		mutex_exit(&ipsec_loader_lock);
9485 
9486 		/*
9487 		 * Test for valid requests. Invalid algorithms
9488 		 * need to be tested by IPSEC code because new
9489 		 * algorithms can be added dynamically.
9490 		 */
9491 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9492 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9493 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9494 			return (EINVAL);
9495 		}
9496 
9497 		/*
9498 		 * Only privileged users can issue these
9499 		 * requests.
9500 		 */
9501 		if (((ah_req & IPSEC_PREF_NEVER) ||
9502 		    (esp_req & IPSEC_PREF_NEVER) ||
9503 		    (se_req & IPSEC_PREF_NEVER)) &&
9504 		    secpolicy_net_config(cr, B_FALSE) != 0) {
9505 			return (EPERM);
9506 		}
9507 
9508 		/*
9509 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
9510 		 * are mutually exclusive.
9511 		 */
9512 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
9513 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
9514 		    ((se_req & REQ_MASK) == REQ_MASK)) {
9515 			/* Both of them are set */
9516 			return (EINVAL);
9517 		}
9518 	}
9519 
9520 	mutex_enter(&connp->conn_lock);
9521 
9522 	/*
9523 	 * If we have already cached policies in ip_bind_connected*(), don't
9524 	 * let them change now. We cache policies for connections
9525 	 * whose src,dst [addr, port] is known.  The exception to this is
9526 	 * tunnels.  Tunnels are allowed to change policies after having
9527 	 * become fully bound.
9528 	 */
9529 	if (connp->conn_policy_cached && !IPCL_IS_IPTUN(connp)) {
9530 		mutex_exit(&connp->conn_lock);
9531 		return (EINVAL);
9532 	}
9533 
9534 	/*
9535 	 * We have a zero policies, reset the connection policy if already
9536 	 * set. This will cause the connection to inherit the
9537 	 * global policy, if any.
9538 	 */
9539 	if (is_pol_reset) {
9540 		if (connp->conn_policy != NULL) {
9541 			IPPH_REFRELE(connp->conn_policy);
9542 			connp->conn_policy = NULL;
9543 		}
9544 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
9545 		connp->conn_in_enforce_policy = B_FALSE;
9546 		connp->conn_out_enforce_policy = B_FALSE;
9547 		mutex_exit(&connp->conn_lock);
9548 		return (0);
9549 	}
9550 
9551 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
9552 	if (ph == NULL)
9553 		goto enomem;
9554 
9555 	ipsec_actvec_from_req(req, &actp, &nact);
9556 	if (actp == NULL)
9557 		goto enomem;
9558 
9559 	/*
9560 	 * Always allocate IPv4 policy entries, since they can also
9561 	 * apply to ipv6 sockets being used in ipv4-compat mode.
9562 	 */
9563 	bzero(&sel, sizeof (sel));
9564 	sel.ipsl_valid = IPSL_IPV4;
9565 
9566 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9567 	if (pin4 == NULL)
9568 		goto enomem;
9569 
9570 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET);
9571 	if (pout4 == NULL)
9572 		goto enomem;
9573 
9574 	if (connp->conn_pkt_isv6) {
9575 		/*
9576 		 * We're looking at a v6 socket, also allocate the
9577 		 * v6-specific entries...
9578 		 */
9579 		sel.ipsl_valid = IPSL_IPV6;
9580 		pin6 = ipsec_policy_create(&sel, actp, nact,
9581 		    IPSEC_PRIO_SOCKET);
9582 		if (pin6 == NULL)
9583 			goto enomem;
9584 
9585 		pout6 = ipsec_policy_create(&sel, actp, nact,
9586 		    IPSEC_PRIO_SOCKET);
9587 		if (pout6 == NULL)
9588 			goto enomem;
9589 
9590 		/*
9591 		 * .. and file them away in the right place.
9592 		 */
9593 		fam = IPSEC_AF_V6;
9594 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9595 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
9596 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
9597 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9598 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
9599 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
9600 	}
9601 
9602 	ipsec_actvec_free(actp, nact);
9603 
9604 	/*
9605 	 * File the v4 policies.
9606 	 */
9607 	fam = IPSEC_AF_V4;
9608 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
9609 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
9610 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
9611 
9612 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
9613 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
9614 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
9615 
9616 	/*
9617 	 * If the requests need security, set enforce_policy.
9618 	 * If the requests are IPSEC_PREF_NEVER, one should
9619 	 * still set conn_out_enforce_policy so that an ipsec_out
9620 	 * gets attached in ip_wput. This is needed so that
9621 	 * for connections that we don't cache policy in ip_bind,
9622 	 * if global policy matches in ip_wput_attach_policy, we
9623 	 * don't wrongly inherit global policy. Similarly, we need
9624 	 * to set conn_in_enforce_policy also so that we don't verify
9625 	 * policy wrongly.
9626 	 */
9627 	if ((ah_req & REQ_MASK) != 0 ||
9628 	    (esp_req & REQ_MASK) != 0 ||
9629 	    (se_req & REQ_MASK) != 0) {
9630 		connp->conn_in_enforce_policy = B_TRUE;
9631 		connp->conn_out_enforce_policy = B_TRUE;
9632 		connp->conn_flags |= IPCL_CHECK_POLICY;
9633 	}
9634 
9635 	/*
9636 	 * Tunnels are allowed to set policy after having been fully bound.
9637 	 * If that's the case, cache policy here.
9638 	 */
9639 	if (IPCL_IS_IPTUN(connp) && connp->conn_fully_bound)
9640 		error = ipsec_conn_cache_policy(connp, !connp->conn_af_isv6);
9641 
9642 	mutex_exit(&connp->conn_lock);
9643 	return (error);
9644 #undef REQ_MASK
9645 
9646 	/*
9647 	 * Common memory-allocation-failure exit path.
9648 	 */
9649 enomem:
9650 	mutex_exit(&connp->conn_lock);
9651 	if (actp != NULL)
9652 		ipsec_actvec_free(actp, nact);
9653 	if (pin4 != NULL)
9654 		IPPOL_REFRELE(pin4);
9655 	if (pout4 != NULL)
9656 		IPPOL_REFRELE(pout4);
9657 	if (pin6 != NULL)
9658 		IPPOL_REFRELE(pin6);
9659 	if (pout6 != NULL)
9660 		IPPOL_REFRELE(pout6);
9661 	return (ENOMEM);
9662 }
9663 
9664 /*
9665  * Only for options that pass in an IP addr. Currently only V4 options
9666  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
9667  * So this function assumes level is IPPROTO_IP
9668  */
9669 int
9670 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
9671     mblk_t *first_mp)
9672 {
9673 	ipif_t *ipif = NULL;
9674 	int error;
9675 	ill_t *ill;
9676 	int zoneid;
9677 
9678 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
9679 
9680 	if (addr != INADDR_ANY || checkonly) {
9681 		ASSERT(connp != NULL);
9682 		zoneid = IPCL_ZONEID(connp);
9683 		if (option == IP_NEXTHOP) {
9684 			ipif = ipif_lookup_onlink_addr(addr, zoneid);
9685 		} else {
9686 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
9687 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
9688 			    &error);
9689 		}
9690 		if (ipif == NULL) {
9691 			if (error == EINPROGRESS)
9692 				return (error);
9693 			else if ((option == IP_MULTICAST_IF) ||
9694 			    (option == IP_NEXTHOP))
9695 				return (EHOSTUNREACH);
9696 			else
9697 				return (EINVAL);
9698 		} else if (checkonly) {
9699 			if (option == IP_MULTICAST_IF) {
9700 				ill = ipif->ipif_ill;
9701 				/* not supported by the virtual network iface */
9702 				if (IS_VNI(ill)) {
9703 					ipif_refrele(ipif);
9704 					return (EINVAL);
9705 				}
9706 			}
9707 			ipif_refrele(ipif);
9708 			return (0);
9709 		}
9710 		ill = ipif->ipif_ill;
9711 		mutex_enter(&connp->conn_lock);
9712 		mutex_enter(&ill->ill_lock);
9713 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
9714 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
9715 			mutex_exit(&ill->ill_lock);
9716 			mutex_exit(&connp->conn_lock);
9717 			ipif_refrele(ipif);
9718 			return (option == IP_MULTICAST_IF ?
9719 			    EHOSTUNREACH : EINVAL);
9720 		}
9721 	} else {
9722 		mutex_enter(&connp->conn_lock);
9723 	}
9724 
9725 	/* None of the options below are supported on the VNI */
9726 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
9727 		mutex_exit(&ill->ill_lock);
9728 		mutex_exit(&connp->conn_lock);
9729 		ipif_refrele(ipif);
9730 		return (EINVAL);
9731 	}
9732 
9733 	switch (option) {
9734 	case IP_DONTFAILOVER_IF:
9735 		/*
9736 		 * This option is used by in.mpathd to ensure
9737 		 * that IPMP probe packets only go out on the
9738 		 * test interfaces. in.mpathd sets this option
9739 		 * on the non-failover interfaces.
9740 		 * For backward compatibility, this option
9741 		 * implicitly sets IP_MULTICAST_IF, as used
9742 		 * be done in bind(), so that ip_wput gets
9743 		 * this ipif to send mcast packets.
9744 		 */
9745 		if (ipif != NULL) {
9746 			ASSERT(addr != INADDR_ANY);
9747 			connp->conn_nofailover_ill = ipif->ipif_ill;
9748 			connp->conn_multicast_ipif = ipif;
9749 		} else {
9750 			ASSERT(addr == INADDR_ANY);
9751 			connp->conn_nofailover_ill = NULL;
9752 			connp->conn_multicast_ipif = NULL;
9753 		}
9754 		break;
9755 
9756 	case IP_MULTICAST_IF:
9757 		connp->conn_multicast_ipif = ipif;
9758 		break;
9759 	case IP_NEXTHOP:
9760 		connp->conn_nexthop_v4 = addr;
9761 		connp->conn_nexthop_set = B_TRUE;
9762 		break;
9763 	}
9764 
9765 	if (ipif != NULL) {
9766 		mutex_exit(&ill->ill_lock);
9767 		mutex_exit(&connp->conn_lock);
9768 		ipif_refrele(ipif);
9769 		return (0);
9770 	}
9771 	mutex_exit(&connp->conn_lock);
9772 	/* We succeded in cleared the option */
9773 	return (0);
9774 }
9775 
9776 /*
9777  * For options that pass in an ifindex specifying the ill. V6 options always
9778  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
9779  */
9780 int
9781 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
9782     int level, int option, mblk_t *first_mp)
9783 {
9784 	ill_t *ill = NULL;
9785 	int error = 0;
9786 
9787 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
9788 	if (ifindex != 0) {
9789 		ASSERT(connp != NULL);
9790 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
9791 		    first_mp, ip_restart_optmgmt, &error);
9792 		if (ill != NULL) {
9793 			if (checkonly) {
9794 				/* not supported by the virtual network iface */
9795 				if (IS_VNI(ill)) {
9796 					ill_refrele(ill);
9797 					return (EINVAL);
9798 				}
9799 				ill_refrele(ill);
9800 				return (0);
9801 			}
9802 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
9803 			    0, NULL)) {
9804 				ill_refrele(ill);
9805 				ill = NULL;
9806 				mutex_enter(&connp->conn_lock);
9807 				goto setit;
9808 			}
9809 			mutex_enter(&connp->conn_lock);
9810 			mutex_enter(&ill->ill_lock);
9811 			if (ill->ill_state_flags & ILL_CONDEMNED) {
9812 				mutex_exit(&ill->ill_lock);
9813 				mutex_exit(&connp->conn_lock);
9814 				ill_refrele(ill);
9815 				ill = NULL;
9816 				mutex_enter(&connp->conn_lock);
9817 			}
9818 			goto setit;
9819 		} else if (error == EINPROGRESS) {
9820 			return (error);
9821 		} else {
9822 			error = 0;
9823 		}
9824 	}
9825 	mutex_enter(&connp->conn_lock);
9826 setit:
9827 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
9828 
9829 	/*
9830 	 * The options below assume that the ILL (if any) transmits and/or
9831 	 * receives traffic. Neither of which is true for the virtual network
9832 	 * interface, so fail setting these on a VNI.
9833 	 */
9834 	if (IS_VNI(ill)) {
9835 		ASSERT(ill != NULL);
9836 		mutex_exit(&ill->ill_lock);
9837 		mutex_exit(&connp->conn_lock);
9838 		ill_refrele(ill);
9839 		return (EINVAL);
9840 	}
9841 
9842 	if (level == IPPROTO_IP) {
9843 		switch (option) {
9844 		case IP_BOUND_IF:
9845 			connp->conn_incoming_ill = ill;
9846 			connp->conn_outgoing_ill = ill;
9847 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9848 			    0 : ifindex;
9849 			break;
9850 
9851 		case IP_XMIT_IF:
9852 			/*
9853 			 * Similar to IP_BOUND_IF, but this only
9854 			 * determines the outgoing interface for
9855 			 * unicast packets. Also no IRE_CACHE entry
9856 			 * is added for the destination of the
9857 			 * outgoing packets. This feature is needed
9858 			 * for mobile IP.
9859 			 */
9860 			connp->conn_xmit_if_ill = ill;
9861 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
9862 			    0 : ifindex;
9863 			break;
9864 
9865 		case IP_MULTICAST_IF:
9866 			/*
9867 			 * This option is an internal special. The socket
9868 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
9869 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
9870 			 * specifies an ifindex and we try first on V6 ill's.
9871 			 * If we don't find one, we they try using on v4 ill's
9872 			 * intenally and we come here.
9873 			 */
9874 			if (!checkonly && ill != NULL) {
9875 				ipif_t	*ipif;
9876 				ipif = ill->ill_ipif;
9877 
9878 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
9879 					mutex_exit(&ill->ill_lock);
9880 					mutex_exit(&connp->conn_lock);
9881 					ill_refrele(ill);
9882 					ill = NULL;
9883 					mutex_enter(&connp->conn_lock);
9884 				} else {
9885 					connp->conn_multicast_ipif = ipif;
9886 				}
9887 			}
9888 			break;
9889 		}
9890 	} else {
9891 		switch (option) {
9892 		case IPV6_BOUND_IF:
9893 			connp->conn_incoming_ill = ill;
9894 			connp->conn_outgoing_ill = ill;
9895 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
9896 			    0 : ifindex;
9897 			break;
9898 
9899 		case IPV6_BOUND_PIF:
9900 			/*
9901 			 * Limit all transmit to this ill.
9902 			 * Unlike IPV6_BOUND_IF, using this option
9903 			 * prevents load spreading and failover from
9904 			 * happening when the interface is part of the
9905 			 * group. That's why we don't need to remember
9906 			 * the ifindex in orig_bound_ifindex as in
9907 			 * IPV6_BOUND_IF.
9908 			 */
9909 			connp->conn_outgoing_pill = ill;
9910 			break;
9911 
9912 		case IPV6_DONTFAILOVER_IF:
9913 			/*
9914 			 * This option is used by in.mpathd to ensure
9915 			 * that IPMP probe packets only go out on the
9916 			 * test interfaces. in.mpathd sets this option
9917 			 * on the non-failover interfaces.
9918 			 */
9919 			connp->conn_nofailover_ill = ill;
9920 			/*
9921 			 * For backward compatibility, this option
9922 			 * implicitly sets ip_multicast_ill as used in
9923 			 * IP_MULTICAST_IF so that ip_wput gets
9924 			 * this ipif to send mcast packets.
9925 			 */
9926 			connp->conn_multicast_ill = ill;
9927 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
9928 			    0 : ifindex;
9929 			break;
9930 
9931 		case IPV6_MULTICAST_IF:
9932 			/*
9933 			 * Set conn_multicast_ill to be the IPv6 ill.
9934 			 * Set conn_multicast_ipif to be an IPv4 ipif
9935 			 * for ifindex to make IPv4 mapped addresses
9936 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
9937 			 * Even if no IPv6 ill exists for the ifindex
9938 			 * we need to check for an IPv4 ifindex in order
9939 			 * for this to work with mapped addresses. In that
9940 			 * case only set conn_multicast_ipif.
9941 			 */
9942 			if (!checkonly) {
9943 				if (ifindex == 0) {
9944 					connp->conn_multicast_ill = NULL;
9945 					connp->conn_orig_multicast_ifindex = 0;
9946 					connp->conn_multicast_ipif = NULL;
9947 				} else if (ill != NULL) {
9948 					connp->conn_multicast_ill = ill;
9949 					connp->conn_orig_multicast_ifindex =
9950 					    ifindex;
9951 				}
9952 			}
9953 			break;
9954 		}
9955 	}
9956 
9957 	if (ill != NULL) {
9958 		mutex_exit(&ill->ill_lock);
9959 		mutex_exit(&connp->conn_lock);
9960 		ill_refrele(ill);
9961 		return (0);
9962 	}
9963 	mutex_exit(&connp->conn_lock);
9964 	/*
9965 	 * We succeeded in clearing the option (ifindex == 0) or failed to
9966 	 * locate the ill and could not set the option (ifindex != 0)
9967 	 */
9968 	return (ifindex == 0 ? 0 : EINVAL);
9969 }
9970 
9971 /* This routine sets socket options. */
9972 /* ARGSUSED */
9973 int
9974 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
9975     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9976     void *dummy, cred_t *cr, mblk_t *first_mp)
9977 {
9978 	int		*i1 = (int *)invalp;
9979 	conn_t		*connp = Q_TO_CONN(q);
9980 	int		error = 0;
9981 	boolean_t	checkonly;
9982 	ire_t		*ire;
9983 	boolean_t	found;
9984 
9985 	switch (optset_context) {
9986 
9987 	case SETFN_OPTCOM_CHECKONLY:
9988 		checkonly = B_TRUE;
9989 		/*
9990 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9991 		 * inlen != 0 implies value supplied and
9992 		 * 	we have to "pretend" to set it.
9993 		 * inlen == 0 implies that there is no
9994 		 * 	value part in T_CHECK request and just validation
9995 		 * done elsewhere should be enough, we just return here.
9996 		 */
9997 		if (inlen == 0) {
9998 			*outlenp = 0;
9999 			return (0);
10000 		}
10001 		break;
10002 	case SETFN_OPTCOM_NEGOTIATE:
10003 	case SETFN_UD_NEGOTIATE:
10004 	case SETFN_CONN_NEGOTIATE:
10005 		checkonly = B_FALSE;
10006 		break;
10007 	default:
10008 		/*
10009 		 * We should never get here
10010 		 */
10011 		*outlenp = 0;
10012 		return (EINVAL);
10013 	}
10014 
10015 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10016 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10017 
10018 	/*
10019 	 * For fixed length options, no sanity check
10020 	 * of passed in length is done. It is assumed *_optcom_req()
10021 	 * routines do the right thing.
10022 	 */
10023 
10024 	switch (level) {
10025 	case SOL_SOCKET:
10026 		/*
10027 		 * conn_lock protects the bitfields, and is used to
10028 		 * set the fields atomically.
10029 		 */
10030 		switch (name) {
10031 		case SO_BROADCAST:
10032 			if (!checkonly) {
10033 				/* TODO: use value someplace? */
10034 				mutex_enter(&connp->conn_lock);
10035 				connp->conn_broadcast = *i1 ? 1 : 0;
10036 				mutex_exit(&connp->conn_lock);
10037 			}
10038 			break;	/* goto sizeof (int) option return */
10039 		case SO_USELOOPBACK:
10040 			if (!checkonly) {
10041 				/* TODO: use value someplace? */
10042 				mutex_enter(&connp->conn_lock);
10043 				connp->conn_loopback = *i1 ? 1 : 0;
10044 				mutex_exit(&connp->conn_lock);
10045 			}
10046 			break;	/* goto sizeof (int) option return */
10047 		case SO_DONTROUTE:
10048 			if (!checkonly) {
10049 				mutex_enter(&connp->conn_lock);
10050 				connp->conn_dontroute = *i1 ? 1 : 0;
10051 				mutex_exit(&connp->conn_lock);
10052 			}
10053 			break;	/* goto sizeof (int) option return */
10054 		case SO_REUSEADDR:
10055 			if (!checkonly) {
10056 				mutex_enter(&connp->conn_lock);
10057 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10058 				mutex_exit(&connp->conn_lock);
10059 			}
10060 			break;	/* goto sizeof (int) option return */
10061 		case SO_PROTOTYPE:
10062 			if (!checkonly) {
10063 				mutex_enter(&connp->conn_lock);
10064 				connp->conn_proto = *i1;
10065 				mutex_exit(&connp->conn_lock);
10066 			}
10067 			break;	/* goto sizeof (int) option return */
10068 		case SO_ALLZONES:
10069 			if (!checkonly) {
10070 				mutex_enter(&connp->conn_lock);
10071 				if (IPCL_IS_BOUND(connp)) {
10072 					mutex_exit(&connp->conn_lock);
10073 					return (EINVAL);
10074 				}
10075 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10076 				mutex_exit(&connp->conn_lock);
10077 			}
10078 			break;	/* goto sizeof (int) option return */
10079 		case SO_ANON_MLP:
10080 			if (!checkonly) {
10081 				mutex_enter(&connp->conn_lock);
10082 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10083 				mutex_exit(&connp->conn_lock);
10084 			}
10085 			break;	/* goto sizeof (int) option return */
10086 		case SO_MAC_EXEMPT:
10087 			if (secpolicy_net_mac_aware(cr) != 0 ||
10088 			    IPCL_IS_BOUND(connp))
10089 				return (EACCES);
10090 			if (!checkonly) {
10091 				mutex_enter(&connp->conn_lock);
10092 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10093 				mutex_exit(&connp->conn_lock);
10094 			}
10095 			break;	/* goto sizeof (int) option return */
10096 		default:
10097 			/*
10098 			 * "soft" error (negative)
10099 			 * option not handled at this level
10100 			 * Note: Do not modify *outlenp
10101 			 */
10102 			return (-EINVAL);
10103 		}
10104 		break;
10105 	case IPPROTO_IP:
10106 		switch (name) {
10107 		case IP_NEXTHOP:
10108 		case IP_MULTICAST_IF:
10109 		case IP_DONTFAILOVER_IF: {
10110 			ipaddr_t addr = *i1;
10111 
10112 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10113 			    first_mp);
10114 			if (error != 0)
10115 				return (error);
10116 			break;	/* goto sizeof (int) option return */
10117 		}
10118 
10119 		case IP_MULTICAST_TTL:
10120 			/* Recorded in transport above IP */
10121 			*outvalp = *invalp;
10122 			*outlenp = sizeof (uchar_t);
10123 			return (0);
10124 		case IP_MULTICAST_LOOP:
10125 			if (!checkonly) {
10126 				mutex_enter(&connp->conn_lock);
10127 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10128 				mutex_exit(&connp->conn_lock);
10129 			}
10130 			*outvalp = *invalp;
10131 			*outlenp = sizeof (uchar_t);
10132 			return (0);
10133 		case IP_ADD_MEMBERSHIP:
10134 		case MCAST_JOIN_GROUP:
10135 		case IP_DROP_MEMBERSHIP:
10136 		case MCAST_LEAVE_GROUP: {
10137 			struct ip_mreq *mreqp;
10138 			struct group_req *greqp;
10139 			ire_t *ire;
10140 			boolean_t done = B_FALSE;
10141 			ipaddr_t group, ifaddr;
10142 			struct sockaddr_in *sin;
10143 			uint32_t *ifindexp;
10144 			boolean_t mcast_opt = B_TRUE;
10145 			mcast_record_t fmode;
10146 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10147 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10148 
10149 			switch (name) {
10150 			case IP_ADD_MEMBERSHIP:
10151 				mcast_opt = B_FALSE;
10152 				/* FALLTHRU */
10153 			case MCAST_JOIN_GROUP:
10154 				fmode = MODE_IS_EXCLUDE;
10155 				optfn = ip_opt_add_group;
10156 				break;
10157 
10158 			case IP_DROP_MEMBERSHIP:
10159 				mcast_opt = B_FALSE;
10160 				/* FALLTHRU */
10161 			case MCAST_LEAVE_GROUP:
10162 				fmode = MODE_IS_INCLUDE;
10163 				optfn = ip_opt_delete_group;
10164 				break;
10165 			}
10166 
10167 			if (mcast_opt) {
10168 				greqp = (struct group_req *)i1;
10169 				sin = (struct sockaddr_in *)&greqp->gr_group;
10170 				if (sin->sin_family != AF_INET) {
10171 					*outlenp = 0;
10172 					return (ENOPROTOOPT);
10173 				}
10174 				group = (ipaddr_t)sin->sin_addr.s_addr;
10175 				ifaddr = INADDR_ANY;
10176 				ifindexp = &greqp->gr_interface;
10177 			} else {
10178 				mreqp = (struct ip_mreq *)i1;
10179 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10180 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10181 				ifindexp = NULL;
10182 			}
10183 
10184 			/*
10185 			 * In the multirouting case, we need to replicate
10186 			 * the request on all interfaces that will take part
10187 			 * in replication.  We do so because multirouting is
10188 			 * reflective, thus we will probably receive multi-
10189 			 * casts on those interfaces.
10190 			 * The ip_multirt_apply_membership() succeeds if the
10191 			 * operation succeeds on at least one interface.
10192 			 */
10193 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10194 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10195 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10196 			if (ire != NULL) {
10197 				if (ire->ire_flags & RTF_MULTIRT) {
10198 					error = ip_multirt_apply_membership(
10199 					    optfn, ire, connp, checkonly, group,
10200 					    fmode, INADDR_ANY, first_mp);
10201 					done = B_TRUE;
10202 				}
10203 				ire_refrele(ire);
10204 			}
10205 			if (!done) {
10206 				error = optfn(connp, checkonly, group, ifaddr,
10207 				    ifindexp, fmode, INADDR_ANY, first_mp);
10208 			}
10209 			if (error) {
10210 				/*
10211 				 * EINPROGRESS is a soft error, needs retry
10212 				 * so don't make *outlenp zero.
10213 				 */
10214 				if (error != EINPROGRESS)
10215 					*outlenp = 0;
10216 				return (error);
10217 			}
10218 			/* OK return - copy input buffer into output buffer */
10219 			if (invalp != outvalp) {
10220 				/* don't trust bcopy for identical src/dst */
10221 				bcopy(invalp, outvalp, inlen);
10222 			}
10223 			*outlenp = inlen;
10224 			return (0);
10225 		}
10226 		case IP_BLOCK_SOURCE:
10227 		case IP_UNBLOCK_SOURCE:
10228 		case IP_ADD_SOURCE_MEMBERSHIP:
10229 		case IP_DROP_SOURCE_MEMBERSHIP:
10230 		case MCAST_BLOCK_SOURCE:
10231 		case MCAST_UNBLOCK_SOURCE:
10232 		case MCAST_JOIN_SOURCE_GROUP:
10233 		case MCAST_LEAVE_SOURCE_GROUP: {
10234 			struct ip_mreq_source *imreqp;
10235 			struct group_source_req *gsreqp;
10236 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10237 			uint32_t ifindex = 0;
10238 			mcast_record_t fmode;
10239 			struct sockaddr_in *sin;
10240 			ire_t *ire;
10241 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10242 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10243 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10244 
10245 			switch (name) {
10246 			case IP_BLOCK_SOURCE:
10247 				mcast_opt = B_FALSE;
10248 				/* FALLTHRU */
10249 			case MCAST_BLOCK_SOURCE:
10250 				fmode = MODE_IS_EXCLUDE;
10251 				optfn = ip_opt_add_group;
10252 				break;
10253 
10254 			case IP_UNBLOCK_SOURCE:
10255 				mcast_opt = B_FALSE;
10256 				/* FALLTHRU */
10257 			case MCAST_UNBLOCK_SOURCE:
10258 				fmode = MODE_IS_EXCLUDE;
10259 				optfn = ip_opt_delete_group;
10260 				break;
10261 
10262 			case IP_ADD_SOURCE_MEMBERSHIP:
10263 				mcast_opt = B_FALSE;
10264 				/* FALLTHRU */
10265 			case MCAST_JOIN_SOURCE_GROUP:
10266 				fmode = MODE_IS_INCLUDE;
10267 				optfn = ip_opt_add_group;
10268 				break;
10269 
10270 			case IP_DROP_SOURCE_MEMBERSHIP:
10271 				mcast_opt = B_FALSE;
10272 				/* FALLTHRU */
10273 			case MCAST_LEAVE_SOURCE_GROUP:
10274 				fmode = MODE_IS_INCLUDE;
10275 				optfn = ip_opt_delete_group;
10276 				break;
10277 			}
10278 
10279 			if (mcast_opt) {
10280 				gsreqp = (struct group_source_req *)i1;
10281 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10282 					*outlenp = 0;
10283 					return (ENOPROTOOPT);
10284 				}
10285 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10286 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10287 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10288 				src = (ipaddr_t)sin->sin_addr.s_addr;
10289 				ifindex = gsreqp->gsr_interface;
10290 			} else {
10291 				imreqp = (struct ip_mreq_source *)i1;
10292 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10293 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10294 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10295 			}
10296 
10297 			/*
10298 			 * In the multirouting case, we need to replicate
10299 			 * the request as noted in the mcast cases above.
10300 			 */
10301 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10302 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10303 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10304 			if (ire != NULL) {
10305 				if (ire->ire_flags & RTF_MULTIRT) {
10306 					error = ip_multirt_apply_membership(
10307 					    optfn, ire, connp, checkonly, grp,
10308 					    fmode, src, first_mp);
10309 					done = B_TRUE;
10310 				}
10311 				ire_refrele(ire);
10312 			}
10313 			if (!done) {
10314 				error = optfn(connp, checkonly, grp, ifaddr,
10315 				    &ifindex, fmode, src, first_mp);
10316 			}
10317 			if (error != 0) {
10318 				/*
10319 				 * EINPROGRESS is a soft error, needs retry
10320 				 * so don't make *outlenp zero.
10321 				 */
10322 				if (error != EINPROGRESS)
10323 					*outlenp = 0;
10324 				return (error);
10325 			}
10326 			/* OK return - copy input buffer into output buffer */
10327 			if (invalp != outvalp) {
10328 				bcopy(invalp, outvalp, inlen);
10329 			}
10330 			*outlenp = inlen;
10331 			return (0);
10332 		}
10333 		case IP_SEC_OPT:
10334 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10335 			if (error != 0) {
10336 				*outlenp = 0;
10337 				return (error);
10338 			}
10339 			break;
10340 		case IP_HDRINCL:
10341 		case IP_OPTIONS:
10342 		case T_IP_OPTIONS:
10343 		case IP_TOS:
10344 		case T_IP_TOS:
10345 		case IP_TTL:
10346 		case IP_RECVDSTADDR:
10347 		case IP_RECVOPTS:
10348 			/* OK return - copy input buffer into output buffer */
10349 			if (invalp != outvalp) {
10350 				/* don't trust bcopy for identical src/dst */
10351 				bcopy(invalp, outvalp, inlen);
10352 			}
10353 			*outlenp = inlen;
10354 			return (0);
10355 		case IP_RECVIF:
10356 			/* Retrieve the inbound interface index */
10357 			if (!checkonly) {
10358 				mutex_enter(&connp->conn_lock);
10359 				connp->conn_recvif = *i1 ? 1 : 0;
10360 				mutex_exit(&connp->conn_lock);
10361 			}
10362 			break;	/* goto sizeof (int) option return */
10363 		case IP_RECVSLLA:
10364 			/* Retrieve the source link layer address */
10365 			if (!checkonly) {
10366 				mutex_enter(&connp->conn_lock);
10367 				connp->conn_recvslla = *i1 ? 1 : 0;
10368 				mutex_exit(&connp->conn_lock);
10369 			}
10370 			break;	/* goto sizeof (int) option return */
10371 		case MRT_INIT:
10372 		case MRT_DONE:
10373 		case MRT_ADD_VIF:
10374 		case MRT_DEL_VIF:
10375 		case MRT_ADD_MFC:
10376 		case MRT_DEL_MFC:
10377 		case MRT_ASSERT:
10378 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10379 				*outlenp = 0;
10380 				return (error);
10381 			}
10382 			error = ip_mrouter_set((int)name, q, checkonly,
10383 			    (uchar_t *)invalp, inlen, first_mp);
10384 			if (error) {
10385 				*outlenp = 0;
10386 				return (error);
10387 			}
10388 			/* OK return - copy input buffer into output buffer */
10389 			if (invalp != outvalp) {
10390 				/* don't trust bcopy for identical src/dst */
10391 				bcopy(invalp, outvalp, inlen);
10392 			}
10393 			*outlenp = inlen;
10394 			return (0);
10395 		case IP_BOUND_IF:
10396 		case IP_XMIT_IF:
10397 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10398 			    level, name, first_mp);
10399 			if (error != 0)
10400 				return (error);
10401 			break; 		/* goto sizeof (int) option return */
10402 
10403 		case IP_UNSPEC_SRC:
10404 			/* Allow sending with a zero source address */
10405 			if (!checkonly) {
10406 				mutex_enter(&connp->conn_lock);
10407 				connp->conn_unspec_src = *i1 ? 1 : 0;
10408 				mutex_exit(&connp->conn_lock);
10409 			}
10410 			break;	/* goto sizeof (int) option return */
10411 		default:
10412 			/*
10413 			 * "soft" error (negative)
10414 			 * option not handled at this level
10415 			 * Note: Do not modify *outlenp
10416 			 */
10417 			return (-EINVAL);
10418 		}
10419 		break;
10420 	case IPPROTO_IPV6:
10421 		switch (name) {
10422 		case IPV6_BOUND_IF:
10423 		case IPV6_BOUND_PIF:
10424 		case IPV6_DONTFAILOVER_IF:
10425 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10426 			    level, name, first_mp);
10427 			if (error != 0)
10428 				return (error);
10429 			break; 		/* goto sizeof (int) option return */
10430 
10431 		case IPV6_MULTICAST_IF:
10432 			/*
10433 			 * The only possible errors are EINPROGRESS and
10434 			 * EINVAL. EINPROGRESS will be restarted and is not
10435 			 * a hard error. We call this option on both V4 and V6
10436 			 * If both return EINVAL, then this call returns
10437 			 * EINVAL. If at least one of them succeeds we
10438 			 * return success.
10439 			 */
10440 			found = B_FALSE;
10441 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10442 			    level, name, first_mp);
10443 			if (error == EINPROGRESS)
10444 				return (error);
10445 			if (error == 0)
10446 				found = B_TRUE;
10447 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10448 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10449 			if (error == 0)
10450 				found = B_TRUE;
10451 			if (!found)
10452 				return (error);
10453 			break; 		/* goto sizeof (int) option return */
10454 
10455 		case IPV6_MULTICAST_HOPS:
10456 			/* Recorded in transport above IP */
10457 			break;	/* goto sizeof (int) option return */
10458 		case IPV6_MULTICAST_LOOP:
10459 			if (!checkonly) {
10460 				mutex_enter(&connp->conn_lock);
10461 				connp->conn_multicast_loop = *i1;
10462 				mutex_exit(&connp->conn_lock);
10463 			}
10464 			break;	/* goto sizeof (int) option return */
10465 		case IPV6_JOIN_GROUP:
10466 		case MCAST_JOIN_GROUP:
10467 		case IPV6_LEAVE_GROUP:
10468 		case MCAST_LEAVE_GROUP: {
10469 			struct ipv6_mreq *ip_mreqp;
10470 			struct group_req *greqp;
10471 			ire_t *ire;
10472 			boolean_t done = B_FALSE;
10473 			in6_addr_t groupv6;
10474 			uint32_t ifindex;
10475 			boolean_t mcast_opt = B_TRUE;
10476 			mcast_record_t fmode;
10477 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10478 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10479 
10480 			switch (name) {
10481 			case IPV6_JOIN_GROUP:
10482 				mcast_opt = B_FALSE;
10483 				/* FALLTHRU */
10484 			case MCAST_JOIN_GROUP:
10485 				fmode = MODE_IS_EXCLUDE;
10486 				optfn = ip_opt_add_group_v6;
10487 				break;
10488 
10489 			case IPV6_LEAVE_GROUP:
10490 				mcast_opt = B_FALSE;
10491 				/* FALLTHRU */
10492 			case MCAST_LEAVE_GROUP:
10493 				fmode = MODE_IS_INCLUDE;
10494 				optfn = ip_opt_delete_group_v6;
10495 				break;
10496 			}
10497 
10498 			if (mcast_opt) {
10499 				struct sockaddr_in *sin;
10500 				struct sockaddr_in6 *sin6;
10501 				greqp = (struct group_req *)i1;
10502 				if (greqp->gr_group.ss_family == AF_INET) {
10503 					sin = (struct sockaddr_in *)
10504 					    &(greqp->gr_group);
10505 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10506 					    &groupv6);
10507 				} else {
10508 					sin6 = (struct sockaddr_in6 *)
10509 					    &(greqp->gr_group);
10510 					groupv6 = sin6->sin6_addr;
10511 				}
10512 				ifindex = greqp->gr_interface;
10513 			} else {
10514 				ip_mreqp = (struct ipv6_mreq *)i1;
10515 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
10516 				ifindex = ip_mreqp->ipv6mr_interface;
10517 			}
10518 			/*
10519 			 * In the multirouting case, we need to replicate
10520 			 * the request on all interfaces that will take part
10521 			 * in replication.  We do so because multirouting is
10522 			 * reflective, thus we will probably receive multi-
10523 			 * casts on those interfaces.
10524 			 * The ip_multirt_apply_membership_v6() succeeds if
10525 			 * the operation succeeds on at least one interface.
10526 			 */
10527 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
10528 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10529 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10530 			if (ire != NULL) {
10531 				if (ire->ire_flags & RTF_MULTIRT) {
10532 					error = ip_multirt_apply_membership_v6(
10533 					    optfn, ire, connp, checkonly,
10534 					    &groupv6, fmode, &ipv6_all_zeros,
10535 					    first_mp);
10536 					done = B_TRUE;
10537 				}
10538 				ire_refrele(ire);
10539 			}
10540 			if (!done) {
10541 				error = optfn(connp, checkonly, &groupv6,
10542 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
10543 			}
10544 			if (error) {
10545 				/*
10546 				 * EINPROGRESS is a soft error, needs retry
10547 				 * so don't make *outlenp zero.
10548 				 */
10549 				if (error != EINPROGRESS)
10550 					*outlenp = 0;
10551 				return (error);
10552 			}
10553 			/* OK return - copy input buffer into output buffer */
10554 			if (invalp != outvalp) {
10555 				/* don't trust bcopy for identical src/dst */
10556 				bcopy(invalp, outvalp, inlen);
10557 			}
10558 			*outlenp = inlen;
10559 			return (0);
10560 		}
10561 		case MCAST_BLOCK_SOURCE:
10562 		case MCAST_UNBLOCK_SOURCE:
10563 		case MCAST_JOIN_SOURCE_GROUP:
10564 		case MCAST_LEAVE_SOURCE_GROUP: {
10565 			struct group_source_req *gsreqp;
10566 			in6_addr_t v6grp, v6src;
10567 			uint32_t ifindex;
10568 			mcast_record_t fmode;
10569 			ire_t *ire;
10570 			boolean_t done = B_FALSE;
10571 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10572 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10573 
10574 			switch (name) {
10575 			case MCAST_BLOCK_SOURCE:
10576 				fmode = MODE_IS_EXCLUDE;
10577 				optfn = ip_opt_add_group_v6;
10578 				break;
10579 			case MCAST_UNBLOCK_SOURCE:
10580 				fmode = MODE_IS_EXCLUDE;
10581 				optfn = ip_opt_delete_group_v6;
10582 				break;
10583 			case MCAST_JOIN_SOURCE_GROUP:
10584 				fmode = MODE_IS_INCLUDE;
10585 				optfn = ip_opt_add_group_v6;
10586 				break;
10587 			case MCAST_LEAVE_SOURCE_GROUP:
10588 				fmode = MODE_IS_INCLUDE;
10589 				optfn = ip_opt_delete_group_v6;
10590 				break;
10591 			}
10592 
10593 			gsreqp = (struct group_source_req *)i1;
10594 			ifindex = gsreqp->gsr_interface;
10595 			if (gsreqp->gsr_group.ss_family == AF_INET) {
10596 				struct sockaddr_in *s;
10597 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
10598 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
10599 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
10600 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
10601 			} else {
10602 				struct sockaddr_in6 *s6;
10603 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
10604 				v6grp = s6->sin6_addr;
10605 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
10606 				v6src = s6->sin6_addr;
10607 			}
10608 
10609 			/*
10610 			 * In the multirouting case, we need to replicate
10611 			 * the request as noted in the mcast cases above.
10612 			 */
10613 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
10614 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10615 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10616 			if (ire != NULL) {
10617 				if (ire->ire_flags & RTF_MULTIRT) {
10618 					error = ip_multirt_apply_membership_v6(
10619 					    optfn, ire, connp, checkonly,
10620 					    &v6grp, fmode, &v6src, first_mp);
10621 					done = B_TRUE;
10622 				}
10623 				ire_refrele(ire);
10624 			}
10625 			if (!done) {
10626 				error = optfn(connp, checkonly, &v6grp,
10627 				    ifindex, fmode, &v6src, first_mp);
10628 			}
10629 			if (error != 0) {
10630 				/*
10631 				 * EINPROGRESS is a soft error, needs retry
10632 				 * so don't make *outlenp zero.
10633 				 */
10634 				if (error != EINPROGRESS)
10635 					*outlenp = 0;
10636 				return (error);
10637 			}
10638 			/* OK return - copy input buffer into output buffer */
10639 			if (invalp != outvalp) {
10640 				bcopy(invalp, outvalp, inlen);
10641 			}
10642 			*outlenp = inlen;
10643 			return (0);
10644 		}
10645 		case IPV6_UNICAST_HOPS:
10646 			/* Recorded in transport above IP */
10647 			break;	/* goto sizeof (int) option return */
10648 		case IPV6_UNSPEC_SRC:
10649 			/* Allow sending with a zero source address */
10650 			if (!checkonly) {
10651 				mutex_enter(&connp->conn_lock);
10652 				connp->conn_unspec_src = *i1 ? 1 : 0;
10653 				mutex_exit(&connp->conn_lock);
10654 			}
10655 			break;	/* goto sizeof (int) option return */
10656 		case IPV6_RECVPKTINFO:
10657 			if (!checkonly) {
10658 				mutex_enter(&connp->conn_lock);
10659 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
10660 				mutex_exit(&connp->conn_lock);
10661 			}
10662 			break;	/* goto sizeof (int) option return */
10663 		case IPV6_RECVTCLASS:
10664 			if (!checkonly) {
10665 				if (*i1 < 0 || *i1 > 1) {
10666 					return (EINVAL);
10667 				}
10668 				mutex_enter(&connp->conn_lock);
10669 				connp->conn_ipv6_recvtclass = *i1;
10670 				mutex_exit(&connp->conn_lock);
10671 			}
10672 			break;
10673 		case IPV6_RECVPATHMTU:
10674 			if (!checkonly) {
10675 				if (*i1 < 0 || *i1 > 1) {
10676 					return (EINVAL);
10677 				}
10678 				mutex_enter(&connp->conn_lock);
10679 				connp->conn_ipv6_recvpathmtu = *i1;
10680 				mutex_exit(&connp->conn_lock);
10681 			}
10682 			break;
10683 		case IPV6_RECVHOPLIMIT:
10684 			if (!checkonly) {
10685 				mutex_enter(&connp->conn_lock);
10686 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
10687 				mutex_exit(&connp->conn_lock);
10688 			}
10689 			break;	/* goto sizeof (int) option return */
10690 		case IPV6_RECVHOPOPTS:
10691 			if (!checkonly) {
10692 				mutex_enter(&connp->conn_lock);
10693 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
10694 				mutex_exit(&connp->conn_lock);
10695 			}
10696 			break;	/* goto sizeof (int) option return */
10697 		case IPV6_RECVDSTOPTS:
10698 			if (!checkonly) {
10699 				mutex_enter(&connp->conn_lock);
10700 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
10701 				mutex_exit(&connp->conn_lock);
10702 			}
10703 			break;	/* goto sizeof (int) option return */
10704 		case IPV6_RECVRTHDR:
10705 			if (!checkonly) {
10706 				mutex_enter(&connp->conn_lock);
10707 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
10708 				mutex_exit(&connp->conn_lock);
10709 			}
10710 			break;	/* goto sizeof (int) option return */
10711 		case IPV6_RECVRTHDRDSTOPTS:
10712 			if (!checkonly) {
10713 				mutex_enter(&connp->conn_lock);
10714 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
10715 				mutex_exit(&connp->conn_lock);
10716 			}
10717 			break;	/* goto sizeof (int) option return */
10718 		case IPV6_PKTINFO:
10719 			if (inlen == 0)
10720 				return (-EINVAL);	/* clearing option */
10721 			error = ip6_set_pktinfo(cr, connp,
10722 			    (struct in6_pktinfo *)invalp, first_mp);
10723 			if (error != 0)
10724 				*outlenp = 0;
10725 			else
10726 				*outlenp = inlen;
10727 			return (error);
10728 		case IPV6_NEXTHOP: {
10729 			struct sockaddr_in6 *sin6;
10730 
10731 			/* Verify that the nexthop is reachable */
10732 			if (inlen == 0)
10733 				return (-EINVAL);	/* clearing option */
10734 
10735 			sin6 = (struct sockaddr_in6 *)invalp;
10736 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
10737 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
10738 			    NULL, MATCH_IRE_DEFAULT);
10739 
10740 			if (ire == NULL) {
10741 				*outlenp = 0;
10742 				return (EHOSTUNREACH);
10743 			}
10744 			ire_refrele(ire);
10745 			return (-EINVAL);
10746 		}
10747 		case IPV6_SEC_OPT:
10748 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10749 			if (error != 0) {
10750 				*outlenp = 0;
10751 				return (error);
10752 			}
10753 			break;
10754 		case IPV6_SRC_PREFERENCES: {
10755 			/*
10756 			 * This is implemented strictly in the ip module
10757 			 * (here and in tcp_opt_*() to accomodate tcp
10758 			 * sockets).  Modules above ip pass this option
10759 			 * down here since ip is the only one that needs to
10760 			 * be aware of source address preferences.
10761 			 *
10762 			 * This socket option only affects connected
10763 			 * sockets that haven't already bound to a specific
10764 			 * IPv6 address.  In other words, sockets that
10765 			 * don't call bind() with an address other than the
10766 			 * unspecified address and that call connect().
10767 			 * ip_bind_connected_v6() passes these preferences
10768 			 * to the ipif_select_source_v6() function.
10769 			 */
10770 			if (inlen != sizeof (uint32_t))
10771 				return (EINVAL);
10772 			error = ip6_set_src_preferences(connp,
10773 			    *(uint32_t *)invalp);
10774 			if (error != 0) {
10775 				*outlenp = 0;
10776 				return (error);
10777 			} else {
10778 				*outlenp = sizeof (uint32_t);
10779 			}
10780 			break;
10781 		}
10782 		case IPV6_V6ONLY:
10783 			if (*i1 < 0 || *i1 > 1) {
10784 				return (EINVAL);
10785 			}
10786 			mutex_enter(&connp->conn_lock);
10787 			connp->conn_ipv6_v6only = *i1;
10788 			mutex_exit(&connp->conn_lock);
10789 			break;
10790 		default:
10791 			return (-EINVAL);
10792 		}
10793 		break;
10794 	default:
10795 		/*
10796 		 * "soft" error (negative)
10797 		 * option not handled at this level
10798 		 * Note: Do not modify *outlenp
10799 		 */
10800 		return (-EINVAL);
10801 	}
10802 	/*
10803 	 * Common case of return from an option that is sizeof (int)
10804 	 */
10805 	*(int *)outvalp = *i1;
10806 	*outlenp = sizeof (int);
10807 	return (0);
10808 }
10809 
10810 /*
10811  * This routine gets default values of certain options whose default
10812  * values are maintained by protocol specific code
10813  */
10814 /* ARGSUSED */
10815 int
10816 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
10817 {
10818 	int *i1 = (int *)ptr;
10819 
10820 	switch (level) {
10821 	case IPPROTO_IP:
10822 		switch (name) {
10823 		case IP_MULTICAST_TTL:
10824 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
10825 			return (sizeof (uchar_t));
10826 		case IP_MULTICAST_LOOP:
10827 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
10828 			return (sizeof (uchar_t));
10829 		default:
10830 			return (-1);
10831 		}
10832 	case IPPROTO_IPV6:
10833 		switch (name) {
10834 		case IPV6_UNICAST_HOPS:
10835 			*i1 = ipv6_def_hops;
10836 			return (sizeof (int));
10837 		case IPV6_MULTICAST_HOPS:
10838 			*i1 = IP_DEFAULT_MULTICAST_TTL;
10839 			return (sizeof (int));
10840 		case IPV6_MULTICAST_LOOP:
10841 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
10842 			return (sizeof (int));
10843 		case IPV6_V6ONLY:
10844 			*i1 = 1;
10845 			return (sizeof (int));
10846 		default:
10847 			return (-1);
10848 		}
10849 	default:
10850 		return (-1);
10851 	}
10852 	/* NOTREACHED */
10853 }
10854 
10855 /*
10856  * Given a destination address and a pointer to where to put the information
10857  * this routine fills in the mtuinfo.
10858  */
10859 int
10860 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
10861     struct ip6_mtuinfo *mtuinfo)
10862 {
10863 	ire_t *ire;
10864 
10865 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
10866 		return (-1);
10867 
10868 	bzero(mtuinfo, sizeof (*mtuinfo));
10869 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
10870 	mtuinfo->ip6m_addr.sin6_port = port;
10871 	mtuinfo->ip6m_addr.sin6_addr = *in6;
10872 
10873 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
10874 	if (ire != NULL) {
10875 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
10876 		ire_refrele(ire);
10877 	} else {
10878 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
10879 	}
10880 	return (sizeof (struct ip6_mtuinfo));
10881 }
10882 
10883 /*
10884  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
10885  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
10886  * isn't.  This doesn't matter as the error checking is done properly for the
10887  * other MRT options coming in through ip_opt_set.
10888  */
10889 int
10890 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
10891 {
10892 	conn_t		*connp = Q_TO_CONN(q);
10893 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
10894 
10895 	switch (level) {
10896 	case IPPROTO_IP:
10897 		switch (name) {
10898 		case MRT_VERSION:
10899 		case MRT_ASSERT:
10900 			(void) ip_mrouter_get(name, q, ptr);
10901 			return (sizeof (int));
10902 		case IP_SEC_OPT:
10903 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
10904 		case IP_NEXTHOP:
10905 			if (connp->conn_nexthop_set) {
10906 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
10907 				return (sizeof (ipaddr_t));
10908 			} else
10909 				return (0);
10910 		default:
10911 			break;
10912 		}
10913 		break;
10914 	case IPPROTO_IPV6:
10915 		switch (name) {
10916 		case IPV6_SEC_OPT:
10917 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
10918 		case IPV6_SRC_PREFERENCES: {
10919 			return (ip6_get_src_preferences(connp,
10920 			    (uint32_t *)ptr));
10921 		}
10922 		case IPV6_V6ONLY:
10923 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
10924 			return (sizeof (int));
10925 		case IPV6_PATHMTU:
10926 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
10927 				(struct ip6_mtuinfo *)ptr));
10928 		default:
10929 			break;
10930 		}
10931 		break;
10932 	default:
10933 		break;
10934 	}
10935 	return (-1);
10936 }
10937 
10938 /* Named Dispatch routine to get a current value out of our parameter table. */
10939 /* ARGSUSED */
10940 static int
10941 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10942 {
10943 	ipparam_t *ippa = (ipparam_t *)cp;
10944 
10945 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
10946 	return (0);
10947 }
10948 
10949 /* ARGSUSED */
10950 static int
10951 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
10952 {
10953 
10954 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
10955 	return (0);
10956 }
10957 
10958 /*
10959  * Set ip{,6}_forwarding values.  This means walking through all of the
10960  * ill's and toggling their forwarding values.
10961  */
10962 /* ARGSUSED */
10963 static int
10964 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
10965 {
10966 	long new_value;
10967 	int *forwarding_value = (int *)cp;
10968 	ill_t *walker;
10969 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
10970 	ill_walk_context_t ctx;
10971 
10972 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
10973 	    new_value < 0 || new_value > 1) {
10974 		return (EINVAL);
10975 	}
10976 
10977 	*forwarding_value = new_value;
10978 
10979 	/*
10980 	 * Regardless of the current value of ip_forwarding, set all per-ill
10981 	 * values of ip_forwarding to the value being set.
10982 	 *
10983 	 * Bring all the ill's up to date with the new global value.
10984 	 */
10985 	rw_enter(&ill_g_lock, RW_READER);
10986 
10987 	if (isv6)
10988 		walker = ILL_START_WALK_V6(&ctx);
10989 	else
10990 		walker = ILL_START_WALK_V4(&ctx);
10991 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
10992 		(void) ill_forward_set(q, mp, (new_value != 0),
10993 		    (caddr_t)walker);
10994 	}
10995 	rw_exit(&ill_g_lock);
10996 
10997 	return (0);
10998 }
10999 
11000 /*
11001  * Walk through the param array specified registering each element with the
11002  * Named Dispatch handler. This is called only during init. So it is ok
11003  * not to acquire any locks
11004  */
11005 static boolean_t
11006 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11007     ipndp_t *ipnd, size_t ipnd_cnt)
11008 {
11009 	for (; ippa_cnt-- > 0; ippa++) {
11010 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11011 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11012 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11013 				nd_free(&ip_g_nd);
11014 				return (B_FALSE);
11015 			}
11016 		}
11017 	}
11018 
11019 	for (; ipnd_cnt-- > 0; ipnd++) {
11020 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11021 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11022 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11023 			    ipnd->ip_ndp_data)) {
11024 				nd_free(&ip_g_nd);
11025 				return (B_FALSE);
11026 			}
11027 		}
11028 	}
11029 
11030 	return (B_TRUE);
11031 }
11032 
11033 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11034 /* ARGSUSED */
11035 static int
11036 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11037 {
11038 	long		new_value;
11039 	ipparam_t	*ippa = (ipparam_t *)cp;
11040 
11041 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11042 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11043 		return (EINVAL);
11044 	}
11045 	ippa->ip_param_value = new_value;
11046 	return (0);
11047 }
11048 
11049 /*
11050  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11051  * When an ipf is passed here for the first time, if
11052  * we already have in-order fragments on the queue, we convert from the fast-
11053  * path reassembly scheme to the hard-case scheme.  From then on, additional
11054  * fragments are reassembled here.  We keep track of the start and end offsets
11055  * of each piece, and the number of holes in the chain.  When the hole count
11056  * goes to zero, we are done!
11057  *
11058  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11059  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11060  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11061  * after the call to ip_reassemble().
11062  */
11063 int
11064 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11065     size_t msg_len)
11066 {
11067 	uint_t	end;
11068 	mblk_t	*next_mp;
11069 	mblk_t	*mp1;
11070 	uint_t	offset;
11071 	boolean_t incr_dups = B_TRUE;
11072 	boolean_t offset_zero_seen = B_FALSE;
11073 	boolean_t pkt_boundary_checked = B_FALSE;
11074 
11075 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11076 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11077 
11078 	/* Add in byte count */
11079 	ipf->ipf_count += msg_len;
11080 	if (ipf->ipf_end) {
11081 		/*
11082 		 * We were part way through in-order reassembly, but now there
11083 		 * is a hole.  We walk through messages already queued, and
11084 		 * mark them for hard case reassembly.  We know that up till
11085 		 * now they were in order starting from offset zero.
11086 		 */
11087 		offset = 0;
11088 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11089 			IP_REASS_SET_START(mp1, offset);
11090 			if (offset == 0) {
11091 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11092 				offset = -ipf->ipf_nf_hdr_len;
11093 			}
11094 			offset += mp1->b_wptr - mp1->b_rptr;
11095 			IP_REASS_SET_END(mp1, offset);
11096 		}
11097 		/* One hole at the end. */
11098 		ipf->ipf_hole_cnt = 1;
11099 		/* Brand it as a hard case, forever. */
11100 		ipf->ipf_end = 0;
11101 	}
11102 	/* Walk through all the new pieces. */
11103 	do {
11104 		end = start + (mp->b_wptr - mp->b_rptr);
11105 		/*
11106 		 * If start is 0, decrease 'end' only for the first mblk of
11107 		 * the fragment. Otherwise 'end' can get wrong value in the
11108 		 * second pass of the loop if first mblk is exactly the
11109 		 * size of ipf_nf_hdr_len.
11110 		 */
11111 		if (start == 0 && !offset_zero_seen) {
11112 			/* First segment */
11113 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11114 			end -= ipf->ipf_nf_hdr_len;
11115 			offset_zero_seen = B_TRUE;
11116 		}
11117 		next_mp = mp->b_cont;
11118 		/*
11119 		 * We are checking to see if there is any interesing data
11120 		 * to process.  If there isn't and the mblk isn't the
11121 		 * one which carries the unfragmentable header then we
11122 		 * drop it.  It's possible to have just the unfragmentable
11123 		 * header come through without any data.  That needs to be
11124 		 * saved.
11125 		 *
11126 		 * If the assert at the top of this function holds then the
11127 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11128 		 * is infrequently traveled enough that the test is left in
11129 		 * to protect against future code changes which break that
11130 		 * invariant.
11131 		 */
11132 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11133 			/* Empty.  Blast it. */
11134 			IP_REASS_SET_START(mp, 0);
11135 			IP_REASS_SET_END(mp, 0);
11136 			/*
11137 			 * If the ipf points to the mblk we are about to free,
11138 			 * update ipf to point to the next mblk (or NULL
11139 			 * if none).
11140 			 */
11141 			if (ipf->ipf_mp->b_cont == mp)
11142 				ipf->ipf_mp->b_cont = next_mp;
11143 			freeb(mp);
11144 			continue;
11145 		}
11146 		mp->b_cont = NULL;
11147 		IP_REASS_SET_START(mp, start);
11148 		IP_REASS_SET_END(mp, end);
11149 		if (!ipf->ipf_tail_mp) {
11150 			ipf->ipf_tail_mp = mp;
11151 			ipf->ipf_mp->b_cont = mp;
11152 			if (start == 0 || !more) {
11153 				ipf->ipf_hole_cnt = 1;
11154 				/*
11155 				 * if the first fragment comes in more than one
11156 				 * mblk, this loop will be executed for each
11157 				 * mblk. Need to adjust hole count so exiting
11158 				 * this routine will leave hole count at 1.
11159 				 */
11160 				if (next_mp)
11161 					ipf->ipf_hole_cnt++;
11162 			} else
11163 				ipf->ipf_hole_cnt = 2;
11164 			continue;
11165 		} else if (ipf->ipf_last_frag_seen && !more &&
11166 			    !pkt_boundary_checked) {
11167 			/*
11168 			 * We check datagram boundary only if this fragment
11169 			 * claims to be the last fragment and we have seen a
11170 			 * last fragment in the past too. We do this only
11171 			 * once for a given fragment.
11172 			 *
11173 			 * start cannot be 0 here as fragments with start=0
11174 			 * and MF=0 gets handled as a complete packet. These
11175 			 * fragments should not reach here.
11176 			 */
11177 
11178 			if (start + msgdsize(mp) !=
11179 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11180 				/*
11181 				 * We have two fragments both of which claim
11182 				 * to be the last fragment but gives conflicting
11183 				 * information about the whole datagram size.
11184 				 * Something fishy is going on. Drop the
11185 				 * fragment and free up the reassembly list.
11186 				 */
11187 				return (IP_REASS_FAILED);
11188 			}
11189 
11190 			/*
11191 			 * We shouldn't come to this code block again for this
11192 			 * particular fragment.
11193 			 */
11194 			pkt_boundary_checked = B_TRUE;
11195 		}
11196 
11197 		/* New stuff at or beyond tail? */
11198 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11199 		if (start >= offset) {
11200 			if (ipf->ipf_last_frag_seen) {
11201 				/* current fragment is beyond last fragment */
11202 				return (IP_REASS_FAILED);
11203 			}
11204 			/* Link it on end. */
11205 			ipf->ipf_tail_mp->b_cont = mp;
11206 			ipf->ipf_tail_mp = mp;
11207 			if (more) {
11208 				if (start != offset)
11209 					ipf->ipf_hole_cnt++;
11210 			} else if (start == offset && next_mp == NULL)
11211 					ipf->ipf_hole_cnt--;
11212 			continue;
11213 		}
11214 		mp1 = ipf->ipf_mp->b_cont;
11215 		offset = IP_REASS_START(mp1);
11216 		/* New stuff at the front? */
11217 		if (start < offset) {
11218 			if (start == 0) {
11219 				if (end >= offset) {
11220 					/* Nailed the hole at the begining. */
11221 					ipf->ipf_hole_cnt--;
11222 				}
11223 			} else if (end < offset) {
11224 				/*
11225 				 * A hole, stuff, and a hole where there used
11226 				 * to be just a hole.
11227 				 */
11228 				ipf->ipf_hole_cnt++;
11229 			}
11230 			mp->b_cont = mp1;
11231 			/* Check for overlap. */
11232 			while (end > offset) {
11233 				if (end < IP_REASS_END(mp1)) {
11234 					mp->b_wptr -= end - offset;
11235 					IP_REASS_SET_END(mp, offset);
11236 					if (ill->ill_isv6) {
11237 						BUMP_MIB(ill->ill_ip6_mib,
11238 						    ipv6ReasmPartDups);
11239 					} else {
11240 						BUMP_MIB(&ip_mib,
11241 						    ipReasmPartDups);
11242 					}
11243 					break;
11244 				}
11245 				/* Did we cover another hole? */
11246 				if ((mp1->b_cont &&
11247 				    IP_REASS_END(mp1) !=
11248 				    IP_REASS_START(mp1->b_cont) &&
11249 				    end >= IP_REASS_START(mp1->b_cont)) ||
11250 				    (!ipf->ipf_last_frag_seen && !more)) {
11251 					ipf->ipf_hole_cnt--;
11252 				}
11253 				/* Clip out mp1. */
11254 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11255 					/*
11256 					 * After clipping out mp1, this guy
11257 					 * is now hanging off the end.
11258 					 */
11259 					ipf->ipf_tail_mp = mp;
11260 				}
11261 				IP_REASS_SET_START(mp1, 0);
11262 				IP_REASS_SET_END(mp1, 0);
11263 				/* Subtract byte count */
11264 				ipf->ipf_count -= mp1->b_datap->db_lim -
11265 				    mp1->b_datap->db_base;
11266 				freeb(mp1);
11267 				if (ill->ill_isv6) {
11268 					BUMP_MIB(ill->ill_ip6_mib,
11269 					    ipv6ReasmPartDups);
11270 				} else {
11271 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11272 				}
11273 				mp1 = mp->b_cont;
11274 				if (!mp1)
11275 					break;
11276 				offset = IP_REASS_START(mp1);
11277 			}
11278 			ipf->ipf_mp->b_cont = mp;
11279 			continue;
11280 		}
11281 		/*
11282 		 * The new piece starts somewhere between the start of the head
11283 		 * and before the end of the tail.
11284 		 */
11285 		for (; mp1; mp1 = mp1->b_cont) {
11286 			offset = IP_REASS_END(mp1);
11287 			if (start < offset) {
11288 				if (end <= offset) {
11289 					/* Nothing new. */
11290 					IP_REASS_SET_START(mp, 0);
11291 					IP_REASS_SET_END(mp, 0);
11292 					/* Subtract byte count */
11293 					ipf->ipf_count -= mp->b_datap->db_lim -
11294 					    mp->b_datap->db_base;
11295 					if (incr_dups) {
11296 						ipf->ipf_num_dups++;
11297 						incr_dups = B_FALSE;
11298 					}
11299 					freeb(mp);
11300 					if (ill->ill_isv6) {
11301 						BUMP_MIB(ill->ill_ip6_mib,
11302 						    ipv6ReasmDuplicates);
11303 					} else {
11304 						BUMP_MIB(&ip_mib,
11305 						    ipReasmDuplicates);
11306 					}
11307 					break;
11308 				}
11309 				/*
11310 				 * Trim redundant stuff off beginning of new
11311 				 * piece.
11312 				 */
11313 				IP_REASS_SET_START(mp, offset);
11314 				mp->b_rptr += offset - start;
11315 				if (ill->ill_isv6) {
11316 					BUMP_MIB(ill->ill_ip6_mib,
11317 					    ipv6ReasmPartDups);
11318 				} else {
11319 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11320 				}
11321 				start = offset;
11322 				if (!mp1->b_cont) {
11323 					/*
11324 					 * After trimming, this guy is now
11325 					 * hanging off the end.
11326 					 */
11327 					mp1->b_cont = mp;
11328 					ipf->ipf_tail_mp = mp;
11329 					if (!more) {
11330 						ipf->ipf_hole_cnt--;
11331 					}
11332 					break;
11333 				}
11334 			}
11335 			if (start >= IP_REASS_START(mp1->b_cont))
11336 				continue;
11337 			/* Fill a hole */
11338 			if (start > offset)
11339 				ipf->ipf_hole_cnt++;
11340 			mp->b_cont = mp1->b_cont;
11341 			mp1->b_cont = mp;
11342 			mp1 = mp->b_cont;
11343 			offset = IP_REASS_START(mp1);
11344 			if (end >= offset) {
11345 				ipf->ipf_hole_cnt--;
11346 				/* Check for overlap. */
11347 				while (end > offset) {
11348 					if (end < IP_REASS_END(mp1)) {
11349 						mp->b_wptr -= end - offset;
11350 						IP_REASS_SET_END(mp, offset);
11351 						/*
11352 						 * TODO we might bump
11353 						 * this up twice if there is
11354 						 * overlap at both ends.
11355 						 */
11356 						if (ill->ill_isv6) {
11357 							BUMP_MIB(
11358 							    ill->ill_ip6_mib,
11359 							    ipv6ReasmPartDups);
11360 						} else {
11361 							BUMP_MIB(&ip_mib,
11362 							    ipReasmPartDups);
11363 						}
11364 						break;
11365 					}
11366 					/* Did we cover another hole? */
11367 					if ((mp1->b_cont &&
11368 					    IP_REASS_END(mp1)
11369 					    != IP_REASS_START(mp1->b_cont) &&
11370 					    end >=
11371 					    IP_REASS_START(mp1->b_cont)) ||
11372 					    (!ipf->ipf_last_frag_seen &&
11373 					    !more)) {
11374 						ipf->ipf_hole_cnt--;
11375 					}
11376 					/* Clip out mp1. */
11377 					if ((mp->b_cont = mp1->b_cont) ==
11378 					    NULL) {
11379 						/*
11380 						 * After clipping out mp1,
11381 						 * this guy is now hanging
11382 						 * off the end.
11383 						 */
11384 						ipf->ipf_tail_mp = mp;
11385 					}
11386 					IP_REASS_SET_START(mp1, 0);
11387 					IP_REASS_SET_END(mp1, 0);
11388 					/* Subtract byte count */
11389 					ipf->ipf_count -=
11390 					    mp1->b_datap->db_lim -
11391 					    mp1->b_datap->db_base;
11392 					freeb(mp1);
11393 					if (ill->ill_isv6) {
11394 						BUMP_MIB(ill->ill_ip6_mib,
11395 						    ipv6ReasmPartDups);
11396 					} else {
11397 						BUMP_MIB(&ip_mib,
11398 						    ipReasmPartDups);
11399 					}
11400 					mp1 = mp->b_cont;
11401 					if (!mp1)
11402 						break;
11403 					offset = IP_REASS_START(mp1);
11404 				}
11405 			}
11406 			break;
11407 		}
11408 	} while (start = end, mp = next_mp);
11409 
11410 	/* Fragment just processed could be the last one. Remember this fact */
11411 	if (!more)
11412 		ipf->ipf_last_frag_seen = B_TRUE;
11413 
11414 	/* Still got holes? */
11415 	if (ipf->ipf_hole_cnt)
11416 		return (IP_REASS_PARTIAL);
11417 	/* Clean up overloaded fields to avoid upstream disasters. */
11418 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11419 		IP_REASS_SET_START(mp1, 0);
11420 		IP_REASS_SET_END(mp1, 0);
11421 	}
11422 	return (IP_REASS_COMPLETE);
11423 }
11424 
11425 /*
11426  * ipsec processing for the fast path, used for input UDP Packets
11427  */
11428 static boolean_t
11429 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11430     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11431 {
11432 	uint32_t	ill_index;
11433 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11434 
11435 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11436 	/* The ill_index of the incoming ILL */
11437 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11438 
11439 	/* pass packet up to the transport */
11440 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11441 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11442 		    NULL, mctl_present);
11443 		if (*first_mpp == NULL) {
11444 			return (B_FALSE);
11445 		}
11446 	}
11447 
11448 	/* Initiate IPPF processing for fastpath UDP */
11449 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11450 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11451 		if (*mpp == NULL) {
11452 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11453 			    "deferred/dropped during IPPF processing\n"));
11454 			return (B_FALSE);
11455 		}
11456 	}
11457 	/*
11458 	 * We make the checks as below since we are in the fast path
11459 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11460 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11461 	 */
11462 	if (connp->conn_recvif || connp->conn_recvslla ||
11463 	    connp->conn_ipv6_recvpktinfo) {
11464 		if (connp->conn_recvif ||
11465 		    connp->conn_ipv6_recvpktinfo) {
11466 			in_flags = IPF_RECVIF;
11467 		}
11468 		if (connp->conn_recvslla) {
11469 			in_flags |= IPF_RECVSLLA;
11470 		}
11471 		/*
11472 		 * since in_flags are being set ill will be
11473 		 * referenced in ip_add_info, so it better not
11474 		 * be NULL.
11475 		 */
11476 		/*
11477 		 * the actual data will be contained in b_cont
11478 		 * upon successful return of the following call.
11479 		 * If the call fails then the original mblk is
11480 		 * returned.
11481 		 */
11482 		*mpp = ip_add_info(*mpp, ill, in_flags);
11483 	}
11484 
11485 	return (B_TRUE);
11486 }
11487 
11488 /*
11489  * Fragmentation reassembly.  Each ILL has a hash table for
11490  * queuing packets undergoing reassembly for all IPIFs
11491  * associated with the ILL.  The hash is based on the packet
11492  * IP ident field.  The ILL frag hash table was allocated
11493  * as a timer block at the time the ILL was created.  Whenever
11494  * there is anything on the reassembly queue, the timer will
11495  * be running.  Returns B_TRUE if successful else B_FALSE;
11496  * frees mp on failure.
11497  */
11498 static boolean_t
11499 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11500     uint32_t *cksum_val, uint16_t *cksum_flags)
11501 {
11502 	uint32_t	frag_offset_flags;
11503 	ill_t		*ill = (ill_t *)q->q_ptr;
11504 	mblk_t		*mp = *mpp;
11505 	mblk_t		*t_mp;
11506 	ipaddr_t	dst;
11507 	uint8_t		proto = ipha->ipha_protocol;
11508 	uint32_t	sum_val;
11509 	uint16_t	sum_flags;
11510 	ipf_t		*ipf;
11511 	ipf_t		**ipfp;
11512 	ipfb_t		*ipfb;
11513 	uint16_t	ident;
11514 	uint32_t	offset;
11515 	ipaddr_t	src;
11516 	uint_t		hdr_length;
11517 	uint32_t	end;
11518 	mblk_t		*mp1;
11519 	mblk_t		*tail_mp;
11520 	size_t		count;
11521 	size_t		msg_len;
11522 	uint8_t		ecn_info = 0;
11523 	uint32_t	packet_size;
11524 	boolean_t	pruned = B_FALSE;
11525 
11526 	if (cksum_val != NULL)
11527 		*cksum_val = 0;
11528 	if (cksum_flags != NULL)
11529 		*cksum_flags = 0;
11530 
11531 	/*
11532 	 * Drop the fragmented as early as possible, if
11533 	 * we don't have resource(s) to re-assemble.
11534 	 */
11535 	if (ip_reass_queue_bytes == 0) {
11536 		freemsg(mp);
11537 		return (B_FALSE);
11538 	}
11539 
11540 	/* Check for fragmentation offset; return if there's none */
11541 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
11542 	    (IPH_MF | IPH_OFFSET)) == 0)
11543 		return (B_TRUE);
11544 
11545 	/*
11546 	 * We utilize hardware computed checksum info only for UDP since
11547 	 * IP fragmentation is a normal occurence for the protocol.  In
11548 	 * addition, checksum offload support for IP fragments carrying
11549 	 * UDP payload is commonly implemented across network adapters.
11550 	 */
11551 	ASSERT(ill != NULL);
11552 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
11553 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
11554 		mblk_t *mp1 = mp->b_cont;
11555 		int32_t len;
11556 
11557 		/* Record checksum information from the packet */
11558 		sum_val = (uint32_t)DB_CKSUM16(mp);
11559 		sum_flags = DB_CKSUMFLAGS(mp);
11560 
11561 		/* IP payload offset from beginning of mblk */
11562 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
11563 
11564 		if ((sum_flags & HCK_PARTIALCKSUM) &&
11565 		    (mp1 == NULL || mp1->b_cont == NULL) &&
11566 		    offset >= DB_CKSUMSTART(mp) &&
11567 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
11568 			uint32_t adj;
11569 			/*
11570 			 * Partial checksum has been calculated by hardware
11571 			 * and attached to the packet; in addition, any
11572 			 * prepended extraneous data is even byte aligned.
11573 			 * If any such data exists, we adjust the checksum;
11574 			 * this would also handle any postpended data.
11575 			 */
11576 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
11577 			    mp, mp1, len, adj);
11578 
11579 			/* One's complement subtract extraneous checksum */
11580 			if (adj >= sum_val)
11581 				sum_val = ~(adj - sum_val) & 0xFFFF;
11582 			else
11583 				sum_val -= adj;
11584 		}
11585 	} else {
11586 		sum_val = 0;
11587 		sum_flags = 0;
11588 	}
11589 
11590 	/* Clear hardware checksumming flag */
11591 	DB_CKSUMFLAGS(mp) = 0;
11592 
11593 	ident = ipha->ipha_ident;
11594 	offset = (frag_offset_flags << 3) & 0xFFFF;
11595 	src = ipha->ipha_src;
11596 	dst = ipha->ipha_dst;
11597 	hdr_length = IPH_HDR_LENGTH(ipha);
11598 	end = ntohs(ipha->ipha_length) - hdr_length;
11599 
11600 	/* If end == 0 then we have a packet with no data, so just free it */
11601 	if (end == 0) {
11602 		freemsg(mp);
11603 		return (B_FALSE);
11604 	}
11605 
11606 	/* Record the ECN field info. */
11607 	ecn_info = (ipha->ipha_type_of_service & 0x3);
11608 	if (offset != 0) {
11609 		/*
11610 		 * If this isn't the first piece, strip the header, and
11611 		 * add the offset to the end value.
11612 		 */
11613 		mp->b_rptr += hdr_length;
11614 		end += offset;
11615 	}
11616 
11617 	msg_len = MBLKSIZE(mp);
11618 	tail_mp = mp;
11619 	while (tail_mp->b_cont != NULL) {
11620 		tail_mp = tail_mp->b_cont;
11621 		msg_len += MBLKSIZE(tail_mp);
11622 	}
11623 
11624 	/* If the reassembly list for this ILL will get too big, prune it */
11625 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
11626 	    ip_reass_queue_bytes) {
11627 		ill_frag_prune(ill,
11628 		    (ip_reass_queue_bytes < msg_len) ? 0 :
11629 		    (ip_reass_queue_bytes - msg_len));
11630 		pruned = B_TRUE;
11631 	}
11632 
11633 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
11634 	mutex_enter(&ipfb->ipfb_lock);
11635 
11636 	ipfp = &ipfb->ipfb_ipf;
11637 	/* Try to find an existing fragment queue for this packet. */
11638 	for (;;) {
11639 		ipf = ipfp[0];
11640 		if (ipf != NULL) {
11641 			/*
11642 			 * It has to match on ident and src/dst address.
11643 			 */
11644 			if (ipf->ipf_ident == ident &&
11645 			    ipf->ipf_src == src &&
11646 			    ipf->ipf_dst == dst &&
11647 			    ipf->ipf_protocol == proto) {
11648 				/*
11649 				 * If we have received too many
11650 				 * duplicate fragments for this packet
11651 				 * free it.
11652 				 */
11653 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
11654 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
11655 					freemsg(mp);
11656 					mutex_exit(&ipfb->ipfb_lock);
11657 					return (B_FALSE);
11658 				}
11659 				/* Found it. */
11660 				break;
11661 			}
11662 			ipfp = &ipf->ipf_hash_next;
11663 			continue;
11664 		}
11665 
11666 		/*
11667 		 * If we pruned the list, do we want to store this new
11668 		 * fragment?. We apply an optimization here based on the
11669 		 * fact that most fragments will be received in order.
11670 		 * So if the offset of this incoming fragment is zero,
11671 		 * it is the first fragment of a new packet. We will
11672 		 * keep it.  Otherwise drop the fragment, as we have
11673 		 * probably pruned the packet already (since the
11674 		 * packet cannot be found).
11675 		 */
11676 		if (pruned && offset != 0) {
11677 			mutex_exit(&ipfb->ipfb_lock);
11678 			freemsg(mp);
11679 			return (B_FALSE);
11680 		}
11681 
11682 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
11683 			/*
11684 			 * Too many fragmented packets in this hash
11685 			 * bucket. Free the oldest.
11686 			 */
11687 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
11688 		}
11689 
11690 		/* New guy.  Allocate a frag message. */
11691 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
11692 		if (mp1 == NULL) {
11693 			BUMP_MIB(&ip_mib, ipInDiscards);
11694 			freemsg(mp);
11695 reass_done:
11696 			mutex_exit(&ipfb->ipfb_lock);
11697 			return (B_FALSE);
11698 		}
11699 
11700 
11701 		BUMP_MIB(&ip_mib, ipReasmReqds);
11702 		mp1->b_cont = mp;
11703 
11704 		/* Initialize the fragment header. */
11705 		ipf = (ipf_t *)mp1->b_rptr;
11706 		ipf->ipf_mp = mp1;
11707 		ipf->ipf_ptphn = ipfp;
11708 		ipfp[0] = ipf;
11709 		ipf->ipf_hash_next = NULL;
11710 		ipf->ipf_ident = ident;
11711 		ipf->ipf_protocol = proto;
11712 		ipf->ipf_src = src;
11713 		ipf->ipf_dst = dst;
11714 		ipf->ipf_nf_hdr_len = 0;
11715 		/* Record reassembly start time. */
11716 		ipf->ipf_timestamp = gethrestime_sec();
11717 		/* Record ipf generation and account for frag header */
11718 		ipf->ipf_gen = ill->ill_ipf_gen++;
11719 		ipf->ipf_count = MBLKSIZE(mp1);
11720 		ipf->ipf_last_frag_seen = B_FALSE;
11721 		ipf->ipf_ecn = ecn_info;
11722 		ipf->ipf_num_dups = 0;
11723 		ipfb->ipfb_frag_pkts++;
11724 		ipf->ipf_checksum = 0;
11725 		ipf->ipf_checksum_flags = 0;
11726 
11727 		/* Store checksum value in fragment header */
11728 		if (sum_flags != 0) {
11729 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11730 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11731 			ipf->ipf_checksum = sum_val;
11732 			ipf->ipf_checksum_flags = sum_flags;
11733 		}
11734 
11735 		/*
11736 		 * We handle reassembly two ways.  In the easy case,
11737 		 * where all the fragments show up in order, we do
11738 		 * minimal bookkeeping, and just clip new pieces on
11739 		 * the end.  If we ever see a hole, then we go off
11740 		 * to ip_reassemble which has to mark the pieces and
11741 		 * keep track of the number of holes, etc.  Obviously,
11742 		 * the point of having both mechanisms is so we can
11743 		 * handle the easy case as efficiently as possible.
11744 		 */
11745 		if (offset == 0) {
11746 			/* Easy case, in-order reassembly so far. */
11747 			ipf->ipf_count += msg_len;
11748 			ipf->ipf_tail_mp = tail_mp;
11749 			/*
11750 			 * Keep track of next expected offset in
11751 			 * ipf_end.
11752 			 */
11753 			ipf->ipf_end = end;
11754 			ipf->ipf_nf_hdr_len = hdr_length;
11755 		} else {
11756 			/* Hard case, hole at the beginning. */
11757 			ipf->ipf_tail_mp = NULL;
11758 			/*
11759 			 * ipf_end == 0 means that we have given up
11760 			 * on easy reassembly.
11761 			 */
11762 			ipf->ipf_end = 0;
11763 
11764 			/* Forget checksum offload from now on */
11765 			ipf->ipf_checksum_flags = 0;
11766 
11767 			/*
11768 			 * ipf_hole_cnt is set by ip_reassemble.
11769 			 * ipf_count is updated by ip_reassemble.
11770 			 * No need to check for return value here
11771 			 * as we don't expect reassembly to complete
11772 			 * or fail for the first fragment itself.
11773 			 */
11774 			(void) ip_reassemble(mp, ipf,
11775 			    (frag_offset_flags & IPH_OFFSET) << 3,
11776 			    (frag_offset_flags & IPH_MF), ill, msg_len);
11777 		}
11778 		/* Update per ipfb and ill byte counts */
11779 		ipfb->ipfb_count += ipf->ipf_count;
11780 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11781 		ill->ill_frag_count += ipf->ipf_count;
11782 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11783 		/* If the frag timer wasn't already going, start it. */
11784 		mutex_enter(&ill->ill_lock);
11785 		ill_frag_timer_start(ill);
11786 		mutex_exit(&ill->ill_lock);
11787 		goto reass_done;
11788 	}
11789 
11790 	/*
11791 	 * If the packet's flag has changed (it could be coming up
11792 	 * from an interface different than the previous, therefore
11793 	 * possibly different checksum capability), then forget about
11794 	 * any stored checksum states.  Otherwise add the value to
11795 	 * the existing one stored in the fragment header.
11796 	 */
11797 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
11798 		sum_val += ipf->ipf_checksum;
11799 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11800 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
11801 		ipf->ipf_checksum = sum_val;
11802 	} else if (ipf->ipf_checksum_flags != 0) {
11803 		/* Forget checksum offload from now on */
11804 		ipf->ipf_checksum_flags = 0;
11805 	}
11806 
11807 	/*
11808 	 * We have a new piece of a datagram which is already being
11809 	 * reassembled.  Update the ECN info if all IP fragments
11810 	 * are ECN capable.  If there is one which is not, clear
11811 	 * all the info.  If there is at least one which has CE
11812 	 * code point, IP needs to report that up to transport.
11813 	 */
11814 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
11815 		if (ecn_info == IPH_ECN_CE)
11816 			ipf->ipf_ecn = IPH_ECN_CE;
11817 	} else {
11818 		ipf->ipf_ecn = IPH_ECN_NECT;
11819 	}
11820 	if (offset && ipf->ipf_end == offset) {
11821 		/* The new fragment fits at the end */
11822 		ipf->ipf_tail_mp->b_cont = mp;
11823 		/* Update the byte count */
11824 		ipf->ipf_count += msg_len;
11825 		/* Update per ipfb and ill byte counts */
11826 		ipfb->ipfb_count += msg_len;
11827 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
11828 		ill->ill_frag_count += msg_len;
11829 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
11830 		if (frag_offset_flags & IPH_MF) {
11831 			/* More to come. */
11832 			ipf->ipf_end = end;
11833 			ipf->ipf_tail_mp = tail_mp;
11834 			goto reass_done;
11835 		}
11836 	} else {
11837 		/* Go do the hard cases. */
11838 		int ret;
11839 
11840 		if (offset == 0)
11841 			ipf->ipf_nf_hdr_len = hdr_length;
11842 
11843 		/* Save current byte count */
11844 		count = ipf->ipf_count;
11845 		ret = ip_reassemble(mp, ipf,
11846 		    (frag_offset_flags & IPH_OFFSET) << 3,
11847 		    (frag_offset_flags & IPH_MF), ill, msg_len);
11848 		/* Count of bytes added and subtracted (freeb()ed) */
11849 		count = ipf->ipf_count - count;
11850 		if (count) {
11851 			/* Update per ipfb and ill byte counts */
11852 			ipfb->ipfb_count += count;
11853 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
11854 			ill->ill_frag_count += count;
11855 			ASSERT(ill->ill_frag_count > 0);
11856 		}
11857 		if (ret == IP_REASS_PARTIAL) {
11858 			goto reass_done;
11859 		} else if (ret == IP_REASS_FAILED) {
11860 			/* Reassembly failed. Free up all resources */
11861 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
11862 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
11863 				IP_REASS_SET_START(t_mp, 0);
11864 				IP_REASS_SET_END(t_mp, 0);
11865 			}
11866 			freemsg(mp);
11867 			goto reass_done;
11868 		}
11869 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
11870 	}
11871 	/*
11872 	 * We have completed reassembly.  Unhook the frag header from
11873 	 * the reassembly list.
11874 	 *
11875 	 * Before we free the frag header, record the ECN info
11876 	 * to report back to the transport.
11877 	 */
11878 	ecn_info = ipf->ipf_ecn;
11879 	BUMP_MIB(&ip_mib, ipReasmOKs);
11880 	ipfp = ipf->ipf_ptphn;
11881 
11882 	/* We need to supply these to caller */
11883 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
11884 		sum_val = ipf->ipf_checksum;
11885 	else
11886 		sum_val = 0;
11887 
11888 	mp1 = ipf->ipf_mp;
11889 	count = ipf->ipf_count;
11890 	ipf = ipf->ipf_hash_next;
11891 	if (ipf != NULL)
11892 		ipf->ipf_ptphn = ipfp;
11893 	ipfp[0] = ipf;
11894 	ill->ill_frag_count -= count;
11895 	ASSERT(ipfb->ipfb_count >= count);
11896 	ipfb->ipfb_count -= count;
11897 	ipfb->ipfb_frag_pkts--;
11898 	mutex_exit(&ipfb->ipfb_lock);
11899 	/* Ditch the frag header. */
11900 	mp = mp1->b_cont;
11901 
11902 	freeb(mp1);
11903 
11904 	/* Restore original IP length in header. */
11905 	packet_size = (uint32_t)msgdsize(mp);
11906 	if (packet_size > IP_MAXPACKET) {
11907 		freemsg(mp);
11908 		BUMP_MIB(&ip_mib, ipInHdrErrors);
11909 		return (B_FALSE);
11910 	}
11911 
11912 	if (DB_REF(mp) > 1) {
11913 		mblk_t *mp2 = copymsg(mp);
11914 
11915 		freemsg(mp);
11916 		if (mp2 == NULL) {
11917 			BUMP_MIB(&ip_mib, ipInDiscards);
11918 			return (B_FALSE);
11919 		}
11920 		mp = mp2;
11921 	}
11922 	ipha = (ipha_t *)mp->b_rptr;
11923 
11924 	ipha->ipha_length = htons((uint16_t)packet_size);
11925 	/* We're now complete, zip the frag state */
11926 	ipha->ipha_fragment_offset_and_flags = 0;
11927 	/* Record the ECN info. */
11928 	ipha->ipha_type_of_service &= 0xFC;
11929 	ipha->ipha_type_of_service |= ecn_info;
11930 	*mpp = mp;
11931 
11932 	/* Reassembly is successful; return checksum information if needed */
11933 	if (cksum_val != NULL)
11934 		*cksum_val = sum_val;
11935 	if (cksum_flags != NULL)
11936 		*cksum_flags = sum_flags;
11937 
11938 	return (B_TRUE);
11939 }
11940 
11941 /*
11942  * Perform ip header check sum update local options.
11943  * return B_TRUE if all is well, else return B_FALSE and release
11944  * the mp. caller is responsible for decrementing ire ref cnt.
11945  */
11946 static boolean_t
11947 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
11948 {
11949 	mblk_t		*first_mp;
11950 	boolean_t	mctl_present;
11951 	uint16_t	sum;
11952 
11953 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11954 	/*
11955 	 * Don't do the checksum if it has gone through AH/ESP
11956 	 * processing.
11957 	 */
11958 	if (!mctl_present) {
11959 		sum = ip_csum_hdr(ipha);
11960 		if (sum != 0) {
11961 			BUMP_MIB(&ip_mib, ipInCksumErrs);
11962 			freemsg(first_mp);
11963 			return (B_FALSE);
11964 		}
11965 	}
11966 
11967 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
11968 		if (mctl_present)
11969 			freeb(first_mp);
11970 		return (B_FALSE);
11971 	}
11972 
11973 	return (B_TRUE);
11974 }
11975 
11976 /*
11977  * All udp packet are delivered to the local host via this routine.
11978  */
11979 void
11980 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
11981     ill_t *recv_ill)
11982 {
11983 	uint32_t	sum;
11984 	uint32_t	u1;
11985 	boolean_t	mctl_present;
11986 	conn_t		*connp;
11987 	mblk_t		*first_mp;
11988 	uint16_t	*up;
11989 	ill_t		*ill = (ill_t *)q->q_ptr;
11990 	uint16_t	reass_hck_flags = 0;
11991 
11992 #define	rptr    ((uchar_t *)ipha)
11993 
11994 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
11995 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
11996 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11997 
11998 	/*
11999 	 * FAST PATH for udp packets
12000 	 */
12001 
12002 	/* u1 is # words of IP options */
12003 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12004 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12005 
12006 	/* IP options present */
12007 	if (u1 != 0)
12008 		goto ipoptions;
12009 
12010 	/* Check the IP header checksum.  */
12011 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12012 		/* Clear the IP header h/w cksum flag */
12013 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12014 	} else {
12015 #define	uph	((uint16_t *)ipha)
12016 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12017 		    uph[6] + uph[7] + uph[8] + uph[9];
12018 #undef	uph
12019 		/* finish doing IP checksum */
12020 		sum = (sum & 0xFFFF) + (sum >> 16);
12021 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12022 		/*
12023 		 * Don't verify header checksum if this packet is coming
12024 		 * back from AH/ESP as we already did it.
12025 		 */
12026 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12027 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12028 			freemsg(first_mp);
12029 			return;
12030 		}
12031 	}
12032 
12033 	/*
12034 	 * Count for SNMP of inbound packets for ire.
12035 	 * if mctl is present this might be a secure packet and
12036 	 * has already been counted for in ip_proto_input().
12037 	 */
12038 	if (!mctl_present) {
12039 		UPDATE_IB_PKT_COUNT(ire);
12040 		ire->ire_last_used_time = lbolt;
12041 	}
12042 
12043 	/* packet part of fragmented IP packet? */
12044 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12045 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12046 		goto fragmented;
12047 	}
12048 
12049 	/* u1 = IP header length (20 bytes) */
12050 	u1 = IP_SIMPLE_HDR_LENGTH;
12051 
12052 	/* packet does not contain complete IP & UDP headers */
12053 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12054 		goto udppullup;
12055 
12056 	/* up points to UDP header */
12057 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12058 #define	iphs    ((uint16_t *)ipha)
12059 
12060 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12061 	if (up[3] != 0) {
12062 		mblk_t *mp1 = mp->b_cont;
12063 		boolean_t cksum_err;
12064 		uint16_t hck_flags = 0;
12065 
12066 		/* Pseudo-header checksum */
12067 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12068 		    iphs[9] + up[2];
12069 
12070 		/*
12071 		 * Revert to software checksum calculation if the interface
12072 		 * isn't capable of checksum offload or if IPsec is present.
12073 		 */
12074 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12075 			hck_flags = DB_CKSUMFLAGS(mp);
12076 
12077 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12078 			IP_STAT(ip_in_sw_cksum);
12079 
12080 		IP_CKSUM_RECV(hck_flags, u1,
12081 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12082 		    (int32_t)((uchar_t *)up - rptr),
12083 		    mp, mp1, cksum_err);
12084 
12085 		if (cksum_err) {
12086 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12087 
12088 			if (hck_flags & HCK_FULLCKSUM)
12089 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12090 			else if (hck_flags & HCK_PARTIALCKSUM)
12091 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12092 			else
12093 				IP_STAT(ip_udp_in_sw_cksum_err);
12094 
12095 			freemsg(first_mp);
12096 			return;
12097 		}
12098 	}
12099 
12100 	/* Non-fragmented broadcast or multicast packet? */
12101 	if (ire->ire_type == IRE_BROADCAST)
12102 		goto udpslowpath;
12103 
12104 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12105 	    ire->ire_zoneid)) != NULL) {
12106 		ASSERT(connp->conn_upq != NULL);
12107 		IP_STAT(ip_udp_fast_path);
12108 
12109 		if (CONN_UDP_FLOWCTLD(connp)) {
12110 			freemsg(mp);
12111 			BUMP_MIB(&ip_mib, udpInOverflows);
12112 		} else {
12113 			if (!mctl_present) {
12114 				BUMP_MIB(&ip_mib, ipInDelivers);
12115 			}
12116 			/*
12117 			 * mp and first_mp can change.
12118 			 */
12119 			if (ip_udp_check(q, connp, recv_ill,
12120 			    ipha, &mp, &first_mp, mctl_present)) {
12121 				/* Send it upstream */
12122 				CONN_UDP_RECV(connp, mp);
12123 			}
12124 		}
12125 		/*
12126 		 * freeb() cannot deal with null mblk being passed
12127 		 * in and first_mp can be set to null in the call
12128 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12129 		 */
12130 		if (mctl_present && first_mp != NULL) {
12131 			freeb(first_mp);
12132 		}
12133 		CONN_DEC_REF(connp);
12134 		return;
12135 	}
12136 
12137 	/*
12138 	 * if we got here we know the packet is not fragmented and
12139 	 * has no options. The classifier could not find a conn_t and
12140 	 * most likely its an icmp packet so send it through slow path.
12141 	 */
12142 
12143 	goto udpslowpath;
12144 
12145 ipoptions:
12146 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12147 		goto slow_done;
12148 	}
12149 
12150 	UPDATE_IB_PKT_COUNT(ire);
12151 	ire->ire_last_used_time = lbolt;
12152 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12153 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12154 fragmented:
12155 		/*
12156 		 * "sum" and "reass_hck_flags" are non-zero if the
12157 		 * reassembled packet has a valid hardware computed
12158 		 * checksum information associated with it.
12159 		 */
12160 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12161 			goto slow_done;
12162 		/*
12163 		 * Make sure that first_mp points back to mp as
12164 		 * the mp we came in with could have changed in
12165 		 * ip_rput_fragment().
12166 		 */
12167 		ASSERT(!mctl_present);
12168 		ipha = (ipha_t *)mp->b_rptr;
12169 		first_mp = mp;
12170 	}
12171 
12172 	/* Now we have a complete datagram, destined for this machine. */
12173 	u1 = IPH_HDR_LENGTH(ipha);
12174 	/* Pull up the UDP header, if necessary. */
12175 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12176 udppullup:
12177 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12178 			BUMP_MIB(&ip_mib, ipInDiscards);
12179 			freemsg(first_mp);
12180 			goto slow_done;
12181 		}
12182 		ipha = (ipha_t *)mp->b_rptr;
12183 	}
12184 
12185 	/*
12186 	 * Validate the checksum for the reassembled packet; for the
12187 	 * pullup case we calculate the payload checksum in software.
12188 	 */
12189 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12190 	if (up[3] != 0) {
12191 		boolean_t cksum_err;
12192 
12193 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12194 			IP_STAT(ip_in_sw_cksum);
12195 
12196 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12197 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12198 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12199 		    iphs[9] + up[2], sum, cksum_err);
12200 
12201 		if (cksum_err) {
12202 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12203 
12204 			if (reass_hck_flags & HCK_FULLCKSUM)
12205 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12206 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12207 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12208 			else
12209 				IP_STAT(ip_udp_in_sw_cksum_err);
12210 
12211 			freemsg(first_mp);
12212 			goto slow_done;
12213 		}
12214 	}
12215 udpslowpath:
12216 
12217 	/* Clear hardware checksum flag to be safe */
12218 	DB_CKSUMFLAGS(mp) = 0;
12219 
12220 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12221 	    (ire->ire_type == IRE_BROADCAST),
12222 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12223 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12224 
12225 slow_done:
12226 	IP_STAT(ip_udp_slow_path);
12227 	return;
12228 
12229 #undef  iphs
12230 #undef  rptr
12231 }
12232 
12233 /* ARGSUSED */
12234 static mblk_t *
12235 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12236     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12237     ill_rx_ring_t *ill_ring)
12238 {
12239 	conn_t		*connp;
12240 	uint32_t	sum;
12241 	uint32_t	u1;
12242 	uint16_t	*up;
12243 	int		offset;
12244 	ssize_t		len;
12245 	mblk_t		*mp1;
12246 	boolean_t	syn_present = B_FALSE;
12247 	tcph_t		*tcph;
12248 	uint_t		ip_hdr_len;
12249 	ill_t		*ill = (ill_t *)q->q_ptr;
12250 	zoneid_t	zoneid = ire->ire_zoneid;
12251 	boolean_t	cksum_err;
12252 	uint16_t	hck_flags = 0;
12253 
12254 #define	rptr	((uchar_t *)ipha)
12255 
12256 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12257 
12258 	/*
12259 	 * FAST PATH for tcp packets
12260 	 */
12261 
12262 	/* u1 is # words of IP options */
12263 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12264 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12265 
12266 	/* IP options present */
12267 	if (u1) {
12268 		goto ipoptions;
12269 	} else {
12270 		/* Check the IP header checksum.  */
12271 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12272 			/* Clear the IP header h/w cksum flag */
12273 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12274 		} else {
12275 #define	uph	((uint16_t *)ipha)
12276 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12277 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12278 #undef	uph
12279 			/* finish doing IP checksum */
12280 			sum = (sum & 0xFFFF) + (sum >> 16);
12281 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12282 			/*
12283 			 * Don't verify header checksum if this packet
12284 			 * is coming back from AH/ESP as we already did it.
12285 			 */
12286 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12287 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12288 				goto error;
12289 			}
12290 		}
12291 	}
12292 
12293 	if (!mctl_present) {
12294 		UPDATE_IB_PKT_COUNT(ire);
12295 		ire->ire_last_used_time = lbolt;
12296 	}
12297 
12298 	/* packet part of fragmented IP packet? */
12299 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12300 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12301 		goto fragmented;
12302 	}
12303 
12304 	/* u1 = IP header length (20 bytes) */
12305 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12306 
12307 	/* does packet contain IP+TCP headers? */
12308 	len = mp->b_wptr - rptr;
12309 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12310 		IP_STAT(ip_tcppullup);
12311 		goto tcppullup;
12312 	}
12313 
12314 	/* TCP options present? */
12315 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12316 
12317 	/*
12318 	 * If options need to be pulled up, then goto tcpoptions.
12319 	 * otherwise we are still in the fast path
12320 	 */
12321 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12322 		IP_STAT(ip_tcpoptions);
12323 		goto tcpoptions;
12324 	}
12325 
12326 	/* multiple mblks of tcp data? */
12327 	if ((mp1 = mp->b_cont) != NULL) {
12328 		/* more then two? */
12329 		if (mp1->b_cont != NULL) {
12330 			IP_STAT(ip_multipkttcp);
12331 			goto multipkttcp;
12332 		}
12333 		len += mp1->b_wptr - mp1->b_rptr;
12334 	}
12335 
12336 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12337 
12338 	/* part of pseudo checksum */
12339 
12340 	/* TCP datagram length */
12341 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12342 
12343 #define	iphs    ((uint16_t *)ipha)
12344 
12345 #ifdef	_BIG_ENDIAN
12346 	u1 += IPPROTO_TCP;
12347 #else
12348 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12349 #endif
12350 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12351 
12352 	/*
12353 	 * Revert to software checksum calculation if the interface
12354 	 * isn't capable of checksum offload or if IPsec is present.
12355 	 */
12356 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12357 		hck_flags = DB_CKSUMFLAGS(mp);
12358 
12359 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12360 		IP_STAT(ip_in_sw_cksum);
12361 
12362 	IP_CKSUM_RECV(hck_flags, u1,
12363 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12364 	    (int32_t)((uchar_t *)up - rptr),
12365 	    mp, mp1, cksum_err);
12366 
12367 	if (cksum_err) {
12368 		BUMP_MIB(&ip_mib, tcpInErrs);
12369 
12370 		if (hck_flags & HCK_FULLCKSUM)
12371 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12372 		else if (hck_flags & HCK_PARTIALCKSUM)
12373 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12374 		else
12375 			IP_STAT(ip_tcp_in_sw_cksum_err);
12376 
12377 		goto error;
12378 	}
12379 
12380 try_again:
12381 
12382 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12383 	    NULL) {
12384 		/* Send the TH_RST */
12385 		goto no_conn;
12386 	}
12387 
12388 	/*
12389 	 * TCP FAST PATH for AF_INET socket.
12390 	 *
12391 	 * TCP fast path to avoid extra work. An AF_INET socket type
12392 	 * does not have facility to receive extra information via
12393 	 * ip_process or ip_add_info. Also, when the connection was
12394 	 * established, we made a check if this connection is impacted
12395 	 * by any global IPSec policy or per connection policy (a
12396 	 * policy that comes in effect later will not apply to this
12397 	 * connection). Since all this can be determined at the
12398 	 * connection establishment time, a quick check of flags
12399 	 * can avoid extra work.
12400 	 */
12401 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12402 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12403 		ASSERT(first_mp == mp);
12404 		SET_SQUEUE(mp, tcp_rput_data, connp);
12405 		return (mp);
12406 	}
12407 
12408 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12409 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12410 		if (IPCL_IS_TCP(connp)) {
12411 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12412 			DB_CKSUMSTART(mp) =
12413 			    (intptr_t)ip_squeue_get(ill_ring);
12414 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12415 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12416 				SET_SQUEUE(mp, connp->conn_recv, connp);
12417 				return (mp);
12418 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12419 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12420 				ip_squeue_enter_unbound++;
12421 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12422 				    connp);
12423 				return (mp);
12424 			}
12425 			syn_present = B_TRUE;
12426 		}
12427 
12428 	}
12429 
12430 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12431 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12432 
12433 		/* No need to send this packet to TCP */
12434 		if ((flags & TH_RST) || (flags & TH_URG)) {
12435 			CONN_DEC_REF(connp);
12436 			freemsg(first_mp);
12437 			return (NULL);
12438 		}
12439 		if (flags & TH_ACK) {
12440 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len);
12441 			CONN_DEC_REF(connp);
12442 			return (NULL);
12443 		}
12444 
12445 		CONN_DEC_REF(connp);
12446 		freemsg(first_mp);
12447 		return (NULL);
12448 	}
12449 
12450 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12451 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12452 		    ipha, NULL, mctl_present);
12453 		if (first_mp == NULL) {
12454 			CONN_DEC_REF(connp);
12455 			return (NULL);
12456 		}
12457 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12458 			ASSERT(syn_present);
12459 			if (mctl_present) {
12460 				ASSERT(first_mp != mp);
12461 				first_mp->b_datap->db_struioflag |=
12462 				    STRUIO_POLICY;
12463 			} else {
12464 				ASSERT(first_mp == mp);
12465 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12466 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12467 			}
12468 		} else {
12469 			/*
12470 			 * Discard first_mp early since we're dealing with a
12471 			 * fully-connected conn_t and tcp doesn't do policy in
12472 			 * this case.
12473 			 */
12474 			if (mctl_present) {
12475 				freeb(first_mp);
12476 				mctl_present = B_FALSE;
12477 			}
12478 			first_mp = mp;
12479 		}
12480 	}
12481 
12482 	/* Initiate IPPF processing for fastpath */
12483 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12484 		uint32_t	ill_index;
12485 
12486 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12487 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12488 		if (mp == NULL) {
12489 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12490 			    "deferred/dropped during IPPF processing\n"));
12491 			CONN_DEC_REF(connp);
12492 			if (mctl_present)
12493 				freeb(first_mp);
12494 			return (NULL);
12495 		} else if (mctl_present) {
12496 			/*
12497 			 * ip_process might return a new mp.
12498 			 */
12499 			ASSERT(first_mp != mp);
12500 			first_mp->b_cont = mp;
12501 		} else {
12502 			first_mp = mp;
12503 		}
12504 
12505 	}
12506 
12507 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12508 		mp = ip_add_info(mp, recv_ill, flags);
12509 		if (mp == NULL) {
12510 			CONN_DEC_REF(connp);
12511 			if (mctl_present)
12512 				freeb(first_mp);
12513 			return (NULL);
12514 		} else if (mctl_present) {
12515 			/*
12516 			 * ip_add_info might return a new mp.
12517 			 */
12518 			ASSERT(first_mp != mp);
12519 			first_mp->b_cont = mp;
12520 		} else {
12521 			first_mp = mp;
12522 		}
12523 	}
12524 
12525 	if (IPCL_IS_TCP(connp)) {
12526 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
12527 		return (first_mp);
12528 	} else {
12529 		putnext(connp->conn_rq, first_mp);
12530 		CONN_DEC_REF(connp);
12531 		return (NULL);
12532 	}
12533 
12534 no_conn:
12535 	/* Initiate IPPf processing, if needed. */
12536 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12537 		uint32_t ill_index;
12538 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12539 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
12540 		if (first_mp == NULL) {
12541 			return (NULL);
12542 		}
12543 	}
12544 	BUMP_MIB(&ip_mib, ipInDelivers);
12545 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr));
12546 	return (NULL);
12547 ipoptions:
12548 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
12549 		goto slow_done;
12550 	}
12551 
12552 	UPDATE_IB_PKT_COUNT(ire);
12553 	ire->ire_last_used_time = lbolt;
12554 
12555 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12556 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12557 fragmented:
12558 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
12559 			if (mctl_present)
12560 				freeb(first_mp);
12561 			goto slow_done;
12562 		}
12563 		/*
12564 		 * Make sure that first_mp points back to mp as
12565 		 * the mp we came in with could have changed in
12566 		 * ip_rput_fragment().
12567 		 */
12568 		ASSERT(!mctl_present);
12569 		ipha = (ipha_t *)mp->b_rptr;
12570 		first_mp = mp;
12571 	}
12572 
12573 	/* Now we have a complete datagram, destined for this machine. */
12574 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
12575 
12576 	len = mp->b_wptr - mp->b_rptr;
12577 	/* Pull up a minimal TCP header, if necessary. */
12578 	if (len < (u1 + 20)) {
12579 tcppullup:
12580 		if (!pullupmsg(mp, u1 + 20)) {
12581 			BUMP_MIB(&ip_mib, ipInDiscards);
12582 			goto error;
12583 		}
12584 		ipha = (ipha_t *)mp->b_rptr;
12585 		len = mp->b_wptr - mp->b_rptr;
12586 	}
12587 
12588 	/*
12589 	 * Extract the offset field from the TCP header.  As usual, we
12590 	 * try to help the compiler more than the reader.
12591 	 */
12592 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
12593 	if (offset != 5) {
12594 tcpoptions:
12595 		if (offset < 5) {
12596 			BUMP_MIB(&ip_mib, ipInDiscards);
12597 			goto error;
12598 		}
12599 		/*
12600 		 * There must be TCP options.
12601 		 * Make sure we can grab them.
12602 		 */
12603 		offset <<= 2;
12604 		offset += u1;
12605 		if (len < offset) {
12606 			if (!pullupmsg(mp, offset)) {
12607 				BUMP_MIB(&ip_mib, ipInDiscards);
12608 				goto error;
12609 			}
12610 			ipha = (ipha_t *)mp->b_rptr;
12611 			len = mp->b_wptr - rptr;
12612 		}
12613 	}
12614 
12615 	/* Get the total packet length in len, including headers. */
12616 	if (mp->b_cont) {
12617 multipkttcp:
12618 		len = msgdsize(mp);
12619 	}
12620 
12621 	/*
12622 	 * Check the TCP checksum by pulling together the pseudo-
12623 	 * header checksum, and passing it to ip_csum to be added in
12624 	 * with the TCP datagram.
12625 	 *
12626 	 * Since we are not using the hwcksum if available we must
12627 	 * clear the flag. We may come here via tcppullup or tcpoptions.
12628 	 * If either of these fails along the way the mblk is freed.
12629 	 * If this logic ever changes and mblk is reused to say send
12630 	 * ICMP's back, then this flag may need to be cleared in
12631 	 * other places as well.
12632 	 */
12633 	DB_CKSUMFLAGS(mp) = 0;
12634 
12635 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
12636 
12637 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
12638 #ifdef	_BIG_ENDIAN
12639 	u1 += IPPROTO_TCP;
12640 #else
12641 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12642 #endif
12643 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12644 	/*
12645 	 * Not M_DATA mblk or its a dup, so do the checksum now.
12646 	 */
12647 	IP_STAT(ip_in_sw_cksum);
12648 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
12649 		BUMP_MIB(&ip_mib, tcpInErrs);
12650 		goto error;
12651 	}
12652 
12653 	IP_STAT(ip_tcp_slow_path);
12654 	goto try_again;
12655 #undef  iphs
12656 #undef  rptr
12657 
12658 error:
12659 	freemsg(first_mp);
12660 slow_done:
12661 	return (NULL);
12662 }
12663 
12664 /* ARGSUSED */
12665 static void
12666 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12667     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
12668 {
12669 	conn_t		*connp;
12670 	uint32_t	sum;
12671 	uint32_t	u1;
12672 	ssize_t		len;
12673 	sctp_hdr_t	*sctph;
12674 	zoneid_t	zoneid = ire->ire_zoneid;
12675 	uint32_t	pktsum;
12676 	uint32_t	calcsum;
12677 	uint32_t	ports;
12678 	uint_t		ipif_seqid;
12679 	in6_addr_t	map_src, map_dst;
12680 	ill_t		*ill = (ill_t *)q->q_ptr;
12681 
12682 #define	rptr	((uchar_t *)ipha)
12683 
12684 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
12685 
12686 	/* u1 is # words of IP options */
12687 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12688 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12689 
12690 	/* IP options present */
12691 	if (u1 > 0) {
12692 		goto ipoptions;
12693 	} else {
12694 		/* Check the IP header checksum.  */
12695 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12696 #define	uph	((uint16_t *)ipha)
12697 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12698 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12699 #undef	uph
12700 			/* finish doing IP checksum */
12701 			sum = (sum & 0xFFFF) + (sum >> 16);
12702 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12703 			/*
12704 			 * Don't verify header checksum if this packet
12705 			 * is coming back from AH/ESP as we already did it.
12706 			 */
12707 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12708 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12709 				goto error;
12710 			}
12711 		}
12712 		/*
12713 		 * Since there is no SCTP h/w cksum support yet, just
12714 		 * clear the flag.
12715 		 */
12716 		DB_CKSUMFLAGS(mp) = 0;
12717 	}
12718 
12719 	/*
12720 	 * Don't verify header checksum if this packet is coming
12721 	 * back from AH/ESP as we already did it.
12722 	 */
12723 	if (!mctl_present) {
12724 		UPDATE_IB_PKT_COUNT(ire);
12725 		ire->ire_last_used_time = lbolt;
12726 	}
12727 
12728 	/* packet part of fragmented IP packet? */
12729 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12730 	if (u1 & (IPH_MF | IPH_OFFSET))
12731 		goto fragmented;
12732 
12733 	/* u1 = IP header length (20 bytes) */
12734 	u1 = IP_SIMPLE_HDR_LENGTH;
12735 
12736 find_sctp_client:
12737 	/* Pullup if we don't have the sctp common header. */
12738 	len = MBLKL(mp);
12739 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
12740 		if (mp->b_cont == NULL ||
12741 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
12742 			BUMP_MIB(&ip_mib, ipInDiscards);
12743 			goto error;
12744 		}
12745 		ipha = (ipha_t *)mp->b_rptr;
12746 		len = MBLKL(mp);
12747 	}
12748 
12749 	sctph = (sctp_hdr_t *)(rptr + u1);
12750 #ifdef	DEBUG
12751 	if (!skip_sctp_cksum) {
12752 #endif
12753 		pktsum = sctph->sh_chksum;
12754 		sctph->sh_chksum = 0;
12755 		calcsum = sctp_cksum(mp, u1);
12756 		if (calcsum != pktsum) {
12757 			BUMP_MIB(&sctp_mib, sctpChecksumError);
12758 			goto error;
12759 		}
12760 		sctph->sh_chksum = pktsum;
12761 #ifdef	DEBUG	/* skip_sctp_cksum */
12762 	}
12763 #endif
12764 	/* get the ports */
12765 	ports = *(uint32_t *)&sctph->sh_sport;
12766 
12767 	ipif_seqid = ire->ire_ipif->ipif_seqid;
12768 	IRE_REFRELE(ire);
12769 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
12770 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
12771 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
12772 	    mp)) == NULL) {
12773 		/* Check for raw socket or OOTB handling */
12774 		goto no_conn;
12775 	}
12776 
12777 	/* Found a client; up it goes */
12778 	BUMP_MIB(&ip_mib, ipInDelivers);
12779 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
12780 	return;
12781 
12782 no_conn:
12783 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
12784 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
12785 	return;
12786 
12787 ipoptions:
12788 	DB_CKSUMFLAGS(mp) = 0;
12789 	if (!ip_options_cksum(q, first_mp, ipha, ire))
12790 		goto slow_done;
12791 
12792 	UPDATE_IB_PKT_COUNT(ire);
12793 	ire->ire_last_used_time = lbolt;
12794 
12795 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12796 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12797 fragmented:
12798 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
12799 			goto slow_done;
12800 		/*
12801 		 * Make sure that first_mp points back to mp as
12802 		 * the mp we came in with could have changed in
12803 		 * ip_rput_fragment().
12804 		 */
12805 		ASSERT(!mctl_present);
12806 		ipha = (ipha_t *)mp->b_rptr;
12807 		first_mp = mp;
12808 	}
12809 
12810 	/* Now we have a complete datagram, destined for this machine. */
12811 	u1 = IPH_HDR_LENGTH(ipha);
12812 	goto find_sctp_client;
12813 #undef  iphs
12814 #undef  rptr
12815 
12816 error:
12817 	freemsg(first_mp);
12818 slow_done:
12819 	IRE_REFRELE(ire);
12820 }
12821 
12822 #define	VER_BITS	0xF0
12823 #define	VERSION_6	0x60
12824 
12825 static boolean_t
12826 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
12827     ipaddr_t *dstp)
12828 {
12829 	uint_t	opt_len;
12830 	ipha_t *ipha;
12831 	ssize_t len;
12832 	uint_t	pkt_len;
12833 
12834 	IP_STAT(ip_ipoptions);
12835 	ipha = *iphapp;
12836 
12837 #define	rptr    ((uchar_t *)ipha)
12838 	/* Assume no IPv6 packets arrive over the IPv4 queue */
12839 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
12840 		BUMP_MIB(&ip_mib, ipInIPv6);
12841 		freemsg(mp);
12842 		return (B_FALSE);
12843 	}
12844 
12845 	/* multiple mblk or too short */
12846 	pkt_len = ntohs(ipha->ipha_length);
12847 
12848 	/* Get the number of words of IP options in the IP header. */
12849 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
12850 	if (opt_len) {
12851 		/* IP Options present!  Validate and process. */
12852 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
12853 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12854 			goto done;
12855 		}
12856 		/*
12857 		 * Recompute complete header length and make sure we
12858 		 * have access to all of it.
12859 		 */
12860 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
12861 		if (len > (mp->b_wptr - rptr)) {
12862 			if (len > pkt_len) {
12863 				BUMP_MIB(&ip_mib, ipInHdrErrors);
12864 				goto done;
12865 			}
12866 			if (!pullupmsg(mp, len)) {
12867 				BUMP_MIB(&ip_mib, ipInDiscards);
12868 				goto done;
12869 			}
12870 			ipha = (ipha_t *)mp->b_rptr;
12871 		}
12872 		/*
12873 		 * Go off to ip_rput_options which returns the next hop
12874 		 * destination address, which may have been affected
12875 		 * by source routing.
12876 		 */
12877 		IP_STAT(ip_opt);
12878 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
12879 			return (B_FALSE);
12880 		}
12881 	}
12882 	*iphapp = ipha;
12883 	return (B_TRUE);
12884 done:
12885 	/* clear b_prev - used by ip_mroute_decap */
12886 	mp->b_prev = NULL;
12887 	freemsg(mp);
12888 	return (B_FALSE);
12889 #undef  rptr
12890 }
12891 
12892 /*
12893  * Deal with the fact that there is no ire for the destination.
12894  * The incoming ill (in_ill) is passed in to ip_newroute only
12895  * in the case of packets coming from mobile ip forward tunnel.
12896  * It must be null otherwise.
12897  */
12898 static void
12899 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
12900     ipaddr_t dst)
12901 {
12902 	ipha_t	*ipha;
12903 	ill_t	*ill;
12904 
12905 	ipha = (ipha_t *)mp->b_rptr;
12906 	ill = (ill_t *)q->q_ptr;
12907 
12908 	ASSERT(ill != NULL);
12909 	/*
12910 	 * No IRE for this destination, so it can't be for us.
12911 	 * Unless we are forwarding, drop the packet.
12912 	 * We have to let source routed packets through
12913 	 * since we don't yet know if they are 'ping -l'
12914 	 * packets i.e. if they will go out over the
12915 	 * same interface as they came in on.
12916 	 */
12917 	if (ll_multicast) {
12918 		freemsg(mp);
12919 		return;
12920 	}
12921 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
12922 		BUMP_MIB(&ip_mib, ipForwProhibits);
12923 		freemsg(mp);
12924 		return;
12925 	}
12926 
12927 	/* Check for Martian addresses */
12928 	if ((in_ill == NULL) && (ip_no_forward(ipha, ill))) {
12929 		freemsg(mp);
12930 		return;
12931 	}
12932 
12933 	/* Mark this packet as having originated externally */
12934 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
12935 
12936 	/*
12937 	 * Clear the indication that this may have a hardware checksum
12938 	 * as we are not using it
12939 	 */
12940 	DB_CKSUMFLAGS(mp) = 0;
12941 
12942 	/*
12943 	 * Now hand the packet to ip_newroute.
12944 	 */
12945 	ip_newroute(q, mp, dst, in_ill, NULL);
12946 }
12947 
12948 /*
12949  * check ip header length and align it.
12950  */
12951 static boolean_t
12952 ip_check_and_align_header(queue_t *q, mblk_t *mp)
12953 {
12954 	ssize_t len;
12955 	ill_t *ill;
12956 	ipha_t	*ipha;
12957 
12958 	len = MBLKL(mp);
12959 
12960 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
12961 		if (!OK_32PTR(mp->b_rptr))
12962 			IP_STAT(ip_notaligned1);
12963 		else
12964 			IP_STAT(ip_notaligned2);
12965 		/* Guard against bogus device drivers */
12966 		if (len < 0) {
12967 			/* clear b_prev - used by ip_mroute_decap */
12968 			mp->b_prev = NULL;
12969 			BUMP_MIB(&ip_mib, ipInHdrErrors);
12970 			freemsg(mp);
12971 			return (B_FALSE);
12972 		}
12973 
12974 		if (ip_rput_pullups++ == 0) {
12975 			ill = (ill_t *)q->q_ptr;
12976 			ipha = (ipha_t *)mp->b_rptr;
12977 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12978 			    "ip_check_and_align_header: %s forced us to "
12979 			    " pullup pkt, hdr len %ld, hdr addr %p",
12980 			    ill->ill_name, len, ipha);
12981 		}
12982 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
12983 			/* clear b_prev - used by ip_mroute_decap */
12984 			mp->b_prev = NULL;
12985 			BUMP_MIB(&ip_mib, ipInDiscards);
12986 			freemsg(mp);
12987 			return (B_FALSE);
12988 		}
12989 	}
12990 	return (B_TRUE);
12991 }
12992 
12993 static boolean_t
12994 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
12995 {
12996 	ill_group_t	*ill_group;
12997 	ill_group_t	*ire_group;
12998 	queue_t 	*q;
12999 	ill_t		*ire_ill;
13000 	uint_t		ill_ifindex;
13001 
13002 	q = *qp;
13003 	/*
13004 	 * We need to check to make sure the packet came in
13005 	 * on the queue associated with the destination IRE.
13006 	 * Note that for multicast packets and broadcast packets sent to
13007 	 * a broadcast address which is shared between multiple interfaces
13008 	 * we should not do this since we just got a random broadcast ire.
13009 	 */
13010 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13011 		boolean_t check_multi = B_TRUE;
13012 
13013 		/*
13014 		 * This packet came in on an interface other than the
13015 		 * one associated with the destination address.
13016 		 * "Gateway" it to the appropriate interface here.
13017 		 * As long as the ills belong to the same group,
13018 		 * we don't consider them to arriving on the wrong
13019 		 * interface. Thus, when the switch is doing inbound
13020 		 * load spreading, we won't drop packets when we
13021 		 * are doing strict multihoming checks. Note, the
13022 		 * same holds true for 'usesrc groups' where the
13023 		 * destination address may belong to another interface
13024 		 * to allow multipathing to happen
13025 		 */
13026 		ill_group = ill->ill_group;
13027 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13028 		ill_ifindex = ill->ill_usesrc_ifindex;
13029 		ire_group = ire_ill->ill_group;
13030 
13031 		/*
13032 		 * If it's part of the same IPMP group, or if it's a legal
13033 		 * address on the 'usesrc' interface, then bypass strict
13034 		 * checks.
13035 		 */
13036 		if (ill_group != NULL && ill_group == ire_group) {
13037 			check_multi = B_FALSE;
13038 		} else if (ill_ifindex != 0 &&
13039 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13040 			check_multi = B_FALSE;
13041 		}
13042 
13043 		if (check_multi &&
13044 		    ip_strict_dst_multihoming &&
13045 		    ((ill->ill_flags &
13046 		    ire->ire_ipif->ipif_ill->ill_flags &
13047 		    ILLF_ROUTER) == 0)) {
13048 			/* Drop packet */
13049 			BUMP_MIB(&ip_mib, ipForwProhibits);
13050 			freemsg(mp);
13051 			ire_refrele(ire);
13052 			return (B_TRUE);
13053 		}
13054 
13055 		/*
13056 		 * Change the queue (for non-virtual destination network
13057 		 * interfaces) and ip_rput_local will be called with the right
13058 		 * queue
13059 		 */
13060 		q = ire->ire_rfq;
13061 	}
13062 	/* Must be broadcast.  We'll take it. */
13063 	*qp = q;
13064 	return (B_FALSE);
13065 }
13066 
13067 static void
13068 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13069     ill_t *ill, int ll_multicast)
13070 {
13071 	ill_group_t	*ill_group;
13072 	ill_group_t	*ire_group;
13073 	queue_t	*dev_q;
13074 
13075 	ASSERT(ire->ire_stq != NULL);
13076 	if (ll_multicast != 0)
13077 		goto drop_pkt;
13078 
13079 	if (ip_no_forward(ipha, ill))
13080 		goto drop_pkt;
13081 
13082 	ill_group = ill->ill_group;
13083 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13084 	/*
13085 	 * Check if we want to forward this one at this time.
13086 	 * We allow source routed packets on a host provided that
13087 	 * they go out the same interface or same interface group
13088 	 * as they came in on.
13089 	 *
13090 	 * XXX To be quicker, we may wish to not chase pointers to
13091 	 * get the ILLF_ROUTER flag and instead store the
13092 	 * forwarding policy in the ire.  An unfortunate
13093 	 * side-effect of that would be requiring an ire flush
13094 	 * whenever the ILLF_ROUTER flag changes.
13095 	 */
13096 	if (((ill->ill_flags &
13097 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13098 	    ILLF_ROUTER) == 0) &&
13099 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13100 	    (ill_group != NULL && ill_group == ire_group)))) {
13101 		BUMP_MIB(&ip_mib, ipForwProhibits);
13102 		if (ip_source_routed(ipha)) {
13103 			q = WR(q);
13104 			/*
13105 			 * Clear the indication that this may have
13106 			 * hardware checksum as we are not using it.
13107 			 */
13108 			DB_CKSUMFLAGS(mp) = 0;
13109 			icmp_unreachable(q, mp,
13110 			    ICMP_SOURCE_ROUTE_FAILED);
13111 			ire_refrele(ire);
13112 			return;
13113 		}
13114 		goto drop_pkt;
13115 	}
13116 
13117 	/* Packet is being forwarded. Turning off hwcksum flag. */
13118 	DB_CKSUMFLAGS(mp) = 0;
13119 	if (ip_g_send_redirects) {
13120 		/*
13121 		 * Check whether the incoming interface and outgoing
13122 		 * interface is part of the same group. If so,
13123 		 * send redirects.
13124 		 *
13125 		 * Check the source address to see if it originated
13126 		 * on the same logical subnet it is going back out on.
13127 		 * If so, we should be able to send it a redirect.
13128 		 * Avoid sending a redirect if the destination
13129 		 * is directly connected (gw_addr == 0),
13130 		 * or if the packet was source routed out this
13131 		 * interface.
13132 		 */
13133 		ipaddr_t src;
13134 		mblk_t	*mp1;
13135 		ire_t	*src_ire = NULL;
13136 
13137 		/*
13138 		 * Check whether ire_rfq and q are from the same ill
13139 		 * or if they are not same, they at least belong
13140 		 * to the same group. If so, send redirects.
13141 		 */
13142 		if ((ire->ire_rfq == q ||
13143 		    (ill_group != NULL && ill_group == ire_group)) &&
13144 		    (ire->ire_gateway_addr != 0) &&
13145 		    !ip_source_routed(ipha)) {
13146 
13147 			src = ipha->ipha_src;
13148 			src_ire = ire_ftable_lookup(src, 0, 0,
13149 			    IRE_INTERFACE, ire->ire_ipif, NULL, ALL_ZONES,
13150 			    0, NULL, MATCH_IRE_IPIF | MATCH_IRE_TYPE);
13151 
13152 			if (src_ire != NULL) {
13153 				/*
13154 				 * The source is directly connected.
13155 				 * Just copy the ip header (which is
13156 				 * in the first mblk)
13157 				 */
13158 				mp1 = copyb(mp);
13159 				if (mp1 != NULL) {
13160 					icmp_send_redirect(WR(q), mp1,
13161 					    ire->ire_gateway_addr);
13162 				}
13163 				ire_refrele(src_ire);
13164 			}
13165 		}
13166 	}
13167 
13168 	dev_q = ire->ire_stq->q_next;
13169 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13170 		BUMP_MIB(&ip_mib, ipInDiscards);
13171 		freemsg(mp);
13172 		ire_refrele(ire);
13173 		return;
13174 	}
13175 
13176 	ip_rput_forward(ire, ipha, mp, ill);
13177 	IRE_REFRELE(ire);
13178 	return;
13179 
13180 drop_pkt:
13181 	ire_refrele(ire);
13182 	ip2dbg(("ip_rput_forward: drop pkt\n"));
13183 	freemsg(mp);
13184 }
13185 
13186 static boolean_t
13187 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t **irep, ipha_t *ipha,
13188     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13189 {
13190 	queue_t		*q;
13191 	ire_t		*ire;
13192 	uint16_t	hcksumflags;
13193 
13194 	q = *qp;
13195 	ire = *irep;
13196 
13197 	/*
13198 	 * Clear the indication that this may have hardware
13199 	 * checksum as we are not using it for forwarding.
13200 	 */
13201 	hcksumflags = DB_CKSUMFLAGS(mp);
13202 	DB_CKSUMFLAGS(mp) = 0;
13203 
13204 	/*
13205 	 * Directed broadcast forwarding: if the packet came in over a
13206 	 * different interface then it is routed out over we can forward it.
13207 	 */
13208 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13209 		ire_refrele(ire);
13210 		freemsg(mp);
13211 		BUMP_MIB(&ip_mib, ipInDiscards);
13212 		return (B_TRUE);
13213 	}
13214 	/*
13215 	 * For multicast we have set dst to be INADDR_BROADCAST
13216 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13217 	 * only for broadcast packets.
13218 	 */
13219 	if (!CLASSD(ipha->ipha_dst)) {
13220 		ire_t *new_ire;
13221 		ipif_t *ipif;
13222 		/*
13223 		 * For ill groups, as the switch duplicates broadcasts
13224 		 * across all the ports, we need to filter out and
13225 		 * send up only one copy. There is one copy for every
13226 		 * broadcast address on each ill. Thus, we look for a
13227 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13228 		 * later to see whether this ill is eligible to receive
13229 		 * them or not. ill_nominate_bcast_rcv() nominates only
13230 		 * one set of IREs for receiving.
13231 		 */
13232 
13233 		ipif = ipif_get_next_ipif(NULL, ill);
13234 		if (ipif == NULL) {
13235 			ire_refrele(ire);
13236 			freemsg(mp);
13237 			BUMP_MIB(&ip_mib, ipInDiscards);
13238 			return (B_TRUE);
13239 		}
13240 		new_ire = ire_ctable_lookup(dst, 0, 0,
13241 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13242 		ipif_refrele(ipif);
13243 
13244 		if (new_ire != NULL) {
13245 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13246 				ire_refrele(ire);
13247 				ire_refrele(new_ire);
13248 				freemsg(mp);
13249 				BUMP_MIB(&ip_mib, ipInDiscards);
13250 				return (B_TRUE);
13251 			}
13252 			/*
13253 			 * In the special case of multirouted broadcast
13254 			 * packets, we unconditionally need to "gateway"
13255 			 * them to the appropriate interface here.
13256 			 * In the normal case, this cannot happen, because
13257 			 * there is no broadcast IRE tagged with the
13258 			 * RTF_MULTIRT flag.
13259 			 */
13260 			if (new_ire->ire_flags & RTF_MULTIRT) {
13261 				ire_refrele(new_ire);
13262 				if (ire->ire_rfq != NULL) {
13263 					q = ire->ire_rfq;
13264 					*qp = q;
13265 				}
13266 			} else {
13267 				ire_refrele(ire);
13268 				ire = new_ire;
13269 			}
13270 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
13271 			if (!ip_g_forward_directed_bcast) {
13272 				/*
13273 				 * Free the message if
13274 				 * ip_g_forward_directed_bcast is turned
13275 				 * off for non-local broadcast.
13276 				 */
13277 				ire_refrele(ire);
13278 				freemsg(mp);
13279 				BUMP_MIB(&ip_mib, ipInDiscards);
13280 				return (B_TRUE);
13281 			}
13282 		} else {
13283 			/*
13284 			 * This CGTP packet successfully passed the
13285 			 * CGTP filter, but the related CGTP
13286 			 * broadcast IRE has not been found,
13287 			 * meaning that the redundant ipif is
13288 			 * probably down. However, if we discarded
13289 			 * this packet, its duplicate would be
13290 			 * filtered out by the CGTP filter so none
13291 			 * of them would get through. So we keep
13292 			 * going with this one.
13293 			 */
13294 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
13295 			if (ire->ire_rfq != NULL) {
13296 				q = ire->ire_rfq;
13297 				*qp = q;
13298 			}
13299 		}
13300 	}
13301 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
13302 		/*
13303 		 * Verify that there are not more then one
13304 		 * IRE_BROADCAST with this broadcast address which
13305 		 * has ire_stq set.
13306 		 * TODO: simplify, loop over all IRE's
13307 		 */
13308 		ire_t	*ire1;
13309 		int	num_stq = 0;
13310 		mblk_t	*mp1;
13311 
13312 		/* Find the first one with ire_stq set */
13313 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
13314 		for (ire1 = ire; ire1 &&
13315 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
13316 		    ire1 = ire1->ire_next)
13317 			;
13318 		if (ire1) {
13319 			ire_refrele(ire);
13320 			ire = ire1;
13321 			IRE_REFHOLD(ire);
13322 		}
13323 
13324 		/* Check if there are additional ones with stq set */
13325 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
13326 			if (ire->ire_addr != ire1->ire_addr)
13327 				break;
13328 			if (ire1->ire_stq) {
13329 				num_stq++;
13330 				break;
13331 			}
13332 		}
13333 		rw_exit(&ire->ire_bucket->irb_lock);
13334 		if (num_stq == 1 && ire->ire_stq != NULL) {
13335 			ip1dbg(("ip_rput_process_broadcast: directed "
13336 			    "broadcast to 0x%x\n",
13337 			    ntohl(ire->ire_addr)));
13338 			mp1 = copymsg(mp);
13339 			if (mp1) {
13340 				switch (ipha->ipha_protocol) {
13341 				case IPPROTO_UDP:
13342 					ip_udp_input(q, mp1, ipha, ire, ill);
13343 					break;
13344 				default:
13345 					ip_proto_input(q, mp1, ipha, ire, ill);
13346 					break;
13347 				}
13348 			}
13349 			/*
13350 			 * Adjust ttl to 2 (1+1 - the forward engine
13351 			 * will decrement it by one.
13352 			 */
13353 			if (ip_csum_hdr(ipha)) {
13354 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13355 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
13356 				freemsg(mp);
13357 				ire_refrele(ire);
13358 				return (B_TRUE);
13359 			}
13360 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
13361 			ipha->ipha_hdr_checksum = 0;
13362 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
13363 			ip_rput_process_forward(q, mp, ire, ipha,
13364 			    ill, ll_multicast);
13365 			return (B_TRUE);
13366 		}
13367 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
13368 		    ntohl(ire->ire_addr)));
13369 	}
13370 
13371 	*irep = ire;
13372 
13373 	/* Restore any hardware checksum flags */
13374 	DB_CKSUMFLAGS(mp) = hcksumflags;
13375 	return (B_FALSE);
13376 }
13377 
13378 /* ARGSUSED */
13379 static boolean_t
13380 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
13381     int *ll_multicast, ipaddr_t *dstp)
13382 {
13383 	/*
13384 	 * Forward packets only if we have joined the allmulti
13385 	 * group on this interface.
13386 	 */
13387 	if (ip_g_mrouter && ill->ill_join_allmulti) {
13388 		int retval;
13389 
13390 		/*
13391 		 * Clear the indication that this may have hardware
13392 		 * checksum as we are not using it.
13393 		 */
13394 		DB_CKSUMFLAGS(mp) = 0;
13395 		retval = ip_mforward(ill, ipha, mp);
13396 		/* ip_mforward updates mib variables if needed */
13397 		/* clear b_prev - used by ip_mroute_decap */
13398 		mp->b_prev = NULL;
13399 
13400 		switch (retval) {
13401 		case 0:
13402 			/*
13403 			 * pkt is okay and arrived on phyint.
13404 			 *
13405 			 * If we are running as a multicast router
13406 			 * we need to see all IGMP and/or PIM packets.
13407 			 */
13408 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
13409 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
13410 				goto done;
13411 			}
13412 			break;
13413 		case -1:
13414 			/* pkt is mal-formed, toss it */
13415 			goto drop_pkt;
13416 		case 1:
13417 			/* pkt is okay and arrived on a tunnel */
13418 			/*
13419 			 * If we are running a multicast router
13420 			 *  we need to see all igmp packets.
13421 			 */
13422 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
13423 				*dstp = INADDR_BROADCAST;
13424 				*ll_multicast = 1;
13425 				return (B_FALSE);
13426 			}
13427 
13428 			goto drop_pkt;
13429 		}
13430 	}
13431 
13432 	ILM_WALKER_HOLD(ill);
13433 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
13434 		/*
13435 		 * This might just be caused by the fact that
13436 		 * multiple IP Multicast addresses map to the same
13437 		 * link layer multicast - no need to increment counter!
13438 		 */
13439 		ILM_WALKER_RELE(ill);
13440 		freemsg(mp);
13441 		return (B_TRUE);
13442 	}
13443 	ILM_WALKER_RELE(ill);
13444 done:
13445 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
13446 	/*
13447 	 * This assumes the we deliver to all streams for multicast
13448 	 * and broadcast packets.
13449 	 */
13450 	*dstp = INADDR_BROADCAST;
13451 	*ll_multicast = 1;
13452 	return (B_FALSE);
13453 drop_pkt:
13454 	ip2dbg(("ip_rput: drop pkt\n"));
13455 	freemsg(mp);
13456 	return (B_TRUE);
13457 }
13458 
13459 static boolean_t
13460 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
13461     int *ll_multicast, mblk_t **mpp)
13462 {
13463 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
13464 	boolean_t must_copy = B_FALSE;
13465 	struct iocblk   *iocp;
13466 	ipha_t		*ipha;
13467 
13468 #define	rptr    ((uchar_t *)ipha)
13469 
13470 	first_mp = *first_mpp;
13471 	mp = *mpp;
13472 
13473 	ASSERT(first_mp == mp);
13474 
13475 	/*
13476 	 * if db_ref > 1 then copymsg and free original. Packet may be
13477 	 * changed and do not want other entity who has a reference to this
13478 	 * message to trip over the changes. This is a blind change because
13479 	 * trying to catch all places that might change packet is too
13480 	 * difficult (since it may be a module above this one)
13481 	 *
13482 	 * This corresponds to the non-fast path case. We walk down the full
13483 	 * chain in this case, and check the db_ref count of all the dblks,
13484 	 * and do a copymsg if required. It is possible that the db_ref counts
13485 	 * of the data blocks in the mblk chain can be different.
13486 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
13487 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
13488 	 * 'snoop' is running.
13489 	 */
13490 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
13491 		if (mp1->b_datap->db_ref > 1) {
13492 			must_copy = B_TRUE;
13493 			break;
13494 		}
13495 	}
13496 
13497 	if (must_copy) {
13498 		mp1 = copymsg(mp);
13499 		if (mp1 == NULL) {
13500 			for (mp1 = mp; mp1 != NULL;
13501 			    mp1 = mp1->b_cont) {
13502 				mp1->b_next = NULL;
13503 				mp1->b_prev = NULL;
13504 			}
13505 			freemsg(mp);
13506 			BUMP_MIB(&ip_mib, ipInDiscards);
13507 			return (B_TRUE);
13508 		}
13509 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
13510 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
13511 			/* Copy b_next - used in M_BREAK messages */
13512 			to_mp->b_next = from_mp->b_next;
13513 			from_mp->b_next = NULL;
13514 			/* Copy b_prev - used by ip_mroute_decap */
13515 			to_mp->b_prev = from_mp->b_prev;
13516 			from_mp->b_prev = NULL;
13517 		}
13518 		*first_mpp = first_mp = mp1;
13519 		freemsg(mp);
13520 		mp = mp1;
13521 		*mpp = mp1;
13522 	}
13523 
13524 	ipha = (ipha_t *)mp->b_rptr;
13525 
13526 	/*
13527 	 * previous code has a case for M_DATA.
13528 	 * We want to check how that happens.
13529 	 */
13530 	ASSERT(first_mp->b_datap->db_type != M_DATA);
13531 	switch (first_mp->b_datap->db_type) {
13532 	case M_PROTO:
13533 	case M_PCPROTO:
13534 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
13535 		    DL_UNITDATA_IND) {
13536 			/* Go handle anything other than data elsewhere. */
13537 			ip_rput_dlpi(q, mp);
13538 			return (B_TRUE);
13539 		}
13540 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
13541 		/* Ditch the DLPI header. */
13542 		mp1 = mp->b_cont;
13543 		ASSERT(first_mp == mp);
13544 		*first_mpp = mp1;
13545 		freeb(mp);
13546 		*mpp = mp1;
13547 		return (B_FALSE);
13548 	case M_BREAK:
13549 		/*
13550 		 * A packet arrives as M_BREAK following a cycle through
13551 		 * ip_rput, ip_newroute, ... and finally ire_add_then_send.
13552 		 * This is an IP datagram sans lower level header.
13553 		 * M_BREAK are also used to pass back in multicast packets
13554 		 * that are encapsulated with a source route.
13555 		 */
13556 		/* Ditch the M_BREAK mblk */
13557 		mp1 = mp->b_cont;
13558 		ASSERT(first_mp == mp);
13559 		*first_mpp = mp1;
13560 		freeb(mp);
13561 		mp = mp1;
13562 		mp->b_next = NULL;
13563 		*mpp = mp;
13564 		*ll_multicast = 0;
13565 		return (B_FALSE);
13566 	case M_IOCACK:
13567 		ip1dbg(("got iocack "));
13568 		iocp = (struct iocblk *)mp->b_rptr;
13569 		switch (iocp->ioc_cmd) {
13570 		case DL_IOC_HDR_INFO:
13571 			ill = (ill_t *)q->q_ptr;
13572 			ill_fastpath_ack(ill, mp);
13573 			return (B_TRUE);
13574 		case SIOCSTUNPARAM:
13575 		case OSIOCSTUNPARAM:
13576 			/* Go through qwriter_ip */
13577 			break;
13578 		case SIOCGTUNPARAM:
13579 		case OSIOCGTUNPARAM:
13580 			ip_rput_other(NULL, q, mp, NULL);
13581 			return (B_TRUE);
13582 		default:
13583 			putnext(q, mp);
13584 			return (B_TRUE);
13585 		}
13586 		/* FALLTHRU */
13587 	case M_ERROR:
13588 	case M_HANGUP:
13589 		/*
13590 		 * Since this is on the ill stream we unconditionally
13591 		 * bump up the refcount
13592 		 */
13593 		ill_refhold(ill);
13594 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
13595 		    B_FALSE);
13596 		return (B_TRUE);
13597 	case M_CTL:
13598 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
13599 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
13600 			IPHADA_M_CTL)) {
13601 			/*
13602 			 * It's an IPsec accelerated packet.
13603 			 * Make sure that the ill from which we received the
13604 			 * packet has enabled IPsec hardware acceleration.
13605 			 */
13606 			if (!(ill->ill_capabilities &
13607 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
13608 				/* IPsec kstats: bean counter */
13609 				freemsg(mp);
13610 				return (B_TRUE);
13611 			}
13612 
13613 			/*
13614 			 * Make mp point to the mblk following the M_CTL,
13615 			 * then process according to type of mp.
13616 			 * After this processing, first_mp will point to
13617 			 * the data-attributes and mp to the pkt following
13618 			 * the M_CTL.
13619 			 */
13620 			mp = first_mp->b_cont;
13621 			if (mp == NULL) {
13622 				freemsg(first_mp);
13623 				return (B_TRUE);
13624 			}
13625 			/*
13626 			 * A Hardware Accelerated packet can only be M_DATA
13627 			 * ESP or AH packet.
13628 			 */
13629 			if (mp->b_datap->db_type != M_DATA) {
13630 				/* non-M_DATA IPsec accelerated packet */
13631 				IPSECHW_DEBUG(IPSECHW_PKT,
13632 				    ("non-M_DATA IPsec accelerated pkt\n"));
13633 				freemsg(first_mp);
13634 				return (B_TRUE);
13635 			}
13636 			ipha = (ipha_t *)mp->b_rptr;
13637 			if (ipha->ipha_protocol != IPPROTO_AH &&
13638 			    ipha->ipha_protocol != IPPROTO_ESP) {
13639 				IPSECHW_DEBUG(IPSECHW_PKT,
13640 				    ("non-M_DATA IPsec accelerated pkt\n"));
13641 				freemsg(first_mp);
13642 				return (B_TRUE);
13643 			}
13644 			*mpp = mp;
13645 			return (B_FALSE);
13646 		}
13647 		putnext(q, mp);
13648 		return (B_TRUE);
13649 	case M_FLUSH:
13650 		if (*mp->b_rptr & FLUSHW) {
13651 			*mp->b_rptr &= ~FLUSHR;
13652 			qreply(q, mp);
13653 			return (B_TRUE);
13654 		}
13655 		freemsg(mp);
13656 		return (B_TRUE);
13657 	case M_IOCNAK:
13658 		ip1dbg(("got iocnak "));
13659 		iocp = (struct iocblk *)mp->b_rptr;
13660 		switch (iocp->ioc_cmd) {
13661 		case DL_IOC_HDR_INFO:
13662 		case SIOCSTUNPARAM:
13663 		case OSIOCSTUNPARAM:
13664 			/*
13665 			 * Since this is on the ill stream we unconditionally
13666 			 * bump up the refcount
13667 			 */
13668 			ill_refhold(ill);
13669 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
13670 			    CUR_OP, B_FALSE);
13671 			return (B_TRUE);
13672 		case SIOCGTUNPARAM:
13673 		case OSIOCGTUNPARAM:
13674 			ip_rput_other(NULL, q, mp, NULL);
13675 			return (B_TRUE);
13676 		default:
13677 			break;
13678 		}
13679 		/* FALLTHRU */
13680 	default:
13681 		putnext(q, mp);
13682 		return (B_TRUE);
13683 	}
13684 }
13685 
13686 /* Read side put procedure.  Packets coming from the wire arrive here. */
13687 void
13688 ip_rput(queue_t *q, mblk_t *mp)
13689 {
13690 	ill_t		*ill;
13691 
13692 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
13693 
13694 	ill = (ill_t *)q->q_ptr;
13695 
13696 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
13697 		union DL_primitives *dl;
13698 
13699 		/*
13700 		 * Things are opening or closing. Only accept DLPI control
13701 		 * messages. In the open case, the ill->ill_ipif has not yet
13702 		 * been created. In the close case, things hanging off the
13703 		 * ill could have been freed already. In either case it
13704 		 * may not be safe to proceed further.
13705 		 */
13706 
13707 		dl = (union DL_primitives *)mp->b_rptr;
13708 		if ((mp->b_datap->db_type != M_PCPROTO) ||
13709 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
13710 			/*
13711 			 * Also SIOC[GS]TUN* ioctls can come here.
13712 			 */
13713 			inet_freemsg(mp);
13714 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13715 			    "ip_input_end: q %p (%S)", q, "uninit");
13716 			return;
13717 		}
13718 	}
13719 
13720 	/*
13721 	 * if db_ref > 1 then copymsg and free original. Packet may be
13722 	 * changed and we do not want the other entity who has a reference to
13723 	 * this message to trip over the changes. This is a blind change because
13724 	 * trying to catch all places that might change the packet is too
13725 	 * difficult.
13726 	 *
13727 	 * This corresponds to the fast path case, where we have a chain of
13728 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
13729 	 * in the mblk chain. There doesn't seem to be a reason why a device
13730 	 * driver would send up data with varying db_ref counts in the mblk
13731 	 * chain. In any case the Fast path is a private interface, and our
13732 	 * drivers don't do such a thing. Given the above assumption, there is
13733 	 * no need to walk down the entire mblk chain (which could have a
13734 	 * potential performance problem)
13735 	 */
13736 	if (mp->b_datap->db_ref > 1) {
13737 		mblk_t  *mp1;
13738 		boolean_t adjusted = B_FALSE;
13739 		IP_STAT(ip_db_ref);
13740 
13741 		/*
13742 		 * The IP_RECVSLLA option depends on having the link layer
13743 		 * header. First check that:
13744 		 * a> the underlying device is of type ether, since this
13745 		 * option is currently supported only over ethernet.
13746 		 * b> there is enough room to copy over the link layer header.
13747 		 *
13748 		 * Once the checks are done, adjust rptr so that the link layer
13749 		 * header will be copied via copymsg. Note that, IFT_ETHER may
13750 		 * be returned by some non-ethernet drivers but in this case the
13751 		 * second check will fail.
13752 		 */
13753 		if (ill->ill_type == IFT_ETHER &&
13754 		    (mp->b_rptr - mp->b_datap->db_base) >=
13755 		    sizeof (struct ether_header)) {
13756 			mp->b_rptr -= sizeof (struct ether_header);
13757 			adjusted = B_TRUE;
13758 		}
13759 		mp1 = copymsg(mp);
13760 		if (mp1 == NULL) {
13761 			/* Clear b_next - used in M_BREAK messages */
13762 			mp->b_next = NULL;
13763 			/* clear b_prev - used by ip_mroute_decap */
13764 			mp->b_prev = NULL;
13765 			freemsg(mp);
13766 			BUMP_MIB(&ip_mib, ipInDiscards);
13767 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13768 			    "ip_rput_end: q %p (%S)", q, "copymsg");
13769 			return;
13770 		}
13771 		if (adjusted) {
13772 			/*
13773 			 * Copy is done. Restore the pointer in the _new_ mblk
13774 			 */
13775 			mp1->b_rptr += sizeof (struct ether_header);
13776 		}
13777 		/* Copy b_next - used in M_BREAK messages */
13778 		mp1->b_next = mp->b_next;
13779 		mp->b_next = NULL;
13780 		/* Copy b_prev - used by ip_mroute_decap */
13781 		mp1->b_prev = mp->b_prev;
13782 		mp->b_prev = NULL;
13783 		freemsg(mp);
13784 		mp = mp1;
13785 	}
13786 
13787 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
13788 	    "ip_rput_end: q %p (%S)", q, "end");
13789 
13790 	ip_input(ill, NULL, mp, 0);
13791 }
13792 
13793 /*
13794  * Direct read side procedure capable of dealing with chains. GLDv3 based
13795  * drivers call this function directly with mblk chains while STREAMS
13796  * read side procedure ip_rput() calls this for single packet with ip_ring
13797  * set to NULL to process one packet at a time.
13798  *
13799  * The ill will always be valid if this function is called directly from
13800  * the driver.
13801  */
13802 /*ARGSUSED*/
13803 void
13804 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain, size_t hdrlen)
13805 {
13806 	ipaddr_t		dst;
13807 	ire_t			*ire;
13808 	ipha_t			*ipha;
13809 	uint_t			pkt_len;
13810 	ssize_t			len;
13811 	uint_t			opt_len;
13812 	int			ll_multicast;
13813 	int			cgtp_flt_pkt;
13814 	queue_t			*q = ill->ill_rq;
13815 	squeue_t		*curr_sqp = NULL;
13816 	mblk_t 			*head = NULL;
13817 	mblk_t			*tail = NULL;
13818 	mblk_t			*first_mp;
13819 	mblk_t 			*mp;
13820 	int			cnt = 0;
13821 
13822 	ASSERT(mp_chain != NULL);
13823 	ASSERT(ill != NULL);
13824 
13825 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
13826 
13827 #define	rptr	((uchar_t *)ipha)
13828 
13829 	while (mp_chain != NULL) {
13830 		first_mp = mp = mp_chain;
13831 		mp_chain = mp_chain->b_next;
13832 		mp->b_next = NULL;
13833 		ll_multicast = 0;
13834 		ire = NULL;
13835 
13836 		/*
13837 		 * ip_input fast path
13838 		 */
13839 
13840 		/* mblk type is not M_DATA */
13841 		if (mp->b_datap->db_type != M_DATA) {
13842 			if (ip_rput_process_notdata(q, &first_mp, ill,
13843 			    &ll_multicast, &mp))
13844 				continue;
13845 		}
13846 
13847 		ASSERT(mp->b_datap->db_type == M_DATA);
13848 		ASSERT(mp->b_datap->db_ref == 1);
13849 
13850 
13851 		ipha = (ipha_t *)mp->b_rptr;
13852 		len = mp->b_wptr - rptr;
13853 
13854 		BUMP_MIB(&ip_mib, ipInReceives);
13855 
13856 		/*
13857 		 * IP header ptr not aligned?
13858 		 * OR IP header not complete in first mblk
13859 		 */
13860 		if (!OK_32PTR(rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13861 			if (!ip_check_and_align_header(q, mp))
13862 				continue;
13863 			ipha = (ipha_t *)mp->b_rptr;
13864 			len = mp->b_wptr - rptr;
13865 		}
13866 
13867 		/* multiple mblk or too short */
13868 		pkt_len = ntohs(ipha->ipha_length);
13869 		len -= pkt_len;
13870 		if (len != 0) {
13871 			/*
13872 			 * Make sure we have data length consistent
13873 			 * with the IP header.
13874 			 */
13875 			if (mp->b_cont == NULL) {
13876 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13877 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13878 					ip2dbg(("ip_input: drop pkt\n"));
13879 					freemsg(mp);
13880 					continue;
13881 				}
13882 				mp->b_wptr = rptr + pkt_len;
13883 			} else if (len += msgdsize(mp->b_cont)) {
13884 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
13885 					BUMP_MIB(&ip_mib, ipInHdrErrors);
13886 					ip2dbg(("ip_input: drop pkt\n"));
13887 					freemsg(mp);
13888 					continue;
13889 				}
13890 				(void) adjmsg(mp, -len);
13891 				IP_STAT(ip_multimblk3);
13892 			}
13893 		}
13894 
13895 		if (ip_loopback_src_or_dst(ipha, ill)) {
13896 			ip2dbg(("ip_input: drop pkt\n"));
13897 			freemsg(mp);
13898 			continue;
13899 		}
13900 
13901 		/*
13902 		 * Attach any necessary label information to this packet.
13903 		 */
13904 		if (is_system_labeled() &&
13905 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
13906 			BUMP_MIB(&ip_mib, ipInDiscards);
13907 			freemsg(mp);
13908 			continue;
13909 		}
13910 
13911 		opt_len = ipha->ipha_version_and_hdr_length -
13912 		    IP_SIMPLE_HDR_VERSION;
13913 		/* IP version bad or there are IP options */
13914 		if (opt_len) {
13915 			if (len != 0)
13916 				IP_STAT(ip_multimblk4);
13917 			else
13918 				IP_STAT(ip_ipoptions);
13919 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
13920 				continue;
13921 		} else {
13922 			dst = ipha->ipha_dst;
13923 		}
13924 
13925 		/*
13926 		 * Invoke the CGTP (multirouting) filtering module to process
13927 		 * the incoming packet. Packets identified as duplicates
13928 		 * must be discarded. Filtering is active only if the
13929 		 * the ip_cgtp_filter ndd variable is non-zero.
13930 		 */
13931 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
13932 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
13933 			cgtp_flt_pkt =
13934 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
13935 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
13936 				freemsg(first_mp);
13937 				continue;
13938 			}
13939 		}
13940 
13941 		/*
13942 		 * If rsvpd is running, let RSVP daemon handle its processing
13943 		 * and forwarding of RSVP multicast/unicast packets.
13944 		 * If rsvpd is not running but mrouted is running, RSVP
13945 		 * multicast packets are forwarded as multicast traffic
13946 		 * and RSVP unicast packets are forwarded by unicast router.
13947 		 * If neither rsvpd nor mrouted is running, RSVP multicast
13948 		 * packets are not forwarded, but the unicast packets are
13949 		 * forwarded like unicast traffic.
13950 		 */
13951 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
13952 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
13953 			/* RSVP packet and rsvpd running. Treat as ours */
13954 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
13955 			/*
13956 			 * This assumes that we deliver to all streams for
13957 			 * multicast and broadcast packets.
13958 			 * We have to force ll_multicast to 1 to handle the
13959 			 * M_DATA messages passed in from ip_mroute_decap.
13960 			 */
13961 			dst = INADDR_BROADCAST;
13962 			ll_multicast = 1;
13963 		} else if (CLASSD(dst)) {
13964 			/* packet is multicast */
13965 			mp->b_next = NULL;
13966 			if (ip_rput_process_multicast(q, mp, ill, ipha,
13967 			    &ll_multicast, &dst))
13968 				continue;
13969 		}
13970 
13971 
13972 		/*
13973 		 * Check if the packet is coming from the Mobile IP
13974 		 * forward tunnel interface
13975 		 */
13976 		if (ill->ill_srcif_refcnt > 0) {
13977 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
13978 			    NULL, ill, MATCH_IRE_TYPE);
13979 			if (ire != NULL && ire->ire_dlureq_mp == NULL &&
13980 			    ire->ire_ipif->ipif_net_type ==
13981 			    IRE_IF_RESOLVER) {
13982 				/* We need to resolve the link layer info */
13983 				ire_refrele(ire);
13984 				ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
13985 				    ll_multicast, dst);
13986 				continue;
13987 			}
13988 		}
13989 
13990 		if (ire == NULL) {
13991 			ire = ire_cache_lookup(dst, ALL_ZONES,
13992 			    MBLK_GETLABEL(mp));
13993 		}
13994 
13995 		/*
13996 		 * If mipagent is running and reverse tunnel is created as per
13997 		 * mobile node request, then any packet coming through the
13998 		 * incoming interface from the mobile-node, should be reverse
13999 		 * tunneled to it's home agent except those that are destined
14000 		 * to foreign agent only.
14001 		 * This needs source address based ire lookup. The routing
14002 		 * entries for source address based lookup are only created by
14003 		 * mipagent program only when a reverse tunnel is created.
14004 		 * Reference : RFC2002, RFC2344
14005 		 */
14006 		if (ill->ill_mrtun_refcnt > 0) {
14007 			ipaddr_t	srcaddr;
14008 			ire_t		*tmp_ire;
14009 
14010 			tmp_ire = ire;	/* Save, we might need it later */
14011 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14012 			    ire->ire_type != IRE_BROADCAST)) {
14013 				srcaddr = ipha->ipha_src;
14014 				ire = ire_mrtun_lookup(srcaddr, ill);
14015 				if (ire != NULL) {
14016 					/*
14017 					 * Should not be getting iphada packet
14018 					 * here. we should only get those for
14019 					 * IRE_LOCAL traffic, excluded above.
14020 					 * Fail-safe (drop packet) in the event
14021 					 * hardware is misbehaving.
14022 					 */
14023 					if (first_mp != mp) {
14024 						/* IPsec KSTATS: beancount me */
14025 						freemsg(first_mp);
14026 					} else {
14027 						/*
14028 						 * This packet must be forwarded
14029 						 * to Reverse Tunnel
14030 						 */
14031 						ip_mrtun_forward(ire, ill, mp);
14032 					}
14033 					ire_refrele(ire);
14034 					if (tmp_ire != NULL)
14035 						ire_refrele(tmp_ire);
14036 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14037 					    "ip_input_end: q %p (%S)",
14038 					    q, "uninit");
14039 					continue;
14040 				}
14041 			}
14042 			/*
14043 			 * If this packet is from a non-mobilenode  or a
14044 			 * mobile-node which does not request reverse
14045 			 * tunnel service
14046 			 */
14047 			ire = tmp_ire;
14048 		}
14049 
14050 
14051 		/*
14052 		 * If we reach here that means the incoming packet satisfies
14053 		 * one of the following conditions:
14054 		 *   - packet is from a mobile node which does not request
14055 		 *	reverse tunnel
14056 		 *   - packet is from a non-mobile node, which is the most
14057 		 *	common case
14058 		 *   - packet is from a reverse tunnel enabled mobile node
14059 		 *	and destined to foreign agent only
14060 		 */
14061 
14062 		if (ire == NULL) {
14063 			/*
14064 			 * No IRE for this destination, so it can't be for us.
14065 			 * Unless we are forwarding, drop the packet.
14066 			 * We have to let source routed packets through
14067 			 * since we don't yet know if they are 'ping -l'
14068 			 * packets i.e. if they will go out over the
14069 			 * same interface as they came in on.
14070 			 */
14071 			ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14072 			continue;
14073 		}
14074 
14075 		/*
14076 		 * Broadcast IRE may indicate either broadcast or
14077 		 * multicast packet
14078 		 */
14079 		if (ire->ire_type == IRE_BROADCAST) {
14080 			/*
14081 			 * Skip broadcast checks if packet is UDP multicast;
14082 			 * we'd rather not enter ip_rput_process_broadcast()
14083 			 * unless the packet is broadcast for real, since
14084 			 * that routine is a no-op for multicast.
14085 			 */
14086 			if ((ipha->ipha_protocol != IPPROTO_UDP ||
14087 			    !CLASSD(ipha->ipha_dst)) &&
14088 			    ip_rput_process_broadcast(&q, mp, &ire, ipha, ill,
14089 			    dst, cgtp_flt_pkt, ll_multicast)) {
14090 				continue;
14091 			}
14092 		} else if (ire->ire_stq != NULL) {
14093 			/* fowarding? */
14094 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14095 			    ll_multicast);
14096 			continue;
14097 		}
14098 
14099 		/* packet not for us */
14100 		if (ire->ire_rfq != q) {
14101 			if (ip_rput_notforus(&q, mp, ire, ill)) {
14102 				continue;
14103 			}
14104 		}
14105 
14106 		switch (ipha->ipha_protocol) {
14107 		case IPPROTO_TCP:
14108 			ASSERT(first_mp == mp);
14109 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14110 				mp, 0, q, ip_ring)) != NULL) {
14111 				if (curr_sqp == NULL) {
14112 					curr_sqp = GET_SQUEUE(mp);
14113 					ASSERT(cnt == 0);
14114 					cnt++;
14115 					head = tail = mp;
14116 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14117 					ASSERT(tail != NULL);
14118 					cnt++;
14119 					tail->b_next = mp;
14120 					tail = mp;
14121 				} else {
14122 					/*
14123 					 * A different squeue. Send the
14124 					 * chain for the previous squeue on
14125 					 * its way. This shouldn't happen
14126 					 * often unless interrupt binding
14127 					 * changes.
14128 					 */
14129 					IP_STAT(ip_input_multi_squeue);
14130 					squeue_enter_chain(curr_sqp, head,
14131 					    tail, cnt, SQTAG_IP_INPUT);
14132 					curr_sqp = GET_SQUEUE(mp);
14133 					head = mp;
14134 					tail = mp;
14135 					cnt = 1;
14136 				}
14137 			}
14138 			IRE_REFRELE(ire);
14139 			continue;
14140 		case IPPROTO_UDP:
14141 			ASSERT(first_mp == mp);
14142 			ip_udp_input(q, mp, ipha, ire, ill);
14143 			IRE_REFRELE(ire);
14144 			continue;
14145 		case IPPROTO_SCTP:
14146 			ASSERT(first_mp == mp);
14147 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14148 			    q, dst);
14149 			continue;
14150 		default:
14151 			ip_proto_input(q, first_mp, ipha, ire, ill);
14152 			IRE_REFRELE(ire);
14153 			continue;
14154 		}
14155 	}
14156 
14157 	if (head != NULL)
14158 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14159 
14160 	/*
14161 	 * This code is there just to make netperf/ttcp look good.
14162 	 *
14163 	 * Its possible that after being in polling mode (and having cleared
14164 	 * the backlog), squeues have turned the interrupt frequency higher
14165 	 * to improve latency at the expense of more CPU utilization (less
14166 	 * packets per interrupts or more number of interrupts). Workloads
14167 	 * like ttcp/netperf do manage to tickle polling once in a while
14168 	 * but for the remaining time, stay in higher interrupt mode since
14169 	 * their packet arrival rate is pretty uniform and this shows up
14170 	 * as higher CPU utilization. Since people care about CPU utilization
14171 	 * while running netperf/ttcp, turn the interrupt frequency back to
14172 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14173 	 */
14174 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14175 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14176 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14177 			ip_ring->rr_blank(ip_ring->rr_handle,
14178 			    ip_ring->rr_normal_blank_time,
14179 			    ip_ring->rr_normal_pkt_cnt);
14180 		}
14181 	}
14182 
14183 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14184 	    "ip_input_end: q %p (%S)", q, "end");
14185 #undef	rptr
14186 }
14187 
14188 static void
14189 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
14190     t_uscalar_t err)
14191 {
14192 	if (dl_err == DL_SYSERR) {
14193 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14194 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
14195 		    ill->ill_name, dlpi_prim_str(prim), err);
14196 		return;
14197 	}
14198 
14199 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
14200 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
14201 	    dlpi_err_str(dl_err));
14202 }
14203 
14204 /*
14205  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
14206  * than DL_UNITDATA_IND messages. If we need to process this message
14207  * exclusively, we call qwriter_ip, in which case we also need to call
14208  * ill_refhold before that, since qwriter_ip does an ill_refrele.
14209  */
14210 void
14211 ip_rput_dlpi(queue_t *q, mblk_t *mp)
14212 {
14213 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14214 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14215 	ill_t		*ill;
14216 
14217 	ip1dbg(("ip_rput_dlpi"));
14218 	ill = (ill_t *)q->q_ptr;
14219 	switch (dloa->dl_primitive) {
14220 	case DL_ERROR_ACK:
14221 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
14222 		    "%s (0x%x), unix %u\n", ill->ill_name,
14223 		    dlpi_prim_str(dlea->dl_error_primitive),
14224 		    dlea->dl_error_primitive,
14225 		    dlpi_err_str(dlea->dl_errno),
14226 		    dlea->dl_errno,
14227 		    dlea->dl_unix_errno));
14228 		switch (dlea->dl_error_primitive) {
14229 		case DL_UNBIND_REQ:
14230 			mutex_enter(&ill->ill_lock);
14231 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14232 			cv_signal(&ill->ill_cv);
14233 			mutex_exit(&ill->ill_lock);
14234 			/* FALLTHRU */
14235 		case DL_NOTIFY_REQ:
14236 		case DL_ATTACH_REQ:
14237 		case DL_DETACH_REQ:
14238 		case DL_INFO_REQ:
14239 		case DL_BIND_REQ:
14240 		case DL_ENABMULTI_REQ:
14241 		case DL_PHYS_ADDR_REQ:
14242 		case DL_CAPABILITY_REQ:
14243 		case DL_CONTROL_REQ:
14244 			/*
14245 			 * Refhold the ill to match qwriter_ip which does a
14246 			 * refrele. Since this is on the ill stream we
14247 			 * unconditionally bump up the refcount without
14248 			 * checking for ILL_CAN_LOOKUP
14249 			 */
14250 			ill_refhold(ill);
14251 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14252 			    CUR_OP, B_FALSE);
14253 			return;
14254 		case DL_DISABMULTI_REQ:
14255 			freemsg(mp);	/* Don't want to pass this up */
14256 			return;
14257 		default:
14258 			break;
14259 		}
14260 		ip_dlpi_error(ill, dlea->dl_error_primitive,
14261 		    dlea->dl_errno, dlea->dl_unix_errno);
14262 		freemsg(mp);
14263 		return;
14264 	case DL_INFO_ACK:
14265 	case DL_BIND_ACK:
14266 	case DL_PHYS_ADDR_ACK:
14267 	case DL_NOTIFY_ACK:
14268 	case DL_CAPABILITY_ACK:
14269 	case DL_CONTROL_ACK:
14270 		/*
14271 		 * Refhold the ill to match qwriter_ip which does a refrele
14272 		 * Since this is on the ill stream we unconditionally
14273 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
14274 		 */
14275 		ill_refhold(ill);
14276 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14277 		    CUR_OP, B_FALSE);
14278 		return;
14279 	case DL_NOTIFY_IND:
14280 		ill_refhold(ill);
14281 		/*
14282 		 * The DL_NOTIFY_IND is an asynchronous message that has no
14283 		 * relation to the current ioctl in progress (if any). Hence we
14284 		 * pass in NEW_OP in this case.
14285 		 */
14286 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14287 		    NEW_OP, B_FALSE);
14288 		return;
14289 	case DL_OK_ACK:
14290 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
14291 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
14292 		switch (dloa->dl_correct_primitive) {
14293 		case DL_UNBIND_REQ:
14294 			mutex_enter(&ill->ill_lock);
14295 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
14296 			cv_signal(&ill->ill_cv);
14297 			mutex_exit(&ill->ill_lock);
14298 			/* FALLTHRU */
14299 		case DL_ATTACH_REQ:
14300 		case DL_DETACH_REQ:
14301 			/*
14302 			 * Refhold the ill to match qwriter_ip which does a
14303 			 * refrele. Since this is on the ill stream we
14304 			 * unconditionally bump up the refcount
14305 			 */
14306 			ill_refhold(ill);
14307 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
14308 			    CUR_OP, B_FALSE);
14309 			return;
14310 		case DL_ENABMULTI_REQ:
14311 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14312 				ill->ill_dlpi_multicast_state = IDMS_OK;
14313 			break;
14314 
14315 		}
14316 		break;
14317 	default:
14318 		break;
14319 	}
14320 	freemsg(mp);
14321 }
14322 
14323 /*
14324  * Handling of DLPI messages that require exclusive access to the ipsq.
14325  *
14326  * Need to do ill_pending_mp_release on ioctl completion, which could
14327  * happen here. (along with mi_copy_done)
14328  */
14329 /* ARGSUSED */
14330 static void
14331 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
14332 {
14333 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
14334 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
14335 	int		err = 0;
14336 	ill_t		*ill;
14337 	ipif_t		*ipif = NULL;
14338 	mblk_t		*mp1 = NULL;
14339 	conn_t		*connp = NULL;
14340 	t_uscalar_t	physaddr_req;
14341 	mblk_t		*mp_hw;
14342 	union DL_primitives *dlp;
14343 	boolean_t	success;
14344 	boolean_t	ioctl_aborted = B_FALSE;
14345 	boolean_t	log = B_TRUE;
14346 
14347 	ip1dbg(("ip_rput_dlpi_writer .."));
14348 	ill = (ill_t *)q->q_ptr;
14349 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
14350 
14351 	ASSERT(IAM_WRITER_ILL(ill));
14352 
14353 	/*
14354 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
14355 	 * both are null or non-null. However we can assert that only
14356 	 * after grabbing the ipsq_lock. So we don't make any assertion
14357 	 * here and in other places in the code.
14358 	 */
14359 	ipif = ipsq->ipsq_pending_ipif;
14360 	/*
14361 	 * The current ioctl could have been aborted by the user and a new
14362 	 * ioctl to bring up another ill could have started. We could still
14363 	 * get a response from the driver later.
14364 	 */
14365 	if (ipif != NULL && ipif->ipif_ill != ill)
14366 		ioctl_aborted = B_TRUE;
14367 
14368 	switch (dloa->dl_primitive) {
14369 	case DL_ERROR_ACK:
14370 		switch (dlea->dl_error_primitive) {
14371 		case DL_UNBIND_REQ:
14372 		case DL_ATTACH_REQ:
14373 		case DL_DETACH_REQ:
14374 		case DL_INFO_REQ:
14375 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14376 			break;
14377 		case DL_NOTIFY_REQ:
14378 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
14379 			log = B_FALSE;
14380 			break;
14381 		case DL_PHYS_ADDR_REQ:
14382 			/*
14383 			 * For IPv6 only, there are two additional
14384 			 * phys_addr_req's sent to the driver to get the
14385 			 * IPv6 token and lla. This allows IP to acquire
14386 			 * the hardware address format for a given interface
14387 			 * without having built in knowledge of the hardware
14388 			 * address. ill_phys_addr_pend keeps track of the last
14389 			 * DL_PAR sent so we know which response we are
14390 			 * dealing with. ill_dlpi_done will update
14391 			 * ill_phys_addr_pend when it sends the next req.
14392 			 * We don't complete the IOCTL until all three DL_PARs
14393 			 * have been attempted, so set *_len to 0 and break.
14394 			 */
14395 			physaddr_req = ill->ill_phys_addr_pend;
14396 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
14397 			if (physaddr_req == DL_IPV6_TOKEN) {
14398 				ill->ill_token_length = 0;
14399 				log = B_FALSE;
14400 				break;
14401 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
14402 				ill->ill_nd_lla_len = 0;
14403 				log = B_FALSE;
14404 				break;
14405 			}
14406 			/*
14407 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
14408 			 * We presumably have an IOCTL hanging out waiting
14409 			 * for completion. Find it and complete the IOCTL
14410 			 * with the error noted.
14411 			 * However, ill_dl_phys was called on an ill queue
14412 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
14413 			 * set. But the ioctl is known to be pending on ill_wq.
14414 			 */
14415 			if (!ill->ill_ifname_pending)
14416 				break;
14417 			ill->ill_ifname_pending = 0;
14418 			if (!ioctl_aborted)
14419 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14420 			if (mp1 != NULL) {
14421 				/*
14422 				 * This operation (SIOCSLIFNAME) must have
14423 				 * happened on the ill. Assert there is no conn
14424 				 */
14425 				ASSERT(connp == NULL);
14426 				q = ill->ill_wq;
14427 			}
14428 			break;
14429 		case DL_BIND_REQ:
14430 			ill_dlpi_done(ill, DL_BIND_REQ);
14431 			if (ill->ill_ifname_pending)
14432 				break;
14433 			/*
14434 			 * Something went wrong with the bind.  We presumably
14435 			 * have an IOCTL hanging out waiting for completion.
14436 			 * Find it, take down the interface that was coming
14437 			 * up, and complete the IOCTL with the error noted.
14438 			 */
14439 			if (!ioctl_aborted)
14440 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14441 			if (mp1 != NULL) {
14442 				/*
14443 				 * This operation (SIOCSLIFFLAGS) must have
14444 				 * happened from a conn.
14445 				 */
14446 				ASSERT(connp != NULL);
14447 				q = CONNP_TO_WQ(connp);
14448 				if (ill->ill_move_in_progress) {
14449 					ILL_CLEAR_MOVE(ill);
14450 				}
14451 				(void) ipif_down(ipif, NULL, NULL);
14452 				/* error is set below the switch */
14453 			}
14454 			break;
14455 		case DL_ENABMULTI_REQ:
14456 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
14457 
14458 			if (ill->ill_dlpi_multicast_state == IDMS_INPROGRESS)
14459 				ill->ill_dlpi_multicast_state = IDMS_FAILED;
14460 			if (ill->ill_dlpi_multicast_state == IDMS_FAILED) {
14461 				ipif_t *ipif;
14462 
14463 				log = B_FALSE;
14464 				printf("ip: joining multicasts failed (%d)"
14465 				    " on %s - will use link layer "
14466 				    "broadcasts for multicast\n",
14467 				    dlea->dl_errno, ill->ill_name);
14468 
14469 				/*
14470 				 * Set up the multicast mapping alone.
14471 				 * writer, so ok to access ill->ill_ipif
14472 				 * without any lock.
14473 				 */
14474 				ipif = ill->ill_ipif;
14475 				mutex_enter(&ill->ill_phyint->phyint_lock);
14476 				ill->ill_phyint->phyint_flags |=
14477 				    PHYI_MULTI_BCAST;
14478 				mutex_exit(&ill->ill_phyint->phyint_lock);
14479 
14480 				if (!ill->ill_isv6) {
14481 					(void) ipif_arp_setup_multicast(ipif,
14482 					    NULL);
14483 				} else {
14484 					(void) ipif_ndp_setup_multicast(ipif,
14485 					    NULL);
14486 				}
14487 			}
14488 			freemsg(mp);	/* Don't want to pass this up */
14489 			return;
14490 		case DL_CAPABILITY_REQ:
14491 		case DL_CONTROL_REQ:
14492 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
14493 			    "DL_CAPABILITY/CONTROL REQ\n"));
14494 			ill_dlpi_done(ill, dlea->dl_error_primitive);
14495 			ill->ill_capab_state = IDMS_FAILED;
14496 			freemsg(mp);
14497 			return;
14498 		}
14499 		/*
14500 		 * Note the error for IOCTL completion (mp1 is set when
14501 		 * ready to complete ioctl). If ill_ifname_pending_err is
14502 		 * set, an error occured during plumbing (ill_ifname_pending),
14503 		 * so we want to report that error.
14504 		 *
14505 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
14506 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
14507 		 * expected to get errack'd if the driver doesn't support
14508 		 * these flags (e.g. ethernet). log will be set to B_FALSE
14509 		 * if these error conditions are encountered.
14510 		 */
14511 		if (mp1 != NULL) {
14512 			if (ill->ill_ifname_pending_err != 0)  {
14513 				err = ill->ill_ifname_pending_err;
14514 				ill->ill_ifname_pending_err = 0;
14515 			} else {
14516 				err = dlea->dl_unix_errno ?
14517 				    dlea->dl_unix_errno : ENXIO;
14518 			}
14519 		/*
14520 		 * If we're plumbing an interface and an error hasn't already
14521 		 * been saved, set ill_ifname_pending_err to the error passed
14522 		 * up. Ignore the error if log is B_FALSE (see comment above).
14523 		 */
14524 		} else if (log && ill->ill_ifname_pending &&
14525 		    ill->ill_ifname_pending_err == 0) {
14526 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
14527 			dlea->dl_unix_errno : ENXIO;
14528 		}
14529 
14530 		if (log)
14531 			ip_dlpi_error(ill, dlea->dl_error_primitive,
14532 			    dlea->dl_errno, dlea->dl_unix_errno);
14533 		break;
14534 	case DL_CAPABILITY_ACK: {
14535 		boolean_t reneg_flag = B_FALSE;
14536 		/* Call a routine to handle this one. */
14537 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
14538 		/*
14539 		 * Check if the ACK is due to renegotiation case since we
14540 		 * will need to send a new CAPABILITY_REQ later.
14541 		 */
14542 		if (ill->ill_capab_state == IDMS_RENEG) {
14543 			/* This is the ack for a renogiation case */
14544 			reneg_flag = B_TRUE;
14545 			ill->ill_capab_state = IDMS_UNKNOWN;
14546 		}
14547 		ill_capability_ack(ill, mp);
14548 		if (reneg_flag)
14549 			ill_capability_probe(ill);
14550 		break;
14551 	}
14552 	case DL_CONTROL_ACK:
14553 		/* We treat all of these as "fire and forget" */
14554 		ill_dlpi_done(ill, DL_CONTROL_REQ);
14555 		break;
14556 	case DL_INFO_ACK:
14557 		/* Call a routine to handle this one. */
14558 		ill_dlpi_done(ill, DL_INFO_REQ);
14559 		ip_ll_subnet_defaults(ill, mp);
14560 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
14561 		return;
14562 	case DL_BIND_ACK:
14563 		/*
14564 		 * We should have an IOCTL waiting on this unless
14565 		 * sent by ill_dl_phys, in which case just return
14566 		 */
14567 		ill_dlpi_done(ill, DL_BIND_REQ);
14568 		if (ill->ill_ifname_pending)
14569 			break;
14570 
14571 		if (!ioctl_aborted)
14572 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
14573 		if (mp1 == NULL)
14574 			break;
14575 		ASSERT(connp != NULL);
14576 		q = CONNP_TO_WQ(connp);
14577 
14578 		/*
14579 		 * We are exclusive. So nothing can change even after
14580 		 * we get the pending mp. If need be we can put it back
14581 		 * and restart, as in calling ipif_arp_up()  below.
14582 		 */
14583 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
14584 
14585 		mutex_enter(&ill->ill_lock);
14586 		ill->ill_dl_up = 1;
14587 		mutex_exit(&ill->ill_lock);
14588 
14589 		/*
14590 		 * Now bring up the resolver, when that is
14591 		 * done we'll create IREs and we are done.
14592 		 */
14593 		if (ill->ill_isv6) {
14594 			/*
14595 			 * v6 interfaces.
14596 			 * Unlike ARP which has to do another bind
14597 			 * and attach, once we get here we are
14598 			 * done withh NDP. Except in the case of
14599 			 * ILLF_XRESOLV, in which case we send an
14600 			 * AR_INTERFACE_UP to the external resolver.
14601 			 * If all goes well, the ioctl will complete
14602 			 * in ip_rput(). If there's an error, we
14603 			 * complete it here.
14604 			 */
14605 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
14606 			    B_FALSE);
14607 			if (err == 0) {
14608 				if (ill->ill_flags & ILLF_XRESOLV) {
14609 					mutex_enter(&connp->conn_lock);
14610 					mutex_enter(&ill->ill_lock);
14611 					success = ipsq_pending_mp_add(
14612 					    connp, ipif, q, mp1, 0);
14613 					mutex_exit(&ill->ill_lock);
14614 					mutex_exit(&connp->conn_lock);
14615 					if (success) {
14616 						err = ipif_resolver_up(ipif,
14617 						    B_FALSE);
14618 						if (err == EINPROGRESS) {
14619 							freemsg(mp);
14620 							return;
14621 						}
14622 						ASSERT(err != 0);
14623 						mp1 = ipsq_pending_mp_get(ipsq,
14624 						    &connp);
14625 						ASSERT(mp1 != NULL);
14626 					} else {
14627 						/* conn has started closing */
14628 						err = EINTR;
14629 					}
14630 				} else { /* Non XRESOLV interface */
14631 					err = ipif_up_done_v6(ipif);
14632 				}
14633 			}
14634 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
14635 			/*
14636 			 * ARP and other v4 external resolvers.
14637 			 * Leave the pending mblk intact so that
14638 			 * the ioctl completes in ip_rput().
14639 			 */
14640 			mutex_enter(&connp->conn_lock);
14641 			mutex_enter(&ill->ill_lock);
14642 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
14643 			mutex_exit(&ill->ill_lock);
14644 			mutex_exit(&connp->conn_lock);
14645 			if (success) {
14646 				err = ipif_resolver_up(ipif, B_FALSE);
14647 				if (err == EINPROGRESS) {
14648 					freemsg(mp);
14649 					return;
14650 				}
14651 				ASSERT(err != 0);
14652 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
14653 			} else {
14654 				/* The conn has started closing */
14655 				err = EINTR;
14656 			}
14657 		} else {
14658 			/*
14659 			 * This one is complete. Reply to pending ioctl.
14660 			 */
14661 			err = ipif_up_done(ipif);
14662 		}
14663 
14664 		if ((err == 0) && (ill->ill_up_ipifs)) {
14665 			err = ill_up_ipifs(ill, q, mp1);
14666 			if (err == EINPROGRESS) {
14667 				freemsg(mp);
14668 				return;
14669 			}
14670 		}
14671 
14672 		if (ill->ill_up_ipifs) {
14673 			ill_group_cleanup(ill);
14674 		}
14675 
14676 		break;
14677 	case DL_NOTIFY_IND: {
14678 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
14679 		ire_t *ire;
14680 		boolean_t need_ire_walk_v4 = B_FALSE;
14681 		boolean_t need_ire_walk_v6 = B_FALSE;
14682 
14683 		/*
14684 		 * Change the address everywhere we need to.
14685 		 * What we're getting here is a link-level addr or phys addr.
14686 		 * The new addr is at notify + notify->dl_addr_offset
14687 		 * The address length is notify->dl_addr_length;
14688 		 */
14689 		switch (notify->dl_notification) {
14690 		case DL_NOTE_PHYS_ADDR:
14691 			mp_hw = copyb(mp);
14692 			if (mp_hw == NULL) {
14693 				err = ENOMEM;
14694 				break;
14695 			}
14696 			dlp = (union DL_primitives *)mp_hw->b_rptr;
14697 			/*
14698 			 * We currently don't support changing
14699 			 * the token via DL_NOTIFY_IND.
14700 			 * When we do support it, we have to consider
14701 			 * what the implications are with respect to
14702 			 * the token and the link local address.
14703 			 */
14704 			mutex_enter(&ill->ill_lock);
14705 			if (dlp->notify_ind.dl_data ==
14706 			    DL_IPV6_LINK_LAYER_ADDR) {
14707 				if (ill->ill_nd_lla_mp != NULL)
14708 					freemsg(ill->ill_nd_lla_mp);
14709 				ill->ill_nd_lla_mp = mp_hw;
14710 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
14711 				    dlp->notify_ind.dl_addr_offset;
14712 				ill->ill_nd_lla_len =
14713 				    dlp->notify_ind.dl_addr_length -
14714 				    ABS(ill->ill_sap_length);
14715 				mutex_exit(&ill->ill_lock);
14716 				break;
14717 			} else if (dlp->notify_ind.dl_data ==
14718 			    DL_CURR_PHYS_ADDR) {
14719 				if (ill->ill_phys_addr_mp != NULL)
14720 					freemsg(ill->ill_phys_addr_mp);
14721 				ill->ill_phys_addr_mp = mp_hw;
14722 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
14723 				    dlp->notify_ind.dl_addr_offset;
14724 				ill->ill_phys_addr_length =
14725 				    dlp->notify_ind.dl_addr_length -
14726 				    ABS(ill->ill_sap_length);
14727 				if (ill->ill_isv6 &&
14728 				    !(ill->ill_flags & ILLF_XRESOLV)) {
14729 					if (ill->ill_nd_lla_mp != NULL)
14730 						freemsg(ill->ill_nd_lla_mp);
14731 					ill->ill_nd_lla_mp = copyb(mp_hw);
14732 					ill->ill_nd_lla = (uchar_t *)
14733 					    ill->ill_nd_lla_mp->b_rptr +
14734 					    dlp->notify_ind.dl_addr_offset;
14735 					ill->ill_nd_lla_len =
14736 					    ill->ill_phys_addr_length;
14737 				}
14738 			}
14739 			mutex_exit(&ill->ill_lock);
14740 			/*
14741 			 * Send out gratuitous arp request for our new
14742 			 * hardware address.
14743 			 */
14744 			for (ipif = ill->ill_ipif; ipif != NULL;
14745 			    ipif = ipif->ipif_next) {
14746 				if (!(ipif->ipif_flags & IPIF_UP))
14747 					continue;
14748 				if (ill->ill_isv6) {
14749 					ipif_ndp_down(ipif);
14750 					/*
14751 					 * Set B_TRUE to enable
14752 					 * ipif_ndp_up() to send out
14753 					 * unsolicited advertisements.
14754 					 */
14755 					err = ipif_ndp_up(ipif,
14756 					    &ipif->ipif_v6lcl_addr,
14757 					    B_TRUE);
14758 					if (err) {
14759 						ip1dbg((
14760 						    "ip_rput_dlpi_writer: "
14761 						    "Failed to update ndp "
14762 						    "err %d\n", err));
14763 					}
14764 				} else {
14765 					/*
14766 					 * IPv4 ARP case
14767 					 *
14768 					 * Set B_TRUE, as we only want
14769 					 * ipif_resolver_up to send an
14770 					 * AR_ENTRY_ADD request up to
14771 					 * ARP.
14772 					 */
14773 					err = ipif_resolver_up(ipif,
14774 					    B_TRUE);
14775 					if (err) {
14776 						ip1dbg((
14777 						    "ip_rput_dlpi_writer: "
14778 						    "Failed to update arp "
14779 						    "err %d\n", err));
14780 					}
14781 				}
14782 			}
14783 			/*
14784 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
14785 			 * case so that all old fastpath information can be
14786 			 * purged from IRE caches.
14787 			 */
14788 		/* FALLTHRU */
14789 		case DL_NOTE_FASTPATH_FLUSH:
14790 			/*
14791 			 * Any fastpath probe sent henceforth will get the
14792 			 * new fp mp. So we first delete any ires that are
14793 			 * waiting for the fastpath. Then walk all ires and
14794 			 * delete the ire or delete the fp mp. In the case of
14795 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
14796 			 * recreate the ire's without going through a complex
14797 			 * ipif up/down dance. So we don't delete the ire
14798 			 * itself, but just the ire_fp_mp for these 2 ire's
14799 			 * In the case of the other ire's we delete the ire's
14800 			 * themselves. Access to ire_fp_mp is completely
14801 			 * protected by ire_lock for IRE_MIPRTUN and
14802 			 * IRE_BROADCAST. Deleting the ire is preferable in the
14803 			 * other cases for performance.
14804 			 */
14805 			if (ill->ill_isv6) {
14806 				nce_fastpath_list_dispatch(ill, NULL, NULL);
14807 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
14808 				    NULL);
14809 			} else {
14810 				ire_fastpath_list_dispatch(ill, NULL, NULL);
14811 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
14812 				    IRE_CACHE | IRE_BROADCAST,
14813 				    ire_fastpath_flush, NULL, ill);
14814 				mutex_enter(&ire_mrtun_lock);
14815 				if (ire_mrtun_count != 0) {
14816 					mutex_exit(&ire_mrtun_lock);
14817 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
14818 					    IRE_MIPRTUN, ire_fastpath_flush,
14819 					    NULL, ill);
14820 				} else {
14821 					mutex_exit(&ire_mrtun_lock);
14822 				}
14823 			}
14824 			break;
14825 		case DL_NOTE_SDU_SIZE:
14826 			/*
14827 			 * Change the MTU size of the interface, of all
14828 			 * attached ipif's, and of all relevant ire's.  The
14829 			 * new value's a uint32_t at notify->dl_data.
14830 			 * Mtu change Vs. new ire creation - protocol below.
14831 			 *
14832 			 * a Mark the ipif as IPIF_CHANGING.
14833 			 * b Set the new mtu in the ipif.
14834 			 * c Change the ire_max_frag on all affected ires
14835 			 * d Unmark the IPIF_CHANGING
14836 			 *
14837 			 * To see how the protocol works, assume an interface
14838 			 * route is also being added simultaneously by
14839 			 * ip_rt_add and let 'ipif' be the ipif referenced by
14840 			 * the ire. If the ire is created before step a,
14841 			 * it will be cleaned up by step c. If the ire is
14842 			 * created after step d, it will see the new value of
14843 			 * ipif_mtu. Any attempt to create the ire between
14844 			 * steps a to d will fail because of the IPIF_CHANGING
14845 			 * flag. Note that ire_create() is passed a pointer to
14846 			 * the ipif_mtu, and not the value. During ire_add
14847 			 * under the bucket lock, the ire_max_frag of the
14848 			 * new ire being created is set from the ipif/ire from
14849 			 * which it is being derived.
14850 			 */
14851 			mutex_enter(&ill->ill_lock);
14852 			ill->ill_max_frag = (uint_t)notify->dl_data;
14853 
14854 			/*
14855 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
14856 			 * leave it alone
14857 			 */
14858 			if (ill->ill_mtu_userspecified) {
14859 				mutex_exit(&ill->ill_lock);
14860 				break;
14861 			}
14862 			ill->ill_max_mtu = ill->ill_max_frag;
14863 			if (ill->ill_isv6) {
14864 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
14865 					ill->ill_max_mtu = IPV6_MIN_MTU;
14866 			} else {
14867 				if (ill->ill_max_mtu < IP_MIN_MTU)
14868 					ill->ill_max_mtu = IP_MIN_MTU;
14869 			}
14870 			for (ipif = ill->ill_ipif; ipif != NULL;
14871 			    ipif = ipif->ipif_next) {
14872 				/*
14873 				 * Don't override the mtu if the user
14874 				 * has explicitly set it.
14875 				 */
14876 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
14877 					continue;
14878 				ipif->ipif_mtu = (uint_t)notify->dl_data;
14879 				if (ipif->ipif_isv6)
14880 					ire = ipif_to_ire_v6(ipif);
14881 				else
14882 					ire = ipif_to_ire(ipif);
14883 				if (ire != NULL) {
14884 					ire->ire_max_frag = ipif->ipif_mtu;
14885 					ire_refrele(ire);
14886 				}
14887 				if (ipif->ipif_flags & IPIF_UP) {
14888 					if (ill->ill_isv6)
14889 						need_ire_walk_v6 = B_TRUE;
14890 					else
14891 						need_ire_walk_v4 = B_TRUE;
14892 				}
14893 			}
14894 			mutex_exit(&ill->ill_lock);
14895 			if (need_ire_walk_v4)
14896 				ire_walk_v4(ill_mtu_change, (char *)ill,
14897 				    ALL_ZONES);
14898 			if (need_ire_walk_v6)
14899 				ire_walk_v6(ill_mtu_change, (char *)ill,
14900 				    ALL_ZONES);
14901 			break;
14902 		case DL_NOTE_LINK_UP:
14903 		case DL_NOTE_LINK_DOWN: {
14904 			/*
14905 			 * We are writer. ill / phyint / ipsq assocs stable.
14906 			 * The RUNNING flag reflects the state of the link.
14907 			 */
14908 			phyint_t *phyint = ill->ill_phyint;
14909 			uint64_t new_phyint_flags;
14910 			boolean_t changed = B_FALSE;
14911 
14912 			mutex_enter(&phyint->phyint_lock);
14913 			new_phyint_flags =
14914 			    (notify->dl_notification == DL_NOTE_LINK_UP) ?
14915 			    phyint->phyint_flags | PHYI_RUNNING :
14916 			    phyint->phyint_flags & ~PHYI_RUNNING;
14917 			if (new_phyint_flags != phyint->phyint_flags) {
14918 				phyint->phyint_flags = new_phyint_flags;
14919 				changed = B_TRUE;
14920 			}
14921 			mutex_exit(&phyint->phyint_lock);
14922 			/*
14923 			 * If the flags have changed, send a message to
14924 			 * the routing socket.
14925 			 */
14926 			if (changed) {
14927 				if (phyint->phyint_illv4 != NULL) {
14928 					ip_rts_ifmsg(
14929 					    phyint->phyint_illv4->ill_ipif);
14930 				}
14931 				if (phyint->phyint_illv6 != NULL) {
14932 					ip_rts_ifmsg(
14933 					    phyint->phyint_illv6->ill_ipif);
14934 				}
14935 			}
14936 			break;
14937 		}
14938 		case DL_NOTE_PROMISC_ON_PHYS:
14939 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14940 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
14941 			mutex_enter(&ill->ill_lock);
14942 			ill->ill_promisc_on_phys = B_TRUE;
14943 			mutex_exit(&ill->ill_lock);
14944 			break;
14945 		case DL_NOTE_PROMISC_OFF_PHYS:
14946 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
14947 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
14948 			mutex_enter(&ill->ill_lock);
14949 			ill->ill_promisc_on_phys = B_FALSE;
14950 			mutex_exit(&ill->ill_lock);
14951 			break;
14952 		case DL_NOTE_CAPAB_RENEG:
14953 			/*
14954 			 * Something changed on the driver side.
14955 			 * It wants us to renegotiate the capabilities
14956 			 * on this ill. The most likely cause is the
14957 			 * aggregation interface under us where a
14958 			 * port got added or went away.
14959 			 *
14960 			 * We reset the capabilities and set the
14961 			 * state to IDMS_RENG so that when the ack
14962 			 * comes back, we can start the
14963 			 * renegotiation process.
14964 			 */
14965 			ill_capability_reset(ill);
14966 			ill->ill_capab_state = IDMS_RENEG;
14967 			break;
14968 		default:
14969 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
14970 			    "type 0x%x for DL_NOTIFY_IND\n",
14971 			    notify->dl_notification));
14972 			break;
14973 		}
14974 
14975 		/*
14976 		 * As this is an asynchronous operation, we
14977 		 * should not call ill_dlpi_done
14978 		 */
14979 		break;
14980 	}
14981 	case DL_NOTIFY_ACK:
14982 		/*
14983 		 * Don't really need to check for what notifications
14984 		 * are supported; we'll process what gets sent upstream,
14985 		 * and we know it'll be something we support changing
14986 		 * based on our DL_NOTIFY_REQ.
14987 		 */
14988 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
14989 		break;
14990 	case DL_PHYS_ADDR_ACK: {
14991 		/*
14992 		 * We should have an IOCTL waiting on this when request
14993 		 * sent by ill_dl_phys.
14994 		 * However, ill_dl_phys was called on an ill queue (from
14995 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
14996 		 * ioctl is known to be pending on ill_wq.
14997 		 * There are two additional phys_addr_req's sent to the
14998 		 * driver to get the token and lla. ill_phys_addr_pend
14999 		 * keeps track of the last one sent so we know which
15000 		 * response we are dealing with. ill_dlpi_done will
15001 		 * update ill_phys_addr_pend when it sends the next req.
15002 		 * We don't complete the IOCTL until all three DL_PARs
15003 		 * have been attempted.
15004 		 *
15005 		 * We don't need any lock to update ill_nd_lla* fields,
15006 		 * since the ill is not yet up, We grab the lock just
15007 		 * for uniformity with other code that accesses ill_nd_lla.
15008 		 */
15009 		physaddr_req = ill->ill_phys_addr_pend;
15010 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15011 		if (physaddr_req == DL_IPV6_TOKEN ||
15012 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15013 			if (physaddr_req == DL_IPV6_TOKEN) {
15014 				/*
15015 				 * bcopy to low-order bits of ill_token
15016 				 *
15017 				 * XXX Temporary hack - currently,
15018 				 * all known tokens are 64 bits,
15019 				 * so I'll cheat for the moment.
15020 				 */
15021 				dlp = (union DL_primitives *)mp->b_rptr;
15022 
15023 				mutex_enter(&ill->ill_lock);
15024 				bcopy((uchar_t *)(mp->b_rptr +
15025 				dlp->physaddr_ack.dl_addr_offset),
15026 				(void *)&ill->ill_token.s6_addr32[2],
15027 				dlp->physaddr_ack.dl_addr_length);
15028 				ill->ill_token_length =
15029 					dlp->physaddr_ack.dl_addr_length;
15030 				mutex_exit(&ill->ill_lock);
15031 			} else {
15032 				ASSERT(ill->ill_nd_lla_mp == NULL);
15033 				mp_hw = copyb(mp);
15034 				if (mp_hw == NULL) {
15035 					err = ENOMEM;
15036 					break;
15037 				}
15038 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15039 				mutex_enter(&ill->ill_lock);
15040 				ill->ill_nd_lla_mp = mp_hw;
15041 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15042 				dlp->physaddr_ack.dl_addr_offset;
15043 				ill->ill_nd_lla_len =
15044 					dlp->physaddr_ack.dl_addr_length;
15045 				mutex_exit(&ill->ill_lock);
15046 			}
15047 			break;
15048 		}
15049 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15050 		ASSERT(ill->ill_phys_addr_mp == NULL);
15051 		if (!ill->ill_ifname_pending)
15052 			break;
15053 		ill->ill_ifname_pending = 0;
15054 		if (!ioctl_aborted)
15055 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15056 		if (mp1 != NULL) {
15057 			ASSERT(connp == NULL);
15058 			q = ill->ill_wq;
15059 		}
15060 		/*
15061 		 * If any error acks received during the plumbing sequence,
15062 		 * ill_ifname_pending_err will be set. Break out and send up
15063 		 * the error to the pending ioctl.
15064 		 */
15065 		if (ill->ill_ifname_pending_err != 0) {
15066 			err = ill->ill_ifname_pending_err;
15067 			ill->ill_ifname_pending_err = 0;
15068 			break;
15069 		}
15070 		/*
15071 		 * Get the interface token.  If the zeroth interface
15072 		 * address is zero then set the address to the link local
15073 		 * address
15074 		 */
15075 		mp_hw = copyb(mp);
15076 		if (mp_hw == NULL) {
15077 			err = ENOMEM;
15078 			break;
15079 		}
15080 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15081 		ill->ill_phys_addr_mp = mp_hw;
15082 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15083 				dlp->physaddr_ack.dl_addr_offset;
15084 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15085 		    ill->ill_phys_addr_length == 0 ||
15086 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15087 			/*
15088 			 * Compatibility: atun driver returns a length of 0.
15089 			 * ipdptp has an ill_phys_addr_length of zero(from
15090 			 * DL_BIND_ACK) but a non-zero length here.
15091 			 * ipd has an ill_phys_addr_length of 4(from
15092 			 * DL_BIND_ACK) but a non-zero length here.
15093 			 */
15094 			ill->ill_phys_addr = NULL;
15095 		} else if (dlp->physaddr_ack.dl_addr_length !=
15096 		    ill->ill_phys_addr_length) {
15097 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15098 			    "Address length mismatch %d %d\n",
15099 			    dlp->physaddr_ack.dl_addr_length,
15100 			    ill->ill_phys_addr_length));
15101 			err = EINVAL;
15102 			break;
15103 		}
15104 		mutex_enter(&ill->ill_lock);
15105 		if (ill->ill_nd_lla_mp == NULL) {
15106 			ill->ill_nd_lla_mp = copyb(mp_hw);
15107 			if (ill->ill_nd_lla_mp == NULL) {
15108 				err = ENOMEM;
15109 				mutex_exit(&ill->ill_lock);
15110 				break;
15111 			}
15112 			ill->ill_nd_lla =
15113 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15114 			    dlp->physaddr_ack.dl_addr_offset;
15115 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15116 		}
15117 		mutex_exit(&ill->ill_lock);
15118 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15119 			(void) ill_setdefaulttoken(ill);
15120 
15121 		/*
15122 		 * If the ill zero interface has a zero address assign
15123 		 * it the proper link local address.
15124 		 */
15125 		ASSERT(ill->ill_ipif->ipif_id == 0);
15126 		if (ipif != NULL &&
15127 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15128 			(void) ipif_setlinklocal(ipif);
15129 		break;
15130 	}
15131 	case DL_OK_ACK:
15132 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15133 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15134 		    dloa->dl_correct_primitive));
15135 		switch (dloa->dl_correct_primitive) {
15136 		case DL_UNBIND_REQ:
15137 		case DL_ATTACH_REQ:
15138 		case DL_DETACH_REQ:
15139 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15140 			break;
15141 		}
15142 		break;
15143 	default:
15144 		break;
15145 	}
15146 
15147 	freemsg(mp);
15148 	if (mp1) {
15149 		struct iocblk *iocp;
15150 		int mode;
15151 
15152 		/*
15153 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15154 		 * SIOCSLIFNAME do a copyout.
15155 		 */
15156 		iocp = (struct iocblk *)mp1->b_rptr;
15157 
15158 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
15159 		    iocp->ioc_cmd == SIOCSLIFNAME)
15160 			mode = COPYOUT;
15161 		else
15162 			mode = NO_COPYOUT;
15163 		/*
15164 		 * The ioctl must complete now without EINPROGRESS
15165 		 * since ipsq_pending_mp_get has removed the ioctl mblk
15166 		 * from ipsq_pending_mp. Otherwise the ioctl will be
15167 		 * stuck for ever in the ipsq.
15168 		 */
15169 		ASSERT(err != EINPROGRESS);
15170 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
15171 
15172 	}
15173 }
15174 
15175 /*
15176  * ip_rput_other is called by ip_rput to handle messages modifying the global
15177  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15178  */
15179 /* ARGSUSED */
15180 void
15181 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15182 {
15183 	ill_t		*ill;
15184 	struct iocblk	*iocp;
15185 	mblk_t		*mp1;
15186 	conn_t		*connp = NULL;
15187 
15188 	ip1dbg(("ip_rput_other "));
15189 	ill = (ill_t *)q->q_ptr;
15190 	/*
15191 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15192 	 * in which case ipsq is NULL.
15193 	 */
15194 	if (ipsq != NULL) {
15195 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15196 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15197 	}
15198 
15199 	switch (mp->b_datap->db_type) {
15200 	case M_ERROR:
15201 	case M_HANGUP:
15202 		/*
15203 		 * The device has a problem.  We force the ILL down.  It can
15204 		 * be brought up again manually using SIOCSIFFLAGS (via
15205 		 * ifconfig or equivalent).
15206 		 */
15207 		ASSERT(ipsq != NULL);
15208 		if (mp->b_rptr < mp->b_wptr)
15209 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15210 		if (ill->ill_error == 0)
15211 			ill->ill_error = ENXIO;
15212 		if (!ill_down_start(q, mp))
15213 			return;
15214 		ipif_all_down_tail(ipsq, q, mp, NULL);
15215 		break;
15216 	case M_IOCACK:
15217 		iocp = (struct iocblk *)mp->b_rptr;
15218 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15219 		switch (iocp->ioc_cmd) {
15220 		case SIOCSTUNPARAM:
15221 		case OSIOCSTUNPARAM:
15222 			ASSERT(ipsq != NULL);
15223 			/*
15224 			 * Finish socket ioctl passed through to tun.
15225 			 * We should have an IOCTL waiting on this.
15226 			 */
15227 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15228 			if (ill->ill_isv6) {
15229 				struct iftun_req *ta;
15230 
15231 				/*
15232 				 * if a source or destination is
15233 				 * being set, try and set the link
15234 				 * local address for the tunnel
15235 				 */
15236 				ta = (struct iftun_req *)mp->b_cont->
15237 				    b_cont->b_rptr;
15238 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
15239 					ipif_set_tun_llink(ill, ta);
15240 				}
15241 
15242 			}
15243 			if (mp1 != NULL) {
15244 				/*
15245 				 * Now copy back the b_next/b_prev used by
15246 				 * mi code for the mi_copy* functions.
15247 				 * See ip_sioctl_tunparam() for the reason.
15248 				 * Also protect against missing b_cont.
15249 				 */
15250 				if (mp->b_cont != NULL) {
15251 					mp->b_cont->b_next =
15252 					    mp1->b_cont->b_next;
15253 					mp->b_cont->b_prev =
15254 					    mp1->b_cont->b_prev;
15255 				}
15256 				inet_freemsg(mp1);
15257 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15258 				ASSERT(connp != NULL);
15259 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15260 				    iocp->ioc_error, NO_COPYOUT,
15261 				    ipsq->ipsq_current_ipif, ipsq);
15262 			} else {
15263 				ASSERT(connp == NULL);
15264 				putnext(q, mp);
15265 			}
15266 			break;
15267 		case SIOCGTUNPARAM:
15268 		case OSIOCGTUNPARAM:
15269 			/*
15270 			 * This is really M_IOCDATA from the tunnel driver.
15271 			 * convert back and complete the ioctl.
15272 			 * We should have an IOCTL waiting on this.
15273 			 */
15274 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
15275 			if (mp1) {
15276 				/*
15277 				 * Now copy back the b_next/b_prev used by
15278 				 * mi code for the mi_copy* functions.
15279 				 * See ip_sioctl_tunparam() for the reason.
15280 				 * Also protect against missing b_cont.
15281 				 */
15282 				if (mp->b_cont != NULL) {
15283 					mp->b_cont->b_next =
15284 					    mp1->b_cont->b_next;
15285 					mp->b_cont->b_prev =
15286 					    mp1->b_cont->b_prev;
15287 				}
15288 				inet_freemsg(mp1);
15289 				if (iocp->ioc_error == 0)
15290 					mp->b_datap->db_type = M_IOCDATA;
15291 				ASSERT(connp != NULL);
15292 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15293 				    iocp->ioc_error, COPYOUT, NULL, NULL);
15294 			} else {
15295 				ASSERT(connp == NULL);
15296 				putnext(q, mp);
15297 			}
15298 			break;
15299 		default:
15300 			break;
15301 		}
15302 		break;
15303 	case M_IOCNAK:
15304 		iocp = (struct iocblk *)mp->b_rptr;
15305 
15306 		switch (iocp->ioc_cmd) {
15307 		int mode;
15308 		ipif_t	*ipif;
15309 
15310 		case DL_IOC_HDR_INFO:
15311 			/*
15312 			 * If this was the first attempt turn of the
15313 			 * fastpath probing.
15314 			 */
15315 			mutex_enter(&ill->ill_lock);
15316 			if (ill->ill_dlpi_fastpath_state == IDMS_INPROGRESS) {
15317 				ill->ill_dlpi_fastpath_state = IDMS_FAILED;
15318 				mutex_exit(&ill->ill_lock);
15319 				ill_fastpath_nack(ill);
15320 				ip1dbg(("ip_rput: DLPI fastpath off on "
15321 				    "interface %s\n",
15322 				    ill->ill_name));
15323 			} else {
15324 				mutex_exit(&ill->ill_lock);
15325 			}
15326 			freemsg(mp);
15327 			break;
15328 		case SIOCSTUNPARAM:
15329 		case OSIOCSTUNPARAM:
15330 			ASSERT(ipsq != NULL);
15331 			/*
15332 			 * Finish socket ioctl passed through to tun
15333 			 * We should have an IOCTL waiting on this.
15334 			 */
15335 			/* FALLTHRU */
15336 		case SIOCGTUNPARAM:
15337 		case OSIOCGTUNPARAM:
15338 			/*
15339 			 * This is really M_IOCDATA from the tunnel driver.
15340 			 * convert back and complete the ioctl.
15341 			 * We should have an IOCTL waiting on this.
15342 			 */
15343 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
15344 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
15345 				mp1 = ill_pending_mp_get(ill, &connp,
15346 				    iocp->ioc_id);
15347 				mode = COPYOUT;
15348 				ipsq = NULL;
15349 				ipif = NULL;
15350 			} else {
15351 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15352 				mode = NO_COPYOUT;
15353 				ASSERT(ipsq->ipsq_current_ipif != NULL);
15354 				ipif = ipsq->ipsq_current_ipif;
15355 			}
15356 			if (mp1 != NULL) {
15357 				/*
15358 				 * Now copy back the b_next/b_prev used by
15359 				 * mi code for the mi_copy* functions.
15360 				 * See ip_sioctl_tunparam() for the reason.
15361 				 * Also protect against missing b_cont.
15362 				 */
15363 				if (mp->b_cont != NULL) {
15364 					mp->b_cont->b_next =
15365 					    mp1->b_cont->b_next;
15366 					mp->b_cont->b_prev =
15367 					    mp1->b_cont->b_prev;
15368 				}
15369 				inet_freemsg(mp1);
15370 				if (iocp->ioc_error == 0)
15371 					iocp->ioc_error = EINVAL;
15372 				ASSERT(connp != NULL);
15373 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
15374 				    iocp->ioc_error, mode, ipif, ipsq);
15375 			} else {
15376 				ASSERT(connp == NULL);
15377 				putnext(q, mp);
15378 			}
15379 			break;
15380 		default:
15381 			break;
15382 		}
15383 	default:
15384 		break;
15385 	}
15386 }
15387 
15388 /*
15389  * NOTE : This function does not ire_refrele the ire argument passed in.
15390  *
15391  * IPQoS notes
15392  * IP policy is invoked twice for a forwarded packet, once on the read side
15393  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
15394  * enabled. An additional parameter, in_ill, has been added for this purpose.
15395  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
15396  * because ip_mroute drops this information.
15397  *
15398  */
15399 void
15400 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
15401 {
15402 	uint32_t	pkt_len;
15403 	queue_t	*q;
15404 	uint32_t	sum;
15405 #define	rptr	((uchar_t *)ipha)
15406 	uint32_t	max_frag;
15407 	uint32_t	ill_index;
15408 
15409 	/* Get the ill_index of the incoming ILL */
15410 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
15411 
15412 	/* Initiate Read side IPPF processing */
15413 	if (IPP_ENABLED(IPP_FWD_IN)) {
15414 		ip_process(IPP_FWD_IN, &mp, ill_index);
15415 		if (mp == NULL) {
15416 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
15417 			    "during IPPF processing\n"));
15418 			return;
15419 		}
15420 	}
15421 	pkt_len = ntohs(ipha->ipha_length);
15422 
15423 	/* Adjust the checksum to reflect the ttl decrement. */
15424 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
15425 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
15426 
15427 	if (ipha->ipha_ttl-- <= 1) {
15428 		if (ip_csum_hdr(ipha)) {
15429 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15430 			goto drop_pkt;
15431 		}
15432 		/*
15433 		 * Note: ire_stq this will be NULL for multicast
15434 		 * datagrams using the long path through arp (the IRE
15435 		 * is not an IRE_CACHE). This should not cause
15436 		 * problems since we don't generate ICMP errors for
15437 		 * multicast packets.
15438 		 */
15439 		q = ire->ire_stq;
15440 		if (q)
15441 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED);
15442 		else
15443 			freemsg(mp);
15444 		return;
15445 	}
15446 
15447 	/*
15448 	 * Don't forward if the interface is down
15449 	 */
15450 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
15451 		BUMP_MIB(&ip_mib, ipInDiscards);
15452 		goto drop_pkt;
15453 	}
15454 
15455 	/* Get the ill_index of the outgoing ILL */
15456 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
15457 
15458 	if (is_system_labeled()) {
15459 		mblk_t *mp1;
15460 
15461 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
15462 			BUMP_MIB(&ip_mib, ipForwProhibits);
15463 			goto drop_pkt;
15464 		}
15465 		/* Size may have changed */
15466 		mp = mp1;
15467 		ipha = (ipha_t *)mp->b_rptr;
15468 		pkt_len = ntohs(ipha->ipha_length);
15469 	}
15470 
15471 	/* Check if there are options to update */
15472 	if (!IS_SIMPLE_IPH(ipha)) {
15473 		if (ip_csum_hdr(ipha)) {
15474 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15475 			goto drop_pkt;
15476 		}
15477 		if (ip_rput_forward_options(mp, ipha, ire)) {
15478 			return;
15479 		}
15480 
15481 		ipha->ipha_hdr_checksum = 0;
15482 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
15483 	}
15484 	max_frag = ire->ire_max_frag;
15485 	if (pkt_len > max_frag) {
15486 		/*
15487 		 * It needs fragging on its way out.  We haven't
15488 		 * verified the header checksum yet.  Since we
15489 		 * are going to put a surely good checksum in the
15490 		 * outgoing header, we have to make sure that it
15491 		 * was good coming in.
15492 		 */
15493 		if (ip_csum_hdr(ipha)) {
15494 			BUMP_MIB(&ip_mib, ipInCksumErrs);
15495 			goto drop_pkt;
15496 		}
15497 		/* Initiate Write side IPPF processing */
15498 		if (IPP_ENABLED(IPP_FWD_OUT)) {
15499 			ip_process(IPP_FWD_OUT, &mp, ill_index);
15500 			if (mp == NULL) {
15501 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
15502 				    " during IPPF processing\n"));
15503 				return;
15504 			}
15505 		}
15506 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0);
15507 		return;
15508 	}
15509 
15510 	mp = ip_wput_attach_llhdr(mp, ire, IPP_FWD_OUT, ill_index);
15511 	if (mp == NULL) {
15512 		BUMP_MIB(&ip_mib, ipInDiscards);
15513 		return;
15514 	}
15515 
15516 	q = ire->ire_stq;
15517 	UPDATE_IB_PKT_COUNT(ire);
15518 	ire->ire_last_used_time = lbolt;
15519 	BUMP_MIB(&ip_mib, ipForwDatagrams);
15520 	putnext(q, mp);
15521 	return;
15522 
15523 drop_pkt:;
15524 	ip1dbg(("ip_rput_forward: drop pkt\n"));
15525 	freemsg(mp);
15526 #undef	rptr
15527 }
15528 
15529 void
15530 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
15531 {
15532 	ire_t	*ire;
15533 
15534 	ASSERT(!ipif->ipif_isv6);
15535 	/*
15536 	 * Find an IRE which matches the destination and the outgoing
15537 	 * queue in the cache table. All we need is an IRE_CACHE which
15538 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
15539 	 * then it is enough to have some IRE_CACHE in the group.
15540 	 */
15541 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
15542 		dst = ipif->ipif_pp_dst_addr;
15543 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
15544 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
15545 	if (ire == NULL) {
15546 		/*
15547 		 * Mark this packet to make it be delivered to
15548 		 * ip_rput_forward after the new ire has been
15549 		 * created.
15550 		 */
15551 		mp->b_prev = NULL;
15552 		mp->b_next = mp;
15553 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
15554 		    NULL, 0);
15555 	} else {
15556 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
15557 		IRE_REFRELE(ire);
15558 	}
15559 }
15560 
15561 /* Update any source route, record route or timestamp options */
15562 static int
15563 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
15564 {
15565 	ipoptp_t	opts;
15566 	uchar_t		*opt;
15567 	uint8_t		optval;
15568 	uint8_t		optlen;
15569 	ipaddr_t	dst;
15570 	uint32_t	ts;
15571 	ire_t		*dst_ire = NULL;
15572 	ire_t		*tmp_ire = NULL;
15573 	timestruc_t	now;
15574 
15575 	ip2dbg(("ip_rput_forward_options\n"));
15576 	dst = ipha->ipha_dst;
15577 	for (optval = ipoptp_first(&opts, ipha);
15578 	    optval != IPOPT_EOL;
15579 	    optval = ipoptp_next(&opts)) {
15580 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
15581 		opt = opts.ipoptp_cur;
15582 		optlen = opts.ipoptp_len;
15583 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
15584 		    optval, opts.ipoptp_len));
15585 		switch (optval) {
15586 			uint32_t off;
15587 		case IPOPT_SSRR:
15588 		case IPOPT_LSRR:
15589 			/* Check if adminstratively disabled */
15590 			if (!ip_forward_src_routed) {
15591 				BUMP_MIB(&ip_mib, ipForwProhibits);
15592 				if (ire->ire_stq)
15593 					icmp_unreachable(ire->ire_stq, mp,
15594 					    ICMP_SOURCE_ROUTE_FAILED);
15595 				else {
15596 					ip0dbg(("ip_rput_forward_options: "
15597 					    "unable to send unreach\n"));
15598 					freemsg(mp);
15599 				}
15600 				return (-1);
15601 			}
15602 
15603 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15604 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15605 			if (dst_ire == NULL) {
15606 				/*
15607 				 * Must be partial since ip_rput_options
15608 				 * checked for strict.
15609 				 */
15610 				break;
15611 			}
15612 			off = opt[IPOPT_OFFSET];
15613 			off--;
15614 		redo_srr:
15615 			if (optlen < IP_ADDR_LEN ||
15616 			    off > optlen - IP_ADDR_LEN) {
15617 				/* End of source route */
15618 				ip1dbg((
15619 				    "ip_rput_forward_options: end of SR\n"));
15620 				ire_refrele(dst_ire);
15621 				break;
15622 			}
15623 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15624 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15625 			    IP_ADDR_LEN);
15626 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
15627 			    ntohl(dst)));
15628 
15629 			/*
15630 			 * Check if our address is present more than
15631 			 * once as consecutive hops in source route.
15632 			 */
15633 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
15634 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
15635 			if (tmp_ire != NULL) {
15636 				ire_refrele(tmp_ire);
15637 				off += IP_ADDR_LEN;
15638 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15639 				goto redo_srr;
15640 			}
15641 			ipha->ipha_dst = dst;
15642 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15643 			ire_refrele(dst_ire);
15644 			break;
15645 		case IPOPT_RR:
15646 			off = opt[IPOPT_OFFSET];
15647 			off--;
15648 			if (optlen < IP_ADDR_LEN ||
15649 			    off > optlen - IP_ADDR_LEN) {
15650 				/* No more room - ignore */
15651 				ip1dbg((
15652 				    "ip_rput_forward_options: end of RR\n"));
15653 				break;
15654 			}
15655 			bcopy(&ire->ire_src_addr, (char *)opt + off,
15656 			    IP_ADDR_LEN);
15657 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15658 			break;
15659 		case IPOPT_TS:
15660 			/* Insert timestamp if there is room */
15661 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15662 			case IPOPT_TS_TSONLY:
15663 				off = IPOPT_TS_TIMELEN;
15664 				break;
15665 			case IPOPT_TS_PRESPEC:
15666 			case IPOPT_TS_PRESPEC_RFC791:
15667 				/* Verify that the address matched */
15668 				off = opt[IPOPT_OFFSET] - 1;
15669 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
15670 				dst_ire = ire_ctable_lookup(dst, 0,
15671 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
15672 				    MATCH_IRE_TYPE);
15673 
15674 				if (dst_ire == NULL) {
15675 					/* Not for us */
15676 					break;
15677 				}
15678 				ire_refrele(dst_ire);
15679 				/* FALLTHRU */
15680 			case IPOPT_TS_TSANDADDR:
15681 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
15682 				break;
15683 			default:
15684 				/*
15685 				 * ip_*put_options should have already
15686 				 * dropped this packet.
15687 				 */
15688 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
15689 				    "unknown IT - bug in ip_rput_options?\n");
15690 				return (0);	/* Keep "lint" happy */
15691 			}
15692 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
15693 				/* Increase overflow counter */
15694 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
15695 				opt[IPOPT_POS_OV_FLG] =
15696 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
15697 				    (off << 4));
15698 				break;
15699 			}
15700 			off = opt[IPOPT_OFFSET] - 1;
15701 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
15702 			case IPOPT_TS_PRESPEC:
15703 			case IPOPT_TS_PRESPEC_RFC791:
15704 			case IPOPT_TS_TSANDADDR:
15705 				bcopy(&ire->ire_src_addr,
15706 				    (char *)opt + off, IP_ADDR_LEN);
15707 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
15708 				/* FALLTHRU */
15709 			case IPOPT_TS_TSONLY:
15710 				off = opt[IPOPT_OFFSET] - 1;
15711 				/* Compute # of milliseconds since midnight */
15712 				gethrestime(&now);
15713 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
15714 				    now.tv_nsec / (NANOSEC / MILLISEC);
15715 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
15716 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
15717 				break;
15718 			}
15719 			break;
15720 		}
15721 	}
15722 	return (0);
15723 }
15724 
15725 /*
15726  * This is called after processing at least one of AH/ESP headers.
15727  *
15728  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
15729  * the actual, physical interface on which the packet was received,
15730  * but, when ip_strict_dst_multihoming is set to 1, could be the
15731  * interface which had the ipha_dst configured when the packet went
15732  * through ip_rput. The ill_index corresponding to the recv_ill
15733  * is saved in ipsec_in_rill_index
15734  */
15735 void
15736 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
15737 {
15738 	mblk_t *mp;
15739 	ipaddr_t dst;
15740 	in6_addr_t *v6dstp;
15741 	ipha_t *ipha;
15742 	ip6_t *ip6h;
15743 	ipsec_in_t *ii;
15744 	boolean_t ill_need_rele = B_FALSE;
15745 	boolean_t rill_need_rele = B_FALSE;
15746 	boolean_t ire_need_rele = B_FALSE;
15747 
15748 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
15749 	ASSERT(ii->ipsec_in_ill_index != 0);
15750 
15751 	mp = ipsec_mp->b_cont;
15752 	ASSERT(mp != NULL);
15753 
15754 
15755 	if (ill == NULL) {
15756 		ASSERT(recv_ill == NULL);
15757 		/*
15758 		 * We need to get the original queue on which ip_rput_local
15759 		 * or ip_rput_data_v6 was called.
15760 		 */
15761 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
15762 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
15763 		ill_need_rele = B_TRUE;
15764 
15765 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
15766 			recv_ill = ill_lookup_on_ifindex(
15767 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
15768 			    NULL, NULL, NULL, NULL);
15769 			rill_need_rele = B_TRUE;
15770 		} else {
15771 			recv_ill = ill;
15772 		}
15773 
15774 		if ((ill == NULL) || (recv_ill == NULL)) {
15775 			ip0dbg(("ip_fanout_proto_again: interface "
15776 			    "disappeared\n"));
15777 			if (ill != NULL)
15778 				ill_refrele(ill);
15779 			if (recv_ill != NULL)
15780 				ill_refrele(recv_ill);
15781 			freemsg(ipsec_mp);
15782 			return;
15783 		}
15784 	}
15785 
15786 	ASSERT(ill != NULL && recv_ill != NULL);
15787 
15788 	if (mp->b_datap->db_type == M_CTL) {
15789 		/*
15790 		 * AH/ESP is returning the ICMP message after
15791 		 * removing their headers. Fanout again till
15792 		 * it gets to the right protocol.
15793 		 */
15794 		if (ii->ipsec_in_v4) {
15795 			icmph_t *icmph;
15796 			int iph_hdr_length;
15797 			int hdr_length;
15798 
15799 			ipha = (ipha_t *)mp->b_rptr;
15800 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
15801 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
15802 			ipha = (ipha_t *)&icmph[1];
15803 			hdr_length = IPH_HDR_LENGTH(ipha);
15804 			/*
15805 			 * icmp_inbound_error_fanout may need to do pullupmsg.
15806 			 * Reset the type to M_DATA.
15807 			 */
15808 			mp->b_datap->db_type = M_DATA;
15809 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
15810 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
15811 			    B_FALSE, ill, ii->ipsec_in_zoneid);
15812 		} else {
15813 			icmp6_t *icmp6;
15814 			int hdr_length;
15815 
15816 			ip6h = (ip6_t *)mp->b_rptr;
15817 			/* Don't call hdr_length_v6() unless you have to. */
15818 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
15819 				hdr_length = ip_hdr_length_v6(mp, ip6h);
15820 			else
15821 				hdr_length = IPV6_HDR_LEN;
15822 
15823 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
15824 			/*
15825 			 * icmp_inbound_error_fanout_v6 may need to do
15826 			 * pullupmsg.  Reset the type to M_DATA.
15827 			 */
15828 			mp->b_datap->db_type = M_DATA;
15829 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
15830 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
15831 		}
15832 		if (ill_need_rele)
15833 			ill_refrele(ill);
15834 		if (rill_need_rele)
15835 			ill_refrele(recv_ill);
15836 		return;
15837 	}
15838 
15839 	if (ii->ipsec_in_v4) {
15840 		ipha = (ipha_t *)mp->b_rptr;
15841 		dst = ipha->ipha_dst;
15842 		if (CLASSD(dst)) {
15843 			/*
15844 			 * Multicast has to be delivered to all streams.
15845 			 */
15846 			dst = INADDR_BROADCAST;
15847 		}
15848 
15849 		if (ire == NULL) {
15850 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
15851 			    MBLK_GETLABEL(mp));
15852 			if (ire == NULL) {
15853 				if (ill_need_rele)
15854 					ill_refrele(ill);
15855 				if (rill_need_rele)
15856 					ill_refrele(recv_ill);
15857 				ip1dbg(("ip_fanout_proto_again: "
15858 				    "IRE not found"));
15859 				freemsg(ipsec_mp);
15860 				return;
15861 			}
15862 			ire_need_rele = B_TRUE;
15863 		}
15864 
15865 		switch (ipha->ipha_protocol) {
15866 			case IPPROTO_UDP:
15867 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
15868 				    recv_ill);
15869 				if (ire_need_rele)
15870 					ire_refrele(ire);
15871 				break;
15872 			case IPPROTO_TCP:
15873 				if (!ire_need_rele)
15874 					IRE_REFHOLD(ire);
15875 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
15876 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
15877 				IRE_REFRELE(ire);
15878 				if (mp != NULL)
15879 					squeue_enter_chain(GET_SQUEUE(mp), mp,
15880 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
15881 				break;
15882 			case IPPROTO_SCTP:
15883 				if (!ire_need_rele)
15884 					IRE_REFHOLD(ire);
15885 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
15886 				    ipsec_mp, 0, ill->ill_rq, dst);
15887 				break;
15888 			default:
15889 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
15890 				    recv_ill);
15891 				if (ire_need_rele)
15892 					ire_refrele(ire);
15893 				break;
15894 		}
15895 	} else {
15896 		uint32_t rput_flags = 0;
15897 
15898 		ip6h = (ip6_t *)mp->b_rptr;
15899 		v6dstp = &ip6h->ip6_dst;
15900 		/*
15901 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
15902 		 * address.
15903 		 *
15904 		 * Currently, we don't store that state in the IPSEC_IN
15905 		 * message, and we may need to.
15906 		 */
15907 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
15908 		    IP6_IN_LLMCAST : 0);
15909 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
15910 		    NULL);
15911 	}
15912 	if (ill_need_rele)
15913 		ill_refrele(ill);
15914 	if (rill_need_rele)
15915 		ill_refrele(recv_ill);
15916 }
15917 
15918 /*
15919  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
15920  * returns 'true' if there are still fragments left on the queue, in
15921  * which case we restart the timer.
15922  */
15923 void
15924 ill_frag_timer(void *arg)
15925 {
15926 	ill_t	*ill = (ill_t *)arg;
15927 	boolean_t frag_pending;
15928 
15929 	mutex_enter(&ill->ill_lock);
15930 	ASSERT(!ill->ill_fragtimer_executing);
15931 	if (ill->ill_state_flags & ILL_CONDEMNED) {
15932 		ill->ill_frag_timer_id = 0;
15933 		mutex_exit(&ill->ill_lock);
15934 		return;
15935 	}
15936 	ill->ill_fragtimer_executing = 1;
15937 	mutex_exit(&ill->ill_lock);
15938 
15939 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
15940 
15941 	/*
15942 	 * Restart the timer, if we have fragments pending or if someone
15943 	 * wanted us to be scheduled again.
15944 	 */
15945 	mutex_enter(&ill->ill_lock);
15946 	ill->ill_fragtimer_executing = 0;
15947 	ill->ill_frag_timer_id = 0;
15948 	if (frag_pending || ill->ill_fragtimer_needrestart)
15949 		ill_frag_timer_start(ill);
15950 	mutex_exit(&ill->ill_lock);
15951 }
15952 
15953 void
15954 ill_frag_timer_start(ill_t *ill)
15955 {
15956 	ASSERT(MUTEX_HELD(&ill->ill_lock));
15957 
15958 	/* If the ill is closing or opening don't proceed */
15959 	if (ill->ill_state_flags & ILL_CONDEMNED)
15960 		return;
15961 
15962 	if (ill->ill_fragtimer_executing) {
15963 		/*
15964 		 * ill_frag_timer is currently executing. Just record the
15965 		 * the fact that we want the timer to be restarted.
15966 		 * ill_frag_timer will post a timeout before it returns,
15967 		 * ensuring it will be called again.
15968 		 */
15969 		ill->ill_fragtimer_needrestart = 1;
15970 		return;
15971 	}
15972 
15973 	if (ill->ill_frag_timer_id == 0) {
15974 		/*
15975 		 * The timer is neither running nor is the timeout handler
15976 		 * executing. Post a timeout so that ill_frag_timer will be
15977 		 * called
15978 		 */
15979 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
15980 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
15981 		ill->ill_fragtimer_needrestart = 0;
15982 	}
15983 }
15984 
15985 /*
15986  * This routine is needed for loopback when forwarding multicasts.
15987  *
15988  * IPQoS Notes:
15989  * IPPF processing is done in fanout routines.
15990  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
15991  * processing for IPSec packets is done when it comes back in clear.
15992  * NOTE : The callers of this function need to do the ire_refrele for the
15993  *	  ire that is being passed in.
15994  */
15995 void
15996 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
15997     ill_t *recv_ill)
15998 {
15999 	ill_t	*ill = (ill_t *)q->q_ptr;
16000 	uint32_t	sum;
16001 	uint32_t	u1;
16002 	uint32_t	u2;
16003 	int		hdr_length;
16004 	boolean_t	mctl_present;
16005 	mblk_t		*first_mp = mp;
16006 	mblk_t		*hada_mp = NULL;
16007 	ipha_t		*inner_ipha;
16008 
16009 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16010 	    "ip_rput_locl_start: q %p", q);
16011 
16012 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16013 
16014 
16015 #define	rptr	((uchar_t *)ipha)
16016 #define	iphs	((uint16_t *)ipha)
16017 
16018 	/*
16019 	 * no UDP or TCP packet should come here anymore.
16020 	 */
16021 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16022 	    (ipha->ipha_protocol != IPPROTO_UDP));
16023 
16024 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16025 	if (mctl_present &&
16026 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16027 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16028 
16029 		/*
16030 		 * It's an IPsec accelerated packet.
16031 		 * Keep a pointer to the data attributes around until
16032 		 * we allocate the ipsec_info_t.
16033 		 */
16034 		IPSECHW_DEBUG(IPSECHW_PKT,
16035 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16036 		hada_mp = first_mp;
16037 		hada_mp->b_cont = NULL;
16038 		/*
16039 		 * Since it is accelerated, it comes directly from
16040 		 * the ill and the data attributes is followed by
16041 		 * the packet data.
16042 		 */
16043 		ASSERT(mp->b_datap->db_type != M_CTL);
16044 		first_mp = mp;
16045 		mctl_present = B_FALSE;
16046 	}
16047 
16048 	/*
16049 	 * IF M_CTL is not present, then ipsec_in_is_secure
16050 	 * should return B_TRUE. There is a case where loopback
16051 	 * packets has an M_CTL in the front with all the
16052 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16053 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16054 	 * packets never comes here, it is safe to ASSERT the
16055 	 * following.
16056 	 */
16057 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16058 
16059 
16060 	/* u1 is # words of IP options */
16061 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16062 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16063 
16064 	if (u1) {
16065 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16066 			if (hada_mp != NULL)
16067 				freemsg(hada_mp);
16068 			return;
16069 		}
16070 	} else {
16071 		/* Check the IP header checksum.  */
16072 #define	uph	((uint16_t *)ipha)
16073 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16074 		    uph[6] + uph[7] + uph[8] + uph[9];
16075 #undef  uph
16076 		/* finish doing IP checksum */
16077 		sum = (sum & 0xFFFF) + (sum >> 16);
16078 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16079 		/*
16080 		 * Don't verify header checksum if this packet is coming
16081 		 * back from AH/ESP as we already did it.
16082 		 */
16083 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16084 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16085 			goto drop_pkt;
16086 		}
16087 	}
16088 
16089 	/*
16090 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16091 	 * might be called more than once for secure packets, count only
16092 	 * the first time.
16093 	 */
16094 	if (!mctl_present) {
16095 		UPDATE_IB_PKT_COUNT(ire);
16096 		ire->ire_last_used_time = lbolt;
16097 	}
16098 
16099 	/* Check for fragmentation offset. */
16100 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16101 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16102 	if (u1) {
16103 		/*
16104 		 * We re-assemble fragments before we do the AH/ESP
16105 		 * processing. Thus, M_CTL should not be present
16106 		 * while we are re-assembling.
16107 		 */
16108 		ASSERT(!mctl_present);
16109 		ASSERT(first_mp == mp);
16110 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16111 			return;
16112 		}
16113 		/*
16114 		 * Make sure that first_mp points back to mp as
16115 		 * the mp we came in with could have changed in
16116 		 * ip_rput_fragment().
16117 		 */
16118 		ipha = (ipha_t *)mp->b_rptr;
16119 		first_mp = mp;
16120 	}
16121 
16122 	/*
16123 	 * Clear hardware checksumming flag as it is currently only
16124 	 * used by TCP and UDP.
16125 	 */
16126 	DB_CKSUMFLAGS(mp) = 0;
16127 
16128 	/* Now we have a complete datagram, destined for this machine. */
16129 	u1 = IPH_HDR_LENGTH(ipha);
16130 	switch (ipha->ipha_protocol) {
16131 	case IPPROTO_ICMP: {
16132 		ire_t		*ire_zone;
16133 		ilm_t		*ilm;
16134 		mblk_t		*mp1;
16135 		zoneid_t	last_zoneid;
16136 
16137 		if (CLASSD(ipha->ipha_dst) &&
16138 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
16139 			ASSERT(ire->ire_type == IRE_BROADCAST);
16140 			/*
16141 			 * In the multicast case, applications may have joined
16142 			 * the group from different zones, so we need to deliver
16143 			 * the packet to each of them. Loop through the
16144 			 * multicast memberships structures (ilm) on the receive
16145 			 * ill and send a copy of the packet up each matching
16146 			 * one. However, we don't do this for multicasts sent on
16147 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16148 			 * they must stay in the sender's zone.
16149 			 *
16150 			 * ilm_add_v6() ensures that ilms in the same zone are
16151 			 * contiguous in the ill_ilm list. We use this property
16152 			 * to avoid sending duplicates needed when two
16153 			 * applications in the same zone join the same group on
16154 			 * different logical interfaces: we ignore the ilm if
16155 			 * its zoneid is the same as the last matching one.
16156 			 * In addition, the sending of the packet for
16157 			 * ire_zoneid is delayed until all of the other ilms
16158 			 * have been exhausted.
16159 			 */
16160 			last_zoneid = -1;
16161 			ILM_WALKER_HOLD(recv_ill);
16162 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16163 			    ilm = ilm->ilm_next) {
16164 				if ((ilm->ilm_flags & ILM_DELETED) ||
16165 				    ipha->ipha_dst != ilm->ilm_addr ||
16166 				    ilm->ilm_zoneid == last_zoneid ||
16167 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16168 				    ilm->ilm_zoneid == ALL_ZONES ||
16169 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
16170 					continue;
16171 				mp1 = ip_copymsg(first_mp);
16172 				if (mp1 == NULL)
16173 					continue;
16174 				icmp_inbound(q, mp1, B_TRUE, ill,
16175 				    0, sum, mctl_present, B_TRUE,
16176 				    recv_ill, ilm->ilm_zoneid);
16177 				last_zoneid = ilm->ilm_zoneid;
16178 			}
16179 			ILM_WALKER_RELE(recv_ill);
16180 		} else if (ire->ire_type == IRE_BROADCAST) {
16181 			/*
16182 			 * In the broadcast case, there may be many zones
16183 			 * which need a copy of the packet delivered to them.
16184 			 * There is one IRE_BROADCAST per broadcast address
16185 			 * and per zone; we walk those using a helper function.
16186 			 * In addition, the sending of the packet for ire is
16187 			 * delayed until all of the other ires have been
16188 			 * processed.
16189 			 */
16190 			IRB_REFHOLD(ire->ire_bucket);
16191 			ire_zone = NULL;
16192 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
16193 			    ire)) != NULL) {
16194 				mp1 = ip_copymsg(first_mp);
16195 				if (mp1 == NULL)
16196 					continue;
16197 
16198 				UPDATE_IB_PKT_COUNT(ire_zone);
16199 				ire_zone->ire_last_used_time = lbolt;
16200 				icmp_inbound(q, mp1, B_TRUE, ill,
16201 				    0, sum, mctl_present, B_TRUE,
16202 				    recv_ill, ire_zone->ire_zoneid);
16203 			}
16204 			IRB_REFRELE(ire->ire_bucket);
16205 		}
16206 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
16207 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
16208 		    ire->ire_zoneid);
16209 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16210 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
16211 		return;
16212 	}
16213 	case IPPROTO_IGMP:
16214 		/*
16215 		 * If we are not willing to accept IGMP packets in clear,
16216 		 * then check with global policy.
16217 		 */
16218 		if (igmp_accept_clear_messages == 0) {
16219 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16220 			    ipha, NULL, mctl_present);
16221 			if (first_mp == NULL)
16222 				return;
16223 		}
16224 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16225 			freemsg(first_mp);
16226 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
16227 			BUMP_MIB(&ip_mib, ipInDiscards);
16228 			return;
16229 		}
16230 		if (igmp_input(q, mp, ill)) {
16231 			/* Bad packet - discarded by igmp_input */
16232 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16233 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
16234 			if (mctl_present)
16235 				freeb(first_mp);
16236 			return;
16237 		}
16238 		/*
16239 		 * igmp_input() may have pulled up the message so ipha needs to
16240 		 * be reinitialized.
16241 		 */
16242 		ipha = (ipha_t *)mp->b_rptr;
16243 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16244 			/* No user-level listener for IGMP packets */
16245 			goto drop_pkt;
16246 		}
16247 		/* deliver to local raw users */
16248 		break;
16249 	case IPPROTO_PIM:
16250 		/*
16251 		 * If we are not willing to accept PIM packets in clear,
16252 		 * then check with global policy.
16253 		 */
16254 		if (pim_accept_clear_messages == 0) {
16255 			first_mp = ipsec_check_global_policy(first_mp, NULL,
16256 			    ipha, NULL, mctl_present);
16257 			if (first_mp == NULL)
16258 				return;
16259 		}
16260 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
16261 			freemsg(first_mp);
16262 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
16263 			BUMP_MIB(&ip_mib, ipInDiscards);
16264 			return;
16265 		}
16266 		if (pim_input(q, mp) != 0) {
16267 			/* Bad packet - discarded by pim_input */
16268 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16269 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
16270 			if (mctl_present)
16271 				freeb(first_mp);
16272 			return;
16273 		}
16274 
16275 		/*
16276 		 * pim_input() may have pulled up the message so ipha needs to
16277 		 * be reinitialized.
16278 		 */
16279 		ipha = (ipha_t *)mp->b_rptr;
16280 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
16281 			/* No user-level listener for PIM packets */
16282 			goto drop_pkt;
16283 		}
16284 		/* deliver to local raw users */
16285 		break;
16286 	case IPPROTO_ENCAP:
16287 		/*
16288 		 * Handle self-encapsulated packets (IP-in-IP where
16289 		 * the inner addresses == the outer addresses).
16290 		 */
16291 		hdr_length = IPH_HDR_LENGTH(ipha);
16292 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
16293 		    mp->b_wptr) {
16294 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
16295 			    sizeof (ipha_t) - mp->b_rptr)) {
16296 				BUMP_MIB(&ip_mib, ipInDiscards);
16297 				freemsg(first_mp);
16298 				return;
16299 			}
16300 			ipha = (ipha_t *)mp->b_rptr;
16301 		}
16302 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
16303 		/*
16304 		 * Check the sanity of the inner IP header.
16305 		 */
16306 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
16307 			BUMP_MIB(&ip_mib, ipInDiscards);
16308 			freemsg(first_mp);
16309 			return;
16310 		}
16311 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
16312 			BUMP_MIB(&ip_mib, ipInDiscards);
16313 			freemsg(first_mp);
16314 			return;
16315 		}
16316 		if (inner_ipha->ipha_src == ipha->ipha_src &&
16317 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
16318 			ipsec_in_t *ii;
16319 
16320 			/*
16321 			 * Self-encapsulated tunnel packet. Remove
16322 			 * the outer IP header and fanout again.
16323 			 * We also need to make sure that the inner
16324 			 * header is pulled up until options.
16325 			 */
16326 			mp->b_rptr = (uchar_t *)inner_ipha;
16327 			ipha = inner_ipha;
16328 			hdr_length = IPH_HDR_LENGTH(ipha);
16329 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
16330 				if (!pullupmsg(mp, (uchar_t *)ipha +
16331 				    + hdr_length - mp->b_rptr)) {
16332 					freemsg(first_mp);
16333 					return;
16334 				}
16335 				ipha = (ipha_t *)mp->b_rptr;
16336 			}
16337 			if (!mctl_present) {
16338 				ASSERT(first_mp == mp);
16339 				/*
16340 				 * This means that somebody is sending
16341 				 * Self-encapsualted packets without AH/ESP.
16342 				 * If AH/ESP was present, we would have already
16343 				 * allocated the first_mp.
16344 				 */
16345 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
16346 				    NULL) {
16347 					ip1dbg(("ip_proto_input: IPSEC_IN "
16348 					    "allocation failure.\n"));
16349 					BUMP_MIB(&ip_mib, ipInDiscards);
16350 					freemsg(mp);
16351 					return;
16352 				}
16353 				first_mp->b_cont = mp;
16354 			}
16355 			/*
16356 			 * We generally store the ill_index if we need to
16357 			 * do IPSEC processing as we lose the ill queue when
16358 			 * we come back. But in this case, we never should
16359 			 * have to store the ill_index here as it should have
16360 			 * been stored previously when we processed the
16361 			 * AH/ESP header in this routine or for non-ipsec
16362 			 * cases, we still have the queue. But for some bad
16363 			 * packets from the wire, we can get to IPSEC after
16364 			 * this and we better store the index for that case.
16365 			 */
16366 			ill = (ill_t *)q->q_ptr;
16367 			ii = (ipsec_in_t *)first_mp->b_rptr;
16368 			ii->ipsec_in_ill_index =
16369 			    ill->ill_phyint->phyint_ifindex;
16370 			ii->ipsec_in_rill_index =
16371 			    recv_ill->ill_phyint->phyint_ifindex;
16372 			if (ii->ipsec_in_decaps) {
16373 				/*
16374 				 * This packet is self-encapsulated multiple
16375 				 * times. We don't want to recurse infinitely.
16376 				 * To keep it simple, drop the packet.
16377 				 */
16378 				BUMP_MIB(&ip_mib, ipInDiscards);
16379 				freemsg(first_mp);
16380 				return;
16381 			}
16382 			ii->ipsec_in_decaps = B_TRUE;
16383 			ip_proto_input(q, first_mp, ipha, ire, recv_ill);
16384 			return;
16385 		}
16386 		break;
16387 	case IPPROTO_AH:
16388 	case IPPROTO_ESP: {
16389 		/*
16390 		 * Fast path for AH/ESP. If this is the first time
16391 		 * we are sending a datagram to AH/ESP, allocate
16392 		 * a IPSEC_IN message and prepend it. Otherwise,
16393 		 * just fanout.
16394 		 */
16395 
16396 		int ipsec_rc;
16397 		ipsec_in_t *ii;
16398 
16399 		IP_STAT(ipsec_proto_ahesp);
16400 		if (!mctl_present) {
16401 			ASSERT(first_mp == mp);
16402 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
16403 				ip1dbg(("ip_proto_input: IPSEC_IN "
16404 				    "allocation failure.\n"));
16405 				freemsg(hada_mp); /* okay ifnull */
16406 				BUMP_MIB(&ip_mib, ipInDiscards);
16407 				freemsg(mp);
16408 				return;
16409 			}
16410 			/*
16411 			 * Store the ill_index so that when we come back
16412 			 * from IPSEC we ride on the same queue.
16413 			 */
16414 			ill = (ill_t *)q->q_ptr;
16415 			ii = (ipsec_in_t *)first_mp->b_rptr;
16416 			ii->ipsec_in_ill_index =
16417 			    ill->ill_phyint->phyint_ifindex;
16418 			ii->ipsec_in_rill_index =
16419 			    recv_ill->ill_phyint->phyint_ifindex;
16420 			first_mp->b_cont = mp;
16421 			/*
16422 			 * Cache hardware acceleration info.
16423 			 */
16424 			if (hada_mp != NULL) {
16425 				IPSECHW_DEBUG(IPSECHW_PKT,
16426 				    ("ip_rput_local: caching data attr.\n"));
16427 				ii->ipsec_in_accelerated = B_TRUE;
16428 				ii->ipsec_in_da = hada_mp;
16429 				hada_mp = NULL;
16430 			}
16431 		} else {
16432 			ii = (ipsec_in_t *)first_mp->b_rptr;
16433 		}
16434 
16435 		if (!ipsec_loaded()) {
16436 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
16437 			    ire->ire_zoneid);
16438 			return;
16439 		}
16440 
16441 		/* select inbound SA and have IPsec process the pkt */
16442 		if (ipha->ipha_protocol == IPPROTO_ESP) {
16443 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
16444 			if (esph == NULL)
16445 				return;
16446 			ASSERT(ii->ipsec_in_esp_sa != NULL);
16447 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
16448 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
16449 			    first_mp, esph);
16450 		} else {
16451 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
16452 			if (ah == NULL)
16453 				return;
16454 			ASSERT(ii->ipsec_in_ah_sa != NULL);
16455 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
16456 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
16457 			    first_mp, ah);
16458 		}
16459 
16460 		switch (ipsec_rc) {
16461 		case IPSEC_STATUS_SUCCESS:
16462 			break;
16463 		case IPSEC_STATUS_FAILED:
16464 			BUMP_MIB(&ip_mib, ipInDiscards);
16465 			/* FALLTHRU */
16466 		case IPSEC_STATUS_PENDING:
16467 			return;
16468 		}
16469 		/* we're done with IPsec processing, send it up */
16470 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
16471 		return;
16472 	}
16473 	default:
16474 		break;
16475 	}
16476 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
16477 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
16478 		    ire->ire_zoneid));
16479 		goto drop_pkt;
16480 	}
16481 	/*
16482 	 * Handle protocols with which IP is less intimate.  There
16483 	 * can be more than one stream bound to a particular
16484 	 * protocol.  When this is the case, each one gets a copy
16485 	 * of any incoming packets.
16486 	 */
16487 	ip_fanout_proto(q, first_mp, ill, ipha,
16488 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
16489 	    B_TRUE, recv_ill, ire->ire_zoneid);
16490 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16491 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
16492 	return;
16493 
16494 drop_pkt:
16495 	freemsg(first_mp);
16496 	if (hada_mp != NULL)
16497 		freeb(hada_mp);
16498 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
16499 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
16500 #undef	rptr
16501 #undef  iphs
16502 
16503 }
16504 
16505 /*
16506  * Update any source route, record route or timestamp options.
16507  * Check that we are at end of strict source route.
16508  * The options have already been checked for sanity in ip_rput_options().
16509  */
16510 static boolean_t
16511 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
16512 {
16513 	ipoptp_t	opts;
16514 	uchar_t		*opt;
16515 	uint8_t		optval;
16516 	uint8_t		optlen;
16517 	ipaddr_t	dst;
16518 	uint32_t	ts;
16519 	ire_t		*dst_ire;
16520 	timestruc_t	now;
16521 
16522 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16523 
16524 	ip2dbg(("ip_rput_local_options\n"));
16525 
16526 	for (optval = ipoptp_first(&opts, ipha);
16527 	    optval != IPOPT_EOL;
16528 	    optval = ipoptp_next(&opts)) {
16529 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16530 		opt = opts.ipoptp_cur;
16531 		optlen = opts.ipoptp_len;
16532 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
16533 		    optval, optlen));
16534 		switch (optval) {
16535 			uint32_t off;
16536 		case IPOPT_SSRR:
16537 		case IPOPT_LSRR:
16538 			off = opt[IPOPT_OFFSET];
16539 			off--;
16540 			if (optlen < IP_ADDR_LEN ||
16541 			    off > optlen - IP_ADDR_LEN) {
16542 				/* End of source route */
16543 				ip1dbg(("ip_rput_local_options: end of SR\n"));
16544 				break;
16545 			}
16546 			/*
16547 			 * This will only happen if two consecutive entries
16548 			 * in the source route contains our address or if
16549 			 * it is a packet with a loose source route which
16550 			 * reaches us before consuming the whole source route
16551 			 */
16552 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
16553 			if (optval == IPOPT_SSRR) {
16554 				goto bad_src_route;
16555 			}
16556 			/*
16557 			 * Hack: instead of dropping the packet truncate the
16558 			 * source route to what has been used by filling the
16559 			 * rest with IPOPT_NOP.
16560 			 */
16561 			opt[IPOPT_OLEN] = (uint8_t)off;
16562 			while (off < optlen) {
16563 				opt[off++] = IPOPT_NOP;
16564 			}
16565 			break;
16566 		case IPOPT_RR:
16567 			off = opt[IPOPT_OFFSET];
16568 			off--;
16569 			if (optlen < IP_ADDR_LEN ||
16570 			    off > optlen - IP_ADDR_LEN) {
16571 				/* No more room - ignore */
16572 				ip1dbg((
16573 				    "ip_rput_local_options: end of RR\n"));
16574 				break;
16575 			}
16576 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16577 			    IP_ADDR_LEN);
16578 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16579 			break;
16580 		case IPOPT_TS:
16581 			/* Insert timestamp if there is romm */
16582 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16583 			case IPOPT_TS_TSONLY:
16584 				off = IPOPT_TS_TIMELEN;
16585 				break;
16586 			case IPOPT_TS_PRESPEC:
16587 			case IPOPT_TS_PRESPEC_RFC791:
16588 				/* Verify that the address matched */
16589 				off = opt[IPOPT_OFFSET] - 1;
16590 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16591 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16592 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16593 				if (dst_ire == NULL) {
16594 					/* Not for us */
16595 					break;
16596 				}
16597 				ire_refrele(dst_ire);
16598 				/* FALLTHRU */
16599 			case IPOPT_TS_TSANDADDR:
16600 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16601 				break;
16602 			default:
16603 				/*
16604 				 * ip_*put_options should have already
16605 				 * dropped this packet.
16606 				 */
16607 				cmn_err(CE_PANIC, "ip_rput_local_options: "
16608 				    "unknown IT - bug in ip_rput_options?\n");
16609 				return (B_TRUE);	/* Keep "lint" happy */
16610 			}
16611 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16612 				/* Increase overflow counter */
16613 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16614 				opt[IPOPT_POS_OV_FLG] =
16615 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16616 				    (off << 4));
16617 				break;
16618 			}
16619 			off = opt[IPOPT_OFFSET] - 1;
16620 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16621 			case IPOPT_TS_PRESPEC:
16622 			case IPOPT_TS_PRESPEC_RFC791:
16623 			case IPOPT_TS_TSANDADDR:
16624 				bcopy(&ire->ire_src_addr, (char *)opt + off,
16625 				    IP_ADDR_LEN);
16626 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16627 				/* FALLTHRU */
16628 			case IPOPT_TS_TSONLY:
16629 				off = opt[IPOPT_OFFSET] - 1;
16630 				/* Compute # of milliseconds since midnight */
16631 				gethrestime(&now);
16632 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16633 				    now.tv_nsec / (NANOSEC / MILLISEC);
16634 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16635 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16636 				break;
16637 			}
16638 			break;
16639 		}
16640 	}
16641 	return (B_TRUE);
16642 
16643 bad_src_route:
16644 	q = WR(q);
16645 	/* make sure we clear any indication of a hardware checksum */
16646 	DB_CKSUMFLAGS(mp) = 0;
16647 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16648 	return (B_FALSE);
16649 
16650 }
16651 
16652 /*
16653  * Process IP options in an inbound packet.  If an option affects the
16654  * effective destination address, return the next hop address via dstp.
16655  * Returns -1 if something fails in which case an ICMP error has been sent
16656  * and mp freed.
16657  */
16658 static int
16659 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
16660 {
16661 	ipoptp_t	opts;
16662 	uchar_t		*opt;
16663 	uint8_t		optval;
16664 	uint8_t		optlen;
16665 	ipaddr_t	dst;
16666 	intptr_t	code = 0;
16667 	ire_t		*ire = NULL;
16668 
16669 	ip2dbg(("ip_rput_options\n"));
16670 	dst = ipha->ipha_dst;
16671 	for (optval = ipoptp_first(&opts, ipha);
16672 	    optval != IPOPT_EOL;
16673 	    optval = ipoptp_next(&opts)) {
16674 		opt = opts.ipoptp_cur;
16675 		optlen = opts.ipoptp_len;
16676 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
16677 		    optval, optlen));
16678 		/*
16679 		 * Note: we need to verify the checksum before we
16680 		 * modify anything thus this routine only extracts the next
16681 		 * hop dst from any source route.
16682 		 */
16683 		switch (optval) {
16684 			uint32_t off;
16685 		case IPOPT_SSRR:
16686 		case IPOPT_LSRR:
16687 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16688 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16689 			if (ire == NULL) {
16690 				if (optval == IPOPT_SSRR) {
16691 					ip1dbg(("ip_rput_options: not next"
16692 					    " strict source route 0x%x\n",
16693 					    ntohl(dst)));
16694 					code = (char *)&ipha->ipha_dst -
16695 					    (char *)ipha;
16696 					goto param_prob; /* RouterReq's */
16697 				}
16698 				ip2dbg(("ip_rput_options: "
16699 				    "not next source route 0x%x\n",
16700 				    ntohl(dst)));
16701 				break;
16702 			}
16703 			ire_refrele(ire);
16704 
16705 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16706 				ip1dbg((
16707 				    "ip_rput_options: bad option offset\n"));
16708 				code = (char *)&opt[IPOPT_OLEN] -
16709 				    (char *)ipha;
16710 				goto param_prob;
16711 			}
16712 			off = opt[IPOPT_OFFSET];
16713 			off--;
16714 		redo_srr:
16715 			if (optlen < IP_ADDR_LEN ||
16716 			    off > optlen - IP_ADDR_LEN) {
16717 				/* End of source route */
16718 				ip1dbg(("ip_rput_options: end of SR\n"));
16719 				break;
16720 			}
16721 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16722 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
16723 			    ntohl(dst)));
16724 
16725 			/*
16726 			 * Check if our address is present more than
16727 			 * once as consecutive hops in source route.
16728 			 * XXX verify per-interface ip_forwarding
16729 			 * for source route?
16730 			 */
16731 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
16732 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
16733 
16734 			if (ire != NULL) {
16735 				ire_refrele(ire);
16736 				off += IP_ADDR_LEN;
16737 				goto redo_srr;
16738 			}
16739 
16740 			if (dst == htonl(INADDR_LOOPBACK)) {
16741 				ip1dbg(("ip_rput_options: loopback addr in "
16742 				    "source route!\n"));
16743 				goto bad_src_route;
16744 			}
16745 			/*
16746 			 * For strict: verify that dst is directly
16747 			 * reachable.
16748 			 */
16749 			if (optval == IPOPT_SSRR) {
16750 				ire = ire_ftable_lookup(dst, 0, 0,
16751 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
16752 				    MBLK_GETLABEL(mp),
16753 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
16754 				if (ire == NULL) {
16755 					ip1dbg(("ip_rput_options: SSRR not "
16756 					    "directly reachable: 0x%x\n",
16757 					    ntohl(dst)));
16758 					goto bad_src_route;
16759 				}
16760 				ire_refrele(ire);
16761 			}
16762 			/*
16763 			 * Defer update of the offset and the record route
16764 			 * until the packet is forwarded.
16765 			 */
16766 			break;
16767 		case IPOPT_RR:
16768 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16769 				ip1dbg((
16770 				    "ip_rput_options: bad option offset\n"));
16771 				code = (char *)&opt[IPOPT_OLEN] -
16772 				    (char *)ipha;
16773 				goto param_prob;
16774 			}
16775 			break;
16776 		case IPOPT_TS:
16777 			/*
16778 			 * Verify that length >= 5 and that there is either
16779 			 * room for another timestamp or that the overflow
16780 			 * counter is not maxed out.
16781 			 */
16782 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
16783 			if (optlen < IPOPT_MINLEN_IT) {
16784 				goto param_prob;
16785 			}
16786 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
16787 				ip1dbg((
16788 				    "ip_rput_options: bad option offset\n"));
16789 				code = (char *)&opt[IPOPT_OFFSET] -
16790 				    (char *)ipha;
16791 				goto param_prob;
16792 			}
16793 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16794 			case IPOPT_TS_TSONLY:
16795 				off = IPOPT_TS_TIMELEN;
16796 				break;
16797 			case IPOPT_TS_TSANDADDR:
16798 			case IPOPT_TS_PRESPEC:
16799 			case IPOPT_TS_PRESPEC_RFC791:
16800 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16801 				break;
16802 			default:
16803 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
16804 				    (char *)ipha;
16805 				goto param_prob;
16806 			}
16807 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
16808 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
16809 				/*
16810 				 * No room and the overflow counter is 15
16811 				 * already.
16812 				 */
16813 				goto param_prob;
16814 			}
16815 			break;
16816 		}
16817 	}
16818 
16819 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
16820 		*dstp = dst;
16821 		return (0);
16822 	}
16823 
16824 	ip1dbg(("ip_rput_options: error processing IP options."));
16825 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
16826 
16827 param_prob:
16828 	q = WR(q);
16829 	/* make sure we clear any indication of a hardware checksum */
16830 	DB_CKSUMFLAGS(mp) = 0;
16831 	icmp_param_problem(q, mp, (uint8_t)code);
16832 	return (-1);
16833 
16834 bad_src_route:
16835 	q = WR(q);
16836 	/* make sure we clear any indication of a hardware checksum */
16837 	DB_CKSUMFLAGS(mp) = 0;
16838 	icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED);
16839 	return (-1);
16840 }
16841 
16842 /*
16843  * IP & ICMP info in >=14 msg's ...
16844  *  - ip fixed part (mib2_ip_t)
16845  *  - icmp fixed part (mib2_icmp_t)
16846  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
16847  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
16848  *  - ipNetToMediaEntryTable (ip 22)	IPv4 IREs for on-link destinations
16849  *  - ipRouteAttributeTable (ip 102)	labeled routes
16850  *  - ip multicast membership (ip_member_t)
16851  *  - ip multicast source filtering (ip_grpsrc_t)
16852  *  - igmp fixed part (struct igmpstat)
16853  *  - multicast routing stats (struct mrtstat)
16854  *  - multicast routing vifs (array of struct vifctl)
16855  *  - multicast routing routes (array of struct mfcctl)
16856  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
16857  *					One per ill plus one generic
16858  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
16859  *					One per ill plus one generic
16860  *  - ipv6RouteEntry			all IPv6 IREs
16861  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
16862  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
16863  *  - ipv6AddrEntry			all IPv6 ipifs
16864  *  - ipv6 multicast membership (ipv6_member_t)
16865  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
16866  *
16867  * IP_ROUTE and IP_MEDIA are augmented in arp to include arp cache entries not
16868  * already present.
16869  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
16870  * already filled in by the caller.
16871  * Return value of 0 indicates that no messages were sent and caller
16872  * should free mpctl.
16873  */
16874 int
16875 ip_snmp_get(queue_t *q, mblk_t *mpctl)
16876 {
16877 
16878 	if (mpctl == NULL || mpctl->b_cont == NULL) {
16879 		return (0);
16880 	}
16881 
16882 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
16883 		return (1);
16884 	}
16885 
16886 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
16887 		return (1);
16888 	}
16889 
16890 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
16891 		return (1);
16892 	}
16893 
16894 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
16895 		return (1);
16896 	}
16897 
16898 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
16899 		return (1);
16900 	}
16901 
16902 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
16903 		return (1);
16904 	}
16905 
16906 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
16907 		return (1);
16908 	}
16909 
16910 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
16911 		return (1);
16912 	}
16913 
16914 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
16915 		return (1);
16916 	}
16917 
16918 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
16919 		return (1);
16920 	}
16921 
16922 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
16923 		return (1);
16924 	}
16925 
16926 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
16927 		return (1);
16928 	}
16929 
16930 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
16931 		return (1);
16932 	}
16933 
16934 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
16935 		return (1);
16936 	}
16937 
16938 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
16939 		return (1);
16940 	}
16941 
16942 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
16943 		return (1);
16944 	}
16945 
16946 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
16947 		return (1);
16948 	}
16949 	freemsg(mpctl);
16950 	return (1);
16951 }
16952 
16953 
16954 /* Get global IPv4 statistics */
16955 static mblk_t *
16956 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
16957 {
16958 	struct opthdr		*optp;
16959 	mblk_t			*mp2ctl;
16960 
16961 	/*
16962 	 * make a copy of the original message
16963 	 */
16964 	mp2ctl = copymsg(mpctl);
16965 
16966 	/* fixed length IP structure... */
16967 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16968 	optp->level = MIB2_IP;
16969 	optp->name = 0;
16970 	SET_MIB(ip_mib.ipForwarding,
16971 	    (WE_ARE_FORWARDING ? 1 : 2));
16972 	SET_MIB(ip_mib.ipDefaultTTL,
16973 	    (uint32_t)ip_def_ttl);
16974 	SET_MIB(ip_mib.ipReasmTimeout,
16975 	    ip_g_frag_timeout);
16976 	SET_MIB(ip_mib.ipAddrEntrySize,
16977 	    sizeof (mib2_ipAddrEntry_t));
16978 	SET_MIB(ip_mib.ipRouteEntrySize,
16979 	    sizeof (mib2_ipRouteEntry_t));
16980 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
16981 	    sizeof (mib2_ipNetToMediaEntry_t));
16982 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
16983 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
16984 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
16985 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
16986 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
16987 	    (int)sizeof (ip_mib))) {
16988 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
16989 		    (uint_t)sizeof (ip_mib)));
16990 	}
16991 
16992 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
16993 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
16994 	    (int)optp->level, (int)optp->name, (int)optp->len));
16995 	qreply(q, mpctl);
16996 	return (mp2ctl);
16997 }
16998 
16999 /* Global IPv4 ICMP statistics */
17000 static mblk_t *
17001 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17002 {
17003 	struct opthdr		*optp;
17004 	mblk_t			*mp2ctl;
17005 
17006 	/*
17007 	 * Make a copy of the original message
17008 	 */
17009 	mp2ctl = copymsg(mpctl);
17010 
17011 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17012 	optp->level = MIB2_ICMP;
17013 	optp->name = 0;
17014 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17015 	    (int)sizeof (icmp_mib))) {
17016 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17017 		    (uint_t)sizeof (icmp_mib)));
17018 	}
17019 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17020 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17021 	    (int)optp->level, (int)optp->name, (int)optp->len));
17022 	qreply(q, mpctl);
17023 	return (mp2ctl);
17024 }
17025 
17026 /* Global IPv4 IGMP statistics */
17027 static mblk_t *
17028 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17029 {
17030 	struct opthdr		*optp;
17031 	mblk_t			*mp2ctl;
17032 
17033 	/*
17034 	 * make a copy of the original message
17035 	 */
17036 	mp2ctl = copymsg(mpctl);
17037 
17038 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17039 	optp->level = EXPER_IGMP;
17040 	optp->name = 0;
17041 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17042 	    (int)sizeof (igmpstat))) {
17043 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17044 		    (uint_t)sizeof (igmpstat)));
17045 	}
17046 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17047 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17048 	    (int)optp->level, (int)optp->name, (int)optp->len));
17049 	qreply(q, mpctl);
17050 	return (mp2ctl);
17051 }
17052 
17053 /* Global IPv4 Multicast Routing statistics */
17054 static mblk_t *
17055 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17056 {
17057 	struct opthdr		*optp;
17058 	mblk_t			*mp2ctl;
17059 
17060 	/*
17061 	 * make a copy of the original message
17062 	 */
17063 	mp2ctl = copymsg(mpctl);
17064 
17065 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17066 	optp->level = EXPER_DVMRP;
17067 	optp->name = 0;
17068 	if (!ip_mroute_stats(mpctl->b_cont)) {
17069 		ip0dbg(("ip_mroute_stats: failed\n"));
17070 	}
17071 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17072 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17073 	    (int)optp->level, (int)optp->name, (int)optp->len));
17074 	qreply(q, mpctl);
17075 	return (mp2ctl);
17076 }
17077 
17078 /* IPv4 address information */
17079 static mblk_t *
17080 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17081 {
17082 	struct opthdr		*optp;
17083 	mblk_t			*mp2ctl;
17084 	mblk_t			*mp_tail = NULL;
17085 	ill_t			*ill;
17086 	ipif_t			*ipif;
17087 	uint_t			bitval;
17088 	mib2_ipAddrEntry_t	mae;
17089 	zoneid_t		zoneid;
17090 	ill_walk_context_t ctx;
17091 
17092 	/*
17093 	 * make a copy of the original message
17094 	 */
17095 	mp2ctl = copymsg(mpctl);
17096 
17097 	/* ipAddrEntryTable */
17098 
17099 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17100 	optp->level = MIB2_IP;
17101 	optp->name = MIB2_IP_ADDR;
17102 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17103 
17104 	rw_enter(&ill_g_lock, RW_READER);
17105 	ill = ILL_START_WALK_V4(&ctx);
17106 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17107 		for (ipif = ill->ill_ipif; ipif != NULL;
17108 		    ipif = ipif->ipif_next) {
17109 			if (ipif->ipif_zoneid != zoneid &&
17110 			    ipif->ipif_zoneid != ALL_ZONES)
17111 				continue;
17112 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17113 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17114 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17115 
17116 			(void) ipif_get_name(ipif,
17117 			    mae.ipAdEntIfIndex.o_bytes,
17118 			    OCTET_LENGTH);
17119 			mae.ipAdEntIfIndex.o_length =
17120 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
17121 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
17122 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
17123 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
17124 			mae.ipAdEntInfo.ae_subnet_len =
17125 			    ip_mask_to_plen(ipif->ipif_net_mask);
17126 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
17127 			for (bitval = 1;
17128 			    bitval &&
17129 			    !(bitval & ipif->ipif_brd_addr);
17130 			    bitval <<= 1)
17131 				noop;
17132 			mae.ipAdEntBcastAddr = bitval;
17133 			mae.ipAdEntReasmMaxSize = 65535;
17134 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
17135 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
17136 			mae.ipAdEntInfo.ae_broadcast_addr =
17137 			    ipif->ipif_brd_addr;
17138 			mae.ipAdEntInfo.ae_pp_dst_addr =
17139 			    ipif->ipif_pp_dst_addr;
17140 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
17141 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17142 
17143 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17144 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
17145 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
17146 				    "allocate %u bytes\n",
17147 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
17148 			}
17149 		}
17150 	}
17151 	rw_exit(&ill_g_lock);
17152 
17153 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17154 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
17155 	    (int)optp->level, (int)optp->name, (int)optp->len));
17156 	qreply(q, mpctl);
17157 	return (mp2ctl);
17158 }
17159 
17160 /* IPv6 address information */
17161 static mblk_t *
17162 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
17163 {
17164 	struct opthdr		*optp;
17165 	mblk_t			*mp2ctl;
17166 	mblk_t			*mp_tail = NULL;
17167 	ill_t			*ill;
17168 	ipif_t			*ipif;
17169 	mib2_ipv6AddrEntry_t	mae6;
17170 	zoneid_t		zoneid;
17171 	ill_walk_context_t	ctx;
17172 
17173 	/*
17174 	 * make a copy of the original message
17175 	 */
17176 	mp2ctl = copymsg(mpctl);
17177 
17178 	/* ipv6AddrEntryTable */
17179 
17180 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17181 	optp->level = MIB2_IP6;
17182 	optp->name = MIB2_IP6_ADDR;
17183 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17184 
17185 	rw_enter(&ill_g_lock, RW_READER);
17186 	ill = ILL_START_WALK_V6(&ctx);
17187 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17188 		for (ipif = ill->ill_ipif; ipif; ipif = ipif->ipif_next) {
17189 			if (ipif->ipif_zoneid != zoneid &&
17190 			    ipif->ipif_zoneid != ALL_ZONES)
17191 				continue;
17192 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
17193 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
17194 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
17195 
17196 			(void) ipif_get_name(ipif,
17197 			    mae6.ipv6AddrIfIndex.o_bytes,
17198 			    OCTET_LENGTH);
17199 			mae6.ipv6AddrIfIndex.o_length =
17200 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
17201 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
17202 			mae6.ipv6AddrPfxLength =
17203 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
17204 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
17205 			mae6.ipv6AddrInfo.ae_subnet_len =
17206 			    mae6.ipv6AddrPfxLength;
17207 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
17208 
17209 			/* Type: stateless(1), stateful(2), unknown(3) */
17210 			if (ipif->ipif_flags & IPIF_ADDRCONF)
17211 				mae6.ipv6AddrType = 1;
17212 			else
17213 				mae6.ipv6AddrType = 2;
17214 			/* Anycast: true(1), false(2) */
17215 			if (ipif->ipif_flags & IPIF_ANYCAST)
17216 				mae6.ipv6AddrAnycastFlag = 1;
17217 			else
17218 				mae6.ipv6AddrAnycastFlag = 2;
17219 
17220 			/*
17221 			 * Address status: preferred(1), deprecated(2),
17222 			 * invalid(3), inaccessible(4), unknown(5)
17223 			 */
17224 			if (ipif->ipif_flags & IPIF_NOLOCAL)
17225 				mae6.ipv6AddrStatus = 3;
17226 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
17227 				mae6.ipv6AddrStatus = 2;
17228 			else
17229 				mae6.ipv6AddrStatus = 1;
17230 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
17231 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
17232 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
17233 						ipif->ipif_v6pp_dst_addr;
17234 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
17235 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
17236 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17237 				(char *)&mae6,
17238 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
17239 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
17240 				    "allocate %u bytes\n",
17241 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
17242 			}
17243 		}
17244 	}
17245 	rw_exit(&ill_g_lock);
17246 
17247 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17248 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
17249 	    (int)optp->level, (int)optp->name, (int)optp->len));
17250 	qreply(q, mpctl);
17251 	return (mp2ctl);
17252 }
17253 
17254 /* IPv4 multicast group membership. */
17255 static mblk_t *
17256 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
17257 {
17258 	struct opthdr		*optp;
17259 	mblk_t			*mp2ctl;
17260 	ill_t			*ill;
17261 	ipif_t			*ipif;
17262 	ilm_t			*ilm;
17263 	ip_member_t		ipm;
17264 	mblk_t			*mp_tail = NULL;
17265 	ill_walk_context_t	ctx;
17266 	zoneid_t		zoneid;
17267 
17268 	/*
17269 	 * make a copy of the original message
17270 	 */
17271 	mp2ctl = copymsg(mpctl);
17272 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17273 
17274 	/* ipGroupMember table */
17275 	optp = (struct opthdr *)&mpctl->b_rptr[
17276 	    sizeof (struct T_optmgmt_ack)];
17277 	optp->level = MIB2_IP;
17278 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
17279 
17280 	rw_enter(&ill_g_lock, RW_READER);
17281 	ill = ILL_START_WALK_V4(&ctx);
17282 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17283 		ILM_WALKER_HOLD(ill);
17284 		for (ipif = ill->ill_ipif; ipif != NULL;
17285 		    ipif = ipif->ipif_next) {
17286 			if (ipif->ipif_zoneid != zoneid &&
17287 			    ipif->ipif_zoneid != ALL_ZONES)
17288 				continue;	/* not this zone */
17289 			(void) ipif_get_name(ipif,
17290 			    ipm.ipGroupMemberIfIndex.o_bytes,
17291 			    OCTET_LENGTH);
17292 			ipm.ipGroupMemberIfIndex.o_length =
17293 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
17294 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17295 				ASSERT(ilm->ilm_ipif != NULL);
17296 				ASSERT(ilm->ilm_ill == NULL);
17297 				if (ilm->ilm_ipif != ipif)
17298 					continue;
17299 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
17300 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
17301 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
17302 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17303 				    (char *)&ipm, (int)sizeof (ipm))) {
17304 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
17305 					    "failed to allocate %u bytes\n",
17306 						(uint_t)sizeof (ipm)));
17307 				}
17308 			}
17309 		}
17310 		ILM_WALKER_RELE(ill);
17311 	}
17312 	rw_exit(&ill_g_lock);
17313 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17314 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17315 	    (int)optp->level, (int)optp->name, (int)optp->len));
17316 	qreply(q, mpctl);
17317 	return (mp2ctl);
17318 }
17319 
17320 /* IPv6 multicast group membership. */
17321 static mblk_t *
17322 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
17323 {
17324 	struct opthdr		*optp;
17325 	mblk_t			*mp2ctl;
17326 	ill_t			*ill;
17327 	ilm_t			*ilm;
17328 	ipv6_member_t		ipm6;
17329 	mblk_t			*mp_tail = NULL;
17330 	ill_walk_context_t	ctx;
17331 	zoneid_t		zoneid;
17332 
17333 	/*
17334 	 * make a copy of the original message
17335 	 */
17336 	mp2ctl = copymsg(mpctl);
17337 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17338 
17339 	/* ip6GroupMember table */
17340 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17341 	optp->level = MIB2_IP6;
17342 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
17343 
17344 	rw_enter(&ill_g_lock, RW_READER);
17345 	ill = ILL_START_WALK_V6(&ctx);
17346 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17347 		ILM_WALKER_HOLD(ill);
17348 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
17349 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17350 			ASSERT(ilm->ilm_ipif == NULL);
17351 			ASSERT(ilm->ilm_ill != NULL);
17352 			if (ilm->ilm_zoneid != zoneid)
17353 				continue;	/* not this zone */
17354 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
17355 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
17356 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
17357 			if (!snmp_append_data2(mpctl->b_cont,
17358 			    &mp_tail,
17359 			    (char *)&ipm6, (int)sizeof (ipm6))) {
17360 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
17361 				    "failed to allocate %u bytes\n",
17362 				    (uint_t)sizeof (ipm6)));
17363 			}
17364 		}
17365 		ILM_WALKER_RELE(ill);
17366 	}
17367 	rw_exit(&ill_g_lock);
17368 
17369 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17370 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17371 	    (int)optp->level, (int)optp->name, (int)optp->len));
17372 	qreply(q, mpctl);
17373 	return (mp2ctl);
17374 }
17375 
17376 /* IP multicast filtered sources */
17377 static mblk_t *
17378 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
17379 {
17380 	struct opthdr		*optp;
17381 	mblk_t			*mp2ctl;
17382 	ill_t			*ill;
17383 	ipif_t			*ipif;
17384 	ilm_t			*ilm;
17385 	ip_grpsrc_t		ips;
17386 	mblk_t			*mp_tail = NULL;
17387 	ill_walk_context_t	ctx;
17388 	zoneid_t		zoneid;
17389 	int			i;
17390 	slist_t			*sl;
17391 
17392 	/*
17393 	 * make a copy of the original message
17394 	 */
17395 	mp2ctl = copymsg(mpctl);
17396 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17397 
17398 	/* ipGroupSource table */
17399 	optp = (struct opthdr *)&mpctl->b_rptr[
17400 	    sizeof (struct T_optmgmt_ack)];
17401 	optp->level = MIB2_IP;
17402 	optp->name = EXPER_IP_GROUP_SOURCES;
17403 
17404 	rw_enter(&ill_g_lock, RW_READER);
17405 	ill = ILL_START_WALK_V4(&ctx);
17406 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17407 		ILM_WALKER_HOLD(ill);
17408 		for (ipif = ill->ill_ipif; ipif != NULL;
17409 		    ipif = ipif->ipif_next) {
17410 			if (ipif->ipif_zoneid != zoneid)
17411 				continue;	/* not this zone */
17412 			(void) ipif_get_name(ipif,
17413 			    ips.ipGroupSourceIfIndex.o_bytes,
17414 			    OCTET_LENGTH);
17415 			ips.ipGroupSourceIfIndex.o_length =
17416 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
17417 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17418 				ASSERT(ilm->ilm_ipif != NULL);
17419 				ASSERT(ilm->ilm_ill == NULL);
17420 				sl = ilm->ilm_filter;
17421 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
17422 					continue;
17423 				ips.ipGroupSourceGroup = ilm->ilm_addr;
17424 				for (i = 0; i < sl->sl_numsrc; i++) {
17425 					if (!IN6_IS_ADDR_V4MAPPED(
17426 					    &sl->sl_addr[i]))
17427 						continue;
17428 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
17429 					    ips.ipGroupSourceAddress);
17430 					if (snmp_append_data2(mpctl->b_cont,
17431 					    &mp_tail, (char *)&ips,
17432 					    (int)sizeof (ips)) == 0) {
17433 						ip1dbg(("ip_snmp_get_mib2_"
17434 						    "ip_group_src: failed to "
17435 						    "allocate %u bytes\n",
17436 						    (uint_t)sizeof (ips)));
17437 					}
17438 				}
17439 			}
17440 		}
17441 		ILM_WALKER_RELE(ill);
17442 	}
17443 	rw_exit(&ill_g_lock);
17444 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17445 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17446 	    (int)optp->level, (int)optp->name, (int)optp->len));
17447 	qreply(q, mpctl);
17448 	return (mp2ctl);
17449 }
17450 
17451 /* IPv6 multicast filtered sources. */
17452 static mblk_t *
17453 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
17454 {
17455 	struct opthdr		*optp;
17456 	mblk_t			*mp2ctl;
17457 	ill_t			*ill;
17458 	ilm_t			*ilm;
17459 	ipv6_grpsrc_t		ips6;
17460 	mblk_t			*mp_tail = NULL;
17461 	ill_walk_context_t	ctx;
17462 	zoneid_t		zoneid;
17463 	int			i;
17464 	slist_t			*sl;
17465 
17466 	/*
17467 	 * make a copy of the original message
17468 	 */
17469 	mp2ctl = copymsg(mpctl);
17470 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17471 
17472 	/* ip6GroupMember table */
17473 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17474 	optp->level = MIB2_IP6;
17475 	optp->name = EXPER_IP6_GROUP_SOURCES;
17476 
17477 	rw_enter(&ill_g_lock, RW_READER);
17478 	ill = ILL_START_WALK_V6(&ctx);
17479 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17480 		ILM_WALKER_HOLD(ill);
17481 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
17482 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
17483 			ASSERT(ilm->ilm_ipif == NULL);
17484 			ASSERT(ilm->ilm_ill != NULL);
17485 			sl = ilm->ilm_filter;
17486 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
17487 				continue;
17488 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
17489 			for (i = 0; i < sl->sl_numsrc; i++) {
17490 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
17491 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17492 				    (char *)&ips6, (int)sizeof (ips6))) {
17493 					ip1dbg(("ip_snmp_get_mib2_ip6_"
17494 					    "group_src: failed to allocate "
17495 					    "%u bytes\n",
17496 					    (uint_t)sizeof (ips6)));
17497 				}
17498 			}
17499 		}
17500 		ILM_WALKER_RELE(ill);
17501 	}
17502 	rw_exit(&ill_g_lock);
17503 
17504 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17505 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
17506 	    (int)optp->level, (int)optp->name, (int)optp->len));
17507 	qreply(q, mpctl);
17508 	return (mp2ctl);
17509 }
17510 
17511 /* Multicast routing virtual interface table. */
17512 static mblk_t *
17513 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
17514 {
17515 	struct opthdr		*optp;
17516 	mblk_t			*mp2ctl;
17517 
17518 	/*
17519 	 * make a copy of the original message
17520 	 */
17521 	mp2ctl = copymsg(mpctl);
17522 
17523 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17524 	optp->level = EXPER_DVMRP;
17525 	optp->name = EXPER_DVMRP_VIF;
17526 	if (!ip_mroute_vif(mpctl->b_cont)) {
17527 		ip0dbg(("ip_mroute_vif: failed\n"));
17528 	}
17529 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17530 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
17531 	    (int)optp->level, (int)optp->name, (int)optp->len));
17532 	qreply(q, mpctl);
17533 	return (mp2ctl);
17534 }
17535 
17536 /* Multicast routing table. */
17537 static mblk_t *
17538 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
17539 {
17540 	struct opthdr		*optp;
17541 	mblk_t			*mp2ctl;
17542 
17543 	/*
17544 	 * make a copy of the original message
17545 	 */
17546 	mp2ctl = copymsg(mpctl);
17547 
17548 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17549 	optp->level = EXPER_DVMRP;
17550 	optp->name = EXPER_DVMRP_MRT;
17551 	if (!ip_mroute_mrt(mpctl->b_cont)) {
17552 		ip0dbg(("ip_mroute_mrt: failed\n"));
17553 	}
17554 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17555 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
17556 	    (int)optp->level, (int)optp->name, (int)optp->len));
17557 	qreply(q, mpctl);
17558 	return (mp2ctl);
17559 }
17560 
17561 /*
17562  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
17563  * in one IRE walk.
17564  */
17565 static mblk_t *
17566 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
17567 {
17568 	struct opthdr	*optp;
17569 	mblk_t		*mp2ctl;	/* Returned */
17570 	mblk_t		*mp3ctl;	/* nettomedia */
17571 	mblk_t		*mp4ctl;	/* routeattrs */
17572 	iproutedata_t	ird;
17573 	zoneid_t	zoneid;
17574 
17575 	/*
17576 	 * make copies of the original message
17577 	 *	- mp2ctl is returned unchanged to the caller for his use
17578 	 *	- mpctl is sent upstream as ipRouteEntryTable
17579 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
17580 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
17581 	 */
17582 	mp2ctl = copymsg(mpctl);
17583 	mp3ctl = copymsg(mpctl);
17584 	mp4ctl = copymsg(mpctl);
17585 	if (mp3ctl == NULL || mp4ctl == NULL) {
17586 		freemsg(mp4ctl);
17587 		freemsg(mp3ctl);
17588 		freemsg(mp2ctl);
17589 		freemsg(mpctl);
17590 		return (NULL);
17591 	}
17592 
17593 	bzero(&ird, sizeof (ird));
17594 
17595 	ird.ird_route.lp_head = mpctl->b_cont;
17596 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17597 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17598 
17599 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17600 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
17601 	if (zoneid == GLOBAL_ZONEID) {
17602 		/*
17603 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
17604 		 * the sys_net_config privilege, it can only run in the global
17605 		 * zone, so we don't display these IREs in the other zones.
17606 		 */
17607 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
17608 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
17609 	}
17610 
17611 	/* ipRouteEntryTable in mpctl */
17612 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17613 	optp->level = MIB2_IP;
17614 	optp->name = MIB2_IP_ROUTE;
17615 	optp->len = msgdsize(ird.ird_route.lp_head);
17616 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17617 	    (int)optp->level, (int)optp->name, (int)optp->len));
17618 	qreply(q, mpctl);
17619 
17620 	/* ipNetToMediaEntryTable in mp3ctl */
17621 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17622 	optp->level = MIB2_IP;
17623 	optp->name = MIB2_IP_MEDIA;
17624 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17625 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17626 	    (int)optp->level, (int)optp->name, (int)optp->len));
17627 	qreply(q, mp3ctl);
17628 
17629 	/* ipRouteAttributeTable in mp4ctl */
17630 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17631 	optp->level = MIB2_IP;
17632 	optp->name = EXPER_IP_RTATTR;
17633 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17634 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
17635 	    (int)optp->level, (int)optp->name, (int)optp->len));
17636 	if (optp->len == 0)
17637 		freemsg(mp4ctl);
17638 	else
17639 		qreply(q, mp4ctl);
17640 
17641 	return (mp2ctl);
17642 }
17643 
17644 /*
17645  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
17646  * ipv6NetToMediaEntryTable in an NDP walk.
17647  */
17648 static mblk_t *
17649 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
17650 {
17651 	struct opthdr	*optp;
17652 	mblk_t		*mp2ctl;	/* Returned */
17653 	mblk_t		*mp3ctl;	/* nettomedia */
17654 	mblk_t		*mp4ctl;	/* routeattrs */
17655 	iproutedata_t	ird;
17656 	zoneid_t	zoneid;
17657 
17658 	/*
17659 	 * make copies of the original message
17660 	 *	- mp2ctl is returned unchanged to the caller for his use
17661 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
17662 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
17663 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
17664 	 */
17665 	mp2ctl = copymsg(mpctl);
17666 	mp3ctl = copymsg(mpctl);
17667 	mp4ctl = copymsg(mpctl);
17668 	if (mp3ctl == NULL || mp4ctl == NULL) {
17669 		freemsg(mp4ctl);
17670 		freemsg(mp3ctl);
17671 		freemsg(mp2ctl);
17672 		freemsg(mpctl);
17673 		return (NULL);
17674 	}
17675 
17676 	bzero(&ird, sizeof (ird));
17677 
17678 	ird.ird_route.lp_head = mpctl->b_cont;
17679 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
17680 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
17681 
17682 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17683 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
17684 
17685 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17686 	optp->level = MIB2_IP6;
17687 	optp->name = MIB2_IP6_ROUTE;
17688 	optp->len = msgdsize(ird.ird_route.lp_head);
17689 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17690 	    (int)optp->level, (int)optp->name, (int)optp->len));
17691 	qreply(q, mpctl);
17692 
17693 	/* ipv6NetToMediaEntryTable in mp3ctl */
17694 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
17695 
17696 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17697 	optp->level = MIB2_IP6;
17698 	optp->name = MIB2_IP6_MEDIA;
17699 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
17700 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17701 	    (int)optp->level, (int)optp->name, (int)optp->len));
17702 	qreply(q, mp3ctl);
17703 
17704 	/* ipv6RouteAttributeTable in mp4ctl */
17705 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17706 	optp->level = MIB2_IP6;
17707 	optp->name = EXPER_IP_RTATTR;
17708 	optp->len = msgdsize(ird.ird_attrs.lp_head);
17709 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
17710 	    (int)optp->level, (int)optp->name, (int)optp->len));
17711 	if (optp->len == 0)
17712 		freemsg(mp4ctl);
17713 	else
17714 		qreply(q, mp4ctl);
17715 
17716 	return (mp2ctl);
17717 }
17718 
17719 /*
17720  * ICMPv6 mib: One per ill
17721  */
17722 static mblk_t *
17723 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
17724 {
17725 	struct opthdr		*optp;
17726 	mblk_t			*mp2ctl;
17727 	ill_t			*ill;
17728 	ill_walk_context_t	ctx;
17729 	mblk_t			*mp_tail = NULL;
17730 
17731 	/*
17732 	 * Make a copy of the original message
17733 	 */
17734 	mp2ctl = copymsg(mpctl);
17735 
17736 	/* fixed length IPv6 structure ... */
17737 
17738 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17739 	optp->level = MIB2_IP6;
17740 	optp->name = 0;
17741 	/* Include "unknown interface" ip6_mib */
17742 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
17743 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
17744 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
17745 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
17746 	    sizeof (mib2_ipv6IfStatsEntry_t));
17747 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
17748 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
17749 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
17750 	    sizeof (mib2_ipv6NetToMediaEntry_t));
17751 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
17752 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
17753 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
17754 	    (int)sizeof (ip6_mib))) {
17755 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
17756 		    (uint_t)sizeof (ip6_mib)));
17757 	}
17758 
17759 	rw_enter(&ill_g_lock, RW_READER);
17760 	ill = ILL_START_WALK_V6(&ctx);
17761 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17762 		ill->ill_ip6_mib->ipv6IfIndex =
17763 		    ill->ill_phyint->phyint_ifindex;
17764 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
17765 		    ipv6_forward ? 1 : 2);
17766 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
17767 		    ill->ill_max_hops);
17768 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
17769 		    sizeof (mib2_ipv6IfStatsEntry_t));
17770 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
17771 		    sizeof (mib2_ipv6AddrEntry_t));
17772 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
17773 		    sizeof (mib2_ipv6RouteEntry_t));
17774 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
17775 		    sizeof (mib2_ipv6NetToMediaEntry_t));
17776 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
17777 		    sizeof (ipv6_member_t));
17778 
17779 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17780 		    (char *)ill->ill_ip6_mib,
17781 		    (int)sizeof (*ill->ill_ip6_mib))) {
17782 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
17783 				"%u bytes\n",
17784 				(uint_t)sizeof (*ill->ill_ip6_mib)));
17785 		}
17786 	}
17787 	rw_exit(&ill_g_lock);
17788 
17789 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17790 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
17791 	    (int)optp->level, (int)optp->name, (int)optp->len));
17792 	qreply(q, mpctl);
17793 	return (mp2ctl);
17794 }
17795 
17796 /*
17797  * ICMPv6 mib: One per ill
17798  */
17799 static mblk_t *
17800 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
17801 {
17802 	struct opthdr		*optp;
17803 	mblk_t			*mp2ctl;
17804 	ill_t			*ill;
17805 	ill_walk_context_t	ctx;
17806 	mblk_t			*mp_tail = NULL;
17807 	/*
17808 	 * Make a copy of the original message
17809 	 */
17810 	mp2ctl = copymsg(mpctl);
17811 
17812 	/* fixed length ICMPv6 structure ... */
17813 
17814 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17815 	optp->level = MIB2_ICMP6;
17816 	optp->name = 0;
17817 	/* Include "unknown interface" icmp6_mib */
17818 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
17819 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
17820 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
17821 	    (int)sizeof (icmp6_mib))) {
17822 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
17823 		    (uint_t)sizeof (icmp6_mib)));
17824 	}
17825 
17826 	rw_enter(&ill_g_lock, RW_READER);
17827 	ill = ILL_START_WALK_V6(&ctx);
17828 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17829 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
17830 		    ill->ill_phyint->phyint_ifindex;
17831 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
17832 		    sizeof (mib2_ipv6IfIcmpEntry_t);
17833 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17834 		    (char *)ill->ill_icmp6_mib,
17835 		    (int)sizeof (*ill->ill_icmp6_mib))) {
17836 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
17837 			    "%u bytes\n",
17838 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
17839 		}
17840 	}
17841 	rw_exit(&ill_g_lock);
17842 
17843 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17844 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
17845 	    (int)optp->level, (int)optp->name, (int)optp->len));
17846 	qreply(q, mpctl);
17847 	return (mp2ctl);
17848 }
17849 
17850 /*
17851  * ire_walk routine to create both ipRouteEntryTable and
17852  * ipNetToMediaEntryTable in one IRE walk
17853  */
17854 static void
17855 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
17856 {
17857 	ill_t				*ill;
17858 	ipif_t				*ipif;
17859 	mblk_t				*llmp;
17860 	dl_unitdata_req_t		*dlup;
17861 	mib2_ipRouteEntry_t		*re;
17862 	mib2_ipNetToMediaEntry_t	ntme;
17863 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
17864 	ipaddr_t			gw_addr;
17865 	tsol_ire_gw_secattr_t		*attrp;
17866 	tsol_gc_t			*gc = NULL;
17867 	tsol_gcgrp_t			*gcgrp = NULL;
17868 	uint_t				sacnt = 0;
17869 	int				i;
17870 
17871 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17872 
17873 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
17874 		return;
17875 
17876 	if ((attrp = ire->ire_gw_secattr) != NULL) {
17877 		mutex_enter(&attrp->igsa_lock);
17878 		if ((gc = attrp->igsa_gc) != NULL) {
17879 			gcgrp = gc->gc_grp;
17880 			ASSERT(gcgrp != NULL);
17881 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17882 			sacnt = 1;
17883 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
17884 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
17885 			gc = gcgrp->gcgrp_head;
17886 			sacnt = gcgrp->gcgrp_count;
17887 		}
17888 		mutex_exit(&attrp->igsa_lock);
17889 
17890 		/* do nothing if there's no gc to report */
17891 		if (gc == NULL) {
17892 			ASSERT(sacnt == 0);
17893 			if (gcgrp != NULL) {
17894 				/* we might as well drop the lock now */
17895 				rw_exit(&gcgrp->gcgrp_rwlock);
17896 				gcgrp = NULL;
17897 			}
17898 			attrp = NULL;
17899 		}
17900 
17901 		ASSERT(gc == NULL || (gcgrp != NULL &&
17902 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
17903 	}
17904 	ASSERT(sacnt == 0 || gc != NULL);
17905 
17906 	if (sacnt != 0 &&
17907 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
17908 		kmem_free(re, sizeof (*re));
17909 		rw_exit(&gcgrp->gcgrp_rwlock);
17910 		return;
17911 	}
17912 
17913 	/*
17914 	 * Return all IRE types for route table... let caller pick and choose
17915 	 */
17916 	re->ipRouteDest = ire->ire_addr;
17917 	ipif = ire->ire_ipif;
17918 	re->ipRouteIfIndex.o_length = 0;
17919 	if (ire->ire_type == IRE_CACHE) {
17920 		ill = (ill_t *)ire->ire_stq->q_ptr;
17921 		re->ipRouteIfIndex.o_length =
17922 		    ill->ill_name_length == 0 ? 0 :
17923 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
17924 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
17925 		    re->ipRouteIfIndex.o_length);
17926 	} else if (ipif != NULL) {
17927 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
17928 		    OCTET_LENGTH);
17929 		re->ipRouteIfIndex.o_length =
17930 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
17931 	}
17932 	re->ipRouteMetric1 = -1;
17933 	re->ipRouteMetric2 = -1;
17934 	re->ipRouteMetric3 = -1;
17935 	re->ipRouteMetric4 = -1;
17936 
17937 	gw_addr = ire->ire_gateway_addr;
17938 
17939 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
17940 		re->ipRouteNextHop = ire->ire_src_addr;
17941 	else
17942 		re->ipRouteNextHop = gw_addr;
17943 	/* indirect(4), direct(3), or invalid(2) */
17944 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
17945 		re->ipRouteType = 2;
17946 	else
17947 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
17948 	re->ipRouteProto = -1;
17949 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
17950 	re->ipRouteMask = ire->ire_mask;
17951 	re->ipRouteMetric5 = -1;
17952 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
17953 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
17954 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
17955 	llmp = ire->ire_dlureq_mp;
17956 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
17957 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
17958 	re->ipRouteInfo.re_ire_type	= ire->ire_type;
17959 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
17960 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
17961 	re->ipRouteInfo.re_flags	= ire->ire_flags;
17962 	re->ipRouteInfo.re_in_ill.o_length = 0;
17963 	if (ire->ire_in_ill != NULL) {
17964 		re->ipRouteInfo.re_in_ill.o_length =
17965 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
17966 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
17967 		bcopy(ire->ire_in_ill->ill_name,
17968 		    re->ipRouteInfo.re_in_ill.o_bytes,
17969 		    re->ipRouteInfo.re_in_ill.o_length);
17970 	}
17971 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
17972 
17973 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
17974 	    (char *)re, (int)sizeof (*re))) {
17975 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17976 		    (uint_t)sizeof (*re)));
17977 	}
17978 
17979 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
17980 		iaeptr->iae_routeidx = ird->ird_idx;
17981 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
17982 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
17983 	}
17984 
17985 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
17986 	    (char *)iae, sacnt * sizeof (*iae))) {
17987 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
17988 		    (unsigned)(sacnt * sizeof (*iae))));
17989 	}
17990 
17991 	if (ire->ire_type != IRE_CACHE || gw_addr != 0)
17992 		goto done;
17993 	/*
17994 	 * only IRE_CACHE entries that are for a directly connected subnet
17995 	 * get appended to net -> phys addr table
17996 	 * (others in arp)
17997 	 */
17998 	ntme.ipNetToMediaIfIndex.o_length = 0;
17999 	ill = ire_to_ill(ire);
18000 	ASSERT(ill != NULL);
18001 	ntme.ipNetToMediaIfIndex.o_length =
18002 	    ill->ill_name_length == 0 ? 0 :
18003 	    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18004 	bcopy(ill->ill_name, ntme.ipNetToMediaIfIndex.o_bytes,
18005 		    ntme.ipNetToMediaIfIndex.o_length);
18006 
18007 	ntme.ipNetToMediaPhysAddress.o_length = 0;
18008 	if (llmp) {
18009 		uchar_t *addr;
18010 
18011 		dlup = (dl_unitdata_req_t *)llmp->b_rptr;
18012 		/* Remove sap from  address */
18013 		if (ill->ill_sap_length < 0)
18014 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset;
18015 		else
18016 			addr = llmp->b_rptr + dlup->dl_dest_addr_offset +
18017 			    ill->ill_sap_length;
18018 
18019 		ntme.ipNetToMediaPhysAddress.o_length =
18020 		    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
18021 		bcopy(addr, ntme.ipNetToMediaPhysAddress.o_bytes,
18022 		    ntme.ipNetToMediaPhysAddress.o_length);
18023 	}
18024 	ntme.ipNetToMediaNetAddress = ire->ire_addr;
18025 	/* assume dynamic (may be changed in arp) */
18026 	ntme.ipNetToMediaType = 3;
18027 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (uint32_t);
18028 	bcopy(&ire->ire_mask, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
18029 	    ntme.ipNetToMediaInfo.ntm_mask.o_length);
18030 	ntme.ipNetToMediaInfo.ntm_flags = ACE_F_RESOLVED;
18031 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18032 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18033 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18034 		    (uint_t)sizeof (ntme)));
18035 	}
18036 done:
18037 	/* bump route index for next pass */
18038 	ird->ird_idx++;
18039 
18040 	kmem_free(re, sizeof (*re));
18041 	if (sacnt != 0)
18042 		kmem_free(iae, sacnt * sizeof (*iae));
18043 
18044 	if (gcgrp != NULL)
18045 		rw_exit(&gcgrp->gcgrp_rwlock);
18046 }
18047 
18048 /*
18049  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18050  */
18051 static void
18052 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18053 {
18054 	ill_t				*ill;
18055 	ipif_t				*ipif;
18056 	mib2_ipv6RouteEntry_t		*re;
18057 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18058 	in6_addr_t			gw_addr_v6;
18059 	tsol_ire_gw_secattr_t		*attrp;
18060 	tsol_gc_t			*gc = NULL;
18061 	tsol_gcgrp_t			*gcgrp = NULL;
18062 	uint_t				sacnt = 0;
18063 	int				i;
18064 
18065 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18066 
18067 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18068 		return;
18069 
18070 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18071 		mutex_enter(&attrp->igsa_lock);
18072 		if ((gc = attrp->igsa_gc) != NULL) {
18073 			gcgrp = gc->gc_grp;
18074 			ASSERT(gcgrp != NULL);
18075 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18076 			sacnt = 1;
18077 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18078 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18079 			gc = gcgrp->gcgrp_head;
18080 			sacnt = gcgrp->gcgrp_count;
18081 		}
18082 		mutex_exit(&attrp->igsa_lock);
18083 
18084 		/* do nothing if there's no gc to report */
18085 		if (gc == NULL) {
18086 			ASSERT(sacnt == 0);
18087 			if (gcgrp != NULL) {
18088 				/* we might as well drop the lock now */
18089 				rw_exit(&gcgrp->gcgrp_rwlock);
18090 				gcgrp = NULL;
18091 			}
18092 			attrp = NULL;
18093 		}
18094 
18095 		ASSERT(gc == NULL || (gcgrp != NULL &&
18096 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18097 	}
18098 	ASSERT(sacnt == 0 || gc != NULL);
18099 
18100 	if (sacnt != 0 &&
18101 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18102 		kmem_free(re, sizeof (*re));
18103 		rw_exit(&gcgrp->gcgrp_rwlock);
18104 		return;
18105 	}
18106 
18107 	/*
18108 	 * Return all IRE types for route table... let caller pick and choose
18109 	 */
18110 	re->ipv6RouteDest = ire->ire_addr_v6;
18111 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18112 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18113 	re->ipv6RouteIfIndex.o_length = 0;
18114 	ipif = ire->ire_ipif;
18115 	if (ire->ire_type == IRE_CACHE) {
18116 		ill = (ill_t *)ire->ire_stq->q_ptr;
18117 		re->ipv6RouteIfIndex.o_length =
18118 		    ill->ill_name_length == 0 ? 0 :
18119 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18120 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18121 		    re->ipv6RouteIfIndex.o_length);
18122 	} else if (ipif != NULL) {
18123 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18124 		    OCTET_LENGTH);
18125 		re->ipv6RouteIfIndex.o_length =
18126 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18127 	}
18128 
18129 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18130 
18131 	mutex_enter(&ire->ire_lock);
18132 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18133 	mutex_exit(&ire->ire_lock);
18134 
18135 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18136 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18137 	else
18138 		re->ipv6RouteNextHop = gw_addr_v6;
18139 
18140 	/* remote(4), local(3), or discard(2) */
18141 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18142 		re->ipv6RouteType = 2;
18143 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
18144 		re->ipv6RouteType = 3;
18145 	else
18146 		re->ipv6RouteType = 4;
18147 
18148 	re->ipv6RouteProtocol	= -1;
18149 	re->ipv6RoutePolicy	= 0;
18150 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
18151 	re->ipv6RouteNextHopRDI	= 0;
18152 	re->ipv6RouteWeight	= 0;
18153 	re->ipv6RouteMetric	= 0;
18154 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
18155 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
18156 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
18157 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
18158 	re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
18159 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18160 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18161 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
18162 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
18163 
18164 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18165 	    (char *)re, (int)sizeof (*re))) {
18166 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18167 		    (uint_t)sizeof (*re)));
18168 	}
18169 
18170 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18171 		iaeptr->iae_routeidx = ird->ird_idx;
18172 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18173 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18174 	}
18175 
18176 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18177 	    (char *)iae, sacnt * sizeof (*iae))) {
18178 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
18179 		    (unsigned)(sacnt * sizeof (*iae))));
18180 	}
18181 
18182 	/* bump route index for next pass */
18183 	ird->ird_idx++;
18184 
18185 	kmem_free(re, sizeof (*re));
18186 	if (sacnt != 0)
18187 		kmem_free(iae, sacnt * sizeof (*iae));
18188 
18189 	if (gcgrp != NULL)
18190 		rw_exit(&gcgrp->gcgrp_rwlock);
18191 }
18192 
18193 /*
18194  * ndp_walk routine to create ipv6NetToMediaEntryTable
18195  */
18196 static int
18197 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
18198 {
18199 	ill_t				*ill;
18200 	mib2_ipv6NetToMediaEntry_t	ntme;
18201 	dl_unitdata_req_t		*dl;
18202 
18203 	ill = nce->nce_ill;
18204 	ASSERT(ill->ill_isv6);
18205 
18206 	/*
18207 	 * Neighbor cache entry attached to IRE with on-link
18208 	 * destination.
18209 	 */
18210 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
18211 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
18212 	if ((ill->ill_flags & ILLF_XRESOLV) &&
18213 	    (nce->nce_res_mp != NULL)) {
18214 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
18215 		ntme.ipv6NetToMediaPhysAddress.o_length =
18216 		    dl->dl_dest_addr_length;
18217 	} else {
18218 		ntme.ipv6NetToMediaPhysAddress.o_length =
18219 		    ill->ill_phys_addr_length;
18220 	}
18221 	if (nce->nce_res_mp != NULL) {
18222 		bcopy((char *)nce->nce_res_mp->b_rptr +
18223 		    NCE_LL_ADDR_OFFSET(ill),
18224 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
18225 		    ntme.ipv6NetToMediaPhysAddress.o_length);
18226 	} else {
18227 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
18228 		    ill->ill_phys_addr_length);
18229 	}
18230 	/*
18231 	 * Note: Returns ND_* states. Should be:
18232 	 * reachable(1), stale(2), delay(3), probe(4),
18233 	 * invalid(5), unknown(6)
18234 	 */
18235 	ntme.ipv6NetToMediaState = nce->nce_state;
18236 	ntme.ipv6NetToMediaLastUpdated = 0;
18237 
18238 	/* other(1), dynamic(2), static(3), local(4) */
18239 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
18240 		ntme.ipv6NetToMediaType = 4;
18241 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
18242 		ntme.ipv6NetToMediaType = 1;
18243 	} else {
18244 		ntme.ipv6NetToMediaType = 2;
18245 	}
18246 
18247 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
18248 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
18249 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
18250 		    (uint_t)sizeof (ntme)));
18251 	}
18252 	return (0);
18253 }
18254 
18255 /*
18256  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
18257  */
18258 /* ARGSUSED */
18259 int
18260 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
18261 {
18262 	switch (level) {
18263 	case MIB2_IP:
18264 	case MIB2_ICMP:
18265 		switch (name) {
18266 		default:
18267 			break;
18268 		}
18269 		return (1);
18270 	default:
18271 		return (1);
18272 	}
18273 }
18274 
18275 /*
18276  * Called before the options are updated to check if this packet will
18277  * be source routed from here.
18278  * This routine assumes that the options are well formed i.e. that they
18279  * have already been checked.
18280  */
18281 static boolean_t
18282 ip_source_routed(ipha_t *ipha)
18283 {
18284 	ipoptp_t	opts;
18285 	uchar_t		*opt;
18286 	uint8_t		optval;
18287 	uint8_t		optlen;
18288 	ipaddr_t	dst;
18289 	ire_t		*ire;
18290 
18291 	if (IS_SIMPLE_IPH(ipha)) {
18292 		ip2dbg(("not source routed\n"));
18293 		return (B_FALSE);
18294 	}
18295 	dst = ipha->ipha_dst;
18296 	for (optval = ipoptp_first(&opts, ipha);
18297 	    optval != IPOPT_EOL;
18298 	    optval = ipoptp_next(&opts)) {
18299 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18300 		opt = opts.ipoptp_cur;
18301 		optlen = opts.ipoptp_len;
18302 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
18303 		    optval, optlen));
18304 		switch (optval) {
18305 			uint32_t off;
18306 		case IPOPT_SSRR:
18307 		case IPOPT_LSRR:
18308 			/*
18309 			 * If dst is one of our addresses and there are some
18310 			 * entries left in the source route return (true).
18311 			 */
18312 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18313 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
18314 			if (ire == NULL) {
18315 				ip2dbg(("ip_source_routed: not next"
18316 				    " source route 0x%x\n",
18317 				    ntohl(dst)));
18318 				return (B_FALSE);
18319 			}
18320 			ire_refrele(ire);
18321 			off = opt[IPOPT_OFFSET];
18322 			off--;
18323 			if (optlen < IP_ADDR_LEN ||
18324 			    off > optlen - IP_ADDR_LEN) {
18325 				/* End of source route */
18326 				ip1dbg(("ip_source_routed: end of SR\n"));
18327 				return (B_FALSE);
18328 			}
18329 			return (B_TRUE);
18330 		}
18331 	}
18332 	ip2dbg(("not source routed\n"));
18333 	return (B_FALSE);
18334 }
18335 
18336 /*
18337  * Check if the packet contains any source route.
18338  */
18339 static boolean_t
18340 ip_source_route_included(ipha_t *ipha)
18341 {
18342 	ipoptp_t	opts;
18343 	uint8_t		optval;
18344 
18345 	if (IS_SIMPLE_IPH(ipha))
18346 		return (B_FALSE);
18347 	for (optval = ipoptp_first(&opts, ipha);
18348 	    optval != IPOPT_EOL;
18349 	    optval = ipoptp_next(&opts)) {
18350 		switch (optval) {
18351 		case IPOPT_SSRR:
18352 		case IPOPT_LSRR:
18353 			return (B_TRUE);
18354 		}
18355 	}
18356 	return (B_FALSE);
18357 }
18358 
18359 /*
18360  * Called when the IRE expiration timer fires.
18361  */
18362 /* ARGSUSED */
18363 void
18364 ip_trash_timer_expire(void *args)
18365 {
18366 	int	flush_flag = 0;
18367 
18368 	/*
18369 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
18370 	 * This lock makes sure that a new invocation of this function
18371 	 * that occurs due to an almost immediate timer firing will not
18372 	 * progress beyond this point until the current invocation is done
18373 	 */
18374 	mutex_enter(&ip_trash_timer_lock);
18375 	ip_ire_expire_id = 0;
18376 	mutex_exit(&ip_trash_timer_lock);
18377 
18378 	/* Periodic timer */
18379 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
18380 		/*
18381 		 * Remove all IRE_CACHE entries since they might
18382 		 * contain arp information.
18383 		 */
18384 		flush_flag |= FLUSH_ARP_TIME;
18385 		ip_ire_arp_time_elapsed = 0;
18386 		IP_STAT(ip_ire_arp_timer_expired);
18387 	}
18388 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
18389 		/* Remove all redirects */
18390 		flush_flag |= FLUSH_REDIRECT_TIME;
18391 		ip_ire_rd_time_elapsed = 0;
18392 		IP_STAT(ip_ire_redirect_timer_expired);
18393 	}
18394 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
18395 		/* Increase path mtu */
18396 		flush_flag |= FLUSH_MTU_TIME;
18397 		ip_ire_pmtu_time_elapsed = 0;
18398 		IP_STAT(ip_ire_pmtu_timer_expired);
18399 	}
18400 	if (flush_flag != 0) {
18401 		/* Walk all IPv4 IRE's and update them */
18402 		ire_walk_v4(ire_expire, (char *)(uintptr_t)flush_flag,
18403 		    ALL_ZONES);
18404 	}
18405 	if (flush_flag & FLUSH_MTU_TIME) {
18406 		/*
18407 		 * Walk all IPv6 IRE's and update them
18408 		 * Note that ARP and redirect timers are not
18409 		 * needed since NUD handles stale entries.
18410 		 */
18411 		flush_flag = FLUSH_MTU_TIME;
18412 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
18413 		    ALL_ZONES);
18414 	}
18415 
18416 	ip_ire_arp_time_elapsed += ip_timer_interval;
18417 	ip_ire_rd_time_elapsed += ip_timer_interval;
18418 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
18419 
18420 	/*
18421 	 * Hold the lock to serialize timeout calls and prevent
18422 	 * stale values in ip_ire_expire_id. Otherwise it is possible
18423 	 * for the timer to fire and a new invocation of this function
18424 	 * to start before the return value of timeout has been stored
18425 	 * in ip_ire_expire_id by the current invocation.
18426 	 */
18427 	mutex_enter(&ip_trash_timer_lock);
18428 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
18429 	    MSEC_TO_TICK(ip_timer_interval));
18430 	mutex_exit(&ip_trash_timer_lock);
18431 }
18432 
18433 /*
18434  * Called by the memory allocator subsystem directly, when the system
18435  * is running low on memory.
18436  */
18437 /* ARGSUSED */
18438 void
18439 ip_trash_ire_reclaim(void *args)
18440 {
18441 	ire_cache_count_t icc;
18442 	ire_cache_reclaim_t icr;
18443 	ncc_cache_count_t ncc;
18444 	nce_cache_reclaim_t ncr;
18445 	uint_t delete_cnt;
18446 	/*
18447 	 * Memory reclaim call back.
18448 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
18449 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
18450 	 * entries, determine what fraction to free for
18451 	 * each category of IRE_CACHE entries giving absolute priority
18452 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
18453 	 * entry will be freed unless all offlink entries are freed).
18454 	 */
18455 	icc.icc_total = 0;
18456 	icc.icc_unused = 0;
18457 	icc.icc_offlink = 0;
18458 	icc.icc_pmtu = 0;
18459 	icc.icc_onlink = 0;
18460 	ire_walk(ire_cache_count, (char *)&icc);
18461 
18462 	/*
18463 	 * Free NCEs for IPv6 like the onlink ires.
18464 	 */
18465 	ncc.ncc_total = 0;
18466 	ncc.ncc_host = 0;
18467 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
18468 
18469 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
18470 	    icc.icc_pmtu + icc.icc_onlink);
18471 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
18472 	IP_STAT(ip_trash_ire_reclaim_calls);
18473 	if (delete_cnt == 0)
18474 		return;
18475 	IP_STAT(ip_trash_ire_reclaim_success);
18476 	/* Always delete all unused offlink entries */
18477 	icr.icr_unused = 1;
18478 	if (delete_cnt <= icc.icc_unused) {
18479 		/*
18480 		 * Only need to free unused entries.  In other words,
18481 		 * there are enough unused entries to free to meet our
18482 		 * target number of freed ire cache entries.
18483 		 */
18484 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
18485 		ncr.ncr_host = 0;
18486 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
18487 		/*
18488 		 * Only need to free unused entries, plus a fraction of offlink
18489 		 * entries.  It follows from the first if statement that
18490 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
18491 		 */
18492 		delete_cnt -= icc.icc_unused;
18493 		/* Round up # deleted by truncating fraction */
18494 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
18495 		icr.icr_pmtu = icr.icr_onlink = 0;
18496 		ncr.ncr_host = 0;
18497 	} else if (delete_cnt <=
18498 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
18499 		/*
18500 		 * Free all unused and offlink entries, plus a fraction of
18501 		 * pmtu entries.  It follows from the previous if statement
18502 		 * that icc_pmtu is non-zero, and that
18503 		 * delete_cnt != icc_unused + icc_offlink.
18504 		 */
18505 		icr.icr_offlink = 1;
18506 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
18507 		/* Round up # deleted by truncating fraction */
18508 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
18509 		icr.icr_onlink = 0;
18510 		ncr.ncr_host = 0;
18511 	} else {
18512 		/*
18513 		 * Free all unused, offlink, and pmtu entries, plus a fraction
18514 		 * of onlink entries.  If we're here, then we know that
18515 		 * icc_onlink is non-zero, and that
18516 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
18517 		 */
18518 		icr.icr_offlink = icr.icr_pmtu = 1;
18519 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
18520 		    icc.icc_pmtu;
18521 		/* Round up # deleted by truncating fraction */
18522 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
18523 		/* Using the same delete fraction as for onlink IREs */
18524 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
18525 	}
18526 #ifdef DEBUG
18527 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
18528 	    "fractions %d/%d/%d/%d\n",
18529 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
18530 	    icc.icc_unused, icc.icc_offlink,
18531 	    icc.icc_pmtu, icc.icc_onlink,
18532 	    icr.icr_unused, icr.icr_offlink,
18533 	    icr.icr_pmtu, icr.icr_onlink));
18534 #endif
18535 	ire_walk(ire_cache_reclaim, (char *)&icr);
18536 	if (ncr.ncr_host != 0)
18537 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
18538 		    (uchar_t *)&ncr);
18539 #ifdef DEBUG
18540 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
18541 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
18542 	ire_walk(ire_cache_count, (char *)&icc);
18543 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
18544 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
18545 	    icc.icc_pmtu, icc.icc_onlink));
18546 #endif
18547 }
18548 
18549 /*
18550  * ip_unbind is called when a copy of an unbind request is received from the
18551  * upper level protocol.  We remove this conn from any fanout hash list it is
18552  * on, and zero out the bind information.  No reply is expected up above.
18553  */
18554 mblk_t *
18555 ip_unbind(queue_t *q, mblk_t *mp)
18556 {
18557 	conn_t	*connp = Q_TO_CONN(q);
18558 
18559 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
18560 
18561 	if (is_system_labeled() && connp->conn_anon_port) {
18562 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
18563 		    connp->conn_mlp_type, connp->conn_ulp,
18564 		    ntohs(connp->conn_lport), B_FALSE);
18565 		connp->conn_anon_port = 0;
18566 	}
18567 	connp->conn_mlp_type = mlptSingle;
18568 
18569 	ipcl_hash_remove(connp);
18570 
18571 	ASSERT(mp->b_cont == NULL);
18572 	/*
18573 	 * Convert mp into a T_OK_ACK
18574 	 */
18575 	mp = mi_tpi_ok_ack_alloc(mp);
18576 
18577 	/*
18578 	 * should not happen in practice... T_OK_ACK is smaller than the
18579 	 * original message.
18580 	 */
18581 	if (mp == NULL)
18582 		return (NULL);
18583 
18584 	/*
18585 	 * Don't bzero the ports if its TCP since TCP still needs the
18586 	 * lport to remove it from its own bind hash. TCP will do the
18587 	 * cleanup.
18588 	 */
18589 	if (!IPCL_IS_TCP(connp))
18590 		bzero(&connp->u_port, sizeof (connp->u_port));
18591 
18592 	return (mp);
18593 }
18594 
18595 /*
18596  * Write side put procedure.  Outbound data, IOCTLs, responses from
18597  * resolvers, etc, come down through here.
18598  */
18599 void
18600 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
18601 {
18602 	conn_t		*connp = NULL;
18603 	queue_t		*q = (queue_t *)arg2;
18604 	ipha_t		*ipha;
18605 #define	rptr	((uchar_t *)ipha)
18606 	ire_t		*ire = NULL;
18607 	ire_t		*sctp_ire = NULL;
18608 	uint32_t	v_hlen_tos_len;
18609 	ipaddr_t	dst;
18610 	mblk_t		*first_mp = NULL;
18611 	boolean_t	mctl_present;
18612 	ipsec_out_t	*io;
18613 	int		match_flags;
18614 	ill_t		*attach_ill = NULL;
18615 					/* Bind to IPIF_NOFAILOVER ill etc. */
18616 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
18617 	ipif_t		*dst_ipif;
18618 	boolean_t	multirt_need_resolve = B_FALSE;
18619 	mblk_t		*copy_mp = NULL;
18620 	int		err;
18621 	zoneid_t	zoneid;
18622 	int	adjust;
18623 	uint16_t iplen;
18624 	boolean_t	need_decref = B_FALSE;
18625 	boolean_t	ignore_dontroute = B_FALSE;
18626 	boolean_t	ignore_nexthop = B_FALSE;
18627 	boolean_t	ip_nexthop = B_FALSE;
18628 	ipaddr_t	nexthop_addr;
18629 
18630 #ifdef	_BIG_ENDIAN
18631 #define	V_HLEN	(v_hlen_tos_len >> 24)
18632 #else
18633 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
18634 #endif
18635 
18636 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
18637 	    "ip_wput_start: q %p", q);
18638 
18639 	/*
18640 	 * ip_wput fast path
18641 	 */
18642 
18643 	/* is packet from ARP ? */
18644 	if (q->q_next != NULL)
18645 		goto qnext;
18646 
18647 	connp = (conn_t *)arg;
18648 	zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
18649 
18650 	/* is queue flow controlled? */
18651 	if ((q->q_first != NULL || connp->conn_draining) &&
18652 	    (caller == IP_WPUT)) {
18653 		ASSERT(!need_decref);
18654 		(void) putq(q, mp);
18655 		return;
18656 	}
18657 
18658 	/* Multidata transmit? */
18659 	if (DB_TYPE(mp) == M_MULTIDATA) {
18660 		/*
18661 		 * We should never get here, since all Multidata messages
18662 		 * originating from tcp should have been directed over to
18663 		 * tcp_multisend() in the first place.
18664 		 */
18665 		BUMP_MIB(&ip_mib, ipOutDiscards);
18666 		freemsg(mp);
18667 		return;
18668 	} else if (DB_TYPE(mp) != M_DATA)
18669 		goto notdata;
18670 
18671 	if (mp->b_flag & MSGHASREF) {
18672 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
18673 		mp->b_flag &= ~MSGHASREF;
18674 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
18675 		need_decref = B_TRUE;
18676 	}
18677 	ipha = (ipha_t *)mp->b_rptr;
18678 
18679 	/* is IP header non-aligned or mblk smaller than basic IP header */
18680 #ifndef SAFETY_BEFORE_SPEED
18681 	if (!OK_32PTR(rptr) ||
18682 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
18683 		goto hdrtoosmall;
18684 #endif
18685 
18686 	ASSERT(OK_32PTR(ipha));
18687 
18688 	/*
18689 	 * This function assumes that mp points to an IPv4 packet.  If it's the
18690 	 * wrong version, we'll catch it again in ip_output_v6.
18691 	 *
18692 	 * Note that this is *only* locally-generated output here, and never
18693 	 * forwarded data, and that we need to deal only with transports that
18694 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
18695 	 * label.)
18696 	 */
18697 	if (is_system_labeled() &&
18698 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
18699 	    !connp->conn_ulp_labeled) {
18700 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
18701 		    connp->conn_mac_exempt);
18702 		ipha = (ipha_t *)mp->b_rptr;
18703 		if (err != 0) {
18704 			first_mp = mp;
18705 			if (err == EINVAL)
18706 				goto icmp_parameter_problem;
18707 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
18708 			goto drop_pkt;
18709 		}
18710 		iplen = ntohs(ipha->ipha_length) + adjust;
18711 		ipha->ipha_length = htons(iplen);
18712 	}
18713 
18714 	/*
18715 	 * If there is a policy, try to attach an ipsec_out in
18716 	 * the front. At the end, first_mp either points to a
18717 	 * M_DATA message or IPSEC_OUT message linked to a
18718 	 * M_DATA message. We have to do it now as we might
18719 	 * lose the "conn" if we go through ip_newroute.
18720 	 */
18721 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
18722 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
18723 		    ipha->ipha_protocol)) == NULL)) {
18724 			if (need_decref)
18725 				CONN_DEC_REF(connp);
18726 			return;
18727 		} else {
18728 			ASSERT(mp->b_datap->db_type == M_CTL);
18729 			first_mp = mp;
18730 			mp = mp->b_cont;
18731 			mctl_present = B_TRUE;
18732 		}
18733 	} else {
18734 		first_mp = mp;
18735 		mctl_present = B_FALSE;
18736 	}
18737 
18738 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
18739 
18740 	/* is wrong version or IP options present */
18741 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
18742 		goto version_hdrlen_check;
18743 	dst = ipha->ipha_dst;
18744 
18745 	if (connp->conn_nofailover_ill != NULL) {
18746 		attach_ill = conn_get_held_ill(connp,
18747 		    &connp->conn_nofailover_ill, &err);
18748 		if (err == ILL_LOOKUP_FAILED) {
18749 			if (need_decref)
18750 				CONN_DEC_REF(connp);
18751 			freemsg(first_mp);
18752 			return;
18753 		}
18754 	}
18755 
18756 	/* is packet multicast? */
18757 	if (CLASSD(dst))
18758 		goto multicast;
18759 
18760 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
18761 	    (connp->conn_nexthop_set)) {
18762 		/*
18763 		 * If the destination is a broadcast or a loopback
18764 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
18765 		 * through the standard path. But in the case of local
18766 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
18767 		 * the standard path not IP_XMIT_IF.
18768 		 */
18769 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18770 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
18771 		    (ire->ire_type != IRE_LOOPBACK))) {
18772 			if ((connp->conn_dontroute ||
18773 			    connp->conn_nexthop_set) && (ire != NULL) &&
18774 			    (ire->ire_type == IRE_LOCAL))
18775 				goto standard_path;
18776 
18777 			if (ire != NULL) {
18778 				ire_refrele(ire);
18779 				/* No more access to ire */
18780 				ire = NULL;
18781 			}
18782 			/*
18783 			 * bypass routing checks and go directly to
18784 			 * interface.
18785 			 */
18786 			if (connp->conn_dontroute) {
18787 				goto dontroute;
18788 			} else if (connp->conn_nexthop_set) {
18789 				ip_nexthop = B_TRUE;
18790 				nexthop_addr = connp->conn_nexthop_v4;
18791 				goto send_from_ill;
18792 			}
18793 
18794 			/*
18795 			 * If IP_XMIT_IF socket option is set,
18796 			 * then we allow unicast and multicast
18797 			 * packets to go through the ill. It is
18798 			 * quite possible that the destination
18799 			 * is not in the ire cache table and we
18800 			 * do not want to go to ip_newroute()
18801 			 * instead we call ip_newroute_ipif.
18802 			 */
18803 			xmit_ill = conn_get_held_ill(connp,
18804 			    &connp->conn_xmit_if_ill, &err);
18805 			if (err == ILL_LOOKUP_FAILED) {
18806 				if (attach_ill != NULL)
18807 					ill_refrele(attach_ill);
18808 				if (need_decref)
18809 					CONN_DEC_REF(connp);
18810 				freemsg(first_mp);
18811 				return;
18812 			}
18813 			goto send_from_ill;
18814 		}
18815 standard_path:
18816 		/* Must be a broadcast, a loopback or a local ire */
18817 		if (ire != NULL) {
18818 			ire_refrele(ire);
18819 			/* No more access to ire */
18820 			ire = NULL;
18821 		}
18822 	}
18823 
18824 	if (attach_ill != NULL)
18825 		goto send_from_ill;
18826 
18827 	/*
18828 	 * We cache IRE_CACHEs to avoid lookups. We don't do
18829 	 * this for the tcp global queue and listen end point
18830 	 * as it does not really have a real destination to
18831 	 * talk to.  This is also true for SCTP.
18832 	 */
18833 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
18834 	    !connp->conn_fully_bound) {
18835 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18836 		if (ire == NULL)
18837 			goto noirefound;
18838 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18839 		    "ip_wput_end: q %p (%S)", q, "end");
18840 
18841 		/*
18842 		 * Check if the ire has the RTF_MULTIRT flag, inherited
18843 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18844 		 */
18845 		if (ire->ire_flags & RTF_MULTIRT) {
18846 
18847 			/*
18848 			 * Force the TTL of multirouted packets if required.
18849 			 * The TTL of such packets is bounded by the
18850 			 * ip_multirt_ttl ndd variable.
18851 			 */
18852 			if ((ip_multirt_ttl > 0) &&
18853 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
18854 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
18855 				    "(was %d), dst 0x%08x\n",
18856 				    ip_multirt_ttl, ipha->ipha_ttl,
18857 				    ntohl(ire->ire_addr)));
18858 				ipha->ipha_ttl = ip_multirt_ttl;
18859 			}
18860 			/*
18861 			 * We look at this point if there are pending
18862 			 * unresolved routes. ire_multirt_resolvable()
18863 			 * checks in O(n) that all IRE_OFFSUBNET ire
18864 			 * entries for the packet's destination and
18865 			 * flagged RTF_MULTIRT are currently resolved.
18866 			 * If some remain unresolved, we make a copy
18867 			 * of the current message. It will be used
18868 			 * to initiate additional route resolutions.
18869 			 */
18870 			multirt_need_resolve =
18871 			    ire_multirt_need_resolve(ire->ire_addr,
18872 			    MBLK_GETLABEL(first_mp));
18873 			ip2dbg(("ip_wput[TCP]: ire %p, "
18874 			    "multirt_need_resolve %d, first_mp %p\n",
18875 			    (void *)ire, multirt_need_resolve,
18876 			    (void *)first_mp));
18877 			if (multirt_need_resolve) {
18878 				copy_mp = copymsg(first_mp);
18879 				if (copy_mp != NULL) {
18880 					MULTIRT_DEBUG_TAG(copy_mp);
18881 				}
18882 			}
18883 		}
18884 
18885 		ip_wput_ire(q, first_mp, ire, connp, caller);
18886 
18887 		/*
18888 		 * Try to resolve another multiroute if
18889 		 * ire_multirt_need_resolve() deemed it necessary.
18890 		 */
18891 		if (copy_mp != NULL) {
18892 			ip_newroute(q, copy_mp, dst, NULL, connp);
18893 		}
18894 		if (need_decref)
18895 			CONN_DEC_REF(connp);
18896 		return;
18897 	}
18898 
18899 	/*
18900 	 * Access to conn_ire_cache. (protected by conn_lock)
18901 	 *
18902 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
18903 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
18904 	 * send a packet or two with the IRE_CACHE that is going away.
18905 	 * Access to the ire requires an ire refhold on the ire prior to
18906 	 * its use since an interface unplumb thread may delete the cached
18907 	 * ire and release the refhold at any time.
18908 	 *
18909 	 * Caching an ire in the conn_ire_cache
18910 	 *
18911 	 * o Caching an ire pointer in the conn requires a strict check for
18912 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
18913 	 * ires  before cleaning up the conns. So the caching of an ire pointer
18914 	 * in the conn is done after making sure under the bucket lock that the
18915 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
18916 	 * caching an ire after the unplumb thread has cleaned up the conn.
18917 	 * If the conn does not send a packet subsequently the unplumb thread
18918 	 * will be hanging waiting for the ire count to drop to zero.
18919 	 *
18920 	 * o We also need to atomically test for a null conn_ire_cache and
18921 	 * set the conn_ire_cache under the the protection of the conn_lock
18922 	 * to avoid races among concurrent threads trying to simultaneously
18923 	 * cache an ire in the conn_ire_cache.
18924 	 */
18925 	mutex_enter(&connp->conn_lock);
18926 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
18927 
18928 	if (ire != NULL && ire->ire_addr == dst &&
18929 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18930 
18931 		IRE_REFHOLD(ire);
18932 		mutex_exit(&connp->conn_lock);
18933 
18934 	} else {
18935 		boolean_t cached = B_FALSE;
18936 		connp->conn_ire_cache = NULL;
18937 		mutex_exit(&connp->conn_lock);
18938 		/* Release the old ire */
18939 		if (ire != NULL && sctp_ire == NULL)
18940 			IRE_REFRELE_NOTR(ire);
18941 
18942 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
18943 		if (ire == NULL)
18944 			goto noirefound;
18945 		IRE_REFHOLD_NOTR(ire);
18946 
18947 		mutex_enter(&connp->conn_lock);
18948 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
18949 		    connp->conn_ire_cache == NULL) {
18950 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
18951 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18952 				connp->conn_ire_cache = ire;
18953 				cached = B_TRUE;
18954 			}
18955 			rw_exit(&ire->ire_bucket->irb_lock);
18956 		}
18957 		mutex_exit(&connp->conn_lock);
18958 
18959 		/*
18960 		 * We can continue to use the ire but since it was
18961 		 * not cached, we should drop the extra reference.
18962 		 */
18963 		if (!cached)
18964 			IRE_REFRELE_NOTR(ire);
18965 	}
18966 
18967 
18968 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
18969 	    "ip_wput_end: q %p (%S)", q, "end");
18970 
18971 	/*
18972 	 * Check if the ire has the RTF_MULTIRT flag, inherited
18973 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
18974 	 */
18975 	if (ire->ire_flags & RTF_MULTIRT) {
18976 
18977 		/*
18978 		 * Force the TTL of multirouted packets if required.
18979 		 * The TTL of such packets is bounded by the
18980 		 * ip_multirt_ttl ndd variable.
18981 		 */
18982 		if ((ip_multirt_ttl > 0) &&
18983 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
18984 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
18985 			    "(was %d), dst 0x%08x\n",
18986 			    ip_multirt_ttl, ipha->ipha_ttl,
18987 			    ntohl(ire->ire_addr)));
18988 			ipha->ipha_ttl = ip_multirt_ttl;
18989 		}
18990 
18991 		/*
18992 		 * At this point, we check to see if there are any pending
18993 		 * unresolved routes. ire_multirt_resolvable()
18994 		 * checks in O(n) that all IRE_OFFSUBNET ire
18995 		 * entries for the packet's destination and
18996 		 * flagged RTF_MULTIRT are currently resolved.
18997 		 * If some remain unresolved, we make a copy
18998 		 * of the current message. It will be used
18999 		 * to initiate additional route resolutions.
19000 		 */
19001 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19002 		    MBLK_GETLABEL(first_mp));
19003 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19004 		    "multirt_need_resolve %d, first_mp %p\n",
19005 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19006 		if (multirt_need_resolve) {
19007 			copy_mp = copymsg(first_mp);
19008 			if (copy_mp != NULL) {
19009 				MULTIRT_DEBUG_TAG(copy_mp);
19010 			}
19011 		}
19012 	}
19013 
19014 	ip_wput_ire(q, first_mp, ire, connp, caller);
19015 
19016 	/*
19017 	 * Try to resolve another multiroute if
19018 	 * ire_multirt_resolvable() deemed it necessary
19019 	 */
19020 	if (copy_mp != NULL) {
19021 		ip_newroute(q, copy_mp, dst, NULL, connp);
19022 	}
19023 	if (need_decref)
19024 		CONN_DEC_REF(connp);
19025 	return;
19026 
19027 qnext:
19028 	/*
19029 	 * Upper Level Protocols pass down complete IP datagrams
19030 	 * as M_DATA messages.	Everything else is a sideshow.
19031 	 *
19032 	 * 1) We could be re-entering ip_wput because of ip_neworute
19033 	 *    in which case we could have a IPSEC_OUT message. We
19034 	 *    need to pass through ip_wput like other datagrams and
19035 	 *    hence cannot branch to ip_wput_nondata.
19036 	 *
19037 	 * 2) ARP, AH, ESP, and other clients who are on the module
19038 	 *    instance of IP stream, give us something to deal with.
19039 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19040 	 *
19041 	 * 3) ICMP replies also could come here.
19042 	 */
19043 	if (DB_TYPE(mp) != M_DATA) {
19044 	    notdata:
19045 		if (DB_TYPE(mp) == M_CTL) {
19046 			/*
19047 			 * M_CTL messages are used by ARP, AH and ESP to
19048 			 * communicate with IP. We deal with IPSEC_IN and
19049 			 * IPSEC_OUT here. ip_wput_nondata handles other
19050 			 * cases.
19051 			 */
19052 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19053 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19054 				first_mp = mp->b_cont;
19055 				first_mp->b_flag &= ~MSGHASREF;
19056 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19057 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19058 				CONN_DEC_REF(connp);
19059 				connp = NULL;
19060 			}
19061 			if (ii->ipsec_info_type == IPSEC_IN) {
19062 				/*
19063 				 * Either this message goes back to
19064 				 * IPSEC for further processing or to
19065 				 * ULP after policy checks.
19066 				 */
19067 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19068 				return;
19069 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19070 				io = (ipsec_out_t *)ii;
19071 				if (io->ipsec_out_proc_begin) {
19072 					/*
19073 					 * IPSEC processing has already started.
19074 					 * Complete it.
19075 					 * IPQoS notes: We don't care what is
19076 					 * in ipsec_out_ill_index since this
19077 					 * won't be processed for IPQoS policies
19078 					 * in ipsec_out_process.
19079 					 */
19080 					ipsec_out_process(q, mp, NULL,
19081 					    io->ipsec_out_ill_index);
19082 					return;
19083 				} else {
19084 					connp = (q->q_next != NULL) ?
19085 					    NULL : Q_TO_CONN(q);
19086 					first_mp = mp;
19087 					mp = mp->b_cont;
19088 					mctl_present = B_TRUE;
19089 				}
19090 				zoneid = io->ipsec_out_zoneid;
19091 				ASSERT(zoneid != ALL_ZONES);
19092 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19093 				/*
19094 				 * It's an IPsec control message requesting
19095 				 * an SADB update to be sent to the IPsec
19096 				 * hardware acceleration capable ills.
19097 				 */
19098 				ipsec_ctl_t *ipsec_ctl =
19099 				    (ipsec_ctl_t *)mp->b_rptr;
19100 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19101 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19102 				mblk_t *cmp = mp->b_cont;
19103 
19104 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19105 				ASSERT(cmp != NULL);
19106 
19107 				freeb(mp);
19108 				ill_ipsec_capab_send_all(satype, cmp, sa);
19109 				return;
19110 			} else {
19111 				/*
19112 				 * This must be ARP or special TSOL signaling.
19113 				 */
19114 				ip_wput_nondata(NULL, q, mp, NULL);
19115 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19116 				    "ip_wput_end: q %p (%S)", q, "nondata");
19117 				return;
19118 			}
19119 		} else {
19120 			/*
19121 			 * This must be non-(ARP/AH/ESP) messages.
19122 			 */
19123 			ASSERT(!need_decref);
19124 			ip_wput_nondata(NULL, q, mp, NULL);
19125 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19126 			    "ip_wput_end: q %p (%S)", q, "nondata");
19127 			return;
19128 		}
19129 	} else {
19130 		first_mp = mp;
19131 		mctl_present = B_FALSE;
19132 	}
19133 
19134 	ASSERT(first_mp != NULL);
19135 	/*
19136 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
19137 	 * to make sure that this packet goes out on the same interface it
19138 	 * came in. We handle that here.
19139 	 */
19140 	if (mctl_present) {
19141 		uint_t ifindex;
19142 
19143 		io = (ipsec_out_t *)first_mp->b_rptr;
19144 		if (io->ipsec_out_attach_if ||
19145 		    io->ipsec_out_xmit_if ||
19146 		    io->ipsec_out_ip_nexthop) {
19147 			ill_t	*ill;
19148 
19149 			/*
19150 			 * We may have lost the conn context if we are
19151 			 * coming here from ip_newroute(). Copy the
19152 			 * nexthop information.
19153 			 */
19154 			if (io->ipsec_out_ip_nexthop) {
19155 				ip_nexthop = B_TRUE;
19156 				nexthop_addr = io->ipsec_out_nexthop_addr;
19157 
19158 				ipha = (ipha_t *)mp->b_rptr;
19159 				dst = ipha->ipha_dst;
19160 				goto send_from_ill;
19161 			} else {
19162 				ASSERT(io->ipsec_out_ill_index != 0);
19163 				ifindex = io->ipsec_out_ill_index;
19164 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
19165 				    NULL, NULL, NULL, NULL);
19166 				/*
19167 				 * ipsec_out_xmit_if bit is used to tell
19168 				 * ip_wput to use the ill to send outgoing data
19169 				 * as we have no conn when data comes from ICMP
19170 				 * error msg routines. Currently this feature is
19171 				 * only used by ip_mrtun_forward routine.
19172 				 */
19173 				if (io->ipsec_out_xmit_if) {
19174 					xmit_ill = ill;
19175 					if (xmit_ill == NULL) {
19176 						ip1dbg(("ip_output:bad ifindex "
19177 						    "for xmit_ill %d\n",
19178 						    ifindex));
19179 						freemsg(first_mp);
19180 						BUMP_MIB(&ip_mib,
19181 						    ipOutDiscards);
19182 						ASSERT(!need_decref);
19183 						return;
19184 					}
19185 					/* Free up the ipsec_out_t mblk */
19186 					ASSERT(first_mp->b_cont == mp);
19187 					first_mp->b_cont = NULL;
19188 					freeb(first_mp);
19189 					/* Just send the IP header+ICMP+data */
19190 					first_mp = mp;
19191 					ipha = (ipha_t *)mp->b_rptr;
19192 					dst = ipha->ipha_dst;
19193 					goto send_from_ill;
19194 				} else {
19195 					attach_ill = ill;
19196 				}
19197 
19198 				if (attach_ill == NULL) {
19199 					ASSERT(xmit_ill == NULL);
19200 					ip1dbg(("ip_output: bad ifindex for "
19201 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
19202 					    ifindex));
19203 					freemsg(first_mp);
19204 					BUMP_MIB(&ip_mib, ipOutDiscards);
19205 					ASSERT(!need_decref);
19206 					return;
19207 				}
19208 			}
19209 		}
19210 	}
19211 
19212 	ASSERT(xmit_ill == NULL);
19213 
19214 	/* We have a complete IP datagram heading outbound. */
19215 	ipha = (ipha_t *)mp->b_rptr;
19216 
19217 #ifndef SPEED_BEFORE_SAFETY
19218 	/*
19219 	 * Make sure we have a full-word aligned message and that at least
19220 	 * a simple IP header is accessible in the first message.  If not,
19221 	 * try a pullup.
19222 	 */
19223 	if (!OK_32PTR(rptr) ||
19224 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
19225 	    hdrtoosmall:
19226 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
19227 			BUMP_MIB(&ip_mib, ipOutDiscards);
19228 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19229 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
19230 			if (first_mp == NULL)
19231 				first_mp = mp;
19232 			goto drop_pkt;
19233 		}
19234 
19235 		/* This function assumes that mp points to an IPv4 packet. */
19236 		if (is_system_labeled() && q->q_next == NULL &&
19237 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
19238 		    !connp->conn_ulp_labeled) {
19239 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
19240 			    &adjust, connp->conn_mac_exempt);
19241 			ipha = (ipha_t *)mp->b_rptr;
19242 			if (first_mp != NULL)
19243 				first_mp->b_cont = mp;
19244 			if (err != 0) {
19245 				if (first_mp == NULL)
19246 					first_mp = mp;
19247 				if (err == EINVAL)
19248 					goto icmp_parameter_problem;
19249 				ip2dbg(("ip_wput: label check failed (%d)\n",
19250 				    err));
19251 				goto drop_pkt;
19252 			}
19253 			iplen = ntohs(ipha->ipha_length) + adjust;
19254 			ipha->ipha_length = htons(iplen);
19255 		}
19256 
19257 		ipha = (ipha_t *)mp->b_rptr;
19258 		if (first_mp == NULL) {
19259 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
19260 			/*
19261 			 * If we got here because of "goto hdrtoosmall"
19262 			 * We need to attach a IPSEC_OUT.
19263 			 */
19264 			if (connp->conn_out_enforce_policy) {
19265 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
19266 				    NULL, ipha->ipha_protocol)) == NULL)) {
19267 					if (need_decref)
19268 						CONN_DEC_REF(connp);
19269 					return;
19270 				} else {
19271 					ASSERT(mp->b_datap->db_type == M_CTL);
19272 					first_mp = mp;
19273 					mp = mp->b_cont;
19274 					mctl_present = B_TRUE;
19275 				}
19276 			} else {
19277 				first_mp = mp;
19278 				mctl_present = B_FALSE;
19279 			}
19280 		}
19281 	}
19282 #endif
19283 
19284 	/* Most of the code below is written for speed, not readability */
19285 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19286 
19287 	/*
19288 	 * If ip_newroute() fails, we're going to need a full
19289 	 * header for the icmp wraparound.
19290 	 */
19291 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
19292 		uint_t	v_hlen;
19293 	    version_hdrlen_check:
19294 		ASSERT(first_mp != NULL);
19295 		v_hlen = V_HLEN;
19296 		/*
19297 		 * siphon off IPv6 packets coming down from transport
19298 		 * layer modules here.
19299 		 * Note: high-order bit carries NUD reachability confirmation
19300 		 */
19301 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
19302 			/*
19303 			 * XXX implement a IPv4 and IPv6 packet counter per
19304 			 * conn and switch when ratio exceeds e.g. 10:1
19305 			 */
19306 #ifdef notyet
19307 			if (q->q_next == NULL) /* Avoid ill queue */
19308 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
19309 #endif
19310 			BUMP_MIB(&ip_mib, ipOutIPv6);
19311 			ASSERT(xmit_ill == NULL);
19312 			if (attach_ill != NULL)
19313 				ill_refrele(attach_ill);
19314 			if (need_decref)
19315 				mp->b_flag |= MSGHASREF;
19316 			(void) ip_output_v6(connp, first_mp, q, caller);
19317 			return;
19318 		}
19319 
19320 		if ((v_hlen >> 4) != IP_VERSION) {
19321 			BUMP_MIB(&ip_mib, ipOutDiscards);
19322 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19323 			    "ip_wput_end: q %p (%S)", q, "badvers");
19324 			goto drop_pkt;
19325 		}
19326 		/*
19327 		 * Is the header length at least 20 bytes?
19328 		 *
19329 		 * Are there enough bytes accessible in the header?  If
19330 		 * not, try a pullup.
19331 		 */
19332 		v_hlen &= 0xF;
19333 		v_hlen <<= 2;
19334 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
19335 			BUMP_MIB(&ip_mib, ipOutDiscards);
19336 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19337 			    "ip_wput_end: q %p (%S)", q, "badlen");
19338 			goto drop_pkt;
19339 		}
19340 		if (v_hlen > (mp->b_wptr - rptr)) {
19341 			if (!pullupmsg(mp, v_hlen)) {
19342 				BUMP_MIB(&ip_mib, ipOutDiscards);
19343 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19344 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
19345 				goto drop_pkt;
19346 			}
19347 			ipha = (ipha_t *)mp->b_rptr;
19348 		}
19349 		/*
19350 		 * Move first entry from any source route into ipha_dst and
19351 		 * verify the options
19352 		 */
19353 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
19354 			ASSERT(xmit_ill == NULL);
19355 			if (attach_ill != NULL)
19356 				ill_refrele(attach_ill);
19357 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19358 			    "ip_wput_end: q %p (%S)", q, "badopts");
19359 			if (need_decref)
19360 				CONN_DEC_REF(connp);
19361 			return;
19362 		}
19363 	}
19364 	dst = ipha->ipha_dst;
19365 
19366 	/*
19367 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
19368 	 * we have to run the packet through ip_newroute which will take
19369 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
19370 	 * a resolver, or assigning a default gateway, etc.
19371 	 */
19372 	if (CLASSD(dst)) {
19373 		ipif_t	*ipif;
19374 		uint32_t setsrc = 0;
19375 
19376 	    multicast:
19377 		ASSERT(first_mp != NULL);
19378 		ASSERT(xmit_ill == NULL);
19379 		ip2dbg(("ip_wput: CLASSD\n"));
19380 		if (connp == NULL) {
19381 			/*
19382 			 * Use the first good ipif on the ill.
19383 			 * XXX Should this ever happen? (Appears
19384 			 * to show up with just ppp and no ethernet due
19385 			 * to in.rdisc.)
19386 			 * However, ire_send should be able to
19387 			 * call ip_wput_ire directly.
19388 			 *
19389 			 * XXX Also, this can happen for ICMP and other packets
19390 			 * with multicast source addresses.  Perhaps we should
19391 			 * fix things so that we drop the packet in question,
19392 			 * but for now, just run with it.
19393 			 */
19394 			ill_t *ill = (ill_t *)q->q_ptr;
19395 
19396 			/*
19397 			 * Don't honor attach_if for this case. If ill
19398 			 * is part of the group, ipif could belong to
19399 			 * any ill and we cannot maintain attach_ill
19400 			 * and ipif_ill same anymore and the assert
19401 			 * below would fail.
19402 			 */
19403 			if (mctl_present) {
19404 				io->ipsec_out_ill_index = 0;
19405 				io->ipsec_out_attach_if = B_FALSE;
19406 				ASSERT(attach_ill != NULL);
19407 				ill_refrele(attach_ill);
19408 				attach_ill = NULL;
19409 			}
19410 
19411 			ASSERT(attach_ill == NULL);
19412 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
19413 			if (ipif == NULL) {
19414 				if (need_decref)
19415 					CONN_DEC_REF(connp);
19416 				freemsg(first_mp);
19417 				return;
19418 			}
19419 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
19420 			    ntohl(dst), ill->ill_name));
19421 		} else {
19422 			/*
19423 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
19424 			 * IP_XMIT_IF is honoured.
19425 			 * Block comment above this function explains the
19426 			 * locking mechanism used here
19427 			 */
19428 			xmit_ill = conn_get_held_ill(connp,
19429 			    &connp->conn_xmit_if_ill, &err);
19430 			if (err == ILL_LOOKUP_FAILED) {
19431 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
19432 				goto drop_pkt;
19433 			}
19434 			if (xmit_ill == NULL) {
19435 				ipif = conn_get_held_ipif(connp,
19436 				    &connp->conn_multicast_ipif, &err);
19437 				if (err == IPIF_LOOKUP_FAILED) {
19438 					ip1dbg(("ip_wput: No ipif for "
19439 					    "multicast\n"));
19440 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19441 					goto drop_pkt;
19442 				}
19443 			}
19444 			if (xmit_ill != NULL) {
19445 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19446 				if (ipif == NULL) {
19447 					ip1dbg(("ip_wput: No ipif for "
19448 					    "IP_XMIT_IF\n"));
19449 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19450 					goto drop_pkt;
19451 				}
19452 			} else if (ipif == NULL || ipif->ipif_isv6) {
19453 				/*
19454 				 * We must do this ipif determination here
19455 				 * else we could pass through ip_newroute
19456 				 * and come back here without the conn context.
19457 				 *
19458 				 * Note: we do late binding i.e. we bind to
19459 				 * the interface when the first packet is sent.
19460 				 * For performance reasons we do not rebind on
19461 				 * each packet but keep the binding until the
19462 				 * next IP_MULTICAST_IF option.
19463 				 *
19464 				 * conn_multicast_{ipif,ill} are shared between
19465 				 * IPv4 and IPv6 and AF_INET6 sockets can
19466 				 * send both IPv4 and IPv6 packets. Hence
19467 				 * we have to check that "isv6" matches above.
19468 				 */
19469 				if (ipif != NULL)
19470 					ipif_refrele(ipif);
19471 				ipif = ipif_lookup_group(dst, zoneid);
19472 				if (ipif == NULL) {
19473 					ip1dbg(("ip_wput: No ipif for "
19474 					    "multicast\n"));
19475 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19476 					goto drop_pkt;
19477 				}
19478 				err = conn_set_held_ipif(connp,
19479 				    &connp->conn_multicast_ipif, ipif);
19480 				if (err == IPIF_LOOKUP_FAILED) {
19481 					ipif_refrele(ipif);
19482 					ip1dbg(("ip_wput: No ipif for "
19483 					    "multicast\n"));
19484 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19485 					goto drop_pkt;
19486 				}
19487 			}
19488 		}
19489 		ASSERT(!ipif->ipif_isv6);
19490 		/*
19491 		 * As we may lose the conn by the time we reach ip_wput_ire,
19492 		 * we copy conn_multicast_loop and conn_dontroute on to an
19493 		 * ipsec_out. In case if this datagram goes out secure,
19494 		 * we need the ill_index also. Copy that also into the
19495 		 * ipsec_out.
19496 		 */
19497 		if (mctl_present) {
19498 			io = (ipsec_out_t *)first_mp->b_rptr;
19499 			ASSERT(first_mp->b_datap->db_type == M_CTL);
19500 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
19501 		} else {
19502 			ASSERT(mp == first_mp);
19503 			if ((first_mp = allocb(sizeof (ipsec_info_t),
19504 			    BPRI_HI)) == NULL) {
19505 				ipif_refrele(ipif);
19506 				first_mp = mp;
19507 				goto drop_pkt;
19508 			}
19509 			first_mp->b_datap->db_type = M_CTL;
19510 			first_mp->b_wptr += sizeof (ipsec_info_t);
19511 			/* ipsec_out_secure is B_FALSE now */
19512 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
19513 			io = (ipsec_out_t *)first_mp->b_rptr;
19514 			io->ipsec_out_type = IPSEC_OUT;
19515 			io->ipsec_out_len = sizeof (ipsec_out_t);
19516 			io->ipsec_out_use_global_policy = B_TRUE;
19517 			first_mp->b_cont = mp;
19518 			mctl_present = B_TRUE;
19519 		}
19520 		if (attach_ill != NULL) {
19521 			ASSERT(attach_ill == ipif->ipif_ill);
19522 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19523 
19524 			/*
19525 			 * Check if we need an ire that will not be
19526 			 * looked up by anybody else i.e. HIDDEN.
19527 			 */
19528 			if (ill_is_probeonly(attach_ill)) {
19529 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19530 			}
19531 			io->ipsec_out_ill_index =
19532 			    attach_ill->ill_phyint->phyint_ifindex;
19533 			io->ipsec_out_attach_if = B_TRUE;
19534 		} else {
19535 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
19536 			io->ipsec_out_ill_index =
19537 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
19538 		}
19539 		if (connp != NULL) {
19540 			io->ipsec_out_multicast_loop =
19541 			    connp->conn_multicast_loop;
19542 			io->ipsec_out_dontroute = connp->conn_dontroute;
19543 			io->ipsec_out_zoneid = connp->conn_zoneid;
19544 		}
19545 		/*
19546 		 * If the application uses IP_MULTICAST_IF with
19547 		 * different logical addresses of the same ILL, we
19548 		 * need to make sure that the soruce address of
19549 		 * the packet matches the logical IP address used
19550 		 * in the option. We do it by initializing ipha_src
19551 		 * here. This should keep IPSEC also happy as
19552 		 * when we return from IPSEC processing, we don't
19553 		 * have to worry about getting the right address on
19554 		 * the packet. Thus it is sufficient to look for
19555 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
19556 		 * MATCH_IRE_IPIF.
19557 		 *
19558 		 * NOTE : We need to do it for non-secure case also as
19559 		 * this might go out secure if there is a global policy
19560 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
19561 		 * address, the source should be initialized already and
19562 		 * hence we won't be initializing here.
19563 		 *
19564 		 * As we do not have the ire yet, it is possible that
19565 		 * we set the source address here and then later discover
19566 		 * that the ire implies the source address to be assigned
19567 		 * through the RTF_SETSRC flag.
19568 		 * In that case, the setsrc variable will remind us
19569 		 * that overwritting the source address by the one
19570 		 * of the RTF_SETSRC-flagged ire is allowed.
19571 		 */
19572 		if (ipha->ipha_src == INADDR_ANY &&
19573 		    (connp == NULL || !connp->conn_unspec_src)) {
19574 			ipha->ipha_src = ipif->ipif_src_addr;
19575 			setsrc = RTF_SETSRC;
19576 		}
19577 		/*
19578 		 * Find an IRE which matches the destination and the outgoing
19579 		 * queue (i.e. the outgoing interface.)
19580 		 * For loopback use a unicast IP address for
19581 		 * the ire lookup.
19582 		 */
19583 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
19584 		    PHYI_LOOPBACK) {
19585 			dst = ipif->ipif_lcl_addr;
19586 		}
19587 		/*
19588 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
19589 		 * We don't need to lookup ire in ctable as the packet
19590 		 * needs to be sent to the destination through the specified
19591 		 * ill irrespective of ires in the cache table.
19592 		 */
19593 		ire = NULL;
19594 		if (xmit_ill == NULL) {
19595 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
19596 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19597 		}
19598 
19599 		/*
19600 		 * refrele attach_ill as its not needed anymore.
19601 		 */
19602 		if (attach_ill != NULL) {
19603 			ill_refrele(attach_ill);
19604 			attach_ill = NULL;
19605 		}
19606 
19607 		if (ire == NULL) {
19608 			/*
19609 			 * Multicast loopback and multicast forwarding is
19610 			 * done in ip_wput_ire.
19611 			 *
19612 			 * Mark this packet to make it be delivered to
19613 			 * ip_wput_ire after the new ire has been
19614 			 * created.
19615 			 *
19616 			 * The call to ip_newroute_ipif takes into account
19617 			 * the setsrc reminder. In any case, we take care
19618 			 * of the RTF_MULTIRT flag.
19619 			 */
19620 			mp->b_prev = mp->b_next = NULL;
19621 			if (xmit_ill == NULL ||
19622 			    xmit_ill->ill_ipif_up_count > 0) {
19623 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
19624 				    setsrc | RTF_MULTIRT);
19625 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19626 				    "ip_wput_end: q %p (%S)", q, "noire");
19627 			} else {
19628 				freemsg(first_mp);
19629 			}
19630 			ipif_refrele(ipif);
19631 			if (xmit_ill != NULL)
19632 				ill_refrele(xmit_ill);
19633 			if (need_decref)
19634 				CONN_DEC_REF(connp);
19635 			return;
19636 		}
19637 
19638 		ipif_refrele(ipif);
19639 		ipif = NULL;
19640 		ASSERT(xmit_ill == NULL);
19641 
19642 		/*
19643 		 * Honor the RTF_SETSRC flag for multicast packets,
19644 		 * if allowed by the setsrc reminder.
19645 		 */
19646 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
19647 			ipha->ipha_src = ire->ire_src_addr;
19648 		}
19649 
19650 		/*
19651 		 * Unconditionally force the TTL to 1 for
19652 		 * multirouted multicast packets:
19653 		 * multirouted multicast should not cross
19654 		 * multicast routers.
19655 		 */
19656 		if (ire->ire_flags & RTF_MULTIRT) {
19657 			if (ipha->ipha_ttl > 1) {
19658 				ip2dbg(("ip_wput: forcing multicast "
19659 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
19660 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
19661 				ipha->ipha_ttl = 1;
19662 			}
19663 		}
19664 	} else {
19665 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19666 		if ((ire != NULL) && (ire->ire_type &
19667 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
19668 			ignore_dontroute = B_TRUE;
19669 			ignore_nexthop = B_TRUE;
19670 		}
19671 		if (ire != NULL) {
19672 			ire_refrele(ire);
19673 			ire = NULL;
19674 		}
19675 		/*
19676 		 * Guard against coming in from arp in which case conn is NULL.
19677 		 * Also guard against non M_DATA with dontroute set but
19678 		 * destined to local, loopback or broadcast addresses.
19679 		 */
19680 		if (connp != NULL && connp->conn_dontroute &&
19681 		    !ignore_dontroute) {
19682 dontroute:
19683 			/*
19684 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
19685 			 * routing protocols from seeing false direct
19686 			 * connectivity.
19687 			 */
19688 			ipha->ipha_ttl = 1;
19689 			/*
19690 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
19691 			 * along with SO_DONTROUTE, higher precedence is
19692 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
19693 			 */
19694 			if (connp->conn_xmit_if_ill == NULL) {
19695 				/* If suitable ipif not found, drop packet */
19696 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
19697 				if (dst_ipif == NULL) {
19698 					ip1dbg(("ip_wput: no route for "
19699 					    "dst using SO_DONTROUTE\n"));
19700 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
19701 					mp->b_prev = mp->b_next = NULL;
19702 					if (first_mp == NULL)
19703 						first_mp = mp;
19704 					goto drop_pkt;
19705 				} else {
19706 					/*
19707 					 * If suitable ipif has been found, set
19708 					 * xmit_ill to the corresponding
19709 					 * ipif_ill because we'll be following
19710 					 * the IP_XMIT_IF logic.
19711 					 */
19712 					ASSERT(xmit_ill == NULL);
19713 					xmit_ill = dst_ipif->ipif_ill;
19714 					mutex_enter(&xmit_ill->ill_lock);
19715 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
19716 						mutex_exit(&xmit_ill->ill_lock);
19717 						xmit_ill = NULL;
19718 						ipif_refrele(dst_ipif);
19719 						ip1dbg(("ip_wput: no route for"
19720 						    " dst using"
19721 						    " SO_DONTROUTE\n"));
19722 						BUMP_MIB(&ip_mib,
19723 						    ipOutNoRoutes);
19724 						mp->b_prev = mp->b_next = NULL;
19725 						if (first_mp == NULL)
19726 							first_mp = mp;
19727 						goto drop_pkt;
19728 					}
19729 					ill_refhold_locked(xmit_ill);
19730 					mutex_exit(&xmit_ill->ill_lock);
19731 					ipif_refrele(dst_ipif);
19732 				}
19733 			}
19734 
19735 		}
19736 		/*
19737 		 * If we are bound to IPIF_NOFAILOVER address, look for
19738 		 * an IRE_CACHE matching the ill.
19739 		 */
19740 send_from_ill:
19741 		if (attach_ill != NULL) {
19742 			ipif_t	*attach_ipif;
19743 
19744 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
19745 
19746 			/*
19747 			 * Check if we need an ire that will not be
19748 			 * looked up by anybody else i.e. HIDDEN.
19749 			 */
19750 			if (ill_is_probeonly(attach_ill)) {
19751 				match_flags |= MATCH_IRE_MARK_HIDDEN;
19752 			}
19753 
19754 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
19755 			if (attach_ipif == NULL) {
19756 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
19757 				goto drop_pkt;
19758 			}
19759 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
19760 			    zoneid, MBLK_GETLABEL(mp), match_flags);
19761 			ipif_refrele(attach_ipif);
19762 		} else if (xmit_ill != NULL || (connp != NULL &&
19763 			    connp->conn_xmit_if_ill != NULL)) {
19764 			/*
19765 			 * Mark this packet as originated locally
19766 			 */
19767 			mp->b_prev = mp->b_next = NULL;
19768 			/*
19769 			 * xmit_ill could be NULL if SO_DONTROUTE
19770 			 * is also set.
19771 			 */
19772 			if (xmit_ill == NULL) {
19773 				xmit_ill = conn_get_held_ill(connp,
19774 				    &connp->conn_xmit_if_ill, &err);
19775 				if (err == ILL_LOOKUP_FAILED) {
19776 					if (need_decref)
19777 						CONN_DEC_REF(connp);
19778 					freemsg(first_mp);
19779 					return;
19780 				}
19781 				if (xmit_ill == NULL) {
19782 					if (connp->conn_dontroute)
19783 						goto dontroute;
19784 					goto send_from_ill;
19785 				}
19786 			}
19787 			/*
19788 			 * could be SO_DONTROUTE case also.
19789 			 * check at least one interface is UP as
19790 			 * spcified by this ILL, and then call
19791 			 * ip_newroute_ipif()
19792 			 */
19793 			if (xmit_ill->ill_ipif_up_count > 0) {
19794 				ipif_t *ipif;
19795 
19796 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
19797 				if (ipif != NULL) {
19798 					ip_newroute_ipif(q, first_mp, ipif,
19799 					    dst, connp, 0);
19800 					ipif_refrele(ipif);
19801 					ip1dbg(("ip_wput: ip_unicast_if\n"));
19802 				}
19803 			} else {
19804 				freemsg(first_mp);
19805 			}
19806 			ill_refrele(xmit_ill);
19807 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19808 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
19809 			if (need_decref)
19810 				CONN_DEC_REF(connp);
19811 			return;
19812 		} else if (ip_nexthop || (connp != NULL &&
19813 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
19814 			if (!ip_nexthop) {
19815 				ip_nexthop = B_TRUE;
19816 				nexthop_addr = connp->conn_nexthop_v4;
19817 			}
19818 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
19819 			    MATCH_IRE_GW;
19820 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
19821 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
19822 		} else {
19823 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19824 		}
19825 		if (!ire) {
19826 			/*
19827 			 * Make sure we don't load spread if this
19828 			 * is IPIF_NOFAILOVER case.
19829 			 */
19830 			if ((attach_ill != NULL) ||
19831 			    (ip_nexthop && !ignore_nexthop)) {
19832 				if (mctl_present) {
19833 					io = (ipsec_out_t *)first_mp->b_rptr;
19834 					ASSERT(first_mp->b_datap->db_type ==
19835 					    M_CTL);
19836 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
19837 				} else {
19838 					ASSERT(mp == first_mp);
19839 					first_mp = allocb(
19840 					    sizeof (ipsec_info_t), BPRI_HI);
19841 					if (first_mp == NULL) {
19842 						first_mp = mp;
19843 						goto drop_pkt;
19844 					}
19845 					first_mp->b_datap->db_type = M_CTL;
19846 					first_mp->b_wptr +=
19847 					    sizeof (ipsec_info_t);
19848 					/* ipsec_out_secure is B_FALSE now */
19849 					bzero(first_mp->b_rptr,
19850 					    sizeof (ipsec_info_t));
19851 					io = (ipsec_out_t *)first_mp->b_rptr;
19852 					io->ipsec_out_type = IPSEC_OUT;
19853 					io->ipsec_out_len =
19854 					    sizeof (ipsec_out_t);
19855 					io->ipsec_out_use_global_policy =
19856 					    B_TRUE;
19857 					first_mp->b_cont = mp;
19858 					mctl_present = B_TRUE;
19859 				}
19860 				if (attach_ill != NULL) {
19861 					io->ipsec_out_ill_index = attach_ill->
19862 					    ill_phyint->phyint_ifindex;
19863 					io->ipsec_out_attach_if = B_TRUE;
19864 				} else {
19865 					io->ipsec_out_ip_nexthop = ip_nexthop;
19866 					io->ipsec_out_nexthop_addr =
19867 					    nexthop_addr;
19868 				}
19869 			}
19870 noirefound:
19871 			/*
19872 			 * Mark this packet as having originated on
19873 			 * this machine.  This will be noted in
19874 			 * ire_add_then_send, which needs to know
19875 			 * whether to run it back through ip_wput or
19876 			 * ip_rput following successful resolution.
19877 			 */
19878 			mp->b_prev = NULL;
19879 			mp->b_next = NULL;
19880 			ip_newroute(q, first_mp, dst, NULL, connp);
19881 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19882 			    "ip_wput_end: q %p (%S)", q, "newroute");
19883 			if (attach_ill != NULL)
19884 				ill_refrele(attach_ill);
19885 			if (xmit_ill != NULL)
19886 				ill_refrele(xmit_ill);
19887 			if (need_decref)
19888 				CONN_DEC_REF(connp);
19889 			return;
19890 		}
19891 	}
19892 
19893 	/* We now know where we are going with it. */
19894 
19895 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19896 	    "ip_wput_end: q %p (%S)", q, "end");
19897 
19898 	/*
19899 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19900 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
19901 	 */
19902 	if (ire->ire_flags & RTF_MULTIRT) {
19903 		/*
19904 		 * Force the TTL of multirouted packets if required.
19905 		 * The TTL of such packets is bounded by the
19906 		 * ip_multirt_ttl ndd variable.
19907 		 */
19908 		if ((ip_multirt_ttl > 0) &&
19909 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19910 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19911 			    "(was %d), dst 0x%08x\n",
19912 			    ip_multirt_ttl, ipha->ipha_ttl,
19913 			    ntohl(ire->ire_addr)));
19914 			ipha->ipha_ttl = ip_multirt_ttl;
19915 		}
19916 		/*
19917 		 * At this point, we check to see if there are any pending
19918 		 * unresolved routes. ire_multirt_resolvable()
19919 		 * checks in O(n) that all IRE_OFFSUBNET ire
19920 		 * entries for the packet's destination and
19921 		 * flagged RTF_MULTIRT are currently resolved.
19922 		 * If some remain unresolved, we make a copy
19923 		 * of the current message. It will be used
19924 		 * to initiate additional route resolutions.
19925 		 */
19926 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19927 		    MBLK_GETLABEL(first_mp));
19928 		ip2dbg(("ip_wput[noirefound]: ire %p, "
19929 		    "multirt_need_resolve %d, first_mp %p\n",
19930 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19931 		if (multirt_need_resolve) {
19932 			copy_mp = copymsg(first_mp);
19933 			if (copy_mp != NULL) {
19934 				MULTIRT_DEBUG_TAG(copy_mp);
19935 			}
19936 		}
19937 	}
19938 
19939 	ip_wput_ire(q, first_mp, ire, connp, caller);
19940 	/*
19941 	 * Try to resolve another multiroute if
19942 	 * ire_multirt_resolvable() deemed it necessary.
19943 	 * At this point, we need to distinguish
19944 	 * multicasts from other packets. For multicasts,
19945 	 * we call ip_newroute_ipif() and request that both
19946 	 * multirouting and setsrc flags are checked.
19947 	 */
19948 	if (copy_mp != NULL) {
19949 		if (CLASSD(dst)) {
19950 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
19951 			if (ipif) {
19952 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
19953 				    RTF_SETSRC | RTF_MULTIRT);
19954 				ipif_refrele(ipif);
19955 			} else {
19956 				MULTIRT_DEBUG_UNTAG(copy_mp);
19957 				freemsg(copy_mp);
19958 				copy_mp = NULL;
19959 			}
19960 		} else {
19961 			ip_newroute(q, copy_mp, dst, NULL, connp);
19962 		}
19963 	}
19964 	if (attach_ill != NULL)
19965 		ill_refrele(attach_ill);
19966 	if (xmit_ill != NULL)
19967 		ill_refrele(xmit_ill);
19968 	if (need_decref)
19969 		CONN_DEC_REF(connp);
19970 	return;
19971 
19972 icmp_parameter_problem:
19973 	/* could not have originated externally */
19974 	ASSERT(mp->b_prev == NULL);
19975 	if (ip_hdr_complete(ipha, zoneid) == 0) {
19976 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
19977 		/* it's the IP header length that's in trouble */
19978 		icmp_param_problem(q, first_mp, 0);
19979 		first_mp = NULL;
19980 	}
19981 
19982 drop_pkt:
19983 	ip1dbg(("ip_wput: dropped packet\n"));
19984 	if (ire != NULL)
19985 		ire_refrele(ire);
19986 	if (need_decref)
19987 		CONN_DEC_REF(connp);
19988 	freemsg(first_mp);
19989 	if (attach_ill != NULL)
19990 		ill_refrele(attach_ill);
19991 	if (xmit_ill != NULL)
19992 		ill_refrele(xmit_ill);
19993 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19994 	    "ip_wput_end: q %p (%S)", q, "droppkt");
19995 }
19996 
19997 void
19998 ip_wput(queue_t *q, mblk_t *mp)
19999 {
20000 	ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20001 }
20002 
20003 /*
20004  *
20005  * The following rules must be observed when accessing any ipif or ill
20006  * that has been cached in the conn. Typically conn_nofailover_ill,
20007  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20008  *
20009  * Access: The ipif or ill pointed to from the conn can be accessed under
20010  * the protection of the conn_lock or after it has been refheld under the
20011  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20012  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20013  * The reason for this is that a concurrent unplumb could actually be
20014  * cleaning up these cached pointers by walking the conns and might have
20015  * finished cleaning up the conn in question. The macros check that an
20016  * unplumb has not yet started on the ipif or ill.
20017  *
20018  * Caching: An ipif or ill pointer may be cached in the conn only after
20019  * making sure that an unplumb has not started. So the caching is done
20020  * while holding both the conn_lock and the ill_lock and after using the
20021  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20022  * flag before starting the cleanup of conns.
20023  *
20024  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20025  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20026  * or a reference to the ipif or a reference to an ire that references the
20027  * ipif. An ipif does not change its ill except for failover/failback. Since
20028  * failover/failback happens only after bringing down the ipif and making sure
20029  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20030  * the above holds.
20031  */
20032 ipif_t *
20033 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20034 {
20035 	ipif_t	*ipif;
20036 	ill_t	*ill;
20037 
20038 	*err = 0;
20039 	rw_enter(&ill_g_lock, RW_READER);
20040 	mutex_enter(&connp->conn_lock);
20041 	ipif = *ipifp;
20042 	if (ipif != NULL) {
20043 		ill = ipif->ipif_ill;
20044 		mutex_enter(&ill->ill_lock);
20045 		if (IPIF_CAN_LOOKUP(ipif)) {
20046 			ipif_refhold_locked(ipif);
20047 			mutex_exit(&ill->ill_lock);
20048 			mutex_exit(&connp->conn_lock);
20049 			rw_exit(&ill_g_lock);
20050 			return (ipif);
20051 		} else {
20052 			*err = IPIF_LOOKUP_FAILED;
20053 		}
20054 		mutex_exit(&ill->ill_lock);
20055 	}
20056 	mutex_exit(&connp->conn_lock);
20057 	rw_exit(&ill_g_lock);
20058 	return (NULL);
20059 }
20060 
20061 ill_t *
20062 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20063 {
20064 	ill_t	*ill;
20065 
20066 	*err = 0;
20067 	mutex_enter(&connp->conn_lock);
20068 	ill = *illp;
20069 	if (ill != NULL) {
20070 		mutex_enter(&ill->ill_lock);
20071 		if (ILL_CAN_LOOKUP(ill)) {
20072 			ill_refhold_locked(ill);
20073 			mutex_exit(&ill->ill_lock);
20074 			mutex_exit(&connp->conn_lock);
20075 			return (ill);
20076 		} else {
20077 			*err = ILL_LOOKUP_FAILED;
20078 		}
20079 		mutex_exit(&ill->ill_lock);
20080 	}
20081 	mutex_exit(&connp->conn_lock);
20082 	return (NULL);
20083 }
20084 
20085 static int
20086 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20087 {
20088 	ill_t	*ill;
20089 
20090 	ill = ipif->ipif_ill;
20091 	mutex_enter(&connp->conn_lock);
20092 	mutex_enter(&ill->ill_lock);
20093 	if (IPIF_CAN_LOOKUP(ipif)) {
20094 		*ipifp = ipif;
20095 		mutex_exit(&ill->ill_lock);
20096 		mutex_exit(&connp->conn_lock);
20097 		return (0);
20098 	}
20099 	mutex_exit(&ill->ill_lock);
20100 	mutex_exit(&connp->conn_lock);
20101 	return (IPIF_LOOKUP_FAILED);
20102 }
20103 
20104 /*
20105  * This is called if the outbound datagram needs fragmentation.
20106  *
20107  * NOTE : This function does not ire_refrele the ire argument passed in.
20108  */
20109 static void
20110 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire)
20111 {
20112 	ipha_t		*ipha;
20113 	mblk_t		*mp;
20114 	uint32_t	v_hlen_tos_len;
20115 	uint32_t	max_frag;
20116 	uint32_t	frag_flag;
20117 	boolean_t	dont_use;
20118 
20119 	if (ipsec_mp->b_datap->db_type == M_CTL) {
20120 		mp = ipsec_mp->b_cont;
20121 	} else {
20122 		mp = ipsec_mp;
20123 	}
20124 
20125 	ipha = (ipha_t *)mp->b_rptr;
20126 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20127 
20128 #ifdef	_BIG_ENDIAN
20129 #define	V_HLEN	(v_hlen_tos_len >> 24)
20130 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20131 #else
20132 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20133 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20134 #endif
20135 
20136 #ifndef SPEED_BEFORE_SAFETY
20137 	/*
20138 	 * Check that ipha_length is consistent with
20139 	 * the mblk length
20140 	 */
20141 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
20142 		ip0dbg(("Packet length mismatch: %d, %ld\n",
20143 		    LENGTH, msgdsize(mp)));
20144 		freemsg(ipsec_mp);
20145 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
20146 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
20147 		    "packet length mismatch");
20148 		return;
20149 	}
20150 #endif
20151 	/*
20152 	 * Don't use frag_flag if pre-built packet or source
20153 	 * routed or if multicast (since multicast packets do not solicit
20154 	 * ICMP "packet too big" messages). Get the values of
20155 	 * max_frag and frag_flag atomically by acquiring the
20156 	 * ire_lock.
20157 	 */
20158 	mutex_enter(&ire->ire_lock);
20159 	max_frag = ire->ire_max_frag;
20160 	frag_flag = ire->ire_frag_flag;
20161 	mutex_exit(&ire->ire_lock);
20162 
20163 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
20164 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
20165 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
20166 
20167 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
20168 	    (dont_use ? 0 : frag_flag));
20169 }
20170 
20171 /*
20172  * Used for deciding the MSS size for the upper layer. Thus
20173  * we need to check the outbound policy values in the conn.
20174  */
20175 int
20176 conn_ipsec_length(conn_t *connp)
20177 {
20178 	ipsec_latch_t *ipl;
20179 
20180 	ipl = connp->conn_latch;
20181 	if (ipl == NULL)
20182 		return (0);
20183 
20184 	if (ipl->ipl_out_policy == NULL)
20185 		return (0);
20186 
20187 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
20188 }
20189 
20190 /*
20191  * Returns an estimate of the IPSEC headers size. This is used if
20192  * we don't want to call into IPSEC to get the exact size.
20193  */
20194 int
20195 ipsec_out_extra_length(mblk_t *ipsec_mp)
20196 {
20197 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
20198 	ipsec_action_t *a;
20199 
20200 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
20201 	if (!io->ipsec_out_secure)
20202 		return (0);
20203 
20204 	a = io->ipsec_out_act;
20205 
20206 	if (a == NULL) {
20207 		ASSERT(io->ipsec_out_policy != NULL);
20208 		a = io->ipsec_out_policy->ipsp_act;
20209 	}
20210 	ASSERT(a != NULL);
20211 
20212 	return (a->ipa_ovhd);
20213 }
20214 
20215 /*
20216  * Returns an estimate of the IPSEC headers size. This is used if
20217  * we don't want to call into IPSEC to get the exact size.
20218  */
20219 int
20220 ipsec_in_extra_length(mblk_t *ipsec_mp)
20221 {
20222 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
20223 	ipsec_action_t *a;
20224 
20225 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
20226 
20227 	a = ii->ipsec_in_action;
20228 	return (a == NULL ? 0 : a->ipa_ovhd);
20229 }
20230 
20231 /*
20232  * If there are any source route options, return the true final
20233  * destination. Otherwise, return the destination.
20234  */
20235 ipaddr_t
20236 ip_get_dst(ipha_t *ipha)
20237 {
20238 	ipoptp_t	opts;
20239 	uchar_t		*opt;
20240 	uint8_t		optval;
20241 	uint8_t		optlen;
20242 	ipaddr_t	dst;
20243 	uint32_t off;
20244 
20245 	dst = ipha->ipha_dst;
20246 
20247 	if (IS_SIMPLE_IPH(ipha))
20248 		return (dst);
20249 
20250 	for (optval = ipoptp_first(&opts, ipha);
20251 	    optval != IPOPT_EOL;
20252 	    optval = ipoptp_next(&opts)) {
20253 		opt = opts.ipoptp_cur;
20254 		optlen = opts.ipoptp_len;
20255 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20256 		switch (optval) {
20257 		case IPOPT_SSRR:
20258 		case IPOPT_LSRR:
20259 			off = opt[IPOPT_OFFSET];
20260 			/*
20261 			 * If one of the conditions is true, it means
20262 			 * end of options and dst already has the right
20263 			 * value.
20264 			 */
20265 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
20266 				off = optlen - IP_ADDR_LEN;
20267 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
20268 			}
20269 			return (dst);
20270 		default:
20271 			break;
20272 		}
20273 	}
20274 
20275 	return (dst);
20276 }
20277 
20278 mblk_t *
20279 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
20280     conn_t *connp, boolean_t unspec_src)
20281 {
20282 	ipsec_out_t	*io;
20283 	mblk_t		*first_mp;
20284 	boolean_t policy_present;
20285 
20286 	first_mp = mp;
20287 	if (mp->b_datap->db_type == M_CTL) {
20288 		io = (ipsec_out_t *)first_mp->b_rptr;
20289 		/*
20290 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
20291 		 *
20292 		 * 1) There is per-socket policy (including cached global
20293 		 *    policy).
20294 		 * 2) There is no per-socket policy, but it is
20295 		 *    a multicast packet that needs to go out
20296 		 *    on a specific interface. This is the case
20297 		 *    where (ip_wput and ip_wput_multicast) attaches
20298 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
20299 		 *
20300 		 * In case (2) we check with global policy to
20301 		 * see if there is a match and set the ill_index
20302 		 * appropriately so that we can lookup the ire
20303 		 * properly in ip_wput_ipsec_out.
20304 		 */
20305 
20306 		/*
20307 		 * ipsec_out_use_global_policy is set to B_FALSE
20308 		 * in ipsec_in_to_out(). Refer to that function for
20309 		 * details.
20310 		 */
20311 		if ((io->ipsec_out_latch == NULL) &&
20312 		    (io->ipsec_out_use_global_policy)) {
20313 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
20314 			    ire, connp, unspec_src));
20315 		}
20316 		if (!io->ipsec_out_secure) {
20317 			/*
20318 			 * If this is not a secure packet, drop
20319 			 * the IPSEC_OUT mp and treat it as a clear
20320 			 * packet. This happens when we are sending
20321 			 * a ICMP reply back to a clear packet. See
20322 			 * ipsec_in_to_out() for details.
20323 			 */
20324 			mp = first_mp->b_cont;
20325 			freeb(first_mp);
20326 		}
20327 		return (mp);
20328 	}
20329 	/*
20330 	 * See whether we need to attach a global policy here. We
20331 	 * don't depend on the conn (as it could be null) for deciding
20332 	 * what policy this datagram should go through because it
20333 	 * should have happened in ip_wput if there was some
20334 	 * policy. This normally happens for connections which are not
20335 	 * fully bound preventing us from caching policies in
20336 	 * ip_bind. Packets coming from the TCP listener/global queue
20337 	 * - which are non-hard_bound - could also be affected by
20338 	 * applying policy here.
20339 	 *
20340 	 * If this packet is coming from tcp global queue or listener,
20341 	 * we will be applying policy here.  This may not be *right*
20342 	 * if these packets are coming from the detached connection as
20343 	 * it could have gone in clear before. This happens only if a
20344 	 * TCP connection started when there is no policy and somebody
20345 	 * added policy before it became detached. Thus packets of the
20346 	 * detached connection could go out secure and the other end
20347 	 * would drop it because it will be expecting in clear. The
20348 	 * converse is not true i.e if somebody starts a TCP
20349 	 * connection and deletes the policy, all the packets will
20350 	 * still go out with the policy that existed before deleting
20351 	 * because ip_unbind sends up policy information which is used
20352 	 * by TCP on subsequent ip_wputs. The right solution is to fix
20353 	 * TCP to attach a dummy IPSEC_OUT and set
20354 	 * ipsec_out_use_global_policy to B_FALSE. As this might
20355 	 * affect performance for normal cases, we are not doing it.
20356 	 * Thus, set policy before starting any TCP connections.
20357 	 *
20358 	 * NOTE - We might apply policy even for a hard bound connection
20359 	 * - for which we cached policy in ip_bind - if somebody added
20360 	 * global policy after we inherited the policy in ip_bind.
20361 	 * This means that the packets that were going out in clear
20362 	 * previously would start going secure and hence get dropped
20363 	 * on the other side. To fix this, TCP attaches a dummy
20364 	 * ipsec_out and make sure that we don't apply global policy.
20365 	 */
20366 	if (ipha != NULL)
20367 		policy_present = ipsec_outbound_v4_policy_present;
20368 	else
20369 		policy_present = ipsec_outbound_v6_policy_present;
20370 	if (!policy_present)
20371 		return (mp);
20372 
20373 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src));
20374 }
20375 
20376 ire_t *
20377 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
20378 {
20379 	ipaddr_t addr;
20380 	ire_t *save_ire;
20381 	irb_t *irb;
20382 	ill_group_t *illgrp;
20383 	int	err;
20384 
20385 	save_ire = ire;
20386 	addr = ire->ire_addr;
20387 
20388 	ASSERT(ire->ire_type == IRE_BROADCAST);
20389 
20390 	illgrp = connp->conn_outgoing_ill->ill_group;
20391 	if (illgrp == NULL) {
20392 		*conn_outgoing_ill = conn_get_held_ill(connp,
20393 		    &connp->conn_outgoing_ill, &err);
20394 		if (err == ILL_LOOKUP_FAILED) {
20395 			ire_refrele(save_ire);
20396 			return (NULL);
20397 		}
20398 		return (save_ire);
20399 	}
20400 	/*
20401 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
20402 	 * If it is part of the group, we need to send on the ire
20403 	 * that has been cleared of IRE_MARK_NORECV and that belongs
20404 	 * to this group. This is okay as IP_BOUND_IF really means
20405 	 * any ill in the group. We depend on the fact that the
20406 	 * first ire in the group is always cleared of IRE_MARK_NORECV
20407 	 * if such an ire exists. This is possible only if you have
20408 	 * at least one ill in the group that has not failed.
20409 	 *
20410 	 * First get to the ire that matches the address and group.
20411 	 *
20412 	 * We don't look for an ire with a matching zoneid because a given zone
20413 	 * won't always have broadcast ires on all ills in the group.
20414 	 */
20415 	irb = ire->ire_bucket;
20416 	rw_enter(&irb->irb_lock, RW_READER);
20417 	if (ire->ire_marks & IRE_MARK_NORECV) {
20418 		/*
20419 		 * If the current zone only has an ire broadcast for this
20420 		 * address marked NORECV, the ire we want is ahead in the
20421 		 * bucket, so we look it up deliberately ignoring the zoneid.
20422 		 */
20423 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
20424 			if (ire->ire_addr != addr)
20425 				continue;
20426 			/* skip over deleted ires */
20427 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
20428 				continue;
20429 		}
20430 	}
20431 	while (ire != NULL) {
20432 		/*
20433 		 * If a new interface is coming up, we could end up
20434 		 * seeing the loopback ire and the non-loopback ire
20435 		 * may not have been added yet. So check for ire_stq
20436 		 */
20437 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
20438 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
20439 			break;
20440 		}
20441 		ire = ire->ire_next;
20442 	}
20443 	if (ire != NULL && ire->ire_addr == addr &&
20444 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
20445 		IRE_REFHOLD(ire);
20446 		rw_exit(&irb->irb_lock);
20447 		ire_refrele(save_ire);
20448 		*conn_outgoing_ill = ire_to_ill(ire);
20449 		/*
20450 		 * Refhold the ill to make the conn_outgoing_ill
20451 		 * independent of the ire. ip_wput_ire goes in a loop
20452 		 * and may refrele the ire. Since we have an ire at this
20453 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
20454 		 */
20455 		ill_refhold(*conn_outgoing_ill);
20456 		return (ire);
20457 	}
20458 	rw_exit(&irb->irb_lock);
20459 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
20460 	/*
20461 	 * If we can't find a suitable ire, return the original ire.
20462 	 */
20463 	return (save_ire);
20464 }
20465 
20466 /*
20467  * This function does the ire_refrele of the ire passed in as the
20468  * argument. As this function looks up more ires i.e broadcast ires,
20469  * it needs to REFRELE them. Currently, for simplicity we don't
20470  * differentiate the one passed in and looked up here. We always
20471  * REFRELE.
20472  * IPQoS Notes:
20473  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
20474  * IPSec packets are done in ipsec_out_process.
20475  *
20476  */
20477 void
20478 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller)
20479 {
20480 	ipha_t		*ipha;
20481 #define	rptr	((uchar_t *)ipha)
20482 	mblk_t		*mp1;
20483 	queue_t		*stq;
20484 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
20485 	uint32_t	v_hlen_tos_len;
20486 	uint32_t	ttl_protocol;
20487 	ipaddr_t	src;
20488 	ipaddr_t	dst;
20489 	uint32_t	cksum;
20490 	ipaddr_t	orig_src;
20491 	ire_t		*ire1;
20492 	mblk_t		*next_mp;
20493 	uint_t		hlen;
20494 	uint16_t	*up;
20495 	uint32_t	max_frag = ire->ire_max_frag;
20496 	ill_t		*ill = ire_to_ill(ire);
20497 	int		clusterwide;
20498 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
20499 	int		ipsec_len;
20500 	mblk_t		*first_mp;
20501 	ipsec_out_t	*io;
20502 	boolean_t	conn_dontroute;		/* conn value for multicast */
20503 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
20504 	boolean_t	multicast_forward;	/* Should we forward ? */
20505 	boolean_t	unspec_src;
20506 	ill_t		*conn_outgoing_ill = NULL;
20507 	ill_t		*ire_ill;
20508 	ill_t		*ire1_ill;
20509 	uint32_t 	ill_index = 0;
20510 	boolean_t	multirt_send = B_FALSE;
20511 	int		err;
20512 	zoneid_t	zoneid;
20513 
20514 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
20515 	    "ip_wput_ire_start: q %p", q);
20516 
20517 	multicast_forward = B_FALSE;
20518 	unspec_src = (connp != NULL && connp->conn_unspec_src);
20519 
20520 	if (ire->ire_flags & RTF_MULTIRT) {
20521 		/*
20522 		 * Multirouting case. The bucket where ire is stored
20523 		 * probably holds other RTF_MULTIRT flagged ire
20524 		 * to the destination. In this call to ip_wput_ire,
20525 		 * we attempt to send the packet through all
20526 		 * those ires. Thus, we first ensure that ire is the
20527 		 * first RTF_MULTIRT ire in the bucket,
20528 		 * before walking the ire list.
20529 		 */
20530 		ire_t *first_ire;
20531 		irb_t *irb = ire->ire_bucket;
20532 		ASSERT(irb != NULL);
20533 
20534 		/* Make sure we do not omit any multiroute ire. */
20535 		IRB_REFHOLD(irb);
20536 		for (first_ire = irb->irb_ire;
20537 		    first_ire != NULL;
20538 		    first_ire = first_ire->ire_next) {
20539 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
20540 			    (first_ire->ire_addr == ire->ire_addr) &&
20541 			    !(first_ire->ire_marks &
20542 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
20543 				break;
20544 		}
20545 
20546 		if ((first_ire != NULL) && (first_ire != ire)) {
20547 			IRE_REFHOLD(first_ire);
20548 			ire_refrele(ire);
20549 			ire = first_ire;
20550 			ill = ire_to_ill(ire);
20551 		}
20552 		IRB_REFRELE(irb);
20553 	}
20554 
20555 	/*
20556 	 * conn_outgoing_ill is used only in the broadcast loop.
20557 	 * for performance we don't grab the mutexs in the fastpath
20558 	 */
20559 	if ((connp != NULL) &&
20560 	    (connp->conn_xmit_if_ill == NULL) &&
20561 	    (ire->ire_type == IRE_BROADCAST) &&
20562 	    ((connp->conn_nofailover_ill != NULL) ||
20563 	    (connp->conn_outgoing_ill != NULL))) {
20564 		/*
20565 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
20566 		 * option. So, see if this endpoint is bound to a
20567 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
20568 		 * that if the interface is failed, we will still send
20569 		 * the packet on the same ill which is what we want.
20570 		 */
20571 		conn_outgoing_ill = conn_get_held_ill(connp,
20572 		    &connp->conn_nofailover_ill, &err);
20573 		if (err == ILL_LOOKUP_FAILED) {
20574 			ire_refrele(ire);
20575 			freemsg(mp);
20576 			return;
20577 		}
20578 		if (conn_outgoing_ill == NULL) {
20579 			/*
20580 			 * Choose a good ill in the group to send the
20581 			 * packets on.
20582 			 */
20583 			ire = conn_set_outgoing_ill(connp, ire,
20584 			    &conn_outgoing_ill);
20585 			if (ire == NULL) {
20586 				freemsg(mp);
20587 				return;
20588 			}
20589 		}
20590 	}
20591 
20592 	if (mp->b_datap->db_type != M_CTL) {
20593 		ipha = (ipha_t *)mp->b_rptr;
20594 		zoneid = (connp != NULL ? connp->conn_zoneid : ALL_ZONES);
20595 	} else {
20596 		io = (ipsec_out_t *)mp->b_rptr;
20597 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20598 		zoneid = io->ipsec_out_zoneid;
20599 		ASSERT(zoneid != ALL_ZONES);
20600 		ipha = (ipha_t *)mp->b_cont->b_rptr;
20601 		dst = ipha->ipha_dst;
20602 		/*
20603 		 * For the multicast case, ipsec_out carries conn_dontroute and
20604 		 * conn_multicast_loop as conn may not be available here. We
20605 		 * need this for multicast loopback and forwarding which is done
20606 		 * later in the code.
20607 		 */
20608 		if (CLASSD(dst)) {
20609 			conn_dontroute = io->ipsec_out_dontroute;
20610 			conn_multicast_loop = io->ipsec_out_multicast_loop;
20611 			/*
20612 			 * If conn_dontroute is not set or conn_multicast_loop
20613 			 * is set, we need to do forwarding/loopback. For
20614 			 * datagrams from ip_wput_multicast, conn_dontroute is
20615 			 * set to B_TRUE and conn_multicast_loop is set to
20616 			 * B_FALSE so that we neither do forwarding nor
20617 			 * loopback.
20618 			 */
20619 			if (!conn_dontroute || conn_multicast_loop)
20620 				multicast_forward = B_TRUE;
20621 		}
20622 	}
20623 
20624 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
20625 	    ire->ire_zoneid != ALL_ZONES) {
20626 		/*
20627 		 * When a zone sends a packet to another zone, we try to deliver
20628 		 * the packet under the same conditions as if the destination
20629 		 * was a real node on the network. To do so, we look for a
20630 		 * matching route in the forwarding table.
20631 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
20632 		 * ip_newroute() does.
20633 		 */
20634 		ire_t *src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
20635 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
20636 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
20637 		if (src_ire != NULL &&
20638 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
20639 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
20640 				ipha->ipha_src = src_ire->ire_src_addr;
20641 			ire_refrele(src_ire);
20642 		} else {
20643 			ire_refrele(ire);
20644 			if (conn_outgoing_ill != NULL)
20645 				ill_refrele(conn_outgoing_ill);
20646 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
20647 			if (src_ire != NULL) {
20648 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
20649 					ire_refrele(src_ire);
20650 					freemsg(mp);
20651 					return;
20652 				}
20653 				ire_refrele(src_ire);
20654 			}
20655 			if (ip_hdr_complete(ipha, zoneid)) {
20656 				/* Failed */
20657 				freemsg(mp);
20658 				return;
20659 			}
20660 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE);
20661 			return;
20662 		}
20663 	}
20664 
20665 	if (mp->b_datap->db_type == M_CTL ||
20666 	    ipsec_outbound_v4_policy_present) {
20667 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
20668 		    unspec_src);
20669 		if (mp == NULL) {
20670 			ire_refrele(ire);
20671 			if (conn_outgoing_ill != NULL)
20672 				ill_refrele(conn_outgoing_ill);
20673 			return;
20674 		}
20675 	}
20676 
20677 	first_mp = mp;
20678 	ipsec_len = 0;
20679 
20680 	if (first_mp->b_datap->db_type == M_CTL) {
20681 		io = (ipsec_out_t *)first_mp->b_rptr;
20682 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
20683 		mp = first_mp->b_cont;
20684 		ipsec_len = ipsec_out_extra_length(first_mp);
20685 		ASSERT(ipsec_len >= 0);
20686 		zoneid = io->ipsec_out_zoneid;
20687 		ASSERT(zoneid != ALL_ZONES);
20688 
20689 		/*
20690 		 * Drop M_CTL here if IPsec processing is not needed.
20691 		 * (Non-IPsec use of M_CTL extracted any information it
20692 		 * needed above).
20693 		 */
20694 		if (ipsec_len == 0) {
20695 			freeb(first_mp);
20696 			first_mp = mp;
20697 		}
20698 	}
20699 
20700 	/*
20701 	 * Fast path for ip_wput_ire
20702 	 */
20703 
20704 	ipha = (ipha_t *)mp->b_rptr;
20705 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20706 	dst = ipha->ipha_dst;
20707 
20708 	/*
20709 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
20710 	 * if the socket is a SOCK_RAW type. The transport checksum should
20711 	 * be provided in the pre-built packet, so we don't need to compute it.
20712 	 * Also, other application set flags, like DF, should not be altered.
20713 	 * Other transport MUST pass down zero.
20714 	 */
20715 	ip_hdr_included = ipha->ipha_ident;
20716 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
20717 
20718 	if (CLASSD(dst)) {
20719 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
20720 		    ntohl(dst),
20721 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
20722 		    ntohl(ire->ire_addr)));
20723 	}
20724 
20725 /* Macros to extract header fields from data already in registers */
20726 #ifdef	_BIG_ENDIAN
20727 #define	V_HLEN	(v_hlen_tos_len >> 24)
20728 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
20729 #define	PROTO	(ttl_protocol & 0xFF)
20730 #else
20731 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20732 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
20733 #define	PROTO	(ttl_protocol >> 8)
20734 #endif
20735 
20736 
20737 	orig_src = src = ipha->ipha_src;
20738 	/* (The loop back to "another" is explained down below.) */
20739 another:;
20740 	/*
20741 	 * Assign an ident value for this packet.  We assign idents on
20742 	 * a per destination basis out of the IRE.  There could be
20743 	 * other threads targeting the same destination, so we have to
20744 	 * arrange for a atomic increment.  Note that we use a 32-bit
20745 	 * atomic add because it has better performance than its
20746 	 * 16-bit sibling.
20747 	 *
20748 	 * If running in cluster mode and if the source address
20749 	 * belongs to a replicated service then vector through
20750 	 * cl_inet_ipident vector to allocate ip identifier
20751 	 * NOTE: This is a contract private interface with the
20752 	 * clustering group.
20753 	 */
20754 	clusterwide = 0;
20755 	if (cl_inet_ipident) {
20756 		ASSERT(cl_inet_isclusterwide);
20757 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20758 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
20759 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
20760 			    AF_INET, (uint8_t *)(uintptr_t)src,
20761 			    (uint8_t *)(uintptr_t)dst);
20762 			clusterwide = 1;
20763 		}
20764 	}
20765 	if (!clusterwide) {
20766 		ipha->ipha_ident =
20767 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
20768 	}
20769 
20770 #ifndef _BIG_ENDIAN
20771 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
20772 #endif
20773 
20774 	/*
20775 	 * Set source address unless sent on an ill or conn_unspec_src is set.
20776 	 * This is needed to obey conn_unspec_src when packets go through
20777 	 * ip_newroute + arp.
20778 	 * Assumes ip_newroute{,_multi} sets the source address as well.
20779 	 */
20780 	if (src == INADDR_ANY && !unspec_src) {
20781 		/*
20782 		 * Assign the appropriate source address from the IRE if none
20783 		 * was specified.
20784 		 */
20785 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
20786 
20787 		/*
20788 		 * With IP multipathing, broadcast packets are sent on the ire
20789 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
20790 		 * the group. However, this ire might not be in the same zone so
20791 		 * we can't always use its source address. We look for a
20792 		 * broadcast ire in the same group and in the right zone.
20793 		 */
20794 		if (ire->ire_type == IRE_BROADCAST &&
20795 		    ire->ire_zoneid != zoneid) {
20796 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
20797 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
20798 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
20799 			if (src_ire != NULL) {
20800 				src = src_ire->ire_src_addr;
20801 				ire_refrele(src_ire);
20802 			} else {
20803 				ire_refrele(ire);
20804 				if (conn_outgoing_ill != NULL)
20805 					ill_refrele(conn_outgoing_ill);
20806 				freemsg(first_mp);
20807 				BUMP_MIB(&ip_mib, ipOutDiscards);
20808 				return;
20809 			}
20810 		} else {
20811 			src = ire->ire_src_addr;
20812 		}
20813 
20814 		if (connp == NULL) {
20815 			ip1dbg(("ip_wput_ire: no connp and no src "
20816 			    "address for dst 0x%x, using src 0x%x\n",
20817 			    ntohl(dst),
20818 			    ntohl(src)));
20819 		}
20820 		ipha->ipha_src = src;
20821 	}
20822 	stq = ire->ire_stq;
20823 
20824 	/*
20825 	 * We only allow ire chains for broadcasts since there will
20826 	 * be multiple IRE_CACHE entries for the same multicast
20827 	 * address (one per ipif).
20828 	 */
20829 	next_mp = NULL;
20830 
20831 	/* broadcast packet */
20832 	if (ire->ire_type == IRE_BROADCAST)
20833 		goto broadcast;
20834 
20835 	/* loopback ? */
20836 	if (stq == NULL)
20837 		goto nullstq;
20838 
20839 	/* The ill_index for outbound ILL */
20840 	ill_index = Q_TO_INDEX(stq);
20841 
20842 	BUMP_MIB(&ip_mib, ipOutRequests);
20843 	ttl_protocol = ((uint16_t *)ipha)[4];
20844 
20845 	/* pseudo checksum (do it in parts for IP header checksum) */
20846 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
20847 
20848 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
20849 		queue_t *dev_q = stq->q_next;
20850 
20851 		/* flow controlled */
20852 		if ((dev_q->q_next || dev_q->q_first) &&
20853 		    !canput(dev_q))
20854 			goto blocked;
20855 		if ((PROTO == IPPROTO_UDP) &&
20856 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
20857 			hlen = (V_HLEN & 0xF) << 2;
20858 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
20859 			if (*up != 0) {
20860 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
20861 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
20862 				/* Software checksum? */
20863 				if (DB_CKSUMFLAGS(mp) == 0) {
20864 					IP_STAT(ip_out_sw_cksum);
20865 					IP_STAT_UPDATE(
20866 					    ip_udp_out_sw_cksum_bytes,
20867 					    LENGTH - hlen);
20868 				}
20869 			}
20870 		}
20871 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
20872 		hlen = (V_HLEN & 0xF) << 2;
20873 		if (PROTO == IPPROTO_TCP) {
20874 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
20875 			/*
20876 			 * The packet header is processed once and for all, even
20877 			 * in the multirouting case. We disable hardware
20878 			 * checksum if the packet is multirouted, as it will be
20879 			 * replicated via several interfaces, and not all of
20880 			 * them may have this capability.
20881 			 */
20882 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
20883 			    LENGTH, max_frag, ipsec_len, cksum);
20884 			/* Software checksum? */
20885 			if (DB_CKSUMFLAGS(mp) == 0) {
20886 				IP_STAT(ip_out_sw_cksum);
20887 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
20888 				    LENGTH - hlen);
20889 			}
20890 		} else {
20891 			sctp_hdr_t	*sctph;
20892 
20893 			ASSERT(PROTO == IPPROTO_SCTP);
20894 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
20895 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
20896 			/*
20897 			 * Zero out the checksum field to ensure proper
20898 			 * checksum calculation.
20899 			 */
20900 			sctph->sh_chksum = 0;
20901 #ifdef	DEBUG
20902 			if (!skip_sctp_cksum)
20903 #endif
20904 				sctph->sh_chksum = sctp_cksum(mp, hlen);
20905 		}
20906 	}
20907 
20908 	/*
20909 	 * If this is a multicast packet and originated from ip_wput
20910 	 * we need to do loopback and forwarding checks. If it comes
20911 	 * from ip_wput_multicast, we SHOULD not do this.
20912 	 */
20913 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
20914 
20915 	/* checksum */
20916 	cksum += ttl_protocol;
20917 
20918 	/* fragment the packet */
20919 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
20920 		goto fragmentit;
20921 	/*
20922 	 * Don't use frag_flag if packet is pre-built or source
20923 	 * routed or if multicast (since multicast packets do
20924 	 * not solicit ICMP "packet too big" messages).
20925 	 */
20926 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
20927 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
20928 	    !ip_source_route_included(ipha)) &&
20929 	    !CLASSD(ipha->ipha_dst))
20930 		ipha->ipha_fragment_offset_and_flags |=
20931 		    htons(ire->ire_frag_flag);
20932 
20933 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
20934 		/* calculate IP header checksum */
20935 		cksum += ipha->ipha_ident;
20936 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
20937 		cksum += ipha->ipha_fragment_offset_and_flags;
20938 
20939 		/* IP options present */
20940 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
20941 		if (hlen)
20942 			goto checksumoptions;
20943 
20944 		/* calculate hdr checksum */
20945 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
20946 		cksum = ~(cksum + (cksum >> 16));
20947 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
20948 	}
20949 	if (ipsec_len != 0) {
20950 		/*
20951 		 * We will do the rest of the processing after
20952 		 * we come back from IPSEC in ip_wput_ipsec_out().
20953 		 */
20954 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
20955 
20956 		io = (ipsec_out_t *)first_mp->b_rptr;
20957 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
20958 				ill_phyint->phyint_ifindex;
20959 
20960 		ipsec_out_process(q, first_mp, ire, ill_index);
20961 		ire_refrele(ire);
20962 		if (conn_outgoing_ill != NULL)
20963 			ill_refrele(conn_outgoing_ill);
20964 		return;
20965 	}
20966 
20967 	/*
20968 	 * In most cases, the emission loop below is entered only
20969 	 * once. Only in the case where the ire holds the
20970 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
20971 	 * flagged ires in the bucket, and send the packet
20972 	 * through all crossed RTF_MULTIRT routes.
20973 	 */
20974 	if (ire->ire_flags & RTF_MULTIRT) {
20975 		multirt_send = B_TRUE;
20976 	}
20977 	do {
20978 		if (multirt_send) {
20979 			irb_t *irb;
20980 			/*
20981 			 * We are in a multiple send case, need to get
20982 			 * the next ire and make a duplicate of the packet.
20983 			 * ire1 holds here the next ire to process in the
20984 			 * bucket. If multirouting is expected,
20985 			 * any non-RTF_MULTIRT ire that has the
20986 			 * right destination address is ignored.
20987 			 */
20988 			irb = ire->ire_bucket;
20989 			ASSERT(irb != NULL);
20990 
20991 			IRB_REFHOLD(irb);
20992 			for (ire1 = ire->ire_next;
20993 			    ire1 != NULL;
20994 			    ire1 = ire1->ire_next) {
20995 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
20996 					continue;
20997 				if (ire1->ire_addr != ire->ire_addr)
20998 					continue;
20999 				if (ire1->ire_marks &
21000 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21001 					continue;
21002 
21003 				/* Got one */
21004 				IRE_REFHOLD(ire1);
21005 				break;
21006 			}
21007 			IRB_REFRELE(irb);
21008 
21009 			if (ire1 != NULL) {
21010 				next_mp = copyb(mp);
21011 				if ((next_mp == NULL) ||
21012 				    ((mp->b_cont != NULL) &&
21013 				    ((next_mp->b_cont =
21014 				    dupmsg(mp->b_cont)) == NULL))) {
21015 					freemsg(next_mp);
21016 					next_mp = NULL;
21017 					ire_refrele(ire1);
21018 					ire1 = NULL;
21019 				}
21020 			}
21021 
21022 			/* Last multiroute ire; don't loop anymore. */
21023 			if (ire1 == NULL) {
21024 				multirt_send = B_FALSE;
21025 			}
21026 		}
21027 		mp = ip_wput_attach_llhdr(mp, ire, IPP_LOCAL_OUT, ill_index);
21028 		if (mp == NULL) {
21029 			BUMP_MIB(&ip_mib, ipOutDiscards);
21030 			ip2dbg(("ip_wput_ire: fastpath wput pkt dropped "\
21031 			    "during IPPF processing\n"));
21032 			ire_refrele(ire);
21033 			if (next_mp != NULL) {
21034 				freemsg(next_mp);
21035 				ire_refrele(ire1);
21036 			}
21037 			if (conn_outgoing_ill != NULL)
21038 				ill_refrele(conn_outgoing_ill);
21039 			return;
21040 		}
21041 		UPDATE_OB_PKT_COUNT(ire);
21042 		ire->ire_last_used_time = lbolt;
21043 
21044 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21045 		    "ip_wput_ire_end: q %p (%S)",
21046 		    q, "last copy out");
21047 		putnext(stq, mp);
21048 		IRE_REFRELE(ire);
21049 
21050 		if (multirt_send) {
21051 			ASSERT(ire1);
21052 			/*
21053 			 * Proceed with the next RTF_MULTIRT ire,
21054 			 * Also set up the send-to queue accordingly.
21055 			 */
21056 			ire = ire1;
21057 			ire1 = NULL;
21058 			stq = ire->ire_stq;
21059 			mp = next_mp;
21060 			next_mp = NULL;
21061 			ipha = (ipha_t *)mp->b_rptr;
21062 			ill_index = Q_TO_INDEX(stq);
21063 		}
21064 	} while (multirt_send);
21065 	if (conn_outgoing_ill != NULL)
21066 		ill_refrele(conn_outgoing_ill);
21067 	return;
21068 
21069 	/*
21070 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21071 	 */
21072 broadcast:
21073 	{
21074 		/*
21075 		 * Avoid broadcast storms by setting the ttl to 1
21076 		 * for broadcasts. This parameter can be set
21077 		 * via ndd, so make sure that for the SO_DONTROUTE
21078 		 * case that ipha_ttl is always set to 1.
21079 		 * In the event that we are replying to incoming
21080 		 * ICMP packets, conn could be NULL.
21081 		 */
21082 		if ((connp != NULL) && connp->conn_dontroute)
21083 			ipha->ipha_ttl = 1;
21084 		else
21085 			ipha->ipha_ttl = ip_broadcast_ttl;
21086 
21087 		/*
21088 		 * Note that we are not doing a IRB_REFHOLD here.
21089 		 * Actually we don't care if the list changes i.e
21090 		 * if somebody deletes an IRE from the list while
21091 		 * we drop the lock, the next time we come around
21092 		 * ire_next will be NULL and hence we won't send
21093 		 * out multiple copies which is fine.
21094 		 */
21095 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
21096 		ire1 = ire->ire_next;
21097 		if (conn_outgoing_ill != NULL) {
21098 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
21099 				ASSERT(ire1 == ire->ire_next);
21100 				if (ire1 != NULL && ire1->ire_addr == dst) {
21101 					ire_refrele(ire);
21102 					ire = ire1;
21103 					IRE_REFHOLD(ire);
21104 					ire1 = ire->ire_next;
21105 					continue;
21106 				}
21107 				rw_exit(&ire->ire_bucket->irb_lock);
21108 				/* Did not find a matching ill */
21109 				ip1dbg(("ip_wput_ire: broadcast with no "
21110 				    "matching IP_BOUND_IF ill %s\n",
21111 				    conn_outgoing_ill->ill_name));
21112 				freemsg(first_mp);
21113 				if (ire != NULL)
21114 					ire_refrele(ire);
21115 				ill_refrele(conn_outgoing_ill);
21116 				return;
21117 			}
21118 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
21119 			/*
21120 			 * If the next IRE has the same address and is not one
21121 			 * of the two copies that we need to send, try to see
21122 			 * whether this copy should be sent at all. This
21123 			 * assumes that we insert loopbacks first and then
21124 			 * non-loopbacks. This is acheived by inserting the
21125 			 * loopback always before non-loopback.
21126 			 * This is used to send a single copy of a broadcast
21127 			 * packet out all physical interfaces that have an
21128 			 * matching IRE_BROADCAST while also looping
21129 			 * back one copy (to ip_wput_local) for each
21130 			 * matching physical interface. However, we avoid
21131 			 * sending packets out different logical that match by
21132 			 * having ipif_up/ipif_down supress duplicate
21133 			 * IRE_BROADCASTS.
21134 			 *
21135 			 * This feature is currently used to get broadcasts
21136 			 * sent to multiple interfaces, when the broadcast
21137 			 * address being used applies to multiple interfaces.
21138 			 * For example, a whole net broadcast will be
21139 			 * replicated on every connected subnet of
21140 			 * the target net.
21141 			 *
21142 			 * Each zone has its own set of IRE_BROADCASTs, so that
21143 			 * we're able to distribute inbound packets to multiple
21144 			 * zones who share a broadcast address. We avoid looping
21145 			 * back outbound packets in different zones but on the
21146 			 * same ill, as the application would see duplicates.
21147 			 *
21148 			 * If the interfaces are part of the same group,
21149 			 * we would want to send only one copy out for
21150 			 * whole group.
21151 			 *
21152 			 * This logic assumes that ire_add_v4() groups the
21153 			 * IRE_BROADCAST entries so that those with the same
21154 			 * ire_addr and ill_group are kept together.
21155 			 */
21156 			ire_ill = ire->ire_ipif->ipif_ill;
21157 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
21158 				if (ire_ill->ill_group != NULL &&
21159 				    (ire->ire_marks & IRE_MARK_NORECV)) {
21160 					/*
21161 					 * If the current zone only has an ire
21162 					 * broadcast for this address marked
21163 					 * NORECV, the ire we want is ahead in
21164 					 * the bucket, so we look it up
21165 					 * deliberately ignoring the zoneid.
21166 					 */
21167 					for (ire1 = ire->ire_bucket->irb_ire;
21168 					    ire1 != NULL;
21169 					    ire1 = ire1->ire_next) {
21170 						ire1_ill =
21171 						    ire1->ire_ipif->ipif_ill;
21172 						if (ire1->ire_addr != dst)
21173 							continue;
21174 						/* skip over the current ire */
21175 						if (ire1 == ire)
21176 							continue;
21177 						/* skip over deleted ires */
21178 						if (ire1->ire_marks &
21179 						    IRE_MARK_CONDEMNED)
21180 							continue;
21181 						/*
21182 						 * non-loopback ire in our
21183 						 * group: use it for the next
21184 						 * pass in the loop
21185 						 */
21186 						if (ire1->ire_stq != NULL &&
21187 						    ire1_ill->ill_group ==
21188 						    ire_ill->ill_group)
21189 							break;
21190 					}
21191 				}
21192 			} else {
21193 				while (ire1 != NULL && ire1->ire_addr == dst) {
21194 					ire1_ill = ire1->ire_ipif->ipif_ill;
21195 					/*
21196 					 * We can have two broadcast ires on the
21197 					 * same ill in different zones; here
21198 					 * we'll send a copy of the packet on
21199 					 * each ill and the fanout code will
21200 					 * call conn_wantpacket() to check that
21201 					 * the zone has the broadcast address
21202 					 * configured on the ill. If the two
21203 					 * ires are in the same group we only
21204 					 * send one copy up.
21205 					 */
21206 					if (ire1_ill != ire_ill &&
21207 					    (ire1_ill->ill_group == NULL ||
21208 					    ire_ill->ill_group == NULL ||
21209 					    ire1_ill->ill_group !=
21210 					    ire_ill->ill_group)) {
21211 						break;
21212 					}
21213 					ire1 = ire1->ire_next;
21214 				}
21215 			}
21216 		}
21217 		ASSERT(multirt_send == B_FALSE);
21218 		if (ire1 != NULL && ire1->ire_addr == dst) {
21219 			if ((ire->ire_flags & RTF_MULTIRT) &&
21220 			    (ire1->ire_flags & RTF_MULTIRT)) {
21221 				/*
21222 				 * We are in the multirouting case.
21223 				 * The message must be sent at least
21224 				 * on both ires. These ires have been
21225 				 * inserted AFTER the standard ones
21226 				 * in ip_rt_add(). There are thus no
21227 				 * other ire entries for the destination
21228 				 * address in the rest of the bucket
21229 				 * that do not have the RTF_MULTIRT
21230 				 * flag. We don't process a copy
21231 				 * of the message here. This will be
21232 				 * done in the final sending loop.
21233 				 */
21234 				multirt_send = B_TRUE;
21235 			} else {
21236 				next_mp = ip_copymsg(first_mp);
21237 				if (next_mp != NULL)
21238 					IRE_REFHOLD(ire1);
21239 			}
21240 		}
21241 		rw_exit(&ire->ire_bucket->irb_lock);
21242 	}
21243 
21244 	if (stq) {
21245 		/*
21246 		 * A non-NULL send-to queue means this packet is going
21247 		 * out of this machine.
21248 		 */
21249 
21250 		BUMP_MIB(&ip_mib, ipOutRequests);
21251 		ttl_protocol = ((uint16_t *)ipha)[4];
21252 		/*
21253 		 * We accumulate the pseudo header checksum in cksum.
21254 		 * This is pretty hairy code, so watch close.  One
21255 		 * thing to keep in mind is that UDP and TCP have
21256 		 * stored their respective datagram lengths in their
21257 		 * checksum fields.  This lines things up real nice.
21258 		 */
21259 		cksum = (dst >> 16) + (dst & 0xFFFF) +
21260 		    (src >> 16) + (src & 0xFFFF);
21261 		/*
21262 		 * We assume the udp checksum field contains the
21263 		 * length, so to compute the pseudo header checksum,
21264 		 * all we need is the protocol number and src/dst.
21265 		 */
21266 		/* Provide the checksums for UDP and TCP. */
21267 		if ((PROTO == IPPROTO_TCP) &&
21268 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21269 			/* hlen gets the number of uchar_ts in the IP header */
21270 			hlen = (V_HLEN & 0xF) << 2;
21271 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21272 			IP_STAT(ip_out_sw_cksum);
21273 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21274 			    LENGTH - hlen);
21275 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
21276 			if (*up == 0)
21277 				*up = 0xFFFF;
21278 		} else if (PROTO == IPPROTO_SCTP &&
21279 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21280 			sctp_hdr_t	*sctph;
21281 
21282 			hlen = (V_HLEN & 0xF) << 2;
21283 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21284 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21285 			sctph->sh_chksum = 0;
21286 #ifdef	DEBUG
21287 			if (!skip_sctp_cksum)
21288 #endif
21289 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21290 		} else {
21291 			queue_t *dev_q = stq->q_next;
21292 
21293 			if ((dev_q->q_next || dev_q->q_first) &&
21294 			    !canput(dev_q)) {
21295 			    blocked:
21296 				ipha->ipha_ident = ip_hdr_included;
21297 				/*
21298 				 * If we don't have a conn to apply
21299 				 * backpressure, free the message.
21300 				 * In the ire_send path, we don't know
21301 				 * the position to requeue the packet. Rather
21302 				 * than reorder packets, we just drop this
21303 				 * packet.
21304 				 */
21305 				if (ip_output_queue && connp != NULL &&
21306 				    caller != IRE_SEND) {
21307 					if (caller == IP_WSRV) {
21308 						connp->conn_did_putbq = 1;
21309 						(void) putbq(connp->conn_wq,
21310 						    first_mp);
21311 						conn_drain_insert(connp);
21312 						/*
21313 						 * This is the service thread,
21314 						 * and the queue is already
21315 						 * noenabled. The check for
21316 						 * canput and the putbq is not
21317 						 * atomic. So we need to check
21318 						 * again.
21319 						 */
21320 						if (canput(stq->q_next))
21321 							connp->conn_did_putbq
21322 							    = 0;
21323 						IP_STAT(ip_conn_flputbq);
21324 					} else {
21325 						/*
21326 						 * We are not the service proc.
21327 						 * ip_wsrv will be scheduled or
21328 						 * is already running.
21329 						 */
21330 						(void) putq(connp->conn_wq,
21331 						    first_mp);
21332 					}
21333 				} else {
21334 					BUMP_MIB(&ip_mib, ipOutDiscards);
21335 					freemsg(first_mp);
21336 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21337 					    "ip_wput_ire_end: q %p (%S)",
21338 					    q, "discard");
21339 				}
21340 				ire_refrele(ire);
21341 				if (next_mp) {
21342 					ire_refrele(ire1);
21343 					freemsg(next_mp);
21344 				}
21345 				if (conn_outgoing_ill != NULL)
21346 					ill_refrele(conn_outgoing_ill);
21347 				return;
21348 			}
21349 			if ((PROTO == IPPROTO_UDP) &&
21350 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
21351 				/*
21352 				 * hlen gets the number of uchar_ts in the
21353 				 * IP header
21354 				 */
21355 				hlen = (V_HLEN & 0xF) << 2;
21356 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21357 				max_frag = ire->ire_max_frag;
21358 				if (*up != 0) {
21359 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
21360 					    up, PROTO, hlen, LENGTH, max_frag,
21361 					    ipsec_len, cksum);
21362 					/* Software checksum? */
21363 					if (DB_CKSUMFLAGS(mp) == 0) {
21364 						IP_STAT(ip_out_sw_cksum);
21365 						IP_STAT_UPDATE(
21366 						    ip_udp_out_sw_cksum_bytes,
21367 						    LENGTH - hlen);
21368 					}
21369 				}
21370 			}
21371 		}
21372 		/*
21373 		 * Need to do this even when fragmenting. The local
21374 		 * loopback can be done without computing checksums
21375 		 * but forwarding out other interface must be done
21376 		 * after the IP checksum (and ULP checksums) have been
21377 		 * computed.
21378 		 *
21379 		 * NOTE : multicast_forward is set only if this packet
21380 		 * originated from ip_wput. For packets originating from
21381 		 * ip_wput_multicast, it is not set.
21382 		 */
21383 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
21384 		    multi_loopback:
21385 			ip2dbg(("ip_wput: multicast, loop %d\n",
21386 			    conn_multicast_loop));
21387 
21388 			/*  Forget header checksum offload */
21389 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
21390 
21391 			/*
21392 			 * Local loopback of multicasts?  Check the
21393 			 * ill.
21394 			 *
21395 			 * Note that the loopback function will not come
21396 			 * in through ip_rput - it will only do the
21397 			 * client fanout thus we need to do an mforward
21398 			 * as well.  The is different from the BSD
21399 			 * logic.
21400 			 */
21401 			if (ill != NULL) {
21402 				ilm_t	*ilm;
21403 
21404 				ILM_WALKER_HOLD(ill);
21405 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
21406 				    ALL_ZONES);
21407 				ILM_WALKER_RELE(ill);
21408 				if (ilm != NULL) {
21409 					/*
21410 					 * Pass along the virtual output q.
21411 					 * ip_wput_local() will distribute the
21412 					 * packet to all the matching zones,
21413 					 * except the sending zone when
21414 					 * IP_MULTICAST_LOOP is false.
21415 					 */
21416 					ip_multicast_loopback(q, ill, first_mp,
21417 					    conn_multicast_loop ? 0 :
21418 					    IP_FF_NO_MCAST_LOOP, zoneid);
21419 				}
21420 			}
21421 			if (ipha->ipha_ttl == 0) {
21422 				/*
21423 				 * 0 => only to this host i.e. we are
21424 				 * done. We are also done if this was the
21425 				 * loopback interface since it is sufficient
21426 				 * to loopback one copy of a multicast packet.
21427 				 */
21428 				freemsg(first_mp);
21429 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21430 				    "ip_wput_ire_end: q %p (%S)",
21431 				    q, "loopback");
21432 				ire_refrele(ire);
21433 				if (conn_outgoing_ill != NULL)
21434 					ill_refrele(conn_outgoing_ill);
21435 				return;
21436 			}
21437 			/*
21438 			 * ILLF_MULTICAST is checked in ip_newroute
21439 			 * i.e. we don't need to check it here since
21440 			 * all IRE_CACHEs come from ip_newroute.
21441 			 * For multicast traffic, SO_DONTROUTE is interpreted
21442 			 * to mean only send the packet out the interface
21443 			 * (optionally specified with IP_MULTICAST_IF)
21444 			 * and do not forward it out additional interfaces.
21445 			 * RSVP and the rsvp daemon is an example of a
21446 			 * protocol and user level process that
21447 			 * handles it's own routing. Hence, it uses the
21448 			 * SO_DONTROUTE option to accomplish this.
21449 			 */
21450 
21451 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
21452 				/* Unconditionally redo the checksum */
21453 				ipha->ipha_hdr_checksum = 0;
21454 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
21455 
21456 				/*
21457 				 * If this needs to go out secure, we need
21458 				 * to wait till we finish the IPSEC
21459 				 * processing.
21460 				 */
21461 				if (ipsec_len == 0 &&
21462 				    ip_mforward(ill, ipha, mp)) {
21463 					freemsg(first_mp);
21464 					ip1dbg(("ip_wput: mforward failed\n"));
21465 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21466 					    "ip_wput_ire_end: q %p (%S)",
21467 					    q, "mforward failed");
21468 					ire_refrele(ire);
21469 					if (conn_outgoing_ill != NULL)
21470 						ill_refrele(conn_outgoing_ill);
21471 					return;
21472 				}
21473 			}
21474 		}
21475 		max_frag = ire->ire_max_frag;
21476 		cksum += ttl_protocol;
21477 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
21478 			/* No fragmentation required for this one. */
21479 			/*
21480 			 * Don't use frag_flag if packet is pre-built or source
21481 			 * routed or if multicast (since multicast packets do
21482 			 * not solicit ICMP "packet too big" messages).
21483 			 */
21484 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21485 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21486 			    !ip_source_route_included(ipha)) &&
21487 			    !CLASSD(ipha->ipha_dst))
21488 				ipha->ipha_fragment_offset_and_flags |=
21489 				    htons(ire->ire_frag_flag);
21490 
21491 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21492 				/* Complete the IP header checksum. */
21493 				cksum += ipha->ipha_ident;
21494 				cksum += (v_hlen_tos_len >> 16)+
21495 				    (v_hlen_tos_len & 0xFFFF);
21496 				cksum += ipha->ipha_fragment_offset_and_flags;
21497 				hlen = (V_HLEN & 0xF) -
21498 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21499 				if (hlen) {
21500 				    checksumoptions:
21501 					/*
21502 					 * Account for the IP Options in the IP
21503 					 * header checksum.
21504 					 */
21505 					up = (uint16_t *)(rptr+
21506 					    IP_SIMPLE_HDR_LENGTH);
21507 					do {
21508 						cksum += up[0];
21509 						cksum += up[1];
21510 						up += 2;
21511 					} while (--hlen);
21512 				}
21513 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21514 				cksum = ~(cksum + (cksum >> 16));
21515 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
21516 			}
21517 			if (ipsec_len != 0) {
21518 				ipsec_out_process(q, first_mp, ire, ill_index);
21519 				if (!next_mp) {
21520 					ire_refrele(ire);
21521 					if (conn_outgoing_ill != NULL)
21522 						ill_refrele(conn_outgoing_ill);
21523 					return;
21524 				}
21525 				goto next;
21526 			}
21527 
21528 			/*
21529 			 * multirt_send has already been handled
21530 			 * for broadcast, but not yet for multicast
21531 			 * or IP options.
21532 			 */
21533 			if (next_mp == NULL) {
21534 				if (ire->ire_flags & RTF_MULTIRT) {
21535 					multirt_send = B_TRUE;
21536 				}
21537 			}
21538 
21539 			/*
21540 			 * In most cases, the emission loop below is
21541 			 * entered only once. Only in the case where
21542 			 * the ire holds the RTF_MULTIRT flag, do we loop
21543 			 * to process all RTF_MULTIRT ires in the bucket,
21544 			 * and send the packet through all crossed
21545 			 * RTF_MULTIRT routes.
21546 			 */
21547 			do {
21548 				if (multirt_send) {
21549 					irb_t *irb;
21550 
21551 					irb = ire->ire_bucket;
21552 					ASSERT(irb != NULL);
21553 					/*
21554 					 * We are in a multiple send case,
21555 					 * need to get the next IRE and make
21556 					 * a duplicate of the packet.
21557 					 */
21558 					IRB_REFHOLD(irb);
21559 					for (ire1 = ire->ire_next;
21560 					    ire1 != NULL;
21561 					    ire1 = ire1->ire_next) {
21562 						if (!(ire1->ire_flags &
21563 						    RTF_MULTIRT))
21564 							continue;
21565 						if (ire1->ire_addr !=
21566 						    ire->ire_addr)
21567 							continue;
21568 						if (ire1->ire_marks &
21569 						    (IRE_MARK_CONDEMNED|
21570 							IRE_MARK_HIDDEN))
21571 							continue;
21572 
21573 						/* Got one */
21574 						IRE_REFHOLD(ire1);
21575 						break;
21576 					}
21577 					IRB_REFRELE(irb);
21578 
21579 					if (ire1 != NULL) {
21580 						next_mp = copyb(mp);
21581 						if ((next_mp == NULL) ||
21582 						    ((mp->b_cont != NULL) &&
21583 						    ((next_mp->b_cont =
21584 						    dupmsg(mp->b_cont))
21585 						    == NULL))) {
21586 							freemsg(next_mp);
21587 							next_mp = NULL;
21588 							ire_refrele(ire1);
21589 							ire1 = NULL;
21590 						}
21591 					}
21592 
21593 					/*
21594 					 * Last multiroute ire; don't loop
21595 					 * anymore. The emission is over
21596 					 * and next_mp is NULL.
21597 					 */
21598 					if (ire1 == NULL) {
21599 						multirt_send = B_FALSE;
21600 					}
21601 				}
21602 
21603 				ASSERT(ipsec_len == 0);
21604 				mp1 = ip_wput_attach_llhdr(mp, ire,
21605 				    IPP_LOCAL_OUT, ill_index);
21606 				if (mp1 == NULL) {
21607 					BUMP_MIB(&ip_mib, ipOutDiscards);
21608 					if (next_mp) {
21609 						freemsg(next_mp);
21610 						ire_refrele(ire1);
21611 					}
21612 					ire_refrele(ire);
21613 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21614 					    "ip_wput_ire_end: q %p (%S)",
21615 					    q, "discard MDATA");
21616 					if (conn_outgoing_ill != NULL)
21617 						ill_refrele(conn_outgoing_ill);
21618 					return;
21619 				}
21620 				UPDATE_OB_PKT_COUNT(ire);
21621 				ire->ire_last_used_time = lbolt;
21622 
21623 				if (multirt_send) {
21624 					/*
21625 					 * We are in a multiple send case,
21626 					 * need to re-enter the sending loop
21627 					 * using the next ire.
21628 					 */
21629 					putnext(stq, mp1);
21630 					ire_refrele(ire);
21631 					ire = ire1;
21632 					stq = ire->ire_stq;
21633 					mp = next_mp;
21634 					next_mp = NULL;
21635 					ipha = (ipha_t *)mp->b_rptr;
21636 					ill_index = Q_TO_INDEX(stq);
21637 				}
21638 			} while (multirt_send);
21639 
21640 			if (!next_mp) {
21641 				/*
21642 				 * Last copy going out (the ultra-common
21643 				 * case).  Note that we intentionally replicate
21644 				 * the putnext rather than calling it before
21645 				 * the next_mp check in hopes of a little
21646 				 * tail-call action out of the compiler.
21647 				 */
21648 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21649 				    "ip_wput_ire_end: q %p (%S)",
21650 				    q, "last copy out(1)");
21651 				putnext(stq, mp1);
21652 				ire_refrele(ire);
21653 				if (conn_outgoing_ill != NULL)
21654 					ill_refrele(conn_outgoing_ill);
21655 				return;
21656 			}
21657 			/* More copies going out below. */
21658 			putnext(stq, mp1);
21659 		} else {
21660 			int offset;
21661 		    fragmentit:
21662 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
21663 			/*
21664 			 * If this would generate a icmp_frag_needed message,
21665 			 * we need to handle it before we do the IPSEC
21666 			 * processing. Otherwise, we need to strip the IPSEC
21667 			 * headers before we send up the message to the ULPs
21668 			 * which becomes messy and difficult.
21669 			 */
21670 			if (ipsec_len != 0) {
21671 				if ((max_frag < (unsigned int)(LENGTH +
21672 				    ipsec_len)) && (offset & IPH_DF)) {
21673 
21674 					BUMP_MIB(&ip_mib, ipFragFails);
21675 					ipha->ipha_hdr_checksum = 0;
21676 					ipha->ipha_hdr_checksum =
21677 					    (uint16_t)ip_csum_hdr(ipha);
21678 					icmp_frag_needed(ire->ire_stq, first_mp,
21679 					    max_frag);
21680 					if (!next_mp) {
21681 						ire_refrele(ire);
21682 						if (conn_outgoing_ill != NULL) {
21683 							ill_refrele(
21684 							    conn_outgoing_ill);
21685 						}
21686 						return;
21687 					}
21688 				} else {
21689 					/*
21690 					 * This won't cause a icmp_frag_needed
21691 					 * message. to be gnerated. Send it on
21692 					 * the wire. Note that this could still
21693 					 * cause fragmentation and all we
21694 					 * do is the generation of the message
21695 					 * to the ULP if needed before IPSEC.
21696 					 */
21697 					if (!next_mp) {
21698 						ipsec_out_process(q, first_mp,
21699 						    ire, ill_index);
21700 						TRACE_2(TR_FAC_IP,
21701 						    TR_IP_WPUT_IRE_END,
21702 						    "ip_wput_ire_end: q %p "
21703 						    "(%S)", q,
21704 						    "last ipsec_out_process");
21705 						ire_refrele(ire);
21706 						if (conn_outgoing_ill != NULL) {
21707 							ill_refrele(
21708 							    conn_outgoing_ill);
21709 						}
21710 						return;
21711 					}
21712 					ipsec_out_process(q, first_mp,
21713 					    ire, ill_index);
21714 				}
21715 			} else {
21716 				/* Initiate IPPF processing */
21717 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21718 					ip_process(IPP_LOCAL_OUT, &mp,
21719 					    ill_index);
21720 					if (mp == NULL) {
21721 						BUMP_MIB(&ip_mib,
21722 						    ipOutDiscards);
21723 						if (next_mp != NULL) {
21724 							freemsg(next_mp);
21725 							ire_refrele(ire1);
21726 						}
21727 						ire_refrele(ire);
21728 						TRACE_2(TR_FAC_IP,
21729 						    TR_IP_WPUT_IRE_END,
21730 						    "ip_wput_ire: q %p (%S)",
21731 						    q, "discard MDATA");
21732 						if (conn_outgoing_ill != NULL) {
21733 							ill_refrele(
21734 							    conn_outgoing_ill);
21735 						}
21736 						return;
21737 					}
21738 				}
21739 				if (!next_mp) {
21740 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21741 					    "ip_wput_ire_end: q %p (%S)",
21742 					    q, "last fragmentation");
21743 					ip_wput_ire_fragmentit(mp, ire);
21744 					ire_refrele(ire);
21745 					if (conn_outgoing_ill != NULL)
21746 						ill_refrele(conn_outgoing_ill);
21747 					return;
21748 				}
21749 				ip_wput_ire_fragmentit(mp, ire);
21750 			}
21751 		}
21752 	} else {
21753 	    nullstq:
21754 		/* A NULL stq means the destination address is local. */
21755 		UPDATE_OB_PKT_COUNT(ire);
21756 		ire->ire_last_used_time = lbolt;
21757 		ASSERT(ire->ire_ipif != NULL);
21758 		if (!next_mp) {
21759 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21760 			    "ip_wput_ire_end: q %p (%S)",
21761 			    q, "local address");
21762 			ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha,
21763 			    first_mp, ire, 0, ire->ire_zoneid);
21764 			ire_refrele(ire);
21765 			if (conn_outgoing_ill != NULL)
21766 				ill_refrele(conn_outgoing_ill);
21767 			return;
21768 		}
21769 		ip_wput_local(q, ire->ire_ipif->ipif_ill, ipha, first_mp,
21770 		    ire, 0, ire->ire_zoneid);
21771 	}
21772 next:
21773 	/*
21774 	 * More copies going out to additional interfaces.
21775 	 * ire1 has already been held. We don't need the
21776 	 * "ire" anymore.
21777 	 */
21778 	ire_refrele(ire);
21779 	ire = ire1;
21780 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
21781 	mp = next_mp;
21782 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
21783 	ill = ire_to_ill(ire);
21784 	first_mp = mp;
21785 	if (ipsec_len != 0) {
21786 		ASSERT(first_mp->b_datap->db_type == M_CTL);
21787 		mp = mp->b_cont;
21788 	}
21789 	dst = ire->ire_addr;
21790 	ipha = (ipha_t *)mp->b_rptr;
21791 	/*
21792 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
21793 	 * Restore ipha_ident "no checksum" flag.
21794 	 */
21795 	src = orig_src;
21796 	ipha->ipha_ident = ip_hdr_included;
21797 	goto another;
21798 
21799 #undef	rptr
21800 #undef	Q_TO_INDEX
21801 }
21802 
21803 /*
21804  * Routine to allocate a message that is used to notify the ULP about MDT.
21805  * The caller may provide a pointer to the link-layer MDT capabilities,
21806  * or NULL if MDT is to be disabled on the stream.
21807  */
21808 mblk_t *
21809 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
21810 {
21811 	mblk_t *mp;
21812 	ip_mdt_info_t *mdti;
21813 	ill_mdt_capab_t *idst;
21814 
21815 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
21816 		DB_TYPE(mp) = M_CTL;
21817 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
21818 		mdti = (ip_mdt_info_t *)mp->b_rptr;
21819 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
21820 		idst = &(mdti->mdt_capab);
21821 
21822 		/*
21823 		 * If the caller provides us with the capability, copy
21824 		 * it over into our notification message; otherwise
21825 		 * we zero out the capability portion.
21826 		 */
21827 		if (isrc != NULL)
21828 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
21829 		else
21830 			bzero((caddr_t)idst, sizeof (*idst));
21831 	}
21832 	return (mp);
21833 }
21834 
21835 /*
21836  * Routine which determines whether MDT can be enabled on the destination
21837  * IRE and IPC combination, and if so, allocates and returns the MDT
21838  * notification mblk that may be used by ULP.  We also check if we need to
21839  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
21840  * MDT usage in the past have been lifted.  This gets called during IP
21841  * and ULP binding.
21842  */
21843 mblk_t *
21844 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
21845     ill_mdt_capab_t *mdt_cap)
21846 {
21847 	mblk_t *mp;
21848 	boolean_t rc = B_FALSE;
21849 
21850 	ASSERT(dst_ire != NULL);
21851 	ASSERT(connp != NULL);
21852 	ASSERT(mdt_cap != NULL);
21853 
21854 	/*
21855 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
21856 	 * Multidata, which is handled in tcp_multisend().  This
21857 	 * is the reason why we do all these checks here, to ensure
21858 	 * that we don't enable Multidata for the cases which we
21859 	 * can't handle at the moment.
21860 	 */
21861 	do {
21862 		/* Only do TCP at the moment */
21863 		if (connp->conn_ulp != IPPROTO_TCP)
21864 			break;
21865 
21866 		/*
21867 		 * IPSEC outbound policy present?  Note that we get here
21868 		 * after calling ipsec_conn_cache_policy() where the global
21869 		 * policy checking is performed.  conn_latch will be
21870 		 * non-NULL as long as there's a policy defined,
21871 		 * i.e. conn_out_enforce_policy may be NULL in such case
21872 		 * when the connection is non-secure, and hence we check
21873 		 * further if the latch refers to an outbound policy.
21874 		 */
21875 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
21876 			break;
21877 
21878 		/* CGTP (multiroute) is enabled? */
21879 		if (dst_ire->ire_flags & RTF_MULTIRT)
21880 			break;
21881 
21882 		/* Outbound IPQoS enabled? */
21883 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
21884 			/*
21885 			 * In this case, we disable MDT for this and all
21886 			 * future connections going over the interface.
21887 			 */
21888 			mdt_cap->ill_mdt_on = 0;
21889 			break;
21890 		}
21891 
21892 		/* socket option(s) present? */
21893 		if (!CONN_IS_MD_FASTPATH(connp))
21894 			break;
21895 
21896 		rc = B_TRUE;
21897 	/* CONSTCOND */
21898 	} while (0);
21899 
21900 	/* Remember the result */
21901 	connp->conn_mdt_ok = rc;
21902 
21903 	if (!rc)
21904 		return (NULL);
21905 	else if (!mdt_cap->ill_mdt_on) {
21906 		/*
21907 		 * If MDT has been previously turned off in the past, and we
21908 		 * currently can do MDT (due to IPQoS policy removal, etc.)
21909 		 * then enable it for this interface.
21910 		 */
21911 		mdt_cap->ill_mdt_on = 1;
21912 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
21913 		    "interface %s\n", ill_name));
21914 	}
21915 
21916 	/* Allocate the MDT info mblk */
21917 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
21918 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
21919 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
21920 		return (NULL);
21921 	}
21922 	return (mp);
21923 }
21924 
21925 /*
21926  * Create destination address attribute, and fill it with the physical
21927  * destination address and SAP taken from the template DL_UNITDATA_REQ
21928  * message block.
21929  */
21930 boolean_t
21931 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
21932 {
21933 	dl_unitdata_req_t *dlurp;
21934 	pattr_t *pa;
21935 	pattrinfo_t pa_info;
21936 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
21937 	uint_t das_len, das_off;
21938 
21939 	ASSERT(dlmp != NULL);
21940 
21941 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
21942 	das_len = dlurp->dl_dest_addr_length;
21943 	das_off = dlurp->dl_dest_addr_offset;
21944 
21945 	pa_info.type = PATTR_DSTADDRSAP;
21946 	pa_info.len = sizeof (**das) + das_len - 1;
21947 
21948 	/* create and associate the attribute */
21949 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21950 	if (pa != NULL) {
21951 		ASSERT(*das != NULL);
21952 		(*das)->addr_is_group = 0;
21953 		(*das)->addr_len = (uint8_t)das_len;
21954 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
21955 	}
21956 
21957 	return (pa != NULL);
21958 }
21959 
21960 /*
21961  * Create hardware checksum attribute and fill it with the values passed.
21962  */
21963 boolean_t
21964 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
21965     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
21966 {
21967 	pattr_t *pa;
21968 	pattrinfo_t pa_info;
21969 
21970 	ASSERT(mmd != NULL);
21971 
21972 	pa_info.type = PATTR_HCKSUM;
21973 	pa_info.len = sizeof (pattr_hcksum_t);
21974 
21975 	/* create and associate the attribute */
21976 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
21977 	if (pa != NULL) {
21978 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
21979 
21980 		hck->hcksum_start_offset = start_offset;
21981 		hck->hcksum_stuff_offset = stuff_offset;
21982 		hck->hcksum_end_offset = end_offset;
21983 		hck->hcksum_flags = flags;
21984 	}
21985 	return (pa != NULL);
21986 }
21987 
21988 /*
21989  * Create zerocopy attribute and fill it with the specified flags
21990  */
21991 boolean_t
21992 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
21993 {
21994 	pattr_t *pa;
21995 	pattrinfo_t pa_info;
21996 
21997 	ASSERT(mmd != NULL);
21998 	pa_info.type = PATTR_ZCOPY;
21999 	pa_info.len = sizeof (pattr_zcopy_t);
22000 
22001 	/* create and associate the attribute */
22002 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22003 	if (pa != NULL) {
22004 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22005 
22006 		zcopy->zcopy_flags = flags;
22007 	}
22008 	return (pa != NULL);
22009 }
22010 
22011 /*
22012  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22013  * block chain. We could rewrite to handle arbitrary message block chains but
22014  * that would make the code complicated and slow. Right now there three
22015  * restrictions:
22016  *
22017  *   1. The first message block must contain the complete IP header and
22018  *	at least 1 byte of payload data.
22019  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22020  *	so that we can use a single Multidata message.
22021  *   3. No frag must be distributed over two or more message blocks so
22022  *	that we don't need more than two packet descriptors per frag.
22023  *
22024  * The above restrictions allow us to support userland applications (which
22025  * will send down a single message block) and NFS over UDP (which will
22026  * send down a chain of at most three message blocks).
22027  *
22028  * We also don't use MDT for payloads with less than or equal to
22029  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
22030  */
22031 boolean_t
22032 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
22033 {
22034 	int	blocks;
22035 	ssize_t	total, missing, size;
22036 
22037 	ASSERT(mp != NULL);
22038 	ASSERT(hdr_len > 0);
22039 
22040 	size = MBLKL(mp) - hdr_len;
22041 	if (size <= 0)
22042 		return (B_FALSE);
22043 
22044 	/* The first mblk contains the header and some payload. */
22045 	blocks = 1;
22046 	total = size;
22047 	size %= len;
22048 	missing = (size == 0) ? 0 : (len - size);
22049 	mp = mp->b_cont;
22050 
22051 	while (mp != NULL) {
22052 		/*
22053 		 * Give up if we encounter a zero length message block.
22054 		 * In practice, this should rarely happen and therefore
22055 		 * not worth the trouble of freeing and re-linking the
22056 		 * mblk from the chain to handle such case.
22057 		 */
22058 		if ((size = MBLKL(mp)) == 0)
22059 			return (B_FALSE);
22060 
22061 		/* Too many payload buffers for a single Multidata message? */
22062 		if (++blocks > MULTIDATA_MAX_PBUFS)
22063 			return (B_FALSE);
22064 
22065 		total += size;
22066 		/* Is a frag distributed over two or more message blocks? */
22067 		if (missing > size)
22068 			return (B_FALSE);
22069 		size -= missing;
22070 
22071 		size %= len;
22072 		missing = (size == 0) ? 0 : (len - size);
22073 
22074 		mp = mp->b_cont;
22075 	}
22076 
22077 	return (total > ip_wput_frag_mdt_min);
22078 }
22079 
22080 /*
22081  * Outbound IPv4 fragmentation routine using MDT.
22082  */
22083 static void
22084 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
22085     uint32_t frag_flag, int offset)
22086 {
22087 	ipha_t		*ipha_orig;
22088 	int		i1, ip_data_end;
22089 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
22090 	mblk_t		*hdr_mp, *md_mp = NULL;
22091 	unsigned char	*hdr_ptr, *pld_ptr;
22092 	multidata_t	*mmd;
22093 	ip_pdescinfo_t	pdi;
22094 
22095 	ASSERT(DB_TYPE(mp) == M_DATA);
22096 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
22097 
22098 	ipha_orig = (ipha_t *)mp->b_rptr;
22099 	mp->b_rptr += sizeof (ipha_t);
22100 
22101 	/* Calculate how many packets we will send out */
22102 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
22103 	pkts = (i1 + len - 1) / len;
22104 	ASSERT(pkts > 1);
22105 
22106 	/* Allocate a message block which will hold all the IP Headers. */
22107 	wroff = ip_wroff_extra;
22108 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
22109 
22110 	i1 = pkts * hdr_chunk_len;
22111 	/*
22112 	 * Create the header buffer, Multidata and destination address
22113 	 * and SAP attribute that should be associated with it.
22114 	 */
22115 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
22116 	    ((hdr_mp->b_wptr += i1),
22117 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
22118 	    !ip_md_addr_attr(mmd, NULL, ire->ire_dlureq_mp)) {
22119 		freemsg(mp);
22120 		if (md_mp == NULL) {
22121 			freemsg(hdr_mp);
22122 		} else {
22123 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
22124 			freemsg(md_mp);
22125 		}
22126 		IP_STAT(ip_frag_mdt_allocfail);
22127 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
22128 		return;
22129 	}
22130 	IP_STAT(ip_frag_mdt_allocd);
22131 
22132 	/*
22133 	 * Add a payload buffer to the Multidata; this operation must not
22134 	 * fail, or otherwise our logic in this routine is broken.  There
22135 	 * is no memory allocation done by the routine, so any returned
22136 	 * failure simply tells us that we've done something wrong.
22137 	 *
22138 	 * A failure tells us that either we're adding the same payload
22139 	 * buffer more than once, or we're trying to add more buffers than
22140 	 * allowed.  None of the above cases should happen, and we panic
22141 	 * because either there's horrible heap corruption, and/or
22142 	 * programming mistake.
22143 	 */
22144 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22145 		goto pbuf_panic;
22146 
22147 	hdr_ptr = hdr_mp->b_rptr;
22148 	pld_ptr = mp->b_rptr;
22149 
22150 	/* Establish the ending byte offset, based on the starting offset. */
22151 	offset <<= 3;
22152 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
22153 	    IP_SIMPLE_HDR_LENGTH;
22154 
22155 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
22156 
22157 	while (pld_ptr < mp->b_wptr) {
22158 		ipha_t		*ipha;
22159 		uint16_t	offset_and_flags;
22160 		uint16_t	ip_len;
22161 		int		error;
22162 
22163 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
22164 		ipha = (ipha_t *)(hdr_ptr + wroff);
22165 		ASSERT(OK_32PTR(ipha));
22166 		*ipha = *ipha_orig;
22167 
22168 		if (ip_data_end - offset > len) {
22169 			offset_and_flags = IPH_MF;
22170 		} else {
22171 			/*
22172 			 * Last frag. Set len to the length of this last piece.
22173 			 */
22174 			len = ip_data_end - offset;
22175 			/* A frag of a frag might have IPH_MF non-zero */
22176 			offset_and_flags =
22177 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22178 			    IPH_MF;
22179 		}
22180 		offset_and_flags |= (uint16_t)(offset >> 3);
22181 		offset_and_flags |= (uint16_t)frag_flag;
22182 		/* Store the offset and flags in the IP header. */
22183 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22184 
22185 		/* Store the length in the IP header. */
22186 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
22187 		ipha->ipha_length = htons(ip_len);
22188 
22189 		/*
22190 		 * Set the IP header checksum.  Note that mp is just
22191 		 * the header, so this is easy to pass to ip_csum.
22192 		 */
22193 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22194 
22195 		/*
22196 		 * Record offset and size of header and data of the next packet
22197 		 * in the multidata message.
22198 		 */
22199 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
22200 		PDESC_PLD_INIT(&pdi);
22201 		i1 = MIN(mp->b_wptr - pld_ptr, len);
22202 		ASSERT(i1 > 0);
22203 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
22204 		if (i1 == len) {
22205 			pld_ptr += len;
22206 		} else {
22207 			i1 = len - i1;
22208 			mp = mp->b_cont;
22209 			ASSERT(mp != NULL);
22210 			ASSERT(MBLKL(mp) >= i1);
22211 			/*
22212 			 * Attach the next payload message block to the
22213 			 * multidata message.
22214 			 */
22215 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22216 				goto pbuf_panic;
22217 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
22218 			pld_ptr = mp->b_rptr + i1;
22219 		}
22220 
22221 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
22222 		    KM_NOSLEEP)) == NULL) {
22223 			/*
22224 			 * Any failure other than ENOMEM indicates that we
22225 			 * have passed in invalid pdesc info or parameters
22226 			 * to mmd_addpdesc, which must not happen.
22227 			 *
22228 			 * EINVAL is a result of failure on boundary checks
22229 			 * against the pdesc info contents.  It should not
22230 			 * happen, and we panic because either there's
22231 			 * horrible heap corruption, and/or programming
22232 			 * mistake.
22233 			 */
22234 			if (error != ENOMEM) {
22235 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
22236 				    "pdesc logic error detected for "
22237 				    "mmd %p pinfo %p (%d)\n",
22238 				    (void *)mmd, (void *)&pdi, error);
22239 				/* NOTREACHED */
22240 			}
22241 			IP_STAT(ip_frag_mdt_addpdescfail);
22242 			/* Free unattached payload message blocks as well */
22243 			md_mp->b_cont = mp->b_cont;
22244 			goto free_mmd;
22245 		}
22246 
22247 		/* Advance fragment offset. */
22248 		offset += len;
22249 
22250 		/* Advance to location for next header in the buffer. */
22251 		hdr_ptr += hdr_chunk_len;
22252 
22253 		/* Did we reach the next payload message block? */
22254 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
22255 			mp = mp->b_cont;
22256 			/*
22257 			 * Attach the next message block with payload
22258 			 * data to the multidata message.
22259 			 */
22260 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
22261 				goto pbuf_panic;
22262 			pld_ptr = mp->b_rptr;
22263 		}
22264 	}
22265 
22266 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
22267 	ASSERT(mp->b_wptr == pld_ptr);
22268 
22269 	/* Update IP statistics */
22270 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
22271 	BUMP_MIB(&ip_mib, ipFragOKs);
22272 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
22273 
22274 	if (pkt_type == OB_PKT) {
22275 		ire->ire_ob_pkt_count += pkts;
22276 		if (ire->ire_ipif != NULL)
22277 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
22278 	} else {
22279 		/*
22280 		 * The type is IB_PKT in the forwarding path and in
22281 		 * the mobile IP case when the packet is being reverse-
22282 		 * tunneled to the home agent.
22283 		 */
22284 		ire->ire_ib_pkt_count += pkts;
22285 		ASSERT(!IRE_IS_LOCAL(ire));
22286 		if (ire->ire_type & IRE_BROADCAST)
22287 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
22288 		else
22289 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
22290 	}
22291 	ire->ire_last_used_time = lbolt;
22292 	/* Send it down */
22293 	putnext(ire->ire_stq, md_mp);
22294 	return;
22295 
22296 pbuf_panic:
22297 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
22298 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
22299 	    pbuf_idx);
22300 	/* NOTREACHED */
22301 }
22302 
22303 /*
22304  * Outbound IP fragmentation routine.
22305  *
22306  * NOTE : This routine does not ire_refrele the ire that is passed in
22307  * as the argument.
22308  */
22309 static void
22310 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
22311     uint32_t frag_flag)
22312 {
22313 	int		i1;
22314 	mblk_t		*ll_hdr_mp;
22315 	int 		ll_hdr_len;
22316 	int		hdr_len;
22317 	mblk_t		*hdr_mp;
22318 	ipha_t		*ipha;
22319 	int		ip_data_end;
22320 	int		len;
22321 	mblk_t		*mp = mp_orig;
22322 	int		offset;
22323 	queue_t		*q;
22324 	uint32_t	v_hlen_tos_len;
22325 	mblk_t		*first_mp;
22326 	boolean_t	mctl_present;
22327 	ill_t		*ill;
22328 	mblk_t		*xmit_mp;
22329 	mblk_t		*carve_mp;
22330 	ire_t		*ire1 = NULL;
22331 	ire_t		*save_ire = NULL;
22332 	mblk_t  	*next_mp = NULL;
22333 	boolean_t	last_frag = B_FALSE;
22334 	boolean_t	multirt_send = B_FALSE;
22335 	ire_t		*first_ire = NULL;
22336 	irb_t		*irb = NULL;
22337 
22338 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
22339 	    "ip_wput_frag_start:");
22340 
22341 	if (mp->b_datap->db_type == M_CTL) {
22342 		first_mp = mp;
22343 		mp_orig = mp = mp->b_cont;
22344 		mctl_present = B_TRUE;
22345 	} else {
22346 		first_mp = mp;
22347 		mctl_present = B_FALSE;
22348 	}
22349 
22350 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
22351 	ipha = (ipha_t *)mp->b_rptr;
22352 
22353 	/*
22354 	 * If the Don't Fragment flag is on, generate an ICMP destination
22355 	 * unreachable, fragmentation needed.
22356 	 */
22357 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22358 	if (offset & IPH_DF) {
22359 		BUMP_MIB(&ip_mib, ipFragFails);
22360 		/*
22361 		 * Need to compute hdr checksum if called from ip_wput_ire.
22362 		 * Note that ip_rput_forward verifies the checksum before
22363 		 * calling this routine so in that case this is a noop.
22364 		 */
22365 		ipha->ipha_hdr_checksum = 0;
22366 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22367 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag);
22368 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22369 		    "ip_wput_frag_end:(%S)",
22370 		    "don't fragment");
22371 		return;
22372 	}
22373 	if (mctl_present)
22374 		freeb(first_mp);
22375 	/*
22376 	 * Establish the starting offset.  May not be zero if we are fragging
22377 	 * a fragment that is being forwarded.
22378 	 */
22379 	offset = offset & IPH_OFFSET;
22380 
22381 	/* TODO why is this test needed? */
22382 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22383 	if (((max_frag - LENGTH) & ~7) < 8) {
22384 		/* TODO: notify ulp somehow */
22385 		BUMP_MIB(&ip_mib, ipFragFails);
22386 		freemsg(mp);
22387 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22388 		    "ip_wput_frag_end:(%S)",
22389 		    "len < 8");
22390 		return;
22391 	}
22392 
22393 	hdr_len = (V_HLEN & 0xF) << 2;
22394 
22395 	ipha->ipha_hdr_checksum = 0;
22396 
22397 	/*
22398 	 * Establish the number of bytes maximum per frag, after putting
22399 	 * in the header.
22400 	 */
22401 	len = (max_frag - hdr_len) & ~7;
22402 
22403 	/* Check if we can use MDT to send out the frags. */
22404 	ASSERT(!IRE_IS_LOCAL(ire));
22405 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
22406 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
22407 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
22408 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
22409 		ASSERT(ill->ill_mdt_capab != NULL);
22410 		if (!ill->ill_mdt_capab->ill_mdt_on) {
22411 			/*
22412 			 * If MDT has been previously turned off in the past,
22413 			 * and we currently can do MDT (due to IPQoS policy
22414 			 * removal, etc.) then enable it for this interface.
22415 			 */
22416 			ill->ill_mdt_capab->ill_mdt_on = 1;
22417 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
22418 			    ill->ill_name));
22419 		}
22420 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
22421 		    offset);
22422 		return;
22423 	}
22424 
22425 	/* Get a copy of the header for the trailing frags */
22426 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
22427 	if (!hdr_mp) {
22428 		BUMP_MIB(&ip_mib, ipOutDiscards);
22429 		freemsg(mp);
22430 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22431 		    "ip_wput_frag_end:(%S)",
22432 		    "couldn't copy hdr");
22433 		return;
22434 	}
22435 	if (DB_CRED(mp) != NULL)
22436 		mblk_setcred(hdr_mp, DB_CRED(mp));
22437 
22438 	/* Store the starting offset, with the MoreFrags flag. */
22439 	i1 = offset | IPH_MF | frag_flag;
22440 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
22441 
22442 	/* Establish the ending byte offset, based on the starting offset. */
22443 	offset <<= 3;
22444 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
22445 
22446 	/* Store the length of the first fragment in the IP header. */
22447 	i1 = len + hdr_len;
22448 	ASSERT(i1 <= IP_MAXPACKET);
22449 	ipha->ipha_length = htons((uint16_t)i1);
22450 
22451 	/*
22452 	 * Compute the IP header checksum for the first frag.  We have to
22453 	 * watch out that we stop at the end of the header.
22454 	 */
22455 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22456 
22457 	/*
22458 	 * Now carve off the first frag.  Note that this will include the
22459 	 * original IP header.
22460 	 */
22461 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
22462 		BUMP_MIB(&ip_mib, ipOutDiscards);
22463 		freeb(hdr_mp);
22464 		freemsg(mp_orig);
22465 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22466 		    "ip_wput_frag_end:(%S)",
22467 		    "couldn't carve first");
22468 		return;
22469 	}
22470 
22471 	/*
22472 	 * Multirouting case. Each fragment is replicated
22473 	 * via all non-condemned RTF_MULTIRT routes
22474 	 * currently resolved.
22475 	 * We ensure that first_ire is the first RTF_MULTIRT
22476 	 * ire in the bucket.
22477 	 */
22478 	if (ire->ire_flags & RTF_MULTIRT) {
22479 		irb = ire->ire_bucket;
22480 		ASSERT(irb != NULL);
22481 
22482 		multirt_send = B_TRUE;
22483 
22484 		/* Make sure we do not omit any multiroute ire. */
22485 		IRB_REFHOLD(irb);
22486 		for (first_ire = irb->irb_ire;
22487 		    first_ire != NULL;
22488 		    first_ire = first_ire->ire_next) {
22489 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22490 			    (first_ire->ire_addr == ire->ire_addr) &&
22491 			    !(first_ire->ire_marks &
22492 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22493 				break;
22494 		}
22495 
22496 		if (first_ire != NULL) {
22497 			if (first_ire != ire) {
22498 				IRE_REFHOLD(first_ire);
22499 				/*
22500 				 * Do not release the ire passed in
22501 				 * as the argument.
22502 				 */
22503 				ire = first_ire;
22504 			} else {
22505 				first_ire = NULL;
22506 			}
22507 		}
22508 		IRB_REFRELE(irb);
22509 
22510 		/*
22511 		 * Save the first ire; we will need to restore it
22512 		 * for the trailing frags.
22513 		 * We REFHOLD save_ire, as each iterated ire will be
22514 		 * REFRELEd.
22515 		 */
22516 		save_ire = ire;
22517 		IRE_REFHOLD(save_ire);
22518 	}
22519 
22520 	/*
22521 	 * First fragment emission loop.
22522 	 * In most cases, the emission loop below is entered only
22523 	 * once. Only in the case where the ire holds the RTF_MULTIRT
22524 	 * flag, do we loop to process all RTF_MULTIRT ires in the
22525 	 * bucket, and send the fragment through all crossed
22526 	 * RTF_MULTIRT routes.
22527 	 */
22528 	do {
22529 		if (ire->ire_flags & RTF_MULTIRT) {
22530 			/*
22531 			 * We are in a multiple send case, need to get
22532 			 * the next ire and make a copy of the packet.
22533 			 * ire1 holds here the next ire to process in the
22534 			 * bucket. If multirouting is expected,
22535 			 * any non-RTF_MULTIRT ire that has the
22536 			 * right destination address is ignored.
22537 			 *
22538 			 * We have to take into account the MTU of
22539 			 * each walked ire. max_frag is set by the
22540 			 * the caller and generally refers to
22541 			 * the primary ire entry. Here we ensure that
22542 			 * no route with a lower MTU will be used, as
22543 			 * fragments are carved once for all ires,
22544 			 * then replicated.
22545 			 */
22546 			ASSERT(irb != NULL);
22547 			IRB_REFHOLD(irb);
22548 			for (ire1 = ire->ire_next;
22549 			    ire1 != NULL;
22550 			    ire1 = ire1->ire_next) {
22551 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22552 					continue;
22553 				if (ire1->ire_addr != ire->ire_addr)
22554 					continue;
22555 				if (ire1->ire_marks &
22556 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22557 					continue;
22558 				/*
22559 				 * Ensure we do not exceed the MTU
22560 				 * of the next route.
22561 				 */
22562 				if (ire1->ire_max_frag < max_frag) {
22563 					ip_multirt_bad_mtu(ire1, max_frag);
22564 					continue;
22565 				}
22566 
22567 				/* Got one. */
22568 				IRE_REFHOLD(ire1);
22569 				break;
22570 			}
22571 			IRB_REFRELE(irb);
22572 
22573 			if (ire1 != NULL) {
22574 				next_mp = copyb(mp);
22575 				if ((next_mp == NULL) ||
22576 				    ((mp->b_cont != NULL) &&
22577 				    ((next_mp->b_cont =
22578 				    dupmsg(mp->b_cont)) == NULL))) {
22579 					freemsg(next_mp);
22580 					next_mp = NULL;
22581 					ire_refrele(ire1);
22582 					ire1 = NULL;
22583 				}
22584 			}
22585 
22586 			/* Last multiroute ire; don't loop anymore. */
22587 			if (ire1 == NULL) {
22588 				multirt_send = B_FALSE;
22589 			}
22590 		}
22591 
22592 		ll_hdr_len = 0;
22593 		LOCK_IRE_FP_MP(ire);
22594 		ll_hdr_mp = ire->ire_fp_mp;
22595 		if (ll_hdr_mp != NULL) {
22596 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22597 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
22598 		} else {
22599 			ll_hdr_mp = ire->ire_dlureq_mp;
22600 		}
22601 
22602 		/* If there is a transmit header, get a copy for this frag. */
22603 		/*
22604 		 * TODO: should check db_ref before calling ip_carve_mp since
22605 		 * it might give us a dup.
22606 		 */
22607 		if (!ll_hdr_mp) {
22608 			/* No xmit header. */
22609 			xmit_mp = mp;
22610 		} else if (mp->b_datap->db_ref == 1 &&
22611 		    ll_hdr_len != 0 &&
22612 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22613 			/* M_DATA fastpath */
22614 			mp->b_rptr -= ll_hdr_len;
22615 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
22616 			xmit_mp = mp;
22617 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
22618 			UNLOCK_IRE_FP_MP(ire);
22619 			BUMP_MIB(&ip_mib, ipOutDiscards);
22620 			freeb(hdr_mp);
22621 			freemsg(mp);
22622 			freemsg(mp_orig);
22623 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22624 			    "ip_wput_frag_end:(%S)",
22625 			    "discard");
22626 
22627 			if (multirt_send) {
22628 				ASSERT(ire1);
22629 				ASSERT(next_mp);
22630 
22631 				freemsg(next_mp);
22632 				ire_refrele(ire1);
22633 			}
22634 			if (save_ire != NULL)
22635 				IRE_REFRELE(save_ire);
22636 
22637 			if (first_ire != NULL)
22638 				ire_refrele(first_ire);
22639 			return;
22640 		} else {
22641 			xmit_mp->b_cont = mp;
22642 			if (DB_CRED(mp) != NULL)
22643 				mblk_setcred(xmit_mp, DB_CRED(mp));
22644 			/* Get priority marking, if any. */
22645 			if (DB_TYPE(xmit_mp) == M_DATA)
22646 				xmit_mp->b_band = mp->b_band;
22647 		}
22648 		UNLOCK_IRE_FP_MP(ire);
22649 		q = ire->ire_stq;
22650 		BUMP_MIB(&ip_mib, ipFragCreates);
22651 		putnext(q, xmit_mp);
22652 		if (pkt_type != OB_PKT) {
22653 			/*
22654 			 * Update the packet count of trailing
22655 			 * RTF_MULTIRT ires.
22656 			 */
22657 			UPDATE_OB_PKT_COUNT(ire);
22658 		}
22659 
22660 		if (multirt_send) {
22661 			/*
22662 			 * We are in a multiple send case; look for
22663 			 * the next ire and re-enter the loop.
22664 			 */
22665 			ASSERT(ire1);
22666 			ASSERT(next_mp);
22667 			/* REFRELE the current ire before looping */
22668 			ire_refrele(ire);
22669 			ire = ire1;
22670 			ire1 = NULL;
22671 			mp = next_mp;
22672 			next_mp = NULL;
22673 		}
22674 	} while (multirt_send);
22675 
22676 	ASSERT(ire1 == NULL);
22677 
22678 	/* Restore the original ire; we need it for the trailing frags */
22679 	if (save_ire != NULL) {
22680 		/* REFRELE the last iterated ire */
22681 		ire_refrele(ire);
22682 		/* save_ire has been REFHOLDed */
22683 		ire = save_ire;
22684 		save_ire = NULL;
22685 		q = ire->ire_stq;
22686 	}
22687 
22688 	if (pkt_type == OB_PKT) {
22689 		UPDATE_OB_PKT_COUNT(ire);
22690 	} else {
22691 		UPDATE_IB_PKT_COUNT(ire);
22692 	}
22693 
22694 	/* Advance the offset to the second frag starting point. */
22695 	offset += len;
22696 	/*
22697 	 * Update hdr_len from the copied header - there might be less options
22698 	 * in the later fragments.
22699 	 */
22700 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
22701 	/* Loop until done. */
22702 	for (;;) {
22703 		uint16_t	offset_and_flags;
22704 		uint16_t	ip_len;
22705 
22706 		if (ip_data_end - offset > len) {
22707 			/*
22708 			 * Carve off the appropriate amount from the original
22709 			 * datagram.
22710 			 */
22711 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22712 				mp = NULL;
22713 				break;
22714 			}
22715 			/*
22716 			 * More frags after this one.  Get another copy
22717 			 * of the header.
22718 			 */
22719 			if (carve_mp->b_datap->db_ref == 1 &&
22720 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22721 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22722 				/* Inline IP header */
22723 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22724 				    hdr_mp->b_rptr;
22725 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22726 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22727 				mp = carve_mp;
22728 			} else {
22729 				if (!(mp = copyb(hdr_mp))) {
22730 					freemsg(carve_mp);
22731 					break;
22732 				}
22733 				/* Get priority marking, if any. */
22734 				mp->b_band = carve_mp->b_band;
22735 				mp->b_cont = carve_mp;
22736 			}
22737 			ipha = (ipha_t *)mp->b_rptr;
22738 			offset_and_flags = IPH_MF;
22739 		} else {
22740 			/*
22741 			 * Last frag.  Consume the header. Set len to
22742 			 * the length of this last piece.
22743 			 */
22744 			len = ip_data_end - offset;
22745 
22746 			/*
22747 			 * Carve off the appropriate amount from the original
22748 			 * datagram.
22749 			 */
22750 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
22751 				mp = NULL;
22752 				break;
22753 			}
22754 			if (carve_mp->b_datap->db_ref == 1 &&
22755 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
22756 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
22757 				/* Inline IP header */
22758 				carve_mp->b_rptr -= hdr_mp->b_wptr -
22759 				    hdr_mp->b_rptr;
22760 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
22761 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
22762 				mp = carve_mp;
22763 				freeb(hdr_mp);
22764 				hdr_mp = mp;
22765 			} else {
22766 				mp = hdr_mp;
22767 				/* Get priority marking, if any. */
22768 				mp->b_band = carve_mp->b_band;
22769 				mp->b_cont = carve_mp;
22770 			}
22771 			ipha = (ipha_t *)mp->b_rptr;
22772 			/* A frag of a frag might have IPH_MF non-zero */
22773 			offset_and_flags =
22774 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
22775 			    IPH_MF;
22776 		}
22777 		offset_and_flags |= (uint16_t)(offset >> 3);
22778 		offset_and_flags |= (uint16_t)frag_flag;
22779 		/* Store the offset and flags in the IP header. */
22780 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
22781 
22782 		/* Store the length in the IP header. */
22783 		ip_len = (uint16_t)(len + hdr_len);
22784 		ipha->ipha_length = htons(ip_len);
22785 
22786 		/*
22787 		 * Set the IP header checksum.	Note that mp is just
22788 		 * the header, so this is easy to pass to ip_csum.
22789 		 */
22790 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22791 
22792 		/* Attach a transmit header, if any, and ship it. */
22793 		if (pkt_type == OB_PKT) {
22794 			UPDATE_OB_PKT_COUNT(ire);
22795 		} else {
22796 			UPDATE_IB_PKT_COUNT(ire);
22797 		}
22798 
22799 		if (ire->ire_flags & RTF_MULTIRT) {
22800 			irb = ire->ire_bucket;
22801 			ASSERT(irb != NULL);
22802 
22803 			multirt_send = B_TRUE;
22804 
22805 			/*
22806 			 * Save the original ire; we will need to restore it
22807 			 * for the tailing frags.
22808 			 */
22809 			save_ire = ire;
22810 			IRE_REFHOLD(save_ire);
22811 		}
22812 		/*
22813 		 * Emission loop for this fragment, similar
22814 		 * to what is done for the first fragment.
22815 		 */
22816 		do {
22817 			if (multirt_send) {
22818 				/*
22819 				 * We are in a multiple send case, need to get
22820 				 * the next ire and make a copy of the packet.
22821 				 */
22822 				ASSERT(irb != NULL);
22823 				IRB_REFHOLD(irb);
22824 				for (ire1 = ire->ire_next;
22825 				    ire1 != NULL;
22826 				    ire1 = ire1->ire_next) {
22827 					if (!(ire1->ire_flags & RTF_MULTIRT))
22828 						continue;
22829 					if (ire1->ire_addr != ire->ire_addr)
22830 						continue;
22831 					if (ire1->ire_marks &
22832 					    (IRE_MARK_CONDEMNED|
22833 						IRE_MARK_HIDDEN))
22834 						continue;
22835 					/*
22836 					 * Ensure we do not exceed the MTU
22837 					 * of the next route.
22838 					 */
22839 					if (ire1->ire_max_frag < max_frag) {
22840 						ip_multirt_bad_mtu(ire1,
22841 						    max_frag);
22842 						continue;
22843 					}
22844 
22845 					/* Got one. */
22846 					IRE_REFHOLD(ire1);
22847 					break;
22848 				}
22849 				IRB_REFRELE(irb);
22850 
22851 				if (ire1 != NULL) {
22852 					next_mp = copyb(mp);
22853 					if ((next_mp == NULL) ||
22854 					    ((mp->b_cont != NULL) &&
22855 					    ((next_mp->b_cont =
22856 					    dupmsg(mp->b_cont)) == NULL))) {
22857 						freemsg(next_mp);
22858 						next_mp = NULL;
22859 						ire_refrele(ire1);
22860 						ire1 = NULL;
22861 					}
22862 				}
22863 
22864 				/* Last multiroute ire; don't loop anymore. */
22865 				if (ire1 == NULL) {
22866 					multirt_send = B_FALSE;
22867 				}
22868 			}
22869 
22870 			/* Update transmit header */
22871 			ll_hdr_len = 0;
22872 			LOCK_IRE_FP_MP(ire);
22873 			ll_hdr_mp = ire->ire_fp_mp;
22874 			if (ll_hdr_mp != NULL) {
22875 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
22876 				ll_hdr_len = MBLKL(ll_hdr_mp);
22877 			} else {
22878 				ll_hdr_mp = ire->ire_dlureq_mp;
22879 			}
22880 
22881 			if (!ll_hdr_mp) {
22882 				xmit_mp = mp;
22883 			} else if (mp->b_datap->db_ref == 1 &&
22884 			    ll_hdr_len != 0 &&
22885 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
22886 				/* M_DATA fastpath */
22887 				mp->b_rptr -= ll_hdr_len;
22888 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
22889 				    ll_hdr_len);
22890 				xmit_mp = mp;
22891 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
22892 				xmit_mp->b_cont = mp;
22893 				if (DB_CRED(mp) != NULL)
22894 					mblk_setcred(xmit_mp, DB_CRED(mp));
22895 				/* Get priority marking, if any. */
22896 				if (DB_TYPE(xmit_mp) == M_DATA)
22897 					xmit_mp->b_band = mp->b_band;
22898 			} else {
22899 				/*
22900 				 * Exit both the replication and
22901 				 * fragmentation loops.
22902 				 */
22903 				UNLOCK_IRE_FP_MP(ire);
22904 				goto drop_pkt;
22905 			}
22906 			UNLOCK_IRE_FP_MP(ire);
22907 			BUMP_MIB(&ip_mib, ipFragCreates);
22908 			putnext(q, xmit_mp);
22909 
22910 			if (pkt_type != OB_PKT) {
22911 				/*
22912 				 * Update the packet count of trailing
22913 				 * RTF_MULTIRT ires.
22914 				 */
22915 				UPDATE_OB_PKT_COUNT(ire);
22916 			}
22917 
22918 			/* All done if we just consumed the hdr_mp. */
22919 			if (mp == hdr_mp) {
22920 				last_frag = B_TRUE;
22921 			}
22922 
22923 			if (multirt_send) {
22924 				/*
22925 				 * We are in a multiple send case; look for
22926 				 * the next ire and re-enter the loop.
22927 				 */
22928 				ASSERT(ire1);
22929 				ASSERT(next_mp);
22930 				/* REFRELE the current ire before looping */
22931 				ire_refrele(ire);
22932 				ire = ire1;
22933 				ire1 = NULL;
22934 				q = ire->ire_stq;
22935 				mp = next_mp;
22936 				next_mp = NULL;
22937 			}
22938 		} while (multirt_send);
22939 		/*
22940 		 * Restore the original ire; we need it for the
22941 		 * trailing frags
22942 		 */
22943 		if (save_ire != NULL) {
22944 			ASSERT(ire1 == NULL);
22945 			/* REFRELE the last iterated ire */
22946 			ire_refrele(ire);
22947 			/* save_ire has been REFHOLDed */
22948 			ire = save_ire;
22949 			q = ire->ire_stq;
22950 			save_ire = NULL;
22951 		}
22952 
22953 		if (last_frag) {
22954 			BUMP_MIB(&ip_mib, ipFragOKs);
22955 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22956 			    "ip_wput_frag_end:(%S)",
22957 			    "consumed hdr_mp");
22958 
22959 			if (first_ire != NULL)
22960 				ire_refrele(first_ire);
22961 			return;
22962 		}
22963 		/* Otherwise, advance and loop. */
22964 		offset += len;
22965 	}
22966 
22967 drop_pkt:
22968 	/* Clean up following allocation failure. */
22969 	BUMP_MIB(&ip_mib, ipOutDiscards);
22970 	freemsg(mp);
22971 	if (mp != hdr_mp)
22972 		freeb(hdr_mp);
22973 	if (mp != mp_orig)
22974 		freemsg(mp_orig);
22975 
22976 	if (save_ire != NULL)
22977 		IRE_REFRELE(save_ire);
22978 	if (first_ire != NULL)
22979 		ire_refrele(first_ire);
22980 
22981 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
22982 	    "ip_wput_frag_end:(%S)",
22983 	    "end--alloc failure");
22984 }
22985 
22986 /*
22987  * Copy the header plus those options which have the copy bit set
22988  */
22989 static mblk_t *
22990 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
22991 {
22992 	mblk_t	*mp;
22993 	uchar_t	*up;
22994 
22995 	/*
22996 	 * Quick check if we need to look for options without the copy bit
22997 	 * set
22998 	 */
22999 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
23000 	if (!mp)
23001 		return (mp);
23002 	mp->b_rptr += ip_wroff_extra;
23003 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
23004 		bcopy(rptr, mp->b_rptr, hdr_len);
23005 		mp->b_wptr += hdr_len + ip_wroff_extra;
23006 		return (mp);
23007 	}
23008 	up  = mp->b_rptr;
23009 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
23010 	up += IP_SIMPLE_HDR_LENGTH;
23011 	rptr += IP_SIMPLE_HDR_LENGTH;
23012 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
23013 	while (hdr_len > 0) {
23014 		uint32_t optval;
23015 		uint32_t optlen;
23016 
23017 		optval = *rptr;
23018 		if (optval == IPOPT_EOL)
23019 			break;
23020 		if (optval == IPOPT_NOP)
23021 			optlen = 1;
23022 		else
23023 			optlen = rptr[1];
23024 		if (optval & IPOPT_COPY) {
23025 			bcopy(rptr, up, optlen);
23026 			up += optlen;
23027 		}
23028 		rptr += optlen;
23029 		hdr_len -= optlen;
23030 	}
23031 	/*
23032 	 * Make sure that we drop an even number of words by filling
23033 	 * with EOL to the next word boundary.
23034 	 */
23035 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
23036 	    hdr_len & 0x3; hdr_len++)
23037 		*up++ = IPOPT_EOL;
23038 	mp->b_wptr = up;
23039 	/* Update header length */
23040 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
23041 	return (mp);
23042 }
23043 
23044 /*
23045  * Delivery to local recipients including fanout to multiple recipients.
23046  * Does not do checksumming of UDP/TCP.
23047  * Note: q should be the read side queue for either the ill or conn.
23048  * Note: rq should be the read side q for the lower (ill) stream.
23049  * We don't send packets to IPPF processing, thus the last argument
23050  * to all the fanout calls are B_FALSE.
23051  */
23052 void
23053 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
23054     int fanout_flags, zoneid_t zoneid)
23055 {
23056 	uint32_t	protocol;
23057 	mblk_t		*first_mp;
23058 	boolean_t	mctl_present;
23059 	int		ire_type;
23060 #define	rptr	((uchar_t *)ipha)
23061 
23062 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
23063 	    "ip_wput_local_start: q %p", q);
23064 
23065 	if (ire != NULL) {
23066 		ire_type = ire->ire_type;
23067 	} else {
23068 		/*
23069 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
23070 		 * packet is not multicast, we can't tell the ire type.
23071 		 */
23072 		ASSERT(CLASSD(ipha->ipha_dst));
23073 		ire_type = IRE_BROADCAST;
23074 	}
23075 
23076 	first_mp = mp;
23077 	if (first_mp->b_datap->db_type == M_CTL) {
23078 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
23079 		if (!io->ipsec_out_secure) {
23080 			/*
23081 			 * This ipsec_out_t was allocated in ip_wput
23082 			 * for multicast packets to store the ill_index.
23083 			 * As this is being delivered locally, we don't
23084 			 * need this anymore.
23085 			 */
23086 			mp = first_mp->b_cont;
23087 			freeb(first_mp);
23088 			first_mp = mp;
23089 			mctl_present = B_FALSE;
23090 		} else {
23091 			mctl_present = B_TRUE;
23092 			mp = first_mp->b_cont;
23093 			ASSERT(mp != NULL);
23094 			ipsec_out_to_in(first_mp);
23095 		}
23096 	} else {
23097 		mctl_present = B_FALSE;
23098 	}
23099 
23100 	loopback_packets++;
23101 
23102 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
23103 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
23104 	if (!IS_SIMPLE_IPH(ipha)) {
23105 		ip_wput_local_options(ipha);
23106 	}
23107 
23108 	protocol = ipha->ipha_protocol;
23109 	switch (protocol) {
23110 	case IPPROTO_ICMP: {
23111 		ire_t		*ire_zone;
23112 		ilm_t		*ilm;
23113 		mblk_t		*mp1;
23114 		zoneid_t	last_zoneid;
23115 
23116 		if (CLASSD(ipha->ipha_dst) &&
23117 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
23118 			ASSERT(ire_type == IRE_BROADCAST);
23119 			/*
23120 			 * In the multicast case, applications may have joined
23121 			 * the group from different zones, so we need to deliver
23122 			 * the packet to each of them. Loop through the
23123 			 * multicast memberships structures (ilm) on the receive
23124 			 * ill and send a copy of the packet up each matching
23125 			 * one. However, we don't do this for multicasts sent on
23126 			 * the loopback interface (PHYI_LOOPBACK flag set) as
23127 			 * they must stay in the sender's zone.
23128 			 *
23129 			 * ilm_add_v6() ensures that ilms in the same zone are
23130 			 * contiguous in the ill_ilm list. We use this property
23131 			 * to avoid sending duplicates needed when two
23132 			 * applications in the same zone join the same group on
23133 			 * different logical interfaces: we ignore the ilm if
23134 			 * its zoneid is the same as the last matching one.
23135 			 * In addition, the sending of the packet for
23136 			 * ire_zoneid is delayed until all of the other ilms
23137 			 * have been exhausted.
23138 			 */
23139 			last_zoneid = -1;
23140 			ILM_WALKER_HOLD(ill);
23141 			for (ilm = ill->ill_ilm; ilm != NULL;
23142 			    ilm = ilm->ilm_next) {
23143 				if ((ilm->ilm_flags & ILM_DELETED) ||
23144 				    ipha->ipha_dst != ilm->ilm_addr ||
23145 				    ilm->ilm_zoneid == last_zoneid ||
23146 				    ilm->ilm_zoneid == zoneid ||
23147 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
23148 					continue;
23149 				mp1 = ip_copymsg(first_mp);
23150 				if (mp1 == NULL)
23151 					continue;
23152 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23153 				    mctl_present, B_FALSE, ill,
23154 				    ilm->ilm_zoneid);
23155 				last_zoneid = ilm->ilm_zoneid;
23156 			}
23157 			ILM_WALKER_RELE(ill);
23158 			/*
23159 			 * Loopback case: the sending endpoint has
23160 			 * IP_MULTICAST_LOOP disabled, therefore we don't
23161 			 * dispatch the multicast packet to the sending zone.
23162 			 */
23163 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
23164 				freemsg(first_mp);
23165 				return;
23166 			}
23167 		} else if (ire_type == IRE_BROADCAST) {
23168 			/*
23169 			 * In the broadcast case, there may be many zones
23170 			 * which need a copy of the packet delivered to them.
23171 			 * There is one IRE_BROADCAST per broadcast address
23172 			 * and per zone; we walk those using a helper function.
23173 			 * In addition, the sending of the packet for zoneid is
23174 			 * delayed until all of the other ires have been
23175 			 * processed.
23176 			 */
23177 			IRB_REFHOLD(ire->ire_bucket);
23178 			ire_zone = NULL;
23179 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
23180 			    ire)) != NULL) {
23181 				mp1 = ip_copymsg(first_mp);
23182 				if (mp1 == NULL)
23183 					continue;
23184 
23185 				UPDATE_IB_PKT_COUNT(ire_zone);
23186 				ire_zone->ire_last_used_time = lbolt;
23187 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
23188 				    mctl_present, B_FALSE, ill,
23189 				    ire_zone->ire_zoneid);
23190 			}
23191 			IRB_REFRELE(ire->ire_bucket);
23192 		}
23193 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
23194 		    0, mctl_present, B_FALSE, ill, zoneid);
23195 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23196 		    "ip_wput_local_end: q %p (%S)",
23197 		    q, "icmp");
23198 		return;
23199 	}
23200 	case IPPROTO_IGMP:
23201 		if (igmp_input(q, mp, ill)) {
23202 			/* Bad packet - discarded by igmp_input */
23203 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23204 			    "ip_wput_local_end: q %p (%S)",
23205 			    q, "igmp_input--bad packet");
23206 			if (mctl_present)
23207 				freeb(first_mp);
23208 			return;
23209 		}
23210 		/*
23211 		 * igmp_input() may have pulled up the message so ipha needs to
23212 		 * be reinitialized.
23213 		 */
23214 		ipha = (ipha_t *)mp->b_rptr;
23215 		/* deliver to local raw users */
23216 		break;
23217 	case IPPROTO_ENCAP:
23218 		/*
23219 		 * This case is covered by either ip_fanout_proto, or by
23220 		 * the above security processing for self-tunneled packets.
23221 		 */
23222 		break;
23223 	case IPPROTO_UDP: {
23224 		uint16_t	*up;
23225 		uint32_t	ports;
23226 
23227 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
23228 		    UDP_PORTS_OFFSET);
23229 		/* Force a 'valid' checksum. */
23230 		up[3] = 0;
23231 
23232 		ports = *(uint32_t *)up;
23233 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
23234 		    (ire_type == IRE_BROADCAST),
23235 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23236 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
23237 		    ill, zoneid);
23238 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23239 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
23240 		return;
23241 	}
23242 	case IPPROTO_TCP: {
23243 
23244 		/*
23245 		 * For TCP, discard broadcast packets.
23246 		 */
23247 		if ((ushort_t)ire_type == IRE_BROADCAST) {
23248 			freemsg(first_mp);
23249 			BUMP_MIB(&ip_mib, ipInDiscards);
23250 			ip2dbg(("ip_wput_local: discard broadcast\n"));
23251 			return;
23252 		}
23253 
23254 		if (mp->b_datap->db_type == M_DATA) {
23255 			/*
23256 			 * M_DATA mblk, so init mblk (chain) for no struio().
23257 			 */
23258 			mblk_t	*mp1 = mp;
23259 
23260 			do
23261 				mp1->b_datap->db_struioflag = 0;
23262 			while ((mp1 = mp1->b_cont) != NULL);
23263 		}
23264 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
23265 		    <= mp->b_wptr);
23266 		ip_fanout_tcp(q, first_mp, ill, ipha,
23267 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23268 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
23269 		    mctl_present, B_FALSE, zoneid);
23270 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23271 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
23272 		return;
23273 	}
23274 	case IPPROTO_SCTP:
23275 	{
23276 		uint32_t	ports;
23277 
23278 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
23279 		ip_fanout_sctp(first_mp, ill, ipha, ports,
23280 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
23281 		    IP_FF_IP6INFO,
23282 		    mctl_present, B_FALSE, 0, zoneid);
23283 		return;
23284 	}
23285 
23286 	default:
23287 		break;
23288 	}
23289 	/*
23290 	 * Find a client for some other protocol.  We give
23291 	 * copies to multiple clients, if more than one is
23292 	 * bound.
23293 	 */
23294 	ip_fanout_proto(q, first_mp, ill, ipha,
23295 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
23296 	    mctl_present, B_FALSE, ill, zoneid);
23297 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
23298 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
23299 #undef	rptr
23300 }
23301 
23302 /*
23303  * Update any source route, record route, or timestamp options.
23304  * Check that we are at end of strict source route.
23305  * The options have been sanity checked by ip_wput_options().
23306  */
23307 static void
23308 ip_wput_local_options(ipha_t *ipha)
23309 {
23310 	ipoptp_t	opts;
23311 	uchar_t		*opt;
23312 	uint8_t		optval;
23313 	uint8_t		optlen;
23314 	ipaddr_t	dst;
23315 	uint32_t	ts;
23316 	ire_t		*ire;
23317 	timestruc_t	now;
23318 
23319 	ip2dbg(("ip_wput_local_options\n"));
23320 	for (optval = ipoptp_first(&opts, ipha);
23321 	    optval != IPOPT_EOL;
23322 	    optval = ipoptp_next(&opts)) {
23323 		opt = opts.ipoptp_cur;
23324 		optlen = opts.ipoptp_len;
23325 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
23326 		switch (optval) {
23327 			uint32_t off;
23328 		case IPOPT_SSRR:
23329 		case IPOPT_LSRR:
23330 			off = opt[IPOPT_OFFSET];
23331 			off--;
23332 			if (optlen < IP_ADDR_LEN ||
23333 			    off > optlen - IP_ADDR_LEN) {
23334 				/* End of source route */
23335 				break;
23336 			}
23337 			/*
23338 			 * This will only happen if two consecutive entries
23339 			 * in the source route contains our address or if
23340 			 * it is a packet with a loose source route which
23341 			 * reaches us before consuming the whole source route
23342 			 */
23343 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
23344 			if (optval == IPOPT_SSRR) {
23345 				return;
23346 			}
23347 			/*
23348 			 * Hack: instead of dropping the packet truncate the
23349 			 * source route to what has been used by filling the
23350 			 * rest with IPOPT_NOP.
23351 			 */
23352 			opt[IPOPT_OLEN] = (uint8_t)off;
23353 			while (off < optlen) {
23354 				opt[off++] = IPOPT_NOP;
23355 			}
23356 			break;
23357 		case IPOPT_RR:
23358 			off = opt[IPOPT_OFFSET];
23359 			off--;
23360 			if (optlen < IP_ADDR_LEN ||
23361 			    off > optlen - IP_ADDR_LEN) {
23362 				/* No more room - ignore */
23363 				ip1dbg((
23364 				    "ip_wput_forward_options: end of RR\n"));
23365 				break;
23366 			}
23367 			dst = htonl(INADDR_LOOPBACK);
23368 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23369 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23370 			break;
23371 		case IPOPT_TS:
23372 			/* Insert timestamp if there is romm */
23373 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23374 			case IPOPT_TS_TSONLY:
23375 				off = IPOPT_TS_TIMELEN;
23376 				break;
23377 			case IPOPT_TS_PRESPEC:
23378 			case IPOPT_TS_PRESPEC_RFC791:
23379 				/* Verify that the address matched */
23380 				off = opt[IPOPT_OFFSET] - 1;
23381 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
23382 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
23383 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
23384 				if (ire == NULL) {
23385 					/* Not for us */
23386 					break;
23387 				}
23388 				ire_refrele(ire);
23389 				/* FALLTHRU */
23390 			case IPOPT_TS_TSANDADDR:
23391 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
23392 				break;
23393 			default:
23394 				/*
23395 				 * ip_*put_options should have already
23396 				 * dropped this packet.
23397 				 */
23398 				cmn_err(CE_PANIC, "ip_wput_local_options: "
23399 				    "unknown IT - bug in ip_wput_options?\n");
23400 				return;	/* Keep "lint" happy */
23401 			}
23402 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
23403 				/* Increase overflow counter */
23404 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
23405 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
23406 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
23407 				    (off << 4);
23408 				break;
23409 			}
23410 			off = opt[IPOPT_OFFSET] - 1;
23411 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
23412 			case IPOPT_TS_PRESPEC:
23413 			case IPOPT_TS_PRESPEC_RFC791:
23414 			case IPOPT_TS_TSANDADDR:
23415 				dst = htonl(INADDR_LOOPBACK);
23416 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
23417 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
23418 				/* FALLTHRU */
23419 			case IPOPT_TS_TSONLY:
23420 				off = opt[IPOPT_OFFSET] - 1;
23421 				/* Compute # of milliseconds since midnight */
23422 				gethrestime(&now);
23423 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
23424 				    now.tv_nsec / (NANOSEC / MILLISEC);
23425 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
23426 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
23427 				break;
23428 			}
23429 			break;
23430 		}
23431 	}
23432 }
23433 
23434 /*
23435  * Send out a multicast packet on interface ipif.
23436  * The sender does not have an conn.
23437  * Caller verifies that this isn't a PHYI_LOOPBACK.
23438  */
23439 void
23440 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif)
23441 {
23442 	ipha_t	*ipha;
23443 	ire_t	*ire;
23444 	ipaddr_t	dst;
23445 	mblk_t		*first_mp;
23446 
23447 	/* igmp_sendpkt always allocates a ipsec_out_t */
23448 	ASSERT(mp->b_datap->db_type == M_CTL);
23449 	ASSERT(!ipif->ipif_isv6);
23450 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
23451 
23452 	first_mp = mp;
23453 	mp = first_mp->b_cont;
23454 	ASSERT(mp->b_datap->db_type == M_DATA);
23455 	ipha = (ipha_t *)mp->b_rptr;
23456 
23457 	/*
23458 	 * Find an IRE which matches the destination and the outgoing
23459 	 * queue (i.e. the outgoing interface.)
23460 	 */
23461 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
23462 		dst = ipif->ipif_pp_dst_addr;
23463 	else
23464 		dst = ipha->ipha_dst;
23465 	/*
23466 	 * The source address has already been initialized by the
23467 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
23468 	 * be sufficient rather than MATCH_IRE_IPIF.
23469 	 *
23470 	 * This function is used for sending IGMP packets. We need
23471 	 * to make sure that we send the packet out of the interface
23472 	 * (ipif->ipif_ill) where we joined the group. This is to
23473 	 * prevent from switches doing IGMP snooping to send us multicast
23474 	 * packets for a given group on the interface we have joined.
23475 	 * If we can't find an ire, igmp_sendpkt has already initialized
23476 	 * ipsec_out_attach_if so that this will not be load spread in
23477 	 * ip_newroute_ipif.
23478 	 */
23479 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, NULL,
23480 	    MATCH_IRE_ILL);
23481 	if (!ire) {
23482 		/*
23483 		 * Mark this packet to make it be delivered to
23484 		 * ip_wput_ire after the new ire has been
23485 		 * created.
23486 		 */
23487 		mp->b_prev = NULL;
23488 		mp->b_next = NULL;
23489 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC);
23490 		return;
23491 	}
23492 
23493 	/*
23494 	 * Honor the RTF_SETSRC flag; this is the only case
23495 	 * where we force this addr whatever the current src addr is,
23496 	 * because this address is set by igmp_sendpkt(), and
23497 	 * cannot be specified by any user.
23498 	 */
23499 	if (ire->ire_flags & RTF_SETSRC) {
23500 		ipha->ipha_src = ire->ire_src_addr;
23501 	}
23502 
23503 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE);
23504 }
23505 
23506 /*
23507  * NOTE : This function does not ire_refrele the ire argument passed in.
23508  *
23509  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
23510  * failure. The ire_fp_mp can vanish any time in the case of IRE_MIPRTUN
23511  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
23512  * the ire_lock to access the ire_fp_mp in this case.
23513  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
23514  * prepending a fastpath message IPQoS processing must precede it, we also set
23515  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
23516  * (IPQoS might have set the b_band for CoS marking).
23517  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
23518  * must follow it so that IPQoS can mark the dl_priority field for CoS
23519  * marking, if needed.
23520  */
23521 static mblk_t *
23522 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
23523 {
23524 	uint_t	hlen;
23525 	ipha_t *ipha;
23526 	mblk_t *mp1;
23527 	boolean_t qos_done = B_FALSE;
23528 	uchar_t	*ll_hdr;
23529 
23530 #define	rptr	((uchar_t *)ipha)
23531 
23532 	ipha = (ipha_t *)mp->b_rptr;
23533 	hlen = 0;
23534 	LOCK_IRE_FP_MP(ire);
23535 	if ((mp1 = ire->ire_fp_mp) != NULL) {
23536 		ASSERT(DB_TYPE(mp1) == M_DATA);
23537 		/* Initiate IPPF processing */
23538 		if ((proc != 0) && IPP_ENABLED(proc)) {
23539 			UNLOCK_IRE_FP_MP(ire);
23540 			ip_process(proc, &mp, ill_index);
23541 			if (mp == NULL)
23542 				return (NULL);
23543 
23544 			ipha = (ipha_t *)mp->b_rptr;
23545 			LOCK_IRE_FP_MP(ire);
23546 			if ((mp1 = ire->ire_fp_mp) == NULL) {
23547 				qos_done = B_TRUE;
23548 				goto no_fp_mp;
23549 			}
23550 			ASSERT(DB_TYPE(mp1) == M_DATA);
23551 		}
23552 		hlen = MBLKL(mp1);
23553 		/*
23554 		 * Check if we have enough room to prepend fastpath
23555 		 * header
23556 		 */
23557 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
23558 			ll_hdr = rptr - hlen;
23559 			bcopy(mp1->b_rptr, ll_hdr, hlen);
23560 			/* XXX ipha is not aligned here */
23561 			ipha = (ipha_t *)(rptr - hlen);
23562 			/*
23563 			 * Set the b_rptr to the start of the link layer
23564 			 * header
23565 			 */
23566 			mp->b_rptr = rptr;
23567 			mp1 = mp;
23568 		} else {
23569 			mp1 = copyb(mp1);
23570 			if (mp1 == NULL)
23571 				goto unlock_err;
23572 			mp1->b_band = mp->b_band;
23573 			mp1->b_cont = mp;
23574 			/*
23575 			 * certain system generated traffic may not
23576 			 * have cred/label in ip header block. This
23577 			 * is true even for a labeled system. But for
23578 			 * labeled traffic, inherit the label in the
23579 			 * new header.
23580 			 */
23581 			if (DB_CRED(mp) != NULL)
23582 				mblk_setcred(mp1, DB_CRED(mp));
23583 			/*
23584 			 * XXX disable ICK_VALID and compute checksum
23585 			 * here; can happen if ire_fp_mp changes and
23586 			 * it can't be copied now due to insufficient
23587 			 * space. (unlikely, fp mp can change, but it
23588 			 * does not increase in length)
23589 			 */
23590 		}
23591 		UNLOCK_IRE_FP_MP(ire);
23592 	} else {
23593 no_fp_mp:
23594 		mp1 = copyb(ire->ire_dlureq_mp);
23595 		if (mp1 == NULL) {
23596 unlock_err:
23597 			UNLOCK_IRE_FP_MP(ire);
23598 			freemsg(mp);
23599 			return (NULL);
23600 		}
23601 		UNLOCK_IRE_FP_MP(ire);
23602 		mp1->b_cont = mp;
23603 		/*
23604 		 * certain system generated traffic may not
23605 		 * have cred/label in ip header block. This
23606 		 * is true even for a labeled system. But for
23607 		 * labeled traffic, inherit the label in the
23608 		 * new header.
23609 		 */
23610 		if (DB_CRED(mp) != NULL)
23611 			mblk_setcred(mp1, DB_CRED(mp));
23612 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
23613 			ip_process(proc, &mp1, ill_index);
23614 			if (mp1 == NULL)
23615 				return (NULL);
23616 		}
23617 	}
23618 	return (mp1);
23619 #undef rptr
23620 }
23621 
23622 /*
23623  * Finish the outbound IPsec processing for an IPv6 packet. This function
23624  * is called from ipsec_out_process() if the IPsec packet was processed
23625  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23626  * asynchronously.
23627  */
23628 void
23629 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
23630     ire_t *ire_arg)
23631 {
23632 	in6_addr_t *v6dstp;
23633 	ire_t *ire;
23634 	mblk_t *mp;
23635 	uint_t	ill_index;
23636 	ipsec_out_t *io;
23637 	boolean_t attach_if, hwaccel;
23638 	uint32_t flags = IP6_NO_IPPOLICY;
23639 	int match_flags;
23640 	zoneid_t zoneid;
23641 	boolean_t ill_need_rele = B_FALSE;
23642 	boolean_t ire_need_rele = B_FALSE;
23643 
23644 	mp = ipsec_mp->b_cont;
23645 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23646 	ill_index = io->ipsec_out_ill_index;
23647 	if (io->ipsec_out_reachable) {
23648 		flags |= IPV6_REACHABILITY_CONFIRMATION;
23649 	}
23650 	attach_if = io->ipsec_out_attach_if;
23651 	hwaccel = io->ipsec_out_accelerated;
23652 	zoneid = io->ipsec_out_zoneid;
23653 	ASSERT(zoneid != ALL_ZONES);
23654 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23655 	/* Multicast addresses should have non-zero ill_index. */
23656 	v6dstp = &ip6h->ip6_dst;
23657 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
23658 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
23659 	ASSERT(!attach_if || ill_index != 0);
23660 	if (ill_index != 0) {
23661 		if (ill == NULL) {
23662 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
23663 			    B_TRUE);
23664 
23665 			/* Failure case frees things for us. */
23666 			if (ill == NULL)
23667 				return;
23668 
23669 			ill_need_rele = B_TRUE;
23670 		}
23671 		/*
23672 		 * If this packet needs to go out on a particular interface
23673 		 * honor it.
23674 		 */
23675 		if (attach_if) {
23676 			match_flags = MATCH_IRE_ILL;
23677 
23678 			/*
23679 			 * Check if we need an ire that will not be
23680 			 * looked up by anybody else i.e. HIDDEN.
23681 			 */
23682 			if (ill_is_probeonly(ill)) {
23683 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23684 			}
23685 		}
23686 	}
23687 	ASSERT(mp != NULL);
23688 
23689 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
23690 		boolean_t unspec_src;
23691 		ipif_t	*ipif;
23692 
23693 		/*
23694 		 * Use the ill_index to get the right ill.
23695 		 */
23696 		unspec_src = io->ipsec_out_unspec_src;
23697 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23698 		if (ipif == NULL) {
23699 			if (ill_need_rele)
23700 				ill_refrele(ill);
23701 			freemsg(ipsec_mp);
23702 			return;
23703 		}
23704 
23705 		if (ire_arg != NULL) {
23706 			ire = ire_arg;
23707 		} else {
23708 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23709 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23710 			ire_need_rele = B_TRUE;
23711 		}
23712 		if (ire != NULL) {
23713 			ipif_refrele(ipif);
23714 			/*
23715 			 * XXX Do the multicast forwarding now, as the IPSEC
23716 			 * processing has been done.
23717 			 */
23718 			goto send;
23719 		}
23720 
23721 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
23722 		mp->b_prev = NULL;
23723 		mp->b_next = NULL;
23724 
23725 		/*
23726 		 * If the IPsec packet was processed asynchronously,
23727 		 * drop it now.
23728 		 */
23729 		if (q == NULL) {
23730 			if (ill_need_rele)
23731 				ill_refrele(ill);
23732 			freemsg(ipsec_mp);
23733 			return;
23734 		}
23735 
23736 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
23737 		    unspec_src, zoneid);
23738 		ipif_refrele(ipif);
23739 	} else {
23740 		if (attach_if) {
23741 			ipif_t	*ipif;
23742 
23743 			ipif = ipif_get_next_ipif(NULL, ill);
23744 			if (ipif == NULL) {
23745 				if (ill_need_rele)
23746 					ill_refrele(ill);
23747 				freemsg(ipsec_mp);
23748 				return;
23749 			}
23750 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
23751 			    zoneid, MBLK_GETLABEL(mp), match_flags);
23752 			ire_need_rele = B_TRUE;
23753 			ipif_refrele(ipif);
23754 		} else {
23755 			if (ire_arg != NULL) {
23756 				ire = ire_arg;
23757 			} else {
23758 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
23759 				ire_need_rele = B_TRUE;
23760 			}
23761 		}
23762 		if (ire != NULL)
23763 			goto send;
23764 		/*
23765 		 * ire disappeared underneath.
23766 		 *
23767 		 * What we need to do here is the ip_newroute
23768 		 * logic to get the ire without doing the IPSEC
23769 		 * processing. Follow the same old path. But this
23770 		 * time, ip_wput or ire_add_then_send will call us
23771 		 * directly as all the IPSEC operations are done.
23772 		 */
23773 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
23774 		mp->b_prev = NULL;
23775 		mp->b_next = NULL;
23776 
23777 		/*
23778 		 * If the IPsec packet was processed asynchronously,
23779 		 * drop it now.
23780 		 */
23781 		if (q == NULL) {
23782 			if (ill_need_rele)
23783 				ill_refrele(ill);
23784 			freemsg(ipsec_mp);
23785 			return;
23786 		}
23787 
23788 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
23789 		    zoneid);
23790 	}
23791 	if (ill != NULL && ill_need_rele)
23792 		ill_refrele(ill);
23793 	return;
23794 send:
23795 	if (ill != NULL && ill_need_rele)
23796 		ill_refrele(ill);
23797 
23798 	/* Local delivery */
23799 	if (ire->ire_stq == NULL) {
23800 		ASSERT(q != NULL);
23801 		ip_wput_local_v6(RD(q), ire->ire_ipif->ipif_ill, ip6h, ipsec_mp,
23802 		    ire, 0);
23803 		if (ire_need_rele)
23804 			ire_refrele(ire);
23805 		return;
23806 	}
23807 	/*
23808 	 * Everything is done. Send it out on the wire.
23809 	 * We force the insertion of a fragment header using the
23810 	 * IPH_FRAG_HDR flag in two cases:
23811 	 * - after reception of an ICMPv6 "packet too big" message
23812 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
23813 	 * - for multirouted IPv6 packets, so that the receiver can
23814 	 *   discard duplicates according to their fragment identifier
23815 	 */
23816 	/* XXX fix flow control problems. */
23817 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
23818 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
23819 		if (hwaccel) {
23820 			/*
23821 			 * hardware acceleration does not handle these
23822 			 * "slow path" cases.
23823 			 */
23824 			/* IPsec KSTATS: should bump bean counter here. */
23825 			if (ire_need_rele)
23826 				ire_refrele(ire);
23827 			freemsg(ipsec_mp);
23828 			return;
23829 		}
23830 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
23831 		    (mp->b_cont ? msgdsize(mp) :
23832 		    mp->b_wptr - (uchar_t *)ip6h)) {
23833 			/* IPsec KSTATS: should bump bean counter here. */
23834 			ip0dbg(("Packet length mismatch: %d, %ld\n",
23835 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
23836 			    msgdsize(mp)));
23837 			if (ire_need_rele)
23838 				ire_refrele(ire);
23839 			freemsg(ipsec_mp);
23840 			return;
23841 		}
23842 		ASSERT(mp->b_prev == NULL);
23843 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
23844 		    ntohs(ip6h->ip6_plen) +
23845 		    IPV6_HDR_LEN, ire->ire_max_frag));
23846 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
23847 		    ire->ire_max_frag);
23848 	} else {
23849 		UPDATE_OB_PKT_COUNT(ire);
23850 		ire->ire_last_used_time = lbolt;
23851 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
23852 	}
23853 	if (ire_need_rele)
23854 		ire_refrele(ire);
23855 	freeb(ipsec_mp);
23856 }
23857 
23858 void
23859 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
23860 {
23861 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
23862 	da_ipsec_t *hada;	/* data attributes */
23863 	ill_t *ill = (ill_t *)q->q_ptr;
23864 
23865 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
23866 
23867 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
23868 		/* IPsec KSTATS: Bump lose counter here! */
23869 		freemsg(mp);
23870 		return;
23871 	}
23872 
23873 	/*
23874 	 * It's an IPsec packet that must be
23875 	 * accelerated by the Provider, and the
23876 	 * outbound ill is IPsec acceleration capable.
23877 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
23878 	 * to the ill.
23879 	 * IPsec KSTATS: should bump packet counter here.
23880 	 */
23881 
23882 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
23883 	if (hada_mp == NULL) {
23884 		/* IPsec KSTATS: should bump packet counter here. */
23885 		freemsg(mp);
23886 		return;
23887 	}
23888 
23889 	hada_mp->b_datap->db_type = M_CTL;
23890 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
23891 	hada_mp->b_cont = mp;
23892 
23893 	hada = (da_ipsec_t *)hada_mp->b_rptr;
23894 	bzero(hada, sizeof (da_ipsec_t));
23895 	hada->da_type = IPHADA_M_CTL;
23896 
23897 	putnext(q, hada_mp);
23898 }
23899 
23900 /*
23901  * Finish the outbound IPsec processing. This function is called from
23902  * ipsec_out_process() if the IPsec packet was processed
23903  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
23904  * asynchronously.
23905  */
23906 void
23907 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
23908     ire_t *ire_arg)
23909 {
23910 	uint32_t v_hlen_tos_len;
23911 	ipaddr_t	dst;
23912 	ipif_t	*ipif = NULL;
23913 	ire_t *ire;
23914 	ire_t *ire1 = NULL;
23915 	mblk_t *next_mp = NULL;
23916 	uint32_t max_frag;
23917 	boolean_t multirt_send = B_FALSE;
23918 	mblk_t *mp;
23919 	mblk_t *mp1;
23920 	uint_t	ill_index;
23921 	ipsec_out_t *io;
23922 	boolean_t attach_if;
23923 	int match_flags, offset;
23924 	irb_t *irb = NULL;
23925 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
23926 	zoneid_t zoneid;
23927 	uint32_t cksum;
23928 	uint16_t *up;
23929 #ifdef	_BIG_ENDIAN
23930 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
23931 #else
23932 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
23933 #endif
23934 
23935 	mp = ipsec_mp->b_cont;
23936 	ASSERT(mp != NULL);
23937 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23938 	dst = ipha->ipha_dst;
23939 
23940 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
23941 	ill_index = io->ipsec_out_ill_index;
23942 	attach_if = io->ipsec_out_attach_if;
23943 	zoneid = io->ipsec_out_zoneid;
23944 	ASSERT(zoneid != ALL_ZONES);
23945 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
23946 	if (ill_index != 0) {
23947 		if (ill == NULL) {
23948 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
23949 			    ill_index, B_FALSE);
23950 
23951 			/* Failure case frees things for us. */
23952 			if (ill == NULL)
23953 				return;
23954 
23955 			ill_need_rele = B_TRUE;
23956 		}
23957 		/*
23958 		 * If this packet needs to go out on a particular interface
23959 		 * honor it.
23960 		 */
23961 		if (attach_if) {
23962 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
23963 
23964 			/*
23965 			 * Check if we need an ire that will not be
23966 			 * looked up by anybody else i.e. HIDDEN.
23967 			 */
23968 			if (ill_is_probeonly(ill)) {
23969 				match_flags |= MATCH_IRE_MARK_HIDDEN;
23970 			}
23971 		}
23972 	}
23973 
23974 	if (CLASSD(dst)) {
23975 		boolean_t conn_dontroute;
23976 		/*
23977 		 * Use the ill_index to get the right ipif.
23978 		 */
23979 		conn_dontroute = io->ipsec_out_dontroute;
23980 		if (ill_index == 0)
23981 			ipif = ipif_lookup_group(dst, zoneid);
23982 		else
23983 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
23984 		if (ipif == NULL) {
23985 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
23986 			    " multicast\n"));
23987 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
23988 			freemsg(ipsec_mp);
23989 			goto done;
23990 		}
23991 		/*
23992 		 * ipha_src has already been intialized with the
23993 		 * value of the ipif in ip_wput. All we need now is
23994 		 * an ire to send this downstream.
23995 		 */
23996 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
23997 		    MBLK_GETLABEL(mp), match_flags);
23998 		if (ire != NULL) {
23999 			ill_t *ill1;
24000 			/*
24001 			 * Do the multicast forwarding now, as the IPSEC
24002 			 * processing has been done.
24003 			 */
24004 			if (ip_g_mrouter && !conn_dontroute &&
24005 			    (ill1 = ire_to_ill(ire))) {
24006 				if (ip_mforward(ill1, ipha, mp)) {
24007 					freemsg(ipsec_mp);
24008 					ip1dbg(("ip_wput_ipsec_out: mforward "
24009 					    "failed\n"));
24010 					ire_refrele(ire);
24011 					goto done;
24012 				}
24013 			}
24014 			goto send;
24015 		}
24016 
24017 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
24018 		mp->b_prev = NULL;
24019 		mp->b_next = NULL;
24020 
24021 		/*
24022 		 * If the IPsec packet was processed asynchronously,
24023 		 * drop it now.
24024 		 */
24025 		if (q == NULL) {
24026 			freemsg(ipsec_mp);
24027 			goto done;
24028 		}
24029 
24030 		/*
24031 		 * We may be using a wrong ipif to create the ire.
24032 		 * But it is okay as the source address is assigned
24033 		 * for the packet already. Next outbound packet would
24034 		 * create the IRE with the right IPIF in ip_wput.
24035 		 *
24036 		 * Also handle RTF_MULTIRT routes.
24037 		 */
24038 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT);
24039 	} else {
24040 		if (attach_if) {
24041 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
24042 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24043 		} else {
24044 			if (ire_arg != NULL) {
24045 				ire = ire_arg;
24046 				ire_need_rele = B_FALSE;
24047 			} else {
24048 				ire = ire_cache_lookup(dst, zoneid,
24049 				    MBLK_GETLABEL(mp));
24050 			}
24051 		}
24052 		if (ire != NULL) {
24053 			goto send;
24054 		}
24055 
24056 		/*
24057 		 * ire disappeared underneath.
24058 		 *
24059 		 * What we need to do here is the ip_newroute
24060 		 * logic to get the ire without doing the IPSEC
24061 		 * processing. Follow the same old path. But this
24062 		 * time, ip_wput or ire_add_then_put will call us
24063 		 * directly as all the IPSEC operations are done.
24064 		 */
24065 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
24066 		mp->b_prev = NULL;
24067 		mp->b_next = NULL;
24068 
24069 		/*
24070 		 * If the IPsec packet was processed asynchronously,
24071 		 * drop it now.
24072 		 */
24073 		if (q == NULL) {
24074 			freemsg(ipsec_mp);
24075 			goto done;
24076 		}
24077 
24078 		/*
24079 		 * Since we're going through ip_newroute() again, we
24080 		 * need to make sure we don't:
24081 		 *
24082 		 *	1.) Trigger the ASSERT() with the ipha_ident
24083 		 *	    overloading.
24084 		 *	2.) Redo transport-layer checksumming, since we've
24085 		 *	    already done all that to get this far.
24086 		 *
24087 		 * The easiest way not do either of the above is to set
24088 		 * the ipha_ident field to IP_HDR_INCLUDED.
24089 		 */
24090 		ipha->ipha_ident = IP_HDR_INCLUDED;
24091 		ip_newroute(q, ipsec_mp, dst, NULL,
24092 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL));
24093 	}
24094 	goto done;
24095 send:
24096 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
24097 		/*
24098 		 * ESP NAT-Traversal packet.
24099 		 *
24100 		 * Just do software checksum for now.
24101 		 */
24102 
24103 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
24104 		IP_STAT(ip_out_sw_cksum);
24105 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
24106 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
24107 #define	iphs	((uint16_t *)ipha)
24108 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
24109 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
24110 		    IP_SIMPLE_HDR_LENGTH);
24111 #undef iphs
24112 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
24113 			cksum = 0xFFFF;
24114 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
24115 			if (mp1->b_wptr - mp1->b_rptr >=
24116 			    offset + sizeof (uint16_t)) {
24117 				up = (uint16_t *)(mp1->b_rptr + offset);
24118 				*up = cksum;
24119 				break;	/* out of for loop */
24120 			} else {
24121 				offset -= (mp->b_wptr - mp->b_rptr);
24122 			}
24123 	} /* Otherwise, just keep the all-zero checksum. */
24124 
24125 	if (ire->ire_stq == NULL) {
24126 		/*
24127 		 * Loopbacks go through ip_wput_local except for one case.
24128 		 * We come here if we generate a icmp_frag_needed message
24129 		 * after IPSEC processing is over. When this function calls
24130 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
24131 		 * icmp_frag_needed. The message generated comes back here
24132 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
24133 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
24134 		 * source address as it is usually set in ip_wput_ire. As
24135 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
24136 		 * and we end up here. We can't enter ip_wput_ire once the
24137 		 * IPSEC processing is over and hence we need to do it here.
24138 		 */
24139 		ASSERT(q != NULL);
24140 		UPDATE_OB_PKT_COUNT(ire);
24141 		ire->ire_last_used_time = lbolt;
24142 		if (ipha->ipha_src == 0)
24143 			ipha->ipha_src = ire->ire_src_addr;
24144 		ip_wput_local(RD(q), ire->ire_ipif->ipif_ill, ipha, ipsec_mp,
24145 		    ire, 0, zoneid);
24146 		if (ire_need_rele)
24147 			ire_refrele(ire);
24148 		goto done;
24149 	}
24150 
24151 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
24152 		/*
24153 		 * We are through with IPSEC processing.
24154 		 * Fragment this and send it on the wire.
24155 		 */
24156 		if (io->ipsec_out_accelerated) {
24157 			/*
24158 			 * The packet has been accelerated but must
24159 			 * be fragmented. This should not happen
24160 			 * since AH and ESP must not accelerate
24161 			 * packets that need fragmentation, however
24162 			 * the configuration could have changed
24163 			 * since the AH or ESP processing.
24164 			 * Drop packet.
24165 			 * IPsec KSTATS: bump bean counter here.
24166 			 */
24167 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
24168 			    "fragmented accelerated packet!\n"));
24169 			freemsg(ipsec_mp);
24170 		} else {
24171 			ip_wput_ire_fragmentit(ipsec_mp, ire);
24172 		}
24173 		if (ire_need_rele)
24174 			ire_refrele(ire);
24175 		goto done;
24176 	}
24177 
24178 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
24179 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
24180 	    (void *)ire->ire_ipif, (void *)ipif));
24181 
24182 	/*
24183 	 * Multiroute the secured packet, unless IPsec really
24184 	 * requires the packet to go out only through a particular
24185 	 * interface.
24186 	 */
24187 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
24188 		ire_t *first_ire;
24189 		irb = ire->ire_bucket;
24190 		ASSERT(irb != NULL);
24191 		/*
24192 		 * This ire has been looked up as the one that
24193 		 * goes through the given ipif;
24194 		 * make sure we do not omit any other multiroute ire
24195 		 * that may be present in the bucket before this one.
24196 		 */
24197 		IRB_REFHOLD(irb);
24198 		for (first_ire = irb->irb_ire;
24199 		    first_ire != NULL;
24200 		    first_ire = first_ire->ire_next) {
24201 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24202 			    (first_ire->ire_addr == ire->ire_addr) &&
24203 			    !(first_ire->ire_marks &
24204 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24205 				break;
24206 		}
24207 
24208 		if ((first_ire != NULL) && (first_ire != ire)) {
24209 			/*
24210 			 * Don't change the ire if the packet must
24211 			 * be fragmented if sent via this new one.
24212 			 */
24213 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
24214 				IRE_REFHOLD(first_ire);
24215 				if (ire_need_rele)
24216 					ire_refrele(ire);
24217 				else
24218 					ire_need_rele = B_TRUE;
24219 				ire = first_ire;
24220 			}
24221 		}
24222 		IRB_REFRELE(irb);
24223 
24224 		multirt_send = B_TRUE;
24225 		max_frag = ire->ire_max_frag;
24226 	} else {
24227 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
24228 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
24229 			    "flag, attach_if %d\n", attach_if));
24230 		}
24231 	}
24232 
24233 	/*
24234 	 * In most cases, the emission loop below is entered only once.
24235 	 * Only in the case where the ire holds the RTF_MULTIRT
24236 	 * flag, we loop to process all RTF_MULTIRT ires in the
24237 	 * bucket, and send the packet through all crossed
24238 	 * RTF_MULTIRT routes.
24239 	 */
24240 	do {
24241 		if (multirt_send) {
24242 			/*
24243 			 * ire1 holds here the next ire to process in the
24244 			 * bucket. If multirouting is expected,
24245 			 * any non-RTF_MULTIRT ire that has the
24246 			 * right destination address is ignored.
24247 			 */
24248 			ASSERT(irb != NULL);
24249 			IRB_REFHOLD(irb);
24250 			for (ire1 = ire->ire_next;
24251 			    ire1 != NULL;
24252 			    ire1 = ire1->ire_next) {
24253 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24254 					continue;
24255 				if (ire1->ire_addr != ire->ire_addr)
24256 					continue;
24257 				if (ire1->ire_marks &
24258 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24259 					continue;
24260 				/* No loopback here */
24261 				if (ire1->ire_stq == NULL)
24262 					continue;
24263 				/*
24264 				 * Ensure we do not exceed the MTU
24265 				 * of the next route.
24266 				 */
24267 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
24268 					ip_multirt_bad_mtu(ire1, max_frag);
24269 					continue;
24270 				}
24271 
24272 				IRE_REFHOLD(ire1);
24273 				break;
24274 			}
24275 			IRB_REFRELE(irb);
24276 			if (ire1 != NULL) {
24277 				/*
24278 				 * We are in a multiple send case, need to
24279 				 * make a copy of the packet.
24280 				 */
24281 				next_mp = copymsg(ipsec_mp);
24282 				if (next_mp == NULL) {
24283 					ire_refrele(ire1);
24284 					ire1 = NULL;
24285 				}
24286 			}
24287 		}
24288 
24289 		/* Everything is done. Send it out on the wire */
24290 		mp1 = ip_wput_attach_llhdr(mp, ire, 0, 0);
24291 		if (mp1 == NULL) {
24292 			BUMP_MIB(&ip_mib, ipOutDiscards);
24293 			freemsg(ipsec_mp);
24294 			if (ire_need_rele)
24295 				ire_refrele(ire);
24296 			if (ire1 != NULL) {
24297 				ire_refrele(ire1);
24298 				freemsg(next_mp);
24299 			}
24300 			goto done;
24301 		}
24302 		UPDATE_OB_PKT_COUNT(ire);
24303 		ire->ire_last_used_time = lbolt;
24304 		if (!io->ipsec_out_accelerated) {
24305 			putnext(ire->ire_stq, mp1);
24306 		} else {
24307 			/*
24308 			 * Safety Pup says: make sure this is going to
24309 			 * the right interface!
24310 			 */
24311 			ill_t *ill1 = (ill_t *)ire->ire_stq->q_ptr;
24312 			int ifindex = ill1->ill_phyint->phyint_ifindex;
24313 
24314 			if (ifindex != io->ipsec_out_capab_ill_index) {
24315 				/* IPsec kstats: bump lose counter */
24316 				freemsg(mp1);
24317 			} else {
24318 				ipsec_hw_putnext(ire->ire_stq, mp1);
24319 			}
24320 		}
24321 
24322 		freeb(ipsec_mp);
24323 		if (ire_need_rele)
24324 			ire_refrele(ire);
24325 
24326 		if (ire1 != NULL) {
24327 			ire = ire1;
24328 			ire_need_rele = B_TRUE;
24329 			ASSERT(next_mp);
24330 			ipsec_mp = next_mp;
24331 			mp = ipsec_mp->b_cont;
24332 			ire1 = NULL;
24333 			next_mp = NULL;
24334 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
24335 		} else {
24336 			multirt_send = B_FALSE;
24337 		}
24338 	} while (multirt_send);
24339 done:
24340 	if (ill != NULL && ill_need_rele)
24341 		ill_refrele(ill);
24342 	if (ipif != NULL)
24343 		ipif_refrele(ipif);
24344 }
24345 
24346 /*
24347  * Get the ill corresponding to the specified ire, and compare its
24348  * capabilities with the protocol and algorithms specified by the
24349  * the SA obtained from ipsec_out. If they match, annotate the
24350  * ipsec_out structure to indicate that the packet needs acceleration.
24351  *
24352  *
24353  * A packet is eligible for outbound hardware acceleration if the
24354  * following conditions are satisfied:
24355  *
24356  * 1. the packet will not be fragmented
24357  * 2. the provider supports the algorithm
24358  * 3. there is no pending control message being exchanged
24359  * 4. snoop is not attached
24360  * 5. the destination address is not a broadcast or multicast address.
24361  *
24362  * Rationale:
24363  *	- Hardware drivers do not support fragmentation with
24364  *	  the current interface.
24365  *	- snoop, multicast, and broadcast may result in exposure of
24366  *	  a cleartext datagram.
24367  * We check all five of these conditions here.
24368  *
24369  * XXX would like to nuke "ire_t *" parameter here; problem is that
24370  * IRE is only way to figure out if a v4 address is a broadcast and
24371  * thus ineligible for acceleration...
24372  */
24373 static void
24374 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
24375 {
24376 	ipsec_out_t *io;
24377 	mblk_t *data_mp;
24378 	uint_t plen, overhead;
24379 
24380 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
24381 		return;
24382 
24383 	if (ill == NULL)
24384 		return;
24385 
24386 	/*
24387 	 * Destination address is a broadcast or multicast.  Punt.
24388 	 */
24389 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
24390 	    IRE_LOCAL)))
24391 		return;
24392 
24393 	data_mp = ipsec_mp->b_cont;
24394 
24395 	if (ill->ill_isv6) {
24396 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
24397 
24398 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
24399 			return;
24400 
24401 		plen = ip6h->ip6_plen;
24402 	} else {
24403 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
24404 
24405 		if (CLASSD(ipha->ipha_dst))
24406 			return;
24407 
24408 		plen = ipha->ipha_length;
24409 	}
24410 	/*
24411 	 * Is there a pending DLPI control message being exchanged
24412 	 * between IP/IPsec and the DLS Provider? If there is, it
24413 	 * could be a SADB update, and the state of the DLS Provider
24414 	 * SADB might not be in sync with the SADB maintained by
24415 	 * IPsec. To avoid dropping packets or using the wrong keying
24416 	 * material, we do not accelerate this packet.
24417 	 */
24418 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
24419 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24420 		    "ill_dlpi_pending! don't accelerate packet\n"));
24421 		return;
24422 	}
24423 
24424 	/*
24425 	 * Is the Provider in promiscous mode? If it does, we don't
24426 	 * accelerate the packet since it will bounce back up to the
24427 	 * listeners in the clear.
24428 	 */
24429 	if (ill->ill_promisc_on_phys) {
24430 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
24431 		    "ill in promiscous mode, don't accelerate packet\n"));
24432 		return;
24433 	}
24434 
24435 	/*
24436 	 * Will the packet require fragmentation?
24437 	 */
24438 
24439 	/*
24440 	 * IPsec ESP note: this is a pessimistic estimate, but the same
24441 	 * as is used elsewhere.
24442 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
24443 	 *	+ 2-byte trailer
24444 	 */
24445 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
24446 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
24447 
24448 	if ((plen + overhead) > ill->ill_max_mtu)
24449 		return;
24450 
24451 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24452 
24453 	/*
24454 	 * Can the ill accelerate this IPsec protocol and algorithm
24455 	 * specified by the SA?
24456 	 */
24457 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
24458 	    ill->ill_isv6, sa)) {
24459 		return;
24460 	}
24461 
24462 	/*
24463 	 * Tell AH or ESP that the outbound ill is capable of
24464 	 * accelerating this packet.
24465 	 */
24466 	io->ipsec_out_is_capab_ill = B_TRUE;
24467 }
24468 
24469 /*
24470  * Select which AH & ESP SA's to use (if any) for the outbound packet.
24471  *
24472  * If this function returns B_TRUE, the requested SA's have been filled
24473  * into the ipsec_out_*_sa pointers.
24474  *
24475  * If the function returns B_FALSE, the packet has been "consumed", most
24476  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
24477  *
24478  * The SA references created by the protocol-specific "select"
24479  * function will be released when the ipsec_mp is freed, thanks to the
24480  * ipsec_out_free destructor -- see spd.c.
24481  */
24482 static boolean_t
24483 ipsec_out_select_sa(mblk_t *ipsec_mp)
24484 {
24485 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
24486 	ipsec_out_t *io;
24487 	ipsec_policy_t *pp;
24488 	ipsec_action_t *ap;
24489 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24490 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24491 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24492 
24493 	if (!io->ipsec_out_secure) {
24494 		/*
24495 		 * We came here by mistake.
24496 		 * Don't bother with ipsec processing
24497 		 * We should "discourage" this path in the future.
24498 		 */
24499 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24500 		return (B_FALSE);
24501 	}
24502 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24503 	ASSERT((io->ipsec_out_policy != NULL) ||
24504 	    (io->ipsec_out_act != NULL));
24505 
24506 	ASSERT(io->ipsec_out_failed == B_FALSE);
24507 
24508 	/*
24509 	 * IPSEC processing has started.
24510 	 */
24511 	io->ipsec_out_proc_begin = B_TRUE;
24512 	ap = io->ipsec_out_act;
24513 	if (ap == NULL) {
24514 		pp = io->ipsec_out_policy;
24515 		ASSERT(pp != NULL);
24516 		ap = pp->ipsp_act;
24517 		ASSERT(ap != NULL);
24518 	}
24519 
24520 	/*
24521 	 * We have an action.  now, let's select SA's.
24522 	 * (In the future, we can cache this in the conn_t..)
24523 	 */
24524 	if (ap->ipa_want_esp) {
24525 		if (io->ipsec_out_esp_sa == NULL) {
24526 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
24527 			    IPPROTO_ESP);
24528 		}
24529 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
24530 	}
24531 
24532 	if (ap->ipa_want_ah) {
24533 		if (io->ipsec_out_ah_sa == NULL) {
24534 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
24535 			    IPPROTO_AH);
24536 		}
24537 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
24538 		/*
24539 		 * The ESP and AH processing order needs to be preserved
24540 		 * when both protocols are required (ESP should be applied
24541 		 * before AH for an outbound packet). Force an ESP ACQUIRE
24542 		 * when both ESP and AH are required, and an AH ACQUIRE
24543 		 * is needed.
24544 		 */
24545 		if (ap->ipa_want_esp && need_ah_acquire)
24546 			need_esp_acquire = B_TRUE;
24547 	}
24548 
24549 	/*
24550 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
24551 	 * Release SAs that got referenced, but will not be used until we
24552 	 * acquire _all_ of the SAs we need.
24553 	 */
24554 	if (need_ah_acquire || need_esp_acquire) {
24555 		if (io->ipsec_out_ah_sa != NULL) {
24556 			IPSA_REFRELE(io->ipsec_out_ah_sa);
24557 			io->ipsec_out_ah_sa = NULL;
24558 		}
24559 		if (io->ipsec_out_esp_sa != NULL) {
24560 			IPSA_REFRELE(io->ipsec_out_esp_sa);
24561 			io->ipsec_out_esp_sa = NULL;
24562 		}
24563 
24564 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
24565 		return (B_FALSE);
24566 	}
24567 
24568 	return (B_TRUE);
24569 }
24570 
24571 /*
24572  * Process an IPSEC_OUT message and see what you can
24573  * do with it.
24574  * IPQoS Notes:
24575  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
24576  * IPSec.
24577  * XXX would like to nuke ire_t.
24578  * XXX ill_index better be "real"
24579  */
24580 void
24581 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
24582 {
24583 	ipsec_out_t *io;
24584 	ipsec_policy_t *pp;
24585 	ipsec_action_t *ap;
24586 	ipha_t *ipha;
24587 	ip6_t *ip6h;
24588 	mblk_t *mp;
24589 	ill_t *ill;
24590 	zoneid_t zoneid;
24591 	ipsec_status_t ipsec_rc;
24592 	boolean_t ill_need_rele = B_FALSE;
24593 
24594 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24595 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
24596 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
24597 	mp = ipsec_mp->b_cont;
24598 
24599 	/*
24600 	 * Initiate IPPF processing. We do it here to account for packets
24601 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
24602 	 * We can check for ipsec_out_proc_begin even for such packets, as
24603 	 * they will always be false (asserted below).
24604 	 */
24605 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
24606 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
24607 		    io->ipsec_out_ill_index : ill_index);
24608 		if (mp == NULL) {
24609 			ip2dbg(("ipsec_out_process: packet dropped "\
24610 			    "during IPPF processing\n"));
24611 			freeb(ipsec_mp);
24612 			BUMP_MIB(&ip_mib, ipOutDiscards);
24613 			return;
24614 		}
24615 	}
24616 
24617 	if (!io->ipsec_out_secure) {
24618 		/*
24619 		 * We came here by mistake.
24620 		 * Don't bother with ipsec processing
24621 		 * Should "discourage" this path in the future.
24622 		 */
24623 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
24624 		goto done;
24625 	}
24626 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
24627 	ASSERT((io->ipsec_out_policy != NULL) ||
24628 	    (io->ipsec_out_act != NULL));
24629 	ASSERT(io->ipsec_out_failed == B_FALSE);
24630 
24631 	if (!ipsec_loaded()) {
24632 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
24633 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24634 			BUMP_MIB(&ip_mib, ipOutDiscards);
24635 		} else {
24636 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
24637 		}
24638 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
24639 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
24640 		return;
24641 	}
24642 
24643 	/*
24644 	 * IPSEC processing has started.
24645 	 */
24646 	io->ipsec_out_proc_begin = B_TRUE;
24647 	ap = io->ipsec_out_act;
24648 	if (ap == NULL) {
24649 		pp = io->ipsec_out_policy;
24650 		ASSERT(pp != NULL);
24651 		ap = pp->ipsp_act;
24652 		ASSERT(ap != NULL);
24653 	}
24654 
24655 	/*
24656 	 * Save the outbound ill index. When the packet comes back
24657 	 * from IPsec, we make sure the ill hasn't changed or disappeared
24658 	 * before sending it the accelerated packet.
24659 	 */
24660 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
24661 		int ifindex;
24662 		ill = ire_to_ill(ire);
24663 		ifindex = ill->ill_phyint->phyint_ifindex;
24664 		io->ipsec_out_capab_ill_index = ifindex;
24665 	}
24666 
24667 	/*
24668 	 * The order of processing is first insert a IP header if needed.
24669 	 * Then insert the ESP header and then the AH header.
24670 	 */
24671 	if ((io->ipsec_out_se_done == B_FALSE) &&
24672 	    (ap->ipa_want_se)) {
24673 		/*
24674 		 * First get the outer IP header before sending
24675 		 * it to ESP.
24676 		 */
24677 		ipha_t *oipha, *iipha;
24678 		mblk_t *outer_mp, *inner_mp;
24679 
24680 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
24681 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
24682 			    "ipsec_out_process: "
24683 			    "Self-Encapsulation failed: Out of memory\n");
24684 			freemsg(ipsec_mp);
24685 			BUMP_MIB(&ip_mib, ipOutDiscards);
24686 			return;
24687 		}
24688 		inner_mp = ipsec_mp->b_cont;
24689 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
24690 		oipha = (ipha_t *)outer_mp->b_rptr;
24691 		iipha = (ipha_t *)inner_mp->b_rptr;
24692 		*oipha = *iipha;
24693 		outer_mp->b_wptr += sizeof (ipha_t);
24694 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
24695 		    sizeof (ipha_t));
24696 		oipha->ipha_protocol = IPPROTO_ENCAP;
24697 		oipha->ipha_version_and_hdr_length =
24698 		    IP_SIMPLE_HDR_VERSION;
24699 		oipha->ipha_hdr_checksum = 0;
24700 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
24701 		outer_mp->b_cont = inner_mp;
24702 		ipsec_mp->b_cont = outer_mp;
24703 
24704 		io->ipsec_out_se_done = B_TRUE;
24705 		io->ipsec_out_encaps = B_TRUE;
24706 	}
24707 
24708 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
24709 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
24710 	    !ipsec_out_select_sa(ipsec_mp))
24711 		return;
24712 
24713 	/*
24714 	 * By now, we know what SA's to use.  Toss over to ESP & AH
24715 	 * to do the heavy lifting.
24716 	 */
24717 	zoneid = io->ipsec_out_zoneid;
24718 	ASSERT(zoneid != ALL_ZONES);
24719 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
24720 		ASSERT(io->ipsec_out_esp_sa != NULL);
24721 		io->ipsec_out_esp_done = B_TRUE;
24722 		/*
24723 		 * Note that since hw accel can only apply one transform,
24724 		 * not two, we skip hw accel for ESP if we also have AH
24725 		 * This is an design limitation of the interface
24726 		 * which should be revisited.
24727 		 */
24728 		ASSERT(ire != NULL);
24729 		if (io->ipsec_out_ah_sa == NULL) {
24730 			ill = (ill_t *)ire->ire_stq->q_ptr;
24731 			ipsec_out_is_accelerated(ipsec_mp,
24732 			    io->ipsec_out_esp_sa, ill, ire);
24733 		}
24734 
24735 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
24736 		switch (ipsec_rc) {
24737 		case IPSEC_STATUS_SUCCESS:
24738 			break;
24739 		case IPSEC_STATUS_FAILED:
24740 			BUMP_MIB(&ip_mib, ipOutDiscards);
24741 			/* FALLTHRU */
24742 		case IPSEC_STATUS_PENDING:
24743 			return;
24744 		}
24745 	}
24746 
24747 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
24748 		ASSERT(io->ipsec_out_ah_sa != NULL);
24749 		io->ipsec_out_ah_done = B_TRUE;
24750 		if (ire == NULL) {
24751 			int idx = io->ipsec_out_capab_ill_index;
24752 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
24753 			    NULL, NULL, NULL, NULL);
24754 			ill_need_rele = B_TRUE;
24755 		} else {
24756 			ill = (ill_t *)ire->ire_stq->q_ptr;
24757 		}
24758 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
24759 		    ire);
24760 
24761 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
24762 		switch (ipsec_rc) {
24763 		case IPSEC_STATUS_SUCCESS:
24764 			break;
24765 		case IPSEC_STATUS_FAILED:
24766 			BUMP_MIB(&ip_mib, ipOutDiscards);
24767 			/* FALLTHRU */
24768 		case IPSEC_STATUS_PENDING:
24769 			if (ill != NULL && ill_need_rele)
24770 				ill_refrele(ill);
24771 			return;
24772 		}
24773 	}
24774 	/*
24775 	 * We are done with IPSEC processing. Send it over
24776 	 * the wire.
24777 	 */
24778 done:
24779 	mp = ipsec_mp->b_cont;
24780 	ipha = (ipha_t *)mp->b_rptr;
24781 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
24782 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
24783 	} else {
24784 		ip6h = (ip6_t *)ipha;
24785 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
24786 	}
24787 	if (ill != NULL && ill_need_rele)
24788 		ill_refrele(ill);
24789 }
24790 
24791 /* ARGSUSED */
24792 void
24793 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
24794 {
24795 	opt_restart_t	*or;
24796 	int	err;
24797 	conn_t	*connp;
24798 
24799 	ASSERT(CONN_Q(q));
24800 	connp = Q_TO_CONN(q);
24801 
24802 	ASSERT(first_mp->b_datap->db_type == M_CTL);
24803 	or = (opt_restart_t *)first_mp->b_rptr;
24804 	/*
24805 	 * We don't need to pass any credentials here since this is just
24806 	 * a restart. The credentials are passed in when svr4_optcom_req
24807 	 * is called the first time (from ip_wput_nondata).
24808 	 */
24809 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
24810 		err = svr4_optcom_req(q, first_mp, NULL,
24811 		    &ip_opt_obj);
24812 	} else {
24813 		ASSERT(or->or_type == T_OPTMGMT_REQ);
24814 		err = tpi_optcom_req(q, first_mp, NULL,
24815 		    &ip_opt_obj);
24816 	}
24817 	if (err != EINPROGRESS) {
24818 		/* operation is done */
24819 		CONN_OPER_PENDING_DONE(connp);
24820 	}
24821 }
24822 
24823 /*
24824  * ioctls that go through a down/up sequence may need to wait for the down
24825  * to complete. This involves waiting for the ire and ipif refcnts to go down
24826  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
24827  */
24828 /* ARGSUSED */
24829 void
24830 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
24831 {
24832 	struct iocblk *iocp;
24833 	mblk_t *mp1;
24834 	ipif_t	*ipif;
24835 	ip_ioctl_cmd_t *ipip;
24836 	int err;
24837 	sin_t	*sin;
24838 	struct lifreq *lifr;
24839 	struct ifreq *ifr;
24840 
24841 	iocp = (struct iocblk *)mp->b_rptr;
24842 	ASSERT(ipsq != NULL);
24843 	/* Existence of mp1 verified in ip_wput_nondata */
24844 	mp1 = mp->b_cont->b_cont;
24845 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24846 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
24847 		ill_t *ill;
24848 		/*
24849 		 * Special case where ipsq_current_ipif may not be set.
24850 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
24851 		 * ill could also have become part of a ipmp group in the
24852 		 * process, we are here as were not able to complete the
24853 		 * operation in ipif_set_values because we could not become
24854 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
24855 		 * will not be set so we need to set it.
24856 		 */
24857 		ill = (ill_t *)q->q_ptr;
24858 		ipsq->ipsq_current_ipif = ill->ill_ipif;
24859 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
24860 	}
24861 
24862 	ipif = ipsq->ipsq_current_ipif;
24863 	ASSERT(ipif != NULL);
24864 	if (ipip->ipi_cmd_type == IF_CMD) {
24865 		/* This a old style SIOC[GS]IF* command */
24866 		ifr = (struct ifreq *)mp1->b_rptr;
24867 		sin = (sin_t *)&ifr->ifr_addr;
24868 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
24869 		/* This a new style SIOC[GS]LIF* command */
24870 		lifr = (struct lifreq *)mp1->b_rptr;
24871 		sin = (sin_t *)&lifr->lifr_addr;
24872 	} else {
24873 		sin = NULL;
24874 	}
24875 
24876 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
24877 	    (void *)mp1->b_rptr);
24878 
24879 	/* SIOCLIFREMOVEIF could have removed the ipif */
24880 	ip_ioctl_finish(q, mp, err,
24881 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24882 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
24883 }
24884 
24885 /*
24886  * ioctl processing
24887  *
24888  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
24889  * the ioctl command in the ioctl tables and determines the copyin data size
24890  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
24891  * size.
24892  *
24893  * ioctl processing then continues when the M_IOCDATA makes its way down.
24894  * Now the ioctl is looked up again in the ioctl table, and its properties are
24895  * extracted. The associated 'conn' is then refheld till the end of the ioctl
24896  * and the general ioctl processing function ip_process_ioctl is called.
24897  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
24898  * so goes thru the serialization primitive ipsq_try_enter. Then the
24899  * appropriate function to handle the ioctl is called based on the entry in
24900  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
24901  * which also refreleases the 'conn' that was refheld at the start of the
24902  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
24903  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
24904  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
24905  *
24906  * Many exclusive ioctls go thru an internal down up sequence as part of
24907  * the operation. For example an attempt to change the IP address of an
24908  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
24909  * does all the cleanup such as deleting all ires that use this address.
24910  * Then we need to wait till all references to the interface go away.
24911  */
24912 void
24913 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
24914 {
24915 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
24916 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
24917 	cmd_info_t ci;
24918 	int err;
24919 	boolean_t entered_ipsq = B_FALSE;
24920 
24921 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
24922 
24923 	if (ipip == NULL)
24924 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
24925 
24926 	/*
24927 	 * SIOCLIFADDIF needs to go thru a special path since the
24928 	 * ill may not exist yet. This happens in the case of lo0
24929 	 * which is created using this ioctl.
24930 	 */
24931 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
24932 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
24933 		ip_ioctl_finish(q, mp, err,
24934 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
24935 		    NULL, NULL);
24936 		return;
24937 	}
24938 
24939 	ci.ci_ipif = NULL;
24940 	switch (ipip->ipi_cmd_type) {
24941 	case IF_CMD:
24942 	case LIF_CMD:
24943 		/*
24944 		 * ioctls that pass in a [l]ifreq appear here.
24945 		 * ip_extract_lifreq_cmn returns a refheld ipif in
24946 		 * ci.ci_ipif
24947 		 */
24948 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
24949 		    ipip->ipi_flags, &ci, ip_process_ioctl);
24950 		if (err != 0) {
24951 			ip_ioctl_finish(q, mp, err,
24952 			    ipip->ipi_flags & IPI_GET_CMD ?
24953 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24954 			return;
24955 		}
24956 		ASSERT(ci.ci_ipif != NULL);
24957 		break;
24958 
24959 	case TUN_CMD:
24960 		/*
24961 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
24962 		 * a refheld ipif in ci.ci_ipif
24963 		 */
24964 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
24965 		if (err != 0) {
24966 			ip_ioctl_finish(q, mp, err,
24967 			    ipip->ipi_flags & IPI_GET_CMD ?
24968 			    COPYOUT : NO_COPYOUT, NULL, NULL);
24969 			return;
24970 		}
24971 		ASSERT(ci.ci_ipif != NULL);
24972 		break;
24973 
24974 	case MISC_CMD:
24975 		/*
24976 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
24977 		 * For eg. SIOCGLIFCONF will appear here.
24978 		 */
24979 		switch (ipip->ipi_cmd) {
24980 		case IF_UNITSEL:
24981 			/* ioctl comes down the ill */
24982 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
24983 			ipif_refhold(ci.ci_ipif);
24984 			break;
24985 		case SIOCGMSFILTER:
24986 		case SIOCSMSFILTER:
24987 		case SIOCGIPMSFILTER:
24988 		case SIOCSIPMSFILTER:
24989 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
24990 			    ip_process_ioctl);
24991 			if (err != 0) {
24992 				ip_ioctl_finish(q, mp, err,
24993 				    ipip->ipi_flags & IPI_GET_CMD ?
24994 				    COPYOUT : NO_COPYOUT, NULL, NULL);
24995 				return;
24996 			}
24997 			break;
24998 		}
24999 		err = 0;
25000 		ci.ci_sin = NULL;
25001 		ci.ci_sin6 = NULL;
25002 		ci.ci_lifr = NULL;
25003 		break;
25004 	}
25005 
25006 	/*
25007 	 * If ipsq is non-null, we are already being called exclusively
25008 	 */
25009 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
25010 	if (!(ipip->ipi_flags & IPI_WR)) {
25011 		/*
25012 		 * A return value of EINPROGRESS means the ioctl is
25013 		 * either queued and waiting for some reason or has
25014 		 * already completed.
25015 		 */
25016 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25017 		    ci.ci_lifr);
25018 		if (ci.ci_ipif != NULL)
25019 			ipif_refrele(ci.ci_ipif);
25020 		ip_ioctl_finish(q, mp, err,
25021 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25022 		    NULL, NULL);
25023 		return;
25024 	}
25025 
25026 	ASSERT(ci.ci_ipif != NULL);
25027 
25028 	if (ipsq == NULL) {
25029 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
25030 		    ip_process_ioctl, NEW_OP, B_TRUE);
25031 		entered_ipsq = B_TRUE;
25032 	}
25033 	/*
25034 	 * Release the ipif so that ipif_down and friends that wait for
25035 	 * references to go away are not misled about the current ipif_refcnt
25036 	 * values. We are writer so we can access the ipif even after releasing
25037 	 * the ipif.
25038 	 */
25039 	ipif_refrele(ci.ci_ipif);
25040 	if (ipsq == NULL)
25041 		return;
25042 
25043 	mutex_enter(&ipsq->ipsq_lock);
25044 	ASSERT(ipsq->ipsq_current_ipif == NULL);
25045 	ipsq->ipsq_current_ipif = ci.ci_ipif;
25046 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
25047 	mutex_exit(&ipsq->ipsq_lock);
25048 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
25049 	/*
25050 	 * For most set ioctls that come here, this serves as a single point
25051 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
25052 	 * be any new references to the ipif. This helps functions that go
25053 	 * through this path and end up trying to wait for the refcnts
25054 	 * associated with the ipif to go down to zero. Some exceptions are
25055 	 * Failover, Failback, and Groupname commands that operate on more than
25056 	 * just the ci.ci_ipif. These commands internally determine the
25057 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
25058 	 * flags on that set. Another exception is the Removeif command that
25059 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
25060 	 * ipif to operate on.
25061 	 */
25062 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
25063 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
25064 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
25065 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
25066 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
25067 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
25068 
25069 	/*
25070 	 * A return value of EINPROGRESS means the ioctl is
25071 	 * either queued and waiting for some reason or has
25072 	 * already completed.
25073 	 */
25074 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
25075 	    ci.ci_lifr);
25076 
25077 	/* SIOCLIFREMOVEIF could have removed the ipif */
25078 	ip_ioctl_finish(q, mp, err,
25079 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
25080 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
25081 
25082 	if (entered_ipsq)
25083 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
25084 }
25085 
25086 /*
25087  * Complete the ioctl. Typically ioctls use the mi package and need to
25088  * do mi_copyout/mi_copy_done.
25089  */
25090 void
25091 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
25092     ipif_t *ipif, ipsq_t *ipsq)
25093 {
25094 	conn_t	*connp = NULL;
25095 
25096 	if (err == EINPROGRESS)
25097 		return;
25098 
25099 	if (CONN_Q(q)) {
25100 		connp = Q_TO_CONN(q);
25101 		ASSERT(connp->conn_ref >= 2);
25102 	}
25103 
25104 	switch (mode) {
25105 	case COPYOUT:
25106 		if (err == 0)
25107 			mi_copyout(q, mp);
25108 		else
25109 			mi_copy_done(q, mp, err);
25110 		break;
25111 
25112 	case NO_COPYOUT:
25113 		mi_copy_done(q, mp, err);
25114 		break;
25115 
25116 	default:
25117 		/* An ioctl aborted through a conn close would take this path */
25118 		break;
25119 	}
25120 
25121 	/*
25122 	 * The refhold placed at the start of the ioctl is released here.
25123 	 */
25124 	if (connp != NULL)
25125 		CONN_OPER_PENDING_DONE(connp);
25126 
25127 	/*
25128 	 * If the ioctl were an exclusive ioctl it would have set
25129 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
25130 	 */
25131 	if (ipif != NULL) {
25132 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
25133 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
25134 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
25135 	}
25136 
25137 	/*
25138 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
25139 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
25140 	 * entering the ipsq
25141 	 */
25142 	if (ipsq != NULL) {
25143 		mutex_enter(&ipsq->ipsq_lock);
25144 		ipsq->ipsq_current_ipif = NULL;
25145 		mutex_exit(&ipsq->ipsq_lock);
25146 	}
25147 }
25148 
25149 /*
25150  * This is called from ip_wput_nondata to resume a deferred TCP bind.
25151  */
25152 /* ARGSUSED */
25153 void
25154 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
25155 {
25156 	conn_t *connp = arg;
25157 	tcp_t	*tcp;
25158 
25159 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
25160 	tcp = connp->conn_tcp;
25161 
25162 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
25163 		freemsg(mp);
25164 	else
25165 		tcp_rput_other(tcp, mp);
25166 	CONN_OPER_PENDING_DONE(connp);
25167 }
25168 
25169 /* Called from ip_wput for all non data messages */
25170 /* ARGSUSED */
25171 void
25172 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
25173 {
25174 	mblk_t		*mp1;
25175 	ire_t		*ire;
25176 	ill_t		*ill;
25177 	struct iocblk	*iocp;
25178 	ip_ioctl_cmd_t	*ipip;
25179 	cred_t		*cr;
25180 	conn_t		*connp = NULL;
25181 	int		cmd, err;
25182 
25183 	if (CONN_Q(q))
25184 		connp = Q_TO_CONN(q);
25185 
25186 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
25187 
25188 	/* Check if it is a queue to /dev/sctp. */
25189 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
25190 	    connp->conn_rq == NULL) {
25191 		sctp_wput(q, mp);
25192 		return;
25193 	}
25194 
25195 	switch (DB_TYPE(mp)) {
25196 	case M_IOCTL:
25197 		/*
25198 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
25199 		 * will arrange to copy in associated control structures.
25200 		 */
25201 		ip_sioctl_copyin_setup(q, mp);
25202 		return;
25203 	case M_IOCDATA:
25204 		/*
25205 		 * Ensure that this is associated with one of our trans-
25206 		 * parent ioctls.  If it's not ours, discard it if we're
25207 		 * running as a driver, or pass it on if we're a module.
25208 		 */
25209 		iocp = (struct iocblk *)mp->b_rptr;
25210 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
25211 		if (ipip == NULL) {
25212 			if (q->q_next == NULL) {
25213 				goto nak;
25214 			} else {
25215 				putnext(q, mp);
25216 			}
25217 			return;
25218 		} else if ((q->q_next != NULL) &&
25219 		    !(ipip->ipi_flags & IPI_MODOK)) {
25220 			/*
25221 			 * the ioctl is one we recognise, but is not
25222 			 * consumed by IP as a module, pass M_IOCDATA
25223 			 * for processing downstream, but only for
25224 			 * common Streams ioctls.
25225 			 */
25226 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
25227 				putnext(q, mp);
25228 				return;
25229 			} else {
25230 				goto nak;
25231 			}
25232 		}
25233 
25234 		/* IOCTL continuation following copyin or copyout. */
25235 		if (mi_copy_state(q, mp, NULL) == -1) {
25236 			/*
25237 			 * The copy operation failed.  mi_copy_state already
25238 			 * cleaned up, so we're out of here.
25239 			 */
25240 			return;
25241 		}
25242 		/*
25243 		 * If we just completed a copy in, we become writer and
25244 		 * continue processing in ip_sioctl_copyin_done.  If it
25245 		 * was a copy out, we call mi_copyout again.  If there is
25246 		 * nothing more to copy out, it will complete the IOCTL.
25247 		 */
25248 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
25249 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
25250 				mi_copy_done(q, mp, EPROTO);
25251 				return;
25252 			}
25253 			/*
25254 			 * Check for cases that need more copying.  A return
25255 			 * value of 0 means a second copyin has been started,
25256 			 * so we return; a return value of 1 means no more
25257 			 * copying is needed, so we continue.
25258 			 */
25259 			cmd = iocp->ioc_cmd;
25260 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
25261 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
25262 			    MI_COPY_COUNT(mp) == 1) {
25263 				if (ip_copyin_msfilter(q, mp) == 0)
25264 					return;
25265 			}
25266 			/*
25267 			 * Refhold the conn, till the ioctl completes. This is
25268 			 * needed in case the ioctl ends up in the pending mp
25269 			 * list. Every mp in the ill_pending_mp list and
25270 			 * the ipsq_pending_mp must have a refhold on the conn
25271 			 * to resume processing. The refhold is released when
25272 			 * the ioctl completes. (normally or abnormally)
25273 			 * In all cases ip_ioctl_finish is called to finish
25274 			 * the ioctl.
25275 			 */
25276 			if (connp != NULL) {
25277 				/* This is not a reentry */
25278 				ASSERT(ipsq == NULL);
25279 				CONN_INC_REF(connp);
25280 			} else {
25281 				if (!(ipip->ipi_flags & IPI_MODOK)) {
25282 					mi_copy_done(q, mp, EINVAL);
25283 					return;
25284 				}
25285 			}
25286 
25287 			ip_process_ioctl(ipsq, q, mp, ipip);
25288 
25289 		} else {
25290 			mi_copyout(q, mp);
25291 		}
25292 		return;
25293 nak:
25294 		iocp->ioc_error = EINVAL;
25295 		mp->b_datap->db_type = M_IOCNAK;
25296 		iocp->ioc_count = 0;
25297 		qreply(q, mp);
25298 		return;
25299 
25300 	case M_IOCNAK:
25301 		/*
25302 		 * The only way we could get here is if a resolver didn't like
25303 		 * an IOCTL we sent it.	 This shouldn't happen.
25304 		 */
25305 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
25306 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
25307 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
25308 		freemsg(mp);
25309 		return;
25310 	case M_IOCACK:
25311 		/* Finish socket ioctls passed through to ARP. */
25312 		ip_sioctl_iocack(q, mp);
25313 		return;
25314 	case M_FLUSH:
25315 		if (*mp->b_rptr & FLUSHW)
25316 			flushq(q, FLUSHALL);
25317 		if (q->q_next) {
25318 			/*
25319 			 * M_FLUSH is sent up to IP by some drivers during
25320 			 * unbind. ip_rput has already replied to it. We are
25321 			 * here for the M_FLUSH that we originated in IP
25322 			 * before sending the unbind request to the driver.
25323 			 * Just free it as we don't queue packets in IP
25324 			 * on the write side of the device instance.
25325 			 */
25326 			freemsg(mp);
25327 			return;
25328 		}
25329 		if (*mp->b_rptr & FLUSHR) {
25330 			*mp->b_rptr &= ~FLUSHW;
25331 			qreply(q, mp);
25332 			return;
25333 		}
25334 		freemsg(mp);
25335 		return;
25336 	case IRE_DB_REQ_TYPE:
25337 		/* An Upper Level Protocol wants a copy of an IRE. */
25338 		ip_ire_req(q, mp);
25339 		return;
25340 	case M_CTL:
25341 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
25342 			break;
25343 
25344 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
25345 		    IP_ULP_OUT_LABELED) {
25346 			out_labeled_t *olp;
25347 
25348 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
25349 				break;
25350 			olp = (out_labeled_t *)mp->b_rptr;
25351 			connp->conn_ulp_labeled = olp->out_qnext == q;
25352 			freemsg(mp);
25353 			return;
25354 		}
25355 
25356 		/* M_CTL messages are used by ARP to tell us things. */
25357 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
25358 			break;
25359 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
25360 		case AR_ENTRY_SQUERY:
25361 			ip_wput_ctl(q, mp);
25362 			return;
25363 		case AR_CLIENT_NOTIFY:
25364 			ip_arp_news(q, mp);
25365 			return;
25366 		case AR_DLPIOP_DONE:
25367 			ASSERT(q->q_next != NULL);
25368 			ill = (ill_t *)q->q_ptr;
25369 			/* qwriter_ip releases the refhold */
25370 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
25371 			ill_refhold(ill);
25372 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
25373 			    CUR_OP, B_FALSE);
25374 			return;
25375 		case AR_ARP_CLOSING:
25376 			/*
25377 			 * ARP (above us) is closing. If no ARP bringup is
25378 			 * currently pending, ack the message so that ARP
25379 			 * can complete its close. Also mark ill_arp_closing
25380 			 * so that new ARP bringups will fail. If any
25381 			 * ARP bringup is currently in progress, we will
25382 			 * ack this when the current ARP bringup completes.
25383 			 */
25384 			ASSERT(q->q_next != NULL);
25385 			ill = (ill_t *)q->q_ptr;
25386 			mutex_enter(&ill->ill_lock);
25387 			ill->ill_arp_closing = 1;
25388 			if (!ill->ill_arp_bringup_pending) {
25389 				mutex_exit(&ill->ill_lock);
25390 				qreply(q, mp);
25391 			} else {
25392 				mutex_exit(&ill->ill_lock);
25393 				freemsg(mp);
25394 			}
25395 			return;
25396 		default:
25397 			break;
25398 		}
25399 		break;
25400 	case M_PROTO:
25401 	case M_PCPROTO:
25402 		/*
25403 		 * The only PROTO messages we expect are ULP binds and
25404 		 * copies of option negotiation acknowledgements.
25405 		 */
25406 		switch (((union T_primitives *)mp->b_rptr)->type) {
25407 		case O_T_BIND_REQ:
25408 		case T_BIND_REQ: {
25409 			/* Request can get queued in bind */
25410 			ASSERT(connp != NULL);
25411 			/*
25412 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
25413 			 * instead of going through this path.  We only get
25414 			 * here in the following cases:
25415 			 *
25416 			 * a. Bind retries, where ipsq is non-NULL.
25417 			 * b. T_BIND_REQ is issued from non TCP/UDP
25418 			 *    transport, e.g. icmp for raw socket,
25419 			 *    in which case ipsq will be NULL.
25420 			 */
25421 			ASSERT(ipsq != NULL ||
25422 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
25423 
25424 			/* Don't increment refcnt if this is a re-entry */
25425 			if (ipsq == NULL)
25426 				CONN_INC_REF(connp);
25427 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
25428 			    connp, NULL) : ip_bind_v4(q, mp, connp);
25429 			if (mp == NULL)
25430 				return;
25431 			if (IPCL_IS_TCP(connp)) {
25432 				/*
25433 				 * In the case of TCP endpoint we
25434 				 * come here only for bind retries
25435 				 */
25436 				ASSERT(ipsq != NULL);
25437 				CONN_INC_REF(connp);
25438 				squeue_fill(connp->conn_sqp, mp,
25439 				    ip_resume_tcp_bind, connp,
25440 				    SQTAG_BIND_RETRY);
25441 				return;
25442 			} else if (IPCL_IS_UDP(connp)) {
25443 				/*
25444 				 * In the case of UDP endpoint we
25445 				 * come here only for bind retries
25446 				 */
25447 				ASSERT(ipsq != NULL);
25448 				udp_resume_bind(connp, mp);
25449 				return;
25450 			}
25451 			qreply(q, mp);
25452 			CONN_OPER_PENDING_DONE(connp);
25453 			return;
25454 		}
25455 		case T_SVR4_OPTMGMT_REQ:
25456 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
25457 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
25458 
25459 			ASSERT(connp != NULL);
25460 			if (!snmpcom_req(q, mp, ip_snmp_set,
25461 			    ip_snmp_get, cr)) {
25462 				/*
25463 				 * Call svr4_optcom_req so that it can
25464 				 * generate the ack. We don't come here
25465 				 * if this operation is being restarted.
25466 				 * ip_restart_optmgmt will drop the conn ref.
25467 				 * In the case of ipsec option after the ipsec
25468 				 * load is complete conn_restart_ipsec_waiter
25469 				 * drops the conn ref.
25470 				 */
25471 				ASSERT(ipsq == NULL);
25472 				CONN_INC_REF(connp);
25473 				if (ip_check_for_ipsec_opt(q, mp))
25474 					return;
25475 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
25476 				if (err != EINPROGRESS) {
25477 					/* Operation is done */
25478 					CONN_OPER_PENDING_DONE(connp);
25479 				}
25480 			}
25481 			return;
25482 		case T_OPTMGMT_REQ:
25483 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
25484 			/*
25485 			 * Note: No snmpcom_req support through new
25486 			 * T_OPTMGMT_REQ.
25487 			 * Call tpi_optcom_req so that it can
25488 			 * generate the ack.
25489 			 */
25490 			ASSERT(connp != NULL);
25491 			ASSERT(ipsq == NULL);
25492 			/*
25493 			 * We don't come here for restart. ip_restart_optmgmt
25494 			 * will drop the conn ref. In the case of ipsec option
25495 			 * after the ipsec load is complete
25496 			 * conn_restart_ipsec_waiter drops the conn ref.
25497 			 */
25498 			CONN_INC_REF(connp);
25499 			if (ip_check_for_ipsec_opt(q, mp))
25500 				return;
25501 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
25502 			if (err != EINPROGRESS) {
25503 				/* Operation is done */
25504 				CONN_OPER_PENDING_DONE(connp);
25505 			}
25506 			return;
25507 		case T_UNBIND_REQ:
25508 			mp = ip_unbind(q, mp);
25509 			qreply(q, mp);
25510 			return;
25511 		default:
25512 			/*
25513 			 * Have to drop any DLPI messages coming down from
25514 			 * arp (such as an info_req which would cause ip
25515 			 * to receive an extra info_ack if it was passed
25516 			 * through.
25517 			 */
25518 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
25519 			    (int)*(uint_t *)mp->b_rptr));
25520 			freemsg(mp);
25521 			return;
25522 		}
25523 		/* NOTREACHED */
25524 	case IRE_DB_TYPE: {
25525 		nce_t		*nce;
25526 		ill_t		*ill;
25527 		in6_addr_t	gw_addr_v6;
25528 
25529 
25530 		/*
25531 		 * This is a response back from a resolver.  It
25532 		 * consists of a message chain containing:
25533 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
25534 		 * The IRE_MBLK is the one we allocated in ip_newroute.
25535 		 * The LL_HDR_MBLK is the DLPI header to use to get
25536 		 * the attached packet, and subsequent ones for the
25537 		 * same destination, transmitted.
25538 		 */
25539 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
25540 			break;
25541 		/*
25542 		 * First, check to make sure the resolution succeeded.
25543 		 * If it failed, the second mblk will be empty.
25544 		 * If it is, free the chain, dropping the packet.
25545 		 * (We must ire_delete the ire; that frees the ire mblk)
25546 		 * We're doing this now to support PVCs for ATM; it's
25547 		 * a partial xresolv implementation. When we fully implement
25548 		 * xresolv interfaces, instead of freeing everything here
25549 		 * we'll initiate neighbor discovery.
25550 		 *
25551 		 * For v4 (ARP and other external resolvers) the resolver
25552 		 * frees the message, so no check is needed. This check
25553 		 * is required, though, for a full xresolve implementation.
25554 		 * Including this code here now both shows how external
25555 		 * resolvers can NACK a resolution request using an
25556 		 * existing design that has no specific provisions for NACKs,
25557 		 * and also takes into account that the current non-ARP
25558 		 * external resolver has been coded to use this method of
25559 		 * NACKing for all IPv6 (xresolv) cases,
25560 		 * whether our xresolv implementation is complete or not.
25561 		 *
25562 		 */
25563 		ire = (ire_t *)mp->b_rptr;
25564 		ill = ire_to_ill(ire);
25565 		mp1 = mp->b_cont;		/* dl_unitdata_req */
25566 		if (mp1->b_rptr == mp1->b_wptr) {
25567 			if (ire->ire_ipversion == IPV6_VERSION) {
25568 				/*
25569 				 * XRESOLV interface.
25570 				 */
25571 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
25572 				mutex_enter(&ire->ire_lock);
25573 				gw_addr_v6 = ire->ire_gateway_addr_v6;
25574 				mutex_exit(&ire->ire_lock);
25575 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25576 					nce = ndp_lookup(ill,
25577 					    &ire->ire_addr_v6, B_FALSE);
25578 				} else {
25579 					nce = ndp_lookup(ill, &gw_addr_v6,
25580 					    B_FALSE);
25581 				}
25582 				if (nce != NULL) {
25583 					nce_resolv_failed(nce);
25584 					ndp_delete(nce);
25585 					NCE_REFRELE(nce);
25586 				}
25587 			}
25588 			mp->b_cont = NULL;
25589 			freemsg(mp1);		/* frees the pkt as well */
25590 			ire_delete((ire_t *)mp->b_rptr);
25591 			return;
25592 		}
25593 		/*
25594 		 * Split them into IRE_MBLK and pkt and feed it into
25595 		 * ire_add_then_send. Then in ire_add_then_send
25596 		 * the IRE will be added, and then the packet will be
25597 		 * run back through ip_wput. This time it will make
25598 		 * it to the wire.
25599 		 */
25600 		mp->b_cont = NULL;
25601 		mp = mp1->b_cont;		/* now, mp points to pkt */
25602 		mp1->b_cont = NULL;
25603 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
25604 		if (ire->ire_ipversion == IPV6_VERSION) {
25605 			/*
25606 			 * XRESOLV interface. Find the nce and put a copy
25607 			 * of the dl_unitdata_req in nce_res_mp
25608 			 */
25609 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
25610 			mutex_enter(&ire->ire_lock);
25611 			gw_addr_v6 = ire->ire_gateway_addr_v6;
25612 			mutex_exit(&ire->ire_lock);
25613 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
25614 				nce = ndp_lookup(ill, &ire->ire_addr_v6,
25615 				    B_FALSE);
25616 			} else {
25617 				nce = ndp_lookup(ill, &gw_addr_v6, B_FALSE);
25618 			}
25619 			if (nce != NULL) {
25620 				/*
25621 				 * We have to protect nce_res_mp here
25622 				 * from being accessed by other threads
25623 				 * while we change the mblk pointer.
25624 				 * Other functions will also lock the nce when
25625 				 * accessing nce_res_mp.
25626 				 *
25627 				 * The reason we change the mblk pointer
25628 				 * here rather than copying the resolved address
25629 				 * into the template is that, unlike with
25630 				 * ethernet, we have no guarantee that the
25631 				 * resolved address length will be
25632 				 * smaller than or equal to the lla length
25633 				 * with which the template was allocated,
25634 				 * (for ethernet, they're equal)
25635 				 * so we have to use the actual resolved
25636 				 * address mblk - which holds the real
25637 				 * dl_unitdata_req with the resolved address.
25638 				 *
25639 				 * Doing this is the same behavior as was
25640 				 * previously used in the v4 ARP case.
25641 				 */
25642 				mutex_enter(&nce->nce_lock);
25643 				if (nce->nce_res_mp != NULL)
25644 					freemsg(nce->nce_res_mp);
25645 				nce->nce_res_mp = mp1;
25646 				mutex_exit(&nce->nce_lock);
25647 				/*
25648 				 * We do a fastpath probe here because
25649 				 * we have resolved the address without
25650 				 * using Neighbor Discovery.
25651 				 * In the non-XRESOLV v6 case, the fastpath
25652 				 * probe is done right after neighbor
25653 				 * discovery completes.
25654 				 */
25655 				if (nce->nce_res_mp != NULL) {
25656 					int res;
25657 					nce_fastpath_list_add(nce);
25658 					res = ill_fastpath_probe(ill,
25659 					    nce->nce_res_mp);
25660 					if (res != 0 && res != EAGAIN)
25661 						nce_fastpath_list_delete(nce);
25662 				}
25663 
25664 				ire_add_then_send(q, ire, mp);
25665 				/*
25666 				 * Now we have to clean out any packets
25667 				 * that may have been queued on the nce
25668 				 * while it was waiting for address resolution
25669 				 * to complete.
25670 				 */
25671 				mutex_enter(&nce->nce_lock);
25672 				mp1 = nce->nce_qd_mp;
25673 				nce->nce_qd_mp = NULL;
25674 				mutex_exit(&nce->nce_lock);
25675 				while (mp1 != NULL) {
25676 					mblk_t *nxt_mp;
25677 					queue_t *fwdq = NULL;
25678 					ill_t   *inbound_ill;
25679 					uint_t ifindex;
25680 
25681 					nxt_mp = mp1->b_next;
25682 					mp1->b_next = NULL;
25683 					/*
25684 					 * Retrieve ifindex stored in
25685 					 * ip_rput_data_v6()
25686 					 */
25687 					ifindex =
25688 					    (uint_t)(uintptr_t)mp1->b_prev;
25689 					inbound_ill =
25690 						ill_lookup_on_ifindex(ifindex,
25691 						    B_TRUE, NULL, NULL, NULL,
25692 						    NULL);
25693 					mp1->b_prev = NULL;
25694 					if (inbound_ill != NULL)
25695 						fwdq = inbound_ill->ill_rq;
25696 
25697 					if (fwdq != NULL) {
25698 						put(fwdq, mp1);
25699 						ill_refrele(inbound_ill);
25700 					} else
25701 						put(WR(ill->ill_rq), mp1);
25702 					mp1 = nxt_mp;
25703 				}
25704 				NCE_REFRELE(nce);
25705 			} else {	/* nce is NULL; clean up */
25706 				ire_delete(ire);
25707 				freemsg(mp);
25708 				freemsg(mp1);
25709 				return;
25710 			}
25711 		} else {
25712 			ire->ire_dlureq_mp = mp1;
25713 			ire_add_then_send(q, ire, mp);
25714 		}
25715 		return;	/* All is well, the packet has been sent. */
25716 	}
25717 	default:
25718 		break;
25719 	}
25720 	if (q->q_next) {
25721 		putnext(q, mp);
25722 	} else
25723 		freemsg(mp);
25724 }
25725 
25726 /*
25727  * Process IP options in an outbound packet.  Modify the destination if there
25728  * is a source route option.
25729  * Returns non-zero if something fails in which case an ICMP error has been
25730  * sent and mp freed.
25731  */
25732 static int
25733 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
25734     boolean_t mctl_present, zoneid_t zoneid)
25735 {
25736 	ipoptp_t	opts;
25737 	uchar_t		*opt;
25738 	uint8_t		optval;
25739 	uint8_t		optlen;
25740 	ipaddr_t	dst;
25741 	intptr_t	code = 0;
25742 	mblk_t		*mp;
25743 	ire_t		*ire = NULL;
25744 
25745 	ip2dbg(("ip_wput_options\n"));
25746 	mp = ipsec_mp;
25747 	if (mctl_present) {
25748 		mp = ipsec_mp->b_cont;
25749 	}
25750 
25751 	dst = ipha->ipha_dst;
25752 	for (optval = ipoptp_first(&opts, ipha);
25753 	    optval != IPOPT_EOL;
25754 	    optval = ipoptp_next(&opts)) {
25755 		opt = opts.ipoptp_cur;
25756 		optlen = opts.ipoptp_len;
25757 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
25758 		    optval, optlen));
25759 		switch (optval) {
25760 			uint32_t off;
25761 		case IPOPT_SSRR:
25762 		case IPOPT_LSRR:
25763 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25764 				ip1dbg((
25765 				    "ip_wput_options: bad option offset\n"));
25766 				code = (char *)&opt[IPOPT_OLEN] -
25767 				    (char *)ipha;
25768 				goto param_prob;
25769 			}
25770 			off = opt[IPOPT_OFFSET];
25771 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
25772 			    ntohl(dst)));
25773 			/*
25774 			 * For strict: verify that dst is directly
25775 			 * reachable.
25776 			 */
25777 			if (optval == IPOPT_SSRR) {
25778 				ire = ire_ftable_lookup(dst, 0, 0,
25779 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
25780 				    MBLK_GETLABEL(mp),
25781 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
25782 				if (ire == NULL) {
25783 					ip1dbg(("ip_wput_options: SSRR not"
25784 					    " directly reachable: 0x%x\n",
25785 					    ntohl(dst)));
25786 					goto bad_src_route;
25787 				}
25788 				ire_refrele(ire);
25789 			}
25790 			break;
25791 		case IPOPT_RR:
25792 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25793 				ip1dbg((
25794 				    "ip_wput_options: bad option offset\n"));
25795 				code = (char *)&opt[IPOPT_OLEN] -
25796 				    (char *)ipha;
25797 				goto param_prob;
25798 			}
25799 			break;
25800 		case IPOPT_TS:
25801 			/*
25802 			 * Verify that length >=5 and that there is either
25803 			 * room for another timestamp or that the overflow
25804 			 * counter is not maxed out.
25805 			 */
25806 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
25807 			if (optlen < IPOPT_MINLEN_IT) {
25808 				goto param_prob;
25809 			}
25810 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
25811 				ip1dbg((
25812 				    "ip_wput_options: bad option offset\n"));
25813 				code = (char *)&opt[IPOPT_OFFSET] -
25814 				    (char *)ipha;
25815 				goto param_prob;
25816 			}
25817 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25818 			case IPOPT_TS_TSONLY:
25819 				off = IPOPT_TS_TIMELEN;
25820 				break;
25821 			case IPOPT_TS_TSANDADDR:
25822 			case IPOPT_TS_PRESPEC:
25823 			case IPOPT_TS_PRESPEC_RFC791:
25824 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25825 				break;
25826 			default:
25827 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
25828 				    (char *)ipha;
25829 				goto param_prob;
25830 			}
25831 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
25832 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
25833 				/*
25834 				 * No room and the overflow counter is 15
25835 				 * already.
25836 				 */
25837 				goto param_prob;
25838 			}
25839 			break;
25840 		}
25841 	}
25842 
25843 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
25844 		return (0);
25845 
25846 	ip1dbg(("ip_wput_options: error processing IP options."));
25847 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
25848 
25849 param_prob:
25850 	/*
25851 	 * Since ip_wput() isn't close to finished, we fill
25852 	 * in enough of the header for credible error reporting.
25853 	 */
25854 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25855 		/* Failed */
25856 		freemsg(ipsec_mp);
25857 		return (-1);
25858 	}
25859 	icmp_param_problem(q, ipsec_mp, (uint8_t)code);
25860 	return (-1);
25861 
25862 bad_src_route:
25863 	/*
25864 	 * Since ip_wput() isn't close to finished, we fill
25865 	 * in enough of the header for credible error reporting.
25866 	 */
25867 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
25868 		/* Failed */
25869 		freemsg(ipsec_mp);
25870 		return (-1);
25871 	}
25872 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED);
25873 	return (-1);
25874 }
25875 
25876 /*
25877  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
25878  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
25879  * thru /etc/system.
25880  */
25881 #define	CONN_MAXDRAINCNT	64
25882 
25883 static void
25884 conn_drain_init(void)
25885 {
25886 	int i;
25887 
25888 	conn_drain_list_cnt = conn_drain_nthreads;
25889 
25890 	if ((conn_drain_list_cnt == 0) ||
25891 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
25892 		/*
25893 		 * Default value of the number of drainers is the
25894 		 * number of cpus, subject to maximum of 8 drainers.
25895 		 */
25896 		if (boot_max_ncpus != -1)
25897 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
25898 		else
25899 			conn_drain_list_cnt = MIN(max_ncpus, 8);
25900 	}
25901 
25902 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
25903 	    KM_SLEEP);
25904 
25905 	for (i = 0; i < conn_drain_list_cnt; i++) {
25906 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
25907 		    MUTEX_DEFAULT, NULL);
25908 	}
25909 }
25910 
25911 static void
25912 conn_drain_fini(void)
25913 {
25914 	int i;
25915 
25916 	for (i = 0; i < conn_drain_list_cnt; i++)
25917 		mutex_destroy(&conn_drain_list[i].idl_lock);
25918 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
25919 	conn_drain_list = NULL;
25920 }
25921 
25922 /*
25923  * Note: For an overview of how flowcontrol is handled in IP please see the
25924  * IP Flowcontrol notes at the top of this file.
25925  *
25926  * Flow control has blocked us from proceeding. Insert the given conn in one
25927  * of the conn drain lists. These conn wq's will be qenabled later on when
25928  * STREAMS flow control does a backenable. conn_walk_drain will enable
25929  * the first conn in each of these drain lists. Each of these qenabled conns
25930  * in turn enables the next in the list, after it runs, or when it closes,
25931  * thus sustaining the drain process.
25932  *
25933  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
25934  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
25935  * running at any time, on a given conn, since there can be only 1 service proc
25936  * running on a queue at any time.
25937  */
25938 void
25939 conn_drain_insert(conn_t *connp)
25940 {
25941 	idl_t	*idl;
25942 	uint_t	index;
25943 
25944 	mutex_enter(&connp->conn_lock);
25945 	if (connp->conn_state_flags & CONN_CLOSING) {
25946 		/*
25947 		 * The conn is closing as a result of which CONN_CLOSING
25948 		 * is set. Return.
25949 		 */
25950 		mutex_exit(&connp->conn_lock);
25951 		return;
25952 	} else if (connp->conn_idl == NULL) {
25953 		/*
25954 		 * Assign the next drain list round robin. We dont' use
25955 		 * a lock, and thus it may not be strictly round robin.
25956 		 * Atomicity of load/stores is enough to make sure that
25957 		 * conn_drain_list_index is always within bounds.
25958 		 */
25959 		index = conn_drain_list_index;
25960 		ASSERT(index < conn_drain_list_cnt);
25961 		connp->conn_idl = &conn_drain_list[index];
25962 		index++;
25963 		if (index == conn_drain_list_cnt)
25964 			index = 0;
25965 		conn_drain_list_index = index;
25966 	}
25967 	mutex_exit(&connp->conn_lock);
25968 
25969 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
25970 	if ((connp->conn_drain_prev != NULL) ||
25971 	    (connp->conn_state_flags & CONN_CLOSING)) {
25972 		/*
25973 		 * The conn is already in the drain list, OR
25974 		 * the conn is closing. We need to check again for
25975 		 * the closing case again since close can happen
25976 		 * after we drop the conn_lock, and before we
25977 		 * acquire the CONN_DRAIN_LIST_LOCK.
25978 		 */
25979 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
25980 		return;
25981 	} else {
25982 		idl = connp->conn_idl;
25983 	}
25984 
25985 	/*
25986 	 * The conn is not in the drain list. Insert it at the
25987 	 * tail of the drain list. The drain list is circular
25988 	 * and doubly linked. idl_conn points to the 1st element
25989 	 * in the list.
25990 	 */
25991 	if (idl->idl_conn == NULL) {
25992 		idl->idl_conn = connp;
25993 		connp->conn_drain_next = connp;
25994 		connp->conn_drain_prev = connp;
25995 	} else {
25996 		conn_t *head = idl->idl_conn;
25997 
25998 		connp->conn_drain_next = head;
25999 		connp->conn_drain_prev = head->conn_drain_prev;
26000 		head->conn_drain_prev->conn_drain_next = connp;
26001 		head->conn_drain_prev = connp;
26002 	}
26003 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26004 }
26005 
26006 /*
26007  * This conn is closing, and we are called from ip_close. OR
26008  * This conn has been serviced by ip_wsrv, and we need to do the tail
26009  * processing.
26010  * If this conn is part of the drain list, we may need to sustain the drain
26011  * process by qenabling the next conn in the drain list. We may also need to
26012  * remove this conn from the list, if it is done.
26013  */
26014 static void
26015 conn_drain_tail(conn_t *connp, boolean_t closing)
26016 {
26017 	idl_t *idl;
26018 
26019 	/*
26020 	 * connp->conn_idl is stable at this point, and no lock is needed
26021 	 * to check it. If we are called from ip_close, close has already
26022 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
26023 	 * called us only because conn_idl is non-null. If we are called thru
26024 	 * service, conn_idl could be null, but it cannot change because
26025 	 * service is single-threaded per queue, and there cannot be another
26026 	 * instance of service trying to call conn_drain_insert on this conn
26027 	 * now.
26028 	 */
26029 	ASSERT(!closing || (connp->conn_idl != NULL));
26030 
26031 	/*
26032 	 * If connp->conn_idl is null, the conn has not been inserted into any
26033 	 * drain list even once since creation of the conn. Just return.
26034 	 */
26035 	if (connp->conn_idl == NULL)
26036 		return;
26037 
26038 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
26039 
26040 	if (connp->conn_drain_prev == NULL) {
26041 		/* This conn is currently not in the drain list.  */
26042 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26043 		return;
26044 	}
26045 	idl = connp->conn_idl;
26046 	if (idl->idl_conn_draining == connp) {
26047 		/*
26048 		 * This conn is the current drainer. If this is the last conn
26049 		 * in the drain list, we need to do more checks, in the 'if'
26050 		 * below. Otherwwise we need to just qenable the next conn,
26051 		 * to sustain the draining, and is handled in the 'else'
26052 		 * below.
26053 		 */
26054 		if (connp->conn_drain_next == idl->idl_conn) {
26055 			/*
26056 			 * This conn is the last in this list. This round
26057 			 * of draining is complete. If idl_repeat is set,
26058 			 * it means another flow enabling has happened from
26059 			 * the driver/streams and we need to another round
26060 			 * of draining.
26061 			 * If there are more than 2 conns in the drain list,
26062 			 * do a left rotate by 1, so that all conns except the
26063 			 * conn at the head move towards the head by 1, and the
26064 			 * the conn at the head goes to the tail. This attempts
26065 			 * a more even share for all queues that are being
26066 			 * drained.
26067 			 */
26068 			if ((connp->conn_drain_next != connp) &&
26069 			    (idl->idl_conn->conn_drain_next != connp)) {
26070 				idl->idl_conn = idl->idl_conn->conn_drain_next;
26071 			}
26072 			if (idl->idl_repeat) {
26073 				qenable(idl->idl_conn->conn_wq);
26074 				idl->idl_conn_draining = idl->idl_conn;
26075 				idl->idl_repeat = 0;
26076 			} else {
26077 				idl->idl_conn_draining = NULL;
26078 			}
26079 		} else {
26080 			/*
26081 			 * If the next queue that we are now qenable'ing,
26082 			 * is closing, it will remove itself from this list
26083 			 * and qenable the subsequent queue in ip_close().
26084 			 * Serialization is acheived thru idl_lock.
26085 			 */
26086 			qenable(connp->conn_drain_next->conn_wq);
26087 			idl->idl_conn_draining = connp->conn_drain_next;
26088 		}
26089 	}
26090 	if (!connp->conn_did_putbq || closing) {
26091 		/*
26092 		 * Remove ourself from the drain list, if we did not do
26093 		 * a putbq, or if the conn is closing.
26094 		 * Note: It is possible that q->q_first is non-null. It means
26095 		 * that these messages landed after we did a enableok() in
26096 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
26097 		 * service them.
26098 		 */
26099 		if (connp->conn_drain_next == connp) {
26100 			/* Singleton in the list */
26101 			ASSERT(connp->conn_drain_prev == connp);
26102 			idl->idl_conn = NULL;
26103 			idl->idl_conn_draining = NULL;
26104 		} else {
26105 			connp->conn_drain_prev->conn_drain_next =
26106 			    connp->conn_drain_next;
26107 			connp->conn_drain_next->conn_drain_prev =
26108 			    connp->conn_drain_prev;
26109 			if (idl->idl_conn == connp)
26110 				idl->idl_conn = connp->conn_drain_next;
26111 			ASSERT(idl->idl_conn_draining != connp);
26112 
26113 		}
26114 		connp->conn_drain_next = NULL;
26115 		connp->conn_drain_prev = NULL;
26116 	}
26117 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
26118 }
26119 
26120 /*
26121  * Write service routine. Shared perimeter entry point.
26122  * ip_wsrv can be called in any of the following ways.
26123  * 1. The device queue's messages has fallen below the low water mark
26124  *    and STREAMS has backenabled the ill_wq. We walk thru all the
26125  *    the drain lists and backenable the first conn in each list.
26126  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
26127  *    qenabled non-tcp upper layers. We start dequeing messages and call
26128  *    ip_wput for each message.
26129  */
26130 
26131 void
26132 ip_wsrv(queue_t *q)
26133 {
26134 	conn_t	*connp;
26135 	ill_t	*ill;
26136 	mblk_t	*mp;
26137 
26138 	if (q->q_next) {
26139 		ill = (ill_t *)q->q_ptr;
26140 		if (ill->ill_state_flags == 0) {
26141 			/*
26142 			 * The device flow control has opened up.
26143 			 * Walk through conn drain lists and qenable the
26144 			 * first conn in each list. This makes sense only
26145 			 * if the stream is fully plumbed and setup.
26146 			 * Hence the if check above.
26147 			 */
26148 			ip1dbg(("ip_wsrv: walking\n"));
26149 			conn_walk_drain();
26150 		}
26151 		return;
26152 	}
26153 
26154 	connp = Q_TO_CONN(q);
26155 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
26156 
26157 	/*
26158 	 * 1. Set conn_draining flag to signal that service is active.
26159 	 *
26160 	 * 2. ip_output determines whether it has been called from service,
26161 	 *    based on the last parameter. If it is IP_WSRV it concludes it
26162 	 *    has been called from service.
26163 	 *
26164 	 * 3. Message ordering is preserved by the following logic.
26165 	 *    i. A directly called ip_output (i.e. not thru service) will queue
26166 	 *    the message at the tail, if conn_draining is set (i.e. service
26167 	 *    is running) or if q->q_first is non-null.
26168 	 *
26169 	 *    ii. If ip_output is called from service, and if ip_output cannot
26170 	 *    putnext due to flow control, it does a putbq.
26171 	 *
26172 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
26173 	 *    (causing an infinite loop).
26174 	 */
26175 	ASSERT(!connp->conn_did_putbq);
26176 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
26177 		connp->conn_draining = 1;
26178 		noenable(q);
26179 		while ((mp = getq(q)) != NULL) {
26180 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
26181 			if (connp->conn_did_putbq) {
26182 				/* ip_wput did a putbq */
26183 				break;
26184 			}
26185 		}
26186 		/*
26187 		 * At this point, a thread coming down from top, calling
26188 		 * ip_wput, may end up queueing the message. We have not yet
26189 		 * enabled the queue, so ip_wsrv won't be called again.
26190 		 * To avoid this race, check q->q_first again (in the loop)
26191 		 * If the other thread queued the message before we call
26192 		 * enableok(), we will catch it in the q->q_first check.
26193 		 * If the other thread queues the message after we call
26194 		 * enableok(), ip_wsrv will be called again by STREAMS.
26195 		 */
26196 		connp->conn_draining = 0;
26197 		enableok(q);
26198 	}
26199 
26200 	/* Enable the next conn for draining */
26201 	conn_drain_tail(connp, B_FALSE);
26202 
26203 	connp->conn_did_putbq = 0;
26204 }
26205 
26206 /*
26207  * Walk the list of all conn's calling the function provided with the
26208  * specified argument for each.	 Note that this only walks conn's that
26209  * have been bound.
26210  * Applies to both IPv4 and IPv6.
26211  */
26212 static void
26213 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
26214 {
26215 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
26216 	    func, arg, zoneid);
26217 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
26218 	    func, arg, zoneid);
26219 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
26220 	    func, arg, zoneid);
26221 	conn_walk_fanout_table(ipcl_proto_fanout,
26222 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
26223 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
26224 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
26225 }
26226 
26227 /*
26228  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
26229  * of conns that need to be drained, check if drain is already in progress.
26230  * If so set the idl_repeat bit, indicating that the last conn in the list
26231  * needs to reinitiate the drain once again, for the list. If drain is not
26232  * in progress for the list, initiate the draining, by qenabling the 1st
26233  * conn in the list. The drain is self-sustaining, each qenabled conn will
26234  * in turn qenable the next conn, when it is done/blocked/closing.
26235  */
26236 static void
26237 conn_walk_drain(void)
26238 {
26239 	int i;
26240 	idl_t *idl;
26241 
26242 	IP_STAT(ip_conn_walk_drain);
26243 
26244 	for (i = 0; i < conn_drain_list_cnt; i++) {
26245 		idl = &conn_drain_list[i];
26246 		mutex_enter(&idl->idl_lock);
26247 		if (idl->idl_conn == NULL) {
26248 			mutex_exit(&idl->idl_lock);
26249 			continue;
26250 		}
26251 		/*
26252 		 * If this list is not being drained currently by
26253 		 * an ip_wsrv thread, start the process.
26254 		 */
26255 		if (idl->idl_conn_draining == NULL) {
26256 			ASSERT(idl->idl_repeat == 0);
26257 			qenable(idl->idl_conn->conn_wq);
26258 			idl->idl_conn_draining = idl->idl_conn;
26259 		} else {
26260 			idl->idl_repeat = 1;
26261 		}
26262 		mutex_exit(&idl->idl_lock);
26263 	}
26264 }
26265 
26266 /*
26267  * Walk an conn hash table of `count' buckets, calling func for each entry.
26268  */
26269 static void
26270 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
26271     zoneid_t zoneid)
26272 {
26273 	conn_t	*connp;
26274 
26275 	while (count-- > 0) {
26276 		mutex_enter(&connfp->connf_lock);
26277 		for (connp = connfp->connf_head; connp != NULL;
26278 		    connp = connp->conn_next) {
26279 			if (zoneid == GLOBAL_ZONEID ||
26280 			    zoneid == connp->conn_zoneid) {
26281 				CONN_INC_REF(connp);
26282 				mutex_exit(&connfp->connf_lock);
26283 				(*func)(connp, arg);
26284 				mutex_enter(&connfp->connf_lock);
26285 				CONN_DEC_REF(connp);
26286 			}
26287 		}
26288 		mutex_exit(&connfp->connf_lock);
26289 		connfp++;
26290 	}
26291 }
26292 
26293 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
26294 static void
26295 conn_report1(conn_t *connp, void *mp)
26296 {
26297 	char	buf1[INET6_ADDRSTRLEN];
26298 	char	buf2[INET6_ADDRSTRLEN];
26299 	uint_t	print_len, buf_len;
26300 
26301 	ASSERT(connp != NULL);
26302 
26303 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
26304 	if (buf_len <= 0)
26305 		return;
26306 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
26307 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
26308 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
26309 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
26310 	    "%5d %s/%05d %s/%05d\n",
26311 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
26312 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
26313 	    buf1, connp->conn_lport,
26314 	    buf2, connp->conn_fport);
26315 	if (print_len < buf_len) {
26316 		((mblk_t *)mp)->b_wptr += print_len;
26317 	} else {
26318 		((mblk_t *)mp)->b_wptr += buf_len;
26319 	}
26320 }
26321 
26322 /*
26323  * Named Dispatch routine to produce a formatted report on all conns
26324  * that are listed in one of the fanout tables.
26325  * This report is accessed by using the ndd utility to "get" ND variable
26326  * "ip_conn_status".
26327  */
26328 /* ARGSUSED */
26329 static int
26330 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
26331 {
26332 	(void) mi_mpprintf(mp,
26333 	    "CONN      " MI_COL_HDRPAD_STR
26334 	    "rfq      " MI_COL_HDRPAD_STR
26335 	    "stq      " MI_COL_HDRPAD_STR
26336 	    " zone local                 remote");
26337 
26338 	/*
26339 	 * Because of the ndd constraint, at most we can have 64K buffer
26340 	 * to put in all conn info.  So to be more efficient, just
26341 	 * allocate a 64K buffer here, assuming we need that large buffer.
26342 	 * This should be OK as only privileged processes can do ndd /dev/ip.
26343 	 */
26344 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
26345 		/* The following may work even if we cannot get a large buf. */
26346 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
26347 		return (0);
26348 	}
26349 
26350 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
26351 	return (0);
26352 }
26353 
26354 /*
26355  * Determine if the ill and multicast aspects of that packets
26356  * "matches" the conn.
26357  */
26358 boolean_t
26359 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
26360     zoneid_t zoneid)
26361 {
26362 	ill_t *in_ill;
26363 	boolean_t found;
26364 	ipif_t *ipif;
26365 	ire_t *ire;
26366 	ipaddr_t dst, src;
26367 
26368 	dst = ipha->ipha_dst;
26369 	src = ipha->ipha_src;
26370 
26371 	/*
26372 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
26373 	 * unicast, broadcast and multicast reception to
26374 	 * conn_incoming_ill. conn_wantpacket itself is called
26375 	 * only for BROADCAST and multicast.
26376 	 *
26377 	 * 1) ip_rput supresses duplicate broadcasts if the ill
26378 	 *    is part of a group. Hence, we should be receiving
26379 	 *    just one copy of broadcast for the whole group.
26380 	 *    Thus, if it is part of the group the packet could
26381 	 *    come on any ill of the group and hence we need a
26382 	 *    match on the group. Otherwise, match on ill should
26383 	 *    be sufficient.
26384 	 *
26385 	 * 2) ip_rput does not suppress duplicate multicast packets.
26386 	 *    If there are two interfaces in a ill group and we have
26387 	 *    2 applications (conns) joined a multicast group G on
26388 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
26389 	 *    will give us two packets because we join G on both the
26390 	 *    interfaces rather than nominating just one interface
26391 	 *    for receiving multicast like broadcast above. So,
26392 	 *    we have to call ilg_lookup_ill to filter out duplicate
26393 	 *    copies, if ill is part of a group.
26394 	 */
26395 	in_ill = connp->conn_incoming_ill;
26396 	if (in_ill != NULL) {
26397 		if (in_ill->ill_group == NULL) {
26398 			if (in_ill != ill)
26399 				return (B_FALSE);
26400 		} else if (in_ill->ill_group != ill->ill_group) {
26401 			return (B_FALSE);
26402 		}
26403 	}
26404 
26405 	if (!CLASSD(dst)) {
26406 		if (IPCL_ZONE_MATCH(connp, zoneid))
26407 			return (B_TRUE);
26408 		/*
26409 		 * The conn is in a different zone; we need to check that this
26410 		 * broadcast address is configured in the application's zone and
26411 		 * on one ill in the group.
26412 		 */
26413 		ipif = ipif_get_next_ipif(NULL, ill);
26414 		if (ipif == NULL)
26415 			return (B_FALSE);
26416 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
26417 		    connp->conn_zoneid, NULL,
26418 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
26419 		ipif_refrele(ipif);
26420 		if (ire != NULL) {
26421 			ire_refrele(ire);
26422 			return (B_TRUE);
26423 		} else {
26424 			return (B_FALSE);
26425 		}
26426 	}
26427 
26428 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
26429 	    connp->conn_zoneid == zoneid) {
26430 		/*
26431 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
26432 		 * disabled, therefore we don't dispatch the multicast packet to
26433 		 * the sending zone.
26434 		 */
26435 		return (B_FALSE);
26436 	}
26437 
26438 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
26439 	    connp->conn_zoneid != zoneid) {
26440 		/*
26441 		 * Multicast packet on the loopback interface: we only match
26442 		 * conns who joined the group in the specified zone.
26443 		 */
26444 		return (B_FALSE);
26445 	}
26446 
26447 	if (connp->conn_multi_router) {
26448 		/* multicast packet and multicast router socket: send up */
26449 		return (B_TRUE);
26450 	}
26451 
26452 	mutex_enter(&connp->conn_lock);
26453 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
26454 	mutex_exit(&connp->conn_lock);
26455 	return (found);
26456 }
26457 
26458 /*
26459  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
26460  */
26461 /* ARGSUSED */
26462 static void
26463 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
26464 {
26465 	ill_t *ill = (ill_t *)q->q_ptr;
26466 	mblk_t	*mp1, *mp2;
26467 	ipif_t  *ipif;
26468 	int err = 0;
26469 	conn_t *connp = NULL;
26470 	ipsq_t	*ipsq;
26471 	arc_t	*arc;
26472 
26473 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
26474 
26475 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
26476 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
26477 
26478 	ASSERT(IAM_WRITER_ILL(ill));
26479 	mp2 = mp->b_cont;
26480 	mp->b_cont = NULL;
26481 
26482 	/*
26483 	 * We have now received the arp bringup completion message
26484 	 * from ARP. Mark the arp bringup as done. Also if the arp
26485 	 * stream has already started closing, send up the AR_ARP_CLOSING
26486 	 * ack now since ARP is waiting in close for this ack.
26487 	 */
26488 	mutex_enter(&ill->ill_lock);
26489 	ill->ill_arp_bringup_pending = 0;
26490 	if (ill->ill_arp_closing) {
26491 		mutex_exit(&ill->ill_lock);
26492 		/* Let's reuse the mp for sending the ack */
26493 		arc = (arc_t *)mp->b_rptr;
26494 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
26495 		arc->arc_cmd = AR_ARP_CLOSING;
26496 		qreply(q, mp);
26497 	} else {
26498 		mutex_exit(&ill->ill_lock);
26499 		freeb(mp);
26500 	}
26501 
26502 	/* We should have an IOCTL waiting on this. */
26503 	ipsq = ill->ill_phyint->phyint_ipsq;
26504 	ipif = ipsq->ipsq_pending_ipif;
26505 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
26506 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
26507 	if (mp1 == NULL) {
26508 		/* bringup was aborted by the user */
26509 		freemsg(mp2);
26510 		return;
26511 	}
26512 	ASSERT(connp != NULL);
26513 	q = CONNP_TO_WQ(connp);
26514 	/*
26515 	 * If the DL_BIND_REQ fails, it is noted
26516 	 * in arc_name_offset.
26517 	 */
26518 	err = *((int *)mp2->b_rptr);
26519 	if (err == 0) {
26520 		if (ipif->ipif_isv6) {
26521 			if ((err = ipif_up_done_v6(ipif)) != 0)
26522 				ip0dbg(("ip_arp_done: init failed\n"));
26523 		} else {
26524 			if ((err = ipif_up_done(ipif)) != 0)
26525 				ip0dbg(("ip_arp_done: init failed\n"));
26526 		}
26527 	} else {
26528 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
26529 	}
26530 
26531 	freemsg(mp2);
26532 
26533 	if ((err == 0) && (ill->ill_up_ipifs)) {
26534 		err = ill_up_ipifs(ill, q, mp1);
26535 		if (err == EINPROGRESS)
26536 			return;
26537 	}
26538 
26539 	if (ill->ill_up_ipifs) {
26540 		ill_group_cleanup(ill);
26541 	}
26542 
26543 	/*
26544 	 * The ioctl must complete now without EINPROGRESS
26545 	 * since ipsq_pending_mp_get has removed the ioctl mblk
26546 	 * from ipsq_pending_mp. Otherwise the ioctl will be
26547 	 * stuck for ever in the ipsq.
26548 	 */
26549 	ASSERT(err != EINPROGRESS);
26550 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
26551 }
26552 
26553 /* Allocate the private structure */
26554 static int
26555 ip_priv_alloc(void **bufp)
26556 {
26557 	void	*buf;
26558 
26559 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
26560 		return (ENOMEM);
26561 
26562 	*bufp = buf;
26563 	return (0);
26564 }
26565 
26566 /* Function to delete the private structure */
26567 void
26568 ip_priv_free(void *buf)
26569 {
26570 	ASSERT(buf != NULL);
26571 	kmem_free(buf, sizeof (ip_priv_t));
26572 }
26573 
26574 /*
26575  * The entry point for IPPF processing.
26576  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
26577  * routine just returns.
26578  *
26579  * When called, ip_process generates an ipp_packet_t structure
26580  * which holds the state information for this packet and invokes the
26581  * the classifier (via ipp_packet_process). The classification, depending on
26582  * configured filters, results in a list of actions for this packet. Invoking
26583  * an action may cause the packet to be dropped, in which case the resulting
26584  * mblk (*mpp) is NULL. proc indicates the callout position for
26585  * this packet and ill_index is the interface this packet on or will leave
26586  * on (inbound and outbound resp.).
26587  */
26588 void
26589 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
26590 {
26591 	mblk_t		*mp;
26592 	ip_priv_t	*priv;
26593 	ipp_action_id_t	aid;
26594 	int		rc = 0;
26595 	ipp_packet_t	*pp;
26596 #define	IP_CLASS	"ip"
26597 
26598 	/* If the classifier is not loaded, return  */
26599 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
26600 		return;
26601 	}
26602 
26603 	mp = *mpp;
26604 	ASSERT(mp != NULL);
26605 
26606 	/* Allocate the packet structure */
26607 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
26608 	if (rc != 0) {
26609 		*mpp = NULL;
26610 		freemsg(mp);
26611 		return;
26612 	}
26613 
26614 	/* Allocate the private structure */
26615 	rc = ip_priv_alloc((void **)&priv);
26616 	if (rc != 0) {
26617 		*mpp = NULL;
26618 		freemsg(mp);
26619 		ipp_packet_free(pp);
26620 		return;
26621 	}
26622 	priv->proc = proc;
26623 	priv->ill_index = ill_index;
26624 	ipp_packet_set_private(pp, priv, ip_priv_free);
26625 	ipp_packet_set_data(pp, mp);
26626 
26627 	/* Invoke the classifier */
26628 	rc = ipp_packet_process(&pp);
26629 	if (pp != NULL) {
26630 		mp = ipp_packet_get_data(pp);
26631 		ipp_packet_free(pp);
26632 		if (rc != 0) {
26633 			freemsg(mp);
26634 			*mpp = NULL;
26635 		}
26636 	} else {
26637 		*mpp = NULL;
26638 	}
26639 #undef	IP_CLASS
26640 }
26641 
26642 /*
26643  * Propagate a multicast group membership operation (add/drop) on
26644  * all the interfaces crossed by the related multirt routes.
26645  * The call is considered successful if the operation succeeds
26646  * on at least one interface.
26647  */
26648 static int
26649 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
26650     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
26651     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
26652     mblk_t *first_mp)
26653 {
26654 	ire_t		*ire_gw;
26655 	irb_t		*irb;
26656 	int		error = 0;
26657 	opt_restart_t	*or;
26658 
26659 	irb = ire->ire_bucket;
26660 	ASSERT(irb != NULL);
26661 
26662 	ASSERT(DB_TYPE(first_mp) == M_CTL);
26663 
26664 	or = (opt_restart_t *)first_mp->b_rptr;
26665 	IRB_REFHOLD(irb);
26666 	for (; ire != NULL; ire = ire->ire_next) {
26667 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
26668 			continue;
26669 		if (ire->ire_addr != group)
26670 			continue;
26671 
26672 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
26673 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
26674 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
26675 		/* No resolver exists for the gateway; skip this ire. */
26676 		if (ire_gw == NULL)
26677 			continue;
26678 
26679 		/*
26680 		 * This function can return EINPROGRESS. If so the operation
26681 		 * will be restarted from ip_restart_optmgmt which will
26682 		 * call ip_opt_set and option processing will restart for
26683 		 * this option. So we may end up calling 'fn' more than once.
26684 		 * This requires that 'fn' is idempotent except for the
26685 		 * return value. The operation is considered a success if
26686 		 * it succeeds at least once on any one interface.
26687 		 */
26688 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
26689 		    NULL, fmode, src, first_mp);
26690 		if (error == 0)
26691 			or->or_private = CGTP_MCAST_SUCCESS;
26692 
26693 		if (ip_debug > 0) {
26694 			ulong_t	off;
26695 			char	*ksym;
26696 			ksym = kobj_getsymname((uintptr_t)fn, &off);
26697 			ip2dbg(("ip_multirt_apply_membership: "
26698 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
26699 			    "error %d [success %u]\n",
26700 			    ksym ? ksym : "?",
26701 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
26702 			    error, or->or_private));
26703 		}
26704 
26705 		ire_refrele(ire_gw);
26706 		if (error == EINPROGRESS) {
26707 			IRB_REFRELE(irb);
26708 			return (error);
26709 		}
26710 	}
26711 	IRB_REFRELE(irb);
26712 	/*
26713 	 * Consider the call as successful if we succeeded on at least
26714 	 * one interface. Otherwise, return the last encountered error.
26715 	 */
26716 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
26717 }
26718 
26719 
26720 /*
26721  * Issue a warning regarding a route crossing an interface with an
26722  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
26723  * amount of time is logged.
26724  */
26725 static void
26726 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
26727 {
26728 	hrtime_t	current = gethrtime();
26729 	char		buf[16];
26730 
26731 	/* Convert interval in ms to hrtime in ns */
26732 	if (multirt_bad_mtu_last_time +
26733 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
26734 	    current) {
26735 		cmn_err(CE_WARN, "ip: ignoring multiroute "
26736 		    "to %s, incorrect MTU %u (expected %u)\n",
26737 		    ip_dot_addr(ire->ire_addr, buf),
26738 		    ire->ire_max_frag, max_frag);
26739 
26740 		multirt_bad_mtu_last_time = current;
26741 	}
26742 }
26743 
26744 
26745 /*
26746  * Get the CGTP (multirouting) filtering status.
26747  * If 0, the CGTP hooks are transparent.
26748  */
26749 /* ARGSUSED */
26750 static int
26751 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
26752 {
26753 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26754 
26755 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
26756 	return (0);
26757 }
26758 
26759 
26760 /*
26761  * Set the CGTP (multirouting) filtering status.
26762  * If the status is changed from active to transparent
26763  * or from transparent to active, forward the new status
26764  * to the filtering module (if loaded).
26765  */
26766 /* ARGSUSED */
26767 static int
26768 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
26769     cred_t *ioc_cr)
26770 {
26771 	long		new_value;
26772 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
26773 
26774 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
26775 	    new_value < 0 || new_value > 1) {
26776 		return (EINVAL);
26777 	}
26778 
26779 	/*
26780 	 * Do not enable CGTP filtering - thus preventing the hooks
26781 	 * from being invoked - if the version number of the
26782 	 * filtering module hooks does not match.
26783 	 */
26784 	if ((ip_cgtp_filter_ops != NULL) &&
26785 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
26786 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
26787 		    "(module hooks version %d, expecting %d)\n",
26788 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
26789 		return (ENOTSUP);
26790 	}
26791 
26792 	if ((!*ip_cgtp_filter_value) && new_value) {
26793 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
26794 		    ip_cgtp_filter_ops == NULL ?
26795 		    " (module not loaded)" : "");
26796 	}
26797 	if (*ip_cgtp_filter_value && (!new_value)) {
26798 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
26799 		    ip_cgtp_filter_ops == NULL ?
26800 		    " (module not loaded)" : "");
26801 	}
26802 
26803 	if (ip_cgtp_filter_ops != NULL) {
26804 		int	res;
26805 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
26806 			return (res);
26807 		}
26808 	}
26809 
26810 	*ip_cgtp_filter_value = (boolean_t)new_value;
26811 
26812 	return (0);
26813 }
26814 
26815 
26816 /*
26817  * Return the expected CGTP hooks version number.
26818  */
26819 int
26820 ip_cgtp_filter_supported(void)
26821 {
26822 	return (ip_cgtp_filter_rev);
26823 }
26824 
26825 
26826 /*
26827  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
26828  * or by invoking this function. In the first case, the version number
26829  * of the registered structure is checked at hooks activation time
26830  * in ip_cgtp_filter_set().
26831  */
26832 int
26833 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
26834 {
26835 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
26836 		return (ENOTSUP);
26837 
26838 	ip_cgtp_filter_ops = ops;
26839 	return (0);
26840 }
26841 
26842 static squeue_func_t
26843 ip_squeue_switch(int val)
26844 {
26845 	squeue_func_t rval = squeue_fill;
26846 
26847 	switch (val) {
26848 	case IP_SQUEUE_ENTER_NODRAIN:
26849 		rval = squeue_enter_nodrain;
26850 		break;
26851 	case IP_SQUEUE_ENTER:
26852 		rval = squeue_enter;
26853 		break;
26854 	default:
26855 		break;
26856 	}
26857 	return (rval);
26858 }
26859 
26860 /* ARGSUSED */
26861 static int
26862 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
26863     caddr_t addr, cred_t *cr)
26864 {
26865 	int *v = (int *)addr;
26866 	long new_value;
26867 
26868 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26869 		return (EINVAL);
26870 
26871 	ip_input_proc = ip_squeue_switch(new_value);
26872 	*v = new_value;
26873 	return (0);
26874 }
26875 
26876 /* ARGSUSED */
26877 static int
26878 ip_int_set(queue_t *q, mblk_t *mp, char *value,
26879     caddr_t addr, cred_t *cr)
26880 {
26881 	int *v = (int *)addr;
26882 	long new_value;
26883 
26884 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
26885 		return (EINVAL);
26886 
26887 	*v = new_value;
26888 	return (0);
26889 }
26890 
26891 static void
26892 ip_kstat_init(void)
26893 {
26894 	ip_named_kstat_t template = {
26895 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
26896 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
26897 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
26898 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
26899 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
26900 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
26901 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
26902 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
26903 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
26904 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
26905 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
26906 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
26907 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
26908 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
26909 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
26910 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
26911 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
26912 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
26913 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
26914 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
26915 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
26916 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
26917 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
26918 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
26919 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
26920 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
26921 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
26922 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
26923 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
26924 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
26925 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
26926 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
26927 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
26928 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
26929 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
26930 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
26931 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
26932 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
26933 	};
26934 
26935 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
26936 					NUM_OF_FIELDS(ip_named_kstat_t),
26937 					0);
26938 	if (!ip_mibkp)
26939 		return;
26940 
26941 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
26942 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
26943 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
26944 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
26945 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
26946 
26947 	template.netToMediaEntrySize.value.i32 =
26948 		sizeof (mib2_ipNetToMediaEntry_t);
26949 
26950 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
26951 
26952 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
26953 
26954 	ip_mibkp->ks_update = ip_kstat_update;
26955 
26956 	kstat_install(ip_mibkp);
26957 }
26958 
26959 static void
26960 ip_kstat_fini(void)
26961 {
26962 
26963 	if (ip_mibkp != NULL) {
26964 		kstat_delete(ip_mibkp);
26965 		ip_mibkp = NULL;
26966 	}
26967 }
26968 
26969 static int
26970 ip_kstat_update(kstat_t *kp, int rw)
26971 {
26972 	ip_named_kstat_t *ipkp;
26973 
26974 	if (!kp || !kp->ks_data)
26975 		return (EIO);
26976 
26977 	if (rw == KSTAT_WRITE)
26978 		return (EACCES);
26979 
26980 	ipkp = (ip_named_kstat_t *)kp->ks_data;
26981 
26982 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
26983 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
26984 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
26985 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
26986 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
26987 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
26988 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
26989 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
26990 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
26991 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
26992 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
26993 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
26994 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
26995 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
26996 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
26997 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
26998 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
26999 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
27000 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
27001 
27002 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
27003 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
27004 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
27005 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
27006 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
27007 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
27008 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
27009 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
27010 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
27011 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
27012 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
27013 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
27014 
27015 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
27016 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
27017 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
27018 
27019 	return (0);
27020 }
27021 
27022 static void
27023 icmp_kstat_init(void)
27024 {
27025 	icmp_named_kstat_t template = {
27026 		{ "inMsgs",		KSTAT_DATA_UINT32 },
27027 		{ "inErrors",		KSTAT_DATA_UINT32 },
27028 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
27029 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
27030 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
27031 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
27032 		{ "inRedirects",	KSTAT_DATA_UINT32 },
27033 		{ "inEchos",		KSTAT_DATA_UINT32 },
27034 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
27035 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
27036 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
27037 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
27038 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
27039 		{ "outMsgs",		KSTAT_DATA_UINT32 },
27040 		{ "outErrors",		KSTAT_DATA_UINT32 },
27041 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
27042 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
27043 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
27044 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
27045 		{ "outRedirects",	KSTAT_DATA_UINT32 },
27046 		{ "outEchos",		KSTAT_DATA_UINT32 },
27047 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
27048 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
27049 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
27050 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
27051 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
27052 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
27053 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
27054 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
27055 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
27056 		{ "outDrops",		KSTAT_DATA_UINT32 },
27057 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
27058 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
27059 	};
27060 
27061 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
27062 					NUM_OF_FIELDS(icmp_named_kstat_t),
27063 					0);
27064 	if (icmp_mibkp == NULL)
27065 		return;
27066 
27067 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
27068 
27069 	icmp_mibkp->ks_update = icmp_kstat_update;
27070 
27071 	kstat_install(icmp_mibkp);
27072 }
27073 
27074 static void
27075 icmp_kstat_fini(void)
27076 {
27077 
27078 	if (icmp_mibkp != NULL) {
27079 		kstat_delete(icmp_mibkp);
27080 		icmp_mibkp = NULL;
27081 	}
27082 }
27083 
27084 static int
27085 icmp_kstat_update(kstat_t *kp, int rw)
27086 {
27087 	icmp_named_kstat_t *icmpkp;
27088 
27089 	if ((kp == NULL) || (kp->ks_data == NULL))
27090 		return (EIO);
27091 
27092 	if (rw == KSTAT_WRITE)
27093 		return (EACCES);
27094 
27095 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
27096 
27097 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
27098 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
27099 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
27100 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
27101 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
27102 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
27103 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
27104 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
27105 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
27106 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
27107 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
27108 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
27109 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
27110 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
27111 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
27112 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
27113 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
27114 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
27115 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
27116 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
27117 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
27118 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
27119 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
27120 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
27121 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
27122 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
27123 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
27124 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
27125 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
27126 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
27127 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
27128 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
27129 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
27130 
27131 	return (0);
27132 }
27133 
27134 /*
27135  * This is the fanout function for raw socket opened for SCTP.  Note
27136  * that it is called after SCTP checks that there is no socket which
27137  * wants a packet.  Then before SCTP handles this out of the blue packet,
27138  * this function is called to see if there is any raw socket for SCTP.
27139  * If there is and it is bound to the correct address, the packet will
27140  * be sent to that socket.  Note that only one raw socket can be bound to
27141  * a port.  This is assured in ipcl_sctp_hash_insert();
27142  */
27143 void
27144 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
27145     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
27146     uint_t ipif_seqid, zoneid_t zoneid)
27147 {
27148 	conn_t		*connp;
27149 	queue_t		*rq;
27150 	mblk_t		*first_mp;
27151 	boolean_t	secure;
27152 	ip6_t		*ip6h;
27153 
27154 	first_mp = mp;
27155 	if (mctl_present) {
27156 		mp = first_mp->b_cont;
27157 		secure = ipsec_in_is_secure(first_mp);
27158 		ASSERT(mp != NULL);
27159 	} else {
27160 		secure = B_FALSE;
27161 	}
27162 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
27163 
27164 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
27165 	if (connp == NULL) {
27166 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
27167 		    mctl_present);
27168 		return;
27169 	}
27170 	rq = connp->conn_rq;
27171 	if (!canputnext(rq)) {
27172 		CONN_DEC_REF(connp);
27173 		BUMP_MIB(&ip_mib, rawipInOverflows);
27174 		freemsg(first_mp);
27175 		return;
27176 	}
27177 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
27178 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
27179 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
27180 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
27181 		if (first_mp == NULL) {
27182 			CONN_DEC_REF(connp);
27183 			return;
27184 		}
27185 	}
27186 	/*
27187 	 * We probably should not send M_CTL message up to
27188 	 * raw socket.
27189 	 */
27190 	if (mctl_present)
27191 		freeb(first_mp);
27192 
27193 	/* Initiate IPPF processing here if needed. */
27194 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
27195 	    (!isv4 && IP6_IN_IPP(flags))) {
27196 		ip_process(IPP_LOCAL_IN, &mp,
27197 		    recv_ill->ill_phyint->phyint_ifindex);
27198 		if (mp == NULL) {
27199 			CONN_DEC_REF(connp);
27200 			return;
27201 		}
27202 	}
27203 
27204 	if (connp->conn_recvif || connp->conn_recvslla ||
27205 	    ((connp->conn_ipv6_recvpktinfo ||
27206 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
27207 	    (flags & IP_FF_IP6INFO))) {
27208 		int in_flags = 0;
27209 
27210 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
27211 			in_flags = IPF_RECVIF;
27212 		}
27213 		if (connp->conn_recvslla) {
27214 			in_flags |= IPF_RECVSLLA;
27215 		}
27216 		if (isv4) {
27217 			mp = ip_add_info(mp, recv_ill, in_flags);
27218 		} else {
27219 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
27220 			if (mp == NULL) {
27221 				CONN_DEC_REF(connp);
27222 				return;
27223 			}
27224 		}
27225 	}
27226 
27227 	BUMP_MIB(&ip_mib, ipInDelivers);
27228 	/*
27229 	 * We are sending the IPSEC_IN message also up. Refer
27230 	 * to comments above this function.
27231 	 */
27232 	putnext(rq, mp);
27233 	CONN_DEC_REF(connp);
27234 }
27235 
27236 /*
27237  * Martian Address Filtering [RFC 1812, Section 5.3.7]
27238  */
27239 static boolean_t
27240 ip_no_forward(ipha_t *ipha, ill_t *ill)
27241 {
27242 	ipaddr_t ip_src, ip_dst;
27243 	ire_t *src_ire = NULL;
27244 
27245 	ip_src = ntohl(ipha->ipha_src);
27246 	ip_dst = ntohl(ipha->ipha_dst);
27247 
27248 	if (ip_dst == INADDR_ANY)
27249 		goto dont_forward;
27250 
27251 	if (IN_CLASSD(ip_src))
27252 		goto dont_forward;
27253 
27254 	if ((ip_src >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)
27255 		goto dont_forward;
27256 
27257 	if (IN_BADCLASS(ip_dst))
27258 		goto dont_forward;
27259 
27260 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
27261 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
27262 	if (src_ire != NULL) {
27263 		ire_refrele(src_ire);
27264 		goto dont_forward;
27265 	}
27266 
27267 	return (B_FALSE);
27268 
27269 dont_forward:
27270 	if (ip_debug > 2) {
27271 		printf("ip_no_forward: dropping packet received on %s\n",
27272 		    ill->ill_name);
27273 		pr_addr_dbg("ip_no_forward: from src %s\n",
27274 		    AF_INET, &ipha->ipha_src);
27275 		pr_addr_dbg("ip_no_forward: to dst %s\n",
27276 		    AF_INET, &ipha->ipha_dst);
27277 	}
27278 	BUMP_MIB(&ip_mib, ipForwProhibits);
27279 	return (B_TRUE);
27280 }
27281 
27282 static boolean_t
27283 ip_loopback_src_or_dst(ipha_t *ipha, ill_t *ill)
27284 {
27285 	if (((ntohl(ipha->ipha_src) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) ||
27286 	    ((ntohl(ipha->ipha_dst) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET)) {
27287 		if (ip_debug > 2) {
27288 			if (ill != NULL) {
27289 				printf("ip_loopback_src_or_dst: "
27290 				    "dropping packet received on %s\n",
27291 				    ill->ill_name);
27292 			} else {
27293 				printf("ip_loopback_src_or_dst: "
27294 				    "dropping packet\n");
27295 			}
27296 
27297 			pr_addr_dbg(
27298 			    "ip_loopback_src_or_dst: from src %s\n",
27299 			    AF_INET, &ipha->ipha_src);
27300 			pr_addr_dbg(
27301 			    "ip_loopback_src_or_dst: to dst %s\n",
27302 			    AF_INET, &ipha->ipha_dst);
27303 		}
27304 
27305 		BUMP_MIB(&ip_mib, ipInAddrErrors);
27306 		return (B_TRUE);
27307 	}
27308 	return (B_FALSE);
27309 }
27310 
27311 /*
27312  * Return B_TRUE if the buffers differ in length or content.
27313  * This is used for comparing extension header buffers.
27314  * Note that an extension header would be declared different
27315  * even if all that changed was the next header value in that header i.e.
27316  * what really changed is the next extension header.
27317  */
27318 boolean_t
27319 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
27320     uint_t blen)
27321 {
27322 	if (!b_valid)
27323 		blen = 0;
27324 
27325 	if (alen != blen)
27326 		return (B_TRUE);
27327 	if (alen == 0)
27328 		return (B_FALSE);	/* Both zero length */
27329 	return (bcmp(abuf, bbuf, alen));
27330 }
27331 
27332 /*
27333  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
27334  * Return B_FALSE if memory allocation fails - don't change any state!
27335  */
27336 boolean_t
27337 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27338     const void *src, uint_t srclen)
27339 {
27340 	void *dst;
27341 
27342 	if (!src_valid)
27343 		srclen = 0;
27344 
27345 	ASSERT(*dstlenp == 0);
27346 	if (src != NULL && srclen != 0) {
27347 		dst = mi_alloc(srclen, BPRI_MED);
27348 		if (dst == NULL)
27349 			return (B_FALSE);
27350 	} else {
27351 		dst = NULL;
27352 	}
27353 	if (*dstp != NULL)
27354 		mi_free(*dstp);
27355 	*dstp = dst;
27356 	*dstlenp = dst == NULL ? 0 : srclen;
27357 	return (B_TRUE);
27358 }
27359 
27360 /*
27361  * Replace what is in *dst, *dstlen with the source.
27362  * Assumes ip_allocbuf has already been called.
27363  */
27364 void
27365 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
27366     const void *src, uint_t srclen)
27367 {
27368 	if (!src_valid)
27369 		srclen = 0;
27370 
27371 	ASSERT(*dstlenp == srclen);
27372 	if (src != NULL && srclen != 0)
27373 		bcopy(src, *dstp, srclen);
27374 }
27375 
27376 /*
27377  * Free the storage pointed to by the members of an ip6_pkt_t.
27378  */
27379 void
27380 ip6_pkt_free(ip6_pkt_t *ipp)
27381 {
27382 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
27383 
27384 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
27385 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
27386 		ipp->ipp_hopopts = NULL;
27387 		ipp->ipp_hopoptslen = 0;
27388 	}
27389 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
27390 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
27391 		ipp->ipp_rtdstopts = NULL;
27392 		ipp->ipp_rtdstoptslen = 0;
27393 	}
27394 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
27395 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
27396 		ipp->ipp_dstopts = NULL;
27397 		ipp->ipp_dstoptslen = 0;
27398 	}
27399 	if (ipp->ipp_fields & IPPF_RTHDR) {
27400 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
27401 		ipp->ipp_rthdr = NULL;
27402 		ipp->ipp_rthdrlen = 0;
27403 	}
27404 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
27405 	    IPPF_RTHDR);
27406 }
27407