xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision bb3a048dd74d073e10c2a5d4aa060b4405ba7dfd)
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  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/sunddi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.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_ftable.h>
88 #include <inet/ip_rts.h>
89 #include <inet/optcom.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <sys/sunddi.h>
121 
122 #include <sys/tsol/label.h>
123 #include <sys/tsol/tnet.h>
124 
125 #include <rpc/pmap_prot.h>
126 
127 /*
128  * Values for squeue switch:
129  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
130  * IP_SQUEUE_ENTER: squeue_enter
131  * IP_SQUEUE_FILL: squeue_fill
132  */
133 int ip_squeue_enter = 2;
134 squeue_func_t ip_input_proc;
135 /*
136  * IP statistics.
137  */
138 #define	IP_STAT(x)		(ip_statistics.x.value.ui64++)
139 #define	IP_STAT_UPDATE(x, n)	(ip_statistics.x.value.ui64 += (n))
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 typedef struct ip_stat {
143 	kstat_named_t	ipsec_fanout_proto;
144 	kstat_named_t	ip_udp_fannorm;
145 	kstat_named_t	ip_udp_fanmb;
146 	kstat_named_t	ip_udp_fanothers;
147 	kstat_named_t	ip_udp_fast_path;
148 	kstat_named_t	ip_udp_slow_path;
149 	kstat_named_t	ip_udp_input_err;
150 	kstat_named_t	ip_tcppullup;
151 	kstat_named_t	ip_tcpoptions;
152 	kstat_named_t	ip_multipkttcp;
153 	kstat_named_t	ip_tcp_fast_path;
154 	kstat_named_t	ip_tcp_slow_path;
155 	kstat_named_t	ip_tcp_input_error;
156 	kstat_named_t	ip_db_ref;
157 	kstat_named_t	ip_notaligned1;
158 	kstat_named_t	ip_notaligned2;
159 	kstat_named_t	ip_multimblk3;
160 	kstat_named_t	ip_multimblk4;
161 	kstat_named_t	ip_ipoptions;
162 	kstat_named_t	ip_classify_fail;
163 	kstat_named_t	ip_opt;
164 	kstat_named_t	ip_udp_rput_local;
165 	kstat_named_t	ipsec_proto_ahesp;
166 	kstat_named_t	ip_conn_flputbq;
167 	kstat_named_t	ip_conn_walk_drain;
168 	kstat_named_t   ip_out_sw_cksum;
169 	kstat_named_t   ip_in_sw_cksum;
170 	kstat_named_t   ip_trash_ire_reclaim_calls;
171 	kstat_named_t   ip_trash_ire_reclaim_success;
172 	kstat_named_t   ip_ire_arp_timer_expired;
173 	kstat_named_t   ip_ire_redirect_timer_expired;
174 	kstat_named_t	ip_ire_pmtu_timer_expired;
175 	kstat_named_t	ip_input_multi_squeue;
176 	kstat_named_t	ip_tcp_in_full_hw_cksum_err;
177 	kstat_named_t	ip_tcp_in_part_hw_cksum_err;
178 	kstat_named_t	ip_tcp_in_sw_cksum_err;
179 	kstat_named_t	ip_tcp_out_sw_cksum_bytes;
180 	kstat_named_t	ip_udp_in_full_hw_cksum_err;
181 	kstat_named_t	ip_udp_in_part_hw_cksum_err;
182 	kstat_named_t	ip_udp_in_sw_cksum_err;
183 	kstat_named_t	ip_udp_out_sw_cksum_bytes;
184 	kstat_named_t	ip_frag_mdt_pkt_out;
185 	kstat_named_t	ip_frag_mdt_discarded;
186 	kstat_named_t	ip_frag_mdt_allocfail;
187 	kstat_named_t	ip_frag_mdt_addpdescfail;
188 	kstat_named_t	ip_frag_mdt_allocd;
189 } ip_stat_t;
190 
191 static ip_stat_t ip_statistics = {
192 	{ "ipsec_fanout_proto",			KSTAT_DATA_UINT64 },
193 	{ "ip_udp_fannorm",			KSTAT_DATA_UINT64 },
194 	{ "ip_udp_fanmb",			KSTAT_DATA_UINT64 },
195 	{ "ip_udp_fanothers",			KSTAT_DATA_UINT64 },
196 	{ "ip_udp_fast_path",			KSTAT_DATA_UINT64 },
197 	{ "ip_udp_slow_path",			KSTAT_DATA_UINT64 },
198 	{ "ip_udp_input_err",			KSTAT_DATA_UINT64 },
199 	{ "ip_tcppullup",			KSTAT_DATA_UINT64 },
200 	{ "ip_tcpoptions",			KSTAT_DATA_UINT64 },
201 	{ "ip_multipkttcp",			KSTAT_DATA_UINT64 },
202 	{ "ip_tcp_fast_path",			KSTAT_DATA_UINT64 },
203 	{ "ip_tcp_slow_path",			KSTAT_DATA_UINT64 },
204 	{ "ip_tcp_input_error",			KSTAT_DATA_UINT64 },
205 	{ "ip_db_ref",				KSTAT_DATA_UINT64 },
206 	{ "ip_notaligned1",			KSTAT_DATA_UINT64 },
207 	{ "ip_notaligned2",			KSTAT_DATA_UINT64 },
208 	{ "ip_multimblk3",			KSTAT_DATA_UINT64 },
209 	{ "ip_multimblk4",			KSTAT_DATA_UINT64 },
210 	{ "ip_ipoptions",			KSTAT_DATA_UINT64 },
211 	{ "ip_classify_fail",			KSTAT_DATA_UINT64 },
212 	{ "ip_opt",				KSTAT_DATA_UINT64 },
213 	{ "ip_udp_rput_local",			KSTAT_DATA_UINT64 },
214 	{ "ipsec_proto_ahesp",			KSTAT_DATA_UINT64 },
215 	{ "ip_conn_flputbq",			KSTAT_DATA_UINT64 },
216 	{ "ip_conn_walk_drain",			KSTAT_DATA_UINT64 },
217 	{ "ip_out_sw_cksum",			KSTAT_DATA_UINT64 },
218 	{ "ip_in_sw_cksum",			KSTAT_DATA_UINT64 },
219 	{ "ip_trash_ire_reclaim_calls",		KSTAT_DATA_UINT64 },
220 	{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
221 	{ "ip_ire_arp_timer_expired",		KSTAT_DATA_UINT64 },
222 	{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
223 	{ "ip_ire_pmtu_timer_expired",		KSTAT_DATA_UINT64 },
224 	{ "ip_input_multi_squeue",		KSTAT_DATA_UINT64 },
225 	{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
226 	{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
227 	{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
228 	{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
229 	{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
230 	{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
231 	{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
232 	{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
233 	{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
234 	{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
235 	{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
236 	{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
237 	{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
238 };
239 
240 static kstat_t *ip_kstat;
241 
242 #define	TCP6 "tcp6"
243 #define	TCP "tcp"
244 #define	SCTP "sctp"
245 #define	SCTP6 "sctp6"
246 
247 major_t TCP6_MAJ;
248 major_t TCP_MAJ;
249 major_t SCTP_MAJ;
250 major_t SCTP6_MAJ;
251 
252 int ip_poll_normal_ms = 100;
253 int ip_poll_normal_ticks = 0;
254 
255 /*
256  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
257  */
258 
259 struct listptr_s {
260 	mblk_t	*lp_head;	/* pointer to the head of the list */
261 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
262 };
263 
264 typedef struct listptr_s listptr_t;
265 
266 /*
267  * This is used by ip_snmp_get_mib2_ip_route_media and
268  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
269  */
270 typedef struct iproutedata_s {
271 	uint_t		ird_idx;
272 	listptr_t	ird_route;	/* ipRouteEntryTable */
273 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
274 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
275 } iproutedata_t;
276 
277 /*
278  * Cluster specific hooks. These should be NULL when booted as a non-cluster
279  */
280 
281 /*
282  * Hook functions to enable cluster networking
283  * On non-clustered systems these vectors must always be NULL.
284  *
285  * Hook function to Check ip specified ip address is a shared ip address
286  * in the cluster
287  *
288  */
289 int (*cl_inet_isclusterwide)(uint8_t protocol,
290     sa_family_t addr_family, uint8_t *laddrp) = NULL;
291 
292 /*
293  * Hook function to generate cluster wide ip fragment identifier
294  */
295 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
296     uint8_t *laddrp, uint8_t *faddrp) = NULL;
297 
298 /*
299  * Synchronization notes:
300  *
301  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
302  * MT level protection given by STREAMS. IP uses a combination of its own
303  * internal serialization mechanism and standard Solaris locking techniques.
304  * The internal serialization is per phyint (no IPMP) or per IPMP group.
305  * This is used to serialize plumbing operations, IPMP operations, certain
306  * multicast operations, most set ioctls, igmp/mld timers etc.
307  *
308  * Plumbing is a long sequence of operations involving message
309  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
310  * involved in plumbing operations. A natural model is to serialize these
311  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
312  * parallel without any interference. But various set ioctls on hme0 are best
313  * serialized. However if the system uses IPMP, the operations are easier if
314  * they are serialized on a per IPMP group basis since IPMP operations
315  * happen across ill's of a group. Thus the lowest common denominator is to
316  * serialize most set ioctls, multicast join/leave operations, IPMP operations
317  * igmp/mld timer operations, and processing of DLPI control messages received
318  * from drivers on a per IPMP group basis. If the system does not employ
319  * IPMP the serialization is on a per phyint basis. This serialization is
320  * provided by the ipsq_t and primitives operating on this. Details can
321  * be found in ip_if.c above the core primitives operating on ipsq_t.
322  *
323  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
324  * Simiarly lookup of an ire by a thread also returns a refheld ire.
325  * In addition ipif's and ill's referenced by the ire are also indirectly
326  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
327  * the ipif's address or netmask change as long as an ipif is refheld
328  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
329  * address of an ipif has to go through the ipsq_t. This ensures that only
330  * 1 such exclusive operation proceeds at any time on the ipif. It then
331  * deletes all ires associated with this ipif, and waits for all refcnts
332  * associated with this ipif to come down to zero. The address is changed
333  * only after the ipif has been quiesced. Then the ipif is brought up again.
334  * More details are described above the comment in ip_sioctl_flags.
335  *
336  * Packet processing is based mostly on IREs and are fully multi-threaded
337  * using standard Solaris MT techniques.
338  *
339  * There are explicit locks in IP to handle:
340  * - The ip_g_head list maintained by mi_open_link() and friends.
341  *
342  * - The reassembly data structures (one lock per hash bucket)
343  *
344  * - conn_lock is meant to protect conn_t fields. The fields actually
345  *   protected by conn_lock are documented in the conn_t definition.
346  *
347  * - ire_lock to protect some of the fields of the ire, IRE tables
348  *   (one lock per hash bucket). Refer to ip_ire.c for details.
349  *
350  * - ndp_g_lock and nce_lock for protecting NCEs.
351  *
352  * - ill_lock protects fields of the ill and ipif. Details in ip.h
353  *
354  * - ill_g_lock: This is a global reader/writer lock. Protects the following
355  *	* The AVL tree based global multi list of all ills.
356  *	* The linked list of all ipifs of an ill
357  *	* The <ill-ipsq> mapping
358  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
359  *	* The illgroup list threaded by ill_group_next.
360  *	* <ill-phyint> association
361  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
362  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
363  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
364  *   will all have to hold the ill_g_lock as writer for the actual duration
365  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
366  *   may be found in the IPMP section.
367  *
368  * - ill_lock:  This is a per ill mutex.
369  *   It protects some members of the ill and is documented below.
370  *   It also protects the <ill-ipsq> mapping
371  *   It also protects the illgroup list threaded by ill_group_next.
372  *   It also protects the <ill-phyint> assoc.
373  *   It also protects the list of ipifs hanging off the ill.
374  *
375  * - ipsq_lock: This is a per ipsq_t mutex lock.
376  *   This protects all the other members of the ipsq struct except
377  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
378  *
379  * - illgrp_lock: This is a per ill_group mutex lock.
380  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
381  *   which dictates which is the next ill in an ill_group that is to be chosen
382  *   for sending outgoing packets, through creation of an IRE_CACHE that
383  *   references this ill.
384  *
385  * - phyint_lock: This is a per phyint mutex lock. Protects just the
386  *   phyint_flags
387  *
388  * - ip_g_nd_lock: This is a global reader/writer lock.
389  *   Any call to nd_load to load a new parameter to the ND table must hold the
390  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
391  *   as reader.
392  *
393  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
394  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
395  *   uniqueness check also done atomically.
396  *
397  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
398  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
399  *   as a writer when adding or deleting elements from these lists, and
400  *   as a reader when walking these lists to send a SADB update to the
401  *   IPsec capable ills.
402  *
403  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
404  *   group list linked by ill_usesrc_grp_next. It also protects the
405  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
406  *   group is being added or deleted.  This lock is taken as a reader when
407  *   walking the list/group(eg: to get the number of members in a usesrc group).
408  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
409  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
410  *   example, it is not necessary to take this lock in the initial portion
411  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
412  *   ip_sioctl_flags since the these operations are executed exclusively and
413  *   that ensures that the "usesrc group state" cannot change. The "usesrc
414  *   group state" change can happen only in the latter part of
415  *   ip_sioctl_slifusesrc and in ill_delete.
416  *
417  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
418  *
419  * To change the <ill-phyint> association, the ill_g_lock must be held
420  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
421  * must be held.
422  *
423  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
424  * and the ill_lock of the ill in question must be held.
425  *
426  * To change the <ill-illgroup> association the ill_g_lock must be held as
427  * writer and the ill_lock of the ill in question must be held.
428  *
429  * To add or delete an ipif from the list of ipifs hanging off the ill,
430  * ill_g_lock (writer) and ill_lock must be held and the thread must be
431  * a writer on the associated ipsq,.
432  *
433  * To add or delete an ill to the system, the ill_g_lock must be held as
434  * writer and the thread must be a writer on the associated ipsq.
435  *
436  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
437  * must be a writer on the associated ipsq.
438  *
439  * Lock hierarchy
440  *
441  * Some lock hierarchy scenarios are listed below.
442  *
443  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
444  * ill_g_lock -> illgrp_lock -> ill_lock
445  * ill_g_lock -> ill_lock(s) -> phyint_lock
446  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
447  * ill_g_lock -> ip_addr_avail_lock
448  * conn_lock -> irb_lock -> ill_lock -> ire_lock
449  * ill_g_lock -> ip_g_nd_lock
450  *
451  * When more than 1 ill lock is needed to be held, all ill lock addresses
452  * are sorted on address and locked starting from highest addressed lock
453  * downward.
454  *
455  * Mobile-IP scenarios
456  *
457  * irb_lock -> ill_lock -> ire_mrtun_lock
458  * irb_lock -> ill_lock -> ire_srcif_table_lock
459  *
460  * IPsec scenarios
461  *
462  * ipsa_lock -> ill_g_lock -> ill_lock
463  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ipsa_lock
465  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
466  *
467  * Trusted Solaris scenarios
468  *
469  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
470  * igsa_lock -> gcdb_lock
471  * gcgrp_rwlock -> ire_lock
472  * gcgrp_rwlock -> gcdb_lock
473  *
474  *
475  * Routing/forwarding table locking notes:
476  *
477  * Lock acquisition order: Radix tree lock, irb_lock.
478  * Requirements:
479  * i.  Walker must not hold any locks during the walker callback.
480  * ii  Walker must not see a truncated tree during the walk because of any node
481  *     deletion.
482  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
483  *     in many places in the code to walk the irb list. Thus even if all the
484  *     ires in a bucket have been deleted, we still can't free the radix node
485  *     until the ires have actually been inactive'd (freed).
486  *
487  * Tree traversal - Need to hold the global tree lock in read mode.
488  * Before dropping the global tree lock, need to either increment the ire_refcnt
489  * to ensure that the radix node can't be deleted.
490  *
491  * Tree add - Need to hold the global tree lock in write mode to add a
492  * radix node. To prevent the node from being deleted, increment the
493  * irb_refcnt, after the node is added to the tree. The ire itself is
494  * added later while holding the irb_lock, but not the tree lock.
495  *
496  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
497  * All associated ires must be inactive (i.e. freed), and irb_refcnt
498  * must be zero.
499  *
500  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
501  * global tree lock (read mode) for traversal.
502  *
503  * IPSEC notes :
504  *
505  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
506  * in front of the actual packet. For outbound datagrams, the M_CTL
507  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
508  * information used by the IPSEC code for applying the right level of
509  * protection. The information initialized by IP in the ipsec_out_t
510  * is determined by the per-socket policy or global policy in the system.
511  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
512  * ipsec_info.h) which starts out with nothing in it. It gets filled
513  * with the right information if it goes through the AH/ESP code, which
514  * happens if the incoming packet is secure. The information initialized
515  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
516  * the policy requirements needed by per-socket policy or global policy
517  * is met or not.
518  *
519  * If there is both per-socket policy (set using setsockopt) and there
520  * is also global policy match for the 5 tuples of the socket,
521  * ipsec_override_policy() makes the decision of which one to use.
522  *
523  * For fully connected sockets i.e dst, src [addr, port] is known,
524  * conn_policy_cached is set indicating that policy has been cached.
525  * conn_in_enforce_policy may or may not be set depending on whether
526  * there is a global policy match or per-socket policy match.
527  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
528  * Once the right policy is set on the conn_t, policy cannot change for
529  * this socket. This makes life simpler for TCP (UDP ?) where
530  * re-transmissions go out with the same policy. For symmetry, policy
531  * is cached for fully connected UDP sockets also. Thus if policy is cached,
532  * it also implies that policy is latched i.e policy cannot change
533  * on these sockets. As we have the right policy on the conn, we don't
534  * have to lookup global policy for every outbound and inbound datagram
535  * and thus serving as an optimization. Note that a global policy change
536  * does not affect fully connected sockets if they have policy. If fully
537  * connected sockets did not have any policy associated with it, global
538  * policy change may affect them.
539  *
540  * IP Flow control notes:
541  *
542  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
543  * cannot be sent down to the driver by IP, because of a canput failure, IP
544  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
545  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
546  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
547  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
548  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
549  * the queued messages, and removes the conn from the drain list, if all
550  * messages were drained. It also qenables the next conn in the drain list to
551  * continue the drain process.
552  *
553  * In reality the drain list is not a single list, but a configurable number
554  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
555  * list. If the ip_wsrv of the next qenabled conn does not run, because the
556  * stream closes, ip_close takes responsibility to qenable the next conn in
557  * the drain list. The directly called ip_wput path always does a putq, if
558  * it cannot putnext. Thus synchronization problems are handled between
559  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
560  * functions that manipulate this drain list. Furthermore conn_drain_insert
561  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
562  * running on a queue at any time. conn_drain_tail can be simultaneously called
563  * from both ip_wsrv and ip_close.
564  *
565  * IPQOS notes:
566  *
567  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
568  * and IPQoS modules. IPPF includes hooks in IP at different control points
569  * (callout positions) which direct packets to IPQoS modules for policy
570  * processing. Policies, if present, are global.
571  *
572  * The callout positions are located in the following paths:
573  *		o local_in (packets destined for this host)
574  *		o local_out (packets orginating from this host )
575  *		o fwd_in  (packets forwarded by this m/c - inbound)
576  *		o fwd_out (packets forwarded by this m/c - outbound)
577  * Hooks at these callout points can be enabled/disabled using the ndd variable
578  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
579  * By default all the callout positions are enabled.
580  *
581  * Outbound (local_out)
582  * Hooks are placed in ip_wput_ire and ipsec_out_process.
583  *
584  * Inbound (local_in)
585  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
586  * TCP and UDP fanout routines.
587  *
588  * Forwarding (in and out)
589  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
590  *
591  * IP Policy Framework processing (IPPF processing)
592  * Policy processing for a packet is initiated by ip_process, which ascertains
593  * that the classifier (ipgpc) is loaded and configured, failing which the
594  * packet resumes normal processing in IP. If the clasifier is present, the
595  * packet is acted upon by one or more IPQoS modules (action instances), per
596  * filters configured in ipgpc and resumes normal IP processing thereafter.
597  * An action instance can drop a packet in course of its processing.
598  *
599  * A boolean variable, ip_policy, is used in all the fanout routines that can
600  * invoke ip_process for a packet. This variable indicates if the packet should
601  * to be sent for policy processing. The variable is set to B_TRUE by default,
602  * i.e. when the routines are invoked in the normal ip procesing path for a
603  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
604  * ip_policy is set to B_FALSE for all the routines called in these two
605  * functions because, in the former case,  we don't process loopback traffic
606  * currently while in the latter, the packets have already been processed in
607  * icmp_inbound.
608  *
609  * Zones notes:
610  *
611  * The partitioning rules for networking are as follows:
612  * 1) Packets coming from a zone must have a source address belonging to that
613  * zone.
614  * 2) Packets coming from a zone can only be sent on a physical interface on
615  * which the zone has an IP address.
616  * 3) Between two zones on the same machine, packet delivery is only allowed if
617  * there's a matching route for the destination and zone in the forwarding
618  * table.
619  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
620  * different zones can bind to the same port with the wildcard address
621  * (INADDR_ANY).
622  *
623  * The granularity of interface partitioning is at the logical interface level.
624  * Therefore, every zone has its own IP addresses, and incoming packets can be
625  * attributed to a zone unambiguously. A logical interface is placed into a zone
626  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
627  * structure. Rule (1) is implemented by modifying the source address selection
628  * algorithm so that the list of eligible addresses is filtered based on the
629  * sending process zone.
630  *
631  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
632  * across all zones, depending on their type. Here is the break-up:
633  *
634  * IRE type				Shared/exclusive
635  * --------				----------------
636  * IRE_BROADCAST			Exclusive
637  * IRE_DEFAULT (default routes)		Shared (*)
638  * IRE_LOCAL				Exclusive (x)
639  * IRE_LOOPBACK				Exclusive
640  * IRE_PREFIX (net routes)		Shared (*)
641  * IRE_CACHE				Exclusive
642  * IRE_IF_NORESOLVER (interface routes)	Exclusive
643  * IRE_IF_RESOLVER (interface routes)	Exclusive
644  * IRE_HOST (host routes)		Shared (*)
645  *
646  * (*) A zone can only use a default or off-subnet route if the gateway is
647  * directly reachable from the zone, that is, if the gateway's address matches
648  * one of the zone's logical interfaces.
649  *
650  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
651  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
652  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
653  * address of the zone itself (the destination). Since IRE_LOCAL is used
654  * for communication between zones, ip_wput_ire has special logic to set
655  * the right source address when sending using an IRE_LOCAL.
656  *
657  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
658  * ire_cache_lookup restricts loopback using an IRE_LOCAL
659  * between zone to the case when L2 would have conceptually looped the packet
660  * back, i.e. the loopback which is required since neither Ethernet drivers
661  * nor Ethernet hardware loops them back. This is the case when the normal
662  * routes (ignoring IREs with different zoneids) would send out the packet on
663  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
664  * associated.
665  *
666  * Multiple zones can share a common broadcast address; typically all zones
667  * share the 255.255.255.255 address. Incoming as well as locally originated
668  * broadcast packets must be dispatched to all the zones on the broadcast
669  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
670  * since some zones may not be on the 10.16.72/24 network. To handle this, each
671  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
672  * sent to every zone that has an IRE_BROADCAST entry for the destination
673  * address on the input ill, see conn_wantpacket().
674  *
675  * Applications in different zones can join the same multicast group address.
676  * For IPv4, group memberships are per-logical interface, so they're already
677  * inherently part of a zone. For IPv6, group memberships are per-physical
678  * interface, so we distinguish IPv6 group memberships based on group address,
679  * interface and zoneid. In both cases, received multicast packets are sent to
680  * every zone for which a group membership entry exists. On IPv6 we need to
681  * check that the target zone still has an address on the receiving physical
682  * interface; it could have been removed since the application issued the
683  * IPV6_JOIN_GROUP.
684  */
685 
686 /*
687  * Squeue Fanout flags:
688  *	0: No fanout.
689  *	1: Fanout across all squeues
690  */
691 boolean_t	ip_squeue_fanout = 0;
692 
693 /*
694  * Maximum dups allowed per packet.
695  */
696 uint_t ip_max_frag_dups = 10;
697 
698 #define	IS_SIMPLE_IPH(ipha)						\
699 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
700 
701 /* RFC1122 Conformance */
702 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
703 
704 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
705 
706 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
707 
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
709 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
712 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
713     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
714 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
715 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
716 		    mblk_t *, int);
717 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
718 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
719 		    ill_t *, zoneid_t);
720 static void	icmp_options_update(ipha_t *);
721 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
722 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
723 		    zoneid_t zoneid);
724 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
725 static void	icmp_redirect(mblk_t *);
726 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
727 
728 static void	ip_arp_news(queue_t *, mblk_t *);
729 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
730 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
731 char		*ip_dot_addr(ipaddr_t, char *);
732 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
733 int		ip_close(queue_t *, int);
734 static char	*ip_dot_saddr(uchar_t *, char *);
735 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
736 		    boolean_t, boolean_t, ill_t *, zoneid_t);
737 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
738 		    boolean_t, boolean_t, zoneid_t);
739 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
740 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
741 static void	ip_lrput(queue_t *, mblk_t *);
742 ipaddr_t	ip_massage_options(ipha_t *);
743 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
744 ipaddr_t	ip_net_mask(ipaddr_t);
745 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
746 		    zoneid_t);
747 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
748 		    conn_t *, uint32_t, zoneid_t);
749 char		*ip_nv_lookup(nv_t *, int);
750 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
751 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
752 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
754 			    size_t);
755 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
756 void	ip_rput(queue_t *, mblk_t *);
757 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
758 		    void *dummy_arg);
759 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
760 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
761 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
762 			    ire_t *);
763 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
764 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
765 		    uint16_t *);
766 int		ip_snmp_get(queue_t *, mblk_t *);
767 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *);
768 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
769 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
771 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
772 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
783 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
784 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
785 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
786 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
787 static boolean_t	ip_source_routed(ipha_t *);
788 static boolean_t	ip_source_route_included(ipha_t *);
789 
790 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
791 		    zoneid_t);
792 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
793 static void	ip_wput_local_options(ipha_t *);
794 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
795 		    zoneid_t);
796 
797 static void	conn_drain_init(void);
798 static void	conn_drain_fini(void);
799 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
800 
801 static void	conn_walk_drain(void);
802 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
803     zoneid_t);
804 
805 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
806     zoneid_t);
807 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
808     void *dummy_arg);
809 
810 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
811 
812 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
813     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
814     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
815 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
816 
817 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
818 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
819     caddr_t, cred_t *);
820 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
821     caddr_t cp, cred_t *cr);
822 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
823     cred_t *);
824 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
825     caddr_t cp, cred_t *cr);
826 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
827     cred_t *);
828 static squeue_func_t ip_squeue_switch(int);
829 
830 static void	ip_kstat_init(void);
831 static void	ip_kstat_fini(void);
832 static int	ip_kstat_update(kstat_t *kp, int rw);
833 static void	icmp_kstat_init(void);
834 static void	icmp_kstat_fini(void);
835 static int	icmp_kstat_update(kstat_t *kp, int rw);
836 
837 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
838 
839 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
840     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
841 
842 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
843     ipha_t *, ill_t *, boolean_t);
844 
845 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
846 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
847 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
848 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
849 
850 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
851 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
852 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
853 
854 /* How long, in seconds, we allow frags to hang around. */
855 #define	IP_FRAG_TIMEOUT	60
856 
857 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
858 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
859 
860 /*
861  * Threshold which determines whether MDT should be used when
862  * generating IP fragments; payload size must be greater than
863  * this threshold for MDT to take place.
864  */
865 #define	IP_WPUT_FRAG_MDT_MIN	32768
866 
867 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
868 
869 /* Protected by ip_mi_lock */
870 static void	*ip_g_head;		/* Instance Data List Head */
871 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
872 
873 /* Only modified during _init and _fini thus no locking is needed. */
874 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
875 
876 
877 static long ip_rput_pullups;
878 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
879 
880 vmem_t *ip_minor_arena;
881 
882 /*
883  * MIB-2 stuff for SNMP (both IP and ICMP)
884  */
885 mib2_ip_t	ip_mib;
886 mib2_icmp_t	icmp_mib;
887 
888 #ifdef DEBUG
889 uint32_t ipsechw_debug = 0;
890 #endif
891 
892 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
893 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
894 
895 uint_t	loopback_packets = 0;
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
901 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
902 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
903 /* Interval (in ms) between consecutive 'bad MTU' warnings */
904 hrtime_t ip_multirt_log_interval = 1000;
905 /* Time since last warning issued. */
906 static hrtime_t	multirt_bad_mtu_last_time = 0;
907 
908 kmutex_t ip_trash_timer_lock;
909 krwlock_t ip_g_nd_lock;
910 
911 /*
912  * XXX following really should only be in a header. Would need more
913  * header and .c clean up first.
914  */
915 extern optdb_obj_t	ip_opt_obj;
916 
917 ulong_t ip_squeue_enter_unbound = 0;
918 
919 /*
920  * Named Dispatch Parameter Table.
921  * All of these are alterable, within the min/max values given, at run time.
922  */
923 static ipparam_t	lcl_param_arr[] = {
924 	/* min	max	value	name */
925 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
926 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
927 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
928 	{  0,	1,	0,	"ip_respond_to_timestamp"},
929 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
930 	{  0,	1,	1,	"ip_send_redirects"},
931 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
932 	{  0,	10,	0,	"ip_debug"},
933 	{  0,	10,	0,	"ip_mrtdebug"},
934 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
935 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
936 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
937 	{  1,	255,	255,	"ip_def_ttl" },
938 	{  0,	1,	0,	"ip_forward_src_routed"},
939 	{  0,	256,	32,	"ip_wroff_extra" },
940 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
941 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
942 	{  0,	1,	1,	"ip_path_mtu_discovery" },
943 	{  0,	240,	30,	"ip_ignore_delete_time" },
944 	{  0,	1,	0,	"ip_ignore_redirect" },
945 	{  0,	1,	1,	"ip_output_queue" },
946 	{  1,	254,	1,	"ip_broadcast_ttl" },
947 	{  0,	99999,	100,	"ip_icmp_err_interval" },
948 	{  1,	99999,	10,	"ip_icmp_err_burst" },
949 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
950 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
951 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
952 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
953 	{  0,	1,	1,	"icmp_accept_clear_messages" },
954 	{  0,	1,	1,	"igmp_accept_clear_messages" },
955 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
956 				"ip_ndp_delay_first_probe_time"},
957 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
958 				"ip_ndp_max_unicast_solicit"},
959 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
960 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
961 	{  0,	1,	0,	"ip6_forward_src_routed"},
962 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
963 	{  0,	1,	1,	"ip6_send_redirects"},
964 	{  0,	1,	0,	"ip6_ignore_redirect" },
965 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
966 
967 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
968 
969 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
970 
971 	{  0,	1,	1,	"pim_accept_clear_messages" },
972 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
973 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
974 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
975 	{  0,	15,	0,	"ip_policy_mask" },
976 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
977 	{  0,	255,	1,	"ip_multirt_ttl" },
978 	{  0,	1,	1,	"ip_multidata_outbound" },
979 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
980 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
981 	{  0,	1000,	1,	"ip_max_temp_defend" },
982 	{  0,	1000,	3,	"ip_max_defend" },
983 	{  0,	999999,	30,	"ip_defend_interval" },
984 	{  0,	3600000, 300000, "ip_dup_recovery" },
985 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
986 #ifdef DEBUG
987 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
988 #endif
989 };
990 
991 ipparam_t	*ip_param_arr = lcl_param_arr;
992 
993 /* Extended NDP table */
994 static ipndp_t	lcl_ndp_arr[] = {
995 	/* getf			setf		data			name */
996 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
997 	    "ip_forwarding" },
998 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
999 	    "ip6_forwarding" },
1000 	{  ip_ill_report,	NULL,		NULL,
1001 	    "ip_ill_status" },
1002 	{  ip_ipif_report,	NULL,		NULL,
1003 	    "ip_ipif_status" },
1004 	{  ip_ire_report,	NULL,		NULL,
1005 	    "ipv4_ire_status" },
1006 	{  ip_ire_report_mrtun,	NULL,		NULL,
1007 	    "ipv4_mrtun_ire_status" },
1008 	{  ip_ire_report_srcif,	NULL,		NULL,
1009 	    "ipv4_srcif_ire_status" },
1010 	{  ip_ire_report_v6,	NULL,		NULL,
1011 	    "ipv6_ire_status" },
1012 	{  ip_conn_report,	NULL,		NULL,
1013 	    "ip_conn_status" },
1014 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1015 	    "ip_rput_pullups" },
1016 	{  ndp_report,		NULL,		NULL,
1017 	    "ip_ndp_cache_report" },
1018 	{  ip_srcid_report,	NULL,		NULL,
1019 	    "ip_srcid_status" },
1020 	{ ip_param_generic_get, ip_squeue_profile_set,
1021 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1022 	{ ip_param_generic_get, ip_squeue_bind_set,
1023 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1024 	{ ip_param_generic_get, ip_input_proc_set,
1025 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1026 	{ ip_param_generic_get, ip_int_set,
1027 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1028 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1029 	    "ip_cgtp_filter" },
1030 	{ ip_param_generic_get, ip_int_set,
1031 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1032 };
1033 
1034 /*
1035  * ip_g_forward controls IP forwarding.  It takes two values:
1036  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1037  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1038  *
1039  * RFC1122 says there must be a configuration switch to control forwarding,
1040  * but that the default MUST be to not forward packets ever.  Implicit
1041  * control based on configuration of multiple interfaces MUST NOT be
1042  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1043  * and, in fact, it was the default.  That capability is now provided in the
1044  * /etc/rc2.d/S69inet script.
1045  */
1046 int ip_g_forward = IP_FORWARD_DEFAULT;
1047 
1048 /* It also has an IPv6 counterpart. */
1049 
1050 int ipv6_forward = IP_FORWARD_DEFAULT;
1051 
1052 /*
1053  * Table of IP ioctls encoding the various properties of the ioctl and
1054  * indexed based on the last byte of the ioctl command. Occasionally there
1055  * is a clash, and there is more than 1 ioctl with the same last byte.
1056  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1057  * ioctls are encoded in the misc table. An entry in the ndx table is
1058  * retrieved by indexing on the last byte of the ioctl command and comparing
1059  * the ioctl command with the value in the ndx table. In the event of a
1060  * mismatch the misc table is then searched sequentially for the desired
1061  * ioctl command.
1062  *
1063  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1064  */
1065 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1066 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1078 			MISC_CMD, ip_siocaddrt, NULL },
1079 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1080 			MISC_CMD, ip_siocdelrt, NULL },
1081 
1082 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1083 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1084 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_addr, NULL },
1086 
1087 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1088 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1089 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1090 			IPI_GET_CMD | IPI_REPL,
1091 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1092 
1093 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1094 			IPI_PRIV | IPI_WR | IPI_REPL,
1095 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1096 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1097 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1098 			IF_CMD, ip_sioctl_get_flags, NULL },
1099 
1100 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 
1107 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1108 			IF_CMD, ip_sioctl_mtu, NULL },
1109 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1110 			IF_CMD, ip_sioctl_get_mtu, NULL },
1111 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1112 			IPI_GET_CMD | IPI_REPL,
1113 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1114 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1115 			IF_CMD, ip_sioctl_brdaddr, NULL },
1116 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1117 			IPI_GET_CMD | IPI_REPL,
1118 			IF_CMD, ip_sioctl_get_netmask, NULL },
1119 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1120 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1121 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1122 			IPI_GET_CMD | IPI_REPL,
1123 			IF_CMD, ip_sioctl_get_metric, NULL },
1124 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1125 			IF_CMD, ip_sioctl_metric, NULL },
1126 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 
1128 	/* See 166-168 below for extended SIOC*XARP ioctls */
1129 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1130 			MISC_CMD, ip_sioctl_arp, NULL },
1131 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1132 			MISC_CMD, ip_sioctl_arp, NULL },
1133 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1134 			MISC_CMD, ip_sioctl_arp, NULL },
1135 
1136 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 
1158 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1159 			MISC_CMD, if_unitsel, if_unitsel_restart },
1160 
1161 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 
1180 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1181 			IPI_PRIV | IPI_WR | IPI_MODOK,
1182 			IF_CMD, ip_sioctl_sifname, NULL },
1183 
1184 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1188 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1189 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1190 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 
1198 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1199 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1200 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1201 			IF_CMD, ip_sioctl_get_muxid, NULL },
1202 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1203 			IPI_PRIV | IPI_WR | IPI_REPL,
1204 			IF_CMD, ip_sioctl_muxid, NULL },
1205 
1206 	/* Both if and lif variants share same func */
1207 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1208 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1209 	/* Both if and lif variants share same func */
1210 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1211 			IPI_PRIV | IPI_WR | IPI_REPL,
1212 			IF_CMD, ip_sioctl_slifindex, NULL },
1213 
1214 	/* copyin size cannot be coded for SIOCGIFCONF */
1215 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1216 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1217 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1218 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1219 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1220 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1221 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1222 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1223 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 
1235 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_removeif,
1238 			ip_sioctl_removeif_restart },
1239 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_addif, NULL },
1242 #define	SIOCLIFADDR_NDX 112
1243 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1244 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1245 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1246 			IPI_GET_CMD | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_get_addr, NULL },
1248 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1249 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1250 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1251 			IPI_GET_CMD | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1253 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1256 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_flags, NULL },
1259 
1260 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1261 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1262 
1263 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1266 			LIF_CMD, ip_sioctl_mtu, NULL },
1267 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1269 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1272 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1273 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1274 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1275 			IPI_GET_CMD | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1277 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1278 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1279 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1280 			IPI_GET_CMD | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_get_metric, NULL },
1282 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1283 			LIF_CMD, ip_sioctl_metric, NULL },
1284 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1285 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1286 			LIF_CMD, ip_sioctl_slifname,
1287 			ip_sioctl_slifname_restart },
1288 
1289 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1290 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1291 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1292 			IPI_GET_CMD | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1294 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1295 			IPI_PRIV | IPI_WR | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_muxid, NULL },
1297 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1298 			IPI_GET_CMD | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1300 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR | IPI_REPL,
1302 			LIF_CMD, ip_sioctl_slifindex, 0 },
1303 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1304 			LIF_CMD, ip_sioctl_token, NULL },
1305 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1306 			IPI_GET_CMD | IPI_REPL,
1307 			LIF_CMD, ip_sioctl_get_token, NULL },
1308 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1309 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1310 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1311 			IPI_GET_CMD | IPI_REPL,
1312 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1313 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1314 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1315 
1316 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1317 			IPI_GET_CMD | IPI_REPL,
1318 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1319 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1320 			LIF_CMD, ip_siocdelndp_v6, NULL },
1321 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1322 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1323 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1324 			LIF_CMD, ip_siocsetndp_v6, NULL },
1325 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1326 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1327 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1328 			MISC_CMD, ip_sioctl_tonlink, NULL },
1329 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1330 			MISC_CMD, ip_sioctl_tmysite, NULL },
1331 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1332 			TUN_CMD, ip_sioctl_tunparam, NULL },
1333 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1334 			IPI_PRIV | IPI_WR,
1335 			TUN_CMD, ip_sioctl_tunparam, NULL },
1336 
1337 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1338 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1339 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1340 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1341 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1342 
1343 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1344 			IPI_PRIV | IPI_WR | IPI_REPL,
1345 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1346 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1347 			IPI_PRIV | IPI_WR | IPI_REPL,
1348 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1349 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1350 			IPI_PRIV | IPI_WR,
1351 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1352 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1353 			IPI_GET_CMD | IPI_REPL,
1354 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1355 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1356 			IPI_GET_CMD | IPI_REPL,
1357 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1358 
1359 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1360 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1361 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1362 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1363 
1364 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1365 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1366 
1367 	/* These are handled in ip_sioctl_copyin_setup itself */
1368 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1369 			MISC_CMD, NULL, NULL },
1370 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1371 			MISC_CMD, NULL, NULL },
1372 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1373 
1374 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1375 			ip_sioctl_get_lifconf, NULL },
1376 
1377 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1378 			MISC_CMD, ip_sioctl_xarp, NULL },
1379 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1380 			MISC_CMD, ip_sioctl_xarp, NULL },
1381 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1382 			MISC_CMD, ip_sioctl_xarp, NULL },
1383 
1384 	/* SIOCPOPSOCKFS is not handled by IP */
1385 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1386 
1387 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1388 			IPI_GET_CMD | IPI_REPL,
1389 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1390 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1391 			IPI_PRIV | IPI_WR | IPI_REPL,
1392 			LIF_CMD, ip_sioctl_slifzone,
1393 			ip_sioctl_slifzone_restart },
1394 	/* 172-174 are SCTP ioctls and not handled by IP */
1395 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1396 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1397 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1398 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1399 			IPI_GET_CMD, LIF_CMD,
1400 			ip_sioctl_get_lifusesrc, 0 },
1401 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1402 			IPI_PRIV | IPI_WR,
1403 			LIF_CMD, ip_sioctl_slifusesrc,
1404 			NULL },
1405 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1406 			ip_sioctl_get_lifsrcof, NULL },
1407 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1408 			MISC_CMD, ip_sioctl_msfilter, NULL },
1409 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1410 			MISC_CMD, ip_sioctl_msfilter, NULL },
1411 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1412 			MISC_CMD, ip_sioctl_msfilter, NULL },
1413 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1414 			MISC_CMD, ip_sioctl_msfilter, NULL },
1415 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1416 			ip_sioctl_set_ipmpfailback, NULL }
1417 };
1418 
1419 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1420 
1421 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1422 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1423 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1424 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1425 		TUN_CMD, ip_sioctl_tunparam, NULL },
1426 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1427 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1428 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1429 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1430 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1431 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1432 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1433 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1434 		MISC_CMD, mrt_ioctl},
1435 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1436 		MISC_CMD, mrt_ioctl},
1437 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1438 		MISC_CMD, mrt_ioctl}
1439 };
1440 
1441 int ip_misc_ioctl_count =
1442     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1443 
1444 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1445 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1446 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1447 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1448 					/* Settable in /etc/system */
1449 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1450 
1451 /* Defined in ip_ire.c */
1452 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1453 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1454 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1455 
1456 static nv_t	ire_nv_arr[] = {
1457 	{ IRE_BROADCAST, "BROADCAST" },
1458 	{ IRE_LOCAL, "LOCAL" },
1459 	{ IRE_LOOPBACK, "LOOPBACK" },
1460 	{ IRE_CACHE, "CACHE" },
1461 	{ IRE_DEFAULT, "DEFAULT" },
1462 	{ IRE_PREFIX, "PREFIX" },
1463 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1464 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1465 	{ IRE_HOST, "HOST" },
1466 	{ 0 }
1467 };
1468 
1469 nv_t	*ire_nv_tbl = ire_nv_arr;
1470 
1471 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1472 extern krwlock_t ipsec_capab_ills_lock;
1473 
1474 /* Defined in ip_netinfo.c */
1475 extern ddi_taskq_t	*eventq_queue_nic;
1476 
1477 /* Packet dropper for IP IPsec processing failures */
1478 ipdropper_t ip_dropper;
1479 
1480 /* Simple ICMP IP Header Template */
1481 static ipha_t icmp_ipha = {
1482 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1483 };
1484 
1485 struct module_info ip_mod_info = {
1486 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1487 };
1488 
1489 /*
1490  * Duplicate static symbols within a module confuses mdb; so we avoid the
1491  * problem by making the symbols here distinct from those in udp.c.
1492  */
1493 
1494 static struct qinit iprinit = {
1495 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1496 	&ip_mod_info
1497 };
1498 
1499 static struct qinit ipwinit = {
1500 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1501 	&ip_mod_info
1502 };
1503 
1504 static struct qinit iplrinit = {
1505 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1506 	&ip_mod_info
1507 };
1508 
1509 static struct qinit iplwinit = {
1510 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1511 	&ip_mod_info
1512 };
1513 
1514 struct streamtab ipinfo = {
1515 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1516 };
1517 
1518 #ifdef	DEBUG
1519 static boolean_t skip_sctp_cksum = B_FALSE;
1520 #endif
1521 
1522 /*
1523  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1524  * ip_rput_v6(), ip_output(), etc.  If the message
1525  * block already has a M_CTL at the front of it, then simply set the zoneid
1526  * appropriately.
1527  */
1528 mblk_t *
1529 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1530 {
1531 	mblk_t		*first_mp;
1532 	ipsec_out_t	*io;
1533 
1534 	ASSERT(zoneid != ALL_ZONES);
1535 	if (mp->b_datap->db_type == M_CTL) {
1536 		io = (ipsec_out_t *)mp->b_rptr;
1537 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1538 		io->ipsec_out_zoneid = zoneid;
1539 		return (mp);
1540 	}
1541 
1542 	first_mp = ipsec_alloc_ipsec_out();
1543 	if (first_mp == NULL)
1544 		return (NULL);
1545 	io = (ipsec_out_t *)first_mp->b_rptr;
1546 	/* This is not a secure packet */
1547 	io->ipsec_out_secure = B_FALSE;
1548 	io->ipsec_out_zoneid = zoneid;
1549 	first_mp->b_cont = mp;
1550 	return (first_mp);
1551 }
1552 
1553 /*
1554  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1555  */
1556 mblk_t *
1557 ip_copymsg(mblk_t *mp)
1558 {
1559 	mblk_t *nmp;
1560 	ipsec_info_t *in;
1561 
1562 	if (mp->b_datap->db_type != M_CTL)
1563 		return (copymsg(mp));
1564 
1565 	in = (ipsec_info_t *)mp->b_rptr;
1566 
1567 	/*
1568 	 * Note that M_CTL is also used for delivering ICMP error messages
1569 	 * upstream to transport layers.
1570 	 */
1571 	if (in->ipsec_info_type != IPSEC_OUT &&
1572 	    in->ipsec_info_type != IPSEC_IN)
1573 		return (copymsg(mp));
1574 
1575 	nmp = copymsg(mp->b_cont);
1576 
1577 	if (in->ipsec_info_type == IPSEC_OUT)
1578 		return (ipsec_out_tag(mp, nmp));
1579 	else
1580 		return (ipsec_in_tag(mp, nmp));
1581 }
1582 
1583 /* Generate an ICMP fragmentation needed message. */
1584 static void
1585 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1586 {
1587 	icmph_t	icmph;
1588 	mblk_t *first_mp;
1589 	boolean_t mctl_present;
1590 
1591 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1592 
1593 	if (!(mp = icmp_pkt_err_ok(mp))) {
1594 		if (mctl_present)
1595 			freeb(first_mp);
1596 		return;
1597 	}
1598 
1599 	bzero(&icmph, sizeof (icmph_t));
1600 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1601 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1602 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1603 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1604 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1605 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1606 }
1607 
1608 /*
1609  * icmp_inbound deals with ICMP messages in the following ways.
1610  *
1611  * 1) It needs to send a reply back and possibly delivering it
1612  *    to the "interested" upper clients.
1613  * 2) It needs to send it to the upper clients only.
1614  * 3) It needs to change some values in IP only.
1615  * 4) It needs to change some values in IP and upper layers e.g TCP.
1616  *
1617  * We need to accomodate icmp messages coming in clear until we get
1618  * everything secure from the wire. If icmp_accept_clear_messages
1619  * is zero we check with the global policy and act accordingly. If
1620  * it is non-zero, we accept the message without any checks. But
1621  * *this does not mean* that this will be delivered to the upper
1622  * clients. By accepting we might send replies back, change our MTU
1623  * value etc. but delivery to the ULP/clients depends on their policy
1624  * dispositions.
1625  *
1626  * We handle the above 4 cases in the context of IPSEC in the
1627  * following way :
1628  *
1629  * 1) Send the reply back in the same way as the request came in.
1630  *    If it came in encrypted, it goes out encrypted. If it came in
1631  *    clear, it goes out in clear. Thus, this will prevent chosen
1632  *    plain text attack.
1633  * 2) The client may or may not expect things to come in secure.
1634  *    If it comes in secure, the policy constraints are checked
1635  *    before delivering it to the upper layers. If it comes in
1636  *    clear, ipsec_inbound_accept_clear will decide whether to
1637  *    accept this in clear or not. In both the cases, if the returned
1638  *    message (IP header + 8 bytes) that caused the icmp message has
1639  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1640  *    sending up. If there are only 8 bytes of returned message, then
1641  *    upper client will not be notified.
1642  * 3) Check with global policy to see whether it matches the constaints.
1643  *    But this will be done only if icmp_accept_messages_in_clear is
1644  *    zero.
1645  * 4) If we need to change both in IP and ULP, then the decision taken
1646  *    while affecting the values in IP and while delivering up to TCP
1647  *    should be the same.
1648  *
1649  * 	There are two cases.
1650  *
1651  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1652  *	   failed), we will not deliver it to the ULP, even though they
1653  *	   are *willing* to accept in *clear*. This is fine as our global
1654  *	   disposition to icmp messages asks us reject the datagram.
1655  *
1656  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1657  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1658  *	   to deliver it to ULP (policy failed), it can lead to
1659  *	   consistency problems. The cases known at this time are
1660  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1661  *	   values :
1662  *
1663  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1664  *	     and Upper layer rejects. Then the communication will
1665  *	     come to a stop. This is solved by making similar decisions
1666  *	     at both levels. Currently, when we are unable to deliver
1667  *	     to the Upper Layer (due to policy failures) while IP has
1668  *	     adjusted ire_max_frag, the next outbound datagram would
1669  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1670  *	     will be with the right level of protection. Thus the right
1671  *	     value will be communicated even if we are not able to
1672  *	     communicate when we get from the wire initially. But this
1673  *	     assumes there would be at least one outbound datagram after
1674  *	     IP has adjusted its ire_max_frag value. To make things
1675  *	     simpler, we accept in clear after the validation of
1676  *	     AH/ESP headers.
1677  *
1678  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1679  *	     upper layer depending on the level of protection the upper
1680  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1681  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1682  *	     should be accepted in clear when the Upper layer expects secure.
1683  *	     Thus the communication may get aborted by some bad ICMP
1684  *	     packets.
1685  *
1686  * IPQoS Notes:
1687  * The only instance when a packet is sent for processing is when there
1688  * isn't an ICMP client and if we are interested in it.
1689  * If there is a client, IPPF processing will take place in the
1690  * ip_fanout_proto routine.
1691  *
1692  * Zones notes:
1693  * The packet is only processed in the context of the specified zone: typically
1694  * only this zone will reply to an echo request, and only interested clients in
1695  * this zone will receive a copy of the packet. This means that the caller must
1696  * call icmp_inbound() for each relevant zone.
1697  */
1698 static void
1699 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1700     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1701     ill_t *recv_ill, zoneid_t zoneid)
1702 {
1703 	icmph_t	*icmph;
1704 	ipha_t	*ipha;
1705 	int	iph_hdr_length;
1706 	int	hdr_length;
1707 	boolean_t	interested;
1708 	uint32_t	ts;
1709 	uchar_t	*wptr;
1710 	ipif_t	*ipif;
1711 	mblk_t *first_mp;
1712 	ipsec_in_t *ii;
1713 	ire_t *src_ire;
1714 	boolean_t onlink;
1715 	timestruc_t now;
1716 	uint32_t ill_index;
1717 
1718 	ASSERT(ill != NULL);
1719 
1720 	first_mp = mp;
1721 	if (mctl_present) {
1722 		mp = first_mp->b_cont;
1723 		ASSERT(mp != NULL);
1724 	}
1725 
1726 	ipha = (ipha_t *)mp->b_rptr;
1727 	if (icmp_accept_clear_messages == 0) {
1728 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1729 		    ipha, NULL, mctl_present);
1730 		if (first_mp == NULL)
1731 			return;
1732 	}
1733 
1734 	/*
1735 	 * On a labeled system, we have to check whether the zone itself is
1736 	 * permitted to receive raw traffic.
1737 	 */
1738 	if (is_system_labeled()) {
1739 		if (zoneid == ALL_ZONES)
1740 			zoneid = tsol_packet_to_zoneid(mp);
1741 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1742 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1743 			    zoneid));
1744 			BUMP_MIB(&icmp_mib, icmpInErrors);
1745 			freemsg(first_mp);
1746 			return;
1747 		}
1748 	}
1749 
1750 	/*
1751 	 * We have accepted the ICMP message. It means that we will
1752 	 * respond to the packet if needed. It may not be delivered
1753 	 * to the upper client depending on the policy constraints
1754 	 * and the disposition in ipsec_inbound_accept_clear.
1755 	 */
1756 
1757 	ASSERT(ill != NULL);
1758 
1759 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1760 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1761 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1762 		/* Last chance to get real. */
1763 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1764 			BUMP_MIB(&icmp_mib, icmpInErrors);
1765 			freemsg(first_mp);
1766 			return;
1767 		}
1768 		/* Refresh iph following the pullup. */
1769 		ipha = (ipha_t *)mp->b_rptr;
1770 	}
1771 	/* ICMP header checksum, including checksum field, should be zero. */
1772 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1773 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1774 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1775 		freemsg(first_mp);
1776 		return;
1777 	}
1778 	/* The IP header will always be a multiple of four bytes */
1779 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1780 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1781 	    icmph->icmph_code));
1782 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1783 	/* We will set "interested" to "true" if we want a copy */
1784 	interested = B_FALSE;
1785 	switch (icmph->icmph_type) {
1786 	case ICMP_ECHO_REPLY:
1787 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1788 		break;
1789 	case ICMP_DEST_UNREACHABLE:
1790 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1791 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1792 		interested = B_TRUE;	/* Pass up to transport */
1793 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1794 		break;
1795 	case ICMP_SOURCE_QUENCH:
1796 		interested = B_TRUE;	/* Pass up to transport */
1797 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1798 		break;
1799 	case ICMP_REDIRECT:
1800 		if (!ip_ignore_redirect)
1801 			interested = B_TRUE;
1802 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1803 		break;
1804 	case ICMP_ECHO_REQUEST:
1805 		/*
1806 		 * Whether to respond to echo requests that come in as IP
1807 		 * broadcasts or as IP multicast is subject to debate
1808 		 * (what isn't?).  We aim to please, you pick it.
1809 		 * Default is do it.
1810 		 */
1811 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1812 			/* unicast: always respond */
1813 			interested = B_TRUE;
1814 		} else if (CLASSD(ipha->ipha_dst)) {
1815 			/* multicast: respond based on tunable */
1816 			interested = ip_g_resp_to_echo_mcast;
1817 		} else if (broadcast) {
1818 			/* broadcast: respond based on tunable */
1819 			interested = ip_g_resp_to_echo_bcast;
1820 		}
1821 		BUMP_MIB(&icmp_mib, icmpInEchos);
1822 		break;
1823 	case ICMP_ROUTER_ADVERTISEMENT:
1824 	case ICMP_ROUTER_SOLICITATION:
1825 		break;
1826 	case ICMP_TIME_EXCEEDED:
1827 		interested = B_TRUE;	/* Pass up to transport */
1828 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1829 		break;
1830 	case ICMP_PARAM_PROBLEM:
1831 		interested = B_TRUE;	/* Pass up to transport */
1832 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1833 		break;
1834 	case ICMP_TIME_STAMP_REQUEST:
1835 		/* Response to Time Stamp Requests is local policy. */
1836 		if (ip_g_resp_to_timestamp &&
1837 		    /* So is whether to respond if it was an IP broadcast. */
1838 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1839 			int tstamp_len = 3 * sizeof (uint32_t);
1840 
1841 			if (wptr +  tstamp_len > mp->b_wptr) {
1842 				if (!pullupmsg(mp, wptr + tstamp_len -
1843 				    mp->b_rptr)) {
1844 					BUMP_MIB(&ip_mib, ipInDiscards);
1845 					freemsg(first_mp);
1846 					return;
1847 				}
1848 				/* Refresh ipha following the pullup. */
1849 				ipha = (ipha_t *)mp->b_rptr;
1850 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1851 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1852 			}
1853 			interested = B_TRUE;
1854 		}
1855 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1856 		break;
1857 	case ICMP_TIME_STAMP_REPLY:
1858 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1859 		break;
1860 	case ICMP_INFO_REQUEST:
1861 		/* Per RFC 1122 3.2.2.7, ignore this. */
1862 	case ICMP_INFO_REPLY:
1863 		break;
1864 	case ICMP_ADDRESS_MASK_REQUEST:
1865 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1866 		    /* TODO m_pullup of complete header? */
1867 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1868 			interested = B_TRUE;
1869 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1870 		break;
1871 	case ICMP_ADDRESS_MASK_REPLY:
1872 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1873 		break;
1874 	default:
1875 		interested = B_TRUE;	/* Pass up to transport */
1876 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1877 		break;
1878 	}
1879 	/* See if there is an ICMP client. */
1880 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1881 		/* If there is an ICMP client and we want one too, copy it. */
1882 		mblk_t *first_mp1;
1883 
1884 		if (!interested) {
1885 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1886 			    ip_policy, recv_ill, zoneid);
1887 			return;
1888 		}
1889 		first_mp1 = ip_copymsg(first_mp);
1890 		if (first_mp1 != NULL) {
1891 			ip_fanout_proto(q, first_mp1, ill, ipha,
1892 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1893 		}
1894 	} else if (!interested) {
1895 		freemsg(first_mp);
1896 		return;
1897 	} else {
1898 		/*
1899 		 * Initiate policy processing for this packet if ip_policy
1900 		 * is true.
1901 		 */
1902 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1903 			ill_index = ill->ill_phyint->phyint_ifindex;
1904 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1905 			if (mp == NULL) {
1906 				if (mctl_present) {
1907 					freeb(first_mp);
1908 				}
1909 				BUMP_MIB(&icmp_mib, icmpInErrors);
1910 				return;
1911 			}
1912 		}
1913 	}
1914 	/* We want to do something with it. */
1915 	/* Check db_ref to make sure we can modify the packet. */
1916 	if (mp->b_datap->db_ref > 1) {
1917 		mblk_t	*first_mp1;
1918 
1919 		first_mp1 = ip_copymsg(first_mp);
1920 		freemsg(first_mp);
1921 		if (!first_mp1) {
1922 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1923 			return;
1924 		}
1925 		first_mp = first_mp1;
1926 		if (mctl_present) {
1927 			mp = first_mp->b_cont;
1928 			ASSERT(mp != NULL);
1929 		} else {
1930 			mp = first_mp;
1931 		}
1932 		ipha = (ipha_t *)mp->b_rptr;
1933 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1934 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1935 	}
1936 	switch (icmph->icmph_type) {
1937 	case ICMP_ADDRESS_MASK_REQUEST:
1938 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1939 		if (ipif == NULL) {
1940 			freemsg(first_mp);
1941 			return;
1942 		}
1943 		/*
1944 		 * outging interface must be IPv4
1945 		 */
1946 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1947 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1948 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1949 		ipif_refrele(ipif);
1950 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1951 		break;
1952 	case ICMP_ECHO_REQUEST:
1953 		icmph->icmph_type = ICMP_ECHO_REPLY;
1954 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1955 		break;
1956 	case ICMP_TIME_STAMP_REQUEST: {
1957 		uint32_t *tsp;
1958 
1959 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1960 		tsp = (uint32_t *)wptr;
1961 		tsp++;		/* Skip past 'originate time' */
1962 		/* Compute # of milliseconds since midnight */
1963 		gethrestime(&now);
1964 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1965 		    now.tv_nsec / (NANOSEC / MILLISEC);
1966 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1967 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1968 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1969 		break;
1970 	}
1971 	default:
1972 		ipha = (ipha_t *)&icmph[1];
1973 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1974 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1975 				BUMP_MIB(&ip_mib, ipInDiscards);
1976 				freemsg(first_mp);
1977 				return;
1978 			}
1979 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1980 			ipha = (ipha_t *)&icmph[1];
1981 		}
1982 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1983 			BUMP_MIB(&ip_mib, ipInDiscards);
1984 			freemsg(first_mp);
1985 			return;
1986 		}
1987 		hdr_length = IPH_HDR_LENGTH(ipha);
1988 		if (hdr_length < sizeof (ipha_t)) {
1989 			BUMP_MIB(&ip_mib, ipInDiscards);
1990 			freemsg(first_mp);
1991 			return;
1992 		}
1993 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1994 			if (!pullupmsg(mp,
1995 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1996 				BUMP_MIB(&ip_mib, ipInDiscards);
1997 				freemsg(first_mp);
1998 				return;
1999 			}
2000 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2001 			ipha = (ipha_t *)&icmph[1];
2002 		}
2003 		switch (icmph->icmph_type) {
2004 		case ICMP_REDIRECT:
2005 			/*
2006 			 * As there is no upper client to deliver, we don't
2007 			 * need the first_mp any more.
2008 			 */
2009 			if (mctl_present) {
2010 				freeb(first_mp);
2011 			}
2012 			icmp_redirect(mp);
2013 			return;
2014 		case ICMP_DEST_UNREACHABLE:
2015 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2016 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2017 				    zoneid, mp, iph_hdr_length)) {
2018 					freemsg(first_mp);
2019 					return;
2020 				}
2021 				/*
2022 				 * icmp_inbound_too_big() may alter mp.
2023 				 * Resynch ipha and icmph accordingly.
2024 				 */
2025 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2026 				ipha = (ipha_t *)&icmph[1];
2027 			}
2028 			/* FALLTHRU */
2029 		default :
2030 			/*
2031 			 * IPQoS notes: Since we have already done IPQoS
2032 			 * processing we don't want to do it again in
2033 			 * the fanout routines called by
2034 			 * icmp_inbound_error_fanout, hence the last
2035 			 * argument, ip_policy, is B_FALSE.
2036 			 */
2037 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2038 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2039 			    B_FALSE, recv_ill, zoneid);
2040 		}
2041 		return;
2042 	}
2043 	/* Send out an ICMP packet */
2044 	icmph->icmph_checksum = 0;
2045 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2046 	if (icmph->icmph_checksum == 0)
2047 		icmph->icmph_checksum = 0xFFFF;
2048 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2049 		ipif_t	*ipif_chosen;
2050 		/*
2051 		 * Make it look like it was directed to us, so we don't look
2052 		 * like a fool with a broadcast or multicast source address.
2053 		 */
2054 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2055 		/*
2056 		 * Make sure that we haven't grabbed an interface that's DOWN.
2057 		 */
2058 		if (ipif != NULL) {
2059 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2060 			    ipha->ipha_src, zoneid);
2061 			if (ipif_chosen != NULL) {
2062 				ipif_refrele(ipif);
2063 				ipif = ipif_chosen;
2064 			}
2065 		}
2066 		if (ipif == NULL) {
2067 			ip0dbg(("icmp_inbound: "
2068 			    "No source for broadcast/multicast:\n"
2069 			    "\tsrc 0x%x dst 0x%x ill %p "
2070 			    "ipif_lcl_addr 0x%x\n",
2071 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2072 			    (void *)ill,
2073 			    ill->ill_ipif->ipif_lcl_addr));
2074 			freemsg(first_mp);
2075 			return;
2076 		}
2077 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2078 		ipha->ipha_dst = ipif->ipif_src_addr;
2079 		ipif_refrele(ipif);
2080 	}
2081 	/* Reset time to live. */
2082 	ipha->ipha_ttl = ip_def_ttl;
2083 	{
2084 		/* Swap source and destination addresses */
2085 		ipaddr_t tmp;
2086 
2087 		tmp = ipha->ipha_src;
2088 		ipha->ipha_src = ipha->ipha_dst;
2089 		ipha->ipha_dst = tmp;
2090 	}
2091 	ipha->ipha_ident = 0;
2092 	if (!IS_SIMPLE_IPH(ipha))
2093 		icmp_options_update(ipha);
2094 
2095 	/*
2096 	 * ICMP echo replies should go out on the same interface
2097 	 * the request came on as probes used by in.mpathd for detecting
2098 	 * NIC failures are ECHO packets. We turn-off load spreading
2099 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2100 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2101 	 * function. This is in turn handled by ip_wput and ip_newroute
2102 	 * to make sure that the packet goes out on the interface it came
2103 	 * in on. If we don't turnoff load spreading, the packets might get
2104 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2105 	 * to go out and in.mpathd would wrongly detect a failure or
2106 	 * mis-detect a NIC failure for link failure. As load spreading
2107 	 * can happen only if ill_group is not NULL, we do only for
2108 	 * that case and this does not affect the normal case.
2109 	 *
2110 	 * We turn off load spreading only on echo packets that came from
2111 	 * on-link hosts. If the interface route has been deleted, this will
2112 	 * not be enforced as we can't do much. For off-link hosts, as the
2113 	 * default routes in IPv4 does not typically have an ire_ipif
2114 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2115 	 * Moreover, expecting a default route through this interface may
2116 	 * not be correct. We use ipha_dst because of the swap above.
2117 	 */
2118 	onlink = B_FALSE;
2119 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2120 		/*
2121 		 * First, we need to make sure that it is not one of our
2122 		 * local addresses. If we set onlink when it is one of
2123 		 * our local addresses, we will end up creating IRE_CACHES
2124 		 * for one of our local addresses. Then, we will never
2125 		 * accept packets for them afterwards.
2126 		 */
2127 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2128 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2129 		if (src_ire == NULL) {
2130 			ipif = ipif_get_next_ipif(NULL, ill);
2131 			if (ipif == NULL) {
2132 				BUMP_MIB(&ip_mib, ipInDiscards);
2133 				freemsg(mp);
2134 				return;
2135 			}
2136 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2137 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2138 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2139 			ipif_refrele(ipif);
2140 			if (src_ire != NULL) {
2141 				onlink = B_TRUE;
2142 				ire_refrele(src_ire);
2143 			}
2144 		} else {
2145 			ire_refrele(src_ire);
2146 		}
2147 	}
2148 	if (!mctl_present) {
2149 		/*
2150 		 * This packet should go out the same way as it
2151 		 * came in i.e in clear. To make sure that global
2152 		 * policy will not be applied to this in ip_wput_ire,
2153 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2154 		 */
2155 		ASSERT(first_mp == mp);
2156 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2157 			BUMP_MIB(&ip_mib, ipInDiscards);
2158 			freemsg(mp);
2159 			return;
2160 		}
2161 		ii = (ipsec_in_t *)first_mp->b_rptr;
2162 
2163 		/* This is not a secure packet */
2164 		ii->ipsec_in_secure = B_FALSE;
2165 		if (onlink) {
2166 			ii->ipsec_in_attach_if = B_TRUE;
2167 			ii->ipsec_in_ill_index =
2168 			    ill->ill_phyint->phyint_ifindex;
2169 			ii->ipsec_in_rill_index =
2170 			    recv_ill->ill_phyint->phyint_ifindex;
2171 		}
2172 		first_mp->b_cont = mp;
2173 	} else if (onlink) {
2174 		ii = (ipsec_in_t *)first_mp->b_rptr;
2175 		ii->ipsec_in_attach_if = B_TRUE;
2176 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2177 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2178 	} else {
2179 		ii = (ipsec_in_t *)first_mp->b_rptr;
2180 	}
2181 	ii->ipsec_in_zoneid = zoneid;
2182 	ASSERT(zoneid != ALL_ZONES);
2183 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2184 		BUMP_MIB(&ip_mib, ipInDiscards);
2185 		return;
2186 	}
2187 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2188 	put(WR(q), first_mp);
2189 }
2190 
2191 static ipaddr_t
2192 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2193 {
2194 	conn_t *connp;
2195 	connf_t *connfp;
2196 	ipaddr_t nexthop_addr = INADDR_ANY;
2197 	int hdr_length = IPH_HDR_LENGTH(ipha);
2198 	uint16_t *up;
2199 	uint32_t ports;
2200 
2201 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2202 	switch (ipha->ipha_protocol) {
2203 		case IPPROTO_TCP:
2204 		{
2205 			tcph_t *tcph;
2206 
2207 			/* do a reverse lookup */
2208 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2209 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2210 			    TCPS_LISTEN);
2211 			break;
2212 		}
2213 		case IPPROTO_UDP:
2214 		{
2215 			uint32_t dstport, srcport;
2216 
2217 			((uint16_t *)&ports)[0] = up[1];
2218 			((uint16_t *)&ports)[1] = up[0];
2219 
2220 			/* Extract ports in net byte order */
2221 			dstport = htons(ntohl(ports) & 0xFFFF);
2222 			srcport = htons(ntohl(ports) >> 16);
2223 
2224 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2225 			mutex_enter(&connfp->connf_lock);
2226 			connp = connfp->connf_head;
2227 
2228 			/* do a reverse lookup */
2229 			while ((connp != NULL) &&
2230 			    (!IPCL_UDP_MATCH(connp, dstport,
2231 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2232 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2233 				connp = connp->conn_next;
2234 			}
2235 			if (connp != NULL)
2236 				CONN_INC_REF(connp);
2237 			mutex_exit(&connfp->connf_lock);
2238 			break;
2239 		}
2240 		case IPPROTO_SCTP:
2241 		{
2242 			in6_addr_t map_src, map_dst;
2243 
2244 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2245 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2246 			((uint16_t *)&ports)[0] = up[1];
2247 			((uint16_t *)&ports)[1] = up[0];
2248 
2249 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2250 			    0, zoneid)) == NULL) {
2251 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2252 				    zoneid, ports, ipha);
2253 			} else {
2254 				CONN_INC_REF(connp);
2255 				SCTP_REFRELE(CONN2SCTP(connp));
2256 			}
2257 			break;
2258 		}
2259 		default:
2260 		{
2261 			ipha_t ripha;
2262 
2263 			ripha.ipha_src = ipha->ipha_dst;
2264 			ripha.ipha_dst = ipha->ipha_src;
2265 			ripha.ipha_protocol = ipha->ipha_protocol;
2266 
2267 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2268 			mutex_enter(&connfp->connf_lock);
2269 			connp = connfp->connf_head;
2270 			for (connp = connfp->connf_head; connp != NULL;
2271 			    connp = connp->conn_next) {
2272 				if (IPCL_PROTO_MATCH(connp,
2273 				    ipha->ipha_protocol, &ripha, ill,
2274 				    0, zoneid)) {
2275 					CONN_INC_REF(connp);
2276 					break;
2277 				}
2278 			}
2279 			mutex_exit(&connfp->connf_lock);
2280 		}
2281 	}
2282 	if (connp != NULL) {
2283 		if (connp->conn_nexthop_set)
2284 			nexthop_addr = connp->conn_nexthop_v4;
2285 		CONN_DEC_REF(connp);
2286 	}
2287 	return (nexthop_addr);
2288 }
2289 
2290 /* Table from RFC 1191 */
2291 static int icmp_frag_size_table[] =
2292 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2293 
2294 /*
2295  * Process received ICMP Packet too big.
2296  * After updating any IRE it does the fanout to any matching transport streams.
2297  * Assumes the message has been pulled up till the IP header that caused
2298  * the error.
2299  *
2300  * Returns B_FALSE on failure and B_TRUE on success.
2301  */
2302 static boolean_t
2303 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2304     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2305 {
2306 	ire_t	*ire, *first_ire;
2307 	int	mtu;
2308 	int	hdr_length;
2309 	ipaddr_t nexthop_addr;
2310 
2311 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2312 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2313 
2314 	hdr_length = IPH_HDR_LENGTH(ipha);
2315 
2316 	/* Drop if the original packet contained a source route */
2317 	if (ip_source_route_included(ipha)) {
2318 		return (B_FALSE);
2319 	}
2320 	/*
2321 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2322 	 * header.
2323 	 */
2324 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2325 	    mp->b_wptr) {
2326 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2327 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2328 			BUMP_MIB(&ip_mib, ipInDiscards);
2329 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2330 			return (B_FALSE);
2331 		}
2332 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2333 		ipha = (ipha_t *)&icmph[1];
2334 	}
2335 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2336 	if (nexthop_addr != INADDR_ANY) {
2337 		/* nexthop set */
2338 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2339 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2340 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2341 	} else {
2342 		/* nexthop not set */
2343 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2344 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2345 	}
2346 
2347 	if (!first_ire) {
2348 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2349 		    ntohl(ipha->ipha_dst)));
2350 		return (B_FALSE);
2351 	}
2352 	/* Check for MTU discovery advice as described in RFC 1191 */
2353 	mtu = ntohs(icmph->icmph_du_mtu);
2354 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2355 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2356 	    ire = ire->ire_next) {
2357 		/*
2358 		 * Look for the connection to which this ICMP message is
2359 		 * directed. If it has the IP_NEXTHOP option set, then the
2360 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2361 		 * option. Else the search is limited to regular IREs.
2362 		 */
2363 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2364 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2365 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2366 		    (nexthop_addr != INADDR_ANY)))
2367 			continue;
2368 
2369 		mutex_enter(&ire->ire_lock);
2370 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2371 			/* Reduce the IRE max frag value as advised. */
2372 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2373 			    mtu, ire->ire_max_frag));
2374 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2375 		} else {
2376 			uint32_t length;
2377 			int	i;
2378 
2379 			/*
2380 			 * Use the table from RFC 1191 to figure out
2381 			 * the next "plateau" based on the length in
2382 			 * the original IP packet.
2383 			 */
2384 			length = ntohs(ipha->ipha_length);
2385 			if (ire->ire_max_frag <= length &&
2386 			    ire->ire_max_frag >= length - hdr_length) {
2387 				/*
2388 				 * Handle broken BSD 4.2 systems that
2389 				 * return the wrong iph_length in ICMP
2390 				 * errors.
2391 				 */
2392 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2393 				    length, ire->ire_max_frag));
2394 				length -= hdr_length;
2395 			}
2396 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2397 				if (length > icmp_frag_size_table[i])
2398 					break;
2399 			}
2400 			if (i == A_CNT(icmp_frag_size_table)) {
2401 				/* Smaller than 68! */
2402 				ip1dbg(("Too big for packet size %d\n",
2403 				    length));
2404 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2405 				ire->ire_frag_flag = 0;
2406 			} else {
2407 				mtu = icmp_frag_size_table[i];
2408 				ip1dbg(("Calculated mtu %d, packet size %d, "
2409 				    "before %d", mtu, length,
2410 				    ire->ire_max_frag));
2411 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2412 				ip1dbg((", after %d\n", ire->ire_max_frag));
2413 			}
2414 			/* Record the new max frag size for the ULP. */
2415 			icmph->icmph_du_zero = 0;
2416 			icmph->icmph_du_mtu =
2417 			    htons((uint16_t)ire->ire_max_frag);
2418 		}
2419 		mutex_exit(&ire->ire_lock);
2420 	}
2421 	rw_exit(&first_ire->ire_bucket->irb_lock);
2422 	ire_refrele(first_ire);
2423 	return (B_TRUE);
2424 }
2425 
2426 /*
2427  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2428  * calls this function.
2429  */
2430 static mblk_t *
2431 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2432 {
2433 	ipha_t *ipha;
2434 	icmph_t *icmph;
2435 	ipha_t *in_ipha;
2436 	int length;
2437 
2438 	ASSERT(mp->b_datap->db_type == M_DATA);
2439 
2440 	/*
2441 	 * For Self-encapsulated packets, we added an extra IP header
2442 	 * without the options. Inner IP header is the one from which
2443 	 * the outer IP header was formed. Thus, we need to remove the
2444 	 * outer IP header. To do this, we pullup the whole message
2445 	 * and overlay whatever follows the outer IP header over the
2446 	 * outer IP header.
2447 	 */
2448 
2449 	if (!pullupmsg(mp, -1)) {
2450 		BUMP_MIB(&ip_mib, ipInDiscards);
2451 		return (NULL);
2452 	}
2453 
2454 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2455 	ipha = (ipha_t *)&icmph[1];
2456 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2457 
2458 	/*
2459 	 * The length that we want to overlay is following the inner
2460 	 * IP header. Subtracting the IP header + icmp header + outer
2461 	 * IP header's length should give us the length that we want to
2462 	 * overlay.
2463 	 */
2464 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2465 	    hdr_length;
2466 	/*
2467 	 * Overlay whatever follows the inner header over the
2468 	 * outer header.
2469 	 */
2470 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2471 
2472 	/* Set the wptr to account for the outer header */
2473 	mp->b_wptr -= hdr_length;
2474 	return (mp);
2475 }
2476 
2477 /*
2478  * Try to pass the ICMP message upstream in case the ULP cares.
2479  *
2480  * If the packet that caused the ICMP error is secure, we send
2481  * it to AH/ESP to make sure that the attached packet has a
2482  * valid association. ipha in the code below points to the
2483  * IP header of the packet that caused the error.
2484  *
2485  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2486  * in the context of IPSEC. Normally we tell the upper layer
2487  * whenever we send the ire (including ip_bind), the IPSEC header
2488  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2489  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2490  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2491  * same thing. As TCP has the IPSEC options size that needs to be
2492  * adjusted, we just pass the MTU unchanged.
2493  *
2494  * IFN could have been generated locally or by some router.
2495  *
2496  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2497  *	    This happens because IP adjusted its value of MTU on an
2498  *	    earlier IFN message and could not tell the upper layer,
2499  *	    the new adjusted value of MTU e.g. Packet was encrypted
2500  *	    or there was not enough information to fanout to upper
2501  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2502  *	    generates the IFN, where IPSEC processing has *not* been
2503  *	    done.
2504  *
2505  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2506  *	    could have generated this. This happens because ire_max_frag
2507  *	    value in IP was set to a new value, while the IPSEC processing
2508  *	    was being done and after we made the fragmentation check in
2509  *	    ip_wput_ire. Thus on return from IPSEC processing,
2510  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2511  *	    and generates the IFN. As IPSEC processing is over, we fanout
2512  *	    to AH/ESP to remove the header.
2513  *
2514  *	    In both these cases, ipsec_in_loopback will be set indicating
2515  *	    that IFN was generated locally.
2516  *
2517  * ROUTER : IFN could be secure or non-secure.
2518  *
2519  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2520  *	      packet in error has AH/ESP headers to validate the AH/ESP
2521  *	      headers. AH/ESP will verify whether there is a valid SA or
2522  *	      not and send it back. We will fanout again if we have more
2523  *	      data in the packet.
2524  *
2525  *	      If the packet in error does not have AH/ESP, we handle it
2526  *	      like any other case.
2527  *
2528  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2529  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2530  *	      for validation. AH/ESP will verify whether there is a
2531  *	      valid SA or not and send it back. We will fanout again if
2532  *	      we have more data in the packet.
2533  *
2534  *	      If the packet in error does not have AH/ESP, we handle it
2535  *	      like any other case.
2536  */
2537 static void
2538 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2539     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2540     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2541     zoneid_t zoneid)
2542 {
2543 	uint16_t *up;	/* Pointer to ports in ULP header */
2544 	uint32_t ports;	/* reversed ports for fanout */
2545 	ipha_t ripha;	/* With reversed addresses */
2546 	mblk_t *first_mp;
2547 	ipsec_in_t *ii;
2548 	tcph_t	*tcph;
2549 	conn_t	*connp;
2550 
2551 	first_mp = mp;
2552 	if (mctl_present) {
2553 		mp = first_mp->b_cont;
2554 		ASSERT(mp != NULL);
2555 
2556 		ii = (ipsec_in_t *)first_mp->b_rptr;
2557 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2558 	} else {
2559 		ii = NULL;
2560 	}
2561 
2562 	switch (ipha->ipha_protocol) {
2563 	case IPPROTO_UDP:
2564 		/*
2565 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2566 		 * transport header.
2567 		 */
2568 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2569 		    mp->b_wptr) {
2570 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2571 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2572 				BUMP_MIB(&ip_mib, ipInDiscards);
2573 				goto drop_pkt;
2574 			}
2575 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2576 			ipha = (ipha_t *)&icmph[1];
2577 		}
2578 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2579 
2580 		/*
2581 		 * Attempt to find a client stream based on port.
2582 		 * Note that we do a reverse lookup since the header is
2583 		 * in the form we sent it out.
2584 		 * The ripha header is only used for the IP_UDP_MATCH and we
2585 		 * only set the src and dst addresses and protocol.
2586 		 */
2587 		ripha.ipha_src = ipha->ipha_dst;
2588 		ripha.ipha_dst = ipha->ipha_src;
2589 		ripha.ipha_protocol = ipha->ipha_protocol;
2590 		((uint16_t *)&ports)[0] = up[1];
2591 		((uint16_t *)&ports)[1] = up[0];
2592 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2593 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2594 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2595 		    icmph->icmph_type, icmph->icmph_code));
2596 
2597 		/* Have to change db_type after any pullupmsg */
2598 		DB_TYPE(mp) = M_CTL;
2599 
2600 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2601 		    mctl_present, ip_policy, recv_ill, zoneid);
2602 		return;
2603 
2604 	case IPPROTO_TCP:
2605 		/*
2606 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2607 		 * transport header.
2608 		 */
2609 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2610 		    mp->b_wptr) {
2611 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2612 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2613 				BUMP_MIB(&ip_mib, ipInDiscards);
2614 				goto drop_pkt;
2615 			}
2616 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2617 			ipha = (ipha_t *)&icmph[1];
2618 		}
2619 		/*
2620 		 * Find a TCP client stream for this packet.
2621 		 * Note that we do a reverse lookup since the header is
2622 		 * in the form we sent it out.
2623 		 */
2624 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2625 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2626 		if (connp == NULL) {
2627 			BUMP_MIB(&ip_mib, ipInDiscards);
2628 			goto drop_pkt;
2629 		}
2630 
2631 		/* Have to change db_type after any pullupmsg */
2632 		DB_TYPE(mp) = M_CTL;
2633 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2634 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2635 		return;
2636 
2637 	case IPPROTO_SCTP:
2638 		/*
2639 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2640 		 * transport header.
2641 		 */
2642 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2643 		    mp->b_wptr) {
2644 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2645 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2646 				BUMP_MIB(&ip_mib, ipInDiscards);
2647 				goto drop_pkt;
2648 			}
2649 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2650 			ipha = (ipha_t *)&icmph[1];
2651 		}
2652 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2653 		/*
2654 		 * Find a SCTP client stream for this packet.
2655 		 * Note that we do a reverse lookup since the header is
2656 		 * in the form we sent it out.
2657 		 * The ripha header is only used for the matching and we
2658 		 * only set the src and dst addresses, protocol, and version.
2659 		 */
2660 		ripha.ipha_src = ipha->ipha_dst;
2661 		ripha.ipha_dst = ipha->ipha_src;
2662 		ripha.ipha_protocol = ipha->ipha_protocol;
2663 		ripha.ipha_version_and_hdr_length =
2664 		    ipha->ipha_version_and_hdr_length;
2665 		((uint16_t *)&ports)[0] = up[1];
2666 		((uint16_t *)&ports)[1] = up[0];
2667 
2668 		/* Have to change db_type after any pullupmsg */
2669 		DB_TYPE(mp) = M_CTL;
2670 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2671 		    mctl_present, ip_policy, 0, zoneid);
2672 		return;
2673 
2674 	case IPPROTO_ESP:
2675 	case IPPROTO_AH: {
2676 		int ipsec_rc;
2677 
2678 		/*
2679 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2680 		 * We will re-use the IPSEC_IN if it is already present as
2681 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2682 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2683 		 * one and attach it in the front.
2684 		 */
2685 		if (ii != NULL) {
2686 			/*
2687 			 * ip_fanout_proto_again converts the ICMP errors
2688 			 * that come back from AH/ESP to M_DATA so that
2689 			 * if it is non-AH/ESP and we do a pullupmsg in
2690 			 * this function, it would work. Convert it back
2691 			 * to M_CTL before we send up as this is a ICMP
2692 			 * error. This could have been generated locally or
2693 			 * by some router. Validate the inner IPSEC
2694 			 * headers.
2695 			 *
2696 			 * NOTE : ill_index is used by ip_fanout_proto_again
2697 			 * to locate the ill.
2698 			 */
2699 			ASSERT(ill != NULL);
2700 			ii->ipsec_in_ill_index =
2701 			    ill->ill_phyint->phyint_ifindex;
2702 			ii->ipsec_in_rill_index =
2703 			    recv_ill->ill_phyint->phyint_ifindex;
2704 			DB_TYPE(first_mp->b_cont) = M_CTL;
2705 		} else {
2706 			/*
2707 			 * IPSEC_IN is not present. We attach a ipsec_in
2708 			 * message and send up to IPSEC for validating
2709 			 * and removing the IPSEC headers. Clear
2710 			 * ipsec_in_secure so that when we return
2711 			 * from IPSEC, we don't mistakenly think that this
2712 			 * is a secure packet came from the network.
2713 			 *
2714 			 * NOTE : ill_index is used by ip_fanout_proto_again
2715 			 * to locate the ill.
2716 			 */
2717 			ASSERT(first_mp == mp);
2718 			first_mp = ipsec_in_alloc(B_TRUE);
2719 			if (first_mp == NULL) {
2720 				freemsg(mp);
2721 				BUMP_MIB(&ip_mib, ipInDiscards);
2722 				return;
2723 			}
2724 			ii = (ipsec_in_t *)first_mp->b_rptr;
2725 
2726 			/* This is not a secure packet */
2727 			ii->ipsec_in_secure = B_FALSE;
2728 			first_mp->b_cont = mp;
2729 			DB_TYPE(mp) = M_CTL;
2730 			ASSERT(ill != NULL);
2731 			ii->ipsec_in_ill_index =
2732 			    ill->ill_phyint->phyint_ifindex;
2733 			ii->ipsec_in_rill_index =
2734 			    recv_ill->ill_phyint->phyint_ifindex;
2735 		}
2736 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2737 
2738 		if (!ipsec_loaded()) {
2739 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2740 			return;
2741 		}
2742 
2743 		if (ipha->ipha_protocol == IPPROTO_ESP)
2744 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2745 		else
2746 			ipsec_rc = ipsecah_icmp_error(first_mp);
2747 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2748 			return;
2749 
2750 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2751 		return;
2752 	}
2753 	default:
2754 		/*
2755 		 * The ripha header is only used for the lookup and we
2756 		 * only set the src and dst addresses and protocol.
2757 		 */
2758 		ripha.ipha_src = ipha->ipha_dst;
2759 		ripha.ipha_dst = ipha->ipha_src;
2760 		ripha.ipha_protocol = ipha->ipha_protocol;
2761 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2762 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2763 		    ntohl(ipha->ipha_dst),
2764 		    icmph->icmph_type, icmph->icmph_code));
2765 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2766 			ipha_t *in_ipha;
2767 
2768 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2769 			    mp->b_wptr) {
2770 				if (!pullupmsg(mp, (uchar_t *)ipha +
2771 				    hdr_length + sizeof (ipha_t) -
2772 				    mp->b_rptr)) {
2773 
2774 					BUMP_MIB(&ip_mib, ipInDiscards);
2775 					goto drop_pkt;
2776 				}
2777 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2778 				ipha = (ipha_t *)&icmph[1];
2779 			}
2780 			/*
2781 			 * Caller has verified that length has to be
2782 			 * at least the size of IP header.
2783 			 */
2784 			ASSERT(hdr_length >= sizeof (ipha_t));
2785 			/*
2786 			 * Check the sanity of the inner IP header like
2787 			 * we did for the outer header.
2788 			 */
2789 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2790 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2791 				BUMP_MIB(&ip_mib, ipInDiscards);
2792 				goto drop_pkt;
2793 			}
2794 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2795 				BUMP_MIB(&ip_mib, ipInDiscards);
2796 				goto drop_pkt;
2797 			}
2798 			/* Check for Self-encapsulated tunnels */
2799 			if (in_ipha->ipha_src == ipha->ipha_src &&
2800 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2801 
2802 				mp = icmp_inbound_self_encap_error(mp,
2803 				    iph_hdr_length, hdr_length);
2804 				if (mp == NULL)
2805 					goto drop_pkt;
2806 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2807 				ipha = (ipha_t *)&icmph[1];
2808 				hdr_length = IPH_HDR_LENGTH(ipha);
2809 				/*
2810 				 * The packet in error is self-encapsualted.
2811 				 * And we are finding it further encapsulated
2812 				 * which we could not have possibly generated.
2813 				 */
2814 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2815 					BUMP_MIB(&ip_mib, ipInDiscards);
2816 					goto drop_pkt;
2817 				}
2818 				icmp_inbound_error_fanout(q, ill, first_mp,
2819 				    icmph, ipha, iph_hdr_length, hdr_length,
2820 				    mctl_present, ip_policy, recv_ill, zoneid);
2821 				return;
2822 			}
2823 		}
2824 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2825 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2826 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2827 		    ii != NULL &&
2828 		    ii->ipsec_in_loopback &&
2829 		    ii->ipsec_in_secure) {
2830 			/*
2831 			 * For IP tunnels that get a looped-back
2832 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2833 			 * reported new MTU to take into account the IPsec
2834 			 * headers protecting this configured tunnel.
2835 			 *
2836 			 * This allows the tunnel module (tun.c) to blindly
2837 			 * accept the MTU reported in an ICMP "too big"
2838 			 * message.
2839 			 *
2840 			 * Non-looped back ICMP messages will just be
2841 			 * handled by the security protocols (if needed),
2842 			 * and the first subsequent packet will hit this
2843 			 * path.
2844 			 */
2845 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2846 			    ipsec_in_extra_length(first_mp));
2847 		}
2848 		/* Have to change db_type after any pullupmsg */
2849 		DB_TYPE(mp) = M_CTL;
2850 
2851 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2852 		    ip_policy, recv_ill, zoneid);
2853 		return;
2854 	}
2855 	/* NOTREACHED */
2856 drop_pkt:;
2857 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2858 	freemsg(first_mp);
2859 }
2860 
2861 /*
2862  * Common IP options parser.
2863  *
2864  * Setup routine: fill in *optp with options-parsing state, then
2865  * tail-call ipoptp_next to return the first option.
2866  */
2867 uint8_t
2868 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2869 {
2870 	uint32_t totallen; /* total length of all options */
2871 
2872 	totallen = ipha->ipha_version_and_hdr_length -
2873 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2874 	totallen <<= 2;
2875 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2876 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2877 	optp->ipoptp_flags = 0;
2878 	return (ipoptp_next(optp));
2879 }
2880 
2881 /*
2882  * Common IP options parser: extract next option.
2883  */
2884 uint8_t
2885 ipoptp_next(ipoptp_t *optp)
2886 {
2887 	uint8_t *end = optp->ipoptp_end;
2888 	uint8_t *cur = optp->ipoptp_next;
2889 	uint8_t opt, len, pointer;
2890 
2891 	/*
2892 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2893 	 * has been corrupted.
2894 	 */
2895 	ASSERT(cur <= end);
2896 
2897 	if (cur == end)
2898 		return (IPOPT_EOL);
2899 
2900 	opt = cur[IPOPT_OPTVAL];
2901 
2902 	/*
2903 	 * Skip any NOP options.
2904 	 */
2905 	while (opt == IPOPT_NOP) {
2906 		cur++;
2907 		if (cur == end)
2908 			return (IPOPT_EOL);
2909 		opt = cur[IPOPT_OPTVAL];
2910 	}
2911 
2912 	if (opt == IPOPT_EOL)
2913 		return (IPOPT_EOL);
2914 
2915 	/*
2916 	 * Option requiring a length.
2917 	 */
2918 	if ((cur + 1) >= end) {
2919 		optp->ipoptp_flags |= IPOPTP_ERROR;
2920 		return (IPOPT_EOL);
2921 	}
2922 	len = cur[IPOPT_OLEN];
2923 	if (len < 2) {
2924 		optp->ipoptp_flags |= IPOPTP_ERROR;
2925 		return (IPOPT_EOL);
2926 	}
2927 	optp->ipoptp_cur = cur;
2928 	optp->ipoptp_len = len;
2929 	optp->ipoptp_next = cur + len;
2930 	if (cur + len > end) {
2931 		optp->ipoptp_flags |= IPOPTP_ERROR;
2932 		return (IPOPT_EOL);
2933 	}
2934 
2935 	/*
2936 	 * For the options which require a pointer field, make sure
2937 	 * its there, and make sure it points to either something
2938 	 * inside this option, or the end of the option.
2939 	 */
2940 	switch (opt) {
2941 	case IPOPT_RR:
2942 	case IPOPT_TS:
2943 	case IPOPT_LSRR:
2944 	case IPOPT_SSRR:
2945 		if (len <= IPOPT_OFFSET) {
2946 			optp->ipoptp_flags |= IPOPTP_ERROR;
2947 			return (opt);
2948 		}
2949 		pointer = cur[IPOPT_OFFSET];
2950 		if (pointer - 1 > len) {
2951 			optp->ipoptp_flags |= IPOPTP_ERROR;
2952 			return (opt);
2953 		}
2954 		break;
2955 	}
2956 
2957 	/*
2958 	 * Sanity check the pointer field based on the type of the
2959 	 * option.
2960 	 */
2961 	switch (opt) {
2962 	case IPOPT_RR:
2963 	case IPOPT_SSRR:
2964 	case IPOPT_LSRR:
2965 		if (pointer < IPOPT_MINOFF_SR)
2966 			optp->ipoptp_flags |= IPOPTP_ERROR;
2967 		break;
2968 	case IPOPT_TS:
2969 		if (pointer < IPOPT_MINOFF_IT)
2970 			optp->ipoptp_flags |= IPOPTP_ERROR;
2971 		/*
2972 		 * Note that the Internet Timestamp option also
2973 		 * contains two four bit fields (the Overflow field,
2974 		 * and the Flag field), which follow the pointer
2975 		 * field.  We don't need to check that these fields
2976 		 * fall within the length of the option because this
2977 		 * was implicitely done above.  We've checked that the
2978 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2979 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2980 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2981 		 */
2982 		ASSERT(len > IPOPT_POS_OV_FLG);
2983 		break;
2984 	}
2985 
2986 	return (opt);
2987 }
2988 
2989 /*
2990  * Use the outgoing IP header to create an IP_OPTIONS option the way
2991  * it was passed down from the application.
2992  */
2993 int
2994 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2995 {
2996 	ipoptp_t	opts;
2997 	const uchar_t	*opt;
2998 	uint8_t		optval;
2999 	uint8_t		optlen;
3000 	uint32_t	len = 0;
3001 	uchar_t	*buf1 = buf;
3002 
3003 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
3004 	len += IP_ADDR_LEN;
3005 	bzero(buf1, IP_ADDR_LEN);
3006 
3007 	/*
3008 	 * OK to cast away const here, as we don't store through the returned
3009 	 * opts.ipoptp_cur pointer.
3010 	 */
3011 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
3012 	    optval != IPOPT_EOL;
3013 	    optval = ipoptp_next(&opts)) {
3014 		int	off;
3015 
3016 		opt = opts.ipoptp_cur;
3017 		optlen = opts.ipoptp_len;
3018 		switch (optval) {
3019 		case IPOPT_SSRR:
3020 		case IPOPT_LSRR:
3021 
3022 			/*
3023 			 * Insert ipha_dst as the first entry in the source
3024 			 * route and move down the entries on step.
3025 			 * The last entry gets placed at buf1.
3026 			 */
3027 			buf[IPOPT_OPTVAL] = optval;
3028 			buf[IPOPT_OLEN] = optlen;
3029 			buf[IPOPT_OFFSET] = optlen;
3030 
3031 			off = optlen - IP_ADDR_LEN;
3032 			if (off < 0) {
3033 				/* No entries in source route */
3034 				break;
3035 			}
3036 			/* Last entry in source route */
3037 			bcopy(opt + off, buf1, IP_ADDR_LEN);
3038 			off -= IP_ADDR_LEN;
3039 
3040 			while (off > 0) {
3041 				bcopy(opt + off,
3042 				    buf + off + IP_ADDR_LEN,
3043 				    IP_ADDR_LEN);
3044 				off -= IP_ADDR_LEN;
3045 			}
3046 			/* ipha_dst into first slot */
3047 			bcopy(&ipha->ipha_dst,
3048 			    buf + off + IP_ADDR_LEN,
3049 			    IP_ADDR_LEN);
3050 			buf += optlen;
3051 			len += optlen;
3052 			break;
3053 
3054 		case IPOPT_COMSEC:
3055 		case IPOPT_SECURITY:
3056 			/* if passing up a label is not ok, then remove */
3057 			if (is_system_labeled())
3058 				break;
3059 			/* FALLTHROUGH */
3060 		default:
3061 			bcopy(opt, buf, optlen);
3062 			buf += optlen;
3063 			len += optlen;
3064 			break;
3065 		}
3066 	}
3067 done:
3068 	/* Pad the resulting options */
3069 	while (len & 0x3) {
3070 		*buf++ = IPOPT_EOL;
3071 		len++;
3072 	}
3073 	return (len);
3074 }
3075 
3076 /*
3077  * Update any record route or timestamp options to include this host.
3078  * Reverse any source route option.
3079  * This routine assumes that the options are well formed i.e. that they
3080  * have already been checked.
3081  */
3082 static void
3083 icmp_options_update(ipha_t *ipha)
3084 {
3085 	ipoptp_t	opts;
3086 	uchar_t		*opt;
3087 	uint8_t		optval;
3088 	ipaddr_t	src;		/* Our local address */
3089 	ipaddr_t	dst;
3090 
3091 	ip2dbg(("icmp_options_update\n"));
3092 	src = ipha->ipha_src;
3093 	dst = ipha->ipha_dst;
3094 
3095 	for (optval = ipoptp_first(&opts, ipha);
3096 	    optval != IPOPT_EOL;
3097 	    optval = ipoptp_next(&opts)) {
3098 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3099 		opt = opts.ipoptp_cur;
3100 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3101 		    optval, opts.ipoptp_len));
3102 		switch (optval) {
3103 			int off1, off2;
3104 		case IPOPT_SSRR:
3105 		case IPOPT_LSRR:
3106 			/*
3107 			 * Reverse the source route.  The first entry
3108 			 * should be the next to last one in the current
3109 			 * source route (the last entry is our address).
3110 			 * The last entry should be the final destination.
3111 			 */
3112 			off1 = IPOPT_MINOFF_SR - 1;
3113 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3114 			if (off2 < 0) {
3115 				/* No entries in source route */
3116 				ip1dbg((
3117 				    "icmp_options_update: bad src route\n"));
3118 				break;
3119 			}
3120 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3121 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3122 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3123 			off2 -= IP_ADDR_LEN;
3124 
3125 			while (off1 < off2) {
3126 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3127 				bcopy((char *)opt + off2, (char *)opt + off1,
3128 				    IP_ADDR_LEN);
3129 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3130 				off1 += IP_ADDR_LEN;
3131 				off2 -= IP_ADDR_LEN;
3132 			}
3133 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3134 			break;
3135 		}
3136 	}
3137 }
3138 
3139 /*
3140  * Process received ICMP Redirect messages.
3141  */
3142 /* ARGSUSED */
3143 static void
3144 icmp_redirect(mblk_t *mp)
3145 {
3146 	ipha_t	*ipha;
3147 	int	iph_hdr_length;
3148 	icmph_t	*icmph;
3149 	ipha_t	*ipha_err;
3150 	ire_t	*ire;
3151 	ire_t	*prev_ire;
3152 	ire_t	*save_ire;
3153 	ipaddr_t  src, dst, gateway;
3154 	iulp_t	ulp_info = { 0 };
3155 	int	error;
3156 
3157 	ipha = (ipha_t *)mp->b_rptr;
3158 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3159 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3160 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3161 		BUMP_MIB(&icmp_mib, icmpInErrors);
3162 		freemsg(mp);
3163 		return;
3164 	}
3165 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3166 	ipha_err = (ipha_t *)&icmph[1];
3167 	src = ipha->ipha_src;
3168 	dst = ipha_err->ipha_dst;
3169 	gateway = icmph->icmph_rd_gateway;
3170 	/* Make sure the new gateway is reachable somehow. */
3171 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3172 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
3173 	/*
3174 	 * Make sure we had a route for the dest in question and that
3175 	 * that route was pointing to the old gateway (the source of the
3176 	 * redirect packet.)
3177 	 */
3178 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3179 	    NULL, MATCH_IRE_GW);
3180 	/*
3181 	 * Check that
3182 	 *	the redirect was not from ourselves
3183 	 *	the new gateway and the old gateway are directly reachable
3184 	 */
3185 	if (!prev_ire ||
3186 	    !ire ||
3187 	    ire->ire_type == IRE_LOCAL) {
3188 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3189 		freemsg(mp);
3190 		if (ire != NULL)
3191 			ire_refrele(ire);
3192 		if (prev_ire != NULL)
3193 			ire_refrele(prev_ire);
3194 		return;
3195 	}
3196 
3197 	/*
3198 	 * Should we use the old ULP info to create the new gateway?  From
3199 	 * a user's perspective, we should inherit the info so that it
3200 	 * is a "smooth" transition.  If we do not do that, then new
3201 	 * connections going thru the new gateway will have no route metrics,
3202 	 * which is counter-intuitive to user.  From a network point of
3203 	 * view, this may or may not make sense even though the new gateway
3204 	 * is still directly connected to us so the route metrics should not
3205 	 * change much.
3206 	 *
3207 	 * But if the old ire_uinfo is not initialized, we do another
3208 	 * recursive lookup on the dest using the new gateway.  There may
3209 	 * be a route to that.  If so, use it to initialize the redirect
3210 	 * route.
3211 	 */
3212 	if (prev_ire->ire_uinfo.iulp_set) {
3213 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3214 	} else {
3215 		ire_t *tmp_ire;
3216 		ire_t *sire;
3217 
3218 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3219 		    ALL_ZONES, 0, NULL,
3220 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT));
3221 		if (sire != NULL) {
3222 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3223 			/*
3224 			 * If sire != NULL, ire_ftable_lookup() should not
3225 			 * return a NULL value.
3226 			 */
3227 			ASSERT(tmp_ire != NULL);
3228 			ire_refrele(tmp_ire);
3229 			ire_refrele(sire);
3230 		} else if (tmp_ire != NULL) {
3231 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3232 			    sizeof (iulp_t));
3233 			ire_refrele(tmp_ire);
3234 		}
3235 	}
3236 	if (prev_ire->ire_type == IRE_CACHE)
3237 		ire_delete(prev_ire);
3238 	ire_refrele(prev_ire);
3239 	/*
3240 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3241 	 * require TOS routing
3242 	 */
3243 	switch (icmph->icmph_code) {
3244 	case 0:
3245 	case 1:
3246 		/* TODO: TOS specificity for cases 2 and 3 */
3247 	case 2:
3248 	case 3:
3249 		break;
3250 	default:
3251 		freemsg(mp);
3252 		BUMP_MIB(&icmp_mib, icmpInBadRedirects);
3253 		ire_refrele(ire);
3254 		return;
3255 	}
3256 	/*
3257 	 * Create a Route Association.  This will allow us to remember that
3258 	 * someone we believe told us to use the particular gateway.
3259 	 */
3260 	save_ire = ire;
3261 	ire = ire_create(
3262 		(uchar_t *)&dst,			/* dest addr */
3263 		(uchar_t *)&ip_g_all_ones,		/* mask */
3264 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3265 		(uchar_t *)&gateway,			/* gateway addr */
3266 		NULL,					/* no in_srcaddr */
3267 		&save_ire->ire_max_frag,		/* max frag */
3268 		NULL,					/* Fast Path header */
3269 		NULL,					/* no rfq */
3270 		NULL,					/* no stq */
3271 		IRE_HOST,
3272 		NULL,
3273 		NULL,
3274 		NULL,
3275 		0,
3276 		0,
3277 		0,
3278 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3279 		&ulp_info,
3280 		NULL,
3281 		NULL);
3282 
3283 	if (ire == NULL) {
3284 		freemsg(mp);
3285 		ire_refrele(save_ire);
3286 		return;
3287 	}
3288 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3289 	ire_refrele(save_ire);
3290 	atomic_inc_32(&ip_redirect_cnt);
3291 
3292 	if (error == 0) {
3293 		ire_refrele(ire);		/* Held in ire_add_v4 */
3294 		/* tell routing sockets that we received a redirect */
3295 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3296 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3297 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR));
3298 	}
3299 
3300 	/*
3301 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3302 	 * This together with the added IRE has the effect of
3303 	 * modifying an existing redirect.
3304 	 */
3305 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3306 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE));
3307 	if (prev_ire != NULL) {
3308 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3309 			ire_delete(prev_ire);
3310 		ire_refrele(prev_ire);
3311 	}
3312 
3313 	freemsg(mp);
3314 }
3315 
3316 /*
3317  * Generate an ICMP parameter problem message.
3318  */
3319 static void
3320 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid)
3321 {
3322 	icmph_t	icmph;
3323 	boolean_t mctl_present;
3324 	mblk_t *first_mp;
3325 
3326 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3327 
3328 	if (!(mp = icmp_pkt_err_ok(mp))) {
3329 		if (mctl_present)
3330 			freeb(first_mp);
3331 		return;
3332 	}
3333 
3334 	bzero(&icmph, sizeof (icmph_t));
3335 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3336 	icmph.icmph_pp_ptr = ptr;
3337 	BUMP_MIB(&icmp_mib, icmpOutParmProbs);
3338 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3339 }
3340 
3341 /*
3342  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3343  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3344  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3345  * an icmp error packet can be sent.
3346  * Assigns an appropriate source address to the packet. If ipha_dst is
3347  * one of our addresses use it for source. Otherwise pick a source based
3348  * on a route lookup back to ipha_src.
3349  * Note that ipha_src must be set here since the
3350  * packet is likely to arrive on an ill queue in ip_wput() which will
3351  * not set a source address.
3352  */
3353 static void
3354 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3355     boolean_t mctl_present, zoneid_t zoneid)
3356 {
3357 	ipaddr_t dst;
3358 	icmph_t	*icmph;
3359 	ipha_t	*ipha;
3360 	uint_t	len_needed;
3361 	size_t	msg_len;
3362 	mblk_t	*mp1;
3363 	ipaddr_t src;
3364 	ire_t	*ire;
3365 	mblk_t *ipsec_mp;
3366 	ipsec_out_t	*io = NULL;
3367 	boolean_t xmit_if_on = B_FALSE;
3368 
3369 	if (mctl_present) {
3370 		/*
3371 		 * If it is :
3372 		 *
3373 		 * 1) a IPSEC_OUT, then this is caused by outbound
3374 		 *    datagram originating on this host. IPSEC processing
3375 		 *    may or may not have been done. Refer to comments above
3376 		 *    icmp_inbound_error_fanout for details.
3377 		 *
3378 		 * 2) a IPSEC_IN if we are generating a icmp_message
3379 		 *    for an incoming datagram destined for us i.e called
3380 		 *    from ip_fanout_send_icmp.
3381 		 */
3382 		ipsec_info_t *in;
3383 		ipsec_mp = mp;
3384 		mp = ipsec_mp->b_cont;
3385 
3386 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3390 		    in->ipsec_info_type == IPSEC_IN);
3391 
3392 		if (in->ipsec_info_type == IPSEC_IN) {
3393 			/*
3394 			 * Convert the IPSEC_IN to IPSEC_OUT.
3395 			 */
3396 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3397 				BUMP_MIB(&ip_mib, ipOutDiscards);
3398 				return;
3399 			}
3400 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3401 		} else {
3402 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3403 			io = (ipsec_out_t *)in;
3404 			if (io->ipsec_out_xmit_if)
3405 				xmit_if_on = B_TRUE;
3406 			/*
3407 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3408 			 * ire lookup.
3409 			 */
3410 			io->ipsec_out_proc_begin = B_FALSE;
3411 		}
3412 		ASSERT(zoneid == io->ipsec_out_zoneid);
3413 		ASSERT(zoneid != ALL_ZONES);
3414 	} else {
3415 		/*
3416 		 * This is in clear. The icmp message we are building
3417 		 * here should go out in clear.
3418 		 *
3419 		 * Pardon the convolution of it all, but it's easier to
3420 		 * allocate a "use cleartext" IPSEC_IN message and convert
3421 		 * it than it is to allocate a new one.
3422 		 */
3423 		ipsec_in_t *ii;
3424 		ASSERT(DB_TYPE(mp) == M_DATA);
3425 		if ((ipsec_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
3426 			freemsg(mp);
3427 			BUMP_MIB(&ip_mib, ipOutDiscards);
3428 			return;
3429 		}
3430 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3431 
3432 		/* This is not a secure packet */
3433 		ii->ipsec_in_secure = B_FALSE;
3434 		/*
3435 		 * For trusted extensions using a shared IP address we can
3436 		 * send using any zoneid.
3437 		 */
3438 		if (zoneid == ALL_ZONES)
3439 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3440 		else
3441 			ii->ipsec_in_zoneid = zoneid;
3442 		ipsec_mp->b_cont = mp;
3443 		ipha = (ipha_t *)mp->b_rptr;
3444 		/*
3445 		 * Convert the IPSEC_IN to IPSEC_OUT.
3446 		 */
3447 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3448 			BUMP_MIB(&ip_mib, ipOutDiscards);
3449 			return;
3450 		}
3451 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3452 	}
3453 
3454 	/* Remember our eventual destination */
3455 	dst = ipha->ipha_src;
3456 
3457 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3458 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE);
3459 	if (ire != NULL &&
3460 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3461 		src = ipha->ipha_dst;
3462 	} else if (!xmit_if_on) {
3463 		if (ire != NULL)
3464 			ire_refrele(ire);
3465 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3466 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY));
3467 		if (ire == NULL) {
3468 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3469 			freemsg(ipsec_mp);
3470 			return;
3471 		}
3472 		src = ire->ire_src_addr;
3473 	} else {
3474 		ipif_t	*ipif = NULL;
3475 		ill_t	*ill;
3476 		/*
3477 		 * This must be an ICMP error coming from
3478 		 * ip_mrtun_forward(). The src addr should
3479 		 * be equal to the IP-addr of the outgoing
3480 		 * interface.
3481 		 */
3482 		if (io == NULL) {
3483 			/* This is not a IPSEC_OUT type control msg */
3484 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3485 			freemsg(ipsec_mp);
3486 			return;
3487 		}
3488 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3489 		    NULL, NULL, NULL, NULL);
3490 		if (ill != NULL) {
3491 			ipif = ipif_get_next_ipif(NULL, ill);
3492 			ill_refrele(ill);
3493 		}
3494 		if (ipif == NULL) {
3495 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
3496 			freemsg(ipsec_mp);
3497 			return;
3498 		}
3499 		src = ipif->ipif_src_addr;
3500 		ipif_refrele(ipif);
3501 	}
3502 
3503 	if (ire != NULL)
3504 		ire_refrele(ire);
3505 
3506 	/*
3507 	 * Check if we can send back more then 8 bytes in addition
3508 	 * to the IP header. We will include as much as 64 bytes.
3509 	 */
3510 	len_needed = IPH_HDR_LENGTH(ipha);
3511 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3512 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3513 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3514 	}
3515 	len_needed += ip_icmp_return;
3516 	msg_len = msgdsize(mp);
3517 	if (msg_len > len_needed) {
3518 		(void) adjmsg(mp, len_needed - msg_len);
3519 		msg_len = len_needed;
3520 	}
3521 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3522 	if (mp1 == NULL) {
3523 		BUMP_MIB(&icmp_mib, icmpOutErrors);
3524 		freemsg(ipsec_mp);
3525 		return;
3526 	}
3527 	/*
3528 	 * On an unlabeled system, dblks don't necessarily have creds.
3529 	 */
3530 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3531 	if (DB_CRED(mp) != NULL)
3532 		mblk_setcred(mp1, DB_CRED(mp));
3533 	mp1->b_cont = mp;
3534 	mp = mp1;
3535 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3536 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3537 	    io->ipsec_out_type == IPSEC_OUT);
3538 	ipsec_mp->b_cont = mp;
3539 
3540 	/*
3541 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3542 	 * node generates be accepted in peace by all on-host destinations.
3543 	 * If we do NOT assume that all on-host destinations trust
3544 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3545 	 * (Look for ipsec_out_icmp_loopback).
3546 	 */
3547 	io->ipsec_out_icmp_loopback = B_TRUE;
3548 
3549 	ipha = (ipha_t *)mp->b_rptr;
3550 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3551 	*ipha = icmp_ipha;
3552 	ipha->ipha_src = src;
3553 	ipha->ipha_dst = dst;
3554 	ipha->ipha_ttl = ip_def_ttl;
3555 	msg_len += sizeof (icmp_ipha) + len;
3556 	if (msg_len > IP_MAXPACKET) {
3557 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3558 		msg_len = IP_MAXPACKET;
3559 	}
3560 	ipha->ipha_length = htons((uint16_t)msg_len);
3561 	icmph = (icmph_t *)&ipha[1];
3562 	bcopy(stuff, icmph, len);
3563 	icmph->icmph_checksum = 0;
3564 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3565 	if (icmph->icmph_checksum == 0)
3566 		icmph->icmph_checksum = 0xFFFF;
3567 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
3568 	put(q, ipsec_mp);
3569 }
3570 
3571 /*
3572  * Determine if an ICMP error packet can be sent given the rate limit.
3573  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3574  * in milliseconds) and a burst size. Burst size number of packets can
3575  * be sent arbitrarely closely spaced.
3576  * The state is tracked using two variables to implement an approximate
3577  * token bucket filter:
3578  *	icmp_pkt_err_last - lbolt value when the last burst started
3579  *	icmp_pkt_err_sent - number of packets sent in current burst
3580  */
3581 boolean_t
3582 icmp_err_rate_limit(void)
3583 {
3584 	clock_t now = TICK_TO_MSEC(lbolt);
3585 	uint_t refilled; /* Number of packets refilled in tbf since last */
3586 	uint_t err_interval = ip_icmp_err_interval; /* Guard against changes */
3587 
3588 	if (err_interval == 0)
3589 		return (B_FALSE);
3590 
3591 	if (icmp_pkt_err_last > now) {
3592 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3593 		icmp_pkt_err_last = 0;
3594 		icmp_pkt_err_sent = 0;
3595 	}
3596 	/*
3597 	 * If we are in a burst update the token bucket filter.
3598 	 * Update the "last" time to be close to "now" but make sure
3599 	 * we don't loose precision.
3600 	 */
3601 	if (icmp_pkt_err_sent != 0) {
3602 		refilled = (now - icmp_pkt_err_last)/err_interval;
3603 		if (refilled > icmp_pkt_err_sent) {
3604 			icmp_pkt_err_sent = 0;
3605 		} else {
3606 			icmp_pkt_err_sent -= refilled;
3607 			icmp_pkt_err_last += refilled * err_interval;
3608 		}
3609 	}
3610 	if (icmp_pkt_err_sent == 0) {
3611 		/* Start of new burst */
3612 		icmp_pkt_err_last = now;
3613 	}
3614 	if (icmp_pkt_err_sent < ip_icmp_err_burst) {
3615 		icmp_pkt_err_sent++;
3616 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3617 		    icmp_pkt_err_sent));
3618 		return (B_FALSE);
3619 	}
3620 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3621 	return (B_TRUE);
3622 }
3623 
3624 /*
3625  * Check if it is ok to send an IPv4 ICMP error packet in
3626  * response to the IPv4 packet in mp.
3627  * Free the message and return null if no
3628  * ICMP error packet should be sent.
3629  */
3630 static mblk_t *
3631 icmp_pkt_err_ok(mblk_t *mp)
3632 {
3633 	icmph_t	*icmph;
3634 	ipha_t	*ipha;
3635 	uint_t	len_needed;
3636 	ire_t	*src_ire;
3637 	ire_t	*dst_ire;
3638 
3639 	if (!mp)
3640 		return (NULL);
3641 	ipha = (ipha_t *)mp->b_rptr;
3642 	if (ip_csum_hdr(ipha)) {
3643 		BUMP_MIB(&ip_mib, ipInCksumErrs);
3644 		freemsg(mp);
3645 		return (NULL);
3646 	}
3647 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3648 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3649 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3650 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3651 	if (src_ire != NULL || dst_ire != NULL ||
3652 	    CLASSD(ipha->ipha_dst) ||
3653 	    CLASSD(ipha->ipha_src) ||
3654 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3655 		/* Note: only errors to the fragment with offset 0 */
3656 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3657 		freemsg(mp);
3658 		if (src_ire != NULL)
3659 			ire_refrele(src_ire);
3660 		if (dst_ire != NULL)
3661 			ire_refrele(dst_ire);
3662 		return (NULL);
3663 	}
3664 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3665 		/*
3666 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3667 		 * errors in response to any ICMP errors.
3668 		 */
3669 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3670 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3671 			if (!pullupmsg(mp, len_needed)) {
3672 				BUMP_MIB(&icmp_mib, icmpInErrors);
3673 				freemsg(mp);
3674 				return (NULL);
3675 			}
3676 			ipha = (ipha_t *)mp->b_rptr;
3677 		}
3678 		icmph = (icmph_t *)
3679 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3680 		switch (icmph->icmph_type) {
3681 		case ICMP_DEST_UNREACHABLE:
3682 		case ICMP_SOURCE_QUENCH:
3683 		case ICMP_TIME_EXCEEDED:
3684 		case ICMP_PARAM_PROBLEM:
3685 		case ICMP_REDIRECT:
3686 			BUMP_MIB(&icmp_mib, icmpOutDrops);
3687 			freemsg(mp);
3688 			return (NULL);
3689 		default:
3690 			break;
3691 		}
3692 	}
3693 	/*
3694 	 * If this is a labeled system, then check to see if we're allowed to
3695 	 * send a response to this particular sender.  If not, then just drop.
3696 	 */
3697 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3698 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3699 		BUMP_MIB(&icmp_mib, icmpOutDrops);
3700 		freemsg(mp);
3701 		return (NULL);
3702 	}
3703 	if (icmp_err_rate_limit()) {
3704 		/*
3705 		 * Only send ICMP error packets every so often.
3706 		 * This should be done on a per port/source basis,
3707 		 * but for now this will suffice.
3708 		 */
3709 		freemsg(mp);
3710 		return (NULL);
3711 	}
3712 	return (mp);
3713 }
3714 
3715 /*
3716  * Generate an ICMP redirect message.
3717  */
3718 static void
3719 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway)
3720 {
3721 	icmph_t	icmph;
3722 
3723 	/*
3724 	 * We are called from ip_rput where we could
3725 	 * not have attached an IPSEC_IN.
3726 	 */
3727 	ASSERT(mp->b_datap->db_type == M_DATA);
3728 
3729 	if (!(mp = icmp_pkt_err_ok(mp))) {
3730 		return;
3731 	}
3732 
3733 	bzero(&icmph, sizeof (icmph_t));
3734 	icmph.icmph_type = ICMP_REDIRECT;
3735 	icmph.icmph_code = 1;
3736 	icmph.icmph_rd_gateway = gateway;
3737 	BUMP_MIB(&icmp_mib, icmpOutRedirects);
3738 	/* Redirects sent by router, and router is global zone */
3739 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID);
3740 }
3741 
3742 /*
3743  * Generate an ICMP time exceeded message.
3744  */
3745 void
3746 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3747 {
3748 	icmph_t	icmph;
3749 	boolean_t mctl_present;
3750 	mblk_t *first_mp;
3751 
3752 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3753 
3754 	if (!(mp = icmp_pkt_err_ok(mp))) {
3755 		if (mctl_present)
3756 			freeb(first_mp);
3757 		return;
3758 	}
3759 
3760 	bzero(&icmph, sizeof (icmph_t));
3761 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3762 	icmph.icmph_code = code;
3763 	BUMP_MIB(&icmp_mib, icmpOutTimeExcds);
3764 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
3765 }
3766 
3767 /*
3768  * Generate an ICMP unreachable message.
3769  */
3770 void
3771 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid)
3772 {
3773 	icmph_t	icmph;
3774 	mblk_t *first_mp;
3775 	boolean_t mctl_present;
3776 
3777 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3778 
3779 	if (!(mp = icmp_pkt_err_ok(mp))) {
3780 		if (mctl_present)
3781 			freeb(first_mp);
3782 		return;
3783 	}
3784 
3785 	bzero(&icmph, sizeof (icmph_t));
3786 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3787 	icmph.icmph_code = code;
3788 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
3789 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3790 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3791 	    zoneid);
3792 }
3793 
3794 /*
3795  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3796  * duplicate.  As long as someone else holds the address, the interface will
3797  * stay down.  When that conflict goes away, the interface is brought back up.
3798  * This is done so that accidental shutdowns of addresses aren't made
3799  * permanent.  Your server will recover from a failure.
3800  *
3801  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3802  * user space process (dhcpagent).
3803  *
3804  * Recovery completes if ARP reports that the address is now ours (via
3805  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3806  *
3807  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3808  */
3809 static void
3810 ipif_dup_recovery(void *arg)
3811 {
3812 	ipif_t *ipif = arg;
3813 	ill_t *ill = ipif->ipif_ill;
3814 	mblk_t *arp_add_mp;
3815 	mblk_t *arp_del_mp;
3816 	area_t *area;
3817 
3818 	ipif->ipif_recovery_id = 0;
3819 
3820 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3821 	    (ipif->ipif_flags & IPIF_POINTOPOINT)) {
3822 		/* No reason to try to bring this address back. */
3823 		return;
3824 	}
3825 
3826 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3827 		goto alloc_fail;
3828 
3829 	if (ipif->ipif_arp_del_mp == NULL) {
3830 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3831 			goto alloc_fail;
3832 		ipif->ipif_arp_del_mp = arp_del_mp;
3833 	}
3834 
3835 	/* Setting the 'unverified' flag restarts DAD */
3836 	area = (area_t *)arp_add_mp->b_rptr;
3837 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3838 	    ACE_F_UNVERIFIED;
3839 	putnext(ill->ill_rq, arp_add_mp);
3840 	return;
3841 
3842 alloc_fail:
3843 	/* On allocation failure, just restart the timer */
3844 	freemsg(arp_add_mp);
3845 	if (ip_dup_recovery > 0) {
3846 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3847 		    MSEC_TO_TICK(ip_dup_recovery));
3848 	}
3849 }
3850 
3851 /*
3852  * This is for exclusive changes due to ARP.  Either tear down an interface due
3853  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3854  */
3855 /* ARGSUSED */
3856 static void
3857 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3858 {
3859 	ill_t	*ill = rq->q_ptr;
3860 	arh_t *arh;
3861 	ipaddr_t src;
3862 	ipif_t	*ipif;
3863 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3864 	char hbuf[MAC_STR_LEN];
3865 	char sbuf[INET_ADDRSTRLEN];
3866 	const char *failtype;
3867 	boolean_t bring_up;
3868 
3869 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3870 	case AR_CN_READY:
3871 		failtype = NULL;
3872 		bring_up = B_TRUE;
3873 		break;
3874 	case AR_CN_FAILED:
3875 		failtype = "in use";
3876 		bring_up = B_FALSE;
3877 		break;
3878 	default:
3879 		failtype = "claimed";
3880 		bring_up = B_FALSE;
3881 		break;
3882 	}
3883 
3884 	arh = (arh_t *)mp->b_cont->b_rptr;
3885 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3886 
3887 	/* Handle failures due to probes */
3888 	if (src == 0) {
3889 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3890 		    IP_ADDR_LEN);
3891 	}
3892 
3893 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3894 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3895 	    sizeof (hbuf));
3896 	(void) ip_dot_addr(src, sbuf);
3897 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3898 
3899 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3900 		    ipif->ipif_lcl_addr != src) {
3901 			continue;
3902 		}
3903 
3904 		/*
3905 		 * If we failed on a recovery probe, then restart the timer to
3906 		 * try again later.
3907 		 */
3908 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3909 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3910 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3911 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3912 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3913 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3914 			continue;
3915 		}
3916 
3917 		/*
3918 		 * If what we're trying to do has already been done, then do
3919 		 * nothing.
3920 		 */
3921 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3922 			continue;
3923 
3924 		if (ipif->ipif_id != 0) {
3925 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3926 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3927 			    ipif->ipif_id);
3928 		}
3929 		if (failtype == NULL) {
3930 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3931 			    ibuf);
3932 		} else {
3933 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3934 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3935 		}
3936 
3937 		if (bring_up) {
3938 			ASSERT(ill->ill_dl_up);
3939 			/*
3940 			 * Free up the ARP delete message so we can allocate
3941 			 * a fresh one through the normal path.
3942 			 */
3943 			freemsg(ipif->ipif_arp_del_mp);
3944 			ipif->ipif_arp_del_mp = NULL;
3945 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3946 			    EINPROGRESS) {
3947 				ipif->ipif_addr_ready = 1;
3948 				(void) ipif_up_done(ipif);
3949 			}
3950 			continue;
3951 		}
3952 
3953 		mutex_enter(&ill->ill_lock);
3954 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3955 		ipif->ipif_flags |= IPIF_DUPLICATE;
3956 		ill->ill_ipif_dup_count++;
3957 		mutex_exit(&ill->ill_lock);
3958 		/*
3959 		 * Already exclusive on the ill; no need to handle deferred
3960 		 * processing here.
3961 		 */
3962 		(void) ipif_down(ipif, NULL, NULL);
3963 		ipif_down_tail(ipif);
3964 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3965 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3966 		    ip_dup_recovery > 0) {
3967 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3968 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3969 		}
3970 	}
3971 	freemsg(mp);
3972 }
3973 
3974 /* ARGSUSED */
3975 static void
3976 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3977 {
3978 	ill_t	*ill = rq->q_ptr;
3979 	arh_t *arh;
3980 	ipaddr_t src;
3981 	ipif_t	*ipif;
3982 
3983 	arh = (arh_t *)mp->b_cont->b_rptr;
3984 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3985 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3986 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3987 			(void) ipif_resolver_up(ipif, Res_act_defend);
3988 	}
3989 	freemsg(mp);
3990 }
3991 
3992 /*
3993  * News from ARP.  ARP sends notification of interesting events down
3994  * to its clients using M_CTL messages with the interesting ARP packet
3995  * attached via b_cont.
3996  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3997  * queue as opposed to ARP sending the message to all the clients, i.e. all
3998  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3999  * table if a cache IRE is found to delete all the entries for the address in
4000  * the packet.
4001  */
4002 static void
4003 ip_arp_news(queue_t *q, mblk_t *mp)
4004 {
4005 	arcn_t		*arcn;
4006 	arh_t		*arh;
4007 	ire_t		*ire = NULL;
4008 	char		hbuf[MAC_STR_LEN];
4009 	char		sbuf[INET_ADDRSTRLEN];
4010 	ipaddr_t	src;
4011 	in6_addr_t	v6src;
4012 	boolean_t	isv6 = B_FALSE;
4013 	ipif_t		*ipif;
4014 	ill_t		*ill;
4015 
4016 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4017 		if (q->q_next) {
4018 			putnext(q, mp);
4019 		} else
4020 			freemsg(mp);
4021 		return;
4022 	}
4023 	arh = (arh_t *)mp->b_cont->b_rptr;
4024 	/* Is it one we are interested in? */
4025 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4026 		isv6 = B_TRUE;
4027 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4028 		    IPV6_ADDR_LEN);
4029 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4030 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4031 		    IP_ADDR_LEN);
4032 	} else {
4033 		freemsg(mp);
4034 		return;
4035 	}
4036 
4037 	ill = q->q_ptr;
4038 
4039 	arcn = (arcn_t *)mp->b_rptr;
4040 	switch (arcn->arcn_code) {
4041 	case AR_CN_BOGON:
4042 		/*
4043 		 * Someone is sending ARP packets with a source protocol
4044 		 * address that we have published and for which we believe our
4045 		 * entry is authoritative and (when ill_arp_extend is set)
4046 		 * verified to be unique on the network.
4047 		 *
4048 		 * The ARP module internally handles the cases where the sender
4049 		 * is just probing (for DAD) and where the hardware address of
4050 		 * a non-authoritative entry has changed.  Thus, these are the
4051 		 * real conflicts, and we have to do resolution.
4052 		 *
4053 		 * We back away quickly from the address if it's from DHCP or
4054 		 * otherwise temporary and hasn't been used recently (or at
4055 		 * all).  We'd like to include "deprecated" addresses here as
4056 		 * well (as there's no real reason to defend something we're
4057 		 * discarding), but IPMP "reuses" this flag to mean something
4058 		 * other than the standard meaning.
4059 		 *
4060 		 * If the ARP module above is not extended (meaning that it
4061 		 * doesn't know how to defend the address), then we just log
4062 		 * the problem as we always did and continue on.  It's not
4063 		 * right, but there's little else we can do, and those old ATM
4064 		 * users are going away anyway.
4065 		 */
4066 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4067 		    hbuf, sizeof (hbuf));
4068 		(void) ip_dot_addr(src, sbuf);
4069 		if (isv6)
4070 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4071 		else
4072 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4073 
4074 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4075 			uint32_t now;
4076 			uint32_t maxage;
4077 			clock_t lused;
4078 			uint_t maxdefense;
4079 			uint_t defs;
4080 
4081 			/*
4082 			 * First, figure out if this address hasn't been used
4083 			 * in a while.  If it hasn't, then it's a better
4084 			 * candidate for abandoning.
4085 			 */
4086 			ipif = ire->ire_ipif;
4087 			ASSERT(ipif != NULL);
4088 			now = gethrestime_sec();
4089 			maxage = now - ire->ire_create_time;
4090 			if (maxage > ip_max_temp_idle)
4091 				maxage = ip_max_temp_idle;
4092 			lused = drv_hztousec(ddi_get_lbolt() -
4093 			    ire->ire_last_used_time) / MICROSEC + 1;
4094 			if (lused >= maxage && (ipif->ipif_flags &
4095 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4096 				maxdefense = ip_max_temp_defend;
4097 			else
4098 				maxdefense = ip_max_defend;
4099 
4100 			/*
4101 			 * Now figure out how many times we've defended
4102 			 * ourselves.  Ignore defenses that happened long in
4103 			 * the past.
4104 			 */
4105 			mutex_enter(&ire->ire_lock);
4106 			if ((defs = ire->ire_defense_count) > 0 &&
4107 			    now - ire->ire_defense_time > ip_defend_interval) {
4108 				ire->ire_defense_count = defs = 0;
4109 			}
4110 			ire->ire_defense_count++;
4111 			ire->ire_defense_time = now;
4112 			mutex_exit(&ire->ire_lock);
4113 			ill_refhold(ill);
4114 			ire_refrele(ire);
4115 
4116 			/*
4117 			 * If we've defended ourselves too many times already,
4118 			 * then give up and tear down the interface(s) using
4119 			 * this address.  Otherwise, defend by sending out a
4120 			 * gratuitous ARP.
4121 			 */
4122 			if (defs >= maxdefense && ill->ill_arp_extend) {
4123 				(void) qwriter_ip(NULL, ill, q, mp,
4124 				    ip_arp_excl, CUR_OP, B_FALSE);
4125 			} else {
4126 				cmn_err(CE_WARN,
4127 				    "node %s is using our IP address %s on %s",
4128 				    hbuf, sbuf, ill->ill_name);
4129 				/*
4130 				 * If this is an old (ATM) ARP module, then
4131 				 * don't try to defend the address.  Remain
4132 				 * compatible with the old behavior.  Defend
4133 				 * only with new ARP.
4134 				 */
4135 				if (ill->ill_arp_extend) {
4136 					(void) qwriter_ip(NULL, ill, q, mp,
4137 					    ip_arp_defend, CUR_OP, B_FALSE);
4138 				} else {
4139 					ill_refrele(ill);
4140 				}
4141 			}
4142 			return;
4143 		}
4144 		cmn_err(CE_WARN,
4145 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4146 		    hbuf, sbuf, ill->ill_name);
4147 		if (ire != NULL)
4148 			ire_refrele(ire);
4149 		break;
4150 	case AR_CN_ANNOUNCE:
4151 		if (isv6) {
4152 			/*
4153 			 * For XRESOLV interfaces.
4154 			 * Delete the IRE cache entry and NCE for this
4155 			 * v6 address
4156 			 */
4157 			ip_ire_clookup_and_delete_v6(&v6src);
4158 			/*
4159 			 * If v6src is a non-zero, it's a router address
4160 			 * as below. Do the same sort of thing to clean
4161 			 * out off-net IRE_CACHE entries that go through
4162 			 * the router.
4163 			 */
4164 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4165 				ire_walk_v6(ire_delete_cache_gw_v6,
4166 				    (char *)&v6src, ALL_ZONES);
4167 			}
4168 		} else {
4169 			nce_hw_map_t hwm;
4170 
4171 			/*
4172 			 * ARP gives us a copy of any packet where it thinks
4173 			 * the address has changed, so that we can update our
4174 			 * caches.  We're responsible for caching known answers
4175 			 * in the current design.  We check whether the
4176 			 * hardware address really has changed in all of our
4177 			 * entries that have cached this mapping, and if so, we
4178 			 * blow them away.  This way we will immediately pick
4179 			 * up the rare case of a host changing hardware
4180 			 * address.
4181 			 */
4182 			if (src == 0)
4183 				break;
4184 			hwm.hwm_addr = src;
4185 			hwm.hwm_hwlen = arh->arh_hlen;
4186 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4187 			ndp_walk_common(&ndp4, NULL,
4188 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4189 		}
4190 		break;
4191 	case AR_CN_READY:
4192 		/* No external v6 resolver has a contract to use this */
4193 		if (isv6)
4194 			break;
4195 		/* If the link is down, we'll retry this later */
4196 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4197 			break;
4198 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4199 		    NULL, NULL);
4200 		if (ipif != NULL) {
4201 			/*
4202 			 * If this is a duplicate recovery, then we now need to
4203 			 * go exclusive to bring this thing back up.
4204 			 */
4205 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4206 			    IPIF_DUPLICATE) {
4207 				ipif_refrele(ipif);
4208 				ill_refhold(ill);
4209 				(void) qwriter_ip(NULL, ill, q, mp,
4210 				    ip_arp_excl, CUR_OP, B_FALSE);
4211 				return;
4212 			}
4213 			/*
4214 			 * If this is the first notice that this address is
4215 			 * ready, then let the user know now.
4216 			 */
4217 			if ((ipif->ipif_flags & IPIF_UP) &&
4218 			    !ipif->ipif_addr_ready) {
4219 				ipif_mask_reply(ipif);
4220 				ip_rts_ifmsg(ipif);
4221 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4222 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4223 			}
4224 			ipif->ipif_addr_ready = 1;
4225 			ipif_refrele(ipif);
4226 		}
4227 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4228 		if (ire != NULL) {
4229 			ire->ire_defense_count = 0;
4230 			ire_refrele(ire);
4231 		}
4232 		break;
4233 	case AR_CN_FAILED:
4234 		/* No external v6 resolver has a contract to use this */
4235 		if (isv6)
4236 			break;
4237 		ill_refhold(ill);
4238 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4239 		    B_FALSE);
4240 		return;
4241 	}
4242 	freemsg(mp);
4243 }
4244 
4245 /*
4246  * Create a mblk suitable for carrying the interface index and/or source link
4247  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4248  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4249  * application.
4250  */
4251 mblk_t *
4252 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags)
4253 {
4254 	mblk_t		*mp;
4255 	in_pktinfo_t	*pinfo;
4256 	ipha_t *ipha;
4257 	struct ether_header *pether;
4258 
4259 	mp = allocb(sizeof (in_pktinfo_t), BPRI_MED);
4260 	if (mp == NULL) {
4261 		ip1dbg(("ip_add_info: allocation failure.\n"));
4262 		return (data_mp);
4263 	}
4264 
4265 	ipha	= (ipha_t *)data_mp->b_rptr;
4266 	pinfo = (in_pktinfo_t *)mp->b_rptr;
4267 	bzero(pinfo, sizeof (in_pktinfo_t));
4268 	pinfo->in_pkt_flags = (uchar_t)flags;
4269 	pinfo->in_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4270 
4271 	if (flags & IPF_RECVIF)
4272 		pinfo->in_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4273 
4274 	pether = (struct ether_header *)((char *)ipha
4275 	    - sizeof (struct ether_header));
4276 	/*
4277 	 * Make sure the interface is an ethernet type, since this option
4278 	 * is currently supported only on this type of interface. Also make
4279 	 * sure we are pointing correctly above db_base.
4280 	 */
4281 
4282 	if ((flags & IPF_RECVSLLA) &&
4283 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4284 	    (ill->ill_type == IFT_ETHER) &&
4285 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4286 
4287 		pinfo->in_pkt_slla.sdl_type = IFT_ETHER;
4288 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4289 		    (uchar_t *)pinfo->in_pkt_slla.sdl_data, ETHERADDRL);
4290 	} else {
4291 		/*
4292 		 * Clear the bit. Indicate to upper layer that IP is not
4293 		 * sending this ancillary info.
4294 		 */
4295 		pinfo->in_pkt_flags = pinfo->in_pkt_flags & ~IPF_RECVSLLA;
4296 	}
4297 
4298 	mp->b_datap->db_type = M_CTL;
4299 	mp->b_wptr += sizeof (in_pktinfo_t);
4300 	mp->b_cont = data_mp;
4301 
4302 	return (mp);
4303 }
4304 
4305 /*
4306  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4307  * part of the bind request.
4308  */
4309 
4310 boolean_t
4311 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4312 {
4313 	ipsec_in_t *ii;
4314 
4315 	ASSERT(policy_mp != NULL);
4316 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4317 
4318 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4319 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4320 
4321 	connp->conn_policy = ii->ipsec_in_policy;
4322 	ii->ipsec_in_policy = NULL;
4323 
4324 	if (ii->ipsec_in_action != NULL) {
4325 		if (connp->conn_latch == NULL) {
4326 			connp->conn_latch = iplatch_create();
4327 			if (connp->conn_latch == NULL)
4328 				return (B_FALSE);
4329 		}
4330 		ipsec_latch_inbound(connp->conn_latch, ii);
4331 	}
4332 	return (B_TRUE);
4333 }
4334 
4335 /*
4336  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4337  * and to arrange for power-fanout assist.  The ULP is identified by
4338  * adding a single byte at the end of the original bind message.
4339  * A ULP other than UDP or TCP that wishes to be recognized passes
4340  * down a bind with a zero length address.
4341  *
4342  * The binding works as follows:
4343  * - A zero byte address means just bind to the protocol.
4344  * - A four byte address is treated as a request to validate
4345  *   that the address is a valid local address, appropriate for
4346  *   an application to bind to. This does not affect any fanout
4347  *   information in IP.
4348  * - A sizeof sin_t byte address is used to bind to only the local address
4349  *   and port.
4350  * - A sizeof ipa_conn_t byte address contains complete fanout information
4351  *   consisting of local and remote addresses and ports.  In
4352  *   this case, the addresses are both validated as appropriate
4353  *   for this operation, and, if so, the information is retained
4354  *   for use in the inbound fanout.
4355  *
4356  * The ULP (except in the zero-length bind) can append an
4357  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4358  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4359  * a copy of the source or destination IRE (source for local bind;
4360  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4361  * policy information contained should be copied on to the conn.
4362  *
4363  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4364  */
4365 mblk_t *
4366 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4367 {
4368 	ssize_t		len;
4369 	struct T_bind_req	*tbr;
4370 	sin_t		*sin;
4371 	ipa_conn_t	*ac;
4372 	uchar_t		*ucp;
4373 	mblk_t		*mp1;
4374 	boolean_t	ire_requested;
4375 	boolean_t	ipsec_policy_set = B_FALSE;
4376 	int		error = 0;
4377 	int		protocol;
4378 	ipa_conn_x_t	*acx;
4379 
4380 	ASSERT(!connp->conn_af_isv6);
4381 	connp->conn_pkt_isv6 = B_FALSE;
4382 
4383 	len = MBLKL(mp);
4384 	if (len < (sizeof (*tbr) + 1)) {
4385 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4386 		    "ip_bind: bogus msg, len %ld", len);
4387 		/* XXX: Need to return something better */
4388 		goto bad_addr;
4389 	}
4390 	/* Back up and extract the protocol identifier. */
4391 	mp->b_wptr--;
4392 	protocol = *mp->b_wptr & 0xFF;
4393 	tbr = (struct T_bind_req *)mp->b_rptr;
4394 	/* Reset the message type in preparation for shipping it back. */
4395 	DB_TYPE(mp) = M_PCPROTO;
4396 
4397 	connp->conn_ulp = (uint8_t)protocol;
4398 
4399 	/*
4400 	 * Check for a zero length address.  This is from a protocol that
4401 	 * wants to register to receive all packets of its type.
4402 	 */
4403 	if (tbr->ADDR_length == 0) {
4404 		/*
4405 		 * These protocols are now intercepted in ip_bind_v6().
4406 		 * Reject protocol-level binds here for now.
4407 		 *
4408 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4409 		 * so that the protocol type cannot be SCTP.
4410 		 */
4411 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4412 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4413 			goto bad_addr;
4414 		}
4415 
4416 		/*
4417 		 *
4418 		 * The udp module never sends down a zero-length address,
4419 		 * and allowing this on a labeled system will break MLP
4420 		 * functionality.
4421 		 */
4422 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4423 			goto bad_addr;
4424 
4425 		if (connp->conn_mac_exempt)
4426 			goto bad_addr;
4427 
4428 		/* No hash here really.  The table is big enough. */
4429 		connp->conn_srcv6 = ipv6_all_zeros;
4430 
4431 		ipcl_proto_insert(connp, protocol);
4432 
4433 		tbr->PRIM_type = T_BIND_ACK;
4434 		return (mp);
4435 	}
4436 
4437 	/* Extract the address pointer from the message. */
4438 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4439 	    tbr->ADDR_length);
4440 	if (ucp == NULL) {
4441 		ip1dbg(("ip_bind: no address\n"));
4442 		goto bad_addr;
4443 	}
4444 	if (!OK_32PTR(ucp)) {
4445 		ip1dbg(("ip_bind: unaligned address\n"));
4446 		goto bad_addr;
4447 	}
4448 	/*
4449 	 * Check for trailing mps.
4450 	 */
4451 
4452 	mp1 = mp->b_cont;
4453 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4454 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4455 
4456 	switch (tbr->ADDR_length) {
4457 	default:
4458 		ip1dbg(("ip_bind: bad address length %d\n",
4459 		    (int)tbr->ADDR_length));
4460 		goto bad_addr;
4461 
4462 	case IP_ADDR_LEN:
4463 		/* Verification of local address only */
4464 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4465 		    ire_requested, ipsec_policy_set, B_FALSE);
4466 		break;
4467 
4468 	case sizeof (sin_t):
4469 		sin = (sin_t *)ucp;
4470 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4471 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4472 		if (protocol == IPPROTO_TCP)
4473 			connp->conn_recv = tcp_conn_request;
4474 		break;
4475 
4476 	case sizeof (ipa_conn_t):
4477 		ac = (ipa_conn_t *)ucp;
4478 		/* For raw socket, the local port is not set. */
4479 		if (ac->ac_lport == 0)
4480 			ac->ac_lport = connp->conn_lport;
4481 		/* Always verify destination reachability. */
4482 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4483 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4484 		    ipsec_policy_set, B_TRUE, B_TRUE);
4485 		if (protocol == IPPROTO_TCP)
4486 			connp->conn_recv = tcp_input;
4487 		break;
4488 
4489 	case sizeof (ipa_conn_x_t):
4490 		acx = (ipa_conn_x_t *)ucp;
4491 		/*
4492 		 * Whether or not to verify destination reachability depends
4493 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4494 		 */
4495 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4496 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4497 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4498 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4499 		if (protocol == IPPROTO_TCP)
4500 			connp->conn_recv = tcp_input;
4501 		break;
4502 	}
4503 	if (error == EINPROGRESS)
4504 		return (NULL);
4505 	else if (error != 0)
4506 		goto bad_addr;
4507 	/*
4508 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4509 	 * We can't do this in ip_bind_insert_ire because the policy
4510 	 * may not have been inherited at that point in time and hence
4511 	 * conn_out_enforce_policy may not be set.
4512 	 */
4513 	mp1 = mp->b_cont;
4514 	if (ire_requested && connp->conn_out_enforce_policy &&
4515 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4516 		ire_t *ire = (ire_t *)mp1->b_rptr;
4517 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4518 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4519 	}
4520 
4521 	/* Send it home. */
4522 	mp->b_datap->db_type = M_PCPROTO;
4523 	tbr->PRIM_type = T_BIND_ACK;
4524 	return (mp);
4525 
4526 bad_addr:
4527 	/*
4528 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4529 	 * a unix errno.
4530 	 */
4531 	if (error > 0)
4532 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4533 	else
4534 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4535 	return (mp);
4536 }
4537 
4538 /*
4539  * Here address is verified to be a valid local address.
4540  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4541  * address is also considered a valid local address.
4542  * In the case of a broadcast/multicast address, however, the
4543  * upper protocol is expected to reset the src address
4544  * to 0 if it sees a IRE_BROADCAST type returned so that
4545  * no packets are emitted with broadcast/multicast address as
4546  * source address (that violates hosts requirements RFC1122)
4547  * The addresses valid for bind are:
4548  *	(1) - INADDR_ANY (0)
4549  *	(2) - IP address of an UP interface
4550  *	(3) - IP address of a DOWN interface
4551  *	(4) - valid local IP broadcast addresses. In this case
4552  *	the conn will only receive packets destined to
4553  *	the specified broadcast address.
4554  *	(5) - a multicast address. In this case
4555  *	the conn will only receive packets destined to
4556  *	the specified multicast address. Note: the
4557  *	application still has to issue an
4558  *	IP_ADD_MEMBERSHIP socket option.
4559  *
4560  * On error, return -1 for TBADADDR otherwise pass the
4561  * errno with TSYSERR reply.
4562  *
4563  * In all the above cases, the bound address must be valid in the current zone.
4564  * When the address is loopback, multicast or broadcast, there might be many
4565  * matching IREs so bind has to look up based on the zone.
4566  *
4567  * Note: lport is in network byte order.
4568  */
4569 int
4570 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4571     boolean_t ire_requested, boolean_t ipsec_policy_set,
4572     boolean_t fanout_insert)
4573 {
4574 	int		error = 0;
4575 	ire_t		*src_ire;
4576 	mblk_t		*policy_mp;
4577 	ipif_t		*ipif;
4578 	zoneid_t	zoneid;
4579 
4580 	if (ipsec_policy_set) {
4581 		policy_mp = mp->b_cont;
4582 	}
4583 
4584 	/*
4585 	 * If it was previously connected, conn_fully_bound would have
4586 	 * been set.
4587 	 */
4588 	connp->conn_fully_bound = B_FALSE;
4589 
4590 	src_ire = NULL;
4591 	ipif = NULL;
4592 
4593 	zoneid = IPCL_ZONEID(connp);
4594 
4595 	if (src_addr) {
4596 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4597 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4598 		/*
4599 		 * If an address other than 0.0.0.0 is requested,
4600 		 * we verify that it is a valid address for bind
4601 		 * Note: Following code is in if-else-if form for
4602 		 * readability compared to a condition check.
4603 		 */
4604 		/* LINTED - statement has no consequent */
4605 		if (IRE_IS_LOCAL(src_ire)) {
4606 			/*
4607 			 * (2) Bind to address of local UP interface
4608 			 */
4609 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4610 			/*
4611 			 * (4) Bind to broadcast address
4612 			 * Note: permitted only from transports that
4613 			 * request IRE
4614 			 */
4615 			if (!ire_requested)
4616 				error = EADDRNOTAVAIL;
4617 		} else {
4618 			/*
4619 			 * (3) Bind to address of local DOWN interface
4620 			 * (ipif_lookup_addr() looks up all interfaces
4621 			 * but we do not get here for UP interfaces
4622 			 * - case (2) above)
4623 			 * We put the protocol byte back into the mblk
4624 			 * since we may come back via ip_wput_nondata()
4625 			 * later with this mblk if ipif_lookup_addr chooses
4626 			 * to defer processing.
4627 			 */
4628 			*mp->b_wptr++ = (char)connp->conn_ulp;
4629 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4630 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4631 			    &error)) != NULL) {
4632 				ipif_refrele(ipif);
4633 			} else if (error == EINPROGRESS) {
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				return (EINPROGRESS);
4637 			} else if (CLASSD(src_addr)) {
4638 				error = 0;
4639 				if (src_ire != NULL)
4640 					ire_refrele(src_ire);
4641 				/*
4642 				 * (5) bind to multicast address.
4643 				 * Fake out the IRE returned to upper
4644 				 * layer to be a broadcast IRE.
4645 				 */
4646 				src_ire = ire_ctable_lookup(
4647 				    INADDR_BROADCAST, INADDR_ANY,
4648 				    IRE_BROADCAST, NULL, zoneid, NULL,
4649 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4650 				if (src_ire == NULL || !ire_requested)
4651 					error = EADDRNOTAVAIL;
4652 			} else {
4653 				/*
4654 				 * Not a valid address for bind
4655 				 */
4656 				error = EADDRNOTAVAIL;
4657 			}
4658 			/*
4659 			 * Just to keep it consistent with the processing in
4660 			 * ip_bind_v4()
4661 			 */
4662 			mp->b_wptr--;
4663 		}
4664 		if (error) {
4665 			/* Red Alert!  Attempting to be a bogon! */
4666 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4667 			    ntohl(src_addr)));
4668 			goto bad_addr;
4669 		}
4670 	}
4671 
4672 	/*
4673 	 * Allow setting new policies. For example, disconnects come
4674 	 * down as ipa_t bind. As we would have set conn_policy_cached
4675 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4676 	 * can change after the disconnect.
4677 	 */
4678 	connp->conn_policy_cached = B_FALSE;
4679 
4680 	/*
4681 	 * If not fanout_insert this was just an address verification
4682 	 */
4683 	if (fanout_insert) {
4684 		/*
4685 		 * The addresses have been verified. Time to insert in
4686 		 * the correct fanout list.
4687 		 */
4688 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4689 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4690 		connp->conn_lport = lport;
4691 		connp->conn_fport = 0;
4692 		/*
4693 		 * Do we need to add a check to reject Multicast packets
4694 		 */
4695 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4696 	}
4697 
4698 	if (error == 0) {
4699 		if (ire_requested) {
4700 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4701 				error = -1;
4702 				/* Falls through to bad_addr */
4703 			}
4704 		} else if (ipsec_policy_set) {
4705 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4706 				error = -1;
4707 				/* Falls through to bad_addr */
4708 			}
4709 		}
4710 	}
4711 bad_addr:
4712 	if (error != 0) {
4713 		if (connp->conn_anon_port) {
4714 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4715 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4716 			    B_FALSE);
4717 		}
4718 		connp->conn_mlp_type = mlptSingle;
4719 	}
4720 	if (src_ire != NULL)
4721 		IRE_REFRELE(src_ire);
4722 	if (ipsec_policy_set) {
4723 		ASSERT(policy_mp == mp->b_cont);
4724 		ASSERT(policy_mp != NULL);
4725 		freeb(policy_mp);
4726 		/*
4727 		 * As of now assume that nothing else accompanies
4728 		 * IPSEC_POLICY_SET.
4729 		 */
4730 		mp->b_cont = NULL;
4731 	}
4732 	return (error);
4733 }
4734 
4735 /*
4736  * Verify that both the source and destination addresses
4737  * are valid.  If verify_dst is false, then the destination address may be
4738  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4739  * destination reachability, while tunnels do not.
4740  * Note that we allow connect to broadcast and multicast
4741  * addresses when ire_requested is set. Thus the ULP
4742  * has to check for IRE_BROADCAST and multicast.
4743  *
4744  * Returns zero if ok.
4745  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4746  * (for use with TSYSERR reply).
4747  *
4748  * Note: lport and fport are in network byte order.
4749  */
4750 int
4751 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4752     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4753     boolean_t ire_requested, boolean_t ipsec_policy_set,
4754     boolean_t fanout_insert, boolean_t verify_dst)
4755 {
4756 	ire_t		*src_ire;
4757 	ire_t		*dst_ire;
4758 	int		error = 0;
4759 	int 		protocol;
4760 	mblk_t		*policy_mp;
4761 	ire_t		*sire = NULL;
4762 	ire_t		*md_dst_ire = NULL;
4763 	ill_t		*md_ill = NULL;
4764 	zoneid_t	zoneid;
4765 	ipaddr_t	src_addr = *src_addrp;
4766 
4767 	src_ire = dst_ire = NULL;
4768 	protocol = *mp->b_wptr & 0xFF;
4769 
4770 	/*
4771 	 * If we never got a disconnect before, clear it now.
4772 	 */
4773 	connp->conn_fully_bound = B_FALSE;
4774 
4775 	if (ipsec_policy_set) {
4776 		policy_mp = mp->b_cont;
4777 	}
4778 
4779 	zoneid = IPCL_ZONEID(connp);
4780 
4781 	if (CLASSD(dst_addr)) {
4782 		/* Pick up an IRE_BROADCAST */
4783 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4784 		    NULL, zoneid, MBLK_GETLABEL(mp),
4785 		    (MATCH_IRE_RECURSIVE |
4786 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4787 		    MATCH_IRE_SECATTR));
4788 	} else {
4789 		/*
4790 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4791 		 * and onlink ipif is not found set ENETUNREACH error.
4792 		 */
4793 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4794 			ipif_t *ipif;
4795 
4796 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4797 			    dst_addr : connp->conn_nexthop_v4,
4798 			    connp->conn_zoneid);
4799 			if (ipif == NULL) {
4800 				error = ENETUNREACH;
4801 				goto bad_addr;
4802 			}
4803 			ipif_refrele(ipif);
4804 		}
4805 
4806 		if (connp->conn_nexthop_set) {
4807 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4808 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4809 			    MATCH_IRE_SECATTR);
4810 		} else {
4811 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4812 			    &sire, zoneid, MBLK_GETLABEL(mp),
4813 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4814 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4815 			    MATCH_IRE_SECATTR));
4816 		}
4817 	}
4818 	/*
4819 	 * dst_ire can't be a broadcast when not ire_requested.
4820 	 * We also prevent ire's with src address INADDR_ANY to
4821 	 * be used, which are created temporarily for
4822 	 * sending out packets from endpoints that have
4823 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4824 	 * reachable.  If verify_dst is false, the destination needn't be
4825 	 * reachable.
4826 	 *
4827 	 * If we match on a reject or black hole, then we've got a
4828 	 * local failure.  May as well fail out the connect() attempt,
4829 	 * since it's never going to succeed.
4830 	 */
4831 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4832 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4833 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4834 		/*
4835 		 * If we're verifying destination reachability, we always want
4836 		 * to complain here.
4837 		 *
4838 		 * If we're not verifying destination reachability but the
4839 		 * destination has a route, we still want to fail on the
4840 		 * temporary address and broadcast address tests.
4841 		 */
4842 		if (verify_dst || (dst_ire != NULL)) {
4843 			if (ip_debug > 2) {
4844 				pr_addr_dbg("ip_bind_connected: bad connected "
4845 				    "dst %s\n", AF_INET, &dst_addr);
4846 			}
4847 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4848 				error = ENETUNREACH;
4849 			else
4850 				error = EHOSTUNREACH;
4851 			goto bad_addr;
4852 		}
4853 	}
4854 
4855 	/*
4856 	 * We now know that routing will allow us to reach the destination.
4857 	 * Check whether Trusted Solaris policy allows communication with this
4858 	 * host, and pretend that the destination is unreachable if not.
4859 	 *
4860 	 * This is never a problem for TCP, since that transport is known to
4861 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4862 	 * handling.  If the remote is unreachable, it will be detected at that
4863 	 * point, so there's no reason to check it here.
4864 	 *
4865 	 * Note that for sendto (and other datagram-oriented friends), this
4866 	 * check is done as part of the data path label computation instead.
4867 	 * The check here is just to make non-TCP connect() report the right
4868 	 * error.
4869 	 */
4870 	if (dst_ire != NULL && is_system_labeled() &&
4871 	    !IPCL_IS_TCP(connp) &&
4872 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4873 	    connp->conn_mac_exempt) != 0) {
4874 		error = EHOSTUNREACH;
4875 		if (ip_debug > 2) {
4876 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4877 			    AF_INET, &dst_addr);
4878 		}
4879 		goto bad_addr;
4880 	}
4881 
4882 	/*
4883 	 * If the app does a connect(), it means that it will most likely
4884 	 * send more than 1 packet to the destination.  It makes sense
4885 	 * to clear the temporary flag.
4886 	 */
4887 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4888 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4889 		irb_t *irb = dst_ire->ire_bucket;
4890 
4891 		rw_enter(&irb->irb_lock, RW_WRITER);
4892 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4893 		irb->irb_tmp_ire_cnt--;
4894 		rw_exit(&irb->irb_lock);
4895 	}
4896 
4897 	/*
4898 	 * See if we should notify ULP about MDT; we do this whether or not
4899 	 * ire_requested is TRUE, in order to handle active connects; MDT
4900 	 * eligibility tests for passive connects are handled separately
4901 	 * through tcp_adapt_ire().  We do this before the source address
4902 	 * selection, because dst_ire may change after a call to
4903 	 * ipif_select_source().  This is a best-effort check, as the
4904 	 * packet for this connection may not actually go through
4905 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4906 	 * calling ip_newroute().  This is why we further check on the
4907 	 * IRE during Multidata packet transmission in tcp_multisend().
4908 	 */
4909 	if (ip_multidata_outbound && !ipsec_policy_set && dst_ire != NULL &&
4910 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4911 	    (md_ill = ire_to_ill(dst_ire), md_ill != NULL) &&
4912 	    ILL_MDT_CAPABLE(md_ill)) {
4913 		md_dst_ire = dst_ire;
4914 		IRE_REFHOLD(md_dst_ire);
4915 	}
4916 
4917 	if (dst_ire != NULL &&
4918 	    dst_ire->ire_type == IRE_LOCAL &&
4919 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4920 		/*
4921 		 * If the IRE belongs to a different zone, look for a matching
4922 		 * route in the forwarding table and use the source address from
4923 		 * that route.
4924 		 */
4925 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4926 		    zoneid, 0, NULL,
4927 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4928 		    MATCH_IRE_RJ_BHOLE);
4929 		if (src_ire == NULL) {
4930 			error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4933 			if (!(src_ire->ire_type & IRE_HOST))
4934 				error = ENETUNREACH;
4935 			else
4936 				error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		}
4939 		if (src_addr == INADDR_ANY)
4940 			src_addr = src_ire->ire_src_addr;
4941 		ire_refrele(src_ire);
4942 		src_ire = NULL;
4943 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4944 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4945 			src_addr = sire->ire_src_addr;
4946 			ire_refrele(dst_ire);
4947 			dst_ire = sire;
4948 			sire = NULL;
4949 		} else {
4950 			/*
4951 			 * Pick a source address so that a proper inbound
4952 			 * load spreading would happen.
4953 			 */
4954 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4955 			ipif_t *src_ipif = NULL;
4956 			ire_t *ipif_ire;
4957 
4958 			/*
4959 			 * Supply a local source address such that inbound
4960 			 * load spreading happens.
4961 			 *
4962 			 * Determine the best source address on this ill for
4963 			 * the destination.
4964 			 *
4965 			 * 1) For broadcast, we should return a broadcast ire
4966 			 *    found above so that upper layers know that the
4967 			 *    destination address is a broadcast address.
4968 			 *
4969 			 * 2) If this is part of a group, select a better
4970 			 *    source address so that better inbound load
4971 			 *    balancing happens. Do the same if the ipif
4972 			 *    is DEPRECATED.
4973 			 *
4974 			 * 3) If the outgoing interface is part of a usesrc
4975 			 *    group, then try selecting a source address from
4976 			 *    the usesrc ILL.
4977 			 */
4978 			if ((dst_ire->ire_zoneid != zoneid &&
4979 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4980 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4981 			    ((dst_ill->ill_group != NULL) ||
4982 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4983 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4984 				/*
4985 				 * If the destination is reachable via a
4986 				 * given gateway, the selected source address
4987 				 * should be in the same subnet as the gateway.
4988 				 * Otherwise, the destination is not reachable.
4989 				 *
4990 				 * If there are no interfaces on the same subnet
4991 				 * as the destination, ipif_select_source gives
4992 				 * first non-deprecated interface which might be
4993 				 * on a different subnet than the gateway.
4994 				 * This is not desirable. Hence pass the dst_ire
4995 				 * source address to ipif_select_source.
4996 				 * It is sure that the destination is reachable
4997 				 * with the dst_ire source address subnet.
4998 				 * So passing dst_ire source address to
4999 				 * ipif_select_source will make sure that the
5000 				 * selected source will be on the same subnet
5001 				 * as dst_ire source address.
5002 				 */
5003 				ipaddr_t saddr =
5004 				    dst_ire->ire_ipif->ipif_src_addr;
5005 				src_ipif = ipif_select_source(dst_ill,
5006 				    saddr, zoneid);
5007 				if (src_ipif != NULL) {
5008 					if (IS_VNI(src_ipif->ipif_ill)) {
5009 						/*
5010 						 * For VNI there is no
5011 						 * interface route
5012 						 */
5013 						src_addr =
5014 						    src_ipif->ipif_src_addr;
5015 					} else {
5016 						ipif_ire =
5017 						    ipif_to_ire(src_ipif);
5018 						if (ipif_ire != NULL) {
5019 							IRE_REFRELE(dst_ire);
5020 							dst_ire = ipif_ire;
5021 						}
5022 						src_addr =
5023 						    dst_ire->ire_src_addr;
5024 					}
5025 					ipif_refrele(src_ipif);
5026 				} else {
5027 					src_addr = dst_ire->ire_src_addr;
5028 				}
5029 			} else {
5030 				src_addr = dst_ire->ire_src_addr;
5031 			}
5032 		}
5033 	}
5034 
5035 	/*
5036 	 * We do ire_route_lookup() here (and not
5037 	 * interface lookup as we assert that
5038 	 * src_addr should only come from an
5039 	 * UP interface for hard binding.
5040 	 */
5041 	ASSERT(src_ire == NULL);
5042 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5043 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5044 	/* src_ire must be a local|loopback */
5045 	if (!IRE_IS_LOCAL(src_ire)) {
5046 		if (ip_debug > 2) {
5047 			pr_addr_dbg("ip_bind_connected: bad connected "
5048 			    "src %s\n", AF_INET, &src_addr);
5049 		}
5050 		error = EADDRNOTAVAIL;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * If the source address is a loopback address, the
5056 	 * destination had best be local or multicast.
5057 	 * The transports that can't handle multicast will reject
5058 	 * those addresses.
5059 	 */
5060 	if (src_ire->ire_type == IRE_LOOPBACK &&
5061 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5062 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5063 		error = -1;
5064 		goto bad_addr;
5065 	}
5066 
5067 	/*
5068 	 * Allow setting new policies. For example, disconnects come
5069 	 * down as ipa_t bind. As we would have set conn_policy_cached
5070 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5071 	 * can change after the disconnect.
5072 	 */
5073 	connp->conn_policy_cached = B_FALSE;
5074 
5075 	/*
5076 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5077 	 * can handle their passed-in conn's.
5078 	 */
5079 
5080 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5081 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5082 	connp->conn_lport = lport;
5083 	connp->conn_fport = fport;
5084 	*src_addrp = src_addr;
5085 
5086 	ASSERT(!(ipsec_policy_set && ire_requested));
5087 	if (ire_requested) {
5088 		iulp_t *ulp_info = NULL;
5089 
5090 		/*
5091 		 * Note that sire will not be NULL if this is an off-link
5092 		 * connection and there is not cache for that dest yet.
5093 		 *
5094 		 * XXX Because of an existing bug, if there are multiple
5095 		 * default routes, the IRE returned now may not be the actual
5096 		 * default route used (default routes are chosen in a
5097 		 * round robin fashion).  So if the metrics for different
5098 		 * default routes are different, we may return the wrong
5099 		 * metrics.  This will not be a problem if the existing
5100 		 * bug is fixed.
5101 		 */
5102 		if (sire != NULL) {
5103 			ulp_info = &(sire->ire_uinfo);
5104 		}
5105 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	} else if (ipsec_policy_set) {
5110 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5111 			error = -1;
5112 			goto bad_addr;
5113 		}
5114 	}
5115 
5116 	/*
5117 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5118 	 * we'll cache that.  If we don't, we'll inherit global policy.
5119 	 *
5120 	 * We can't insert until the conn reflects the policy. Note that
5121 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5122 	 * connections where we don't have a policy. This is to prevent
5123 	 * global policy lookups in the inbound path.
5124 	 *
5125 	 * If we insert before we set conn_policy_cached,
5126 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5127 	 * because global policy cound be non-empty. We normally call
5128 	 * ipsec_check_policy() for conn_policy_cached connections only if
5129 	 * ipc_in_enforce_policy is set. But in this case,
5130 	 * conn_policy_cached can get set anytime since we made the
5131 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5132 	 * called, which will make the above assumption false.  Thus, we
5133 	 * need to insert after we set conn_policy_cached.
5134 	 */
5135 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5136 		goto bad_addr;
5137 
5138 	if (fanout_insert) {
5139 		/*
5140 		 * The addresses have been verified. Time to insert in
5141 		 * the correct fanout list.
5142 		 */
5143 		error = ipcl_conn_insert(connp, protocol, src_addr,
5144 		    dst_addr, connp->conn_ports);
5145 	}
5146 
5147 	if (error == 0) {
5148 		connp->conn_fully_bound = B_TRUE;
5149 		/*
5150 		 * Our initial checks for MDT have passed; the IRE is not
5151 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5152 		 * be supporting MDT.  Pass the IRE, IPC and ILL into
5153 		 * ip_mdinfo_return(), which performs further checks
5154 		 * against them and upon success, returns the MDT info
5155 		 * mblk which we will attach to the bind acknowledgment.
5156 		 */
5157 		if (md_dst_ire != NULL) {
5158 			mblk_t *mdinfo_mp;
5159 
5160 			ASSERT(md_ill != NULL);
5161 			ASSERT(md_ill->ill_mdt_capab != NULL);
5162 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5163 			    md_ill->ill_name, md_ill->ill_mdt_capab)) != NULL)
5164 				linkb(mp, mdinfo_mp);
5165 		}
5166 	}
5167 bad_addr:
5168 	if (ipsec_policy_set) {
5169 		ASSERT(policy_mp == mp->b_cont);
5170 		ASSERT(policy_mp != NULL);
5171 		freeb(policy_mp);
5172 		/*
5173 		 * As of now assume that nothing else accompanies
5174 		 * IPSEC_POLICY_SET.
5175 		 */
5176 		mp->b_cont = NULL;
5177 	}
5178 	if (src_ire != NULL)
5179 		IRE_REFRELE(src_ire);
5180 	if (dst_ire != NULL)
5181 		IRE_REFRELE(dst_ire);
5182 	if (sire != NULL)
5183 		IRE_REFRELE(sire);
5184 	if (md_dst_ire != NULL)
5185 		IRE_REFRELE(md_dst_ire);
5186 	return (error);
5187 }
5188 
5189 /*
5190  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5191  * Prefers dst_ire over src_ire.
5192  */
5193 static boolean_t
5194 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5195 {
5196 	mblk_t	*mp1;
5197 	ire_t *ret_ire = NULL;
5198 
5199 	mp1 = mp->b_cont;
5200 	ASSERT(mp1 != NULL);
5201 
5202 	if (ire != NULL) {
5203 		/*
5204 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5205 		 * appended mblk. Its <upper protocol>'s
5206 		 * job to make sure there is room.
5207 		 */
5208 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5209 			return (0);
5210 
5211 		mp1->b_datap->db_type = IRE_DB_TYPE;
5212 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5213 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5214 		ret_ire = (ire_t *)mp1->b_rptr;
5215 		/*
5216 		 * Pass the latest setting of the ip_path_mtu_discovery and
5217 		 * copy the ulp info if any.
5218 		 */
5219 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5220 		    IPH_DF : 0;
5221 		if (ulp_info != NULL) {
5222 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5223 			    sizeof (iulp_t));
5224 		}
5225 		ret_ire->ire_mp = mp1;
5226 	} else {
5227 		/*
5228 		 * No IRE was found. Remove IRE mblk.
5229 		 */
5230 		mp->b_cont = mp1->b_cont;
5231 		freeb(mp1);
5232 	}
5233 
5234 	return (1);
5235 }
5236 
5237 /*
5238  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5239  * the final piece where we don't.  Return a pointer to the first mblk in the
5240  * result, and update the pointer to the next mblk to chew on.  If anything
5241  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5242  * NULL pointer.
5243  */
5244 mblk_t *
5245 ip_carve_mp(mblk_t **mpp, ssize_t len)
5246 {
5247 	mblk_t	*mp0;
5248 	mblk_t	*mp1;
5249 	mblk_t	*mp2;
5250 
5251 	if (!len || !mpp || !(mp0 = *mpp))
5252 		return (NULL);
5253 	/* If we aren't going to consume the first mblk, we need a dup. */
5254 	if (mp0->b_wptr - mp0->b_rptr > len) {
5255 		mp1 = dupb(mp0);
5256 		if (mp1) {
5257 			/* Partition the data between the two mblks. */
5258 			mp1->b_wptr = mp1->b_rptr + len;
5259 			mp0->b_rptr = mp1->b_wptr;
5260 			/*
5261 			 * after adjustments if mblk not consumed is now
5262 			 * unaligned, try to align it. If this fails free
5263 			 * all messages and let upper layer recover.
5264 			 */
5265 			if (!OK_32PTR(mp0->b_rptr)) {
5266 				if (!pullupmsg(mp0, -1)) {
5267 					freemsg(mp0);
5268 					freemsg(mp1);
5269 					*mpp = NULL;
5270 					return (NULL);
5271 				}
5272 			}
5273 		}
5274 		return (mp1);
5275 	}
5276 	/* Eat through as many mblks as we need to get len bytes. */
5277 	len -= mp0->b_wptr - mp0->b_rptr;
5278 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5279 		if (mp2->b_wptr - mp2->b_rptr > len) {
5280 			/*
5281 			 * We won't consume the entire last mblk.  Like
5282 			 * above, dup and partition it.
5283 			 */
5284 			mp1->b_cont = dupb(mp2);
5285 			mp1 = mp1->b_cont;
5286 			if (!mp1) {
5287 				/*
5288 				 * Trouble.  Rather than go to a lot of
5289 				 * trouble to clean up, we free the messages.
5290 				 * This won't be any worse than losing it on
5291 				 * the wire.
5292 				 */
5293 				freemsg(mp0);
5294 				freemsg(mp2);
5295 				*mpp = NULL;
5296 				return (NULL);
5297 			}
5298 			mp1->b_wptr = mp1->b_rptr + len;
5299 			mp2->b_rptr = mp1->b_wptr;
5300 			/*
5301 			 * after adjustments if mblk not consumed is now
5302 			 * unaligned, try to align it. If this fails free
5303 			 * all messages and let upper layer recover.
5304 			 */
5305 			if (!OK_32PTR(mp2->b_rptr)) {
5306 				if (!pullupmsg(mp2, -1)) {
5307 					freemsg(mp0);
5308 					freemsg(mp2);
5309 					*mpp = NULL;
5310 					return (NULL);
5311 				}
5312 			}
5313 			*mpp = mp2;
5314 			return (mp0);
5315 		}
5316 		/* Decrement len by the amount we just got. */
5317 		len -= mp2->b_wptr - mp2->b_rptr;
5318 	}
5319 	/*
5320 	 * len should be reduced to zero now.  If not our caller has
5321 	 * screwed up.
5322 	 */
5323 	if (len) {
5324 		/* Shouldn't happen! */
5325 		freemsg(mp0);
5326 		*mpp = NULL;
5327 		return (NULL);
5328 	}
5329 	/*
5330 	 * We consumed up to exactly the end of an mblk.  Detach the part
5331 	 * we are returning from the rest of the chain.
5332 	 */
5333 	mp1->b_cont = NULL;
5334 	*mpp = mp2;
5335 	return (mp0);
5336 }
5337 
5338 /* The ill stream is being unplumbed. Called from ip_close */
5339 int
5340 ip_modclose(ill_t *ill)
5341 {
5342 
5343 	boolean_t success;
5344 	ipsq_t	*ipsq;
5345 	ipif_t	*ipif;
5346 	queue_t	*q = ill->ill_rq;
5347 	hook_nic_event_t *info;
5348 
5349 	/*
5350 	 * Forcibly enter the ipsq after some delay. This is to take
5351 	 * care of the case when some ioctl does not complete because
5352 	 * we sent a control message to the driver and it did not
5353 	 * send us a reply. We want to be able to at least unplumb
5354 	 * and replumb rather than force the user to reboot the system.
5355 	 */
5356 	success = ipsq_enter(ill, B_FALSE);
5357 
5358 	/*
5359 	 * Open/close/push/pop is guaranteed to be single threaded
5360 	 * per stream by STREAMS. FS guarantees that all references
5361 	 * from top are gone before close is called. So there can't
5362 	 * be another close thread that has set CONDEMNED on this ill.
5363 	 * and cause ipsq_enter to return failure.
5364 	 */
5365 	ASSERT(success);
5366 	ipsq = ill->ill_phyint->phyint_ipsq;
5367 
5368 	/*
5369 	 * Mark it condemned. No new reference will be made to this ill.
5370 	 * Lookup functions will return an error. Threads that try to
5371 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5372 	 * that the refcnt will drop down to zero.
5373 	 */
5374 	mutex_enter(&ill->ill_lock);
5375 	ill->ill_state_flags |= ILL_CONDEMNED;
5376 	for (ipif = ill->ill_ipif; ipif != NULL;
5377 	    ipif = ipif->ipif_next) {
5378 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5379 	}
5380 	/*
5381 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5382 	 * returns  error if ILL_CONDEMNED is set
5383 	 */
5384 	cv_broadcast(&ill->ill_cv);
5385 	mutex_exit(&ill->ill_lock);
5386 
5387 	/*
5388 	 * Shut down fragmentation reassembly.
5389 	 * ill_frag_timer won't start a timer again.
5390 	 * Now cancel any existing timer
5391 	 */
5392 	(void) untimeout(ill->ill_frag_timer_id);
5393 	(void) ill_frag_timeout(ill, 0);
5394 
5395 	/*
5396 	 * If MOVE was in progress, clear the
5397 	 * move_in_progress fields also.
5398 	 */
5399 	if (ill->ill_move_in_progress) {
5400 		ILL_CLEAR_MOVE(ill);
5401 	}
5402 
5403 	/*
5404 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5405 	 * this ill. Then wait for the refcnts to drop to zero.
5406 	 * ill_is_quiescent checks whether the ill is really quiescent.
5407 	 * Then make sure that threads that are waiting to enter the
5408 	 * ipsq have seen the error returned by ipsq_enter and have
5409 	 * gone away. Then we call ill_delete_tail which does the
5410 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5411 	 */
5412 	ill_delete(ill);
5413 	mutex_enter(&ill->ill_lock);
5414 	while (!ill_is_quiescent(ill))
5415 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5416 	while (ill->ill_waiters)
5417 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5418 
5419 	mutex_exit(&ill->ill_lock);
5420 
5421 	/* qprocsoff is called in ill_delete_tail */
5422 	ill_delete_tail(ill);
5423 
5424 	/*
5425 	 * Walk through all upper (conn) streams and qenable
5426 	 * those that have queued data.
5427 	 * close synchronization needs this to
5428 	 * be done to ensure that all upper layers blocked
5429 	 * due to flow control to the closing device
5430 	 * get unblocked.
5431 	 */
5432 	ip1dbg(("ip_wsrv: walking\n"));
5433 	conn_walk_drain();
5434 
5435 	mutex_enter(&ip_mi_lock);
5436 	mi_close_unlink(&ip_g_head, (IDP)ill);
5437 	mutex_exit(&ip_mi_lock);
5438 
5439 	/*
5440 	 * credp could be null if the open didn't succeed and ip_modopen
5441 	 * itself calls ip_close.
5442 	 */
5443 	if (ill->ill_credp != NULL)
5444 		crfree(ill->ill_credp);
5445 
5446 	/*
5447 	 * Unhook the nic event message from the ill and enqueue it into the nic
5448 	 * event taskq.
5449 	 */
5450 	if ((info = ill->ill_nic_event_info) != NULL) {
5451 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5452 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5453 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5454 			if (info->hne_data != NULL)
5455 				kmem_free(info->hne_data, info->hne_datalen);
5456 			kmem_free(info, sizeof (hook_nic_event_t));
5457 		}
5458 		ill->ill_nic_event_info = NULL;
5459 	}
5460 
5461 	mi_close_free((IDP)ill);
5462 	q->q_ptr = WR(q)->q_ptr = NULL;
5463 
5464 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5465 
5466 	return (0);
5467 }
5468 
5469 /*
5470  * This is called as part of close() for both IP and UDP
5471  * in order to quiesce the conn.
5472  */
5473 void
5474 ip_quiesce_conn(conn_t *connp)
5475 {
5476 	boolean_t	drain_cleanup_reqd = B_FALSE;
5477 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5478 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5479 
5480 	ASSERT(!IPCL_IS_TCP(connp));
5481 
5482 	/*
5483 	 * Mark the conn as closing, and this conn must not be
5484 	 * inserted in future into any list. Eg. conn_drain_insert(),
5485 	 * won't insert this conn into the conn_drain_list.
5486 	 * Similarly ill_pending_mp_add() will not add any mp to
5487 	 * the pending mp list, after this conn has started closing.
5488 	 *
5489 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5490 	 * cannot get set henceforth.
5491 	 */
5492 	mutex_enter(&connp->conn_lock);
5493 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5494 	connp->conn_state_flags |= CONN_CLOSING;
5495 	if (connp->conn_idl != NULL)
5496 		drain_cleanup_reqd = B_TRUE;
5497 	if (connp->conn_oper_pending_ill != NULL)
5498 		conn_ioctl_cleanup_reqd = B_TRUE;
5499 	if (connp->conn_ilg_inuse != 0)
5500 		ilg_cleanup_reqd = B_TRUE;
5501 	mutex_exit(&connp->conn_lock);
5502 
5503 	if (IPCL_IS_UDP(connp))
5504 		udp_quiesce_conn(connp);
5505 
5506 	if (conn_ioctl_cleanup_reqd)
5507 		conn_ioctl_cleanup(connp);
5508 
5509 	if (is_system_labeled() && connp->conn_anon_port) {
5510 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5511 		    connp->conn_mlp_type, connp->conn_ulp,
5512 		    ntohs(connp->conn_lport), B_FALSE);
5513 		connp->conn_anon_port = 0;
5514 	}
5515 	connp->conn_mlp_type = mlptSingle;
5516 
5517 	/*
5518 	 * Remove this conn from any fanout list it is on.
5519 	 * and then wait for any threads currently operating
5520 	 * on this endpoint to finish
5521 	 */
5522 	ipcl_hash_remove(connp);
5523 
5524 	/*
5525 	 * Remove this conn from the drain list, and do
5526 	 * any other cleanup that may be required.
5527 	 * (Only non-tcp streams may have a non-null conn_idl.
5528 	 * TCP streams are never flow controlled, and
5529 	 * conn_idl will be null)
5530 	 */
5531 	if (drain_cleanup_reqd)
5532 		conn_drain_tail(connp, B_TRUE);
5533 
5534 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5535 		(void) ip_mrouter_done(NULL);
5536 
5537 	if (ilg_cleanup_reqd)
5538 		ilg_delete_all(connp);
5539 
5540 	conn_delete_ire(connp, NULL);
5541 
5542 	/*
5543 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5544 	 * callers from write side can't be there now because close
5545 	 * is in progress. The only other caller is ipcl_walk
5546 	 * which checks for the condemned flag.
5547 	 */
5548 	mutex_enter(&connp->conn_lock);
5549 	connp->conn_state_flags |= CONN_CONDEMNED;
5550 	while (connp->conn_ref != 1)
5551 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5552 	connp->conn_state_flags |= CONN_QUIESCED;
5553 	mutex_exit(&connp->conn_lock);
5554 }
5555 
5556 /* ARGSUSED */
5557 int
5558 ip_close(queue_t *q, int flags)
5559 {
5560 	conn_t		*connp;
5561 
5562 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5563 
5564 	/*
5565 	 * Call the appropriate delete routine depending on whether this is
5566 	 * a module or device.
5567 	 */
5568 	if (WR(q)->q_next != NULL) {
5569 		/* This is a module close */
5570 		return (ip_modclose((ill_t *)q->q_ptr));
5571 	}
5572 
5573 	connp = q->q_ptr;
5574 	ip_quiesce_conn(connp);
5575 
5576 	qprocsoff(q);
5577 
5578 	/*
5579 	 * Now we are truly single threaded on this stream, and can
5580 	 * delete the things hanging off the connp, and finally the connp.
5581 	 * We removed this connp from the fanout list, it cannot be
5582 	 * accessed thru the fanouts, and we already waited for the
5583 	 * conn_ref to drop to 0. We are already in close, so
5584 	 * there cannot be any other thread from the top. qprocsoff
5585 	 * has completed, and service has completed or won't run in
5586 	 * future.
5587 	 */
5588 	ASSERT(connp->conn_ref == 1);
5589 
5590 	/*
5591 	 * A conn which was previously marked as IPCL_UDP cannot
5592 	 * retain the flag because it would have been cleared by
5593 	 * udp_close().
5594 	 */
5595 	ASSERT(!IPCL_IS_UDP(connp));
5596 
5597 	if (connp->conn_latch != NULL) {
5598 		IPLATCH_REFRELE(connp->conn_latch);
5599 		connp->conn_latch = NULL;
5600 	}
5601 	if (connp->conn_policy != NULL) {
5602 		IPPH_REFRELE(connp->conn_policy);
5603 		connp->conn_policy = NULL;
5604 	}
5605 	if (connp->conn_ipsec_opt_mp != NULL) {
5606 		freemsg(connp->conn_ipsec_opt_mp);
5607 		connp->conn_ipsec_opt_mp = NULL;
5608 	}
5609 
5610 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5611 
5612 	connp->conn_ref--;
5613 	ipcl_conn_destroy(connp);
5614 
5615 	q->q_ptr = WR(q)->q_ptr = NULL;
5616 	return (0);
5617 }
5618 
5619 int
5620 ip_snmpmod_close(queue_t *q)
5621 {
5622 	conn_t *connp = Q_TO_CONN(q);
5623 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5624 
5625 	qprocsoff(q);
5626 
5627 	if (connp->conn_flags & IPCL_UDPMOD)
5628 		udp_close_free(connp);
5629 
5630 	if (connp->conn_cred != NULL) {
5631 		crfree(connp->conn_cred);
5632 		connp->conn_cred = NULL;
5633 	}
5634 	CONN_DEC_REF(connp);
5635 	q->q_ptr = WR(q)->q_ptr = NULL;
5636 	return (0);
5637 }
5638 
5639 /*
5640  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5641  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5642  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5643  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5644  * queues as we never enqueue messages there and we don't handle any ioctls.
5645  * Everything else is freed.
5646  */
5647 void
5648 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5649 {
5650 	conn_t	*connp = q->q_ptr;
5651 	pfi_t	setfn;
5652 	pfi_t	getfn;
5653 
5654 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5655 
5656 	switch (DB_TYPE(mp)) {
5657 	case M_PROTO:
5658 	case M_PCPROTO:
5659 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5660 		    ((((union T_primitives *)mp->b_rptr)->type ==
5661 			T_SVR4_OPTMGMT_REQ) ||
5662 		    (((union T_primitives *)mp->b_rptr)->type ==
5663 			T_OPTMGMT_REQ))) {
5664 			/*
5665 			 * This is the only TPI primitive supported. Its
5666 			 * handling does not require tcp_t, but it does require
5667 			 * conn_t to check permissions.
5668 			 */
5669 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5670 
5671 			if (connp->conn_flags & IPCL_TCPMOD) {
5672 				setfn = tcp_snmp_set;
5673 				getfn = tcp_snmp_get;
5674 			} else {
5675 				setfn = udp_snmp_set;
5676 				getfn = udp_snmp_get;
5677 			}
5678 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5679 				freemsg(mp);
5680 				return;
5681 			}
5682 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5683 		    != NULL)
5684 			qreply(q, mp);
5685 		break;
5686 	case M_FLUSH:
5687 	case M_IOCTL:
5688 		putnext(q, mp);
5689 		break;
5690 	default:
5691 		freemsg(mp);
5692 		break;
5693 	}
5694 }
5695 
5696 /* Return the IP checksum for the IP header at "iph". */
5697 uint16_t
5698 ip_csum_hdr(ipha_t *ipha)
5699 {
5700 	uint16_t	*uph;
5701 	uint32_t	sum;
5702 	int		opt_len;
5703 
5704 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5705 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5706 	uph = (uint16_t *)ipha;
5707 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5708 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5709 	if (opt_len > 0) {
5710 		do {
5711 			sum += uph[10];
5712 			sum += uph[11];
5713 			uph += 2;
5714 		} while (--opt_len);
5715 	}
5716 	sum = (sum & 0xFFFF) + (sum >> 16);
5717 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5718 	if (sum == 0xffff)
5719 		sum = 0;
5720 	return ((uint16_t)sum);
5721 }
5722 
5723 void
5724 ip_ddi_destroy(void)
5725 {
5726 	ipv4_hook_destroy();
5727 	ipv6_hook_destroy();
5728 	ip_net_destroy();
5729 
5730 	tnet_fini();
5731 	tcp_ddi_destroy();
5732 	sctp_ddi_destroy();
5733 	ipsec_loader_destroy();
5734 	ipsec_policy_destroy();
5735 	ipsec_kstat_destroy();
5736 	nd_free(&ip_g_nd);
5737 	mutex_destroy(&igmp_timer_lock);
5738 	mutex_destroy(&mld_timer_lock);
5739 	mutex_destroy(&igmp_slowtimeout_lock);
5740 	mutex_destroy(&mld_slowtimeout_lock);
5741 	mutex_destroy(&ip_mi_lock);
5742 	mutex_destroy(&rts_clients.connf_lock);
5743 	ip_ire_fini();
5744 	ip6_asp_free();
5745 	conn_drain_fini();
5746 	ipcl_destroy();
5747 	inet_minor_destroy(ip_minor_arena);
5748 	icmp_kstat_fini();
5749 	ip_kstat_fini();
5750 	rw_destroy(&ipsec_capab_ills_lock);
5751 	rw_destroy(&ill_g_usesrc_lock);
5752 	ip_drop_unregister(&ip_dropper);
5753 }
5754 
5755 
5756 void
5757 ip_ddi_init(void)
5758 {
5759 	TCP6_MAJ = ddi_name_to_major(TCP6);
5760 	TCP_MAJ	= ddi_name_to_major(TCP);
5761 	SCTP_MAJ = ddi_name_to_major(SCTP);
5762 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5763 
5764 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5765 
5766 	/* IP's IPsec code calls the packet dropper */
5767 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5768 
5769 	if (!ip_g_nd) {
5770 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5771 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5772 			nd_free(&ip_g_nd);
5773 		}
5774 	}
5775 
5776 	ipsec_loader_init();
5777 	ipsec_policy_init();
5778 	ipsec_kstat_init();
5779 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5780 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5781 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5782 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5783 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5784 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5785 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5786 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5787 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5788 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5789 
5790 	/*
5791 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5792 	 * initial devices: ip, ip6, tcp, tcp6.
5793 	 */
5794 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5795 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5796 		cmn_err(CE_PANIC,
5797 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5798 	}
5799 
5800 	ipcl_init();
5801 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5802 	ip_ire_init();
5803 	ip6_asp_init();
5804 	ipif_init();
5805 	conn_drain_init();
5806 	tcp_ddi_init();
5807 	sctp_ddi_init();
5808 
5809 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5810 
5811 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5812 		"net", KSTAT_TYPE_NAMED,
5813 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5814 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5815 		ip_kstat->ks_data = &ip_statistics;
5816 		kstat_install(ip_kstat);
5817 	}
5818 	ip_kstat_init();
5819 	ip6_kstat_init();
5820 	icmp_kstat_init();
5821 	ipsec_loader_start();
5822 	tnet_init();
5823 
5824 	ip_net_init();
5825 	ipv4_hook_init();
5826 	ipv6_hook_init();
5827 }
5828 
5829 /*
5830  * Allocate and initialize a DLPI template of the specified length.  (May be
5831  * called as writer.)
5832  */
5833 mblk_t *
5834 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5835 {
5836 	mblk_t	*mp;
5837 
5838 	mp = allocb(len, BPRI_MED);
5839 	if (!mp)
5840 		return (NULL);
5841 
5842 	/*
5843 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5844 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5845 	 * that other DLPI are M_PROTO.
5846 	 */
5847 	if (prim == DL_INFO_REQ) {
5848 		mp->b_datap->db_type = M_PCPROTO;
5849 	} else {
5850 		mp->b_datap->db_type = M_PROTO;
5851 	}
5852 
5853 	mp->b_wptr = mp->b_rptr + len;
5854 	bzero(mp->b_rptr, len);
5855 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5856 	return (mp);
5857 }
5858 
5859 const char *
5860 dlpi_prim_str(int prim)
5861 {
5862 	switch (prim) {
5863 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5864 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5865 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5866 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5867 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5868 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5869 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5870 	case DL_OK_ACK:		return ("DL_OK_ACK");
5871 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5872 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5873 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5874 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5875 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5876 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5877 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5878 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5879 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5880 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5881 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
5882 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
5883 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
5884 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
5885 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
5886 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
5887 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
5888 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
5889 	default:		return ("<unknown primitive>");
5890 	}
5891 }
5892 
5893 const char *
5894 dlpi_err_str(int err)
5895 {
5896 	switch (err) {
5897 	case DL_ACCESS:		return ("DL_ACCESS");
5898 	case DL_BADADDR:	return ("DL_BADADDR");
5899 	case DL_BADCORR:	return ("DL_BADCORR");
5900 	case DL_BADDATA:	return ("DL_BADDATA");
5901 	case DL_BADPPA:		return ("DL_BADPPA");
5902 	case DL_BADPRIM:	return ("DL_BADPRIM");
5903 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
5904 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
5905 	case DL_BADSAP:		return ("DL_BADSAP");
5906 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
5907 	case DL_BOUND:		return ("DL_BOUND");
5908 	case DL_INITFAILED:	return ("DL_INITFAILED");
5909 	case DL_NOADDR:		return ("DL_NOADDR");
5910 	case DL_NOTINIT:	return ("DL_NOTINIT");
5911 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
5912 	case DL_SYSERR:		return ("DL_SYSERR");
5913 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
5914 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
5915 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
5916 	case DL_TOOMANY:	return ("DL_TOOMANY");
5917 	case DL_NOTENAB:	return ("DL_NOTENAB");
5918 	case DL_BUSY:		return ("DL_BUSY");
5919 	case DL_NOAUTO:		return ("DL_NOAUTO");
5920 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
5921 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
5922 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
5923 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
5924 	case DL_PENDING:	return ("DL_PENDING");
5925 	default:		return ("<unknown error>");
5926 	}
5927 }
5928 
5929 /*
5930  * Debug formatting routine.  Returns a character string representation of the
5931  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
5932  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
5933  *
5934  * Once the ndd table-printing interfaces are removed, this can be changed to
5935  * standard dotted-decimal form.
5936  */
5937 char *
5938 ip_dot_addr(ipaddr_t addr, char *buf)
5939 {
5940 	uint8_t *ap = (uint8_t *)&addr;
5941 
5942 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
5943 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
5944 	return (buf);
5945 }
5946 
5947 /*
5948  * Write the given MAC address as a printable string in the usual colon-
5949  * separated format.
5950  */
5951 const char *
5952 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
5953 {
5954 	char *bp;
5955 
5956 	if (alen == 0 || buflen < 4)
5957 		return ("?");
5958 	bp = buf;
5959 	for (;;) {
5960 		/*
5961 		 * If there are more MAC address bytes available, but we won't
5962 		 * have any room to print them, then add "..." to the string
5963 		 * instead.  See below for the 'magic number' explanation.
5964 		 */
5965 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
5966 			(void) strcpy(bp, "...");
5967 			break;
5968 		}
5969 		(void) sprintf(bp, "%02x", *addr++);
5970 		bp += 2;
5971 		if (--alen == 0)
5972 			break;
5973 		*bp++ = ':';
5974 		buflen -= 3;
5975 		/*
5976 		 * At this point, based on the first 'if' statement above,
5977 		 * either alen == 1 and buflen >= 3, or alen > 1 and
5978 		 * buflen >= 4.  The first case leaves room for the final "xx"
5979 		 * number and trailing NUL byte.  The second leaves room for at
5980 		 * least "...".  Thus the apparently 'magic' numbers chosen for
5981 		 * that statement.
5982 		 */
5983 	}
5984 	return (buf);
5985 }
5986 
5987 /*
5988  * Send an ICMP error after patching up the packet appropriately.  Returns
5989  * non-zero if the appropriate MIB should be bumped; zero otherwise.
5990  */
5991 static boolean_t
5992 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
5993     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
5994 {
5995 	ipha_t *ipha;
5996 	mblk_t *first_mp;
5997 	boolean_t secure;
5998 	unsigned char db_type;
5999 
6000 	first_mp = mp;
6001 	if (mctl_present) {
6002 		mp = mp->b_cont;
6003 		secure = ipsec_in_is_secure(first_mp);
6004 		ASSERT(mp != NULL);
6005 	} else {
6006 		/*
6007 		 * If this is an ICMP error being reported - which goes
6008 		 * up as M_CTLs, we need to convert them to M_DATA till
6009 		 * we finish checking with global policy because
6010 		 * ipsec_check_global_policy() assumes M_DATA as clear
6011 		 * and M_CTL as secure.
6012 		 */
6013 		db_type = DB_TYPE(mp);
6014 		DB_TYPE(mp) = M_DATA;
6015 		secure = B_FALSE;
6016 	}
6017 	/*
6018 	 * We are generating an icmp error for some inbound packet.
6019 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6020 	 * Before we generate an error, check with global policy
6021 	 * to see whether this is allowed to enter the system. As
6022 	 * there is no "conn", we are checking with global policy.
6023 	 */
6024 	ipha = (ipha_t *)mp->b_rptr;
6025 	if (secure || ipsec_inbound_v4_policy_present) {
6026 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6027 		    ipha, NULL, mctl_present);
6028 		if (first_mp == NULL)
6029 			return (B_FALSE);
6030 	}
6031 
6032 	if (!mctl_present)
6033 		DB_TYPE(mp) = db_type;
6034 
6035 	if (flags & IP_FF_SEND_ICMP) {
6036 		if (flags & IP_FF_HDR_COMPLETE) {
6037 			if (ip_hdr_complete(ipha, zoneid)) {
6038 				freemsg(first_mp);
6039 				return (B_TRUE);
6040 			}
6041 		}
6042 		if (flags & IP_FF_CKSUM) {
6043 			/*
6044 			 * Have to correct checksum since
6045 			 * the packet might have been
6046 			 * fragmented and the reassembly code in ip_rput
6047 			 * does not restore the IP checksum.
6048 			 */
6049 			ipha->ipha_hdr_checksum = 0;
6050 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6051 		}
6052 		switch (icmp_type) {
6053 		case ICMP_DEST_UNREACHABLE:
6054 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6055 			break;
6056 		default:
6057 			freemsg(first_mp);
6058 			break;
6059 		}
6060 	} else {
6061 		freemsg(first_mp);
6062 		return (B_FALSE);
6063 	}
6064 
6065 	return (B_TRUE);
6066 }
6067 
6068 /*
6069  * Used to send an ICMP error message when a packet is received for
6070  * a protocol that is not supported. The mblk passed as argument
6071  * is consumed by this function.
6072  */
6073 void
6074 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6075 {
6076 	mblk_t *mp;
6077 	ipha_t *ipha;
6078 	ill_t *ill;
6079 	ipsec_in_t *ii;
6080 
6081 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6082 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6083 
6084 	mp = ipsec_mp->b_cont;
6085 	ipsec_mp->b_cont = NULL;
6086 	ipha = (ipha_t *)mp->b_rptr;
6087 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6088 		if (ip_fanout_send_icmp(q, mp, flags, ICMP_DEST_UNREACHABLE,
6089 		    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6090 			BUMP_MIB(&ip_mib, ipInUnknownProtos);
6091 		}
6092 	} else {
6093 		/* Get ill from index in ipsec_in_t. */
6094 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6095 		    B_TRUE, NULL, NULL, NULL, NULL);
6096 		if (ill != NULL) {
6097 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6098 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6099 			    0, B_FALSE, zoneid)) {
6100 				BUMP_MIB(ill->ill_ip6_mib, ipv6InUnknownProtos);
6101 			}
6102 
6103 			ill_refrele(ill);
6104 		} else { /* re-link for the freemsg() below. */
6105 			ipsec_mp->b_cont = mp;
6106 		}
6107 	}
6108 
6109 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6110 	freemsg(ipsec_mp);
6111 }
6112 
6113 /*
6114  * See if the inbound datagram has had IPsec processing applied to it.
6115  */
6116 boolean_t
6117 ipsec_in_is_secure(mblk_t *ipsec_mp)
6118 {
6119 	ipsec_in_t *ii;
6120 
6121 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6122 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6123 
6124 	if (ii->ipsec_in_loopback) {
6125 		return (ii->ipsec_in_secure);
6126 	} else {
6127 		return (ii->ipsec_in_ah_sa != NULL ||
6128 		    ii->ipsec_in_esp_sa != NULL ||
6129 		    ii->ipsec_in_decaps);
6130 	}
6131 }
6132 
6133 /*
6134  * Handle protocols with which IP is less intimate.  There
6135  * can be more than one stream bound to a particular
6136  * protocol.  When this is the case, normally each one gets a copy
6137  * of any incoming packets.
6138  *
6139  * IPSEC NOTE :
6140  *
6141  * Don't allow a secure packet going up a non-secure connection.
6142  * We don't allow this because
6143  *
6144  * 1) Reply might go out in clear which will be dropped at
6145  *    the sending side.
6146  * 2) If the reply goes out in clear it will give the
6147  *    adversary enough information for getting the key in
6148  *    most of the cases.
6149  *
6150  * Moreover getting a secure packet when we expect clear
6151  * implies that SA's were added without checking for
6152  * policy on both ends. This should not happen once ISAKMP
6153  * is used to negotiate SAs as SAs will be added only after
6154  * verifying the policy.
6155  *
6156  * NOTE : If the packet was tunneled and not multicast we only send
6157  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6158  * back to delivering packets to AF_INET6 raw sockets.
6159  *
6160  * IPQoS Notes:
6161  * Once we have determined the client, invoke IPPF processing.
6162  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6163  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6164  * ip_policy will be false.
6165  *
6166  * Zones notes:
6167  * Currently only applications in the global zone can create raw sockets for
6168  * protocols other than ICMP. So unlike the broadcast / multicast case of
6169  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6170  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6171  */
6172 static void
6173 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6174     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6175     zoneid_t zoneid)
6176 {
6177 	queue_t	*rq;
6178 	mblk_t	*mp1, *first_mp1;
6179 	uint_t	protocol = ipha->ipha_protocol;
6180 	ipaddr_t dst;
6181 	boolean_t one_only;
6182 	mblk_t *first_mp = mp;
6183 	boolean_t secure;
6184 	uint32_t ill_index;
6185 	conn_t	*connp, *first_connp, *next_connp;
6186 	connf_t	*connfp;
6187 	boolean_t shared_addr;
6188 
6189 	if (mctl_present) {
6190 		mp = first_mp->b_cont;
6191 		secure = ipsec_in_is_secure(first_mp);
6192 		ASSERT(mp != NULL);
6193 	} else {
6194 		secure = B_FALSE;
6195 	}
6196 	dst = ipha->ipha_dst;
6197 	/*
6198 	 * If the packet was tunneled and not multicast we only send to it
6199 	 * the first match.
6200 	 */
6201 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6202 	    !CLASSD(dst));
6203 
6204 	shared_addr = (zoneid == ALL_ZONES);
6205 	if (shared_addr) {
6206 		/*
6207 		 * We don't allow multilevel ports for raw IP, so no need to
6208 		 * check for that here.
6209 		 */
6210 		zoneid = tsol_packet_to_zoneid(mp);
6211 	}
6212 
6213 	connfp = &ipcl_proto_fanout[protocol];
6214 	mutex_enter(&connfp->connf_lock);
6215 	connp = connfp->connf_head;
6216 	for (connp = connfp->connf_head; connp != NULL;
6217 		connp = connp->conn_next) {
6218 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6219 		    zoneid) &&
6220 		    (!is_system_labeled() ||
6221 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6222 		    connp)))
6223 			break;
6224 	}
6225 
6226 	if (connp == NULL || connp->conn_upq == NULL) {
6227 		/*
6228 		 * No one bound to these addresses.  Is
6229 		 * there a client that wants all
6230 		 * unclaimed datagrams?
6231 		 */
6232 		mutex_exit(&connfp->connf_lock);
6233 		/*
6234 		 * Check for IPPROTO_ENCAP...
6235 		 */
6236 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6237 			/*
6238 			 * If an IPsec mblk is here on a multicast
6239 			 * tunnel (using ip_mroute stuff), check policy here,
6240 			 * THEN ship off to ip_mroute_decap().
6241 			 *
6242 			 * BTW,  If I match a configured IP-in-IP
6243 			 * tunnel, this path will not be reached, and
6244 			 * ip_mroute_decap will never be called.
6245 			 */
6246 			first_mp = ipsec_check_global_policy(first_mp, connp,
6247 			    ipha, NULL, mctl_present);
6248 			if (first_mp != NULL) {
6249 				if (mctl_present)
6250 					freeb(first_mp);
6251 				ip_mroute_decap(q, mp);
6252 			} /* Else we already freed everything! */
6253 		} else {
6254 			/*
6255 			 * Otherwise send an ICMP protocol unreachable.
6256 			 */
6257 			if (ip_fanout_send_icmp(q, first_mp, flags,
6258 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6259 			    mctl_present, zoneid)) {
6260 				BUMP_MIB(&ip_mib, ipInUnknownProtos);
6261 			}
6262 		}
6263 		return;
6264 	}
6265 	CONN_INC_REF(connp);
6266 	first_connp = connp;
6267 
6268 	/*
6269 	 * Only send message to one tunnel driver by immediately
6270 	 * terminating the loop.
6271 	 */
6272 	connp = one_only ? NULL : connp->conn_next;
6273 
6274 	for (;;) {
6275 		while (connp != NULL) {
6276 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6277 			    flags, zoneid) &&
6278 			    (!is_system_labeled() ||
6279 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6280 			    shared_addr, connp)))
6281 				break;
6282 			connp = connp->conn_next;
6283 		}
6284 
6285 		/*
6286 		 * Copy the packet.
6287 		 */
6288 		if (connp == NULL || connp->conn_upq == NULL ||
6289 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6290 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6291 			/*
6292 			 * No more interested clients or memory
6293 			 * allocation failed
6294 			 */
6295 			connp = first_connp;
6296 			break;
6297 		}
6298 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6299 		CONN_INC_REF(connp);
6300 		mutex_exit(&connfp->connf_lock);
6301 		rq = connp->conn_rq;
6302 		if (!canputnext(rq)) {
6303 			if (flags & IP_FF_RAWIP) {
6304 				BUMP_MIB(&ip_mib, rawipInOverflows);
6305 			} else {
6306 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6307 			}
6308 
6309 			freemsg(first_mp1);
6310 		} else {
6311 			/*
6312 			 * Don't enforce here if we're an actual tunnel -
6313 			 * let "tun" do it instead.
6314 			 */
6315 			if (!IPCL_IS_IPTUN(connp) &&
6316 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6317 				first_mp1 = ipsec_check_inbound_policy
6318 				    (first_mp1, connp, ipha, NULL,
6319 				    mctl_present);
6320 			}
6321 			if (first_mp1 != NULL) {
6322 				/*
6323 				 * ip_fanout_proto also gets called from
6324 				 * icmp_inbound_error_fanout, in which case
6325 				 * the msg type is M_CTL.  Don't add info
6326 				 * in this case for the time being. In future
6327 				 * when there is a need for knowing the
6328 				 * inbound iface index for ICMP error msgs,
6329 				 * then this can be changed.
6330 				 */
6331 				if ((connp->conn_recvif != 0) &&
6332 				    (mp->b_datap->db_type != M_CTL)) {
6333 					/*
6334 					 * the actual data will be
6335 					 * contained in b_cont upon
6336 					 * successful return of the
6337 					 * following call else
6338 					 * original mblk is returned
6339 					 */
6340 					ASSERT(recv_ill != NULL);
6341 					mp1 = ip_add_info(mp1, recv_ill,
6342 						IPF_RECVIF);
6343 				}
6344 				BUMP_MIB(&ip_mib, ipInDelivers);
6345 				if (mctl_present)
6346 					freeb(first_mp1);
6347 				putnext(rq, mp1);
6348 			}
6349 		}
6350 		mutex_enter(&connfp->connf_lock);
6351 		/* Follow the next pointer before releasing the conn. */
6352 		next_connp = connp->conn_next;
6353 		CONN_DEC_REF(connp);
6354 		connp = next_connp;
6355 	}
6356 
6357 	/* Last one.  Send it upstream. */
6358 	mutex_exit(&connfp->connf_lock);
6359 
6360 	/*
6361 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6362 	 * will be set to false.
6363 	 */
6364 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6365 		ill_index = ill->ill_phyint->phyint_ifindex;
6366 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6367 		if (mp == NULL) {
6368 			CONN_DEC_REF(connp);
6369 			if (mctl_present) {
6370 				freeb(first_mp);
6371 			}
6372 			return;
6373 		}
6374 	}
6375 
6376 	rq = connp->conn_rq;
6377 	if (!canputnext(rq)) {
6378 		if (flags & IP_FF_RAWIP) {
6379 			BUMP_MIB(&ip_mib, rawipInOverflows);
6380 		} else {
6381 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6382 		}
6383 
6384 		freemsg(first_mp);
6385 	} else {
6386 		if (IPCL_IS_IPTUN(connp)) {
6387 			/*
6388 			 * Tunneled packet.  We enforce policy in the tunnel
6389 			 * module itself.
6390 			 *
6391 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6392 			 * a policy check.
6393 			 */
6394 			putnext(rq, first_mp);
6395 			CONN_DEC_REF(connp);
6396 			return;
6397 		}
6398 
6399 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6400 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6401 			    ipha, NULL, mctl_present);
6402 		}
6403 
6404 		if (first_mp != NULL) {
6405 			/*
6406 			 * ip_fanout_proto also gets called
6407 			 * from icmp_inbound_error_fanout, in
6408 			 * which case the msg type is M_CTL.
6409 			 * Don't add info in this case for time
6410 			 * being. In future when there is a
6411 			 * need for knowing the inbound iface
6412 			 * index for ICMP error msgs, then this
6413 			 * can be changed
6414 			 */
6415 			if ((connp->conn_recvif != 0) &&
6416 			    (mp->b_datap->db_type != M_CTL)) {
6417 				/*
6418 				 * the actual data will be contained in
6419 				 * b_cont upon successful return
6420 				 * of the following call else original
6421 				 * mblk is returned
6422 				 */
6423 				ASSERT(recv_ill != NULL);
6424 				mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6425 			}
6426 			BUMP_MIB(&ip_mib, ipInDelivers);
6427 			putnext(rq, mp);
6428 			if (mctl_present)
6429 				freeb(first_mp);
6430 		}
6431 	}
6432 	CONN_DEC_REF(connp);
6433 }
6434 
6435 /*
6436  * Fanout for TCP packets
6437  * The caller puts <fport, lport> in the ports parameter.
6438  *
6439  * IPQoS Notes
6440  * Before sending it to the client, invoke IPPF processing.
6441  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6442  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6443  * ip_policy is false.
6444  */
6445 static void
6446 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6447     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6448 {
6449 	mblk_t  *first_mp;
6450 	boolean_t secure;
6451 	uint32_t ill_index;
6452 	int	ip_hdr_len;
6453 	tcph_t	*tcph;
6454 	boolean_t syn_present = B_FALSE;
6455 	conn_t	*connp;
6456 
6457 	first_mp = mp;
6458 	if (mctl_present) {
6459 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6460 		mp = first_mp->b_cont;
6461 		secure = ipsec_in_is_secure(first_mp);
6462 		ASSERT(mp != NULL);
6463 	} else {
6464 		secure = B_FALSE;
6465 	}
6466 
6467 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6468 
6469 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6470 	    NULL) {
6471 		/*
6472 		 * No connected connection or listener. Send a
6473 		 * TH_RST via tcp_xmit_listeners_reset.
6474 		 */
6475 
6476 		/* Initiate IPPf processing, if needed. */
6477 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6478 			uint32_t ill_index;
6479 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6480 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6481 			if (first_mp == NULL)
6482 				return;
6483 		}
6484 		BUMP_MIB(&ip_mib, ipInDelivers);
6485 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6486 		    zoneid));
6487 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6488 		return;
6489 	}
6490 
6491 	/*
6492 	 * Allocate the SYN for the TCP connection here itself
6493 	 */
6494 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6495 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6496 		if (IPCL_IS_TCP(connp)) {
6497 			squeue_t *sqp;
6498 
6499 			/*
6500 			 * For fused tcp loopback, assign the eager's
6501 			 * squeue to be that of the active connect's.
6502 			 * Note that we don't check for IP_FF_LOOPBACK
6503 			 * here since this routine gets called only
6504 			 * for loopback (unlike the IPv6 counterpart).
6505 			 */
6506 			ASSERT(Q_TO_CONN(q) != NULL);
6507 			if (do_tcp_fusion &&
6508 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6509 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6510 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6511 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6512 				sqp = Q_TO_CONN(q)->conn_sqp;
6513 			} else {
6514 				sqp = IP_SQUEUE_GET(lbolt);
6515 			}
6516 
6517 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6518 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6519 			syn_present = B_TRUE;
6520 		}
6521 	}
6522 
6523 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6524 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6525 		if ((flags & TH_RST) || (flags & TH_URG)) {
6526 			CONN_DEC_REF(connp);
6527 			freemsg(first_mp);
6528 			return;
6529 		}
6530 		if (flags & TH_ACK) {
6531 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6532 			CONN_DEC_REF(connp);
6533 			return;
6534 		}
6535 
6536 		CONN_DEC_REF(connp);
6537 		freemsg(first_mp);
6538 		return;
6539 	}
6540 
6541 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6542 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6543 		    NULL, mctl_present);
6544 		if (first_mp == NULL) {
6545 			CONN_DEC_REF(connp);
6546 			return;
6547 		}
6548 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6549 			ASSERT(syn_present);
6550 			if (mctl_present) {
6551 				ASSERT(first_mp != mp);
6552 				first_mp->b_datap->db_struioflag |=
6553 				    STRUIO_POLICY;
6554 			} else {
6555 				ASSERT(first_mp == mp);
6556 				mp->b_datap->db_struioflag &=
6557 				    ~STRUIO_EAGER;
6558 				mp->b_datap->db_struioflag |=
6559 				    STRUIO_POLICY;
6560 			}
6561 		} else {
6562 			/*
6563 			 * Discard first_mp early since we're dealing with a
6564 			 * fully-connected conn_t and tcp doesn't do policy in
6565 			 * this case.
6566 			 */
6567 			if (mctl_present) {
6568 				freeb(first_mp);
6569 				mctl_present = B_FALSE;
6570 			}
6571 			first_mp = mp;
6572 		}
6573 	}
6574 
6575 	/*
6576 	 * Initiate policy processing here if needed. If we get here from
6577 	 * icmp_inbound_error_fanout, ip_policy is false.
6578 	 */
6579 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6580 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6581 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6582 		if (mp == NULL) {
6583 			CONN_DEC_REF(connp);
6584 			if (mctl_present)
6585 				freeb(first_mp);
6586 			return;
6587 		} else if (mctl_present) {
6588 			ASSERT(first_mp != mp);
6589 			first_mp->b_cont = mp;
6590 		} else {
6591 			first_mp = mp;
6592 		}
6593 	}
6594 
6595 
6596 
6597 	/* Handle IPv6 socket options. */
6598 	if (!syn_present &&
6599 	    connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO)) {
6600 		/* Add header */
6601 		ASSERT(recv_ill != NULL);
6602 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF);
6603 		if (mp == NULL) {
6604 			CONN_DEC_REF(connp);
6605 			if (mctl_present)
6606 				freeb(first_mp);
6607 			return;
6608 		} else if (mctl_present) {
6609 			/*
6610 			 * ip_add_info might return a new mp.
6611 			 */
6612 			ASSERT(first_mp != mp);
6613 			first_mp->b_cont = mp;
6614 		} else {
6615 			first_mp = mp;
6616 		}
6617 	}
6618 
6619 	BUMP_MIB(&ip_mib, ipInDelivers);
6620 	if (IPCL_IS_TCP(connp)) {
6621 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6622 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6623 	} else {
6624 		putnext(connp->conn_rq, first_mp);
6625 		CONN_DEC_REF(connp);
6626 	}
6627 }
6628 
6629 /*
6630  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6631  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6632  * Caller is responsible for dropping references to the conn, and freeing
6633  * first_mp.
6634  *
6635  * IPQoS Notes
6636  * Before sending it to the client, invoke IPPF processing. Policy processing
6637  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6638  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6639  * ip_wput_local, ip_policy is false.
6640  */
6641 static void
6642 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6643     boolean_t secure, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6644     boolean_t ip_policy)
6645 {
6646 	boolean_t	mctl_present = (first_mp != NULL);
6647 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6648 	uint32_t	ill_index;
6649 
6650 	if (mctl_present)
6651 		first_mp->b_cont = mp;
6652 	else
6653 		first_mp = mp;
6654 
6655 	if (CONN_UDP_FLOWCTLD(connp)) {
6656 		BUMP_MIB(&ip_mib, udpInOverflows);
6657 		freemsg(first_mp);
6658 		return;
6659 	}
6660 
6661 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6662 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6663 		    NULL, mctl_present);
6664 		if (first_mp == NULL)
6665 			return;	/* Freed by ipsec_check_inbound_policy(). */
6666 	}
6667 	if (mctl_present)
6668 		freeb(first_mp);
6669 
6670 	if (connp->conn_recvif)
6671 		in_flags = IPF_RECVIF;
6672 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6673 		in_flags |= IPF_RECVSLLA;
6674 
6675 	/* Handle IPv6 options. */
6676 	if (connp->conn_ipv6_recvpktinfo && (flags & IP_FF_IP6INFO))
6677 		in_flags |= IPF_RECVIF;
6678 
6679 	/*
6680 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6681 	 * freed if the packet is dropped. The caller will do so.
6682 	 */
6683 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6684 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6685 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6686 		if (mp == NULL) {
6687 			return;
6688 		}
6689 	}
6690 	if ((in_flags != 0) &&
6691 	    (mp->b_datap->db_type != M_CTL)) {
6692 		/*
6693 		 * The actual data will be contained in b_cont
6694 		 * upon successful return of the following call
6695 		 * else original mblk is returned
6696 		 */
6697 		ASSERT(recv_ill != NULL);
6698 		mp = ip_add_info(mp, recv_ill, in_flags);
6699 	}
6700 	BUMP_MIB(&ip_mib, ipInDelivers);
6701 
6702 	/* Send it upstream */
6703 	CONN_UDP_RECV(connp, mp);
6704 }
6705 
6706 /*
6707  * Fanout for UDP packets.
6708  * The caller puts <fport, lport> in the ports parameter.
6709  *
6710  * If SO_REUSEADDR is set all multicast and broadcast packets
6711  * will be delivered to all streams bound to the same port.
6712  *
6713  * Zones notes:
6714  * Multicast and broadcast packets will be distributed to streams in all zones.
6715  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6716  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6717  * packets. To maintain this behavior with multiple zones, the conns are grouped
6718  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6719  * each zone. If unset, all the following conns in the same zone are skipped.
6720  */
6721 static void
6722 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6723     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6724     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6725 {
6726 	uint32_t	dstport, srcport;
6727 	ipaddr_t	dst;
6728 	mblk_t		*first_mp;
6729 	boolean_t	secure;
6730 	in6_addr_t	v6src;
6731 	conn_t		*connp;
6732 	connf_t		*connfp;
6733 	conn_t		*first_connp;
6734 	conn_t		*next_connp;
6735 	mblk_t		*mp1, *first_mp1;
6736 	ipaddr_t	src;
6737 	zoneid_t	last_zoneid;
6738 	boolean_t	reuseaddr;
6739 	boolean_t	shared_addr;
6740 
6741 	first_mp = mp;
6742 	if (mctl_present) {
6743 		mp = first_mp->b_cont;
6744 		first_mp->b_cont = NULL;
6745 		secure = ipsec_in_is_secure(first_mp);
6746 		ASSERT(mp != NULL);
6747 	} else {
6748 		first_mp = NULL;
6749 		secure = B_FALSE;
6750 	}
6751 
6752 	/* Extract ports in net byte order */
6753 	dstport = htons(ntohl(ports) & 0xFFFF);
6754 	srcport = htons(ntohl(ports) >> 16);
6755 	dst = ipha->ipha_dst;
6756 	src = ipha->ipha_src;
6757 
6758 	shared_addr = (zoneid == ALL_ZONES);
6759 	if (shared_addr) {
6760 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6761 		if (zoneid == ALL_ZONES)
6762 			zoneid = tsol_packet_to_zoneid(mp);
6763 	}
6764 
6765 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6766 	mutex_enter(&connfp->connf_lock);
6767 	connp = connfp->connf_head;
6768 	if (!broadcast && !CLASSD(dst)) {
6769 		/*
6770 		 * Not broadcast or multicast. Send to the one (first)
6771 		 * client we find. No need to check conn_wantpacket()
6772 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6773 		 * IPv4 unicast packets.
6774 		 */
6775 		while ((connp != NULL) &&
6776 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6777 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6778 			connp = connp->conn_next;
6779 		}
6780 
6781 		if (connp == NULL || connp->conn_upq == NULL)
6782 			goto notfound;
6783 
6784 		if (is_system_labeled() &&
6785 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6786 		    connp))
6787 			goto notfound;
6788 
6789 		CONN_INC_REF(connp);
6790 		mutex_exit(&connfp->connf_lock);
6791 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6792 		    recv_ill, ip_policy);
6793 		IP_STAT(ip_udp_fannorm);
6794 		CONN_DEC_REF(connp);
6795 		return;
6796 	}
6797 
6798 	/*
6799 	 * Broadcast and multicast case
6800 	 *
6801 	 * Need to check conn_wantpacket().
6802 	 * If SO_REUSEADDR has been set on the first we send the
6803 	 * packet to all clients that have joined the group and
6804 	 * match the port.
6805 	 */
6806 
6807 	while (connp != NULL) {
6808 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
6809 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6810 		    (!is_system_labeled() ||
6811 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6812 		    connp)))
6813 			break;
6814 		connp = connp->conn_next;
6815 	}
6816 
6817 	if (connp == NULL || connp->conn_upq == NULL)
6818 		goto notfound;
6819 
6820 	first_connp = connp;
6821 	/*
6822 	 * When SO_REUSEADDR is not set, send the packet only to the first
6823 	 * matching connection in its zone by keeping track of the zoneid.
6824 	 */
6825 	reuseaddr = first_connp->conn_reuseaddr;
6826 	last_zoneid = first_connp->conn_zoneid;
6827 
6828 	CONN_INC_REF(connp);
6829 	connp = connp->conn_next;
6830 	for (;;) {
6831 		while (connp != NULL) {
6832 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
6833 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
6834 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6835 			    (!is_system_labeled() ||
6836 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6837 			    shared_addr, connp)))
6838 				break;
6839 			connp = connp->conn_next;
6840 		}
6841 		/*
6842 		 * Just copy the data part alone. The mctl part is
6843 		 * needed just for verifying policy and it is never
6844 		 * sent up.
6845 		 */
6846 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
6847 		    ((mp1 = copymsg(mp)) == NULL))) {
6848 			/*
6849 			 * No more interested clients or memory
6850 			 * allocation failed
6851 			 */
6852 			connp = first_connp;
6853 			break;
6854 		}
6855 		if (connp->conn_zoneid != last_zoneid) {
6856 			/*
6857 			 * Update the zoneid so that the packet isn't sent to
6858 			 * any more conns in the same zone unless SO_REUSEADDR
6859 			 * is set.
6860 			 */
6861 			reuseaddr = connp->conn_reuseaddr;
6862 			last_zoneid = connp->conn_zoneid;
6863 		}
6864 		if (first_mp != NULL) {
6865 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
6866 			    ipsec_info_type == IPSEC_IN);
6867 			first_mp1 = ipsec_in_tag(first_mp, NULL);
6868 			if (first_mp1 == NULL) {
6869 				freemsg(mp1);
6870 				connp = first_connp;
6871 				break;
6872 			}
6873 		} else {
6874 			first_mp1 = NULL;
6875 		}
6876 		CONN_INC_REF(connp);
6877 		mutex_exit(&connfp->connf_lock);
6878 		/*
6879 		 * IPQoS notes: We don't send the packet for policy
6880 		 * processing here, will do it for the last one (below).
6881 		 * i.e. we do it per-packet now, but if we do policy
6882 		 * processing per-conn, then we would need to do it
6883 		 * here too.
6884 		 */
6885 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
6886 		    ipha, flags, recv_ill, B_FALSE);
6887 		mutex_enter(&connfp->connf_lock);
6888 		/* Follow the next pointer before releasing the conn. */
6889 		next_connp = connp->conn_next;
6890 		IP_STAT(ip_udp_fanmb);
6891 		CONN_DEC_REF(connp);
6892 		connp = next_connp;
6893 	}
6894 
6895 	/* Last one.  Send it upstream. */
6896 	mutex_exit(&connfp->connf_lock);
6897 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
6898 	    ip_policy);
6899 	IP_STAT(ip_udp_fanmb);
6900 	CONN_DEC_REF(connp);
6901 	return;
6902 
6903 notfound:
6904 
6905 	mutex_exit(&connfp->connf_lock);
6906 	IP_STAT(ip_udp_fanothers);
6907 	/*
6908 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
6909 	 * have already been matched above, since they live in the IPv4
6910 	 * fanout tables. This implies we only need to
6911 	 * check for IPv6 in6addr_any endpoints here.
6912 	 * Thus we compare using ipv6_all_zeros instead of the destination
6913 	 * address, except for the multicast group membership lookup which
6914 	 * uses the IPv4 destination.
6915 	 */
6916 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
6917 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6918 	mutex_enter(&connfp->connf_lock);
6919 	connp = connfp->connf_head;
6920 	if (!broadcast && !CLASSD(dst)) {
6921 		while (connp != NULL) {
6922 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6923 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
6924 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6925 			    !connp->conn_ipv6_v6only)
6926 				break;
6927 			connp = connp->conn_next;
6928 		}
6929 
6930 		if (connp != NULL && is_system_labeled() &&
6931 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6932 		    connp))
6933 			connp = NULL;
6934 
6935 		if (connp == NULL || connp->conn_upq == NULL) {
6936 			/*
6937 			 * No one bound to this port.  Is
6938 			 * there a client that wants all
6939 			 * unclaimed datagrams?
6940 			 */
6941 			mutex_exit(&connfp->connf_lock);
6942 
6943 			if (mctl_present)
6944 				first_mp->b_cont = mp;
6945 			else
6946 				first_mp = mp;
6947 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
6948 				ip_fanout_proto(q, first_mp, ill, ipha,
6949 				    flags | IP_FF_RAWIP, mctl_present,
6950 				    ip_policy, recv_ill, zoneid);
6951 			} else {
6952 				if (ip_fanout_send_icmp(q, first_mp, flags,
6953 				    ICMP_DEST_UNREACHABLE,
6954 				    ICMP_PORT_UNREACHABLE,
6955 				    mctl_present, zoneid)) {
6956 					BUMP_MIB(&ip_mib, udpNoPorts);
6957 				}
6958 			}
6959 			return;
6960 		}
6961 
6962 		CONN_INC_REF(connp);
6963 		mutex_exit(&connfp->connf_lock);
6964 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags,
6965 		    recv_ill, ip_policy);
6966 		CONN_DEC_REF(connp);
6967 		return;
6968 	}
6969 	/*
6970 	 * IPv4 multicast packet being delivered to an AF_INET6
6971 	 * in6addr_any endpoint.
6972 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
6973 	 * and not conn_wantpacket_v6() since any multicast membership is
6974 	 * for an IPv4-mapped multicast address.
6975 	 * The packet is sent to all clients in all zones that have joined the
6976 	 * group and match the port.
6977 	 */
6978 	while (connp != NULL) {
6979 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
6980 		    srcport, v6src) &&
6981 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
6982 		    (!is_system_labeled() ||
6983 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6984 		    connp)))
6985 			break;
6986 		connp = connp->conn_next;
6987 	}
6988 
6989 	if (connp == NULL || connp->conn_upq == NULL) {
6990 		/*
6991 		 * No one bound to this port.  Is
6992 		 * there a client that wants all
6993 		 * unclaimed datagrams?
6994 		 */
6995 		mutex_exit(&connfp->connf_lock);
6996 
6997 		if (mctl_present)
6998 			first_mp->b_cont = mp;
6999 		else
7000 			first_mp = mp;
7001 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7002 			ip_fanout_proto(q, first_mp, ill, ipha,
7003 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7004 			    recv_ill, zoneid);
7005 		} else {
7006 			/*
7007 			 * We used to attempt to send an icmp error here, but
7008 			 * since this is known to be a multicast packet
7009 			 * and we don't send icmp errors in response to
7010 			 * multicast, just drop the packet and give up sooner.
7011 			 */
7012 			BUMP_MIB(&ip_mib, udpNoPorts);
7013 			freemsg(first_mp);
7014 		}
7015 		return;
7016 	}
7017 
7018 	first_connp = connp;
7019 
7020 	CONN_INC_REF(connp);
7021 	connp = connp->conn_next;
7022 	for (;;) {
7023 		while (connp != NULL) {
7024 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7025 			    ipv6_all_zeros, srcport, v6src) &&
7026 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7027 			    (!is_system_labeled() ||
7028 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7029 			    shared_addr, connp)))
7030 				break;
7031 			connp = connp->conn_next;
7032 		}
7033 		/*
7034 		 * Just copy the data part alone. The mctl part is
7035 		 * needed just for verifying policy and it is never
7036 		 * sent up.
7037 		 */
7038 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7039 		    ((mp1 = copymsg(mp)) == NULL))) {
7040 			/*
7041 			 * No more intested clients or memory
7042 			 * allocation failed
7043 			 */
7044 			connp = first_connp;
7045 			break;
7046 		}
7047 		if (first_mp != NULL) {
7048 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7049 			    ipsec_info_type == IPSEC_IN);
7050 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7051 			if (first_mp1 == NULL) {
7052 				freemsg(mp1);
7053 				connp = first_connp;
7054 				break;
7055 			}
7056 		} else {
7057 			first_mp1 = NULL;
7058 		}
7059 		CONN_INC_REF(connp);
7060 		mutex_exit(&connfp->connf_lock);
7061 		/*
7062 		 * IPQoS notes: We don't send the packet for policy
7063 		 * processing here, will do it for the last one (below).
7064 		 * i.e. we do it per-packet now, but if we do policy
7065 		 * processing per-conn, then we would need to do it
7066 		 * here too.
7067 		 */
7068 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure,
7069 		    ipha, flags, recv_ill, B_FALSE);
7070 		mutex_enter(&connfp->connf_lock);
7071 		/* Follow the next pointer before releasing the conn. */
7072 		next_connp = connp->conn_next;
7073 		CONN_DEC_REF(connp);
7074 		connp = next_connp;
7075 	}
7076 
7077 	/* Last one.  Send it upstream. */
7078 	mutex_exit(&connfp->connf_lock);
7079 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ipha, flags, recv_ill,
7080 	    ip_policy);
7081 	CONN_DEC_REF(connp);
7082 }
7083 
7084 /*
7085  * Complete the ip_wput header so that it
7086  * is possible to generate ICMP
7087  * errors.
7088  */
7089 int
7090 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7091 {
7092 	ire_t *ire;
7093 
7094 	if (ipha->ipha_src == INADDR_ANY) {
7095 		ire = ire_lookup_local(zoneid);
7096 		if (ire == NULL) {
7097 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7098 			return (1);
7099 		}
7100 		ipha->ipha_src = ire->ire_addr;
7101 		ire_refrele(ire);
7102 	}
7103 	ipha->ipha_ttl = ip_def_ttl;
7104 	ipha->ipha_hdr_checksum = 0;
7105 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7106 	return (0);
7107 }
7108 
7109 /*
7110  * Nobody should be sending
7111  * packets up this stream
7112  */
7113 static void
7114 ip_lrput(queue_t *q, mblk_t *mp)
7115 {
7116 	mblk_t *mp1;
7117 
7118 	switch (mp->b_datap->db_type) {
7119 	case M_FLUSH:
7120 		/* Turn around */
7121 		if (*mp->b_rptr & FLUSHW) {
7122 			*mp->b_rptr &= ~FLUSHR;
7123 			qreply(q, mp);
7124 			return;
7125 		}
7126 		break;
7127 	}
7128 	/* Could receive messages that passed through ar_rput */
7129 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7130 		mp1->b_prev = mp1->b_next = NULL;
7131 	freemsg(mp);
7132 }
7133 
7134 /* Nobody should be sending packets down this stream */
7135 /* ARGSUSED */
7136 void
7137 ip_lwput(queue_t *q, mblk_t *mp)
7138 {
7139 	freemsg(mp);
7140 }
7141 
7142 /*
7143  * Move the first hop in any source route to ipha_dst and remove that part of
7144  * the source route.  Called by other protocols.  Errors in option formatting
7145  * are ignored - will be handled by ip_wput_options Return the final
7146  * destination (either ipha_dst or the last entry in a source route.)
7147  */
7148 ipaddr_t
7149 ip_massage_options(ipha_t *ipha)
7150 {
7151 	ipoptp_t	opts;
7152 	uchar_t		*opt;
7153 	uint8_t		optval;
7154 	uint8_t		optlen;
7155 	ipaddr_t	dst;
7156 	int		i;
7157 	ire_t		*ire;
7158 
7159 	ip2dbg(("ip_massage_options\n"));
7160 	dst = ipha->ipha_dst;
7161 	for (optval = ipoptp_first(&opts, ipha);
7162 	    optval != IPOPT_EOL;
7163 	    optval = ipoptp_next(&opts)) {
7164 		opt = opts.ipoptp_cur;
7165 		switch (optval) {
7166 			uint8_t off;
7167 		case IPOPT_SSRR:
7168 		case IPOPT_LSRR:
7169 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7170 				ip1dbg(("ip_massage_options: bad src route\n"));
7171 				break;
7172 			}
7173 			optlen = opts.ipoptp_len;
7174 			off = opt[IPOPT_OFFSET];
7175 			off--;
7176 		redo_srr:
7177 			if (optlen < IP_ADDR_LEN ||
7178 			    off > optlen - IP_ADDR_LEN) {
7179 				/* End of source route */
7180 				ip1dbg(("ip_massage_options: end of SR\n"));
7181 				break;
7182 			}
7183 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7184 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7185 			    ntohl(dst)));
7186 			/*
7187 			 * Check if our address is present more than
7188 			 * once as consecutive hops in source route.
7189 			 * XXX verify per-interface ip_forwarding
7190 			 * for source route?
7191 			 */
7192 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7193 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7194 			if (ire != NULL) {
7195 				ire_refrele(ire);
7196 				off += IP_ADDR_LEN;
7197 				goto redo_srr;
7198 			}
7199 			if (dst == htonl(INADDR_LOOPBACK)) {
7200 				ip1dbg(("ip_massage_options: loopback addr in "
7201 				    "source route!\n"));
7202 				break;
7203 			}
7204 			/*
7205 			 * Update ipha_dst to be the first hop and remove the
7206 			 * first hop from the source route (by overwriting
7207 			 * part of the option with NOP options).
7208 			 */
7209 			ipha->ipha_dst = dst;
7210 			/* Put the last entry in dst */
7211 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7212 			    3;
7213 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7214 
7215 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7216 			    ntohl(dst)));
7217 			/* Move down and overwrite */
7218 			opt[IP_ADDR_LEN] = opt[0];
7219 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7220 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7221 			for (i = 0; i < IP_ADDR_LEN; i++)
7222 				opt[i] = IPOPT_NOP;
7223 			break;
7224 		}
7225 	}
7226 	return (dst);
7227 }
7228 
7229 /*
7230  * This function's job is to forward data to the reverse tunnel (FA->HA)
7231  * after doing a few checks. It is assumed that the incoming interface
7232  * of the packet is always different than the outgoing interface and the
7233  * ire_type of the found ire has to be a non-resolver type.
7234  *
7235  * IPQoS notes
7236  * IP policy is invoked twice for a forwarded packet, once on the read side
7237  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7238  * enabled.
7239  */
7240 static void
7241 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7242 {
7243 	ipha_t		*ipha;
7244 	queue_t		*q;
7245 	uint32_t 	pkt_len;
7246 #define	rptr    ((uchar_t *)ipha)
7247 	uint32_t 	sum;
7248 	uint32_t 	max_frag;
7249 	mblk_t		*first_mp;
7250 	uint32_t	ill_index;
7251 	ipxmit_state_t	pktxmit_state;
7252 	ill_t		*out_ill;
7253 
7254 	ASSERT(ire != NULL);
7255 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7256 	ASSERT(ire->ire_stq != NULL);
7257 
7258 	/* Initiate read side IPPF processing */
7259 	if (IPP_ENABLED(IPP_FWD_IN)) {
7260 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7261 		ip_process(IPP_FWD_IN, &mp, ill_index);
7262 		if (mp == NULL) {
7263 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7264 			    "dropped during IPPF processing\n"));
7265 			return;
7266 		}
7267 	}
7268 
7269 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7270 		ILLF_ROUTER) == 0) ||
7271 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7272 		BUMP_MIB(&ip_mib, ipForwProhibits);
7273 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7274 		    "forwarding is not turned on\n"));
7275 		goto drop_pkt;
7276 	}
7277 
7278 	/*
7279 	 * Don't forward if the interface is down
7280 	 */
7281 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7282 		BUMP_MIB(&ip_mib, ipInDiscards);
7283 		goto drop_pkt;
7284 	}
7285 
7286 	ipha = (ipha_t *)mp->b_rptr;
7287 	pkt_len = ntohs(ipha->ipha_length);
7288 	/* Adjust the checksum to reflect the ttl decrement. */
7289 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7290 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7291 	if (ipha->ipha_ttl-- <= 1) {
7292 		if (ip_csum_hdr(ipha)) {
7293 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7294 			goto drop_pkt;
7295 		}
7296 		q = ire->ire_stq;
7297 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7298 		    BPRI_HI)) == NULL) {
7299 			goto drop_pkt;
7300 		}
7301 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7302 		/* Sent by forwarding path, and router is global zone */
7303 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7304 		    GLOBAL_ZONEID);
7305 		return;
7306 	}
7307 
7308 	/* Get the ill_index of the ILL */
7309 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7310 
7311 	/*
7312 	 * This location is chosen for the placement of the forwarding hook
7313 	 * because at this point we know that we have a path out for the
7314 	 * packet but haven't yet applied any logic (such as fragmenting)
7315 	 * that happen as part of transmitting the packet out.
7316 	 */
7317 	out_ill = ire->ire_ipif->ipif_ill;
7318 
7319 	DTRACE_PROBE4(ip4__forwarding__start,
7320 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7321 
7322 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7323 	    in_ill, out_ill, ipha, mp, mp);
7324 
7325 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7326 
7327 	if (mp == NULL)
7328 		return;
7329 	pkt_len = ntohs(ipha->ipha_length);
7330 
7331 	/*
7332 	 * ip_mrtun_forward is only used by foreign agent to reverse
7333 	 * tunnel the incoming packet. So it does not do any option
7334 	 * processing for source routing.
7335 	 */
7336 	max_frag = ire->ire_max_frag;
7337 	if (pkt_len > max_frag) {
7338 		/*
7339 		 * It needs fragging on its way out.  We haven't
7340 		 * verified the header checksum yet.  Since we
7341 		 * are going to put a surely good checksum in the
7342 		 * outgoing header, we have to make sure that it
7343 		 * was good coming in.
7344 		 */
7345 		if (ip_csum_hdr(ipha)) {
7346 			BUMP_MIB(&ip_mib, ipInCksumErrs);
7347 			goto drop_pkt;
7348 		}
7349 
7350 		/* Initiate write side IPPF processing */
7351 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7352 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7353 			if (mp == NULL) {
7354 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7355 				    "dropped/deferred during ip policy "\
7356 				    "processing\n"));
7357 				return;
7358 			}
7359 		}
7360 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7361 		    BPRI_HI)) == NULL) {
7362 			goto drop_pkt;
7363 		}
7364 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7365 		mp = first_mp;
7366 
7367 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7368 		return;
7369 	}
7370 
7371 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7372 
7373 	ASSERT(ire->ire_ipif != NULL);
7374 
7375 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7376 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7377 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7378 	    NULL, out_ill, ipha, mp, mp);
7379 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7380 	if (mp == NULL)
7381 		return;
7382 
7383 	/* Now send the packet to the tunnel interface */
7384 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7385 	q = ire->ire_stq;
7386 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7387 	if ((pktxmit_state == SEND_FAILED) ||
7388 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7389 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7390 		    q->q_ptr));
7391 	}
7392 
7393 	return;
7394 
7395 drop_pkt:;
7396 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7397 	freemsg(mp);
7398 #undef	rptr
7399 }
7400 
7401 /*
7402  * Fills the ipsec_out_t data structure with appropriate fields and
7403  * prepends it to mp which contains the IP hdr + data that was meant
7404  * to be forwarded. Please note that ipsec_out_info data structure
7405  * is used here to communicate the outgoing ill path at ip_wput()
7406  * for the ICMP error packet. This has nothing to do with ipsec IP
7407  * security. ipsec_out_t is really used to pass the info to the module
7408  * IP where this information cannot be extracted from conn.
7409  * This functions is called by ip_mrtun_forward().
7410  */
7411 void
7412 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7413 {
7414 	ipsec_out_t	*io;
7415 
7416 	ASSERT(xmit_ill != NULL);
7417 	first_mp->b_datap->db_type = M_CTL;
7418 	first_mp->b_wptr += sizeof (ipsec_info_t);
7419 	/*
7420 	 * This is to pass info to ip_wput in absence of conn.
7421 	 * ipsec_out_secure will be B_FALSE because of this.
7422 	 * Thus ipsec_out_secure being B_FALSE indicates that
7423 	 * this is not IPSEC security related information.
7424 	 */
7425 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7426 	io = (ipsec_out_t *)first_mp->b_rptr;
7427 	io->ipsec_out_type = IPSEC_OUT;
7428 	io->ipsec_out_len = sizeof (ipsec_out_t);
7429 	first_mp->b_cont = mp;
7430 	io->ipsec_out_ill_index =
7431 	    xmit_ill->ill_phyint->phyint_ifindex;
7432 	io->ipsec_out_xmit_if = B_TRUE;
7433 }
7434 
7435 /*
7436  * Return the network mask
7437  * associated with the specified address.
7438  */
7439 ipaddr_t
7440 ip_net_mask(ipaddr_t addr)
7441 {
7442 	uchar_t	*up = (uchar_t *)&addr;
7443 	ipaddr_t mask = 0;
7444 	uchar_t	*maskp = (uchar_t *)&mask;
7445 
7446 #if defined(__i386) || defined(__amd64)
7447 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7448 #endif
7449 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7450 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7451 #endif
7452 	if (CLASSD(addr)) {
7453 		maskp[0] = 0xF0;
7454 		return (mask);
7455 	}
7456 	if (addr == 0)
7457 		return (0);
7458 	maskp[0] = 0xFF;
7459 	if ((up[0] & 0x80) == 0)
7460 		return (mask);
7461 
7462 	maskp[1] = 0xFF;
7463 	if ((up[0] & 0xC0) == 0x80)
7464 		return (mask);
7465 
7466 	maskp[2] = 0xFF;
7467 	if ((up[0] & 0xE0) == 0xC0)
7468 		return (mask);
7469 
7470 	/* Must be experimental or multicast, indicate as much */
7471 	return ((ipaddr_t)0);
7472 }
7473 
7474 /*
7475  * Select an ill for the packet by considering load spreading across
7476  * a different ill in the group if dst_ill is part of some group.
7477  */
7478 ill_t *
7479 ip_newroute_get_dst_ill(ill_t *dst_ill)
7480 {
7481 	ill_t *ill;
7482 
7483 	/*
7484 	 * We schedule irrespective of whether the source address is
7485 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7486 	 */
7487 	ill = illgrp_scheduler(dst_ill);
7488 	if (ill == NULL)
7489 		return (NULL);
7490 
7491 	/*
7492 	 * For groups with names ip_sioctl_groupname ensures that all
7493 	 * ills are of same type. For groups without names, ifgrp_insert
7494 	 * ensures this.
7495 	 */
7496 	ASSERT(dst_ill->ill_type == ill->ill_type);
7497 
7498 	return (ill);
7499 }
7500 
7501 /*
7502  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7503  */
7504 ill_t *
7505 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7506 {
7507 	ill_t *ret_ill;
7508 
7509 	ASSERT(ifindex != 0);
7510 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7511 	if (ret_ill == NULL ||
7512 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7513 		if (isv6) {
7514 			if (ill != NULL) {
7515 				BUMP_MIB(ill->ill_ip6_mib, ipv6OutDiscards);
7516 			} else {
7517 				BUMP_MIB(&ip6_mib, ipv6OutDiscards);
7518 			}
7519 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7520 			    "bad ifindex %d.\n", ifindex));
7521 		} else {
7522 			BUMP_MIB(&ip_mib, ipOutDiscards);
7523 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7524 			    "bad ifindex %d.\n", ifindex));
7525 		}
7526 		if (ret_ill != NULL)
7527 			ill_refrele(ret_ill);
7528 		freemsg(first_mp);
7529 		return (NULL);
7530 	}
7531 
7532 	return (ret_ill);
7533 }
7534 
7535 /*
7536  * IPv4 -
7537  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7538  * out a packet to a destination address for which we do not have specific
7539  * (or sufficient) routing information.
7540  *
7541  * NOTE : These are the scopes of some of the variables that point at IRE,
7542  *	  which needs to be followed while making any future modifications
7543  *	  to avoid memory leaks.
7544  *
7545  *	- ire and sire are the entries looked up initially by
7546  *	  ire_ftable_lookup.
7547  *	- ipif_ire is used to hold the interface ire associated with
7548  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7549  *	  it before branching out to error paths.
7550  *	- save_ire is initialized before ire_create, so that ire returned
7551  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7552  *	  before breaking out of the switch.
7553  *
7554  *	Thus on failures, we have to REFRELE only ire and sire, if they
7555  *	are not NULL.
7556  */
7557 void
7558 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7559     zoneid_t zoneid)
7560 {
7561 	areq_t	*areq;
7562 	ipaddr_t gw = 0;
7563 	ire_t	*ire = NULL;
7564 	mblk_t	*res_mp;
7565 	ipaddr_t *addrp;
7566 	ipaddr_t nexthop_addr;
7567 	ipif_t  *src_ipif = NULL;
7568 	ill_t	*dst_ill = NULL;
7569 	ipha_t  *ipha;
7570 	ire_t	*sire = NULL;
7571 	mblk_t	*first_mp;
7572 	ire_t	*save_ire;
7573 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7574 	ushort_t ire_marks = 0;
7575 	boolean_t mctl_present;
7576 	ipsec_out_t *io;
7577 	mblk_t	*saved_mp;
7578 	ire_t	*first_sire = NULL;
7579 	mblk_t	*copy_mp = NULL;
7580 	mblk_t	*xmit_mp = NULL;
7581 	ipaddr_t save_dst;
7582 	uint32_t multirt_flags =
7583 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7584 	boolean_t multirt_is_resolvable;
7585 	boolean_t multirt_resolve_next;
7586 	boolean_t do_attach_ill = B_FALSE;
7587 	boolean_t ip_nexthop = B_FALSE;
7588 	tsol_ire_gw_secattr_t *attrp = NULL;
7589 	tsol_gcgrp_t *gcgrp = NULL;
7590 	tsol_gcgrp_addr_t ga;
7591 
7592 	if (ip_debug > 2) {
7593 		/* ip1dbg */
7594 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7595 	}
7596 
7597 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7598 	if (mctl_present) {
7599 		io = (ipsec_out_t *)first_mp->b_rptr;
7600 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7601 		ASSERT(zoneid == io->ipsec_out_zoneid);
7602 		ASSERT(zoneid != ALL_ZONES);
7603 	}
7604 
7605 	ipha = (ipha_t *)mp->b_rptr;
7606 
7607 	/* All multicast lookups come through ip_newroute_ipif() */
7608 	if (CLASSD(dst)) {
7609 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7610 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7611 		freemsg(first_mp);
7612 		return;
7613 	}
7614 
7615 	if (mctl_present && io->ipsec_out_attach_if) {
7616 		/* ip_grab_attach_ill returns a held ill */
7617 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7618 		    io->ipsec_out_ill_index, B_FALSE);
7619 
7620 		/* Failure case frees things for us. */
7621 		if (attach_ill == NULL)
7622 			return;
7623 
7624 		/*
7625 		 * Check if we need an ire that will not be
7626 		 * looked up by anybody else i.e. HIDDEN.
7627 		 */
7628 		if (ill_is_probeonly(attach_ill))
7629 			ire_marks = IRE_MARK_HIDDEN;
7630 	}
7631 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7632 		ip_nexthop = B_TRUE;
7633 		nexthop_addr = io->ipsec_out_nexthop_addr;
7634 	}
7635 	/*
7636 	 * If this IRE is created for forwarding or it is not for
7637 	 * traffic for congestion controlled protocols, mark it as temporary.
7638 	 */
7639 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7640 		ire_marks |= IRE_MARK_TEMPORARY;
7641 
7642 	/*
7643 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7644 	 * chain until it gets the most specific information available.
7645 	 * For example, we know that there is no IRE_CACHE for this dest,
7646 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7647 	 * ire_ftable_lookup will look up the gateway, etc.
7648 	 * Check if in_ill != NULL. If it is true, the packet must be
7649 	 * from an incoming interface where RTA_SRCIFP is set.
7650 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7651 	 * to the destination, of equal netmask length in the forward table,
7652 	 * will be recursively explored. If no information is available
7653 	 * for the final gateway of that route, we force the returned ire
7654 	 * to be equal to sire using MATCH_IRE_PARENT.
7655 	 * At least, in this case we have a starting point (in the buckets)
7656 	 * to look for other routes to the destination in the forward table.
7657 	 * This is actually used only for multirouting, where a list
7658 	 * of routes has to be processed in sequence.
7659 	 *
7660 	 * In the process of coming up with the most specific information,
7661 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7662 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7663 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7664 	 * Two caveats when handling incomplete ire's in ip_newroute:
7665 	 * - we should be careful when accessing its ire_nce (specifically
7666 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7667 	 * - not all legacy code path callers are prepared to handle
7668 	 *   incomplete ire's, so we should not create/add incomplete
7669 	 *   ire_cache entries here. (See discussion about temporary solution
7670 	 *   further below).
7671 	 *
7672 	 * In order to minimize packet dropping, and to preserve existing
7673 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7674 	 * gateway, and instead use the IF_RESOLVER ire to send out
7675 	 * another request to ARP (this is achieved by passing the
7676 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7677 	 * arp response comes back in ip_wput_nondata, we will create
7678 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7679 	 *
7680 	 * Note that this is a temporary solution; the correct solution is
7681 	 * to create an incomplete  per-dst ire_cache entry, and send the
7682 	 * packet out when the gw's nce is resolved. In order to achieve this,
7683 	 * all packet processing must have been completed prior to calling
7684 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7685 	 * to be modified to accomodate this solution.
7686 	 */
7687 	if (in_ill != NULL) {
7688 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7689 		    in_ill, MATCH_IRE_TYPE);
7690 	} else if (ip_nexthop) {
7691 		/*
7692 		 * The first time we come here, we look for an IRE_INTERFACE
7693 		 * entry for the specified nexthop, set the dst to be the
7694 		 * nexthop address and create an IRE_CACHE entry for the
7695 		 * nexthop. The next time around, we are able to find an
7696 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7697 		 * nexthop address and create an IRE_CACHE entry for the
7698 		 * destination address via the specified nexthop.
7699 		 */
7700 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7701 		    MBLK_GETLABEL(mp));
7702 		if (ire != NULL) {
7703 			gw = nexthop_addr;
7704 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7705 		} else {
7706 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7707 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7708 			    MBLK_GETLABEL(mp),
7709 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7710 			if (ire != NULL) {
7711 				dst = nexthop_addr;
7712 			}
7713 		}
7714 	} else if (attach_ill == NULL) {
7715 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7716 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7717 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7718 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7719 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7720 	} else {
7721 		/*
7722 		 * attach_ill is set only for communicating with
7723 		 * on-link hosts. So, don't look for DEFAULT.
7724 		 */
7725 		ipif_t	*attach_ipif;
7726 
7727 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7728 		if (attach_ipif == NULL) {
7729 			ill_refrele(attach_ill);
7730 			goto icmp_err_ret;
7731 		}
7732 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7733 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7734 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7735 		    MATCH_IRE_SECATTR);
7736 		ipif_refrele(attach_ipif);
7737 	}
7738 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7739 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7740 
7741 	/*
7742 	 * This loop is run only once in most cases.
7743 	 * We loop to resolve further routes only when the destination
7744 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7745 	 */
7746 	do {
7747 		/* Clear the previous iteration's values */
7748 		if (src_ipif != NULL) {
7749 			ipif_refrele(src_ipif);
7750 			src_ipif = NULL;
7751 		}
7752 		if (dst_ill != NULL) {
7753 			ill_refrele(dst_ill);
7754 			dst_ill = NULL;
7755 		}
7756 
7757 		multirt_resolve_next = B_FALSE;
7758 		/*
7759 		 * We check if packets have to be multirouted.
7760 		 * In this case, given the current <ire, sire> couple,
7761 		 * we look for the next suitable <ire, sire>.
7762 		 * This check is done in ire_multirt_lookup(),
7763 		 * which applies various criteria to find the next route
7764 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7765 		 * unchanged if it detects it has not been tried yet.
7766 		 */
7767 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7768 			ip3dbg(("ip_newroute: starting next_resolution "
7769 			    "with first_mp %p, tag %d\n",
7770 			    (void *)first_mp,
7771 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7772 
7773 			ASSERT(sire != NULL);
7774 			multirt_is_resolvable =
7775 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7776 				MBLK_GETLABEL(mp));
7777 
7778 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7779 			    "ire %p, sire %p\n",
7780 			    multirt_is_resolvable,
7781 			    (void *)ire, (void *)sire));
7782 
7783 			if (!multirt_is_resolvable) {
7784 				/*
7785 				 * No more multirt route to resolve; give up
7786 				 * (all routes resolved or no more
7787 				 * resolvable routes).
7788 				 */
7789 				if (ire != NULL) {
7790 					ire_refrele(ire);
7791 					ire = NULL;
7792 				}
7793 			} else {
7794 				ASSERT(sire != NULL);
7795 				ASSERT(ire != NULL);
7796 				/*
7797 				 * We simply use first_sire as a flag that
7798 				 * indicates if a resolvable multirt route
7799 				 * has already been found.
7800 				 * If it is not the case, we may have to send
7801 				 * an ICMP error to report that the
7802 				 * destination is unreachable.
7803 				 * We do not IRE_REFHOLD first_sire.
7804 				 */
7805 				if (first_sire == NULL) {
7806 					first_sire = sire;
7807 				}
7808 			}
7809 		}
7810 		if (ire == NULL) {
7811 			if (ip_debug > 3) {
7812 				/* ip2dbg */
7813 				pr_addr_dbg("ip_newroute: "
7814 				    "can't resolve %s\n", AF_INET, &dst);
7815 			}
7816 			ip3dbg(("ip_newroute: "
7817 			    "ire %p, sire %p, first_sire %p\n",
7818 			    (void *)ire, (void *)sire, (void *)first_sire));
7819 
7820 			if (sire != NULL) {
7821 				ire_refrele(sire);
7822 				sire = NULL;
7823 			}
7824 
7825 			if (first_sire != NULL) {
7826 				/*
7827 				 * At least one multirt route has been found
7828 				 * in the same call to ip_newroute();
7829 				 * there is no need to report an ICMP error.
7830 				 * first_sire was not IRE_REFHOLDed.
7831 				 */
7832 				MULTIRT_DEBUG_UNTAG(first_mp);
7833 				freemsg(first_mp);
7834 				return;
7835 			}
7836 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7837 			    RTA_DST);
7838 			if (attach_ill != NULL)
7839 				ill_refrele(attach_ill);
7840 			goto icmp_err_ret;
7841 		}
7842 
7843 		/*
7844 		 * When RTA_SRCIFP is used to add a route, then an interface
7845 		 * route is added in the source interface's routing table.
7846 		 * If the outgoing interface of this route is of type
7847 		 * IRE_IF_RESOLVER, then upon creation of the ire,
7848 		 * ire_nce->nce_res_mp is set to NULL.
7849 		 * Later, when this route is first used for forwarding
7850 		 * a packet, ip_newroute() is called
7851 		 * to resolve the hardware address of the outgoing ipif.
7852 		 * We do not come here for IRE_IF_NORESOLVER entries in the
7853 		 * source interface based table. We only come here if the
7854 		 * outgoing interface is a resolver interface and we don't
7855 		 * have the ire_nce->nce_res_mp information yet.
7856 		 * If in_ill is not null that means it is called from
7857 		 * ip_rput.
7858 		 */
7859 
7860 		ASSERT(ire->ire_in_ill == NULL ||
7861 		    (ire->ire_type == IRE_IF_RESOLVER &&
7862 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
7863 
7864 		/*
7865 		 * Verify that the returned IRE does not have either
7866 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7867 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7868 		 */
7869 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7870 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7871 			if (attach_ill != NULL)
7872 				ill_refrele(attach_ill);
7873 			goto icmp_err_ret;
7874 		}
7875 		/*
7876 		 * Increment the ire_ob_pkt_count field for ire if it is an
7877 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7878 		 * increment the same for the parent IRE, sire, if it is some
7879 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
7880 		 * and HOST_REDIRECT).
7881 		 */
7882 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7883 			UPDATE_OB_PKT_COUNT(ire);
7884 			ire->ire_last_used_time = lbolt;
7885 		}
7886 
7887 		if (sire != NULL) {
7888 			gw = sire->ire_gateway_addr;
7889 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7890 			    IRE_INTERFACE)) == 0);
7891 			UPDATE_OB_PKT_COUNT(sire);
7892 			sire->ire_last_used_time = lbolt;
7893 		}
7894 		/*
7895 		 * We have a route to reach the destination.
7896 		 *
7897 		 * 1) If the interface is part of ill group, try to get a new
7898 		 *    ill taking load spreading into account.
7899 		 *
7900 		 * 2) After selecting the ill, get a source address that
7901 		 *    might create good inbound load spreading.
7902 		 *    ipif_select_source does this for us.
7903 		 *
7904 		 * If the application specified the ill (ifindex), we still
7905 		 * load spread. Only if the packets needs to go out
7906 		 * specifically on a given ill e.g. binding to
7907 		 * IPIF_NOFAILOVER address, then we don't try to use a
7908 		 * different ill for load spreading.
7909 		 */
7910 		if (attach_ill == NULL) {
7911 			/*
7912 			 * Don't perform outbound load spreading in the
7913 			 * case of an RTF_MULTIRT route, as we actually
7914 			 * typically want to replicate outgoing packets
7915 			 * through particular interfaces.
7916 			 */
7917 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7918 				dst_ill = ire->ire_ipif->ipif_ill;
7919 				/* for uniformity */
7920 				ill_refhold(dst_ill);
7921 			} else {
7922 				/*
7923 				 * If we are here trying to create an IRE_CACHE
7924 				 * for an offlink destination and have the
7925 				 * IRE_CACHE for the next hop and the latter is
7926 				 * using virtual IP source address selection i.e
7927 				 * it's ire->ire_ipif is pointing to a virtual
7928 				 * network interface (vni) then
7929 				 * ip_newroute_get_dst_ll() will return the vni
7930 				 * interface as the dst_ill. Since the vni is
7931 				 * virtual i.e not associated with any physical
7932 				 * interface, it cannot be the dst_ill, hence
7933 				 * in such a case call ip_newroute_get_dst_ll()
7934 				 * with the stq_ill instead of the ire_ipif ILL.
7935 				 * The function returns a refheld ill.
7936 				 */
7937 				if ((ire->ire_type == IRE_CACHE) &&
7938 				    IS_VNI(ire->ire_ipif->ipif_ill))
7939 					dst_ill = ip_newroute_get_dst_ill(
7940 						ire->ire_stq->q_ptr);
7941 				else
7942 					dst_ill = ip_newroute_get_dst_ill(
7943 						ire->ire_ipif->ipif_ill);
7944 			}
7945 			if (dst_ill == NULL) {
7946 				if (ip_debug > 2) {
7947 					pr_addr_dbg("ip_newroute: "
7948 					    "no dst ill for dst"
7949 					    " %s\n", AF_INET, &dst);
7950 				}
7951 				goto icmp_err_ret;
7952 			}
7953 		} else {
7954 			dst_ill = ire->ire_ipif->ipif_ill;
7955 			/* for uniformity */
7956 			ill_refhold(dst_ill);
7957 			/*
7958 			 * We should have found a route matching ill as we
7959 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
7960 			 * Rather than asserting, when there is a mismatch,
7961 			 * we just drop the packet.
7962 			 */
7963 			if (dst_ill != attach_ill) {
7964 				ip0dbg(("ip_newroute: Packet dropped as "
7965 				    "IPIF_NOFAILOVER ill is %s, "
7966 				    "ire->ire_ipif->ipif_ill is %s\n",
7967 				    attach_ill->ill_name,
7968 				    dst_ill->ill_name));
7969 				ill_refrele(attach_ill);
7970 				goto icmp_err_ret;
7971 			}
7972 		}
7973 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
7974 		if (attach_ill != NULL) {
7975 			ill_refrele(attach_ill);
7976 			attach_ill = NULL;
7977 			do_attach_ill = B_TRUE;
7978 		}
7979 		ASSERT(dst_ill != NULL);
7980 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
7981 
7982 		/*
7983 		 * Pick the best source address from dst_ill.
7984 		 *
7985 		 * 1) If it is part of a multipathing group, we would
7986 		 *    like to spread the inbound packets across different
7987 		 *    interfaces. ipif_select_source picks a random source
7988 		 *    across the different ills in the group.
7989 		 *
7990 		 * 2) If it is not part of a multipathing group, we try
7991 		 *    to pick the source address from the destination
7992 		 *    route. Clustering assumes that when we have multiple
7993 		 *    prefixes hosted on an interface, the prefix of the
7994 		 *    source address matches the prefix of the destination
7995 		 *    route. We do this only if the address is not
7996 		 *    DEPRECATED.
7997 		 *
7998 		 * 3) If the conn is in a different zone than the ire, we
7999 		 *    need to pick a source address from the right zone.
8000 		 *
8001 		 * NOTE : If we hit case (1) above, the prefix of the source
8002 		 *	  address picked may not match the prefix of the
8003 		 *	  destination routes prefix as ipif_select_source
8004 		 *	  does not look at "dst" while picking a source
8005 		 *	  address.
8006 		 *	  If we want the same behavior as (2), we will need
8007 		 *	  to change the behavior of ipif_select_source.
8008 		 */
8009 		ASSERT(src_ipif == NULL);
8010 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8011 			/*
8012 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8013 			 * Check that the ipif matching the requested source
8014 			 * address still exists.
8015 			 */
8016 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8017 			    zoneid, NULL, NULL, NULL, NULL);
8018 		}
8019 		if (src_ipif == NULL) {
8020 			ire_marks |= IRE_MARK_USESRC_CHECK;
8021 			if ((dst_ill->ill_group != NULL) ||
8022 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8023 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8024 			    ire->ire_zoneid != ALL_ZONES) ||
8025 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8026 				/*
8027 				 * If the destination is reachable via a
8028 				 * given gateway, the selected source address
8029 				 * should be in the same subnet as the gateway.
8030 				 * Otherwise, the destination is not reachable.
8031 				 *
8032 				 * If there are no interfaces on the same subnet
8033 				 * as the destination, ipif_select_source gives
8034 				 * first non-deprecated interface which might be
8035 				 * on a different subnet than the gateway.
8036 				 * This is not desirable. Hence pass the dst_ire
8037 				 * source address to ipif_select_source.
8038 				 * It is sure that the destination is reachable
8039 				 * with the dst_ire source address subnet.
8040 				 * So passing dst_ire source address to
8041 				 * ipif_select_source will make sure that the
8042 				 * selected source will be on the same subnet
8043 				 * as dst_ire source address.
8044 				 */
8045 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8046 				src_ipif = ipif_select_source(dst_ill, saddr,
8047 				    zoneid);
8048 				if (src_ipif == NULL) {
8049 					if (ip_debug > 2) {
8050 						pr_addr_dbg("ip_newroute: "
8051 						    "no src for dst %s ",
8052 						    AF_INET, &dst);
8053 						printf("through interface %s\n",
8054 						    dst_ill->ill_name);
8055 					}
8056 					goto icmp_err_ret;
8057 				}
8058 			} else {
8059 				src_ipif = ire->ire_ipif;
8060 				ASSERT(src_ipif != NULL);
8061 				/* hold src_ipif for uniformity */
8062 				ipif_refhold(src_ipif);
8063 			}
8064 		}
8065 
8066 		/*
8067 		 * Assign a source address while we have the conn.
8068 		 * We can't have ip_wput_ire pick a source address when the
8069 		 * packet returns from arp since we need to look at
8070 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8071 		 * going through arp.
8072 		 *
8073 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8074 		 *	  it uses ip6i to store this information.
8075 		 */
8076 		if (ipha->ipha_src == INADDR_ANY &&
8077 		    (connp == NULL || !connp->conn_unspec_src)) {
8078 			ipha->ipha_src = src_ipif->ipif_src_addr;
8079 		}
8080 		if (ip_debug > 3) {
8081 			/* ip2dbg */
8082 			pr_addr_dbg("ip_newroute: first hop %s\n",
8083 			    AF_INET, &gw);
8084 		}
8085 		ip2dbg(("\tire type %s (%d)\n",
8086 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8087 
8088 		/*
8089 		 * The TTL of multirouted packets is bounded by the
8090 		 * ip_multirt_ttl ndd variable.
8091 		 */
8092 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8093 			/* Force TTL of multirouted packets */
8094 			if ((ip_multirt_ttl > 0) &&
8095 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8096 				ip2dbg(("ip_newroute: forcing multirt TTL "
8097 				    "to %d (was %d), dst 0x%08x\n",
8098 				    ip_multirt_ttl, ipha->ipha_ttl,
8099 				    ntohl(sire->ire_addr)));
8100 				ipha->ipha_ttl = ip_multirt_ttl;
8101 			}
8102 		}
8103 		/*
8104 		 * At this point in ip_newroute(), ire is either the
8105 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8106 		 * destination or an IRE_INTERFACE type that should be used
8107 		 * to resolve an on-subnet destination or an on-subnet
8108 		 * next-hop gateway.
8109 		 *
8110 		 * In the IRE_CACHE case, we have the following :
8111 		 *
8112 		 * 1) src_ipif - used for getting a source address.
8113 		 *
8114 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8115 		 *    means packets using this IRE_CACHE will go out on
8116 		 *    dst_ill.
8117 		 *
8118 		 * 3) The IRE sire will point to the prefix that is the
8119 		 *    longest  matching route for the destination. These
8120 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8121 		 *
8122 		 *    The newly created IRE_CACHE entry for the off-subnet
8123 		 *    destination is tied to both the prefix route and the
8124 		 *    interface route used to resolve the next-hop gateway
8125 		 *    via the ire_phandle and ire_ihandle fields,
8126 		 *    respectively.
8127 		 *
8128 		 * In the IRE_INTERFACE case, we have the following :
8129 		 *
8130 		 * 1) src_ipif - used for getting a source address.
8131 		 *
8132 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8133 		 *    means packets using the IRE_CACHE that we will build
8134 		 *    here will go out on dst_ill.
8135 		 *
8136 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8137 		 *    to be created will only be tied to the IRE_INTERFACE
8138 		 *    that was derived from the ire_ihandle field.
8139 		 *
8140 		 *    If sire is non-NULL, it means the destination is
8141 		 *    off-link and we will first create the IRE_CACHE for the
8142 		 *    gateway. Next time through ip_newroute, we will create
8143 		 *    the IRE_CACHE for the final destination as described
8144 		 *    above.
8145 		 *
8146 		 * In both cases, after the current resolution has been
8147 		 * completed (or possibly initialised, in the IRE_INTERFACE
8148 		 * case), the loop may be re-entered to attempt the resolution
8149 		 * of another RTF_MULTIRT route.
8150 		 *
8151 		 * When an IRE_CACHE entry for the off-subnet destination is
8152 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8153 		 * for further processing in emission loops.
8154 		 */
8155 		save_ire = ire;
8156 		switch (ire->ire_type) {
8157 		case IRE_CACHE: {
8158 			ire_t	*ipif_ire;
8159 			mblk_t	*ire_fp_mp;
8160 
8161 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8162 			if (gw == 0)
8163 				gw = ire->ire_gateway_addr;
8164 			/*
8165 			 * We need 3 ire's to create a new cache ire for an
8166 			 * off-link destination from the cache ire of the
8167 			 * gateway.
8168 			 *
8169 			 *	1. The prefix ire 'sire' (Note that this does
8170 			 *	   not apply to the conn_nexthop_set case)
8171 			 *	2. The cache ire of the gateway 'ire'
8172 			 *	3. The interface ire 'ipif_ire'
8173 			 *
8174 			 * We have (1) and (2). We lookup (3) below.
8175 			 *
8176 			 * If there is no interface route to the gateway,
8177 			 * it is a race condition, where we found the cache
8178 			 * but the interface route has been deleted.
8179 			 */
8180 			if (ip_nexthop) {
8181 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8182 			} else {
8183 				ipif_ire =
8184 				    ire_ihandle_lookup_offlink(ire, sire);
8185 			}
8186 			if (ipif_ire == NULL) {
8187 				ip1dbg(("ip_newroute: "
8188 				    "ire_ihandle_lookup_offlink failed\n"));
8189 				goto icmp_err_ret;
8190 			}
8191 			/*
8192 			 * XXX We are using the same res_mp
8193 			 * (DL_UNITDATA_REQ) though the save_ire is not
8194 			 * pointing at the same ill.
8195 			 * This is incorrect. We need to send it up to the
8196 			 * resolver to get the right res_mp. For ethernets
8197 			 * this may be okay (ill_type == DL_ETHER).
8198 			 */
8199 			res_mp = save_ire->ire_nce->nce_res_mp;
8200 			ire_fp_mp = NULL;
8201 			/*
8202 			 * save_ire's nce_fp_mp can't change since it is
8203 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8204 			 * LOCK_IRE_FP_MP does not do any useful work in
8205 			 * the case of IRE_CACHE. So we don't use it below.
8206 			 */
8207 			if (save_ire->ire_stq == dst_ill->ill_wq)
8208 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8209 
8210 			/*
8211 			 * Check cached gateway IRE for any security
8212 			 * attributes; if found, associate the gateway
8213 			 * credentials group to the destination IRE.
8214 			 */
8215 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8216 				mutex_enter(&attrp->igsa_lock);
8217 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8218 					GCGRP_REFHOLD(gcgrp);
8219 				mutex_exit(&attrp->igsa_lock);
8220 			}
8221 
8222 			ire = ire_create(
8223 			    (uchar_t *)&dst,		/* dest address */
8224 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8225 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8226 			    (uchar_t *)&gw,		/* gateway address */
8227 			    NULL,
8228 			    &save_ire->ire_max_frag,
8229 			    ire_fp_mp,			/* Fast Path header */
8230 			    dst_ill->ill_rq,		/* recv-from queue */
8231 			    dst_ill->ill_wq,		/* send-to queue */
8232 			    IRE_CACHE,			/* IRE type */
8233 			    res_mp,
8234 			    src_ipif,
8235 			    in_ill,			/* incoming ill */
8236 			    (sire != NULL) ?
8237 				sire->ire_mask : 0, 	/* Parent mask */
8238 			    (sire != NULL) ?
8239 				sire->ire_phandle : 0,  /* Parent handle */
8240 			    ipif_ire->ire_ihandle,	/* Interface handle */
8241 			    (sire != NULL) ? (sire->ire_flags &
8242 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8243 			    (sire != NULL) ?
8244 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8245 			    NULL,
8246 			    gcgrp);
8247 
8248 			if (ire == NULL) {
8249 				if (gcgrp != NULL) {
8250 					GCGRP_REFRELE(gcgrp);
8251 					gcgrp = NULL;
8252 				}
8253 				ire_refrele(ipif_ire);
8254 				ire_refrele(save_ire);
8255 				break;
8256 			}
8257 
8258 			/* reference now held by IRE */
8259 			gcgrp = NULL;
8260 
8261 			ire->ire_marks |= ire_marks;
8262 
8263 			/*
8264 			 * Prevent sire and ipif_ire from getting deleted.
8265 			 * The newly created ire is tied to both of them via
8266 			 * the phandle and ihandle respectively.
8267 			 */
8268 			if (sire != NULL) {
8269 				IRB_REFHOLD(sire->ire_bucket);
8270 				/* Has it been removed already ? */
8271 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8272 					IRB_REFRELE(sire->ire_bucket);
8273 					ire_refrele(ipif_ire);
8274 					ire_refrele(save_ire);
8275 					break;
8276 				}
8277 			}
8278 
8279 			IRB_REFHOLD(ipif_ire->ire_bucket);
8280 			/* Has it been removed already ? */
8281 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8282 				IRB_REFRELE(ipif_ire->ire_bucket);
8283 				if (sire != NULL)
8284 					IRB_REFRELE(sire->ire_bucket);
8285 				ire_refrele(ipif_ire);
8286 				ire_refrele(save_ire);
8287 				break;
8288 			}
8289 
8290 			xmit_mp = first_mp;
8291 			/*
8292 			 * In the case of multirouting, a copy
8293 			 * of the packet is done before its sending.
8294 			 * The copy is used to attempt another
8295 			 * route resolution, in a next loop.
8296 			 */
8297 			if (ire->ire_flags & RTF_MULTIRT) {
8298 				copy_mp = copymsg(first_mp);
8299 				if (copy_mp != NULL) {
8300 					xmit_mp = copy_mp;
8301 					MULTIRT_DEBUG_TAG(first_mp);
8302 				}
8303 			}
8304 			ire_add_then_send(q, ire, xmit_mp);
8305 			ire_refrele(save_ire);
8306 
8307 			/* Assert that sire is not deleted yet. */
8308 			if (sire != NULL) {
8309 				ASSERT(sire->ire_ptpn != NULL);
8310 				IRB_REFRELE(sire->ire_bucket);
8311 			}
8312 
8313 			/* Assert that ipif_ire is not deleted yet. */
8314 			ASSERT(ipif_ire->ire_ptpn != NULL);
8315 			IRB_REFRELE(ipif_ire->ire_bucket);
8316 			ire_refrele(ipif_ire);
8317 
8318 			/*
8319 			 * If copy_mp is not NULL, multirouting was
8320 			 * requested. We loop to initiate a next
8321 			 * route resolution attempt, starting from sire.
8322 			 */
8323 			if (copy_mp != NULL) {
8324 				/*
8325 				 * Search for the next unresolved
8326 				 * multirt route.
8327 				 */
8328 				copy_mp = NULL;
8329 				ipif_ire = NULL;
8330 				ire = NULL;
8331 				multirt_resolve_next = B_TRUE;
8332 				continue;
8333 			}
8334 			if (sire != NULL)
8335 				ire_refrele(sire);
8336 			ipif_refrele(src_ipif);
8337 			ill_refrele(dst_ill);
8338 			return;
8339 		}
8340 		case IRE_IF_NORESOLVER: {
8341 			/*
8342 			 * We have what we need to build an IRE_CACHE.
8343 			 *
8344 			 * Create a new res_mp with the IP gateway address
8345 			 * in destination address in the DLPI hdr if the
8346 			 * physical length is exactly 4 bytes.
8347 			 */
8348 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8349 				uchar_t *addr;
8350 
8351 				if (gw)
8352 					addr = (uchar_t *)&gw;
8353 				else
8354 					addr = (uchar_t *)&dst;
8355 
8356 				res_mp = ill_dlur_gen(addr,
8357 				    dst_ill->ill_phys_addr_length,
8358 				    dst_ill->ill_sap,
8359 				    dst_ill->ill_sap_length);
8360 
8361 				if (res_mp == NULL) {
8362 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8363 					break;
8364 				}
8365 			} else {
8366 				res_mp = NULL;
8367 			}
8368 
8369 			/*
8370 			 * TSol note: We are creating the ire cache for the
8371 			 * destination 'dst'. If 'dst' is offlink, going
8372 			 * through the first hop 'gw', the security attributes
8373 			 * of 'dst' must be set to point to the gateway
8374 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8375 			 * is possible that 'dst' is a potential gateway that is
8376 			 * referenced by some route that has some security
8377 			 * attributes. Thus in the former case, we need to do a
8378 			 * gcgrp_lookup of 'gw' while in the latter case we
8379 			 * need to do gcgrp_lookup of 'dst' itself.
8380 			 */
8381 			ga.ga_af = AF_INET;
8382 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8383 			    &ga.ga_addr);
8384 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8385 
8386 			ire = ire_create(
8387 			    (uchar_t *)&dst,		/* dest address */
8388 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8389 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8390 			    (uchar_t *)&gw,		/* gateway address */
8391 			    NULL,
8392 			    &save_ire->ire_max_frag,
8393 			    NULL,			/* Fast Path header */
8394 			    dst_ill->ill_rq,		/* recv-from queue */
8395 			    dst_ill->ill_wq,		/* send-to queue */
8396 			    IRE_CACHE,
8397 			    res_mp,
8398 			    src_ipif,
8399 			    in_ill,			/* Incoming ill */
8400 			    save_ire->ire_mask,		/* Parent mask */
8401 			    (sire != NULL) ?		/* Parent handle */
8402 				sire->ire_phandle : 0,
8403 			    save_ire->ire_ihandle,	/* Interface handle */
8404 			    (sire != NULL) ? sire->ire_flags &
8405 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8406 			    &(save_ire->ire_uinfo),
8407 			    NULL,
8408 			    gcgrp);
8409 
8410 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8411 				freeb(res_mp);
8412 
8413 			if (ire == NULL) {
8414 				if (gcgrp != NULL) {
8415 					GCGRP_REFRELE(gcgrp);
8416 					gcgrp = NULL;
8417 				}
8418 				ire_refrele(save_ire);
8419 				break;
8420 			}
8421 
8422 			/* reference now held by IRE */
8423 			gcgrp = NULL;
8424 
8425 			ire->ire_marks |= ire_marks;
8426 
8427 			/* Prevent save_ire from getting deleted */
8428 			IRB_REFHOLD(save_ire->ire_bucket);
8429 			/* Has it been removed already ? */
8430 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8431 				IRB_REFRELE(save_ire->ire_bucket);
8432 				ire_refrele(save_ire);
8433 				break;
8434 			}
8435 
8436 			/*
8437 			 * In the case of multirouting, a copy
8438 			 * of the packet is made before it is sent.
8439 			 * The copy is used in the next
8440 			 * loop to attempt another resolution.
8441 			 */
8442 			xmit_mp = first_mp;
8443 			if ((sire != NULL) &&
8444 			    (sire->ire_flags & RTF_MULTIRT)) {
8445 				copy_mp = copymsg(first_mp);
8446 				if (copy_mp != NULL) {
8447 					xmit_mp = copy_mp;
8448 					MULTIRT_DEBUG_TAG(first_mp);
8449 				}
8450 			}
8451 			ire_add_then_send(q, ire, xmit_mp);
8452 
8453 			/* Assert that it is not deleted yet. */
8454 			ASSERT(save_ire->ire_ptpn != NULL);
8455 			IRB_REFRELE(save_ire->ire_bucket);
8456 			ire_refrele(save_ire);
8457 
8458 			if (copy_mp != NULL) {
8459 				/*
8460 				 * If we found a (no)resolver, we ignore any
8461 				 * trailing top priority IRE_CACHE in further
8462 				 * loops. This ensures that we do not omit any
8463 				 * (no)resolver.
8464 				 * This IRE_CACHE, if any, will be processed
8465 				 * by another thread entering ip_newroute().
8466 				 * IRE_CACHE entries, if any, will be processed
8467 				 * by another thread entering ip_newroute(),
8468 				 * (upon resolver response, for instance).
8469 				 * This aims to force parallel multirt
8470 				 * resolutions as soon as a packet must be sent.
8471 				 * In the best case, after the tx of only one
8472 				 * packet, all reachable routes are resolved.
8473 				 * Otherwise, the resolution of all RTF_MULTIRT
8474 				 * routes would require several emissions.
8475 				 */
8476 				multirt_flags &= ~MULTIRT_CACHEGW;
8477 
8478 				/*
8479 				 * Search for the next unresolved multirt
8480 				 * route.
8481 				 */
8482 				copy_mp = NULL;
8483 				save_ire = NULL;
8484 				ire = NULL;
8485 				multirt_resolve_next = B_TRUE;
8486 				continue;
8487 			}
8488 
8489 			/*
8490 			 * Don't need sire anymore
8491 			 */
8492 			if (sire != NULL)
8493 				ire_refrele(sire);
8494 
8495 			ipif_refrele(src_ipif);
8496 			ill_refrele(dst_ill);
8497 			return;
8498 		}
8499 		case IRE_IF_RESOLVER:
8500 			/*
8501 			 * We can't build an IRE_CACHE yet, but at least we
8502 			 * found a resolver that can help.
8503 			 */
8504 			res_mp = dst_ill->ill_resolver_mp;
8505 			if (!OK_RESOLVER_MP(res_mp))
8506 				break;
8507 
8508 			/*
8509 			 * To be at this point in the code with a non-zero gw
8510 			 * means that dst is reachable through a gateway that
8511 			 * we have never resolved.  By changing dst to the gw
8512 			 * addr we resolve the gateway first.
8513 			 * When ire_add_then_send() tries to put the IP dg
8514 			 * to dst, it will reenter ip_newroute() at which
8515 			 * time we will find the IRE_CACHE for the gw and
8516 			 * create another IRE_CACHE in case IRE_CACHE above.
8517 			 */
8518 			if (gw != INADDR_ANY) {
8519 				/*
8520 				 * The source ipif that was determined above was
8521 				 * relative to the destination address, not the
8522 				 * gateway's. If src_ipif was not taken out of
8523 				 * the IRE_IF_RESOLVER entry, we'll need to call
8524 				 * ipif_select_source() again.
8525 				 */
8526 				if (src_ipif != ire->ire_ipif) {
8527 					ipif_refrele(src_ipif);
8528 					src_ipif = ipif_select_source(dst_ill,
8529 					    gw, zoneid);
8530 					if (src_ipif == NULL) {
8531 						if (ip_debug > 2) {
8532 							pr_addr_dbg(
8533 							    "ip_newroute: no "
8534 							    "src for gw %s ",
8535 							    AF_INET, &gw);
8536 							printf("through "
8537 							    "interface %s\n",
8538 							    dst_ill->ill_name);
8539 						}
8540 						goto icmp_err_ret;
8541 					}
8542 				}
8543 				save_dst = dst;
8544 				dst = gw;
8545 				gw = INADDR_ANY;
8546 			}
8547 
8548 			/*
8549 			 * We obtain a partial IRE_CACHE which we will pass
8550 			 * along with the resolver query.  When the response
8551 			 * comes back it will be there ready for us to add.
8552 			 * The ire_max_frag is atomically set under the
8553 			 * irebucket lock in ire_add_v[46].
8554 			 */
8555 
8556 			ire = ire_create_mp(
8557 			    (uchar_t *)&dst,		/* dest address */
8558 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8559 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8560 			    (uchar_t *)&gw,		/* gateway address */
8561 			    NULL,			/* no in_src_addr */
8562 			    NULL,			/* ire_max_frag */
8563 			    NULL,			/* Fast Path header */
8564 			    dst_ill->ill_rq,		/* recv-from queue */
8565 			    dst_ill->ill_wq,		/* send-to queue */
8566 			    IRE_CACHE,
8567 			    NULL,
8568 			    src_ipif,			/* Interface ipif */
8569 			    in_ill,			/* Incoming ILL */
8570 			    save_ire->ire_mask,		/* Parent mask */
8571 			    0,
8572 			    save_ire->ire_ihandle,	/* Interface handle */
8573 			    0,				/* flags if any */
8574 			    &(save_ire->ire_uinfo),
8575 			    NULL,
8576 			    NULL);
8577 
8578 			if (ire == NULL) {
8579 				ire_refrele(save_ire);
8580 				break;
8581 			}
8582 
8583 			if ((sire != NULL) &&
8584 			    (sire->ire_flags & RTF_MULTIRT)) {
8585 				copy_mp = copymsg(first_mp);
8586 				if (copy_mp != NULL)
8587 					MULTIRT_DEBUG_TAG(copy_mp);
8588 			}
8589 
8590 			ire->ire_marks |= ire_marks;
8591 
8592 			/*
8593 			 * Construct message chain for the resolver
8594 			 * of the form:
8595 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8596 			 * Packet could contain a IPSEC_OUT mp.
8597 			 *
8598 			 * NOTE : ire will be added later when the response
8599 			 * comes back from ARP. If the response does not
8600 			 * come back, ARP frees the packet. For this reason,
8601 			 * we can't REFHOLD the bucket of save_ire to prevent
8602 			 * deletions. We may not be able to REFRELE the bucket
8603 			 * if the response never comes back. Thus, before
8604 			 * adding the ire, ire_add_v4 will make sure that the
8605 			 * interface route does not get deleted. This is the
8606 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8607 			 * where we can always prevent deletions because of
8608 			 * the synchronous nature of adding IRES i.e
8609 			 * ire_add_then_send is called after creating the IRE.
8610 			 */
8611 			ASSERT(ire->ire_mp != NULL);
8612 			ire->ire_mp->b_cont = first_mp;
8613 			/* Have saved_mp handy, for cleanup if canput fails */
8614 			saved_mp = mp;
8615 			mp = copyb(res_mp);
8616 			if (mp == NULL) {
8617 				/* Prepare for cleanup */
8618 				mp = saved_mp; /* pkt */
8619 				ire_delete(ire); /* ire_mp */
8620 				ire = NULL;
8621 				ire_refrele(save_ire);
8622 				if (copy_mp != NULL) {
8623 					MULTIRT_DEBUG_UNTAG(copy_mp);
8624 					freemsg(copy_mp);
8625 					copy_mp = NULL;
8626 				}
8627 				break;
8628 			}
8629 			linkb(mp, ire->ire_mp);
8630 
8631 			/*
8632 			 * Fill in the source and dest addrs for the resolver.
8633 			 * NOTE: this depends on memory layouts imposed by
8634 			 * ill_init().
8635 			 */
8636 			areq = (areq_t *)mp->b_rptr;
8637 			addrp = (ipaddr_t *)((char *)areq +
8638 			    areq->areq_sender_addr_offset);
8639 			if (do_attach_ill) {
8640 				/*
8641 				 * This is bind to no failover case.
8642 				 * arp packet also must go out on attach_ill.
8643 				 */
8644 				ASSERT(ipha->ipha_src != NULL);
8645 				*addrp = ipha->ipha_src;
8646 			} else {
8647 				*addrp = save_ire->ire_src_addr;
8648 			}
8649 
8650 			ire_refrele(save_ire);
8651 			addrp = (ipaddr_t *)((char *)areq +
8652 			    areq->areq_target_addr_offset);
8653 			*addrp = dst;
8654 			/* Up to the resolver. */
8655 			if (canputnext(dst_ill->ill_rq) &&
8656 			    !(dst_ill->ill_arp_closing)) {
8657 				putnext(dst_ill->ill_rq, mp);
8658 				ire = NULL;
8659 				if (copy_mp != NULL) {
8660 					/*
8661 					 * If we found a resolver, we ignore
8662 					 * any trailing top priority IRE_CACHE
8663 					 * in the further loops. This ensures
8664 					 * that we do not omit any resolver.
8665 					 * IRE_CACHE entries, if any, will be
8666 					 * processed next time we enter
8667 					 * ip_newroute().
8668 					 */
8669 					multirt_flags &= ~MULTIRT_CACHEGW;
8670 					/*
8671 					 * Search for the next unresolved
8672 					 * multirt route.
8673 					 */
8674 					first_mp = copy_mp;
8675 					copy_mp = NULL;
8676 					/* Prepare the next resolution loop. */
8677 					mp = first_mp;
8678 					EXTRACT_PKT_MP(mp, first_mp,
8679 					    mctl_present);
8680 					if (mctl_present)
8681 						io = (ipsec_out_t *)
8682 						    first_mp->b_rptr;
8683 					ipha = (ipha_t *)mp->b_rptr;
8684 
8685 					ASSERT(sire != NULL);
8686 
8687 					dst = save_dst;
8688 					multirt_resolve_next = B_TRUE;
8689 					continue;
8690 				}
8691 
8692 				if (sire != NULL)
8693 					ire_refrele(sire);
8694 
8695 				/*
8696 				 * The response will come back in ip_wput
8697 				 * with db_type IRE_DB_TYPE.
8698 				 */
8699 				ipif_refrele(src_ipif);
8700 				ill_refrele(dst_ill);
8701 				return;
8702 			} else {
8703 				/* Prepare for cleanup */
8704 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8705 				    mp);
8706 				mp->b_cont = NULL;
8707 				freeb(mp); /* areq */
8708 				/*
8709 				 * this is an ire that is not added to the
8710 				 * cache. ire_freemblk will handle the release
8711 				 * of any resources associated with the ire.
8712 				 */
8713 				ire_delete(ire); /* ire_mp */
8714 				mp = saved_mp; /* pkt */
8715 				ire = NULL;
8716 				if (copy_mp != NULL) {
8717 					MULTIRT_DEBUG_UNTAG(copy_mp);
8718 					freemsg(copy_mp);
8719 					copy_mp = NULL;
8720 				}
8721 				break;
8722 			}
8723 		default:
8724 			break;
8725 		}
8726 	} while (multirt_resolve_next);
8727 
8728 	ip1dbg(("ip_newroute: dropped\n"));
8729 	/* Did this packet originate externally? */
8730 	if (mp->b_prev) {
8731 		mp->b_next = NULL;
8732 		mp->b_prev = NULL;
8733 		BUMP_MIB(&ip_mib, ipInDiscards);
8734 	} else {
8735 		BUMP_MIB(&ip_mib, ipOutDiscards);
8736 	}
8737 	ASSERT(copy_mp == NULL);
8738 	MULTIRT_DEBUG_UNTAG(first_mp);
8739 	freemsg(first_mp);
8740 	if (ire != NULL)
8741 		ire_refrele(ire);
8742 	if (sire != NULL)
8743 		ire_refrele(sire);
8744 	if (src_ipif != NULL)
8745 		ipif_refrele(src_ipif);
8746 	if (dst_ill != NULL)
8747 		ill_refrele(dst_ill);
8748 	return;
8749 
8750 icmp_err_ret:
8751 	ip1dbg(("ip_newroute: no route\n"));
8752 	if (src_ipif != NULL)
8753 		ipif_refrele(src_ipif);
8754 	if (dst_ill != NULL)
8755 		ill_refrele(dst_ill);
8756 	if (sire != NULL)
8757 		ire_refrele(sire);
8758 	/* Did this packet originate externally? */
8759 	if (mp->b_prev) {
8760 		mp->b_next = NULL;
8761 		mp->b_prev = NULL;
8762 		/* XXX ipInNoRoutes */
8763 		q = WR(q);
8764 	} else {
8765 		/*
8766 		 * Since ip_wput() isn't close to finished, we fill
8767 		 * in enough of the header for credible error reporting.
8768 		 */
8769 		if (ip_hdr_complete(ipha, zoneid)) {
8770 			/* Failed */
8771 			MULTIRT_DEBUG_UNTAG(first_mp);
8772 			freemsg(first_mp);
8773 			if (ire != NULL)
8774 				ire_refrele(ire);
8775 			return;
8776 		}
8777 	}
8778 	BUMP_MIB(&ip_mib, ipOutNoRoutes);
8779 
8780 	/*
8781 	 * At this point we will have ire only if RTF_BLACKHOLE
8782 	 * or RTF_REJECT flags are set on the IRE. It will not
8783 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8784 	 */
8785 	if (ire != NULL) {
8786 		if (ire->ire_flags & RTF_BLACKHOLE) {
8787 			ire_refrele(ire);
8788 			MULTIRT_DEBUG_UNTAG(first_mp);
8789 			freemsg(first_mp);
8790 			return;
8791 		}
8792 		ire_refrele(ire);
8793 	}
8794 	if (ip_source_routed(ipha)) {
8795 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8796 		    zoneid);
8797 		return;
8798 	}
8799 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
8800 }
8801 
8802 /*
8803  * IPv4 -
8804  * ip_newroute_ipif is called by ip_wput_multicast and
8805  * ip_rput_forward_multicast whenever we need to send
8806  * out a packet to a destination address for which we do not have specific
8807  * routing information. It is used when the packet will be sent out
8808  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8809  * socket option is set or icmp error message wants to go out on a particular
8810  * interface for a unicast packet.
8811  *
8812  * In most cases, the destination address is resolved thanks to the ipif
8813  * intrinsic resolver. However, there are some cases where the call to
8814  * ip_newroute_ipif must take into account the potential presence of
8815  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8816  * that uses the interface. This is specified through flags,
8817  * which can be a combination of:
8818  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8819  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8820  *   and flags. Additionally, the packet source address has to be set to
8821  *   the specified address. The caller is thus expected to set this flag
8822  *   if the packet has no specific source address yet.
8823  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8824  *   flag, the resulting ire will inherit the flag. All unresolved routes
8825  *   to the destination must be explored in the same call to
8826  *   ip_newroute_ipif().
8827  */
8828 static void
8829 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8830     conn_t *connp, uint32_t flags, zoneid_t zoneid)
8831 {
8832 	areq_t	*areq;
8833 	ire_t	*ire = NULL;
8834 	mblk_t	*res_mp;
8835 	ipaddr_t *addrp;
8836 	mblk_t *first_mp;
8837 	ire_t	*save_ire = NULL;
8838 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8839 	ipif_t	*src_ipif = NULL;
8840 	ushort_t ire_marks = 0;
8841 	ill_t	*dst_ill = NULL;
8842 	boolean_t mctl_present;
8843 	ipsec_out_t *io;
8844 	ipha_t *ipha;
8845 	int	ihandle = 0;
8846 	mblk_t	*saved_mp;
8847 	ire_t   *fire = NULL;
8848 	mblk_t  *copy_mp = NULL;
8849 	boolean_t multirt_resolve_next;
8850 	ipaddr_t ipha_dst;
8851 
8852 	/*
8853 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8854 	 * here for uniformity
8855 	 */
8856 	ipif_refhold(ipif);
8857 
8858 	/*
8859 	 * This loop is run only once in most cases.
8860 	 * We loop to resolve further routes only when the destination
8861 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8862 	 */
8863 	do {
8864 		if (dst_ill != NULL) {
8865 			ill_refrele(dst_ill);
8866 			dst_ill = NULL;
8867 		}
8868 		if (src_ipif != NULL) {
8869 			ipif_refrele(src_ipif);
8870 			src_ipif = NULL;
8871 		}
8872 		multirt_resolve_next = B_FALSE;
8873 
8874 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8875 		    ipif->ipif_ill->ill_name));
8876 
8877 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8878 		if (mctl_present)
8879 			io = (ipsec_out_t *)first_mp->b_rptr;
8880 
8881 		ipha = (ipha_t *)mp->b_rptr;
8882 
8883 		/*
8884 		 * Save the packet destination address, we may need it after
8885 		 * the packet has been consumed.
8886 		 */
8887 		ipha_dst = ipha->ipha_dst;
8888 
8889 		/*
8890 		 * If the interface is a pt-pt interface we look for an
8891 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8892 		 * local_address and the pt-pt destination address. Otherwise
8893 		 * we just match the local address.
8894 		 * NOTE: dst could be different than ipha->ipha_dst in case
8895 		 * of sending igmp multicast packets over a point-to-point
8896 		 * connection.
8897 		 * Thus we must be careful enough to check ipha_dst to be a
8898 		 * multicast address, otherwise it will take xmit_if path for
8899 		 * multicast packets resulting into kernel stack overflow by
8900 		 * repeated calls to ip_newroute_ipif from ire_send().
8901 		 */
8902 		if (CLASSD(ipha_dst) &&
8903 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8904 			goto err_ret;
8905 		}
8906 
8907 		/*
8908 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8909 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8910 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8911 		 * propagate its flags to the new ire.
8912 		 */
8913 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8914 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8915 			ip2dbg(("ip_newroute_ipif: "
8916 			    "ipif_lookup_multi_ire("
8917 			    "ipif %p, dst %08x) = fire %p\n",
8918 			    (void *)ipif, ntohl(dst), (void *)fire));
8919 		}
8920 
8921 		if (mctl_present && io->ipsec_out_attach_if) {
8922 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8923 			    io->ipsec_out_ill_index, B_FALSE);
8924 
8925 			/* Failure case frees things for us. */
8926 			if (attach_ill == NULL) {
8927 				ipif_refrele(ipif);
8928 				if (fire != NULL)
8929 					ire_refrele(fire);
8930 				return;
8931 			}
8932 
8933 			/*
8934 			 * Check if we need an ire that will not be
8935 			 * looked up by anybody else i.e. HIDDEN.
8936 			 */
8937 			if (ill_is_probeonly(attach_ill)) {
8938 				ire_marks = IRE_MARK_HIDDEN;
8939 			}
8940 			/*
8941 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
8942 			 * case.
8943 			 */
8944 			dst_ill = ipif->ipif_ill;
8945 			/* attach_ill has been refheld by ip_grab_attach_ill */
8946 			ASSERT(dst_ill == attach_ill);
8947 		} else {
8948 			/*
8949 			 * If this is set by IP_XMIT_IF, then make sure that
8950 			 * ipif is pointing to the same ill as the IP_XMIT_IF
8951 			 * specified ill.
8952 			 */
8953 			ASSERT((connp == NULL) ||
8954 			    (connp->conn_xmit_if_ill == NULL) ||
8955 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
8956 			/*
8957 			 * If the interface belongs to an interface group,
8958 			 * make sure the next possible interface in the group
8959 			 * is used.  This encourages load spreading among
8960 			 * peers in an interface group.
8961 			 * Note: load spreading is disabled for RTF_MULTIRT
8962 			 * routes.
8963 			 */
8964 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
8965 			    (fire->ire_flags & RTF_MULTIRT)) {
8966 				/*
8967 				 * Don't perform outbound load spreading
8968 				 * in the case of an RTF_MULTIRT issued route,
8969 				 * we actually typically want to replicate
8970 				 * outgoing packets through particular
8971 				 * interfaces.
8972 				 */
8973 				dst_ill = ipif->ipif_ill;
8974 				ill_refhold(dst_ill);
8975 			} else {
8976 				dst_ill = ip_newroute_get_dst_ill(
8977 				    ipif->ipif_ill);
8978 			}
8979 			if (dst_ill == NULL) {
8980 				if (ip_debug > 2) {
8981 					pr_addr_dbg("ip_newroute_ipif: "
8982 					    "no dst ill for dst %s\n",
8983 					    AF_INET, &dst);
8984 				}
8985 				goto err_ret;
8986 			}
8987 		}
8988 
8989 		/*
8990 		 * Pick a source address preferring non-deprecated ones.
8991 		 * Unlike ip_newroute, we don't do any source address
8992 		 * selection here since for multicast it really does not help
8993 		 * in inbound load spreading as in the unicast case.
8994 		 */
8995 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
8996 		    (fire->ire_flags & RTF_SETSRC)) {
8997 			/*
8998 			 * As requested by flags, an IRE_OFFSUBNET was looked up
8999 			 * on that interface. This ire has RTF_SETSRC flag, so
9000 			 * the source address of the packet must be changed.
9001 			 * Check that the ipif matching the requested source
9002 			 * address still exists.
9003 			 */
9004 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9005 			    zoneid, NULL, NULL, NULL, NULL);
9006 		}
9007 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9008 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9009 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9010 		    (src_ipif == NULL)) {
9011 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9012 			if (src_ipif == NULL) {
9013 				if (ip_debug > 2) {
9014 					/* ip1dbg */
9015 					pr_addr_dbg("ip_newroute_ipif: "
9016 					    "no src for dst %s",
9017 					    AF_INET, &dst);
9018 				}
9019 				ip1dbg((" through interface %s\n",
9020 				    dst_ill->ill_name));
9021 				goto err_ret;
9022 			}
9023 			ipif_refrele(ipif);
9024 			ipif = src_ipif;
9025 			ipif_refhold(ipif);
9026 		}
9027 		if (src_ipif == NULL) {
9028 			src_ipif = ipif;
9029 			ipif_refhold(src_ipif);
9030 		}
9031 
9032 		/*
9033 		 * Assign a source address while we have the conn.
9034 		 * We can't have ip_wput_ire pick a source address when the
9035 		 * packet returns from arp since conn_unspec_src might be set
9036 		 * and we loose the conn when going through arp.
9037 		 */
9038 		if (ipha->ipha_src == INADDR_ANY &&
9039 		    (connp == NULL || !connp->conn_unspec_src)) {
9040 			ipha->ipha_src = src_ipif->ipif_src_addr;
9041 		}
9042 
9043 		/*
9044 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9045 		 * interface does not have an interface ire.
9046 		 * Example: Thousands of mobileip PPP interfaces to mobile
9047 		 * nodes. We don't want to create interface ires because
9048 		 * packets from other mobile nodes must not take the route
9049 		 * via interface ires to the visiting mobile node without
9050 		 * going through the home agent, in absence of mobileip
9051 		 * route optimization.
9052 		 */
9053 		if (CLASSD(ipha_dst) && (connp == NULL ||
9054 		    connp->conn_xmit_if_ill == NULL)) {
9055 			/* ipif_to_ire returns an held ire */
9056 			ire = ipif_to_ire(ipif);
9057 			if (ire == NULL)
9058 				goto err_ret;
9059 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9060 				goto err_ret;
9061 			/*
9062 			 * ihandle is needed when the ire is added to
9063 			 * cache table.
9064 			 */
9065 			save_ire = ire;
9066 			ihandle = save_ire->ire_ihandle;
9067 
9068 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9069 			    "flags %04x\n",
9070 			    (void *)ire, (void *)ipif, flags));
9071 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9072 			    (fire->ire_flags & RTF_MULTIRT)) {
9073 				/*
9074 				 * As requested by flags, an IRE_OFFSUBNET was
9075 				 * looked up on that interface. This ire has
9076 				 * RTF_MULTIRT flag, so the resolution loop will
9077 				 * be re-entered to resolve additional routes on
9078 				 * other interfaces. For that purpose, a copy of
9079 				 * the packet is performed at this point.
9080 				 */
9081 				fire->ire_last_used_time = lbolt;
9082 				copy_mp = copymsg(first_mp);
9083 				if (copy_mp) {
9084 					MULTIRT_DEBUG_TAG(copy_mp);
9085 				}
9086 			}
9087 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9088 			    (fire->ire_flags & RTF_SETSRC)) {
9089 				/*
9090 				 * As requested by flags, an IRE_OFFSUBET was
9091 				 * looked up on that interface. This ire has
9092 				 * RTF_SETSRC flag, so the source address of the
9093 				 * packet must be changed.
9094 				 */
9095 				ipha->ipha_src = fire->ire_src_addr;
9096 			}
9097 		} else {
9098 			ASSERT((connp == NULL) ||
9099 			    (connp->conn_xmit_if_ill != NULL) ||
9100 			    (connp->conn_dontroute));
9101 			/*
9102 			 * The only ways we can come here are:
9103 			 * 1) IP_XMIT_IF socket option is set
9104 			 * 2) ICMP error message generated from
9105 			 *    ip_mrtun_forward() routine and it needs
9106 			 *    to go through the specified ill.
9107 			 * 3) SO_DONTROUTE socket option is set
9108 			 * In all cases, the new ire will not be added
9109 			 * into cache table.
9110 			 */
9111 			ire_marks |= IRE_MARK_NOADD;
9112 		}
9113 
9114 		switch (ipif->ipif_net_type) {
9115 		case IRE_IF_NORESOLVER: {
9116 			/* We have what we need to build an IRE_CACHE. */
9117 			mblk_t	*res_mp;
9118 
9119 			/*
9120 			 * Create a new res_mp with the
9121 			 * IP gateway address as destination address in the
9122 			 * DLPI hdr if the physical length is exactly 4 bytes.
9123 			 */
9124 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9125 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9126 				    dst_ill->ill_phys_addr_length,
9127 				    dst_ill->ill_sap,
9128 				    dst_ill->ill_sap_length);
9129 			} else {
9130 				/* use the value set in ip_ll_subnet_defaults */
9131 				res_mp = ill_dlur_gen(NULL,
9132 				    dst_ill->ill_phys_addr_length,
9133 				    dst_ill->ill_sap,
9134 				    dst_ill->ill_sap_length);
9135 			}
9136 
9137 			if (res_mp == NULL)
9138 				break;
9139 			/*
9140 			 * The new ire inherits the IRE_OFFSUBNET flags
9141 			 * and source address, if this was requested.
9142 			 */
9143 			ire = ire_create(
9144 			    (uchar_t *)&dst,		/* dest address */
9145 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9146 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9147 			    NULL,			/* gateway address */
9148 			    NULL,
9149 			    &ipif->ipif_mtu,
9150 			    NULL,			/* Fast Path header */
9151 			    dst_ill->ill_rq,		/* recv-from queue */
9152 			    dst_ill->ill_wq,		/* send-to queue */
9153 			    IRE_CACHE,
9154 			    res_mp,
9155 			    src_ipif,
9156 			    NULL,
9157 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9158 			    (fire != NULL) ?		/* Parent handle */
9159 				fire->ire_phandle : 0,
9160 			    ihandle,			/* Interface handle */
9161 			    (fire != NULL) ?
9162 				(fire->ire_flags &
9163 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9164 			    (save_ire == NULL ? &ire_uinfo_null :
9165 				&save_ire->ire_uinfo),
9166 			    NULL,
9167 			    NULL);
9168 
9169 			freeb(res_mp);
9170 
9171 			if (ire == NULL) {
9172 				if (save_ire != NULL)
9173 					ire_refrele(save_ire);
9174 				break;
9175 			}
9176 
9177 			ire->ire_marks |= ire_marks;
9178 
9179 			/*
9180 			 * If IRE_MARK_NOADD is set then we need to convert
9181 			 * the max_fragp to a useable value now. This is
9182 			 * normally done in ire_add_v[46]. We also need to
9183 			 * associate the ire with an nce (normally would be
9184 			 * done in ip_wput_nondata()).
9185 			 *
9186 			 * Note that IRE_MARK_NOADD packets created here
9187 			 * do not have a non-null ire_mp pointer. The null
9188 			 * value of ire_bucket indicates that they were
9189 			 * never added.
9190 			 */
9191 			if (ire->ire_marks & IRE_MARK_NOADD) {
9192 				uint_t  max_frag;
9193 
9194 				max_frag = *ire->ire_max_fragp;
9195 				ire->ire_max_fragp = NULL;
9196 				ire->ire_max_frag = max_frag;
9197 
9198 				if ((ire->ire_nce = ndp_lookup_v4(
9199 				    ire_to_ill(ire),
9200 				    (ire->ire_gateway_addr != INADDR_ANY ?
9201 				    &ire->ire_gateway_addr : &ire->ire_addr),
9202 				    B_FALSE)) == NULL) {
9203 					if (save_ire != NULL)
9204 						ire_refrele(save_ire);
9205 					break;
9206 				}
9207 				ASSERT(ire->ire_nce->nce_state ==
9208 				    ND_REACHABLE);
9209 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9210 			}
9211 
9212 			/* Prevent save_ire from getting deleted */
9213 			if (save_ire != NULL) {
9214 				IRB_REFHOLD(save_ire->ire_bucket);
9215 				/* Has it been removed already ? */
9216 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9217 					IRB_REFRELE(save_ire->ire_bucket);
9218 					ire_refrele(save_ire);
9219 					break;
9220 				}
9221 			}
9222 
9223 			ire_add_then_send(q, ire, first_mp);
9224 
9225 			/* Assert that save_ire is not deleted yet. */
9226 			if (save_ire != NULL) {
9227 				ASSERT(save_ire->ire_ptpn != NULL);
9228 				IRB_REFRELE(save_ire->ire_bucket);
9229 				ire_refrele(save_ire);
9230 				save_ire = NULL;
9231 			}
9232 			if (fire != NULL) {
9233 				ire_refrele(fire);
9234 				fire = NULL;
9235 			}
9236 
9237 			/*
9238 			 * the resolution loop is re-entered if this
9239 			 * was requested through flags and if we
9240 			 * actually are in a multirouting case.
9241 			 */
9242 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9243 				boolean_t need_resolve =
9244 				    ire_multirt_need_resolve(ipha_dst,
9245 					MBLK_GETLABEL(copy_mp));
9246 				if (!need_resolve) {
9247 					MULTIRT_DEBUG_UNTAG(copy_mp);
9248 					freemsg(copy_mp);
9249 					copy_mp = NULL;
9250 				} else {
9251 					/*
9252 					 * ipif_lookup_group() calls
9253 					 * ire_lookup_multi() that uses
9254 					 * ire_ftable_lookup() to find
9255 					 * an IRE_INTERFACE for the group.
9256 					 * In the multirt case,
9257 					 * ire_lookup_multi() then invokes
9258 					 * ire_multirt_lookup() to find
9259 					 * the next resolvable ire.
9260 					 * As a result, we obtain an new
9261 					 * interface, derived from the
9262 					 * next ire.
9263 					 */
9264 					ipif_refrele(ipif);
9265 					ipif = ipif_lookup_group(ipha_dst,
9266 					    zoneid);
9267 					ip2dbg(("ip_newroute_ipif: "
9268 					    "multirt dst %08x, ipif %p\n",
9269 					    htonl(dst), (void *)ipif));
9270 					if (ipif != NULL) {
9271 						mp = copy_mp;
9272 						copy_mp = NULL;
9273 						multirt_resolve_next = B_TRUE;
9274 						continue;
9275 					} else {
9276 						freemsg(copy_mp);
9277 					}
9278 				}
9279 			}
9280 			if (ipif != NULL)
9281 				ipif_refrele(ipif);
9282 			ill_refrele(dst_ill);
9283 			ipif_refrele(src_ipif);
9284 			return;
9285 		}
9286 		case IRE_IF_RESOLVER:
9287 			/*
9288 			 * We can't build an IRE_CACHE yet, but at least
9289 			 * we found a resolver that can help.
9290 			 */
9291 			res_mp = dst_ill->ill_resolver_mp;
9292 			if (!OK_RESOLVER_MP(res_mp))
9293 				break;
9294 
9295 			/*
9296 			 * We obtain a partial IRE_CACHE which we will pass
9297 			 * along with the resolver query.  When the response
9298 			 * comes back it will be there ready for us to add.
9299 			 * The new ire inherits the IRE_OFFSUBNET flags
9300 			 * and source address, if this was requested.
9301 			 * The ire_max_frag is atomically set under the
9302 			 * irebucket lock in ire_add_v[46]. Only in the
9303 			 * case of IRE_MARK_NOADD, we set it here itself.
9304 			 */
9305 			ire = ire_create_mp(
9306 			    (uchar_t *)&dst,		/* dest address */
9307 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9308 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9309 			    NULL,			/* gateway address */
9310 			    NULL,			/* no in_src_addr */
9311 			    (ire_marks & IRE_MARK_NOADD) ?
9312 				ipif->ipif_mtu : 0,	/* max_frag */
9313 			    NULL,			/* Fast path header */
9314 			    dst_ill->ill_rq,		/* recv-from queue */
9315 			    dst_ill->ill_wq,		/* send-to queue */
9316 			    IRE_CACHE,
9317 			    NULL,	/* let ire_nce_init figure res_mp out */
9318 			    src_ipif,
9319 			    NULL,
9320 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9321 			    (fire != NULL) ?		/* Parent handle */
9322 				fire->ire_phandle : 0,
9323 			    ihandle,			/* Interface handle */
9324 			    (fire != NULL) ?		/* flags if any */
9325 				(fire->ire_flags &
9326 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9327 			    (save_ire == NULL ? &ire_uinfo_null :
9328 				&save_ire->ire_uinfo),
9329 			    NULL,
9330 			    NULL);
9331 
9332 			if (save_ire != NULL) {
9333 				ire_refrele(save_ire);
9334 				save_ire = NULL;
9335 			}
9336 			if (ire == NULL)
9337 				break;
9338 
9339 			ire->ire_marks |= ire_marks;
9340 			/*
9341 			 * Construct message chain for the resolver of the
9342 			 * form:
9343 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9344 			 *
9345 			 * NOTE : ire will be added later when the response
9346 			 * comes back from ARP. If the response does not
9347 			 * come back, ARP frees the packet. For this reason,
9348 			 * we can't REFHOLD the bucket of save_ire to prevent
9349 			 * deletions. We may not be able to REFRELE the
9350 			 * bucket if the response never comes back.
9351 			 * Thus, before adding the ire, ire_add_v4 will make
9352 			 * sure that the interface route does not get deleted.
9353 			 * This is the only case unlike ip_newroute_v6,
9354 			 * ip_newroute_ipif_v6 where we can always prevent
9355 			 * deletions because ire_add_then_send is called after
9356 			 * creating the IRE.
9357 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9358 			 * does not add this IRE into the IRE CACHE.
9359 			 */
9360 			ASSERT(ire->ire_mp != NULL);
9361 			ire->ire_mp->b_cont = first_mp;
9362 			/* Have saved_mp handy, for cleanup if canput fails */
9363 			saved_mp = mp;
9364 			mp = copyb(res_mp);
9365 			if (mp == NULL) {
9366 				/* Prepare for cleanup */
9367 				mp = saved_mp; /* pkt */
9368 				ire_delete(ire); /* ire_mp */
9369 				ire = NULL;
9370 				if (copy_mp != NULL) {
9371 					MULTIRT_DEBUG_UNTAG(copy_mp);
9372 					freemsg(copy_mp);
9373 					copy_mp = NULL;
9374 				}
9375 				break;
9376 			}
9377 			linkb(mp, ire->ire_mp);
9378 
9379 			/*
9380 			 * Fill in the source and dest addrs for the resolver.
9381 			 * NOTE: this depends on memory layouts imposed by
9382 			 * ill_init().
9383 			 */
9384 			areq = (areq_t *)mp->b_rptr;
9385 			addrp = (ipaddr_t *)((char *)areq +
9386 			    areq->areq_sender_addr_offset);
9387 			*addrp = ire->ire_src_addr;
9388 			addrp = (ipaddr_t *)((char *)areq +
9389 			    areq->areq_target_addr_offset);
9390 			*addrp = dst;
9391 			/* Up to the resolver. */
9392 			if (canputnext(dst_ill->ill_rq) &&
9393 			    !(dst_ill->ill_arp_closing)) {
9394 				putnext(dst_ill->ill_rq, mp);
9395 				/*
9396 				 * The response will come back in ip_wput
9397 				 * with db_type IRE_DB_TYPE.
9398 				 */
9399 			} else {
9400 				mp->b_cont = NULL;
9401 				freeb(mp); /* areq */
9402 				ire_delete(ire); /* ire_mp */
9403 				saved_mp->b_next = NULL;
9404 				saved_mp->b_prev = NULL;
9405 				freemsg(first_mp); /* pkt */
9406 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9407 			}
9408 
9409 			if (fire != NULL) {
9410 				ire_refrele(fire);
9411 				fire = NULL;
9412 			}
9413 
9414 
9415 			/*
9416 			 * The resolution loop is re-entered if this was
9417 			 * requested through flags and we actually are
9418 			 * in a multirouting case.
9419 			 */
9420 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9421 				boolean_t need_resolve =
9422 				    ire_multirt_need_resolve(ipha_dst,
9423 					MBLK_GETLABEL(copy_mp));
9424 				if (!need_resolve) {
9425 					MULTIRT_DEBUG_UNTAG(copy_mp);
9426 					freemsg(copy_mp);
9427 					copy_mp = NULL;
9428 				} else {
9429 					/*
9430 					 * ipif_lookup_group() calls
9431 					 * ire_lookup_multi() that uses
9432 					 * ire_ftable_lookup() to find
9433 					 * an IRE_INTERFACE for the group.
9434 					 * In the multirt case,
9435 					 * ire_lookup_multi() then invokes
9436 					 * ire_multirt_lookup() to find
9437 					 * the next resolvable ire.
9438 					 * As a result, we obtain an new
9439 					 * interface, derived from the
9440 					 * next ire.
9441 					 */
9442 					ipif_refrele(ipif);
9443 					ipif = ipif_lookup_group(ipha_dst,
9444 					    zoneid);
9445 					if (ipif != NULL) {
9446 						mp = copy_mp;
9447 						copy_mp = NULL;
9448 						multirt_resolve_next = B_TRUE;
9449 						continue;
9450 					} else {
9451 						freemsg(copy_mp);
9452 					}
9453 				}
9454 			}
9455 			if (ipif != NULL)
9456 				ipif_refrele(ipif);
9457 			ill_refrele(dst_ill);
9458 			ipif_refrele(src_ipif);
9459 			return;
9460 		default:
9461 			break;
9462 		}
9463 	} while (multirt_resolve_next);
9464 
9465 err_ret:
9466 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9467 	if (fire != NULL)
9468 		ire_refrele(fire);
9469 	ipif_refrele(ipif);
9470 	/* Did this packet originate externally? */
9471 	if (dst_ill != NULL)
9472 		ill_refrele(dst_ill);
9473 	if (src_ipif != NULL)
9474 		ipif_refrele(src_ipif);
9475 	if (mp->b_prev || mp->b_next) {
9476 		mp->b_next = NULL;
9477 		mp->b_prev = NULL;
9478 	} else {
9479 		/*
9480 		 * Since ip_wput() isn't close to finished, we fill
9481 		 * in enough of the header for credible error reporting.
9482 		 */
9483 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9484 			/* Failed */
9485 			freemsg(first_mp);
9486 			if (ire != NULL)
9487 				ire_refrele(ire);
9488 			return;
9489 		}
9490 	}
9491 	/*
9492 	 * At this point we will have ire only if RTF_BLACKHOLE
9493 	 * or RTF_REJECT flags are set on the IRE. It will not
9494 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9495 	 */
9496 	if (ire != NULL) {
9497 		if (ire->ire_flags & RTF_BLACKHOLE) {
9498 			ire_refrele(ire);
9499 			freemsg(first_mp);
9500 			return;
9501 		}
9502 		ire_refrele(ire);
9503 	}
9504 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9505 }
9506 
9507 /* Name/Value Table Lookup Routine */
9508 char *
9509 ip_nv_lookup(nv_t *nv, int value)
9510 {
9511 	if (!nv)
9512 		return (NULL);
9513 	for (; nv->nv_name; nv++) {
9514 		if (nv->nv_value == value)
9515 			return (nv->nv_name);
9516 	}
9517 	return ("unknown");
9518 }
9519 
9520 /*
9521  * one day it can be patched to 1 from /etc/system for machines that have few
9522  * fast network interfaces feeding multiple cpus.
9523  */
9524 int ill_stream_putlocks = 0;
9525 
9526 /*
9527  * This is a module open, i.e. this is a control stream for access
9528  * to a DLPI device.  We allocate an ill_t as the instance data in
9529  * this case.
9530  */
9531 int
9532 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9533 {
9534 	uint32_t mem_cnt;
9535 	uint32_t cpu_cnt;
9536 	uint32_t min_cnt;
9537 	pgcnt_t mem_avail;
9538 	ill_t	*ill;
9539 	int	err;
9540 
9541 	/*
9542 	 * Prevent unprivileged processes from pushing IP so that
9543 	 * they can't send raw IP.
9544 	 */
9545 	if (secpolicy_net_rawaccess(credp) != 0)
9546 		return (EPERM);
9547 
9548 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9549 	q->q_ptr = WR(q)->q_ptr = ill;
9550 
9551 	/*
9552 	 * ill_init initializes the ill fields and then sends down
9553 	 * down a DL_INFO_REQ after calling qprocson.
9554 	 */
9555 	err = ill_init(q, ill);
9556 	if (err != 0) {
9557 		mi_free(ill);
9558 		q->q_ptr = NULL;
9559 		WR(q)->q_ptr = NULL;
9560 		return (err);
9561 	}
9562 
9563 	/* ill_init initializes the ipsq marking this thread as writer */
9564 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9565 	/* Wait for the DL_INFO_ACK */
9566 	mutex_enter(&ill->ill_lock);
9567 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9568 		/*
9569 		 * Return value of 0 indicates a pending signal.
9570 		 */
9571 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9572 		if (err == 0) {
9573 			mutex_exit(&ill->ill_lock);
9574 			(void) ip_close(q, 0);
9575 			return (EINTR);
9576 		}
9577 	}
9578 	mutex_exit(&ill->ill_lock);
9579 
9580 	/*
9581 	 * ip_rput_other could have set an error  in ill_error on
9582 	 * receipt of M_ERROR.
9583 	 */
9584 
9585 	err = ill->ill_error;
9586 	if (err != 0) {
9587 		(void) ip_close(q, 0);
9588 		return (err);
9589 	}
9590 
9591 	/*
9592 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9593 	 * size and the cpu speed of the machine. This is upper
9594 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9595 	 * and is lower bounded by the compile time value of
9596 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9597 	 * ip6_ire_max_bucket_cnt.
9598 	 */
9599 	mem_avail = kmem_avail();
9600 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9601 	    ip_cache_table_size / sizeof (ire_t);
9602 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9603 
9604 	min_cnt = MIN(cpu_cnt, mem_cnt);
9605 	if (min_cnt < ip_ire_min_bucket_cnt)
9606 		min_cnt = ip_ire_min_bucket_cnt;
9607 	if (ip_ire_max_bucket_cnt > min_cnt) {
9608 		ip_ire_max_bucket_cnt = min_cnt;
9609 	}
9610 
9611 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9612 	    ip6_cache_table_size / sizeof (ire_t);
9613 	min_cnt = MIN(cpu_cnt, mem_cnt);
9614 	if (min_cnt < ip6_ire_min_bucket_cnt)
9615 		min_cnt = ip6_ire_min_bucket_cnt;
9616 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9617 		ip6_ire_max_bucket_cnt = min_cnt;
9618 	}
9619 
9620 	ill->ill_credp = credp;
9621 	crhold(credp);
9622 
9623 	mutex_enter(&ip_mi_lock);
9624 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9625 	mutex_exit(&ip_mi_lock);
9626 	if (err) {
9627 		(void) ip_close(q, 0);
9628 		return (err);
9629 	}
9630 	return (0);
9631 }
9632 
9633 /* IP open routine. */
9634 int
9635 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9636 {
9637 	conn_t 		*connp;
9638 	major_t		maj;
9639 
9640 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9641 
9642 	/* Allow reopen. */
9643 	if (q->q_ptr != NULL)
9644 		return (0);
9645 
9646 	if (sflag & MODOPEN) {
9647 		/* This is a module open */
9648 		return (ip_modopen(q, devp, flag, sflag, credp));
9649 	}
9650 
9651 	/*
9652 	 * We are opening as a device. This is an IP client stream, and we
9653 	 * allocate an conn_t as the instance data.
9654 	 */
9655 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9656 	connp->conn_upq = q;
9657 	q->q_ptr = WR(q)->q_ptr = connp;
9658 
9659 	if (flag & SO_SOCKSTR)
9660 		connp->conn_flags |= IPCL_SOCKET;
9661 
9662 	/* Minor tells us which /dev entry was opened */
9663 	if (geteminor(*devp) == IPV6_MINOR) {
9664 		connp->conn_flags |= IPCL_ISV6;
9665 		connp->conn_af_isv6 = B_TRUE;
9666 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9667 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9668 	} else {
9669 		connp->conn_af_isv6 = B_FALSE;
9670 		connp->conn_pkt_isv6 = B_FALSE;
9671 	}
9672 
9673 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9674 		q->q_ptr = WR(q)->q_ptr = NULL;
9675 		CONN_DEC_REF(connp);
9676 		return (EBUSY);
9677 	}
9678 
9679 	maj = getemajor(*devp);
9680 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9681 
9682 	/*
9683 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9684 	 */
9685 	connp->conn_cred = credp;
9686 	crhold(connp->conn_cred);
9687 
9688 	/*
9689 	 * If the caller has the process-wide flag set, then default to MAC
9690 	 * exempt mode.  This allows read-down to unlabeled hosts.
9691 	 */
9692 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9693 		connp->conn_mac_exempt = B_TRUE;
9694 
9695 	connp->conn_zoneid = getzoneid();
9696 
9697 	/*
9698 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9699 	 * administrative ops.  In these cases, we just need a normal conn_t
9700 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9701 	 * an error will be returned.
9702 	 */
9703 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9704 		connp->conn_rq = q;
9705 		connp->conn_wq = WR(q);
9706 	} else {
9707 		connp->conn_ulp = IPPROTO_SCTP;
9708 		connp->conn_rq = connp->conn_wq = NULL;
9709 	}
9710 	/* Non-zero default values */
9711 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9712 
9713 	/*
9714 	 * Make the conn globally visible to walkers
9715 	 */
9716 	mutex_enter(&connp->conn_lock);
9717 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9718 	mutex_exit(&connp->conn_lock);
9719 	ASSERT(connp->conn_ref == 1);
9720 
9721 	qprocson(q);
9722 
9723 	return (0);
9724 }
9725 
9726 /*
9727  * Change q_qinfo based on the value of isv6.
9728  * This can not called on an ill queue.
9729  * Note that there is no race since either q_qinfo works for conn queues - it
9730  * is just an optimization to enter the best wput routine directly.
9731  */
9732 void
9733 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9734 {
9735 	ASSERT(q->q_flag & QREADR);
9736 	ASSERT(WR(q)->q_next == NULL);
9737 	ASSERT(q->q_ptr != NULL);
9738 
9739 	if (minor == IPV6_MINOR)  {
9740 		if (bump_mib)
9741 			BUMP_MIB(&ip6_mib, ipv6OutSwitchIPv4);
9742 		q->q_qinfo = &rinit_ipv6;
9743 		WR(q)->q_qinfo = &winit_ipv6;
9744 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9745 	} else {
9746 		if (bump_mib)
9747 			BUMP_MIB(&ip_mib, ipOutSwitchIPv6);
9748 		q->q_qinfo = &iprinit;
9749 		WR(q)->q_qinfo = &ipwinit;
9750 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9751 	}
9752 
9753 }
9754 
9755 /*
9756  * See if IPsec needs loading because of the options in mp.
9757  */
9758 static boolean_t
9759 ipsec_opt_present(mblk_t *mp)
9760 {
9761 	uint8_t *optcp, *next_optcp, *opt_endcp;
9762 	struct opthdr *opt;
9763 	struct T_opthdr *topt;
9764 	int opthdr_len;
9765 	t_uscalar_t optname, optlevel;
9766 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9767 	ipsec_req_t *ipsr;
9768 
9769 	/*
9770 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9771 	 * return TRUE.
9772 	 */
9773 
9774 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9775 	opt_endcp = optcp + tor->OPT_length;
9776 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9777 		opthdr_len = sizeof (struct T_opthdr);
9778 	} else {		/* O_OPTMGMT_REQ */
9779 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9780 		opthdr_len = sizeof (struct opthdr);
9781 	}
9782 	for (; optcp < opt_endcp; optcp = next_optcp) {
9783 		if (optcp + opthdr_len > opt_endcp)
9784 			return (B_FALSE);	/* Not enough option header. */
9785 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9786 			topt = (struct T_opthdr *)optcp;
9787 			optlevel = topt->level;
9788 			optname = topt->name;
9789 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9790 		} else {
9791 			opt = (struct opthdr *)optcp;
9792 			optlevel = opt->level;
9793 			optname = opt->name;
9794 			next_optcp = optcp + opthdr_len +
9795 			    _TPI_ALIGN_OPT(opt->len);
9796 		}
9797 		if ((next_optcp < optcp) || /* wraparound pointer space */
9798 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9799 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9800 			return (B_FALSE); /* bad option buffer */
9801 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9802 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9803 			/*
9804 			 * Check to see if it's an all-bypass or all-zeroes
9805 			 * IPsec request.  Don't bother loading IPsec if
9806 			 * the socket doesn't want to use it.  (A good example
9807 			 * is a bypass request.)
9808 			 *
9809 			 * Basically, if any of the non-NEVER bits are set,
9810 			 * load IPsec.
9811 			 */
9812 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9813 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9814 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9815 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9816 			    != 0)
9817 				return (B_TRUE);
9818 		}
9819 	}
9820 	return (B_FALSE);
9821 }
9822 
9823 /*
9824  * If conn is is waiting for ipsec to finish loading, kick it.
9825  */
9826 /* ARGSUSED */
9827 static void
9828 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9829 {
9830 	t_scalar_t	optreq_prim;
9831 	mblk_t		*mp;
9832 	cred_t		*cr;
9833 	int		err = 0;
9834 
9835 	/*
9836 	 * This function is called, after ipsec loading is complete.
9837 	 * Since IP checks exclusively and atomically (i.e it prevents
9838 	 * ipsec load from completing until ip_optcom_req completes)
9839 	 * whether ipsec load is complete, there cannot be a race with IP
9840 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9841 	 */
9842 	mutex_enter(&connp->conn_lock);
9843 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9844 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9845 		mp = connp->conn_ipsec_opt_mp;
9846 		connp->conn_ipsec_opt_mp = NULL;
9847 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9848 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9849 		mutex_exit(&connp->conn_lock);
9850 
9851 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9852 
9853 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9854 		if (optreq_prim == T_OPTMGMT_REQ) {
9855 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9856 			    &ip_opt_obj);
9857 		} else {
9858 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9859 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9860 			    &ip_opt_obj);
9861 		}
9862 		if (err != EINPROGRESS)
9863 			CONN_OPER_PENDING_DONE(connp);
9864 		return;
9865 	}
9866 	mutex_exit(&connp->conn_lock);
9867 }
9868 
9869 /*
9870  * Called from the ipsec_loader thread, outside any perimeter, to tell
9871  * ip qenable any of the queues waiting for the ipsec loader to
9872  * complete.
9873  *
9874  * Use ip_mi_lock to be safe here: all modifications of the mi lists
9875  * are done with this lock held, so it's guaranteed that none of the
9876  * links will change along the way.
9877  */
9878 void
9879 ip_ipsec_load_complete()
9880 {
9881 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
9882 }
9883 
9884 /*
9885  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9886  * determines the grp on which it has to become exclusive, queues the mp
9887  * and sq draining restarts the optmgmt
9888  */
9889 static boolean_t
9890 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9891 {
9892 	conn_t *connp;
9893 
9894 	/*
9895 	 * Take IPsec requests and treat them special.
9896 	 */
9897 	if (ipsec_opt_present(mp)) {
9898 		/* First check if IPsec is loaded. */
9899 		mutex_enter(&ipsec_loader_lock);
9900 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
9901 			mutex_exit(&ipsec_loader_lock);
9902 			return (B_FALSE);
9903 		}
9904 		connp = Q_TO_CONN(q);
9905 		mutex_enter(&connp->conn_lock);
9906 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9907 
9908 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9909 		connp->conn_ipsec_opt_mp = mp;
9910 		mutex_exit(&connp->conn_lock);
9911 		mutex_exit(&ipsec_loader_lock);
9912 
9913 		ipsec_loader_loadnow();
9914 		return (B_TRUE);
9915 	}
9916 	return (B_FALSE);
9917 }
9918 
9919 /*
9920  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9921  * all of them are copied to the conn_t. If the req is "zero", the policy is
9922  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9923  * fields.
9924  * We keep only the latest setting of the policy and thus policy setting
9925  * is not incremental/cumulative.
9926  *
9927  * Requests to set policies with multiple alternative actions will
9928  * go through a different API.
9929  */
9930 int
9931 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9932 {
9933 	uint_t ah_req = 0;
9934 	uint_t esp_req = 0;
9935 	uint_t se_req = 0;
9936 	ipsec_selkey_t sel;
9937 	ipsec_act_t *actp = NULL;
9938 	uint_t nact;
9939 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9940 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9941 	ipsec_policy_root_t *pr;
9942 	ipsec_policy_head_t *ph;
9943 	int fam;
9944 	boolean_t is_pol_reset;
9945 	int error = 0;
9946 
9947 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
9948 
9949 	/*
9950 	 * The IP_SEC_OPT option does not allow variable length parameters,
9951 	 * hence a request cannot be NULL.
9952 	 */
9953 	if (req == NULL)
9954 		return (EINVAL);
9955 
9956 	ah_req = req->ipsr_ah_req;
9957 	esp_req = req->ipsr_esp_req;
9958 	se_req = req->ipsr_self_encap_req;
9959 
9960 	/*
9961 	 * Are we dealing with a request to reset the policy (i.e.
9962 	 * zero requests).
9963 	 */
9964 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
9965 	    (esp_req & REQ_MASK) == 0 &&
9966 	    (se_req & REQ_MASK) == 0);
9967 
9968 	if (!is_pol_reset) {
9969 		/*
9970 		 * If we couldn't load IPsec, fail with "protocol
9971 		 * not supported".
9972 		 * IPsec may not have been loaded for a request with zero
9973 		 * policies, so we don't fail in this case.
9974 		 */
9975 		mutex_enter(&ipsec_loader_lock);
9976 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
9977 			mutex_exit(&ipsec_loader_lock);
9978 			return (EPROTONOSUPPORT);
9979 		}
9980 		mutex_exit(&ipsec_loader_lock);
9981 
9982 		/*
9983 		 * Test for valid requests. Invalid algorithms
9984 		 * need to be tested by IPSEC code because new
9985 		 * algorithms can be added dynamically.
9986 		 */
9987 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9988 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
9989 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
9990 			return (EINVAL);
9991 		}
9992 
9993 		/*
9994 		 * Only privileged users can issue these
9995 		 * requests.
9996 		 */
9997 		if (((ah_req & IPSEC_PREF_NEVER) ||
9998 		    (esp_req & IPSEC_PREF_NEVER) ||
9999 		    (se_req & IPSEC_PREF_NEVER)) &&
10000 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10001 			return (EPERM);
10002 		}
10003 
10004 		/*
10005 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10006 		 * are mutually exclusive.
10007 		 */
10008 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10009 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10010 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10011 			/* Both of them are set */
10012 			return (EINVAL);
10013 		}
10014 	}
10015 
10016 	mutex_enter(&connp->conn_lock);
10017 
10018 	/*
10019 	 * If we have already cached policies in ip_bind_connected*(), don't
10020 	 * let them change now. We cache policies for connections
10021 	 * whose src,dst [addr, port] is known.
10022 	 */
10023 	if (connp->conn_policy_cached) {
10024 		mutex_exit(&connp->conn_lock);
10025 		return (EINVAL);
10026 	}
10027 
10028 	/*
10029 	 * We have a zero policies, reset the connection policy if already
10030 	 * set. This will cause the connection to inherit the
10031 	 * global policy, if any.
10032 	 */
10033 	if (is_pol_reset) {
10034 		if (connp->conn_policy != NULL) {
10035 			IPPH_REFRELE(connp->conn_policy);
10036 			connp->conn_policy = NULL;
10037 		}
10038 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10039 		connp->conn_in_enforce_policy = B_FALSE;
10040 		connp->conn_out_enforce_policy = B_FALSE;
10041 		mutex_exit(&connp->conn_lock);
10042 		return (0);
10043 	}
10044 
10045 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10046 	if (ph == NULL)
10047 		goto enomem;
10048 
10049 	ipsec_actvec_from_req(req, &actp, &nact);
10050 	if (actp == NULL)
10051 		goto enomem;
10052 
10053 	/*
10054 	 * Always allocate IPv4 policy entries, since they can also
10055 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10056 	 */
10057 	bzero(&sel, sizeof (sel));
10058 	sel.ipsl_valid = IPSL_IPV4;
10059 
10060 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10061 	if (pin4 == NULL)
10062 		goto enomem;
10063 
10064 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10065 	if (pout4 == NULL)
10066 		goto enomem;
10067 
10068 	if (connp->conn_pkt_isv6) {
10069 		/*
10070 		 * We're looking at a v6 socket, also allocate the
10071 		 * v6-specific entries...
10072 		 */
10073 		sel.ipsl_valid = IPSL_IPV6;
10074 		pin6 = ipsec_policy_create(&sel, actp, nact,
10075 		    IPSEC_PRIO_SOCKET, NULL);
10076 		if (pin6 == NULL)
10077 			goto enomem;
10078 
10079 		pout6 = ipsec_policy_create(&sel, actp, nact,
10080 		    IPSEC_PRIO_SOCKET, NULL);
10081 		if (pout6 == NULL)
10082 			goto enomem;
10083 
10084 		/*
10085 		 * .. and file them away in the right place.
10086 		 */
10087 		fam = IPSEC_AF_V6;
10088 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10089 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10090 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10091 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10092 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10093 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10094 	}
10095 
10096 	ipsec_actvec_free(actp, nact);
10097 
10098 	/*
10099 	 * File the v4 policies.
10100 	 */
10101 	fam = IPSEC_AF_V4;
10102 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10103 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10104 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10105 
10106 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10107 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10108 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10109 
10110 	/*
10111 	 * If the requests need security, set enforce_policy.
10112 	 * If the requests are IPSEC_PREF_NEVER, one should
10113 	 * still set conn_out_enforce_policy so that an ipsec_out
10114 	 * gets attached in ip_wput. This is needed so that
10115 	 * for connections that we don't cache policy in ip_bind,
10116 	 * if global policy matches in ip_wput_attach_policy, we
10117 	 * don't wrongly inherit global policy. Similarly, we need
10118 	 * to set conn_in_enforce_policy also so that we don't verify
10119 	 * policy wrongly.
10120 	 */
10121 	if ((ah_req & REQ_MASK) != 0 ||
10122 	    (esp_req & REQ_MASK) != 0 ||
10123 	    (se_req & REQ_MASK) != 0) {
10124 		connp->conn_in_enforce_policy = B_TRUE;
10125 		connp->conn_out_enforce_policy = B_TRUE;
10126 		connp->conn_flags |= IPCL_CHECK_POLICY;
10127 	}
10128 
10129 	mutex_exit(&connp->conn_lock);
10130 	return (error);
10131 #undef REQ_MASK
10132 
10133 	/*
10134 	 * Common memory-allocation-failure exit path.
10135 	 */
10136 enomem:
10137 	mutex_exit(&connp->conn_lock);
10138 	if (actp != NULL)
10139 		ipsec_actvec_free(actp, nact);
10140 	if (pin4 != NULL)
10141 		IPPOL_REFRELE(pin4);
10142 	if (pout4 != NULL)
10143 		IPPOL_REFRELE(pout4);
10144 	if (pin6 != NULL)
10145 		IPPOL_REFRELE(pin6);
10146 	if (pout6 != NULL)
10147 		IPPOL_REFRELE(pout6);
10148 	return (ENOMEM);
10149 }
10150 
10151 /*
10152  * Only for options that pass in an IP addr. Currently only V4 options
10153  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10154  * So this function assumes level is IPPROTO_IP
10155  */
10156 int
10157 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10158     mblk_t *first_mp)
10159 {
10160 	ipif_t *ipif = NULL;
10161 	int error;
10162 	ill_t *ill;
10163 	int zoneid;
10164 
10165 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10166 
10167 	if (addr != INADDR_ANY || checkonly) {
10168 		ASSERT(connp != NULL);
10169 		zoneid = IPCL_ZONEID(connp);
10170 		if (option == IP_NEXTHOP) {
10171 			ipif = ipif_lookup_onlink_addr(addr,
10172 			    connp->conn_zoneid);
10173 		} else {
10174 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10175 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10176 			    &error);
10177 		}
10178 		if (ipif == NULL) {
10179 			if (error == EINPROGRESS)
10180 				return (error);
10181 			else if ((option == IP_MULTICAST_IF) ||
10182 			    (option == IP_NEXTHOP))
10183 				return (EHOSTUNREACH);
10184 			else
10185 				return (EINVAL);
10186 		} else if (checkonly) {
10187 			if (option == IP_MULTICAST_IF) {
10188 				ill = ipif->ipif_ill;
10189 				/* not supported by the virtual network iface */
10190 				if (IS_VNI(ill)) {
10191 					ipif_refrele(ipif);
10192 					return (EINVAL);
10193 				}
10194 			}
10195 			ipif_refrele(ipif);
10196 			return (0);
10197 		}
10198 		ill = ipif->ipif_ill;
10199 		mutex_enter(&connp->conn_lock);
10200 		mutex_enter(&ill->ill_lock);
10201 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10202 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10203 			mutex_exit(&ill->ill_lock);
10204 			mutex_exit(&connp->conn_lock);
10205 			ipif_refrele(ipif);
10206 			return (option == IP_MULTICAST_IF ?
10207 			    EHOSTUNREACH : EINVAL);
10208 		}
10209 	} else {
10210 		mutex_enter(&connp->conn_lock);
10211 	}
10212 
10213 	/* None of the options below are supported on the VNI */
10214 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10215 		mutex_exit(&ill->ill_lock);
10216 		mutex_exit(&connp->conn_lock);
10217 		ipif_refrele(ipif);
10218 		return (EINVAL);
10219 	}
10220 
10221 	switch (option) {
10222 	case IP_DONTFAILOVER_IF:
10223 		/*
10224 		 * This option is used by in.mpathd to ensure
10225 		 * that IPMP probe packets only go out on the
10226 		 * test interfaces. in.mpathd sets this option
10227 		 * on the non-failover interfaces.
10228 		 * For backward compatibility, this option
10229 		 * implicitly sets IP_MULTICAST_IF, as used
10230 		 * be done in bind(), so that ip_wput gets
10231 		 * this ipif to send mcast packets.
10232 		 */
10233 		if (ipif != NULL) {
10234 			ASSERT(addr != INADDR_ANY);
10235 			connp->conn_nofailover_ill = ipif->ipif_ill;
10236 			connp->conn_multicast_ipif = ipif;
10237 		} else {
10238 			ASSERT(addr == INADDR_ANY);
10239 			connp->conn_nofailover_ill = NULL;
10240 			connp->conn_multicast_ipif = NULL;
10241 		}
10242 		break;
10243 
10244 	case IP_MULTICAST_IF:
10245 		connp->conn_multicast_ipif = ipif;
10246 		break;
10247 	case IP_NEXTHOP:
10248 		connp->conn_nexthop_v4 = addr;
10249 		connp->conn_nexthop_set = B_TRUE;
10250 		break;
10251 	}
10252 
10253 	if (ipif != NULL) {
10254 		mutex_exit(&ill->ill_lock);
10255 		mutex_exit(&connp->conn_lock);
10256 		ipif_refrele(ipif);
10257 		return (0);
10258 	}
10259 	mutex_exit(&connp->conn_lock);
10260 	/* We succeded in cleared the option */
10261 	return (0);
10262 }
10263 
10264 /*
10265  * For options that pass in an ifindex specifying the ill. V6 options always
10266  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10267  */
10268 int
10269 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10270     int level, int option, mblk_t *first_mp)
10271 {
10272 	ill_t *ill = NULL;
10273 	int error = 0;
10274 
10275 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10276 	if (ifindex != 0) {
10277 		ASSERT(connp != NULL);
10278 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10279 		    first_mp, ip_restart_optmgmt, &error);
10280 		if (ill != NULL) {
10281 			if (checkonly) {
10282 				/* not supported by the virtual network iface */
10283 				if (IS_VNI(ill)) {
10284 					ill_refrele(ill);
10285 					return (EINVAL);
10286 				}
10287 				ill_refrele(ill);
10288 				return (0);
10289 			}
10290 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10291 			    0, NULL)) {
10292 				ill_refrele(ill);
10293 				ill = NULL;
10294 				mutex_enter(&connp->conn_lock);
10295 				goto setit;
10296 			}
10297 			mutex_enter(&connp->conn_lock);
10298 			mutex_enter(&ill->ill_lock);
10299 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10300 				mutex_exit(&ill->ill_lock);
10301 				mutex_exit(&connp->conn_lock);
10302 				ill_refrele(ill);
10303 				ill = NULL;
10304 				mutex_enter(&connp->conn_lock);
10305 			}
10306 			goto setit;
10307 		} else if (error == EINPROGRESS) {
10308 			return (error);
10309 		} else {
10310 			error = 0;
10311 		}
10312 	}
10313 	mutex_enter(&connp->conn_lock);
10314 setit:
10315 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10316 
10317 	/*
10318 	 * The options below assume that the ILL (if any) transmits and/or
10319 	 * receives traffic. Neither of which is true for the virtual network
10320 	 * interface, so fail setting these on a VNI.
10321 	 */
10322 	if (IS_VNI(ill)) {
10323 		ASSERT(ill != NULL);
10324 		mutex_exit(&ill->ill_lock);
10325 		mutex_exit(&connp->conn_lock);
10326 		ill_refrele(ill);
10327 		return (EINVAL);
10328 	}
10329 
10330 	if (level == IPPROTO_IP) {
10331 		switch (option) {
10332 		case IP_BOUND_IF:
10333 			connp->conn_incoming_ill = ill;
10334 			connp->conn_outgoing_ill = ill;
10335 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10336 			    0 : ifindex;
10337 			break;
10338 
10339 		case IP_XMIT_IF:
10340 			/*
10341 			 * Similar to IP_BOUND_IF, but this only
10342 			 * determines the outgoing interface for
10343 			 * unicast packets. Also no IRE_CACHE entry
10344 			 * is added for the destination of the
10345 			 * outgoing packets. This feature is needed
10346 			 * for mobile IP.
10347 			 */
10348 			connp->conn_xmit_if_ill = ill;
10349 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10350 			    0 : ifindex;
10351 			break;
10352 
10353 		case IP_MULTICAST_IF:
10354 			/*
10355 			 * This option is an internal special. The socket
10356 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10357 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10358 			 * specifies an ifindex and we try first on V6 ill's.
10359 			 * If we don't find one, we they try using on v4 ill's
10360 			 * intenally and we come here.
10361 			 */
10362 			if (!checkonly && ill != NULL) {
10363 				ipif_t	*ipif;
10364 				ipif = ill->ill_ipif;
10365 
10366 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10367 					mutex_exit(&ill->ill_lock);
10368 					mutex_exit(&connp->conn_lock);
10369 					ill_refrele(ill);
10370 					ill = NULL;
10371 					mutex_enter(&connp->conn_lock);
10372 				} else {
10373 					connp->conn_multicast_ipif = ipif;
10374 				}
10375 			}
10376 			break;
10377 		}
10378 	} else {
10379 		switch (option) {
10380 		case IPV6_BOUND_IF:
10381 			connp->conn_incoming_ill = ill;
10382 			connp->conn_outgoing_ill = ill;
10383 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10384 			    0 : ifindex;
10385 			break;
10386 
10387 		case IPV6_BOUND_PIF:
10388 			/*
10389 			 * Limit all transmit to this ill.
10390 			 * Unlike IPV6_BOUND_IF, using this option
10391 			 * prevents load spreading and failover from
10392 			 * happening when the interface is part of the
10393 			 * group. That's why we don't need to remember
10394 			 * the ifindex in orig_bound_ifindex as in
10395 			 * IPV6_BOUND_IF.
10396 			 */
10397 			connp->conn_outgoing_pill = ill;
10398 			break;
10399 
10400 		case IPV6_DONTFAILOVER_IF:
10401 			/*
10402 			 * This option is used by in.mpathd to ensure
10403 			 * that IPMP probe packets only go out on the
10404 			 * test interfaces. in.mpathd sets this option
10405 			 * on the non-failover interfaces.
10406 			 */
10407 			connp->conn_nofailover_ill = ill;
10408 			/*
10409 			 * For backward compatibility, this option
10410 			 * implicitly sets ip_multicast_ill as used in
10411 			 * IP_MULTICAST_IF so that ip_wput gets
10412 			 * this ipif to send mcast packets.
10413 			 */
10414 			connp->conn_multicast_ill = ill;
10415 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10416 			    0 : ifindex;
10417 			break;
10418 
10419 		case IPV6_MULTICAST_IF:
10420 			/*
10421 			 * Set conn_multicast_ill to be the IPv6 ill.
10422 			 * Set conn_multicast_ipif to be an IPv4 ipif
10423 			 * for ifindex to make IPv4 mapped addresses
10424 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10425 			 * Even if no IPv6 ill exists for the ifindex
10426 			 * we need to check for an IPv4 ifindex in order
10427 			 * for this to work with mapped addresses. In that
10428 			 * case only set conn_multicast_ipif.
10429 			 */
10430 			if (!checkonly) {
10431 				if (ifindex == 0) {
10432 					connp->conn_multicast_ill = NULL;
10433 					connp->conn_orig_multicast_ifindex = 0;
10434 					connp->conn_multicast_ipif = NULL;
10435 				} else if (ill != NULL) {
10436 					connp->conn_multicast_ill = ill;
10437 					connp->conn_orig_multicast_ifindex =
10438 					    ifindex;
10439 				}
10440 			}
10441 			break;
10442 		}
10443 	}
10444 
10445 	if (ill != NULL) {
10446 		mutex_exit(&ill->ill_lock);
10447 		mutex_exit(&connp->conn_lock);
10448 		ill_refrele(ill);
10449 		return (0);
10450 	}
10451 	mutex_exit(&connp->conn_lock);
10452 	/*
10453 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10454 	 * locate the ill and could not set the option (ifindex != 0)
10455 	 */
10456 	return (ifindex == 0 ? 0 : EINVAL);
10457 }
10458 
10459 /* This routine sets socket options. */
10460 /* ARGSUSED */
10461 int
10462 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10463     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10464     void *dummy, cred_t *cr, mblk_t *first_mp)
10465 {
10466 	int		*i1 = (int *)invalp;
10467 	conn_t		*connp = Q_TO_CONN(q);
10468 	int		error = 0;
10469 	boolean_t	checkonly;
10470 	ire_t		*ire;
10471 	boolean_t	found;
10472 
10473 	switch (optset_context) {
10474 
10475 	case SETFN_OPTCOM_CHECKONLY:
10476 		checkonly = B_TRUE;
10477 		/*
10478 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10479 		 * inlen != 0 implies value supplied and
10480 		 * 	we have to "pretend" to set it.
10481 		 * inlen == 0 implies that there is no
10482 		 * 	value part in T_CHECK request and just validation
10483 		 * done elsewhere should be enough, we just return here.
10484 		 */
10485 		if (inlen == 0) {
10486 			*outlenp = 0;
10487 			return (0);
10488 		}
10489 		break;
10490 	case SETFN_OPTCOM_NEGOTIATE:
10491 	case SETFN_UD_NEGOTIATE:
10492 	case SETFN_CONN_NEGOTIATE:
10493 		checkonly = B_FALSE;
10494 		break;
10495 	default:
10496 		/*
10497 		 * We should never get here
10498 		 */
10499 		*outlenp = 0;
10500 		return (EINVAL);
10501 	}
10502 
10503 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10504 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10505 
10506 	/*
10507 	 * For fixed length options, no sanity check
10508 	 * of passed in length is done. It is assumed *_optcom_req()
10509 	 * routines do the right thing.
10510 	 */
10511 
10512 	switch (level) {
10513 	case SOL_SOCKET:
10514 		/*
10515 		 * conn_lock protects the bitfields, and is used to
10516 		 * set the fields atomically.
10517 		 */
10518 		switch (name) {
10519 		case SO_BROADCAST:
10520 			if (!checkonly) {
10521 				/* TODO: use value someplace? */
10522 				mutex_enter(&connp->conn_lock);
10523 				connp->conn_broadcast = *i1 ? 1 : 0;
10524 				mutex_exit(&connp->conn_lock);
10525 			}
10526 			break;	/* goto sizeof (int) option return */
10527 		case SO_USELOOPBACK:
10528 			if (!checkonly) {
10529 				/* TODO: use value someplace? */
10530 				mutex_enter(&connp->conn_lock);
10531 				connp->conn_loopback = *i1 ? 1 : 0;
10532 				mutex_exit(&connp->conn_lock);
10533 			}
10534 			break;	/* goto sizeof (int) option return */
10535 		case SO_DONTROUTE:
10536 			if (!checkonly) {
10537 				mutex_enter(&connp->conn_lock);
10538 				connp->conn_dontroute = *i1 ? 1 : 0;
10539 				mutex_exit(&connp->conn_lock);
10540 			}
10541 			break;	/* goto sizeof (int) option return */
10542 		case SO_REUSEADDR:
10543 			if (!checkonly) {
10544 				mutex_enter(&connp->conn_lock);
10545 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10546 				mutex_exit(&connp->conn_lock);
10547 			}
10548 			break;	/* goto sizeof (int) option return */
10549 		case SO_PROTOTYPE:
10550 			if (!checkonly) {
10551 				mutex_enter(&connp->conn_lock);
10552 				connp->conn_proto = *i1;
10553 				mutex_exit(&connp->conn_lock);
10554 			}
10555 			break;	/* goto sizeof (int) option return */
10556 		case SO_ALLZONES:
10557 			if (!checkonly) {
10558 				mutex_enter(&connp->conn_lock);
10559 				if (IPCL_IS_BOUND(connp)) {
10560 					mutex_exit(&connp->conn_lock);
10561 					return (EINVAL);
10562 				}
10563 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10564 				mutex_exit(&connp->conn_lock);
10565 			}
10566 			break;	/* goto sizeof (int) option return */
10567 		case SO_ANON_MLP:
10568 			if (!checkonly) {
10569 				mutex_enter(&connp->conn_lock);
10570 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10571 				mutex_exit(&connp->conn_lock);
10572 			}
10573 			break;	/* goto sizeof (int) option return */
10574 		case SO_MAC_EXEMPT:
10575 			if (secpolicy_net_mac_aware(cr) != 0 ||
10576 			    IPCL_IS_BOUND(connp))
10577 				return (EACCES);
10578 			if (!checkonly) {
10579 				mutex_enter(&connp->conn_lock);
10580 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10581 				mutex_exit(&connp->conn_lock);
10582 			}
10583 			break;	/* goto sizeof (int) option return */
10584 		default:
10585 			/*
10586 			 * "soft" error (negative)
10587 			 * option not handled at this level
10588 			 * Note: Do not modify *outlenp
10589 			 */
10590 			return (-EINVAL);
10591 		}
10592 		break;
10593 	case IPPROTO_IP:
10594 		switch (name) {
10595 		case IP_NEXTHOP:
10596 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10597 				return (EPERM);
10598 			/* FALLTHRU */
10599 		case IP_MULTICAST_IF:
10600 		case IP_DONTFAILOVER_IF: {
10601 			ipaddr_t addr = *i1;
10602 
10603 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10604 			    first_mp);
10605 			if (error != 0)
10606 				return (error);
10607 			break;	/* goto sizeof (int) option return */
10608 		}
10609 
10610 		case IP_MULTICAST_TTL:
10611 			/* Recorded in transport above IP */
10612 			*outvalp = *invalp;
10613 			*outlenp = sizeof (uchar_t);
10614 			return (0);
10615 		case IP_MULTICAST_LOOP:
10616 			if (!checkonly) {
10617 				mutex_enter(&connp->conn_lock);
10618 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10619 				mutex_exit(&connp->conn_lock);
10620 			}
10621 			*outvalp = *invalp;
10622 			*outlenp = sizeof (uchar_t);
10623 			return (0);
10624 		case IP_ADD_MEMBERSHIP:
10625 		case MCAST_JOIN_GROUP:
10626 		case IP_DROP_MEMBERSHIP:
10627 		case MCAST_LEAVE_GROUP: {
10628 			struct ip_mreq *mreqp;
10629 			struct group_req *greqp;
10630 			ire_t *ire;
10631 			boolean_t done = B_FALSE;
10632 			ipaddr_t group, ifaddr;
10633 			struct sockaddr_in *sin;
10634 			uint32_t *ifindexp;
10635 			boolean_t mcast_opt = B_TRUE;
10636 			mcast_record_t fmode;
10637 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10638 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10639 
10640 			switch (name) {
10641 			case IP_ADD_MEMBERSHIP:
10642 				mcast_opt = B_FALSE;
10643 				/* FALLTHRU */
10644 			case MCAST_JOIN_GROUP:
10645 				fmode = MODE_IS_EXCLUDE;
10646 				optfn = ip_opt_add_group;
10647 				break;
10648 
10649 			case IP_DROP_MEMBERSHIP:
10650 				mcast_opt = B_FALSE;
10651 				/* FALLTHRU */
10652 			case MCAST_LEAVE_GROUP:
10653 				fmode = MODE_IS_INCLUDE;
10654 				optfn = ip_opt_delete_group;
10655 				break;
10656 			}
10657 
10658 			if (mcast_opt) {
10659 				greqp = (struct group_req *)i1;
10660 				sin = (struct sockaddr_in *)&greqp->gr_group;
10661 				if (sin->sin_family != AF_INET) {
10662 					*outlenp = 0;
10663 					return (ENOPROTOOPT);
10664 				}
10665 				group = (ipaddr_t)sin->sin_addr.s_addr;
10666 				ifaddr = INADDR_ANY;
10667 				ifindexp = &greqp->gr_interface;
10668 			} else {
10669 				mreqp = (struct ip_mreq *)i1;
10670 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10671 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10672 				ifindexp = NULL;
10673 			}
10674 
10675 			/*
10676 			 * In the multirouting case, we need to replicate
10677 			 * the request on all interfaces that will take part
10678 			 * in replication.  We do so because multirouting is
10679 			 * reflective, thus we will probably receive multi-
10680 			 * casts on those interfaces.
10681 			 * The ip_multirt_apply_membership() succeeds if the
10682 			 * operation succeeds on at least one interface.
10683 			 */
10684 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10685 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10686 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10687 			if (ire != NULL) {
10688 				if (ire->ire_flags & RTF_MULTIRT) {
10689 					error = ip_multirt_apply_membership(
10690 					    optfn, ire, connp, checkonly, group,
10691 					    fmode, INADDR_ANY, first_mp);
10692 					done = B_TRUE;
10693 				}
10694 				ire_refrele(ire);
10695 			}
10696 			if (!done) {
10697 				error = optfn(connp, checkonly, group, ifaddr,
10698 				    ifindexp, fmode, INADDR_ANY, first_mp);
10699 			}
10700 			if (error) {
10701 				/*
10702 				 * EINPROGRESS is a soft error, needs retry
10703 				 * so don't make *outlenp zero.
10704 				 */
10705 				if (error != EINPROGRESS)
10706 					*outlenp = 0;
10707 				return (error);
10708 			}
10709 			/* OK return - copy input buffer into output buffer */
10710 			if (invalp != outvalp) {
10711 				/* don't trust bcopy for identical src/dst */
10712 				bcopy(invalp, outvalp, inlen);
10713 			}
10714 			*outlenp = inlen;
10715 			return (0);
10716 		}
10717 		case IP_BLOCK_SOURCE:
10718 		case IP_UNBLOCK_SOURCE:
10719 		case IP_ADD_SOURCE_MEMBERSHIP:
10720 		case IP_DROP_SOURCE_MEMBERSHIP:
10721 		case MCAST_BLOCK_SOURCE:
10722 		case MCAST_UNBLOCK_SOURCE:
10723 		case MCAST_JOIN_SOURCE_GROUP:
10724 		case MCAST_LEAVE_SOURCE_GROUP: {
10725 			struct ip_mreq_source *imreqp;
10726 			struct group_source_req *gsreqp;
10727 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10728 			uint32_t ifindex = 0;
10729 			mcast_record_t fmode;
10730 			struct sockaddr_in *sin;
10731 			ire_t *ire;
10732 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10733 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10734 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10735 
10736 			switch (name) {
10737 			case IP_BLOCK_SOURCE:
10738 				mcast_opt = B_FALSE;
10739 				/* FALLTHRU */
10740 			case MCAST_BLOCK_SOURCE:
10741 				fmode = MODE_IS_EXCLUDE;
10742 				optfn = ip_opt_add_group;
10743 				break;
10744 
10745 			case IP_UNBLOCK_SOURCE:
10746 				mcast_opt = B_FALSE;
10747 				/* FALLTHRU */
10748 			case MCAST_UNBLOCK_SOURCE:
10749 				fmode = MODE_IS_EXCLUDE;
10750 				optfn = ip_opt_delete_group;
10751 				break;
10752 
10753 			case IP_ADD_SOURCE_MEMBERSHIP:
10754 				mcast_opt = B_FALSE;
10755 				/* FALLTHRU */
10756 			case MCAST_JOIN_SOURCE_GROUP:
10757 				fmode = MODE_IS_INCLUDE;
10758 				optfn = ip_opt_add_group;
10759 				break;
10760 
10761 			case IP_DROP_SOURCE_MEMBERSHIP:
10762 				mcast_opt = B_FALSE;
10763 				/* FALLTHRU */
10764 			case MCAST_LEAVE_SOURCE_GROUP:
10765 				fmode = MODE_IS_INCLUDE;
10766 				optfn = ip_opt_delete_group;
10767 				break;
10768 			}
10769 
10770 			if (mcast_opt) {
10771 				gsreqp = (struct group_source_req *)i1;
10772 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10773 					*outlenp = 0;
10774 					return (ENOPROTOOPT);
10775 				}
10776 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10777 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10778 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10779 				src = (ipaddr_t)sin->sin_addr.s_addr;
10780 				ifindex = gsreqp->gsr_interface;
10781 			} else {
10782 				imreqp = (struct ip_mreq_source *)i1;
10783 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10784 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10785 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10786 			}
10787 
10788 			/*
10789 			 * In the multirouting case, we need to replicate
10790 			 * the request as noted in the mcast cases above.
10791 			 */
10792 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10793 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10794 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10795 			if (ire != NULL) {
10796 				if (ire->ire_flags & RTF_MULTIRT) {
10797 					error = ip_multirt_apply_membership(
10798 					    optfn, ire, connp, checkonly, grp,
10799 					    fmode, src, first_mp);
10800 					done = B_TRUE;
10801 				}
10802 				ire_refrele(ire);
10803 			}
10804 			if (!done) {
10805 				error = optfn(connp, checkonly, grp, ifaddr,
10806 				    &ifindex, fmode, src, first_mp);
10807 			}
10808 			if (error != 0) {
10809 				/*
10810 				 * EINPROGRESS is a soft error, needs retry
10811 				 * so don't make *outlenp zero.
10812 				 */
10813 				if (error != EINPROGRESS)
10814 					*outlenp = 0;
10815 				return (error);
10816 			}
10817 			/* OK return - copy input buffer into output buffer */
10818 			if (invalp != outvalp) {
10819 				bcopy(invalp, outvalp, inlen);
10820 			}
10821 			*outlenp = inlen;
10822 			return (0);
10823 		}
10824 		case IP_SEC_OPT:
10825 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10826 			if (error != 0) {
10827 				*outlenp = 0;
10828 				return (error);
10829 			}
10830 			break;
10831 		case IP_HDRINCL:
10832 		case IP_OPTIONS:
10833 		case T_IP_OPTIONS:
10834 		case IP_TOS:
10835 		case T_IP_TOS:
10836 		case IP_TTL:
10837 		case IP_RECVDSTADDR:
10838 		case IP_RECVOPTS:
10839 			/* OK return - copy input buffer into output buffer */
10840 			if (invalp != outvalp) {
10841 				/* don't trust bcopy for identical src/dst */
10842 				bcopy(invalp, outvalp, inlen);
10843 			}
10844 			*outlenp = inlen;
10845 			return (0);
10846 		case IP_RECVIF:
10847 			/* Retrieve the inbound interface index */
10848 			if (!checkonly) {
10849 				mutex_enter(&connp->conn_lock);
10850 				connp->conn_recvif = *i1 ? 1 : 0;
10851 				mutex_exit(&connp->conn_lock);
10852 			}
10853 			break;	/* goto sizeof (int) option return */
10854 		case IP_RECVSLLA:
10855 			/* Retrieve the source link layer address */
10856 			if (!checkonly) {
10857 				mutex_enter(&connp->conn_lock);
10858 				connp->conn_recvslla = *i1 ? 1 : 0;
10859 				mutex_exit(&connp->conn_lock);
10860 			}
10861 			break;	/* goto sizeof (int) option return */
10862 		case MRT_INIT:
10863 		case MRT_DONE:
10864 		case MRT_ADD_VIF:
10865 		case MRT_DEL_VIF:
10866 		case MRT_ADD_MFC:
10867 		case MRT_DEL_MFC:
10868 		case MRT_ASSERT:
10869 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
10870 				*outlenp = 0;
10871 				return (error);
10872 			}
10873 			error = ip_mrouter_set((int)name, q, checkonly,
10874 			    (uchar_t *)invalp, inlen, first_mp);
10875 			if (error) {
10876 				*outlenp = 0;
10877 				return (error);
10878 			}
10879 			/* OK return - copy input buffer into output buffer */
10880 			if (invalp != outvalp) {
10881 				/* don't trust bcopy for identical src/dst */
10882 				bcopy(invalp, outvalp, inlen);
10883 			}
10884 			*outlenp = inlen;
10885 			return (0);
10886 		case IP_BOUND_IF:
10887 		case IP_XMIT_IF:
10888 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10889 			    level, name, first_mp);
10890 			if (error != 0)
10891 				return (error);
10892 			break; 		/* goto sizeof (int) option return */
10893 
10894 		case IP_UNSPEC_SRC:
10895 			/* Allow sending with a zero source address */
10896 			if (!checkonly) {
10897 				mutex_enter(&connp->conn_lock);
10898 				connp->conn_unspec_src = *i1 ? 1 : 0;
10899 				mutex_exit(&connp->conn_lock);
10900 			}
10901 			break;	/* goto sizeof (int) option return */
10902 		default:
10903 			/*
10904 			 * "soft" error (negative)
10905 			 * option not handled at this level
10906 			 * Note: Do not modify *outlenp
10907 			 */
10908 			return (-EINVAL);
10909 		}
10910 		break;
10911 	case IPPROTO_IPV6:
10912 		switch (name) {
10913 		case IPV6_BOUND_IF:
10914 		case IPV6_BOUND_PIF:
10915 		case IPV6_DONTFAILOVER_IF:
10916 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10917 			    level, name, first_mp);
10918 			if (error != 0)
10919 				return (error);
10920 			break; 		/* goto sizeof (int) option return */
10921 
10922 		case IPV6_MULTICAST_IF:
10923 			/*
10924 			 * The only possible errors are EINPROGRESS and
10925 			 * EINVAL. EINPROGRESS will be restarted and is not
10926 			 * a hard error. We call this option on both V4 and V6
10927 			 * If both return EINVAL, then this call returns
10928 			 * EINVAL. If at least one of them succeeds we
10929 			 * return success.
10930 			 */
10931 			found = B_FALSE;
10932 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10933 			    level, name, first_mp);
10934 			if (error == EINPROGRESS)
10935 				return (error);
10936 			if (error == 0)
10937 				found = B_TRUE;
10938 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10939 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
10940 			if (error == 0)
10941 				found = B_TRUE;
10942 			if (!found)
10943 				return (error);
10944 			break; 		/* goto sizeof (int) option return */
10945 
10946 		case IPV6_MULTICAST_HOPS:
10947 			/* Recorded in transport above IP */
10948 			break;	/* goto sizeof (int) option return */
10949 		case IPV6_MULTICAST_LOOP:
10950 			if (!checkonly) {
10951 				mutex_enter(&connp->conn_lock);
10952 				connp->conn_multicast_loop = *i1;
10953 				mutex_exit(&connp->conn_lock);
10954 			}
10955 			break;	/* goto sizeof (int) option return */
10956 		case IPV6_JOIN_GROUP:
10957 		case MCAST_JOIN_GROUP:
10958 		case IPV6_LEAVE_GROUP:
10959 		case MCAST_LEAVE_GROUP: {
10960 			struct ipv6_mreq *ip_mreqp;
10961 			struct group_req *greqp;
10962 			ire_t *ire;
10963 			boolean_t done = B_FALSE;
10964 			in6_addr_t groupv6;
10965 			uint32_t ifindex;
10966 			boolean_t mcast_opt = B_TRUE;
10967 			mcast_record_t fmode;
10968 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
10969 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
10970 
10971 			switch (name) {
10972 			case IPV6_JOIN_GROUP:
10973 				mcast_opt = B_FALSE;
10974 				/* FALLTHRU */
10975 			case MCAST_JOIN_GROUP:
10976 				fmode = MODE_IS_EXCLUDE;
10977 				optfn = ip_opt_add_group_v6;
10978 				break;
10979 
10980 			case IPV6_LEAVE_GROUP:
10981 				mcast_opt = B_FALSE;
10982 				/* FALLTHRU */
10983 			case MCAST_LEAVE_GROUP:
10984 				fmode = MODE_IS_INCLUDE;
10985 				optfn = ip_opt_delete_group_v6;
10986 				break;
10987 			}
10988 
10989 			if (mcast_opt) {
10990 				struct sockaddr_in *sin;
10991 				struct sockaddr_in6 *sin6;
10992 				greqp = (struct group_req *)i1;
10993 				if (greqp->gr_group.ss_family == AF_INET) {
10994 					sin = (struct sockaddr_in *)
10995 					    &(greqp->gr_group);
10996 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
10997 					    &groupv6);
10998 				} else {
10999 					sin6 = (struct sockaddr_in6 *)
11000 					    &(greqp->gr_group);
11001 					groupv6 = sin6->sin6_addr;
11002 				}
11003 				ifindex = greqp->gr_interface;
11004 			} else {
11005 				ip_mreqp = (struct ipv6_mreq *)i1;
11006 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11007 				ifindex = ip_mreqp->ipv6mr_interface;
11008 			}
11009 			/*
11010 			 * In the multirouting case, we need to replicate
11011 			 * the request on all interfaces that will take part
11012 			 * in replication.  We do so because multirouting is
11013 			 * reflective, thus we will probably receive multi-
11014 			 * casts on those interfaces.
11015 			 * The ip_multirt_apply_membership_v6() succeeds if
11016 			 * the operation succeeds on at least one interface.
11017 			 */
11018 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11019 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11020 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11021 			if (ire != NULL) {
11022 				if (ire->ire_flags & RTF_MULTIRT) {
11023 					error = ip_multirt_apply_membership_v6(
11024 					    optfn, ire, connp, checkonly,
11025 					    &groupv6, fmode, &ipv6_all_zeros,
11026 					    first_mp);
11027 					done = B_TRUE;
11028 				}
11029 				ire_refrele(ire);
11030 			}
11031 			if (!done) {
11032 				error = optfn(connp, checkonly, &groupv6,
11033 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11034 			}
11035 			if (error) {
11036 				/*
11037 				 * EINPROGRESS is a soft error, needs retry
11038 				 * so don't make *outlenp zero.
11039 				 */
11040 				if (error != EINPROGRESS)
11041 					*outlenp = 0;
11042 				return (error);
11043 			}
11044 			/* OK return - copy input buffer into output buffer */
11045 			if (invalp != outvalp) {
11046 				/* don't trust bcopy for identical src/dst */
11047 				bcopy(invalp, outvalp, inlen);
11048 			}
11049 			*outlenp = inlen;
11050 			return (0);
11051 		}
11052 		case MCAST_BLOCK_SOURCE:
11053 		case MCAST_UNBLOCK_SOURCE:
11054 		case MCAST_JOIN_SOURCE_GROUP:
11055 		case MCAST_LEAVE_SOURCE_GROUP: {
11056 			struct group_source_req *gsreqp;
11057 			in6_addr_t v6grp, v6src;
11058 			uint32_t ifindex;
11059 			mcast_record_t fmode;
11060 			ire_t *ire;
11061 			boolean_t done = B_FALSE;
11062 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11063 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11064 
11065 			switch (name) {
11066 			case MCAST_BLOCK_SOURCE:
11067 				fmode = MODE_IS_EXCLUDE;
11068 				optfn = ip_opt_add_group_v6;
11069 				break;
11070 			case MCAST_UNBLOCK_SOURCE:
11071 				fmode = MODE_IS_EXCLUDE;
11072 				optfn = ip_opt_delete_group_v6;
11073 				break;
11074 			case MCAST_JOIN_SOURCE_GROUP:
11075 				fmode = MODE_IS_INCLUDE;
11076 				optfn = ip_opt_add_group_v6;
11077 				break;
11078 			case MCAST_LEAVE_SOURCE_GROUP:
11079 				fmode = MODE_IS_INCLUDE;
11080 				optfn = ip_opt_delete_group_v6;
11081 				break;
11082 			}
11083 
11084 			gsreqp = (struct group_source_req *)i1;
11085 			ifindex = gsreqp->gsr_interface;
11086 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11087 				struct sockaddr_in *s;
11088 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11089 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11090 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11091 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11092 			} else {
11093 				struct sockaddr_in6 *s6;
11094 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11095 				v6grp = s6->sin6_addr;
11096 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11097 				v6src = s6->sin6_addr;
11098 			}
11099 
11100 			/*
11101 			 * In the multirouting case, we need to replicate
11102 			 * the request as noted in the mcast cases above.
11103 			 */
11104 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11105 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11106 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11107 			if (ire != NULL) {
11108 				if (ire->ire_flags & RTF_MULTIRT) {
11109 					error = ip_multirt_apply_membership_v6(
11110 					    optfn, ire, connp, checkonly,
11111 					    &v6grp, fmode, &v6src, first_mp);
11112 					done = B_TRUE;
11113 				}
11114 				ire_refrele(ire);
11115 			}
11116 			if (!done) {
11117 				error = optfn(connp, checkonly, &v6grp,
11118 				    ifindex, fmode, &v6src, first_mp);
11119 			}
11120 			if (error != 0) {
11121 				/*
11122 				 * EINPROGRESS is a soft error, needs retry
11123 				 * so don't make *outlenp zero.
11124 				 */
11125 				if (error != EINPROGRESS)
11126 					*outlenp = 0;
11127 				return (error);
11128 			}
11129 			/* OK return - copy input buffer into output buffer */
11130 			if (invalp != outvalp) {
11131 				bcopy(invalp, outvalp, inlen);
11132 			}
11133 			*outlenp = inlen;
11134 			return (0);
11135 		}
11136 		case IPV6_UNICAST_HOPS:
11137 			/* Recorded in transport above IP */
11138 			break;	/* goto sizeof (int) option return */
11139 		case IPV6_UNSPEC_SRC:
11140 			/* Allow sending with a zero source address */
11141 			if (!checkonly) {
11142 				mutex_enter(&connp->conn_lock);
11143 				connp->conn_unspec_src = *i1 ? 1 : 0;
11144 				mutex_exit(&connp->conn_lock);
11145 			}
11146 			break;	/* goto sizeof (int) option return */
11147 		case IPV6_RECVPKTINFO:
11148 			if (!checkonly) {
11149 				mutex_enter(&connp->conn_lock);
11150 				connp->conn_ipv6_recvpktinfo = *i1 ? 1 : 0;
11151 				mutex_exit(&connp->conn_lock);
11152 			}
11153 			break;	/* goto sizeof (int) option return */
11154 		case IPV6_RECVTCLASS:
11155 			if (!checkonly) {
11156 				if (*i1 < 0 || *i1 > 1) {
11157 					return (EINVAL);
11158 				}
11159 				mutex_enter(&connp->conn_lock);
11160 				connp->conn_ipv6_recvtclass = *i1;
11161 				mutex_exit(&connp->conn_lock);
11162 			}
11163 			break;
11164 		case IPV6_RECVPATHMTU:
11165 			if (!checkonly) {
11166 				if (*i1 < 0 || *i1 > 1) {
11167 					return (EINVAL);
11168 				}
11169 				mutex_enter(&connp->conn_lock);
11170 				connp->conn_ipv6_recvpathmtu = *i1;
11171 				mutex_exit(&connp->conn_lock);
11172 			}
11173 			break;
11174 		case IPV6_RECVHOPLIMIT:
11175 			if (!checkonly) {
11176 				mutex_enter(&connp->conn_lock);
11177 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11178 				mutex_exit(&connp->conn_lock);
11179 			}
11180 			break;	/* goto sizeof (int) option return */
11181 		case IPV6_RECVHOPOPTS:
11182 			if (!checkonly) {
11183 				mutex_enter(&connp->conn_lock);
11184 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11185 				mutex_exit(&connp->conn_lock);
11186 			}
11187 			break;	/* goto sizeof (int) option return */
11188 		case IPV6_RECVDSTOPTS:
11189 			if (!checkonly) {
11190 				mutex_enter(&connp->conn_lock);
11191 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11192 				mutex_exit(&connp->conn_lock);
11193 			}
11194 			break;	/* goto sizeof (int) option return */
11195 		case IPV6_RECVRTHDR:
11196 			if (!checkonly) {
11197 				mutex_enter(&connp->conn_lock);
11198 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11199 				mutex_exit(&connp->conn_lock);
11200 			}
11201 			break;	/* goto sizeof (int) option return */
11202 		case IPV6_RECVRTHDRDSTOPTS:
11203 			if (!checkonly) {
11204 				mutex_enter(&connp->conn_lock);
11205 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11206 				mutex_exit(&connp->conn_lock);
11207 			}
11208 			break;	/* goto sizeof (int) option return */
11209 		case IPV6_PKTINFO:
11210 			if (inlen == 0)
11211 				return (-EINVAL);	/* clearing option */
11212 			error = ip6_set_pktinfo(cr, connp,
11213 			    (struct in6_pktinfo *)invalp, first_mp);
11214 			if (error != 0)
11215 				*outlenp = 0;
11216 			else
11217 				*outlenp = inlen;
11218 			return (error);
11219 		case IPV6_NEXTHOP: {
11220 			struct sockaddr_in6 *sin6;
11221 
11222 			/* Verify that the nexthop is reachable */
11223 			if (inlen == 0)
11224 				return (-EINVAL);	/* clearing option */
11225 
11226 			sin6 = (struct sockaddr_in6 *)invalp;
11227 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11228 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11229 			    NULL, MATCH_IRE_DEFAULT);
11230 
11231 			if (ire == NULL) {
11232 				*outlenp = 0;
11233 				return (EHOSTUNREACH);
11234 			}
11235 			ire_refrele(ire);
11236 			return (-EINVAL);
11237 		}
11238 		case IPV6_SEC_OPT:
11239 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11240 			if (error != 0) {
11241 				*outlenp = 0;
11242 				return (error);
11243 			}
11244 			break;
11245 		case IPV6_SRC_PREFERENCES: {
11246 			/*
11247 			 * This is implemented strictly in the ip module
11248 			 * (here and in tcp_opt_*() to accomodate tcp
11249 			 * sockets).  Modules above ip pass this option
11250 			 * down here since ip is the only one that needs to
11251 			 * be aware of source address preferences.
11252 			 *
11253 			 * This socket option only affects connected
11254 			 * sockets that haven't already bound to a specific
11255 			 * IPv6 address.  In other words, sockets that
11256 			 * don't call bind() with an address other than the
11257 			 * unspecified address and that call connect().
11258 			 * ip_bind_connected_v6() passes these preferences
11259 			 * to the ipif_select_source_v6() function.
11260 			 */
11261 			if (inlen != sizeof (uint32_t))
11262 				return (EINVAL);
11263 			error = ip6_set_src_preferences(connp,
11264 			    *(uint32_t *)invalp);
11265 			if (error != 0) {
11266 				*outlenp = 0;
11267 				return (error);
11268 			} else {
11269 				*outlenp = sizeof (uint32_t);
11270 			}
11271 			break;
11272 		}
11273 		case IPV6_V6ONLY:
11274 			if (*i1 < 0 || *i1 > 1) {
11275 				return (EINVAL);
11276 			}
11277 			mutex_enter(&connp->conn_lock);
11278 			connp->conn_ipv6_v6only = *i1;
11279 			mutex_exit(&connp->conn_lock);
11280 			break;
11281 		default:
11282 			return (-EINVAL);
11283 		}
11284 		break;
11285 	default:
11286 		/*
11287 		 * "soft" error (negative)
11288 		 * option not handled at this level
11289 		 * Note: Do not modify *outlenp
11290 		 */
11291 		return (-EINVAL);
11292 	}
11293 	/*
11294 	 * Common case of return from an option that is sizeof (int)
11295 	 */
11296 	*(int *)outvalp = *i1;
11297 	*outlenp = sizeof (int);
11298 	return (0);
11299 }
11300 
11301 /*
11302  * This routine gets default values of certain options whose default
11303  * values are maintained by protocol specific code
11304  */
11305 /* ARGSUSED */
11306 int
11307 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11308 {
11309 	int *i1 = (int *)ptr;
11310 
11311 	switch (level) {
11312 	case IPPROTO_IP:
11313 		switch (name) {
11314 		case IP_MULTICAST_TTL:
11315 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11316 			return (sizeof (uchar_t));
11317 		case IP_MULTICAST_LOOP:
11318 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11319 			return (sizeof (uchar_t));
11320 		default:
11321 			return (-1);
11322 		}
11323 	case IPPROTO_IPV6:
11324 		switch (name) {
11325 		case IPV6_UNICAST_HOPS:
11326 			*i1 = ipv6_def_hops;
11327 			return (sizeof (int));
11328 		case IPV6_MULTICAST_HOPS:
11329 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11330 			return (sizeof (int));
11331 		case IPV6_MULTICAST_LOOP:
11332 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11333 			return (sizeof (int));
11334 		case IPV6_V6ONLY:
11335 			*i1 = 1;
11336 			return (sizeof (int));
11337 		default:
11338 			return (-1);
11339 		}
11340 	default:
11341 		return (-1);
11342 	}
11343 	/* NOTREACHED */
11344 }
11345 
11346 /*
11347  * Given a destination address and a pointer to where to put the information
11348  * this routine fills in the mtuinfo.
11349  */
11350 int
11351 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11352     struct ip6_mtuinfo *mtuinfo)
11353 {
11354 	ire_t *ire;
11355 
11356 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11357 		return (-1);
11358 
11359 	bzero(mtuinfo, sizeof (*mtuinfo));
11360 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11361 	mtuinfo->ip6m_addr.sin6_port = port;
11362 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11363 
11364 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11365 	if (ire != NULL) {
11366 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11367 		ire_refrele(ire);
11368 	} else {
11369 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11370 	}
11371 	return (sizeof (struct ip6_mtuinfo));
11372 }
11373 
11374 /*
11375  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11376  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11377  * isn't.  This doesn't matter as the error checking is done properly for the
11378  * other MRT options coming in through ip_opt_set.
11379  */
11380 int
11381 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11382 {
11383 	conn_t		*connp = Q_TO_CONN(q);
11384 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11385 
11386 	switch (level) {
11387 	case IPPROTO_IP:
11388 		switch (name) {
11389 		case MRT_VERSION:
11390 		case MRT_ASSERT:
11391 			(void) ip_mrouter_get(name, q, ptr);
11392 			return (sizeof (int));
11393 		case IP_SEC_OPT:
11394 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11395 		case IP_NEXTHOP:
11396 			if (connp->conn_nexthop_set) {
11397 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11398 				return (sizeof (ipaddr_t));
11399 			} else
11400 				return (0);
11401 		default:
11402 			break;
11403 		}
11404 		break;
11405 	case IPPROTO_IPV6:
11406 		switch (name) {
11407 		case IPV6_SEC_OPT:
11408 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11409 		case IPV6_SRC_PREFERENCES: {
11410 			return (ip6_get_src_preferences(connp,
11411 			    (uint32_t *)ptr));
11412 		}
11413 		case IPV6_V6ONLY:
11414 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11415 			return (sizeof (int));
11416 		case IPV6_PATHMTU:
11417 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11418 				(struct ip6_mtuinfo *)ptr));
11419 		default:
11420 			break;
11421 		}
11422 		break;
11423 	default:
11424 		break;
11425 	}
11426 	return (-1);
11427 }
11428 
11429 /* Named Dispatch routine to get a current value out of our parameter table. */
11430 /* ARGSUSED */
11431 static int
11432 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11433 {
11434 	ipparam_t *ippa = (ipparam_t *)cp;
11435 
11436 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11437 	return (0);
11438 }
11439 
11440 /* ARGSUSED */
11441 static int
11442 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11443 {
11444 
11445 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11446 	return (0);
11447 }
11448 
11449 /*
11450  * Set ip{,6}_forwarding values.  This means walking through all of the
11451  * ill's and toggling their forwarding values.
11452  */
11453 /* ARGSUSED */
11454 static int
11455 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11456 {
11457 	long new_value;
11458 	int *forwarding_value = (int *)cp;
11459 	ill_t *walker;
11460 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11461 	ill_walk_context_t ctx;
11462 
11463 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11464 	    new_value < 0 || new_value > 1) {
11465 		return (EINVAL);
11466 	}
11467 
11468 	*forwarding_value = new_value;
11469 
11470 	/*
11471 	 * Regardless of the current value of ip_forwarding, set all per-ill
11472 	 * values of ip_forwarding to the value being set.
11473 	 *
11474 	 * Bring all the ill's up to date with the new global value.
11475 	 */
11476 	rw_enter(&ill_g_lock, RW_READER);
11477 
11478 	if (isv6)
11479 		walker = ILL_START_WALK_V6(&ctx);
11480 	else
11481 		walker = ILL_START_WALK_V4(&ctx);
11482 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11483 		(void) ill_forward_set(q, mp, (new_value != 0),
11484 		    (caddr_t)walker);
11485 	}
11486 	rw_exit(&ill_g_lock);
11487 
11488 	return (0);
11489 }
11490 
11491 /*
11492  * Walk through the param array specified registering each element with the
11493  * Named Dispatch handler. This is called only during init. So it is ok
11494  * not to acquire any locks
11495  */
11496 static boolean_t
11497 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11498     ipndp_t *ipnd, size_t ipnd_cnt)
11499 {
11500 	for (; ippa_cnt-- > 0; ippa++) {
11501 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11502 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11503 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11504 				nd_free(&ip_g_nd);
11505 				return (B_FALSE);
11506 			}
11507 		}
11508 	}
11509 
11510 	for (; ipnd_cnt-- > 0; ipnd++) {
11511 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11512 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11513 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11514 			    ipnd->ip_ndp_data)) {
11515 				nd_free(&ip_g_nd);
11516 				return (B_FALSE);
11517 			}
11518 		}
11519 	}
11520 
11521 	return (B_TRUE);
11522 }
11523 
11524 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11525 /* ARGSUSED */
11526 static int
11527 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11528 {
11529 	long		new_value;
11530 	ipparam_t	*ippa = (ipparam_t *)cp;
11531 
11532 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11533 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11534 		return (EINVAL);
11535 	}
11536 	ippa->ip_param_value = new_value;
11537 	return (0);
11538 }
11539 
11540 /*
11541  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11542  * When an ipf is passed here for the first time, if
11543  * we already have in-order fragments on the queue, we convert from the fast-
11544  * path reassembly scheme to the hard-case scheme.  From then on, additional
11545  * fragments are reassembled here.  We keep track of the start and end offsets
11546  * of each piece, and the number of holes in the chain.  When the hole count
11547  * goes to zero, we are done!
11548  *
11549  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11550  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11551  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11552  * after the call to ip_reassemble().
11553  */
11554 int
11555 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11556     size_t msg_len)
11557 {
11558 	uint_t	end;
11559 	mblk_t	*next_mp;
11560 	mblk_t	*mp1;
11561 	uint_t	offset;
11562 	boolean_t incr_dups = B_TRUE;
11563 	boolean_t offset_zero_seen = B_FALSE;
11564 	boolean_t pkt_boundary_checked = B_FALSE;
11565 
11566 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11567 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11568 
11569 	/* Add in byte count */
11570 	ipf->ipf_count += msg_len;
11571 	if (ipf->ipf_end) {
11572 		/*
11573 		 * We were part way through in-order reassembly, but now there
11574 		 * is a hole.  We walk through messages already queued, and
11575 		 * mark them for hard case reassembly.  We know that up till
11576 		 * now they were in order starting from offset zero.
11577 		 */
11578 		offset = 0;
11579 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11580 			IP_REASS_SET_START(mp1, offset);
11581 			if (offset == 0) {
11582 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11583 				offset = -ipf->ipf_nf_hdr_len;
11584 			}
11585 			offset += mp1->b_wptr - mp1->b_rptr;
11586 			IP_REASS_SET_END(mp1, offset);
11587 		}
11588 		/* One hole at the end. */
11589 		ipf->ipf_hole_cnt = 1;
11590 		/* Brand it as a hard case, forever. */
11591 		ipf->ipf_end = 0;
11592 	}
11593 	/* Walk through all the new pieces. */
11594 	do {
11595 		end = start + (mp->b_wptr - mp->b_rptr);
11596 		/*
11597 		 * If start is 0, decrease 'end' only for the first mblk of
11598 		 * the fragment. Otherwise 'end' can get wrong value in the
11599 		 * second pass of the loop if first mblk is exactly the
11600 		 * size of ipf_nf_hdr_len.
11601 		 */
11602 		if (start == 0 && !offset_zero_seen) {
11603 			/* First segment */
11604 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11605 			end -= ipf->ipf_nf_hdr_len;
11606 			offset_zero_seen = B_TRUE;
11607 		}
11608 		next_mp = mp->b_cont;
11609 		/*
11610 		 * We are checking to see if there is any interesing data
11611 		 * to process.  If there isn't and the mblk isn't the
11612 		 * one which carries the unfragmentable header then we
11613 		 * drop it.  It's possible to have just the unfragmentable
11614 		 * header come through without any data.  That needs to be
11615 		 * saved.
11616 		 *
11617 		 * If the assert at the top of this function holds then the
11618 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11619 		 * is infrequently traveled enough that the test is left in
11620 		 * to protect against future code changes which break that
11621 		 * invariant.
11622 		 */
11623 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11624 			/* Empty.  Blast it. */
11625 			IP_REASS_SET_START(mp, 0);
11626 			IP_REASS_SET_END(mp, 0);
11627 			/*
11628 			 * If the ipf points to the mblk we are about to free,
11629 			 * update ipf to point to the next mblk (or NULL
11630 			 * if none).
11631 			 */
11632 			if (ipf->ipf_mp->b_cont == mp)
11633 				ipf->ipf_mp->b_cont = next_mp;
11634 			freeb(mp);
11635 			continue;
11636 		}
11637 		mp->b_cont = NULL;
11638 		IP_REASS_SET_START(mp, start);
11639 		IP_REASS_SET_END(mp, end);
11640 		if (!ipf->ipf_tail_mp) {
11641 			ipf->ipf_tail_mp = mp;
11642 			ipf->ipf_mp->b_cont = mp;
11643 			if (start == 0 || !more) {
11644 				ipf->ipf_hole_cnt = 1;
11645 				/*
11646 				 * if the first fragment comes in more than one
11647 				 * mblk, this loop will be executed for each
11648 				 * mblk. Need to adjust hole count so exiting
11649 				 * this routine will leave hole count at 1.
11650 				 */
11651 				if (next_mp)
11652 					ipf->ipf_hole_cnt++;
11653 			} else
11654 				ipf->ipf_hole_cnt = 2;
11655 			continue;
11656 		} else if (ipf->ipf_last_frag_seen && !more &&
11657 			    !pkt_boundary_checked) {
11658 			/*
11659 			 * We check datagram boundary only if this fragment
11660 			 * claims to be the last fragment and we have seen a
11661 			 * last fragment in the past too. We do this only
11662 			 * once for a given fragment.
11663 			 *
11664 			 * start cannot be 0 here as fragments with start=0
11665 			 * and MF=0 gets handled as a complete packet. These
11666 			 * fragments should not reach here.
11667 			 */
11668 
11669 			if (start + msgdsize(mp) !=
11670 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11671 				/*
11672 				 * We have two fragments both of which claim
11673 				 * to be the last fragment but gives conflicting
11674 				 * information about the whole datagram size.
11675 				 * Something fishy is going on. Drop the
11676 				 * fragment and free up the reassembly list.
11677 				 */
11678 				return (IP_REASS_FAILED);
11679 			}
11680 
11681 			/*
11682 			 * We shouldn't come to this code block again for this
11683 			 * particular fragment.
11684 			 */
11685 			pkt_boundary_checked = B_TRUE;
11686 		}
11687 
11688 		/* New stuff at or beyond tail? */
11689 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11690 		if (start >= offset) {
11691 			if (ipf->ipf_last_frag_seen) {
11692 				/* current fragment is beyond last fragment */
11693 				return (IP_REASS_FAILED);
11694 			}
11695 			/* Link it on end. */
11696 			ipf->ipf_tail_mp->b_cont = mp;
11697 			ipf->ipf_tail_mp = mp;
11698 			if (more) {
11699 				if (start != offset)
11700 					ipf->ipf_hole_cnt++;
11701 			} else if (start == offset && next_mp == NULL)
11702 					ipf->ipf_hole_cnt--;
11703 			continue;
11704 		}
11705 		mp1 = ipf->ipf_mp->b_cont;
11706 		offset = IP_REASS_START(mp1);
11707 		/* New stuff at the front? */
11708 		if (start < offset) {
11709 			if (start == 0) {
11710 				if (end >= offset) {
11711 					/* Nailed the hole at the begining. */
11712 					ipf->ipf_hole_cnt--;
11713 				}
11714 			} else if (end < offset) {
11715 				/*
11716 				 * A hole, stuff, and a hole where there used
11717 				 * to be just a hole.
11718 				 */
11719 				ipf->ipf_hole_cnt++;
11720 			}
11721 			mp->b_cont = mp1;
11722 			/* Check for overlap. */
11723 			while (end > offset) {
11724 				if (end < IP_REASS_END(mp1)) {
11725 					mp->b_wptr -= end - offset;
11726 					IP_REASS_SET_END(mp, offset);
11727 					if (ill->ill_isv6) {
11728 						BUMP_MIB(ill->ill_ip6_mib,
11729 						    ipv6ReasmPartDups);
11730 					} else {
11731 						BUMP_MIB(&ip_mib,
11732 						    ipReasmPartDups);
11733 					}
11734 					break;
11735 				}
11736 				/* Did we cover another hole? */
11737 				if ((mp1->b_cont &&
11738 				    IP_REASS_END(mp1) !=
11739 				    IP_REASS_START(mp1->b_cont) &&
11740 				    end >= IP_REASS_START(mp1->b_cont)) ||
11741 				    (!ipf->ipf_last_frag_seen && !more)) {
11742 					ipf->ipf_hole_cnt--;
11743 				}
11744 				/* Clip out mp1. */
11745 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11746 					/*
11747 					 * After clipping out mp1, this guy
11748 					 * is now hanging off the end.
11749 					 */
11750 					ipf->ipf_tail_mp = mp;
11751 				}
11752 				IP_REASS_SET_START(mp1, 0);
11753 				IP_REASS_SET_END(mp1, 0);
11754 				/* Subtract byte count */
11755 				ipf->ipf_count -= mp1->b_datap->db_lim -
11756 				    mp1->b_datap->db_base;
11757 				freeb(mp1);
11758 				if (ill->ill_isv6) {
11759 					BUMP_MIB(ill->ill_ip6_mib,
11760 					    ipv6ReasmPartDups);
11761 				} else {
11762 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11763 				}
11764 				mp1 = mp->b_cont;
11765 				if (!mp1)
11766 					break;
11767 				offset = IP_REASS_START(mp1);
11768 			}
11769 			ipf->ipf_mp->b_cont = mp;
11770 			continue;
11771 		}
11772 		/*
11773 		 * The new piece starts somewhere between the start of the head
11774 		 * and before the end of the tail.
11775 		 */
11776 		for (; mp1; mp1 = mp1->b_cont) {
11777 			offset = IP_REASS_END(mp1);
11778 			if (start < offset) {
11779 				if (end <= offset) {
11780 					/* Nothing new. */
11781 					IP_REASS_SET_START(mp, 0);
11782 					IP_REASS_SET_END(mp, 0);
11783 					/* Subtract byte count */
11784 					ipf->ipf_count -= mp->b_datap->db_lim -
11785 					    mp->b_datap->db_base;
11786 					if (incr_dups) {
11787 						ipf->ipf_num_dups++;
11788 						incr_dups = B_FALSE;
11789 					}
11790 					freeb(mp);
11791 					if (ill->ill_isv6) {
11792 						BUMP_MIB(ill->ill_ip6_mib,
11793 						    ipv6ReasmDuplicates);
11794 					} else {
11795 						BUMP_MIB(&ip_mib,
11796 						    ipReasmDuplicates);
11797 					}
11798 					break;
11799 				}
11800 				/*
11801 				 * Trim redundant stuff off beginning of new
11802 				 * piece.
11803 				 */
11804 				IP_REASS_SET_START(mp, offset);
11805 				mp->b_rptr += offset - start;
11806 				if (ill->ill_isv6) {
11807 					BUMP_MIB(ill->ill_ip6_mib,
11808 					    ipv6ReasmPartDups);
11809 				} else {
11810 					BUMP_MIB(&ip_mib, ipReasmPartDups);
11811 				}
11812 				start = offset;
11813 				if (!mp1->b_cont) {
11814 					/*
11815 					 * After trimming, this guy is now
11816 					 * hanging off the end.
11817 					 */
11818 					mp1->b_cont = mp;
11819 					ipf->ipf_tail_mp = mp;
11820 					if (!more) {
11821 						ipf->ipf_hole_cnt--;
11822 					}
11823 					break;
11824 				}
11825 			}
11826 			if (start >= IP_REASS_START(mp1->b_cont))
11827 				continue;
11828 			/* Fill a hole */
11829 			if (start > offset)
11830 				ipf->ipf_hole_cnt++;
11831 			mp->b_cont = mp1->b_cont;
11832 			mp1->b_cont = mp;
11833 			mp1 = mp->b_cont;
11834 			offset = IP_REASS_START(mp1);
11835 			if (end >= offset) {
11836 				ipf->ipf_hole_cnt--;
11837 				/* Check for overlap. */
11838 				while (end > offset) {
11839 					if (end < IP_REASS_END(mp1)) {
11840 						mp->b_wptr -= end - offset;
11841 						IP_REASS_SET_END(mp, offset);
11842 						/*
11843 						 * TODO we might bump
11844 						 * this up twice if there is
11845 						 * overlap at both ends.
11846 						 */
11847 						if (ill->ill_isv6) {
11848 							BUMP_MIB(
11849 							    ill->ill_ip6_mib,
11850 							    ipv6ReasmPartDups);
11851 						} else {
11852 							BUMP_MIB(&ip_mib,
11853 							    ipReasmPartDups);
11854 						}
11855 						break;
11856 					}
11857 					/* Did we cover another hole? */
11858 					if ((mp1->b_cont &&
11859 					    IP_REASS_END(mp1)
11860 					    != IP_REASS_START(mp1->b_cont) &&
11861 					    end >=
11862 					    IP_REASS_START(mp1->b_cont)) ||
11863 					    (!ipf->ipf_last_frag_seen &&
11864 					    !more)) {
11865 						ipf->ipf_hole_cnt--;
11866 					}
11867 					/* Clip out mp1. */
11868 					if ((mp->b_cont = mp1->b_cont) ==
11869 					    NULL) {
11870 						/*
11871 						 * After clipping out mp1,
11872 						 * this guy is now hanging
11873 						 * off the end.
11874 						 */
11875 						ipf->ipf_tail_mp = mp;
11876 					}
11877 					IP_REASS_SET_START(mp1, 0);
11878 					IP_REASS_SET_END(mp1, 0);
11879 					/* Subtract byte count */
11880 					ipf->ipf_count -=
11881 					    mp1->b_datap->db_lim -
11882 					    mp1->b_datap->db_base;
11883 					freeb(mp1);
11884 					if (ill->ill_isv6) {
11885 						BUMP_MIB(ill->ill_ip6_mib,
11886 						    ipv6ReasmPartDups);
11887 					} else {
11888 						BUMP_MIB(&ip_mib,
11889 						    ipReasmPartDups);
11890 					}
11891 					mp1 = mp->b_cont;
11892 					if (!mp1)
11893 						break;
11894 					offset = IP_REASS_START(mp1);
11895 				}
11896 			}
11897 			break;
11898 		}
11899 	} while (start = end, mp = next_mp);
11900 
11901 	/* Fragment just processed could be the last one. Remember this fact */
11902 	if (!more)
11903 		ipf->ipf_last_frag_seen = B_TRUE;
11904 
11905 	/* Still got holes? */
11906 	if (ipf->ipf_hole_cnt)
11907 		return (IP_REASS_PARTIAL);
11908 	/* Clean up overloaded fields to avoid upstream disasters. */
11909 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11910 		IP_REASS_SET_START(mp1, 0);
11911 		IP_REASS_SET_END(mp1, 0);
11912 	}
11913 	return (IP_REASS_COMPLETE);
11914 }
11915 
11916 /*
11917  * ipsec processing for the fast path, used for input UDP Packets
11918  */
11919 static boolean_t
11920 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11921     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11922 {
11923 	uint32_t	ill_index;
11924 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11925 
11926 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11927 	/* The ill_index of the incoming ILL */
11928 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11929 
11930 	/* pass packet up to the transport */
11931 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
11932 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11933 		    NULL, mctl_present);
11934 		if (*first_mpp == NULL) {
11935 			return (B_FALSE);
11936 		}
11937 	}
11938 
11939 	/* Initiate IPPF processing for fastpath UDP */
11940 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
11941 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11942 		if (*mpp == NULL) {
11943 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11944 			    "deferred/dropped during IPPF processing\n"));
11945 			return (B_FALSE);
11946 		}
11947 	}
11948 	/*
11949 	 * We make the checks as below since we are in the fast path
11950 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11951 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11952 	 */
11953 	if (connp->conn_recvif || connp->conn_recvslla ||
11954 	    connp->conn_ipv6_recvpktinfo) {
11955 		if (connp->conn_recvif ||
11956 		    connp->conn_ipv6_recvpktinfo) {
11957 			in_flags = IPF_RECVIF;
11958 		}
11959 		if (connp->conn_recvslla) {
11960 			in_flags |= IPF_RECVSLLA;
11961 		}
11962 		/*
11963 		 * since in_flags are being set ill will be
11964 		 * referenced in ip_add_info, so it better not
11965 		 * be NULL.
11966 		 */
11967 		/*
11968 		 * the actual data will be contained in b_cont
11969 		 * upon successful return of the following call.
11970 		 * If the call fails then the original mblk is
11971 		 * returned.
11972 		 */
11973 		*mpp = ip_add_info(*mpp, ill, in_flags);
11974 	}
11975 
11976 	return (B_TRUE);
11977 }
11978 
11979 /*
11980  * Fragmentation reassembly.  Each ILL has a hash table for
11981  * queuing packets undergoing reassembly for all IPIFs
11982  * associated with the ILL.  The hash is based on the packet
11983  * IP ident field.  The ILL frag hash table was allocated
11984  * as a timer block at the time the ILL was created.  Whenever
11985  * there is anything on the reassembly queue, the timer will
11986  * be running.  Returns B_TRUE if successful else B_FALSE;
11987  * frees mp on failure.
11988  */
11989 static boolean_t
11990 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
11991     uint32_t *cksum_val, uint16_t *cksum_flags)
11992 {
11993 	uint32_t	frag_offset_flags;
11994 	ill_t		*ill = (ill_t *)q->q_ptr;
11995 	mblk_t		*mp = *mpp;
11996 	mblk_t		*t_mp;
11997 	ipaddr_t	dst;
11998 	uint8_t		proto = ipha->ipha_protocol;
11999 	uint32_t	sum_val;
12000 	uint16_t	sum_flags;
12001 	ipf_t		*ipf;
12002 	ipf_t		**ipfp;
12003 	ipfb_t		*ipfb;
12004 	uint16_t	ident;
12005 	uint32_t	offset;
12006 	ipaddr_t	src;
12007 	uint_t		hdr_length;
12008 	uint32_t	end;
12009 	mblk_t		*mp1;
12010 	mblk_t		*tail_mp;
12011 	size_t		count;
12012 	size_t		msg_len;
12013 	uint8_t		ecn_info = 0;
12014 	uint32_t	packet_size;
12015 	boolean_t	pruned = B_FALSE;
12016 
12017 	if (cksum_val != NULL)
12018 		*cksum_val = 0;
12019 	if (cksum_flags != NULL)
12020 		*cksum_flags = 0;
12021 
12022 	/*
12023 	 * Drop the fragmented as early as possible, if
12024 	 * we don't have resource(s) to re-assemble.
12025 	 */
12026 	if (ip_reass_queue_bytes == 0) {
12027 		freemsg(mp);
12028 		return (B_FALSE);
12029 	}
12030 
12031 	/* Check for fragmentation offset; return if there's none */
12032 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12033 	    (IPH_MF | IPH_OFFSET)) == 0)
12034 		return (B_TRUE);
12035 
12036 	/*
12037 	 * We utilize hardware computed checksum info only for UDP since
12038 	 * IP fragmentation is a normal occurence for the protocol.  In
12039 	 * addition, checksum offload support for IP fragments carrying
12040 	 * UDP payload is commonly implemented across network adapters.
12041 	 */
12042 	ASSERT(ill != NULL);
12043 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12044 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12045 		mblk_t *mp1 = mp->b_cont;
12046 		int32_t len;
12047 
12048 		/* Record checksum information from the packet */
12049 		sum_val = (uint32_t)DB_CKSUM16(mp);
12050 		sum_flags = DB_CKSUMFLAGS(mp);
12051 
12052 		/* IP payload offset from beginning of mblk */
12053 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12054 
12055 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12056 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12057 		    offset >= DB_CKSUMSTART(mp) &&
12058 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12059 			uint32_t adj;
12060 			/*
12061 			 * Partial checksum has been calculated by hardware
12062 			 * and attached to the packet; in addition, any
12063 			 * prepended extraneous data is even byte aligned.
12064 			 * If any such data exists, we adjust the checksum;
12065 			 * this would also handle any postpended data.
12066 			 */
12067 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12068 			    mp, mp1, len, adj);
12069 
12070 			/* One's complement subtract extraneous checksum */
12071 			if (adj >= sum_val)
12072 				sum_val = ~(adj - sum_val) & 0xFFFF;
12073 			else
12074 				sum_val -= adj;
12075 		}
12076 	} else {
12077 		sum_val = 0;
12078 		sum_flags = 0;
12079 	}
12080 
12081 	/* Clear hardware checksumming flag */
12082 	DB_CKSUMFLAGS(mp) = 0;
12083 
12084 	ident = ipha->ipha_ident;
12085 	offset = (frag_offset_flags << 3) & 0xFFFF;
12086 	src = ipha->ipha_src;
12087 	dst = ipha->ipha_dst;
12088 	hdr_length = IPH_HDR_LENGTH(ipha);
12089 	end = ntohs(ipha->ipha_length) - hdr_length;
12090 
12091 	/* If end == 0 then we have a packet with no data, so just free it */
12092 	if (end == 0) {
12093 		freemsg(mp);
12094 		return (B_FALSE);
12095 	}
12096 
12097 	/* Record the ECN field info. */
12098 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12099 	if (offset != 0) {
12100 		/*
12101 		 * If this isn't the first piece, strip the header, and
12102 		 * add the offset to the end value.
12103 		 */
12104 		mp->b_rptr += hdr_length;
12105 		end += offset;
12106 	}
12107 
12108 	msg_len = MBLKSIZE(mp);
12109 	tail_mp = mp;
12110 	while (tail_mp->b_cont != NULL) {
12111 		tail_mp = tail_mp->b_cont;
12112 		msg_len += MBLKSIZE(tail_mp);
12113 	}
12114 
12115 	/* If the reassembly list for this ILL will get too big, prune it */
12116 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12117 	    ip_reass_queue_bytes) {
12118 		ill_frag_prune(ill,
12119 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12120 		    (ip_reass_queue_bytes - msg_len));
12121 		pruned = B_TRUE;
12122 	}
12123 
12124 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12125 	mutex_enter(&ipfb->ipfb_lock);
12126 
12127 	ipfp = &ipfb->ipfb_ipf;
12128 	/* Try to find an existing fragment queue for this packet. */
12129 	for (;;) {
12130 		ipf = ipfp[0];
12131 		if (ipf != NULL) {
12132 			/*
12133 			 * It has to match on ident and src/dst address.
12134 			 */
12135 			if (ipf->ipf_ident == ident &&
12136 			    ipf->ipf_src == src &&
12137 			    ipf->ipf_dst == dst &&
12138 			    ipf->ipf_protocol == proto) {
12139 				/*
12140 				 * If we have received too many
12141 				 * duplicate fragments for this packet
12142 				 * free it.
12143 				 */
12144 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12145 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12146 					freemsg(mp);
12147 					mutex_exit(&ipfb->ipfb_lock);
12148 					return (B_FALSE);
12149 				}
12150 				/* Found it. */
12151 				break;
12152 			}
12153 			ipfp = &ipf->ipf_hash_next;
12154 			continue;
12155 		}
12156 
12157 		/*
12158 		 * If we pruned the list, do we want to store this new
12159 		 * fragment?. We apply an optimization here based on the
12160 		 * fact that most fragments will be received in order.
12161 		 * So if the offset of this incoming fragment is zero,
12162 		 * it is the first fragment of a new packet. We will
12163 		 * keep it.  Otherwise drop the fragment, as we have
12164 		 * probably pruned the packet already (since the
12165 		 * packet cannot be found).
12166 		 */
12167 		if (pruned && offset != 0) {
12168 			mutex_exit(&ipfb->ipfb_lock);
12169 			freemsg(mp);
12170 			return (B_FALSE);
12171 		}
12172 
12173 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12174 			/*
12175 			 * Too many fragmented packets in this hash
12176 			 * bucket. Free the oldest.
12177 			 */
12178 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12179 		}
12180 
12181 		/* New guy.  Allocate a frag message. */
12182 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12183 		if (mp1 == NULL) {
12184 			BUMP_MIB(&ip_mib, ipInDiscards);
12185 			freemsg(mp);
12186 reass_done:
12187 			mutex_exit(&ipfb->ipfb_lock);
12188 			return (B_FALSE);
12189 		}
12190 
12191 
12192 		BUMP_MIB(&ip_mib, ipReasmReqds);
12193 		mp1->b_cont = mp;
12194 
12195 		/* Initialize the fragment header. */
12196 		ipf = (ipf_t *)mp1->b_rptr;
12197 		ipf->ipf_mp = mp1;
12198 		ipf->ipf_ptphn = ipfp;
12199 		ipfp[0] = ipf;
12200 		ipf->ipf_hash_next = NULL;
12201 		ipf->ipf_ident = ident;
12202 		ipf->ipf_protocol = proto;
12203 		ipf->ipf_src = src;
12204 		ipf->ipf_dst = dst;
12205 		ipf->ipf_nf_hdr_len = 0;
12206 		/* Record reassembly start time. */
12207 		ipf->ipf_timestamp = gethrestime_sec();
12208 		/* Record ipf generation and account for frag header */
12209 		ipf->ipf_gen = ill->ill_ipf_gen++;
12210 		ipf->ipf_count = MBLKSIZE(mp1);
12211 		ipf->ipf_last_frag_seen = B_FALSE;
12212 		ipf->ipf_ecn = ecn_info;
12213 		ipf->ipf_num_dups = 0;
12214 		ipfb->ipfb_frag_pkts++;
12215 		ipf->ipf_checksum = 0;
12216 		ipf->ipf_checksum_flags = 0;
12217 
12218 		/* Store checksum value in fragment header */
12219 		if (sum_flags != 0) {
12220 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12221 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12222 			ipf->ipf_checksum = sum_val;
12223 			ipf->ipf_checksum_flags = sum_flags;
12224 		}
12225 
12226 		/*
12227 		 * We handle reassembly two ways.  In the easy case,
12228 		 * where all the fragments show up in order, we do
12229 		 * minimal bookkeeping, and just clip new pieces on
12230 		 * the end.  If we ever see a hole, then we go off
12231 		 * to ip_reassemble which has to mark the pieces and
12232 		 * keep track of the number of holes, etc.  Obviously,
12233 		 * the point of having both mechanisms is so we can
12234 		 * handle the easy case as efficiently as possible.
12235 		 */
12236 		if (offset == 0) {
12237 			/* Easy case, in-order reassembly so far. */
12238 			ipf->ipf_count += msg_len;
12239 			ipf->ipf_tail_mp = tail_mp;
12240 			/*
12241 			 * Keep track of next expected offset in
12242 			 * ipf_end.
12243 			 */
12244 			ipf->ipf_end = end;
12245 			ipf->ipf_nf_hdr_len = hdr_length;
12246 		} else {
12247 			/* Hard case, hole at the beginning. */
12248 			ipf->ipf_tail_mp = NULL;
12249 			/*
12250 			 * ipf_end == 0 means that we have given up
12251 			 * on easy reassembly.
12252 			 */
12253 			ipf->ipf_end = 0;
12254 
12255 			/* Forget checksum offload from now on */
12256 			ipf->ipf_checksum_flags = 0;
12257 
12258 			/*
12259 			 * ipf_hole_cnt is set by ip_reassemble.
12260 			 * ipf_count is updated by ip_reassemble.
12261 			 * No need to check for return value here
12262 			 * as we don't expect reassembly to complete
12263 			 * or fail for the first fragment itself.
12264 			 */
12265 			(void) ip_reassemble(mp, ipf,
12266 			    (frag_offset_flags & IPH_OFFSET) << 3,
12267 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12268 		}
12269 		/* Update per ipfb and ill byte counts */
12270 		ipfb->ipfb_count += ipf->ipf_count;
12271 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12272 		ill->ill_frag_count += ipf->ipf_count;
12273 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12274 		/* If the frag timer wasn't already going, start it. */
12275 		mutex_enter(&ill->ill_lock);
12276 		ill_frag_timer_start(ill);
12277 		mutex_exit(&ill->ill_lock);
12278 		goto reass_done;
12279 	}
12280 
12281 	/*
12282 	 * If the packet's flag has changed (it could be coming up
12283 	 * from an interface different than the previous, therefore
12284 	 * possibly different checksum capability), then forget about
12285 	 * any stored checksum states.  Otherwise add the value to
12286 	 * the existing one stored in the fragment header.
12287 	 */
12288 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12289 		sum_val += ipf->ipf_checksum;
12290 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12291 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12292 		ipf->ipf_checksum = sum_val;
12293 	} else if (ipf->ipf_checksum_flags != 0) {
12294 		/* Forget checksum offload from now on */
12295 		ipf->ipf_checksum_flags = 0;
12296 	}
12297 
12298 	/*
12299 	 * We have a new piece of a datagram which is already being
12300 	 * reassembled.  Update the ECN info if all IP fragments
12301 	 * are ECN capable.  If there is one which is not, clear
12302 	 * all the info.  If there is at least one which has CE
12303 	 * code point, IP needs to report that up to transport.
12304 	 */
12305 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12306 		if (ecn_info == IPH_ECN_CE)
12307 			ipf->ipf_ecn = IPH_ECN_CE;
12308 	} else {
12309 		ipf->ipf_ecn = IPH_ECN_NECT;
12310 	}
12311 	if (offset && ipf->ipf_end == offset) {
12312 		/* The new fragment fits at the end */
12313 		ipf->ipf_tail_mp->b_cont = mp;
12314 		/* Update the byte count */
12315 		ipf->ipf_count += msg_len;
12316 		/* Update per ipfb and ill byte counts */
12317 		ipfb->ipfb_count += msg_len;
12318 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12319 		ill->ill_frag_count += msg_len;
12320 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12321 		if (frag_offset_flags & IPH_MF) {
12322 			/* More to come. */
12323 			ipf->ipf_end = end;
12324 			ipf->ipf_tail_mp = tail_mp;
12325 			goto reass_done;
12326 		}
12327 	} else {
12328 		/* Go do the hard cases. */
12329 		int ret;
12330 
12331 		if (offset == 0)
12332 			ipf->ipf_nf_hdr_len = hdr_length;
12333 
12334 		/* Save current byte count */
12335 		count = ipf->ipf_count;
12336 		ret = ip_reassemble(mp, ipf,
12337 		    (frag_offset_flags & IPH_OFFSET) << 3,
12338 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12339 		/* Count of bytes added and subtracted (freeb()ed) */
12340 		count = ipf->ipf_count - count;
12341 		if (count) {
12342 			/* Update per ipfb and ill byte counts */
12343 			ipfb->ipfb_count += count;
12344 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12345 			ill->ill_frag_count += count;
12346 			ASSERT(ill->ill_frag_count > 0);
12347 		}
12348 		if (ret == IP_REASS_PARTIAL) {
12349 			goto reass_done;
12350 		} else if (ret == IP_REASS_FAILED) {
12351 			/* Reassembly failed. Free up all resources */
12352 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12353 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12354 				IP_REASS_SET_START(t_mp, 0);
12355 				IP_REASS_SET_END(t_mp, 0);
12356 			}
12357 			freemsg(mp);
12358 			goto reass_done;
12359 		}
12360 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12361 	}
12362 	/*
12363 	 * We have completed reassembly.  Unhook the frag header from
12364 	 * the reassembly list.
12365 	 *
12366 	 * Before we free the frag header, record the ECN info
12367 	 * to report back to the transport.
12368 	 */
12369 	ecn_info = ipf->ipf_ecn;
12370 	BUMP_MIB(&ip_mib, ipReasmOKs);
12371 	ipfp = ipf->ipf_ptphn;
12372 
12373 	/* We need to supply these to caller */
12374 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12375 		sum_val = ipf->ipf_checksum;
12376 	else
12377 		sum_val = 0;
12378 
12379 	mp1 = ipf->ipf_mp;
12380 	count = ipf->ipf_count;
12381 	ipf = ipf->ipf_hash_next;
12382 	if (ipf != NULL)
12383 		ipf->ipf_ptphn = ipfp;
12384 	ipfp[0] = ipf;
12385 	ill->ill_frag_count -= count;
12386 	ASSERT(ipfb->ipfb_count >= count);
12387 	ipfb->ipfb_count -= count;
12388 	ipfb->ipfb_frag_pkts--;
12389 	mutex_exit(&ipfb->ipfb_lock);
12390 	/* Ditch the frag header. */
12391 	mp = mp1->b_cont;
12392 
12393 	freeb(mp1);
12394 
12395 	/* Restore original IP length in header. */
12396 	packet_size = (uint32_t)msgdsize(mp);
12397 	if (packet_size > IP_MAXPACKET) {
12398 		freemsg(mp);
12399 		BUMP_MIB(&ip_mib, ipInHdrErrors);
12400 		return (B_FALSE);
12401 	}
12402 
12403 	if (DB_REF(mp) > 1) {
12404 		mblk_t *mp2 = copymsg(mp);
12405 
12406 		freemsg(mp);
12407 		if (mp2 == NULL) {
12408 			BUMP_MIB(&ip_mib, ipInDiscards);
12409 			return (B_FALSE);
12410 		}
12411 		mp = mp2;
12412 	}
12413 	ipha = (ipha_t *)mp->b_rptr;
12414 
12415 	ipha->ipha_length = htons((uint16_t)packet_size);
12416 	/* We're now complete, zip the frag state */
12417 	ipha->ipha_fragment_offset_and_flags = 0;
12418 	/* Record the ECN info. */
12419 	ipha->ipha_type_of_service &= 0xFC;
12420 	ipha->ipha_type_of_service |= ecn_info;
12421 	*mpp = mp;
12422 
12423 	/* Reassembly is successful; return checksum information if needed */
12424 	if (cksum_val != NULL)
12425 		*cksum_val = sum_val;
12426 	if (cksum_flags != NULL)
12427 		*cksum_flags = sum_flags;
12428 
12429 	return (B_TRUE);
12430 }
12431 
12432 /*
12433  * Perform ip header check sum update local options.
12434  * return B_TRUE if all is well, else return B_FALSE and release
12435  * the mp. caller is responsible for decrementing ire ref cnt.
12436  */
12437 static boolean_t
12438 ip_options_cksum(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12439 {
12440 	mblk_t		*first_mp;
12441 	boolean_t	mctl_present;
12442 	uint16_t	sum;
12443 
12444 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12445 	/*
12446 	 * Don't do the checksum if it has gone through AH/ESP
12447 	 * processing.
12448 	 */
12449 	if (!mctl_present) {
12450 		sum = ip_csum_hdr(ipha);
12451 		if (sum != 0) {
12452 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12453 			freemsg(first_mp);
12454 			return (B_FALSE);
12455 		}
12456 	}
12457 
12458 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12459 		if (mctl_present)
12460 			freeb(first_mp);
12461 		return (B_FALSE);
12462 	}
12463 
12464 	return (B_TRUE);
12465 }
12466 
12467 /*
12468  * All udp packet are delivered to the local host via this routine.
12469  */
12470 void
12471 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12472     ill_t *recv_ill)
12473 {
12474 	uint32_t	sum;
12475 	uint32_t	u1;
12476 	boolean_t	mctl_present;
12477 	conn_t		*connp;
12478 	mblk_t		*first_mp;
12479 	uint16_t	*up;
12480 	ill_t		*ill = (ill_t *)q->q_ptr;
12481 	uint16_t	reass_hck_flags = 0;
12482 
12483 #define	rptr    ((uchar_t *)ipha)
12484 
12485 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12486 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12487 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12488 
12489 	/*
12490 	 * FAST PATH for udp packets
12491 	 */
12492 
12493 	/* u1 is # words of IP options */
12494 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12495 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12496 
12497 	/* IP options present */
12498 	if (u1 != 0)
12499 		goto ipoptions;
12500 
12501 	/* Check the IP header checksum.  */
12502 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12503 		/* Clear the IP header h/w cksum flag */
12504 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12505 	} else {
12506 #define	uph	((uint16_t *)ipha)
12507 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12508 		    uph[6] + uph[7] + uph[8] + uph[9];
12509 #undef	uph
12510 		/* finish doing IP checksum */
12511 		sum = (sum & 0xFFFF) + (sum >> 16);
12512 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12513 		/*
12514 		 * Don't verify header checksum if this packet is coming
12515 		 * back from AH/ESP as we already did it.
12516 		 */
12517 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12518 			BUMP_MIB(&ip_mib, ipInCksumErrs);
12519 			freemsg(first_mp);
12520 			return;
12521 		}
12522 	}
12523 
12524 	/*
12525 	 * Count for SNMP of inbound packets for ire.
12526 	 * if mctl is present this might be a secure packet and
12527 	 * has already been counted for in ip_proto_input().
12528 	 */
12529 	if (!mctl_present) {
12530 		UPDATE_IB_PKT_COUNT(ire);
12531 		ire->ire_last_used_time = lbolt;
12532 	}
12533 
12534 	/* packet part of fragmented IP packet? */
12535 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12536 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12537 		goto fragmented;
12538 	}
12539 
12540 	/* u1 = IP header length (20 bytes) */
12541 	u1 = IP_SIMPLE_HDR_LENGTH;
12542 
12543 	/* packet does not contain complete IP & UDP headers */
12544 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12545 		goto udppullup;
12546 
12547 	/* up points to UDP header */
12548 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12549 #define	iphs    ((uint16_t *)ipha)
12550 
12551 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12552 	if (up[3] != 0) {
12553 		mblk_t *mp1 = mp->b_cont;
12554 		boolean_t cksum_err;
12555 		uint16_t hck_flags = 0;
12556 
12557 		/* Pseudo-header checksum */
12558 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12559 		    iphs[9] + up[2];
12560 
12561 		/*
12562 		 * Revert to software checksum calculation if the interface
12563 		 * isn't capable of checksum offload or if IPsec is present.
12564 		 */
12565 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12566 			hck_flags = DB_CKSUMFLAGS(mp);
12567 
12568 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12569 			IP_STAT(ip_in_sw_cksum);
12570 
12571 		IP_CKSUM_RECV(hck_flags, u1,
12572 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12573 		    (int32_t)((uchar_t *)up - rptr),
12574 		    mp, mp1, cksum_err);
12575 
12576 		if (cksum_err) {
12577 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12578 
12579 			if (hck_flags & HCK_FULLCKSUM)
12580 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12581 			else if (hck_flags & HCK_PARTIALCKSUM)
12582 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12583 			else
12584 				IP_STAT(ip_udp_in_sw_cksum_err);
12585 
12586 			freemsg(first_mp);
12587 			return;
12588 		}
12589 	}
12590 
12591 	/* Non-fragmented broadcast or multicast packet? */
12592 	if (ire->ire_type == IRE_BROADCAST)
12593 		goto udpslowpath;
12594 
12595 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12596 	    ire->ire_zoneid)) != NULL) {
12597 		ASSERT(connp->conn_upq != NULL);
12598 		IP_STAT(ip_udp_fast_path);
12599 
12600 		if (CONN_UDP_FLOWCTLD(connp)) {
12601 			freemsg(mp);
12602 			BUMP_MIB(&ip_mib, udpInOverflows);
12603 		} else {
12604 			if (!mctl_present) {
12605 				BUMP_MIB(&ip_mib, ipInDelivers);
12606 			}
12607 			/*
12608 			 * mp and first_mp can change.
12609 			 */
12610 			if (ip_udp_check(q, connp, recv_ill,
12611 			    ipha, &mp, &first_mp, mctl_present)) {
12612 				/* Send it upstream */
12613 				CONN_UDP_RECV(connp, mp);
12614 			}
12615 		}
12616 		/*
12617 		 * freeb() cannot deal with null mblk being passed
12618 		 * in and first_mp can be set to null in the call
12619 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12620 		 */
12621 		if (mctl_present && first_mp != NULL) {
12622 			freeb(first_mp);
12623 		}
12624 		CONN_DEC_REF(connp);
12625 		return;
12626 	}
12627 
12628 	/*
12629 	 * if we got here we know the packet is not fragmented and
12630 	 * has no options. The classifier could not find a conn_t and
12631 	 * most likely its an icmp packet so send it through slow path.
12632 	 */
12633 
12634 	goto udpslowpath;
12635 
12636 ipoptions:
12637 	if (!ip_options_cksum(q, mp, ipha, ire)) {
12638 		goto slow_done;
12639 	}
12640 
12641 	UPDATE_IB_PKT_COUNT(ire);
12642 	ire->ire_last_used_time = lbolt;
12643 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12644 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12645 fragmented:
12646 		/*
12647 		 * "sum" and "reass_hck_flags" are non-zero if the
12648 		 * reassembled packet has a valid hardware computed
12649 		 * checksum information associated with it.
12650 		 */
12651 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12652 			goto slow_done;
12653 		/*
12654 		 * Make sure that first_mp points back to mp as
12655 		 * the mp we came in with could have changed in
12656 		 * ip_rput_fragment().
12657 		 */
12658 		ASSERT(!mctl_present);
12659 		ipha = (ipha_t *)mp->b_rptr;
12660 		first_mp = mp;
12661 	}
12662 
12663 	/* Now we have a complete datagram, destined for this machine. */
12664 	u1 = IPH_HDR_LENGTH(ipha);
12665 	/* Pull up the UDP header, if necessary. */
12666 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12667 udppullup:
12668 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12669 			BUMP_MIB(&ip_mib, ipInDiscards);
12670 			freemsg(first_mp);
12671 			goto slow_done;
12672 		}
12673 		ipha = (ipha_t *)mp->b_rptr;
12674 	}
12675 
12676 	/*
12677 	 * Validate the checksum for the reassembled packet; for the
12678 	 * pullup case we calculate the payload checksum in software.
12679 	 */
12680 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12681 	if (up[3] != 0) {
12682 		boolean_t cksum_err;
12683 
12684 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12685 			IP_STAT(ip_in_sw_cksum);
12686 
12687 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12688 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12689 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12690 		    iphs[9] + up[2], sum, cksum_err);
12691 
12692 		if (cksum_err) {
12693 			BUMP_MIB(&ip_mib, udpInCksumErrs);
12694 
12695 			if (reass_hck_flags & HCK_FULLCKSUM)
12696 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12697 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12698 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12699 			else
12700 				IP_STAT(ip_udp_in_sw_cksum_err);
12701 
12702 			freemsg(first_mp);
12703 			goto slow_done;
12704 		}
12705 	}
12706 udpslowpath:
12707 
12708 	/* Clear hardware checksum flag to be safe */
12709 	DB_CKSUMFLAGS(mp) = 0;
12710 
12711 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12712 	    (ire->ire_type == IRE_BROADCAST),
12713 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IP6INFO,
12714 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12715 
12716 slow_done:
12717 	IP_STAT(ip_udp_slow_path);
12718 	return;
12719 
12720 #undef  iphs
12721 #undef  rptr
12722 }
12723 
12724 /* ARGSUSED */
12725 static mblk_t *
12726 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12727     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12728     ill_rx_ring_t *ill_ring)
12729 {
12730 	conn_t		*connp;
12731 	uint32_t	sum;
12732 	uint32_t	u1;
12733 	uint16_t	*up;
12734 	int		offset;
12735 	ssize_t		len;
12736 	mblk_t		*mp1;
12737 	boolean_t	syn_present = B_FALSE;
12738 	tcph_t		*tcph;
12739 	uint_t		ip_hdr_len;
12740 	ill_t		*ill = (ill_t *)q->q_ptr;
12741 	zoneid_t	zoneid = ire->ire_zoneid;
12742 	boolean_t	cksum_err;
12743 	uint16_t	hck_flags = 0;
12744 
12745 #define	rptr	((uchar_t *)ipha)
12746 
12747 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12748 
12749 	/*
12750 	 * FAST PATH for tcp packets
12751 	 */
12752 
12753 	/* u1 is # words of IP options */
12754 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12755 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12756 
12757 	/* IP options present */
12758 	if (u1) {
12759 		goto ipoptions;
12760 	} else {
12761 		/* Check the IP header checksum.  */
12762 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12763 			/* Clear the IP header h/w cksum flag */
12764 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12765 		} else {
12766 #define	uph	((uint16_t *)ipha)
12767 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12768 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12769 #undef	uph
12770 			/* finish doing IP checksum */
12771 			sum = (sum & 0xFFFF) + (sum >> 16);
12772 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12773 			/*
12774 			 * Don't verify header checksum if this packet
12775 			 * is coming back from AH/ESP as we already did it.
12776 			 */
12777 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12778 				BUMP_MIB(&ip_mib, ipInCksumErrs);
12779 				goto error;
12780 			}
12781 		}
12782 	}
12783 
12784 	if (!mctl_present) {
12785 		UPDATE_IB_PKT_COUNT(ire);
12786 		ire->ire_last_used_time = lbolt;
12787 	}
12788 
12789 	/* packet part of fragmented IP packet? */
12790 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12791 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12792 		goto fragmented;
12793 	}
12794 
12795 	/* u1 = IP header length (20 bytes) */
12796 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12797 
12798 	/* does packet contain IP+TCP headers? */
12799 	len = mp->b_wptr - rptr;
12800 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12801 		IP_STAT(ip_tcppullup);
12802 		goto tcppullup;
12803 	}
12804 
12805 	/* TCP options present? */
12806 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12807 
12808 	/*
12809 	 * If options need to be pulled up, then goto tcpoptions.
12810 	 * otherwise we are still in the fast path
12811 	 */
12812 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12813 		IP_STAT(ip_tcpoptions);
12814 		goto tcpoptions;
12815 	}
12816 
12817 	/* multiple mblks of tcp data? */
12818 	if ((mp1 = mp->b_cont) != NULL) {
12819 		/* more then two? */
12820 		if (mp1->b_cont != NULL) {
12821 			IP_STAT(ip_multipkttcp);
12822 			goto multipkttcp;
12823 		}
12824 		len += mp1->b_wptr - mp1->b_rptr;
12825 	}
12826 
12827 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12828 
12829 	/* part of pseudo checksum */
12830 
12831 	/* TCP datagram length */
12832 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12833 
12834 #define	iphs    ((uint16_t *)ipha)
12835 
12836 #ifdef	_BIG_ENDIAN
12837 	u1 += IPPROTO_TCP;
12838 #else
12839 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12840 #endif
12841 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12842 
12843 	/*
12844 	 * Revert to software checksum calculation if the interface
12845 	 * isn't capable of checksum offload or if IPsec is present.
12846 	 */
12847 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12848 		hck_flags = DB_CKSUMFLAGS(mp);
12849 
12850 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12851 		IP_STAT(ip_in_sw_cksum);
12852 
12853 	IP_CKSUM_RECV(hck_flags, u1,
12854 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12855 	    (int32_t)((uchar_t *)up - rptr),
12856 	    mp, mp1, cksum_err);
12857 
12858 	if (cksum_err) {
12859 		BUMP_MIB(&ip_mib, tcpInErrs);
12860 
12861 		if (hck_flags & HCK_FULLCKSUM)
12862 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
12863 		else if (hck_flags & HCK_PARTIALCKSUM)
12864 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
12865 		else
12866 			IP_STAT(ip_tcp_in_sw_cksum_err);
12867 
12868 		goto error;
12869 	}
12870 
12871 try_again:
12872 
12873 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
12874 	    NULL) {
12875 		/* Send the TH_RST */
12876 		goto no_conn;
12877 	}
12878 
12879 	/*
12880 	 * TCP FAST PATH for AF_INET socket.
12881 	 *
12882 	 * TCP fast path to avoid extra work. An AF_INET socket type
12883 	 * does not have facility to receive extra information via
12884 	 * ip_process or ip_add_info. Also, when the connection was
12885 	 * established, we made a check if this connection is impacted
12886 	 * by any global IPSec policy or per connection policy (a
12887 	 * policy that comes in effect later will not apply to this
12888 	 * connection). Since all this can be determined at the
12889 	 * connection establishment time, a quick check of flags
12890 	 * can avoid extra work.
12891 	 */
12892 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12893 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
12894 		ASSERT(first_mp == mp);
12895 		SET_SQUEUE(mp, tcp_rput_data, connp);
12896 		return (mp);
12897 	}
12898 
12899 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12900 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12901 		if (IPCL_IS_TCP(connp)) {
12902 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12903 			DB_CKSUMSTART(mp) =
12904 			    (intptr_t)ip_squeue_get(ill_ring);
12905 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12906 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12907 				SET_SQUEUE(mp, connp->conn_recv, connp);
12908 				return (mp);
12909 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12910 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
12911 				ip_squeue_enter_unbound++;
12912 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12913 				    connp);
12914 				return (mp);
12915 			}
12916 			syn_present = B_TRUE;
12917 		}
12918 
12919 	}
12920 
12921 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
12922 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12923 
12924 		/* No need to send this packet to TCP */
12925 		if ((flags & TH_RST) || (flags & TH_URG)) {
12926 			CONN_DEC_REF(connp);
12927 			freemsg(first_mp);
12928 			return (NULL);
12929 		}
12930 		if (flags & TH_ACK) {
12931 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
12932 			CONN_DEC_REF(connp);
12933 			return (NULL);
12934 		}
12935 
12936 		CONN_DEC_REF(connp);
12937 		freemsg(first_mp);
12938 		return (NULL);
12939 	}
12940 
12941 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12942 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
12943 		    ipha, NULL, mctl_present);
12944 		if (first_mp == NULL) {
12945 			CONN_DEC_REF(connp);
12946 			return (NULL);
12947 		}
12948 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
12949 			ASSERT(syn_present);
12950 			if (mctl_present) {
12951 				ASSERT(first_mp != mp);
12952 				first_mp->b_datap->db_struioflag |=
12953 				    STRUIO_POLICY;
12954 			} else {
12955 				ASSERT(first_mp == mp);
12956 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
12957 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
12958 			}
12959 		} else {
12960 			/*
12961 			 * Discard first_mp early since we're dealing with a
12962 			 * fully-connected conn_t and tcp doesn't do policy in
12963 			 * this case.
12964 			 */
12965 			if (mctl_present) {
12966 				freeb(first_mp);
12967 				mctl_present = B_FALSE;
12968 			}
12969 			first_mp = mp;
12970 		}
12971 	}
12972 
12973 	/* Initiate IPPF processing for fastpath */
12974 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12975 		uint32_t	ill_index;
12976 
12977 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
12978 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
12979 		if (mp == NULL) {
12980 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
12981 			    "deferred/dropped during IPPF processing\n"));
12982 			CONN_DEC_REF(connp);
12983 			if (mctl_present)
12984 				freeb(first_mp);
12985 			return (NULL);
12986 		} else if (mctl_present) {
12987 			/*
12988 			 * ip_process might return a new mp.
12989 			 */
12990 			ASSERT(first_mp != mp);
12991 			first_mp->b_cont = mp;
12992 		} else {
12993 			first_mp = mp;
12994 		}
12995 
12996 	}
12997 
12998 	if (!syn_present && connp->conn_ipv6_recvpktinfo) {
12999 		mp = ip_add_info(mp, recv_ill, flags);
13000 		if (mp == NULL) {
13001 			CONN_DEC_REF(connp);
13002 			if (mctl_present)
13003 				freeb(first_mp);
13004 			return (NULL);
13005 		} else if (mctl_present) {
13006 			/*
13007 			 * ip_add_info might return a new mp.
13008 			 */
13009 			ASSERT(first_mp != mp);
13010 			first_mp->b_cont = mp;
13011 		} else {
13012 			first_mp = mp;
13013 		}
13014 	}
13015 
13016 	if (IPCL_IS_TCP(connp)) {
13017 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13018 		return (first_mp);
13019 	} else {
13020 		putnext(connp->conn_rq, first_mp);
13021 		CONN_DEC_REF(connp);
13022 		return (NULL);
13023 	}
13024 
13025 no_conn:
13026 	/* Initiate IPPf processing, if needed. */
13027 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13028 		uint32_t ill_index;
13029 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13030 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13031 		if (first_mp == NULL) {
13032 			return (NULL);
13033 		}
13034 	}
13035 	BUMP_MIB(&ip_mib, ipInDelivers);
13036 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13037 	return (NULL);
13038 ipoptions:
13039 	if (!ip_options_cksum(q, first_mp, ipha, ire)) {
13040 		goto slow_done;
13041 	}
13042 
13043 	UPDATE_IB_PKT_COUNT(ire);
13044 	ire->ire_last_used_time = lbolt;
13045 
13046 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13047 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13048 fragmented:
13049 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13050 			if (mctl_present)
13051 				freeb(first_mp);
13052 			goto slow_done;
13053 		}
13054 		/*
13055 		 * Make sure that first_mp points back to mp as
13056 		 * the mp we came in with could have changed in
13057 		 * ip_rput_fragment().
13058 		 */
13059 		ASSERT(!mctl_present);
13060 		ipha = (ipha_t *)mp->b_rptr;
13061 		first_mp = mp;
13062 	}
13063 
13064 	/* Now we have a complete datagram, destined for this machine. */
13065 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13066 
13067 	len = mp->b_wptr - mp->b_rptr;
13068 	/* Pull up a minimal TCP header, if necessary. */
13069 	if (len < (u1 + 20)) {
13070 tcppullup:
13071 		if (!pullupmsg(mp, u1 + 20)) {
13072 			BUMP_MIB(&ip_mib, ipInDiscards);
13073 			goto error;
13074 		}
13075 		ipha = (ipha_t *)mp->b_rptr;
13076 		len = mp->b_wptr - mp->b_rptr;
13077 	}
13078 
13079 	/*
13080 	 * Extract the offset field from the TCP header.  As usual, we
13081 	 * try to help the compiler more than the reader.
13082 	 */
13083 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13084 	if (offset != 5) {
13085 tcpoptions:
13086 		if (offset < 5) {
13087 			BUMP_MIB(&ip_mib, ipInDiscards);
13088 			goto error;
13089 		}
13090 		/*
13091 		 * There must be TCP options.
13092 		 * Make sure we can grab them.
13093 		 */
13094 		offset <<= 2;
13095 		offset += u1;
13096 		if (len < offset) {
13097 			if (!pullupmsg(mp, offset)) {
13098 				BUMP_MIB(&ip_mib, ipInDiscards);
13099 				goto error;
13100 			}
13101 			ipha = (ipha_t *)mp->b_rptr;
13102 			len = mp->b_wptr - rptr;
13103 		}
13104 	}
13105 
13106 	/* Get the total packet length in len, including headers. */
13107 	if (mp->b_cont) {
13108 multipkttcp:
13109 		len = msgdsize(mp);
13110 	}
13111 
13112 	/*
13113 	 * Check the TCP checksum by pulling together the pseudo-
13114 	 * header checksum, and passing it to ip_csum to be added in
13115 	 * with the TCP datagram.
13116 	 *
13117 	 * Since we are not using the hwcksum if available we must
13118 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13119 	 * If either of these fails along the way the mblk is freed.
13120 	 * If this logic ever changes and mblk is reused to say send
13121 	 * ICMP's back, then this flag may need to be cleared in
13122 	 * other places as well.
13123 	 */
13124 	DB_CKSUMFLAGS(mp) = 0;
13125 
13126 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13127 
13128 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13129 #ifdef	_BIG_ENDIAN
13130 	u1 += IPPROTO_TCP;
13131 #else
13132 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13133 #endif
13134 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13135 	/*
13136 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13137 	 */
13138 	IP_STAT(ip_in_sw_cksum);
13139 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13140 		BUMP_MIB(&ip_mib, tcpInErrs);
13141 		goto error;
13142 	}
13143 
13144 	IP_STAT(ip_tcp_slow_path);
13145 	goto try_again;
13146 #undef  iphs
13147 #undef  rptr
13148 
13149 error:
13150 	freemsg(first_mp);
13151 slow_done:
13152 	return (NULL);
13153 }
13154 
13155 /* ARGSUSED */
13156 static void
13157 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13158     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13159 {
13160 	conn_t		*connp;
13161 	uint32_t	sum;
13162 	uint32_t	u1;
13163 	ssize_t		len;
13164 	sctp_hdr_t	*sctph;
13165 	zoneid_t	zoneid = ire->ire_zoneid;
13166 	uint32_t	pktsum;
13167 	uint32_t	calcsum;
13168 	uint32_t	ports;
13169 	uint_t		ipif_seqid;
13170 	in6_addr_t	map_src, map_dst;
13171 	ill_t		*ill = (ill_t *)q->q_ptr;
13172 
13173 #define	rptr	((uchar_t *)ipha)
13174 
13175 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13176 
13177 	/* u1 is # words of IP options */
13178 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13179 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13180 
13181 	/* IP options present */
13182 	if (u1 > 0) {
13183 		goto ipoptions;
13184 	} else {
13185 		/* Check the IP header checksum.  */
13186 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13187 #define	uph	((uint16_t *)ipha)
13188 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13189 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13190 #undef	uph
13191 			/* finish doing IP checksum */
13192 			sum = (sum & 0xFFFF) + (sum >> 16);
13193 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13194 			/*
13195 			 * Don't verify header checksum if this packet
13196 			 * is coming back from AH/ESP as we already did it.
13197 			 */
13198 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13199 				BUMP_MIB(&ip_mib, ipInCksumErrs);
13200 				goto error;
13201 			}
13202 		}
13203 		/*
13204 		 * Since there is no SCTP h/w cksum support yet, just
13205 		 * clear the flag.
13206 		 */
13207 		DB_CKSUMFLAGS(mp) = 0;
13208 	}
13209 
13210 	/*
13211 	 * Don't verify header checksum if this packet is coming
13212 	 * back from AH/ESP as we already did it.
13213 	 */
13214 	if (!mctl_present) {
13215 		UPDATE_IB_PKT_COUNT(ire);
13216 		ire->ire_last_used_time = lbolt;
13217 	}
13218 
13219 	/* packet part of fragmented IP packet? */
13220 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13221 	if (u1 & (IPH_MF | IPH_OFFSET))
13222 		goto fragmented;
13223 
13224 	/* u1 = IP header length (20 bytes) */
13225 	u1 = IP_SIMPLE_HDR_LENGTH;
13226 
13227 find_sctp_client:
13228 	/* Pullup if we don't have the sctp common header. */
13229 	len = MBLKL(mp);
13230 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13231 		if (mp->b_cont == NULL ||
13232 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13233 			BUMP_MIB(&ip_mib, ipInDiscards);
13234 			goto error;
13235 		}
13236 		ipha = (ipha_t *)mp->b_rptr;
13237 		len = MBLKL(mp);
13238 	}
13239 
13240 	sctph = (sctp_hdr_t *)(rptr + u1);
13241 #ifdef	DEBUG
13242 	if (!skip_sctp_cksum) {
13243 #endif
13244 		pktsum = sctph->sh_chksum;
13245 		sctph->sh_chksum = 0;
13246 		calcsum = sctp_cksum(mp, u1);
13247 		if (calcsum != pktsum) {
13248 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13249 			goto error;
13250 		}
13251 		sctph->sh_chksum = pktsum;
13252 #ifdef	DEBUG	/* skip_sctp_cksum */
13253 	}
13254 #endif
13255 	/* get the ports */
13256 	ports = *(uint32_t *)&sctph->sh_sport;
13257 
13258 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13259 	IRE_REFRELE(ire);
13260 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13261 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13262 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13263 	    mp)) == NULL) {
13264 		/* Check for raw socket or OOTB handling */
13265 		goto no_conn;
13266 	}
13267 
13268 	/* Found a client; up it goes */
13269 	BUMP_MIB(&ip_mib, ipInDelivers);
13270 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13271 	return;
13272 
13273 no_conn:
13274 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13275 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13276 	return;
13277 
13278 ipoptions:
13279 	DB_CKSUMFLAGS(mp) = 0;
13280 	if (!ip_options_cksum(q, first_mp, ipha, ire))
13281 		goto slow_done;
13282 
13283 	UPDATE_IB_PKT_COUNT(ire);
13284 	ire->ire_last_used_time = lbolt;
13285 
13286 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13287 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13288 fragmented:
13289 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13290 			goto slow_done;
13291 		/*
13292 		 * Make sure that first_mp points back to mp as
13293 		 * the mp we came in with could have changed in
13294 		 * ip_rput_fragment().
13295 		 */
13296 		ASSERT(!mctl_present);
13297 		ipha = (ipha_t *)mp->b_rptr;
13298 		first_mp = mp;
13299 	}
13300 
13301 	/* Now we have a complete datagram, destined for this machine. */
13302 	u1 = IPH_HDR_LENGTH(ipha);
13303 	goto find_sctp_client;
13304 #undef  iphs
13305 #undef  rptr
13306 
13307 error:
13308 	freemsg(first_mp);
13309 slow_done:
13310 	IRE_REFRELE(ire);
13311 }
13312 
13313 #define	VER_BITS	0xF0
13314 #define	VERSION_6	0x60
13315 
13316 static boolean_t
13317 ip_rput_multimblk_ipoptions(queue_t *q, mblk_t *mp, ipha_t **iphapp,
13318     ipaddr_t *dstp)
13319 {
13320 	uint_t	opt_len;
13321 	ipha_t *ipha;
13322 	ssize_t len;
13323 	uint_t	pkt_len;
13324 
13325 	IP_STAT(ip_ipoptions);
13326 	ipha = *iphapp;
13327 
13328 #define	rptr    ((uchar_t *)ipha)
13329 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13330 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13331 		BUMP_MIB(&ip_mib, ipInIPv6);
13332 		freemsg(mp);
13333 		return (B_FALSE);
13334 	}
13335 
13336 	/* multiple mblk or too short */
13337 	pkt_len = ntohs(ipha->ipha_length);
13338 
13339 	/* Get the number of words of IP options in the IP header. */
13340 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13341 	if (opt_len) {
13342 		/* IP Options present!  Validate and process. */
13343 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13344 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13345 			goto done;
13346 		}
13347 		/*
13348 		 * Recompute complete header length and make sure we
13349 		 * have access to all of it.
13350 		 */
13351 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13352 		if (len > (mp->b_wptr - rptr)) {
13353 			if (len > pkt_len) {
13354 				BUMP_MIB(&ip_mib, ipInHdrErrors);
13355 				goto done;
13356 			}
13357 			if (!pullupmsg(mp, len)) {
13358 				BUMP_MIB(&ip_mib, ipInDiscards);
13359 				goto done;
13360 			}
13361 			ipha = (ipha_t *)mp->b_rptr;
13362 		}
13363 		/*
13364 		 * Go off to ip_rput_options which returns the next hop
13365 		 * destination address, which may have been affected
13366 		 * by source routing.
13367 		 */
13368 		IP_STAT(ip_opt);
13369 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13370 			return (B_FALSE);
13371 		}
13372 	}
13373 	*iphapp = ipha;
13374 	return (B_TRUE);
13375 done:
13376 	/* clear b_prev - used by ip_mroute_decap */
13377 	mp->b_prev = NULL;
13378 	freemsg(mp);
13379 	return (B_FALSE);
13380 #undef  rptr
13381 }
13382 
13383 /*
13384  * Deal with the fact that there is no ire for the destination.
13385  * The incoming ill (in_ill) is passed in to ip_newroute only
13386  * in the case of packets coming from mobile ip forward tunnel.
13387  * It must be null otherwise.
13388  */
13389 static ire_t *
13390 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13391     ipaddr_t dst)
13392 {
13393 	ipha_t	*ipha;
13394 	ill_t	*ill;
13395 	ire_t	*ire;
13396 	boolean_t	check_multirt = B_FALSE;
13397 
13398 	ipha = (ipha_t *)mp->b_rptr;
13399 	ill = (ill_t *)q->q_ptr;
13400 
13401 	ASSERT(ill != NULL);
13402 	/*
13403 	 * No IRE for this destination, so it can't be for us.
13404 	 * Unless we are forwarding, drop the packet.
13405 	 * We have to let source routed packets through
13406 	 * since we don't yet know if they are 'ping -l'
13407 	 * packets i.e. if they will go out over the
13408 	 * same interface as they came in on.
13409 	 */
13410 	if (ll_multicast) {
13411 		freemsg(mp);
13412 		return (NULL);
13413 	}
13414 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13415 		BUMP_MIB(&ip_mib, ipForwProhibits);
13416 		freemsg(mp);
13417 		return (NULL);
13418 	}
13419 
13420 	/*
13421 	 * Mark this packet as having originated externally.
13422 	 *
13423 	 * For non-forwarding code path, ire_send later double
13424 	 * checks this interface to see if it is still exists
13425 	 * post-ARP resolution.
13426 	 *
13427 	 * Also, IPQOS uses this to differentiate between
13428 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13429 	 * QOS packet processing in ip_wput_attach_llhdr().
13430 	 * The QoS module can mark the b_band for a fastpath message
13431 	 * or the dl_priority field in a unitdata_req header for
13432 	 * CoS marking. This info can only be found in
13433 	 * ip_wput_attach_llhdr().
13434 	 */
13435 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13436 	/*
13437 	 * Clear the indication that this may have a hardware checksum
13438 	 * as we are not using it
13439 	 */
13440 	DB_CKSUMFLAGS(mp) = 0;
13441 
13442 	if (in_ill != NULL) {
13443 		/*
13444 		 * Now hand the packet to ip_newroute.
13445 		 */
13446 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13447 		return (NULL);
13448 	}
13449 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13450 	    MBLK_GETLABEL(mp));
13451 
13452 	if (ire == NULL && check_multirt) {
13453 		/* Let ip_newroute handle CGTP  */
13454 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13455 		return (NULL);
13456 	}
13457 
13458 	if (ire != NULL)
13459 		return (ire);
13460 
13461 	mp->b_prev = mp->b_next = 0;
13462 	/* send icmp unreachable */
13463 	q = WR(q);
13464 	/* Sent by forwarding path, and router is global zone */
13465 	if (ip_source_routed(ipha)) {
13466 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13467 		    GLOBAL_ZONEID);
13468 	} else {
13469 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13470 	}
13471 
13472 	return (NULL);
13473 
13474 }
13475 
13476 /*
13477  * check ip header length and align it.
13478  */
13479 static boolean_t
13480 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13481 {
13482 	ssize_t len;
13483 	ill_t *ill;
13484 	ipha_t	*ipha;
13485 
13486 	len = MBLKL(mp);
13487 
13488 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13489 		if (!OK_32PTR(mp->b_rptr))
13490 			IP_STAT(ip_notaligned1);
13491 		else
13492 			IP_STAT(ip_notaligned2);
13493 		/* Guard against bogus device drivers */
13494 		if (len < 0) {
13495 			/* clear b_prev - used by ip_mroute_decap */
13496 			mp->b_prev = NULL;
13497 			BUMP_MIB(&ip_mib, ipInHdrErrors);
13498 			freemsg(mp);
13499 			return (B_FALSE);
13500 		}
13501 
13502 		if (ip_rput_pullups++ == 0) {
13503 			ill = (ill_t *)q->q_ptr;
13504 			ipha = (ipha_t *)mp->b_rptr;
13505 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13506 			    "ip_check_and_align_header: %s forced us to "
13507 			    " pullup pkt, hdr len %ld, hdr addr %p",
13508 			    ill->ill_name, len, ipha);
13509 		}
13510 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13511 			/* clear b_prev - used by ip_mroute_decap */
13512 			mp->b_prev = NULL;
13513 			BUMP_MIB(&ip_mib, ipInDiscards);
13514 			freemsg(mp);
13515 			return (B_FALSE);
13516 		}
13517 	}
13518 	return (B_TRUE);
13519 }
13520 
13521 static boolean_t
13522 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13523 {
13524 	ill_group_t	*ill_group;
13525 	ill_group_t	*ire_group;
13526 	queue_t 	*q;
13527 	ill_t		*ire_ill;
13528 	uint_t		ill_ifindex;
13529 
13530 	q = *qp;
13531 	/*
13532 	 * We need to check to make sure the packet came in
13533 	 * on the queue associated with the destination IRE.
13534 	 * Note that for multicast packets and broadcast packets sent to
13535 	 * a broadcast address which is shared between multiple interfaces
13536 	 * we should not do this since we just got a random broadcast ire.
13537 	 */
13538 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13539 		boolean_t check_multi = B_TRUE;
13540 
13541 		/*
13542 		 * This packet came in on an interface other than the
13543 		 * one associated with the destination address.
13544 		 * "Gateway" it to the appropriate interface here.
13545 		 * As long as the ills belong to the same group,
13546 		 * we don't consider them to arriving on the wrong
13547 		 * interface. Thus, when the switch is doing inbound
13548 		 * load spreading, we won't drop packets when we
13549 		 * are doing strict multihoming checks. Note, the
13550 		 * same holds true for 'usesrc groups' where the
13551 		 * destination address may belong to another interface
13552 		 * to allow multipathing to happen
13553 		 */
13554 		ill_group = ill->ill_group;
13555 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13556 		ill_ifindex = ill->ill_usesrc_ifindex;
13557 		ire_group = ire_ill->ill_group;
13558 
13559 		/*
13560 		 * If it's part of the same IPMP group, or if it's a legal
13561 		 * address on the 'usesrc' interface, then bypass strict
13562 		 * checks.
13563 		 */
13564 		if (ill_group != NULL && ill_group == ire_group) {
13565 			check_multi = B_FALSE;
13566 		} else if (ill_ifindex != 0 &&
13567 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13568 			check_multi = B_FALSE;
13569 		}
13570 
13571 		if (check_multi &&
13572 		    ip_strict_dst_multihoming &&
13573 		    ((ill->ill_flags &
13574 		    ire->ire_ipif->ipif_ill->ill_flags &
13575 		    ILLF_ROUTER) == 0)) {
13576 			/* Drop packet */
13577 			BUMP_MIB(&ip_mib, ipForwProhibits);
13578 			freemsg(mp);
13579 			return (B_TRUE);
13580 		}
13581 
13582 		/*
13583 		 * Change the queue (for non-virtual destination network
13584 		 * interfaces) and ip_rput_local will be called with the right
13585 		 * queue
13586 		 */
13587 		q = ire->ire_rfq;
13588 	}
13589 	/* Must be broadcast.  We'll take it. */
13590 	*qp = q;
13591 	return (B_FALSE);
13592 }
13593 
13594 ire_t *
13595 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13596 {
13597 	ipha_t	*ipha;
13598 	ipaddr_t ip_dst, ip_src;
13599 	ire_t	*src_ire = NULL;
13600 	ill_t	*stq_ill;
13601 	uint_t	hlen;
13602 	uint32_t sum;
13603 	queue_t	*dev_q;
13604 	boolean_t check_multirt = B_FALSE;
13605 
13606 
13607 	ipha = (ipha_t *)mp->b_rptr;
13608 
13609 	/*
13610 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13611 	 * The loopback address check for both src and dst has already
13612 	 * been checked in ip_input
13613 	 */
13614 	ip_dst = ntohl(dst);
13615 	ip_src = ntohl(ipha->ipha_src);
13616 
13617 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13618 	    IN_CLASSD(ip_src)) {
13619 		BUMP_MIB(&ip_mib, ipForwProhibits);
13620 		goto drop;
13621 	}
13622 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13623 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13624 
13625 	if (src_ire != NULL) {
13626 		BUMP_MIB(&ip_mib, ipForwProhibits);
13627 		goto drop;
13628 	}
13629 
13630 	/* No ire cache of nexthop. So first create one  */
13631 	if (ire == NULL) {
13632 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13633 		/*
13634 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13635 		 * is not set. So upon return from ire_forward
13636 		 * check_multirt should remain as false.
13637 		 */
13638 		ASSERT(!check_multirt);
13639 		if (ire == NULL) {
13640 			BUMP_MIB(&ip_mib, ipInDiscards);
13641 			mp->b_prev = mp->b_next = 0;
13642 			/* send icmp unreachable */
13643 			/* Sent by forwarding path, and router is global zone */
13644 			if (ip_source_routed(ipha)) {
13645 				icmp_unreachable(ill->ill_wq, mp,
13646 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13647 			} else {
13648 				icmp_unreachable(ill->ill_wq, mp,
13649 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13650 			}
13651 			return (ire);
13652 		}
13653 	}
13654 
13655 	/*
13656 	 * Forwarding fastpath exception case:
13657 	 * If either of the follwoing case is true, we take
13658 	 * the slowpath
13659 	 *	o forwarding is not enabled
13660 	 *	o incoming and outgoing interface are the same, or the same
13661 	 *	  IPMP group
13662 	 *	o corresponding ire is in incomplete state
13663 	 *	o packet needs fragmentation
13664 	 *
13665 	 * The codeflow from here on is thus:
13666 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13667 	 */
13668 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13669 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13670 	    !(ill->ill_flags & ILLF_ROUTER) ||
13671 	    (ill == stq_ill) ||
13672 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13673 	    (ire->ire_nce == NULL) ||
13674 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13675 	    (ntohs(ipha->ipha_length) > ire->ire_max_frag) ||
13676 	    ipha->ipha_ttl <= 1) {
13677 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13678 		    ipha, ill, B_FALSE);
13679 		return (ire);
13680 	}
13681 
13682 	DTRACE_PROBE4(ip4__forwarding__start,
13683 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13684 
13685 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13686 	    ill, stq_ill, ipha, mp, mp);
13687 
13688 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13689 
13690 	if (mp == NULL)
13691 		goto drop;
13692 
13693 	mp->b_datap->db_struioun.cksum.flags = 0;
13694 	/* Adjust the checksum to reflect the ttl decrement. */
13695 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13696 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13697 	ipha->ipha_ttl--;
13698 
13699 	dev_q = ire->ire_stq->q_next;
13700 	if ((dev_q->q_next != NULL ||
13701 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13702 		goto indiscard;
13703 	}
13704 
13705 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13706 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13707 
13708 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13709 		mblk_t *mpip = mp;
13710 
13711 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13712 		if (mp != NULL) {
13713 			DTRACE_PROBE4(ip4__physical__out__start,
13714 			    ill_t *, NULL, ill_t *, stq_ill,
13715 			    ipha_t *, ipha, mblk_t *, mp);
13716 			FW_HOOKS(ip4_physical_out_event,
13717 			    ipv4firewall_physical_out,
13718 			    NULL, stq_ill, ipha, mp, mpip);
13719 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13720 			    mp);
13721 			if (mp == NULL)
13722 				goto drop;
13723 
13724 			UPDATE_IB_PKT_COUNT(ire);
13725 			ire->ire_last_used_time = lbolt;
13726 			BUMP_MIB(&ip_mib, ipForwDatagrams);
13727 			putnext(ire->ire_stq, mp);
13728 			return (ire);
13729 		}
13730 	}
13731 
13732 indiscard:
13733 	BUMP_MIB(&ip_mib, ipInDiscards);
13734 drop:
13735 	if (mp != NULL)
13736 		freemsg(mp);
13737 	if (src_ire != NULL)
13738 		ire_refrele(src_ire);
13739 	return (ire);
13740 
13741 }
13742 
13743 /*
13744  * This function is called in the forwarding slowpath, when
13745  * either the ire lacks the link-layer address, or the packet needs
13746  * further processing(eg. fragmentation), before transmission.
13747  */
13748 
13749 static void
13750 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13751     ill_t *ill, boolean_t ll_multicast)
13752 {
13753 	ill_group_t	*ill_group;
13754 	ill_group_t	*ire_group;
13755 	queue_t		*dev_q;
13756 	ire_t		*src_ire;
13757 
13758 	ASSERT(ire->ire_stq != NULL);
13759 
13760 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13761 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13762 
13763 	if (ll_multicast != 0)
13764 		goto drop_pkt;
13765 
13766 	/*
13767 	 * check if ipha_src is a broadcast address. Note that this
13768 	 * check is redundant when we get here from ip_fast_forward()
13769 	 * which has already done this check. However, since we can
13770 	 * also get here from ip_rput_process_broadcast() or, for
13771 	 * for the slow path through ip_fast_forward(), we perform
13772 	 * the check again for code-reusability
13773 	 */
13774 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13775 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13776 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13777 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13778 		if (src_ire != NULL)
13779 			ire_refrele(src_ire);
13780 		BUMP_MIB(&ip_mib, ipForwProhibits);
13781 		ip2dbg(("ip_rput_process_forward: Received packet with"
13782 		    " bad src/dst address on %s\n", ill->ill_name));
13783 		goto drop_pkt;
13784 	}
13785 
13786 	ill_group = ill->ill_group;
13787 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13788 	/*
13789 	 * Check if we want to forward this one at this time.
13790 	 * We allow source routed packets on a host provided that
13791 	 * they go out the same interface or same interface group
13792 	 * as they came in on.
13793 	 *
13794 	 * XXX To be quicker, we may wish to not chase pointers to
13795 	 * get the ILLF_ROUTER flag and instead store the
13796 	 * forwarding policy in the ire.  An unfortunate
13797 	 * side-effect of that would be requiring an ire flush
13798 	 * whenever the ILLF_ROUTER flag changes.
13799 	 */
13800 	if (((ill->ill_flags &
13801 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13802 	    ILLF_ROUTER) == 0) &&
13803 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
13804 	    (ill_group != NULL && ill_group == ire_group)))) {
13805 		BUMP_MIB(&ip_mib, ipForwProhibits);
13806 		if (ip_source_routed(ipha)) {
13807 			q = WR(q);
13808 			/*
13809 			 * Clear the indication that this may have
13810 			 * hardware checksum as we are not using it.
13811 			 */
13812 			DB_CKSUMFLAGS(mp) = 0;
13813 			/* Sent by forwarding path, and router is global zone */
13814 			icmp_unreachable(q, mp,
13815 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13816 			return;
13817 		}
13818 		goto drop_pkt;
13819 	}
13820 
13821 	/* Packet is being forwarded. Turning off hwcksum flag. */
13822 	DB_CKSUMFLAGS(mp) = 0;
13823 	if (ip_g_send_redirects) {
13824 		/*
13825 		 * Check whether the incoming interface and outgoing
13826 		 * interface is part of the same group. If so,
13827 		 * send redirects.
13828 		 *
13829 		 * Check the source address to see if it originated
13830 		 * on the same logical subnet it is going back out on.
13831 		 * If so, we should be able to send it a redirect.
13832 		 * Avoid sending a redirect if the destination
13833 		 * is directly connected (i.e., ipha_dst is the same
13834 		 * as ire_gateway_addr or the ire_addr of the
13835 		 * nexthop IRE_CACHE ), or if the packet was source
13836 		 * routed out this interface.
13837 		 */
13838 		ipaddr_t src, nhop;
13839 		mblk_t	*mp1;
13840 		ire_t	*nhop_ire = NULL;
13841 
13842 		/*
13843 		 * Check whether ire_rfq and q are from the same ill
13844 		 * or if they are not same, they at least belong
13845 		 * to the same group. If so, send redirects.
13846 		 */
13847 		if ((ire->ire_rfq == q ||
13848 		    (ill_group != NULL && ill_group == ire_group)) &&
13849 		    !ip_source_routed(ipha)) {
13850 
13851 			nhop = (ire->ire_gateway_addr != 0 ?
13852 			    ire->ire_gateway_addr : ire->ire_addr);
13853 
13854 			if (ipha->ipha_dst == nhop) {
13855 				/*
13856 				 * We avoid sending a redirect if the
13857 				 * destination is directly connected
13858 				 * because it is possible that multiple
13859 				 * IP subnets may have been configured on
13860 				 * the link, and the source may not
13861 				 * be on the same subnet as ip destination,
13862 				 * even though they are on the same
13863 				 * physical link.
13864 				 */
13865 				goto sendit;
13866 			}
13867 
13868 			src = ipha->ipha_src;
13869 
13870 			/*
13871 			 * We look up the interface ire for the nexthop,
13872 			 * to see if ipha_src is in the same subnet
13873 			 * as the nexthop.
13874 			 *
13875 			 * Note that, if, in the future, IRE_CACHE entries
13876 			 * are obsoleted,  this lookup will not be needed,
13877 			 * as the ire passed to this function will be the
13878 			 * same as the nhop_ire computed below.
13879 			 */
13880 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
13881 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
13882 			    0, NULL, MATCH_IRE_TYPE);
13883 
13884 			if (nhop_ire != NULL) {
13885 				if ((src & nhop_ire->ire_mask) ==
13886 				    (nhop & nhop_ire->ire_mask)) {
13887 					/*
13888 					 * The source is directly connected.
13889 					 * Just copy the ip header (which is
13890 					 * in the first mblk)
13891 					 */
13892 					mp1 = copyb(mp);
13893 					if (mp1 != NULL) {
13894 						icmp_send_redirect(WR(q), mp1,
13895 						    nhop);
13896 					}
13897 				}
13898 				ire_refrele(nhop_ire);
13899 			}
13900 		}
13901 	}
13902 sendit:
13903 	dev_q = ire->ire_stq->q_next;
13904 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
13905 		BUMP_MIB(&ip_mib, ipInDiscards);
13906 		freemsg(mp);
13907 		return;
13908 	}
13909 
13910 	ip_rput_forward(ire, ipha, mp, ill);
13911 	return;
13912 
13913 drop_pkt:
13914 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
13915 	freemsg(mp);
13916 }
13917 
13918 ire_t *
13919 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13920     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
13921 {
13922 	queue_t		*q;
13923 	uint16_t	hcksumflags;
13924 
13925 	q = *qp;
13926 
13927 	/*
13928 	 * Clear the indication that this may have hardware
13929 	 * checksum as we are not using it for forwarding.
13930 	 */
13931 	hcksumflags = DB_CKSUMFLAGS(mp);
13932 	DB_CKSUMFLAGS(mp) = 0;
13933 
13934 	/*
13935 	 * Directed broadcast forwarding: if the packet came in over a
13936 	 * different interface then it is routed out over we can forward it.
13937 	 */
13938 	if (ipha->ipha_protocol == IPPROTO_TCP) {
13939 		ire_refrele(ire);
13940 		freemsg(mp);
13941 		BUMP_MIB(&ip_mib, ipInDiscards);
13942 		return (NULL);
13943 	}
13944 	/*
13945 	 * For multicast we have set dst to be INADDR_BROADCAST
13946 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
13947 	 * only for broadcast packets.
13948 	 */
13949 	if (!CLASSD(ipha->ipha_dst)) {
13950 		ire_t *new_ire;
13951 		ipif_t *ipif;
13952 		/*
13953 		 * For ill groups, as the switch duplicates broadcasts
13954 		 * across all the ports, we need to filter out and
13955 		 * send up only one copy. There is one copy for every
13956 		 * broadcast address on each ill. Thus, we look for a
13957 		 * specific IRE on this ill and look at IRE_MARK_NORECV
13958 		 * later to see whether this ill is eligible to receive
13959 		 * them or not. ill_nominate_bcast_rcv() nominates only
13960 		 * one set of IREs for receiving.
13961 		 */
13962 
13963 		ipif = ipif_get_next_ipif(NULL, ill);
13964 		if (ipif == NULL) {
13965 			ire_refrele(ire);
13966 			freemsg(mp);
13967 			BUMP_MIB(&ip_mib, ipInDiscards);
13968 			return (NULL);
13969 		}
13970 		new_ire = ire_ctable_lookup(dst, 0, 0,
13971 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
13972 		ipif_refrele(ipif);
13973 
13974 		if (new_ire != NULL) {
13975 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
13976 				ire_refrele(ire);
13977 				ire_refrele(new_ire);
13978 				freemsg(mp);
13979 				BUMP_MIB(&ip_mib, ipInDiscards);
13980 				return (NULL);
13981 			}
13982 			/*
13983 			 * In the special case of multirouted broadcast
13984 			 * packets, we unconditionally need to "gateway"
13985 			 * them to the appropriate interface here.
13986 			 * In the normal case, this cannot happen, because
13987 			 * there is no broadcast IRE tagged with the
13988 			 * RTF_MULTIRT flag.
13989 			 */
13990 			if (new_ire->ire_flags & RTF_MULTIRT) {
13991 				ire_refrele(new_ire);
13992 				if (ire->ire_rfq != NULL) {
13993 					q = ire->ire_rfq;
13994 					*qp = q;
13995 				}
13996 			} else {
13997 				ire_refrele(ire);
13998 				ire = new_ire;
13999 			}
14000 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14001 			if (!ip_g_forward_directed_bcast) {
14002 				/*
14003 				 * Free the message if
14004 				 * ip_g_forward_directed_bcast is turned
14005 				 * off for non-local broadcast.
14006 				 */
14007 				ire_refrele(ire);
14008 				freemsg(mp);
14009 				BUMP_MIB(&ip_mib, ipInDiscards);
14010 				return (NULL);
14011 			}
14012 		} else {
14013 			/*
14014 			 * This CGTP packet successfully passed the
14015 			 * CGTP filter, but the related CGTP
14016 			 * broadcast IRE has not been found,
14017 			 * meaning that the redundant ipif is
14018 			 * probably down. However, if we discarded
14019 			 * this packet, its duplicate would be
14020 			 * filtered out by the CGTP filter so none
14021 			 * of them would get through. So we keep
14022 			 * going with this one.
14023 			 */
14024 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14025 			if (ire->ire_rfq != NULL) {
14026 				q = ire->ire_rfq;
14027 				*qp = q;
14028 			}
14029 		}
14030 	}
14031 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14032 		/*
14033 		 * Verify that there are not more then one
14034 		 * IRE_BROADCAST with this broadcast address which
14035 		 * has ire_stq set.
14036 		 * TODO: simplify, loop over all IRE's
14037 		 */
14038 		ire_t	*ire1;
14039 		int	num_stq = 0;
14040 		mblk_t	*mp1;
14041 
14042 		/* Find the first one with ire_stq set */
14043 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14044 		for (ire1 = ire; ire1 &&
14045 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14046 		    ire1 = ire1->ire_next)
14047 			;
14048 		if (ire1) {
14049 			ire_refrele(ire);
14050 			ire = ire1;
14051 			IRE_REFHOLD(ire);
14052 		}
14053 
14054 		/* Check if there are additional ones with stq set */
14055 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14056 			if (ire->ire_addr != ire1->ire_addr)
14057 				break;
14058 			if (ire1->ire_stq) {
14059 				num_stq++;
14060 				break;
14061 			}
14062 		}
14063 		rw_exit(&ire->ire_bucket->irb_lock);
14064 		if (num_stq == 1 && ire->ire_stq != NULL) {
14065 			ip1dbg(("ip_rput_process_broadcast: directed "
14066 			    "broadcast to 0x%x\n",
14067 			    ntohl(ire->ire_addr)));
14068 			mp1 = copymsg(mp);
14069 			if (mp1) {
14070 				switch (ipha->ipha_protocol) {
14071 				case IPPROTO_UDP:
14072 					ip_udp_input(q, mp1, ipha, ire, ill);
14073 					break;
14074 				default:
14075 					ip_proto_input(q, mp1, ipha, ire, ill);
14076 					break;
14077 				}
14078 			}
14079 			/*
14080 			 * Adjust ttl to 2 (1+1 - the forward engine
14081 			 * will decrement it by one.
14082 			 */
14083 			if (ip_csum_hdr(ipha)) {
14084 				BUMP_MIB(&ip_mib, ipInCksumErrs);
14085 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14086 				freemsg(mp);
14087 				ire_refrele(ire);
14088 				return (NULL);
14089 			}
14090 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14091 			ipha->ipha_hdr_checksum = 0;
14092 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14093 			ip_rput_process_forward(q, mp, ire, ipha,
14094 			    ill, ll_multicast);
14095 			ire_refrele(ire);
14096 			return (NULL);
14097 		}
14098 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14099 		    ntohl(ire->ire_addr)));
14100 	}
14101 
14102 
14103 	/* Restore any hardware checksum flags */
14104 	DB_CKSUMFLAGS(mp) = hcksumflags;
14105 	return (ire);
14106 }
14107 
14108 /* ARGSUSED */
14109 static boolean_t
14110 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14111     int *ll_multicast, ipaddr_t *dstp)
14112 {
14113 	/*
14114 	 * Forward packets only if we have joined the allmulti
14115 	 * group on this interface.
14116 	 */
14117 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14118 		int retval;
14119 
14120 		/*
14121 		 * Clear the indication that this may have hardware
14122 		 * checksum as we are not using it.
14123 		 */
14124 		DB_CKSUMFLAGS(mp) = 0;
14125 		retval = ip_mforward(ill, ipha, mp);
14126 		/* ip_mforward updates mib variables if needed */
14127 		/* clear b_prev - used by ip_mroute_decap */
14128 		mp->b_prev = NULL;
14129 
14130 		switch (retval) {
14131 		case 0:
14132 			/*
14133 			 * pkt is okay and arrived on phyint.
14134 			 *
14135 			 * If we are running as a multicast router
14136 			 * we need to see all IGMP and/or PIM packets.
14137 			 */
14138 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14139 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14140 				goto done;
14141 			}
14142 			break;
14143 		case -1:
14144 			/* pkt is mal-formed, toss it */
14145 			goto drop_pkt;
14146 		case 1:
14147 			/* pkt is okay and arrived on a tunnel */
14148 			/*
14149 			 * If we are running a multicast router
14150 			 *  we need to see all igmp packets.
14151 			 */
14152 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14153 				*dstp = INADDR_BROADCAST;
14154 				*ll_multicast = 1;
14155 				return (B_FALSE);
14156 			}
14157 
14158 			goto drop_pkt;
14159 		}
14160 	}
14161 
14162 	ILM_WALKER_HOLD(ill);
14163 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14164 		/*
14165 		 * This might just be caused by the fact that
14166 		 * multiple IP Multicast addresses map to the same
14167 		 * link layer multicast - no need to increment counter!
14168 		 */
14169 		ILM_WALKER_RELE(ill);
14170 		freemsg(mp);
14171 		return (B_TRUE);
14172 	}
14173 	ILM_WALKER_RELE(ill);
14174 done:
14175 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14176 	/*
14177 	 * This assumes the we deliver to all streams for multicast
14178 	 * and broadcast packets.
14179 	 */
14180 	*dstp = INADDR_BROADCAST;
14181 	*ll_multicast = 1;
14182 	return (B_FALSE);
14183 drop_pkt:
14184 	ip2dbg(("ip_rput: drop pkt\n"));
14185 	freemsg(mp);
14186 	return (B_TRUE);
14187 }
14188 
14189 static boolean_t
14190 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14191     int *ll_multicast, mblk_t **mpp)
14192 {
14193 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14194 	boolean_t must_copy = B_FALSE;
14195 	struct iocblk   *iocp;
14196 	ipha_t		*ipha;
14197 
14198 #define	rptr    ((uchar_t *)ipha)
14199 
14200 	first_mp = *first_mpp;
14201 	mp = *mpp;
14202 
14203 	ASSERT(first_mp == mp);
14204 
14205 	/*
14206 	 * if db_ref > 1 then copymsg and free original. Packet may be
14207 	 * changed and do not want other entity who has a reference to this
14208 	 * message to trip over the changes. This is a blind change because
14209 	 * trying to catch all places that might change packet is too
14210 	 * difficult (since it may be a module above this one)
14211 	 *
14212 	 * This corresponds to the non-fast path case. We walk down the full
14213 	 * chain in this case, and check the db_ref count of all the dblks,
14214 	 * and do a copymsg if required. It is possible that the db_ref counts
14215 	 * of the data blocks in the mblk chain can be different.
14216 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14217 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14218 	 * 'snoop' is running.
14219 	 */
14220 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14221 		if (mp1->b_datap->db_ref > 1) {
14222 			must_copy = B_TRUE;
14223 			break;
14224 		}
14225 	}
14226 
14227 	if (must_copy) {
14228 		mp1 = copymsg(mp);
14229 		if (mp1 == NULL) {
14230 			for (mp1 = mp; mp1 != NULL;
14231 			    mp1 = mp1->b_cont) {
14232 				mp1->b_next = NULL;
14233 				mp1->b_prev = NULL;
14234 			}
14235 			freemsg(mp);
14236 			BUMP_MIB(&ip_mib, ipInDiscards);
14237 			return (B_TRUE);
14238 		}
14239 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14240 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14241 			/* Copy b_prev - used by ip_mroute_decap */
14242 			to_mp->b_prev = from_mp->b_prev;
14243 			from_mp->b_prev = NULL;
14244 		}
14245 		*first_mpp = first_mp = mp1;
14246 		freemsg(mp);
14247 		mp = mp1;
14248 		*mpp = mp1;
14249 	}
14250 
14251 	ipha = (ipha_t *)mp->b_rptr;
14252 
14253 	/*
14254 	 * previous code has a case for M_DATA.
14255 	 * We want to check how that happens.
14256 	 */
14257 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14258 	switch (first_mp->b_datap->db_type) {
14259 	case M_PROTO:
14260 	case M_PCPROTO:
14261 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14262 		    DL_UNITDATA_IND) {
14263 			/* Go handle anything other than data elsewhere. */
14264 			ip_rput_dlpi(q, mp);
14265 			return (B_TRUE);
14266 		}
14267 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14268 		/* Ditch the DLPI header. */
14269 		mp1 = mp->b_cont;
14270 		ASSERT(first_mp == mp);
14271 		*first_mpp = mp1;
14272 		freeb(mp);
14273 		*mpp = mp1;
14274 		return (B_FALSE);
14275 	case M_IOCACK:
14276 		ip1dbg(("got iocack "));
14277 		iocp = (struct iocblk *)mp->b_rptr;
14278 		switch (iocp->ioc_cmd) {
14279 		case DL_IOC_HDR_INFO:
14280 			ill = (ill_t *)q->q_ptr;
14281 			ill_fastpath_ack(ill, mp);
14282 			return (B_TRUE);
14283 		case SIOCSTUNPARAM:
14284 		case OSIOCSTUNPARAM:
14285 			/* Go through qwriter_ip */
14286 			break;
14287 		case SIOCGTUNPARAM:
14288 		case OSIOCGTUNPARAM:
14289 			ip_rput_other(NULL, q, mp, NULL);
14290 			return (B_TRUE);
14291 		default:
14292 			putnext(q, mp);
14293 			return (B_TRUE);
14294 		}
14295 		/* FALLTHRU */
14296 	case M_ERROR:
14297 	case M_HANGUP:
14298 		/*
14299 		 * Since this is on the ill stream we unconditionally
14300 		 * bump up the refcount
14301 		 */
14302 		ill_refhold(ill);
14303 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14304 		    B_FALSE);
14305 		return (B_TRUE);
14306 	case M_CTL:
14307 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14308 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14309 			IPHADA_M_CTL)) {
14310 			/*
14311 			 * It's an IPsec accelerated packet.
14312 			 * Make sure that the ill from which we received the
14313 			 * packet has enabled IPsec hardware acceleration.
14314 			 */
14315 			if (!(ill->ill_capabilities &
14316 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14317 				/* IPsec kstats: bean counter */
14318 				freemsg(mp);
14319 				return (B_TRUE);
14320 			}
14321 
14322 			/*
14323 			 * Make mp point to the mblk following the M_CTL,
14324 			 * then process according to type of mp.
14325 			 * After this processing, first_mp will point to
14326 			 * the data-attributes and mp to the pkt following
14327 			 * the M_CTL.
14328 			 */
14329 			mp = first_mp->b_cont;
14330 			if (mp == NULL) {
14331 				freemsg(first_mp);
14332 				return (B_TRUE);
14333 			}
14334 			/*
14335 			 * A Hardware Accelerated packet can only be M_DATA
14336 			 * ESP or AH packet.
14337 			 */
14338 			if (mp->b_datap->db_type != M_DATA) {
14339 				/* non-M_DATA IPsec accelerated packet */
14340 				IPSECHW_DEBUG(IPSECHW_PKT,
14341 				    ("non-M_DATA IPsec accelerated pkt\n"));
14342 				freemsg(first_mp);
14343 				return (B_TRUE);
14344 			}
14345 			ipha = (ipha_t *)mp->b_rptr;
14346 			if (ipha->ipha_protocol != IPPROTO_AH &&
14347 			    ipha->ipha_protocol != IPPROTO_ESP) {
14348 				IPSECHW_DEBUG(IPSECHW_PKT,
14349 				    ("non-M_DATA IPsec accelerated pkt\n"));
14350 				freemsg(first_mp);
14351 				return (B_TRUE);
14352 			}
14353 			*mpp = mp;
14354 			return (B_FALSE);
14355 		}
14356 		putnext(q, mp);
14357 		return (B_TRUE);
14358 	case M_FLUSH:
14359 		if (*mp->b_rptr & FLUSHW) {
14360 			*mp->b_rptr &= ~FLUSHR;
14361 			qreply(q, mp);
14362 			return (B_TRUE);
14363 		}
14364 		freemsg(mp);
14365 		return (B_TRUE);
14366 	case M_IOCNAK:
14367 		ip1dbg(("got iocnak "));
14368 		iocp = (struct iocblk *)mp->b_rptr;
14369 		switch (iocp->ioc_cmd) {
14370 		case DL_IOC_HDR_INFO:
14371 		case SIOCSTUNPARAM:
14372 		case OSIOCSTUNPARAM:
14373 			/*
14374 			 * Since this is on the ill stream we unconditionally
14375 			 * bump up the refcount
14376 			 */
14377 			ill_refhold(ill);
14378 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14379 			    CUR_OP, B_FALSE);
14380 			return (B_TRUE);
14381 		case SIOCGTUNPARAM:
14382 		case OSIOCGTUNPARAM:
14383 			ip_rput_other(NULL, q, mp, NULL);
14384 			return (B_TRUE);
14385 		default:
14386 			break;
14387 		}
14388 		/* FALLTHRU */
14389 	default:
14390 		putnext(q, mp);
14391 		return (B_TRUE);
14392 	}
14393 }
14394 
14395 /* Read side put procedure.  Packets coming from the wire arrive here. */
14396 void
14397 ip_rput(queue_t *q, mblk_t *mp)
14398 {
14399 	ill_t	*ill;
14400 	mblk_t	 *dmp = NULL;
14401 
14402 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14403 
14404 	ill = (ill_t *)q->q_ptr;
14405 
14406 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14407 		union DL_primitives *dl;
14408 
14409 		/*
14410 		 * Things are opening or closing. Only accept DLPI control
14411 		 * messages. In the open case, the ill->ill_ipif has not yet
14412 		 * been created. In the close case, things hanging off the
14413 		 * ill could have been freed already. In either case it
14414 		 * may not be safe to proceed further.
14415 		 */
14416 
14417 		dl = (union DL_primitives *)mp->b_rptr;
14418 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14419 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14420 			/*
14421 			 * Also SIOC[GS]TUN* ioctls can come here.
14422 			 */
14423 			inet_freemsg(mp);
14424 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14425 			    "ip_input_end: q %p (%S)", q, "uninit");
14426 			return;
14427 		}
14428 	}
14429 
14430 	/*
14431 	 * if db_ref > 1 then copymsg and free original. Packet may be
14432 	 * changed and we do not want the other entity who has a reference to
14433 	 * this message to trip over the changes. This is a blind change because
14434 	 * trying to catch all places that might change the packet is too
14435 	 * difficult.
14436 	 *
14437 	 * This corresponds to the fast path case, where we have a chain of
14438 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14439 	 * in the mblk chain. There doesn't seem to be a reason why a device
14440 	 * driver would send up data with varying db_ref counts in the mblk
14441 	 * chain. In any case the Fast path is a private interface, and our
14442 	 * drivers don't do such a thing. Given the above assumption, there is
14443 	 * no need to walk down the entire mblk chain (which could have a
14444 	 * potential performance problem)
14445 	 */
14446 	if (mp->b_datap->db_ref > 1) {
14447 		mblk_t  *mp1;
14448 		boolean_t adjusted = B_FALSE;
14449 		IP_STAT(ip_db_ref);
14450 
14451 		/*
14452 		 * The IP_RECVSLLA option depends on having the link layer
14453 		 * header. First check that:
14454 		 * a> the underlying device is of type ether, since this
14455 		 * option is currently supported only over ethernet.
14456 		 * b> there is enough room to copy over the link layer header.
14457 		 *
14458 		 * Once the checks are done, adjust rptr so that the link layer
14459 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14460 		 * be returned by some non-ethernet drivers but in this case the
14461 		 * second check will fail.
14462 		 */
14463 		if (ill->ill_type == IFT_ETHER &&
14464 		    (mp->b_rptr - mp->b_datap->db_base) >=
14465 		    sizeof (struct ether_header)) {
14466 			mp->b_rptr -= sizeof (struct ether_header);
14467 			adjusted = B_TRUE;
14468 		}
14469 		mp1 = copymsg(mp);
14470 		if (mp1 == NULL) {
14471 			mp->b_next = NULL;
14472 			/* clear b_prev - used by ip_mroute_decap */
14473 			mp->b_prev = NULL;
14474 			freemsg(mp);
14475 			BUMP_MIB(&ip_mib, ipInDiscards);
14476 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14477 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14478 			return;
14479 		}
14480 		if (adjusted) {
14481 			/*
14482 			 * Copy is done. Restore the pointer in the _new_ mblk
14483 			 */
14484 			mp1->b_rptr += sizeof (struct ether_header);
14485 		}
14486 		/* Copy b_prev - used by ip_mroute_decap */
14487 		mp1->b_prev = mp->b_prev;
14488 		mp->b_prev = NULL;
14489 		freemsg(mp);
14490 		mp = mp1;
14491 	}
14492 	if (DB_TYPE(mp) == M_DATA) {
14493 		dmp = mp;
14494 	} else if (DB_TYPE(mp) == M_PROTO &&
14495 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14496 		dmp = mp->b_cont;
14497 	}
14498 	if (dmp != NULL) {
14499 		/*
14500 		 * IP header ptr not aligned?
14501 		 * OR IP header not complete in first mblk
14502 		 */
14503 		if (!OK_32PTR(dmp->b_rptr) ||
14504 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14505 			if (!ip_check_and_align_header(q, dmp))
14506 				return;
14507 		}
14508 	}
14509 
14510 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14511 	    "ip_rput_end: q %p (%S)", q, "end");
14512 
14513 	ip_input(ill, NULL, mp, NULL);
14514 }
14515 
14516 /*
14517  * Direct read side procedure capable of dealing with chains. GLDv3 based
14518  * drivers call this function directly with mblk chains while STREAMS
14519  * read side procedure ip_rput() calls this for single packet with ip_ring
14520  * set to NULL to process one packet at a time.
14521  *
14522  * The ill will always be valid if this function is called directly from
14523  * the driver.
14524  *
14525  * If ip_input() is called from GLDv3:
14526  *
14527  *   - This must be a non-VLAN IP stream.
14528  *   - 'mp' is either an untagged or a special priority-tagged packet.
14529  *   - Any VLAN tag that was in the MAC header has been stripped.
14530  *
14531  * Thus, there is no need to adjust b_rptr in this function.
14532  */
14533 /* ARGSUSED */
14534 void
14535 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14536     struct mac_header_info_s *mhip)
14537 {
14538 	ipaddr_t		dst = NULL;
14539 	ipaddr_t		prev_dst;
14540 	ire_t			*ire = NULL;
14541 	ipha_t			*ipha;
14542 	uint_t			pkt_len;
14543 	ssize_t			len;
14544 	uint_t			opt_len;
14545 	int			ll_multicast;
14546 	int			cgtp_flt_pkt;
14547 	queue_t			*q = ill->ill_rq;
14548 	squeue_t		*curr_sqp = NULL;
14549 	mblk_t 			*head = NULL;
14550 	mblk_t			*tail = NULL;
14551 	mblk_t			*first_mp;
14552 	mblk_t 			*mp;
14553 	int			cnt = 0;
14554 
14555 	ASSERT(mp_chain != NULL);
14556 	ASSERT(ill != NULL);
14557 
14558 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14559 
14560 #define	rptr	((uchar_t *)ipha)
14561 
14562 	while (mp_chain != NULL) {
14563 		first_mp = mp = mp_chain;
14564 		mp_chain = mp_chain->b_next;
14565 		mp->b_next = NULL;
14566 		ll_multicast = 0;
14567 
14568 		/*
14569 		 * We do ire caching from one iteration to
14570 		 * another. In the event the packet chain contains
14571 		 * all packets from the same dst, this caching saves
14572 		 * an ire_cache_lookup for each of the succeeding
14573 		 * packets in a packet chain.
14574 		 */
14575 		prev_dst = dst;
14576 
14577 		/*
14578 		 * ip_input fast path
14579 		 */
14580 
14581 		/* mblk type is not M_DATA */
14582 		if (mp->b_datap->db_type != M_DATA) {
14583 			if (ip_rput_process_notdata(q, &first_mp, ill,
14584 			    &ll_multicast, &mp))
14585 				continue;
14586 		}
14587 
14588 		/* Make sure its an M_DATA and that its aligned */
14589 		ASSERT(mp->b_datap->db_type == M_DATA);
14590 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14591 
14592 		ipha = (ipha_t *)mp->b_rptr;
14593 		len = mp->b_wptr - rptr;
14594 
14595 		BUMP_MIB(&ip_mib, ipInReceives);
14596 
14597 
14598 		/* multiple mblk or too short */
14599 		pkt_len = ntohs(ipha->ipha_length);
14600 		len -= pkt_len;
14601 		if (len != 0) {
14602 			/*
14603 			 * Make sure we have data length consistent
14604 			 * with the IP header.
14605 			 */
14606 			if (mp->b_cont == NULL) {
14607 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14608 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14609 					ip2dbg(("ip_input: drop pkt\n"));
14610 					freemsg(mp);
14611 					continue;
14612 				}
14613 				mp->b_wptr = rptr + pkt_len;
14614 			} else if (len += msgdsize(mp->b_cont)) {
14615 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14616 					BUMP_MIB(&ip_mib, ipInHdrErrors);
14617 					ip2dbg(("ip_input: drop pkt\n"));
14618 					freemsg(mp);
14619 					continue;
14620 				}
14621 				(void) adjmsg(mp, -len);
14622 				IP_STAT(ip_multimblk3);
14623 			}
14624 		}
14625 
14626 		/* Obtain the dst of the current packet */
14627 		dst = ipha->ipha_dst;
14628 
14629 		if (IP_LOOPBACK_ADDR(dst) ||
14630 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14631 			BUMP_MIB(&ip_mib, ipInAddrErrors);
14632 			cmn_err(CE_CONT, "dst %X src %X\n",
14633 			    dst, ipha->ipha_src);
14634 			freemsg(mp);
14635 			continue;
14636 		}
14637 
14638 		/*
14639 		 * The event for packets being received from a 'physical'
14640 		 * interface is placed after validation of the source and/or
14641 		 * destination address as being local so that packets can be
14642 		 * redirected to loopback addresses using ipnat.
14643 		 */
14644 		DTRACE_PROBE4(ip4__physical__in__start,
14645 		    ill_t *, ill, ill_t *, NULL,
14646 		    ipha_t *, ipha, mblk_t *, first_mp);
14647 
14648 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14649 		    ill, NULL, ipha, first_mp, mp);
14650 
14651 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14652 
14653 		if (first_mp == NULL) {
14654 			continue;
14655 		}
14656 		dst = ipha->ipha_dst;
14657 
14658 		/*
14659 		 * Attach any necessary label information to
14660 		 * this packet
14661 		 */
14662 		if (is_system_labeled() &&
14663 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14664 			BUMP_MIB(&ip_mib, ipInDiscards);
14665 			freemsg(mp);
14666 			continue;
14667 		}
14668 
14669 		/*
14670 		 * Reuse the cached ire only if the ipha_dst of the previous
14671 		 * packet is the same as the current packet AND it is not
14672 		 * INADDR_ANY.
14673 		 */
14674 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14675 		    (ire != NULL)) {
14676 			ire_refrele(ire);
14677 			ire = NULL;
14678 		}
14679 		opt_len = ipha->ipha_version_and_hdr_length -
14680 		    IP_SIMPLE_HDR_VERSION;
14681 
14682 		/*
14683 		 * Check to see if we can take the fastpath.
14684 		 * That is possible if the following conditions are met
14685 		 *	o Tsol disabled
14686 		 *	o CGTP disabled
14687 		 *	o ipp_action_count is 0
14688 		 *	o Mobile IP not running
14689 		 *	o no options in the packet
14690 		 *	o not a RSVP packet
14691 		 * 	o not a multicast packet
14692 		 */
14693 		if (!is_system_labeled() &&
14694 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14695 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14696 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14697 		    !ll_multicast && !CLASSD(dst)) {
14698 			if (ire == NULL)
14699 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14700 
14701 			/* incoming packet is for forwarding */
14702 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14703 				ire = ip_fast_forward(ire, dst, ill, mp);
14704 				continue;
14705 			}
14706 			/* incoming packet is for local consumption */
14707 			if (ire->ire_type & IRE_LOCAL)
14708 				goto local;
14709 		}
14710 
14711 		/*
14712 		 * Disable ire caching for anything more complex
14713 		 * than the simple fast path case we checked for above.
14714 		 */
14715 		if (ire != NULL) {
14716 			ire_refrele(ire);
14717 			ire = NULL;
14718 		}
14719 
14720 		/* Full-blown slow path */
14721 		if (opt_len != 0) {
14722 			if (len != 0)
14723 				IP_STAT(ip_multimblk4);
14724 			else
14725 				IP_STAT(ip_ipoptions);
14726 			if (!ip_rput_multimblk_ipoptions(q, mp, &ipha, &dst))
14727 				continue;
14728 		}
14729 
14730 		/*
14731 		 * Invoke the CGTP (multirouting) filtering module to process
14732 		 * the incoming packet. Packets identified as duplicates
14733 		 * must be discarded. Filtering is active only if the
14734 		 * the ip_cgtp_filter ndd variable is non-zero.
14735 		 */
14736 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14737 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
14738 			cgtp_flt_pkt =
14739 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
14740 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14741 				freemsg(first_mp);
14742 				continue;
14743 			}
14744 		}
14745 
14746 		/*
14747 		 * If rsvpd is running, let RSVP daemon handle its processing
14748 		 * and forwarding of RSVP multicast/unicast packets.
14749 		 * If rsvpd is not running but mrouted is running, RSVP
14750 		 * multicast packets are forwarded as multicast traffic
14751 		 * and RSVP unicast packets are forwarded by unicast router.
14752 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14753 		 * packets are not forwarded, but the unicast packets are
14754 		 * forwarded like unicast traffic.
14755 		 */
14756 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14757 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
14758 			/* RSVP packet and rsvpd running. Treat as ours */
14759 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14760 			/*
14761 			 * This assumes that we deliver to all streams for
14762 			 * multicast and broadcast packets.
14763 			 * We have to force ll_multicast to 1 to handle the
14764 			 * M_DATA messages passed in from ip_mroute_decap.
14765 			 */
14766 			dst = INADDR_BROADCAST;
14767 			ll_multicast = 1;
14768 		} else if (CLASSD(dst)) {
14769 			/* packet is multicast */
14770 			mp->b_next = NULL;
14771 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14772 			    &ll_multicast, &dst))
14773 				continue;
14774 		}
14775 
14776 
14777 		/*
14778 		 * Check if the packet is coming from the Mobile IP
14779 		 * forward tunnel interface
14780 		 */
14781 		if (ill->ill_srcif_refcnt > 0) {
14782 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
14783 			    NULL, ill, MATCH_IRE_TYPE);
14784 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
14785 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
14786 
14787 				/* We need to resolve the link layer info */
14788 				ire_refrele(ire);
14789 				ire = NULL;
14790 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
14791 				    ll_multicast, dst);
14792 				continue;
14793 			}
14794 		}
14795 
14796 		if (ire == NULL) {
14797 			ire = ire_cache_lookup(dst, ALL_ZONES,
14798 			    MBLK_GETLABEL(mp));
14799 		}
14800 
14801 		/*
14802 		 * If mipagent is running and reverse tunnel is created as per
14803 		 * mobile node request, then any packet coming through the
14804 		 * incoming interface from the mobile-node, should be reverse
14805 		 * tunneled to it's home agent except those that are destined
14806 		 * to foreign agent only.
14807 		 * This needs source address based ire lookup. The routing
14808 		 * entries for source address based lookup are only created by
14809 		 * mipagent program only when a reverse tunnel is created.
14810 		 * Reference : RFC2002, RFC2344
14811 		 */
14812 		if (ill->ill_mrtun_refcnt > 0) {
14813 			ipaddr_t	srcaddr;
14814 			ire_t		*tmp_ire;
14815 
14816 			tmp_ire = ire;	/* Save, we might need it later */
14817 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
14818 			    ire->ire_type != IRE_BROADCAST)) {
14819 				srcaddr = ipha->ipha_src;
14820 				ire = ire_mrtun_lookup(srcaddr, ill);
14821 				if (ire != NULL) {
14822 					/*
14823 					 * Should not be getting iphada packet
14824 					 * here. we should only get those for
14825 					 * IRE_LOCAL traffic, excluded above.
14826 					 * Fail-safe (drop packet) in the event
14827 					 * hardware is misbehaving.
14828 					 */
14829 					if (first_mp != mp) {
14830 						/* IPsec KSTATS: beancount me */
14831 						freemsg(first_mp);
14832 					} else {
14833 						/*
14834 						 * This packet must be forwarded
14835 						 * to Reverse Tunnel
14836 						 */
14837 						ip_mrtun_forward(ire, ill, mp);
14838 					}
14839 					ire_refrele(ire);
14840 					ire = NULL;
14841 					if (tmp_ire != NULL) {
14842 						ire_refrele(tmp_ire);
14843 						tmp_ire = NULL;
14844 					}
14845 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14846 					    "ip_input_end: q %p (%S)",
14847 					    q, "uninit");
14848 					continue;
14849 				}
14850 			}
14851 			/*
14852 			 * If this packet is from a non-mobilenode  or a
14853 			 * mobile-node which does not request reverse
14854 			 * tunnel service
14855 			 */
14856 			ire = tmp_ire;
14857 		}
14858 
14859 
14860 		/*
14861 		 * If we reach here that means the incoming packet satisfies
14862 		 * one of the following conditions:
14863 		 *   - packet is from a mobile node which does not request
14864 		 *	reverse tunnel
14865 		 *   - packet is from a non-mobile node, which is the most
14866 		 *	common case
14867 		 *   - packet is from a reverse tunnel enabled mobile node
14868 		 *	and destined to foreign agent only
14869 		 */
14870 
14871 		if (ire == NULL) {
14872 			/*
14873 			 * No IRE for this destination, so it can't be for us.
14874 			 * Unless we are forwarding, drop the packet.
14875 			 * We have to let source routed packets through
14876 			 * since we don't yet know if they are 'ping -l'
14877 			 * packets i.e. if they will go out over the
14878 			 * same interface as they came in on.
14879 			 */
14880 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
14881 			if (ire == NULL)
14882 				continue;
14883 		}
14884 
14885 		/*
14886 		 * Broadcast IRE may indicate either broadcast or
14887 		 * multicast packet
14888 		 */
14889 		if (ire->ire_type == IRE_BROADCAST) {
14890 			/*
14891 			 * Skip broadcast checks if packet is UDP multicast;
14892 			 * we'd rather not enter ip_rput_process_broadcast()
14893 			 * unless the packet is broadcast for real, since
14894 			 * that routine is a no-op for multicast.
14895 			 */
14896 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14897 			    !CLASSD(ipha->ipha_dst)) {
14898 				ire = ip_rput_process_broadcast(&q, mp,
14899 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14900 				    ll_multicast);
14901 				if (ire == NULL)
14902 					continue;
14903 			}
14904 		} else if (ire->ire_stq != NULL) {
14905 			/* fowarding? */
14906 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14907 			    ll_multicast);
14908 			/* ip_rput_process_forward consumed the packet */
14909 			continue;
14910 		}
14911 
14912 local:
14913 		/* packet not for us */
14914 		if (ire->ire_rfq != q) {
14915 			if (ip_rput_notforus(&q, mp, ire, ill))
14916 				continue;
14917 		}
14918 
14919 		switch (ipha->ipha_protocol) {
14920 		case IPPROTO_TCP:
14921 			ASSERT(first_mp == mp);
14922 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
14923 				mp, 0, q, ip_ring)) != NULL) {
14924 				if (curr_sqp == NULL) {
14925 					curr_sqp = GET_SQUEUE(mp);
14926 					ASSERT(cnt == 0);
14927 					cnt++;
14928 					head = tail = mp;
14929 				} else if (curr_sqp == GET_SQUEUE(mp)) {
14930 					ASSERT(tail != NULL);
14931 					cnt++;
14932 					tail->b_next = mp;
14933 					tail = mp;
14934 				} else {
14935 					/*
14936 					 * A different squeue. Send the
14937 					 * chain for the previous squeue on
14938 					 * its way. This shouldn't happen
14939 					 * often unless interrupt binding
14940 					 * changes.
14941 					 */
14942 					IP_STAT(ip_input_multi_squeue);
14943 					squeue_enter_chain(curr_sqp, head,
14944 					    tail, cnt, SQTAG_IP_INPUT);
14945 					curr_sqp = GET_SQUEUE(mp);
14946 					head = mp;
14947 					tail = mp;
14948 					cnt = 1;
14949 				}
14950 			}
14951 			continue;
14952 		case IPPROTO_UDP:
14953 			ASSERT(first_mp == mp);
14954 			ip_udp_input(q, mp, ipha, ire, ill);
14955 			continue;
14956 		case IPPROTO_SCTP:
14957 			ASSERT(first_mp == mp);
14958 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
14959 			    q, dst);
14960 			/* ire has been released by ip_sctp_input */
14961 			ire = NULL;
14962 			continue;
14963 		default:
14964 			ip_proto_input(q, first_mp, ipha, ire, ill);
14965 			continue;
14966 		}
14967 	}
14968 
14969 	if (ire != NULL)
14970 		ire_refrele(ire);
14971 
14972 	if (head != NULL)
14973 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
14974 
14975 	/*
14976 	 * This code is there just to make netperf/ttcp look good.
14977 	 *
14978 	 * Its possible that after being in polling mode (and having cleared
14979 	 * the backlog), squeues have turned the interrupt frequency higher
14980 	 * to improve latency at the expense of more CPU utilization (less
14981 	 * packets per interrupts or more number of interrupts). Workloads
14982 	 * like ttcp/netperf do manage to tickle polling once in a while
14983 	 * but for the remaining time, stay in higher interrupt mode since
14984 	 * their packet arrival rate is pretty uniform and this shows up
14985 	 * as higher CPU utilization. Since people care about CPU utilization
14986 	 * while running netperf/ttcp, turn the interrupt frequency back to
14987 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
14988 	 */
14989 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
14990 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
14991 			ip_ring->rr_poll_state &= ~ILL_POLLING;
14992 			ip_ring->rr_blank(ip_ring->rr_handle,
14993 			    ip_ring->rr_normal_blank_time,
14994 			    ip_ring->rr_normal_pkt_cnt);
14995 		}
14996 	}
14997 
14998 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14999 	    "ip_input_end: q %p (%S)", q, "end");
15000 #undef	rptr
15001 }
15002 
15003 static void
15004 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15005     t_uscalar_t err)
15006 {
15007 	if (dl_err == DL_SYSERR) {
15008 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15009 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15010 		    ill->ill_name, dlpi_prim_str(prim), err);
15011 		return;
15012 	}
15013 
15014 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15015 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15016 	    dlpi_err_str(dl_err));
15017 }
15018 
15019 /*
15020  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15021  * than DL_UNITDATA_IND messages. If we need to process this message
15022  * exclusively, we call qwriter_ip, in which case we also need to call
15023  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15024  */
15025 void
15026 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15027 {
15028 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15029 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15030 	ill_t		*ill;
15031 
15032 	ip1dbg(("ip_rput_dlpi"));
15033 	ill = (ill_t *)q->q_ptr;
15034 	switch (dloa->dl_primitive) {
15035 	case DL_ERROR_ACK:
15036 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15037 		    "%s (0x%x), unix %u\n", ill->ill_name,
15038 		    dlpi_prim_str(dlea->dl_error_primitive),
15039 		    dlea->dl_error_primitive,
15040 		    dlpi_err_str(dlea->dl_errno),
15041 		    dlea->dl_errno,
15042 		    dlea->dl_unix_errno));
15043 		switch (dlea->dl_error_primitive) {
15044 		case DL_UNBIND_REQ:
15045 			mutex_enter(&ill->ill_lock);
15046 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15047 			cv_signal(&ill->ill_cv);
15048 			mutex_exit(&ill->ill_lock);
15049 			/* FALLTHRU */
15050 		case DL_NOTIFY_REQ:
15051 		case DL_ATTACH_REQ:
15052 		case DL_DETACH_REQ:
15053 		case DL_INFO_REQ:
15054 		case DL_BIND_REQ:
15055 		case DL_ENABMULTI_REQ:
15056 		case DL_PHYS_ADDR_REQ:
15057 		case DL_CAPABILITY_REQ:
15058 		case DL_CONTROL_REQ:
15059 			/*
15060 			 * Refhold the ill to match qwriter_ip which does a
15061 			 * refrele. Since this is on the ill stream we
15062 			 * unconditionally bump up the refcount without
15063 			 * checking for ILL_CAN_LOOKUP
15064 			 */
15065 			ill_refhold(ill);
15066 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15067 			    CUR_OP, B_FALSE);
15068 			return;
15069 		case DL_DISABMULTI_REQ:
15070 			freemsg(mp);	/* Don't want to pass this up */
15071 			return;
15072 		default:
15073 			break;
15074 		}
15075 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15076 		    dlea->dl_errno, dlea->dl_unix_errno);
15077 		freemsg(mp);
15078 		return;
15079 	case DL_INFO_ACK:
15080 	case DL_BIND_ACK:
15081 	case DL_PHYS_ADDR_ACK:
15082 	case DL_NOTIFY_ACK:
15083 	case DL_CAPABILITY_ACK:
15084 	case DL_CONTROL_ACK:
15085 		/*
15086 		 * Refhold the ill to match qwriter_ip which does a refrele
15087 		 * Since this is on the ill stream we unconditionally
15088 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15089 		 */
15090 		ill_refhold(ill);
15091 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15092 		    CUR_OP, B_FALSE);
15093 		return;
15094 	case DL_NOTIFY_IND:
15095 		ill_refhold(ill);
15096 		/*
15097 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15098 		 * relation to the current ioctl in progress (if any). Hence we
15099 		 * pass in NEW_OP in this case.
15100 		 */
15101 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15102 		    NEW_OP, B_FALSE);
15103 		return;
15104 	case DL_OK_ACK:
15105 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15106 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15107 		switch (dloa->dl_correct_primitive) {
15108 		case DL_UNBIND_REQ:
15109 			mutex_enter(&ill->ill_lock);
15110 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15111 			cv_signal(&ill->ill_cv);
15112 			mutex_exit(&ill->ill_lock);
15113 			/* FALLTHRU */
15114 		case DL_ATTACH_REQ:
15115 		case DL_DETACH_REQ:
15116 			/*
15117 			 * Refhold the ill to match qwriter_ip which does a
15118 			 * refrele. Since this is on the ill stream we
15119 			 * unconditionally bump up the refcount
15120 			 */
15121 			ill_refhold(ill);
15122 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15123 			    CUR_OP, B_FALSE);
15124 			return;
15125 		case DL_ENABMULTI_REQ:
15126 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15127 				ill->ill_dlpi_multicast_state = IDS_OK;
15128 			break;
15129 
15130 		}
15131 		break;
15132 	default:
15133 		break;
15134 	}
15135 	freemsg(mp);
15136 }
15137 
15138 /*
15139  * Handling of DLPI messages that require exclusive access to the ipsq.
15140  *
15141  * Need to do ill_pending_mp_release on ioctl completion, which could
15142  * happen here. (along with mi_copy_done)
15143  */
15144 /* ARGSUSED */
15145 static void
15146 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15147 {
15148 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15149 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15150 	int		err = 0;
15151 	ill_t		*ill;
15152 	ipif_t		*ipif = NULL;
15153 	mblk_t		*mp1 = NULL;
15154 	conn_t		*connp = NULL;
15155 	t_uscalar_t	physaddr_req;
15156 	mblk_t		*mp_hw;
15157 	union DL_primitives *dlp;
15158 	boolean_t	success;
15159 	boolean_t	ioctl_aborted = B_FALSE;
15160 	boolean_t	log = B_TRUE;
15161 	hook_nic_event_t	*info;
15162 
15163 	ip1dbg(("ip_rput_dlpi_writer .."));
15164 	ill = (ill_t *)q->q_ptr;
15165 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15166 
15167 	ASSERT(IAM_WRITER_ILL(ill));
15168 
15169 	/*
15170 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15171 	 * both are null or non-null. However we can assert that only
15172 	 * after grabbing the ipsq_lock. So we don't make any assertion
15173 	 * here and in other places in the code.
15174 	 */
15175 	ipif = ipsq->ipsq_pending_ipif;
15176 	/*
15177 	 * The current ioctl could have been aborted by the user and a new
15178 	 * ioctl to bring up another ill could have started. We could still
15179 	 * get a response from the driver later.
15180 	 */
15181 	if (ipif != NULL && ipif->ipif_ill != ill)
15182 		ioctl_aborted = B_TRUE;
15183 
15184 	switch (dloa->dl_primitive) {
15185 	case DL_ERROR_ACK:
15186 		switch (dlea->dl_error_primitive) {
15187 		case DL_UNBIND_REQ:
15188 		case DL_ATTACH_REQ:
15189 		case DL_DETACH_REQ:
15190 		case DL_INFO_REQ:
15191 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15192 			break;
15193 		case DL_NOTIFY_REQ:
15194 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15195 			log = B_FALSE;
15196 			break;
15197 		case DL_PHYS_ADDR_REQ:
15198 			/*
15199 			 * For IPv6 only, there are two additional
15200 			 * phys_addr_req's sent to the driver to get the
15201 			 * IPv6 token and lla. This allows IP to acquire
15202 			 * the hardware address format for a given interface
15203 			 * without having built in knowledge of the hardware
15204 			 * address. ill_phys_addr_pend keeps track of the last
15205 			 * DL_PAR sent so we know which response we are
15206 			 * dealing with. ill_dlpi_done will update
15207 			 * ill_phys_addr_pend when it sends the next req.
15208 			 * We don't complete the IOCTL until all three DL_PARs
15209 			 * have been attempted, so set *_len to 0 and break.
15210 			 */
15211 			physaddr_req = ill->ill_phys_addr_pend;
15212 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15213 			if (physaddr_req == DL_IPV6_TOKEN) {
15214 				ill->ill_token_length = 0;
15215 				log = B_FALSE;
15216 				break;
15217 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15218 				ill->ill_nd_lla_len = 0;
15219 				log = B_FALSE;
15220 				break;
15221 			}
15222 			/*
15223 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15224 			 * We presumably have an IOCTL hanging out waiting
15225 			 * for completion. Find it and complete the IOCTL
15226 			 * with the error noted.
15227 			 * However, ill_dl_phys was called on an ill queue
15228 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15229 			 * set. But the ioctl is known to be pending on ill_wq.
15230 			 */
15231 			if (!ill->ill_ifname_pending)
15232 				break;
15233 			ill->ill_ifname_pending = 0;
15234 			if (!ioctl_aborted)
15235 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15236 			if (mp1 != NULL) {
15237 				/*
15238 				 * This operation (SIOCSLIFNAME) must have
15239 				 * happened on the ill. Assert there is no conn
15240 				 */
15241 				ASSERT(connp == NULL);
15242 				q = ill->ill_wq;
15243 			}
15244 			break;
15245 		case DL_BIND_REQ:
15246 			ill_dlpi_done(ill, DL_BIND_REQ);
15247 			if (ill->ill_ifname_pending)
15248 				break;
15249 			/*
15250 			 * Something went wrong with the bind.  We presumably
15251 			 * have an IOCTL hanging out waiting for completion.
15252 			 * Find it, take down the interface that was coming
15253 			 * up, and complete the IOCTL with the error noted.
15254 			 */
15255 			if (!ioctl_aborted)
15256 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15257 			if (mp1 != NULL) {
15258 				/*
15259 				 * This operation (SIOCSLIFFLAGS) must have
15260 				 * happened from a conn.
15261 				 */
15262 				ASSERT(connp != NULL);
15263 				q = CONNP_TO_WQ(connp);
15264 				if (ill->ill_move_in_progress) {
15265 					ILL_CLEAR_MOVE(ill);
15266 				}
15267 				(void) ipif_down(ipif, NULL, NULL);
15268 				/* error is set below the switch */
15269 			}
15270 			break;
15271 		case DL_ENABMULTI_REQ:
15272 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15273 
15274 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15275 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15276 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15277 				ipif_t *ipif;
15278 
15279 				log = B_FALSE;
15280 				printf("ip: joining multicasts failed (%d)"
15281 				    " on %s - will use link layer "
15282 				    "broadcasts for multicast\n",
15283 				    dlea->dl_errno, ill->ill_name);
15284 
15285 				/*
15286 				 * Set up the multicast mapping alone.
15287 				 * writer, so ok to access ill->ill_ipif
15288 				 * without any lock.
15289 				 */
15290 				ipif = ill->ill_ipif;
15291 				mutex_enter(&ill->ill_phyint->phyint_lock);
15292 				ill->ill_phyint->phyint_flags |=
15293 				    PHYI_MULTI_BCAST;
15294 				mutex_exit(&ill->ill_phyint->phyint_lock);
15295 
15296 				if (!ill->ill_isv6) {
15297 					(void) ipif_arp_setup_multicast(ipif,
15298 					    NULL);
15299 				} else {
15300 					(void) ipif_ndp_setup_multicast(ipif,
15301 					    NULL);
15302 				}
15303 			}
15304 			freemsg(mp);	/* Don't want to pass this up */
15305 			return;
15306 		case DL_CAPABILITY_REQ:
15307 		case DL_CONTROL_REQ:
15308 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15309 			    "DL_CAPABILITY/CONTROL REQ\n"));
15310 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15311 			ill->ill_dlpi_capab_state = IDS_FAILED;
15312 			freemsg(mp);
15313 			return;
15314 		}
15315 		/*
15316 		 * Note the error for IOCTL completion (mp1 is set when
15317 		 * ready to complete ioctl). If ill_ifname_pending_err is
15318 		 * set, an error occured during plumbing (ill_ifname_pending),
15319 		 * so we want to report that error.
15320 		 *
15321 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15322 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15323 		 * expected to get errack'd if the driver doesn't support
15324 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15325 		 * if these error conditions are encountered.
15326 		 */
15327 		if (mp1 != NULL) {
15328 			if (ill->ill_ifname_pending_err != 0)  {
15329 				err = ill->ill_ifname_pending_err;
15330 				ill->ill_ifname_pending_err = 0;
15331 			} else {
15332 				err = dlea->dl_unix_errno ?
15333 				    dlea->dl_unix_errno : ENXIO;
15334 			}
15335 		/*
15336 		 * If we're plumbing an interface and an error hasn't already
15337 		 * been saved, set ill_ifname_pending_err to the error passed
15338 		 * up. Ignore the error if log is B_FALSE (see comment above).
15339 		 */
15340 		} else if (log && ill->ill_ifname_pending &&
15341 		    ill->ill_ifname_pending_err == 0) {
15342 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15343 			dlea->dl_unix_errno : ENXIO;
15344 		}
15345 
15346 		if (log)
15347 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15348 			    dlea->dl_errno, dlea->dl_unix_errno);
15349 		break;
15350 	case DL_CAPABILITY_ACK: {
15351 		boolean_t reneg_flag = B_FALSE;
15352 		/* Call a routine to handle this one. */
15353 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15354 		/*
15355 		 * Check if the ACK is due to renegotiation case since we
15356 		 * will need to send a new CAPABILITY_REQ later.
15357 		 */
15358 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15359 			/* This is the ack for a renogiation case */
15360 			reneg_flag = B_TRUE;
15361 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15362 		}
15363 		ill_capability_ack(ill, mp);
15364 		if (reneg_flag)
15365 			ill_capability_probe(ill);
15366 		break;
15367 	}
15368 	case DL_CONTROL_ACK:
15369 		/* We treat all of these as "fire and forget" */
15370 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15371 		break;
15372 	case DL_INFO_ACK:
15373 		/* Call a routine to handle this one. */
15374 		ill_dlpi_done(ill, DL_INFO_REQ);
15375 		ip_ll_subnet_defaults(ill, mp);
15376 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15377 		return;
15378 	case DL_BIND_ACK:
15379 		/*
15380 		 * We should have an IOCTL waiting on this unless
15381 		 * sent by ill_dl_phys, in which case just return
15382 		 */
15383 		ill_dlpi_done(ill, DL_BIND_REQ);
15384 		if (ill->ill_ifname_pending)
15385 			break;
15386 
15387 		if (!ioctl_aborted)
15388 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15389 		if (mp1 == NULL)
15390 			break;
15391 		ASSERT(connp != NULL);
15392 		q = CONNP_TO_WQ(connp);
15393 
15394 		/*
15395 		 * We are exclusive. So nothing can change even after
15396 		 * we get the pending mp. If need be we can put it back
15397 		 * and restart, as in calling ipif_arp_up()  below.
15398 		 */
15399 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15400 
15401 		mutex_enter(&ill->ill_lock);
15402 
15403 		ill->ill_dl_up = 1;
15404 
15405 		if ((info = ill->ill_nic_event_info) != NULL) {
15406 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15407 			    "attached for %s\n", info->hne_event,
15408 			    ill->ill_name));
15409 			if (info->hne_data != NULL)
15410 				kmem_free(info->hne_data, info->hne_datalen);
15411 			kmem_free(info, sizeof (hook_nic_event_t));
15412 		}
15413 
15414 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15415 		if (info != NULL) {
15416 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15417 			info->hne_lif = 0;
15418 			info->hne_event = NE_UP;
15419 			info->hne_data = NULL;
15420 			info->hne_datalen = 0;
15421 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15422 		} else
15423 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15424 			    "event information for %s (ENOMEM)\n",
15425 			    ill->ill_name));
15426 
15427 		ill->ill_nic_event_info = info;
15428 
15429 		mutex_exit(&ill->ill_lock);
15430 
15431 		/*
15432 		 * Now bring up the resolver; when that is complete, we'll
15433 		 * create IREs.  Note that we intentionally mirror what
15434 		 * ipif_up() would have done, because we got here by way of
15435 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15436 		 */
15437 		if (ill->ill_isv6) {
15438 			/*
15439 			 * v6 interfaces.
15440 			 * Unlike ARP which has to do another bind
15441 			 * and attach, once we get here we are
15442 			 * done with NDP. Except in the case of
15443 			 * ILLF_XRESOLV, in which case we send an
15444 			 * AR_INTERFACE_UP to the external resolver.
15445 			 * If all goes well, the ioctl will complete
15446 			 * in ip_rput(). If there's an error, we
15447 			 * complete it here.
15448 			 */
15449 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15450 			    B_FALSE);
15451 			if (err == 0) {
15452 				if (ill->ill_flags & ILLF_XRESOLV) {
15453 					mutex_enter(&connp->conn_lock);
15454 					mutex_enter(&ill->ill_lock);
15455 					success = ipsq_pending_mp_add(
15456 					    connp, ipif, q, mp1, 0);
15457 					mutex_exit(&ill->ill_lock);
15458 					mutex_exit(&connp->conn_lock);
15459 					if (success) {
15460 						err = ipif_resolver_up(ipif,
15461 						    Res_act_initial);
15462 						if (err == EINPROGRESS) {
15463 							freemsg(mp);
15464 							return;
15465 						}
15466 						ASSERT(err != 0);
15467 						mp1 = ipsq_pending_mp_get(ipsq,
15468 						    &connp);
15469 						ASSERT(mp1 != NULL);
15470 					} else {
15471 						/* conn has started closing */
15472 						err = EINTR;
15473 					}
15474 				} else { /* Non XRESOLV interface */
15475 					(void) ipif_resolver_up(ipif,
15476 					    Res_act_initial);
15477 					err = ipif_up_done_v6(ipif);
15478 				}
15479 			}
15480 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15481 			/*
15482 			 * ARP and other v4 external resolvers.
15483 			 * Leave the pending mblk intact so that
15484 			 * the ioctl completes in ip_rput().
15485 			 */
15486 			mutex_enter(&connp->conn_lock);
15487 			mutex_enter(&ill->ill_lock);
15488 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15489 			mutex_exit(&ill->ill_lock);
15490 			mutex_exit(&connp->conn_lock);
15491 			if (success) {
15492 				err = ipif_resolver_up(ipif, Res_act_initial);
15493 				if (err == EINPROGRESS) {
15494 					freemsg(mp);
15495 					return;
15496 				}
15497 				ASSERT(err != 0);
15498 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15499 			} else {
15500 				/* The conn has started closing */
15501 				err = EINTR;
15502 			}
15503 		} else {
15504 			/*
15505 			 * This one is complete. Reply to pending ioctl.
15506 			 */
15507 			(void) ipif_resolver_up(ipif, Res_act_initial);
15508 			err = ipif_up_done(ipif);
15509 		}
15510 
15511 		if ((err == 0) && (ill->ill_up_ipifs)) {
15512 			err = ill_up_ipifs(ill, q, mp1);
15513 			if (err == EINPROGRESS) {
15514 				freemsg(mp);
15515 				return;
15516 			}
15517 		}
15518 
15519 		if (ill->ill_up_ipifs) {
15520 			ill_group_cleanup(ill);
15521 		}
15522 
15523 		break;
15524 	case DL_NOTIFY_IND: {
15525 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15526 		ire_t *ire;
15527 		boolean_t need_ire_walk_v4 = B_FALSE;
15528 		boolean_t need_ire_walk_v6 = B_FALSE;
15529 
15530 		/*
15531 		 * Change the address everywhere we need to.
15532 		 * What we're getting here is a link-level addr or phys addr.
15533 		 * The new addr is at notify + notify->dl_addr_offset
15534 		 * The address length is notify->dl_addr_length;
15535 		 */
15536 		switch (notify->dl_notification) {
15537 		case DL_NOTE_PHYS_ADDR:
15538 			mp_hw = copyb(mp);
15539 			if (mp_hw == NULL) {
15540 				err = ENOMEM;
15541 				break;
15542 			}
15543 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15544 			/*
15545 			 * We currently don't support changing
15546 			 * the token via DL_NOTIFY_IND.
15547 			 * When we do support it, we have to consider
15548 			 * what the implications are with respect to
15549 			 * the token and the link local address.
15550 			 */
15551 			mutex_enter(&ill->ill_lock);
15552 			if (dlp->notify_ind.dl_data ==
15553 			    DL_IPV6_LINK_LAYER_ADDR) {
15554 				if (ill->ill_nd_lla_mp != NULL)
15555 					freemsg(ill->ill_nd_lla_mp);
15556 				ill->ill_nd_lla_mp = mp_hw;
15557 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15558 				    dlp->notify_ind.dl_addr_offset;
15559 				ill->ill_nd_lla_len =
15560 				    dlp->notify_ind.dl_addr_length -
15561 				    ABS(ill->ill_sap_length);
15562 				mutex_exit(&ill->ill_lock);
15563 				break;
15564 			} else if (dlp->notify_ind.dl_data ==
15565 			    DL_CURR_PHYS_ADDR) {
15566 				if (ill->ill_phys_addr_mp != NULL)
15567 					freemsg(ill->ill_phys_addr_mp);
15568 				ill->ill_phys_addr_mp = mp_hw;
15569 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15570 				    dlp->notify_ind.dl_addr_offset;
15571 				ill->ill_phys_addr_length =
15572 				    dlp->notify_ind.dl_addr_length -
15573 				    ABS(ill->ill_sap_length);
15574 				if (ill->ill_isv6 &&
15575 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15576 					if (ill->ill_nd_lla_mp != NULL)
15577 						freemsg(ill->ill_nd_lla_mp);
15578 					ill->ill_nd_lla_mp = copyb(mp_hw);
15579 					ill->ill_nd_lla = (uchar_t *)
15580 					    ill->ill_nd_lla_mp->b_rptr +
15581 					    dlp->notify_ind.dl_addr_offset;
15582 					ill->ill_nd_lla_len =
15583 					    ill->ill_phys_addr_length;
15584 				}
15585 			}
15586 			mutex_exit(&ill->ill_lock);
15587 			/*
15588 			 * Send out gratuitous arp request for our new
15589 			 * hardware address.
15590 			 */
15591 			for (ipif = ill->ill_ipif; ipif != NULL;
15592 			    ipif = ipif->ipif_next) {
15593 				if (!(ipif->ipif_flags & IPIF_UP))
15594 					continue;
15595 				if (ill->ill_isv6) {
15596 					ipif_ndp_down(ipif);
15597 					/*
15598 					 * Set B_TRUE to enable
15599 					 * ipif_ndp_up() to send out
15600 					 * unsolicited advertisements.
15601 					 */
15602 					err = ipif_ndp_up(ipif,
15603 					    &ipif->ipif_v6lcl_addr,
15604 					    B_TRUE);
15605 					if (err) {
15606 						ip1dbg((
15607 						    "ip_rput_dlpi_writer: "
15608 						    "Failed to update ndp "
15609 						    "err %d\n", err));
15610 					}
15611 				} else {
15612 					/*
15613 					 * IPv4 ARP case
15614 					 *
15615 					 * Set Res_act_move, as we only want
15616 					 * ipif_resolver_up to send an
15617 					 * AR_ENTRY_ADD request up to
15618 					 * ARP.
15619 					 */
15620 					err = ipif_resolver_up(ipif,
15621 					    Res_act_move);
15622 					if (err) {
15623 						ip1dbg((
15624 						    "ip_rput_dlpi_writer: "
15625 						    "Failed to update arp "
15626 						    "err %d\n", err));
15627 					}
15628 				}
15629 			}
15630 			/*
15631 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15632 			 * case so that all old fastpath information can be
15633 			 * purged from IRE caches.
15634 			 */
15635 		/* FALLTHRU */
15636 		case DL_NOTE_FASTPATH_FLUSH:
15637 			/*
15638 			 * Any fastpath probe sent henceforth will get the
15639 			 * new fp mp. So we first delete any ires that are
15640 			 * waiting for the fastpath. Then walk all ires and
15641 			 * delete the ire or delete the fp mp. In the case of
15642 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15643 			 * recreate the ire's without going through a complex
15644 			 * ipif up/down dance. So we don't delete the ire
15645 			 * itself, but just the nce_fp_mp for these 2 ire's
15646 			 * In the case of the other ire's we delete the ire's
15647 			 * themselves. Access to nce_fp_mp is completely
15648 			 * protected by ire_lock for IRE_MIPRTUN and
15649 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15650 			 * other cases for performance.
15651 			 */
15652 			if (ill->ill_isv6) {
15653 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15654 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15655 				    NULL);
15656 			} else {
15657 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15658 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15659 				    IRE_CACHE | IRE_BROADCAST,
15660 				    ire_fastpath_flush, NULL, ill);
15661 				mutex_enter(&ire_mrtun_lock);
15662 				if (ire_mrtun_count != 0) {
15663 					mutex_exit(&ire_mrtun_lock);
15664 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15665 					    IRE_MIPRTUN, ire_fastpath_flush,
15666 					    NULL, ill);
15667 				} else {
15668 					mutex_exit(&ire_mrtun_lock);
15669 				}
15670 			}
15671 			break;
15672 		case DL_NOTE_SDU_SIZE:
15673 			/*
15674 			 * Change the MTU size of the interface, of all
15675 			 * attached ipif's, and of all relevant ire's.  The
15676 			 * new value's a uint32_t at notify->dl_data.
15677 			 * Mtu change Vs. new ire creation - protocol below.
15678 			 *
15679 			 * a Mark the ipif as IPIF_CHANGING.
15680 			 * b Set the new mtu in the ipif.
15681 			 * c Change the ire_max_frag on all affected ires
15682 			 * d Unmark the IPIF_CHANGING
15683 			 *
15684 			 * To see how the protocol works, assume an interface
15685 			 * route is also being added simultaneously by
15686 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15687 			 * the ire. If the ire is created before step a,
15688 			 * it will be cleaned up by step c. If the ire is
15689 			 * created after step d, it will see the new value of
15690 			 * ipif_mtu. Any attempt to create the ire between
15691 			 * steps a to d will fail because of the IPIF_CHANGING
15692 			 * flag. Note that ire_create() is passed a pointer to
15693 			 * the ipif_mtu, and not the value. During ire_add
15694 			 * under the bucket lock, the ire_max_frag of the
15695 			 * new ire being created is set from the ipif/ire from
15696 			 * which it is being derived.
15697 			 */
15698 			mutex_enter(&ill->ill_lock);
15699 			ill->ill_max_frag = (uint_t)notify->dl_data;
15700 
15701 			/*
15702 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15703 			 * leave it alone
15704 			 */
15705 			if (ill->ill_mtu_userspecified) {
15706 				mutex_exit(&ill->ill_lock);
15707 				break;
15708 			}
15709 			ill->ill_max_mtu = ill->ill_max_frag;
15710 			if (ill->ill_isv6) {
15711 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15712 					ill->ill_max_mtu = IPV6_MIN_MTU;
15713 			} else {
15714 				if (ill->ill_max_mtu < IP_MIN_MTU)
15715 					ill->ill_max_mtu = IP_MIN_MTU;
15716 			}
15717 			for (ipif = ill->ill_ipif; ipif != NULL;
15718 			    ipif = ipif->ipif_next) {
15719 				/*
15720 				 * Don't override the mtu if the user
15721 				 * has explicitly set it.
15722 				 */
15723 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15724 					continue;
15725 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15726 				if (ipif->ipif_isv6)
15727 					ire = ipif_to_ire_v6(ipif);
15728 				else
15729 					ire = ipif_to_ire(ipif);
15730 				if (ire != NULL) {
15731 					ire->ire_max_frag = ipif->ipif_mtu;
15732 					ire_refrele(ire);
15733 				}
15734 				if (ipif->ipif_flags & IPIF_UP) {
15735 					if (ill->ill_isv6)
15736 						need_ire_walk_v6 = B_TRUE;
15737 					else
15738 						need_ire_walk_v4 = B_TRUE;
15739 				}
15740 			}
15741 			mutex_exit(&ill->ill_lock);
15742 			if (need_ire_walk_v4)
15743 				ire_walk_v4(ill_mtu_change, (char *)ill,
15744 				    ALL_ZONES);
15745 			if (need_ire_walk_v6)
15746 				ire_walk_v6(ill_mtu_change, (char *)ill,
15747 				    ALL_ZONES);
15748 			break;
15749 		case DL_NOTE_LINK_UP:
15750 		case DL_NOTE_LINK_DOWN: {
15751 			/*
15752 			 * We are writer. ill / phyint / ipsq assocs stable.
15753 			 * The RUNNING flag reflects the state of the link.
15754 			 */
15755 			phyint_t *phyint = ill->ill_phyint;
15756 			uint64_t new_phyint_flags;
15757 			boolean_t changed = B_FALSE;
15758 			boolean_t went_up;
15759 
15760 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15761 			mutex_enter(&phyint->phyint_lock);
15762 			new_phyint_flags = went_up ?
15763 			    phyint->phyint_flags | PHYI_RUNNING :
15764 			    phyint->phyint_flags & ~PHYI_RUNNING;
15765 			if (new_phyint_flags != phyint->phyint_flags) {
15766 				phyint->phyint_flags = new_phyint_flags;
15767 				changed = B_TRUE;
15768 			}
15769 			mutex_exit(&phyint->phyint_lock);
15770 			/*
15771 			 * ill_restart_dad handles the DAD restart and routing
15772 			 * socket notification logic.
15773 			 */
15774 			if (changed) {
15775 				ill_restart_dad(phyint->phyint_illv4, went_up);
15776 				ill_restart_dad(phyint->phyint_illv6, went_up);
15777 			}
15778 			break;
15779 		}
15780 		case DL_NOTE_PROMISC_ON_PHYS:
15781 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15782 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15783 			mutex_enter(&ill->ill_lock);
15784 			ill->ill_promisc_on_phys = B_TRUE;
15785 			mutex_exit(&ill->ill_lock);
15786 			break;
15787 		case DL_NOTE_PROMISC_OFF_PHYS:
15788 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15789 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15790 			mutex_enter(&ill->ill_lock);
15791 			ill->ill_promisc_on_phys = B_FALSE;
15792 			mutex_exit(&ill->ill_lock);
15793 			break;
15794 		case DL_NOTE_CAPAB_RENEG:
15795 			/*
15796 			 * Something changed on the driver side.
15797 			 * It wants us to renegotiate the capabilities
15798 			 * on this ill. The most likely cause is the
15799 			 * aggregation interface under us where a
15800 			 * port got added or went away.
15801 			 *
15802 			 * We reset the capabilities and set the
15803 			 * state to IDS_RENG so that when the ack
15804 			 * comes back, we can start the
15805 			 * renegotiation process.
15806 			 */
15807 			ill_capability_reset(ill);
15808 			ill->ill_dlpi_capab_state = IDS_RENEG;
15809 			break;
15810 		default:
15811 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15812 			    "type 0x%x for DL_NOTIFY_IND\n",
15813 			    notify->dl_notification));
15814 			break;
15815 		}
15816 
15817 		/*
15818 		 * As this is an asynchronous operation, we
15819 		 * should not call ill_dlpi_done
15820 		 */
15821 		break;
15822 	}
15823 	case DL_NOTIFY_ACK: {
15824 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15825 
15826 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15827 			ill->ill_note_link = 1;
15828 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15829 		break;
15830 	}
15831 	case DL_PHYS_ADDR_ACK: {
15832 		/*
15833 		 * We should have an IOCTL waiting on this when request
15834 		 * sent by ill_dl_phys.
15835 		 * However, ill_dl_phys was called on an ill queue (from
15836 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
15837 		 * ioctl is known to be pending on ill_wq.
15838 		 * There are two additional phys_addr_req's sent to the
15839 		 * driver to get the token and lla. ill_phys_addr_pend
15840 		 * keeps track of the last one sent so we know which
15841 		 * response we are dealing with. ill_dlpi_done will
15842 		 * update ill_phys_addr_pend when it sends the next req.
15843 		 * We don't complete the IOCTL until all three DL_PARs
15844 		 * have been attempted.
15845 		 *
15846 		 * We don't need any lock to update ill_nd_lla* fields,
15847 		 * since the ill is not yet up, We grab the lock just
15848 		 * for uniformity with other code that accesses ill_nd_lla.
15849 		 */
15850 		physaddr_req = ill->ill_phys_addr_pend;
15851 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15852 		if (physaddr_req == DL_IPV6_TOKEN ||
15853 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15854 			if (physaddr_req == DL_IPV6_TOKEN) {
15855 				/*
15856 				 * bcopy to low-order bits of ill_token
15857 				 *
15858 				 * XXX Temporary hack - currently,
15859 				 * all known tokens are 64 bits,
15860 				 * so I'll cheat for the moment.
15861 				 */
15862 				dlp = (union DL_primitives *)mp->b_rptr;
15863 
15864 				mutex_enter(&ill->ill_lock);
15865 				bcopy((uchar_t *)(mp->b_rptr +
15866 				dlp->physaddr_ack.dl_addr_offset),
15867 				(void *)&ill->ill_token.s6_addr32[2],
15868 				dlp->physaddr_ack.dl_addr_length);
15869 				ill->ill_token_length =
15870 					dlp->physaddr_ack.dl_addr_length;
15871 				mutex_exit(&ill->ill_lock);
15872 			} else {
15873 				ASSERT(ill->ill_nd_lla_mp == NULL);
15874 				mp_hw = copyb(mp);
15875 				if (mp_hw == NULL) {
15876 					err = ENOMEM;
15877 					break;
15878 				}
15879 				dlp = (union DL_primitives *)mp_hw->b_rptr;
15880 				mutex_enter(&ill->ill_lock);
15881 				ill->ill_nd_lla_mp = mp_hw;
15882 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15883 				dlp->physaddr_ack.dl_addr_offset;
15884 				ill->ill_nd_lla_len =
15885 					dlp->physaddr_ack.dl_addr_length;
15886 				mutex_exit(&ill->ill_lock);
15887 			}
15888 			break;
15889 		}
15890 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
15891 		ASSERT(ill->ill_phys_addr_mp == NULL);
15892 		if (!ill->ill_ifname_pending)
15893 			break;
15894 		ill->ill_ifname_pending = 0;
15895 		if (!ioctl_aborted)
15896 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15897 		if (mp1 != NULL) {
15898 			ASSERT(connp == NULL);
15899 			q = ill->ill_wq;
15900 		}
15901 		/*
15902 		 * If any error acks received during the plumbing sequence,
15903 		 * ill_ifname_pending_err will be set. Break out and send up
15904 		 * the error to the pending ioctl.
15905 		 */
15906 		if (ill->ill_ifname_pending_err != 0) {
15907 			err = ill->ill_ifname_pending_err;
15908 			ill->ill_ifname_pending_err = 0;
15909 			break;
15910 		}
15911 		/*
15912 		 * Get the interface token.  If the zeroth interface
15913 		 * address is zero then set the address to the link local
15914 		 * address
15915 		 */
15916 		mp_hw = copyb(mp);
15917 		if (mp_hw == NULL) {
15918 			err = ENOMEM;
15919 			break;
15920 		}
15921 		dlp = (union DL_primitives *)mp_hw->b_rptr;
15922 		ill->ill_phys_addr_mp = mp_hw;
15923 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15924 				dlp->physaddr_ack.dl_addr_offset;
15925 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
15926 		    ill->ill_phys_addr_length == 0 ||
15927 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15928 			/*
15929 			 * Compatibility: atun driver returns a length of 0.
15930 			 * ipdptp has an ill_phys_addr_length of zero(from
15931 			 * DL_BIND_ACK) but a non-zero length here.
15932 			 * ipd has an ill_phys_addr_length of 4(from
15933 			 * DL_BIND_ACK) but a non-zero length here.
15934 			 */
15935 			ill->ill_phys_addr = NULL;
15936 		} else if (dlp->physaddr_ack.dl_addr_length !=
15937 		    ill->ill_phys_addr_length) {
15938 			ip0dbg(("DL_PHYS_ADDR_ACK: "
15939 			    "Address length mismatch %d %d\n",
15940 			    dlp->physaddr_ack.dl_addr_length,
15941 			    ill->ill_phys_addr_length));
15942 			err = EINVAL;
15943 			break;
15944 		}
15945 		mutex_enter(&ill->ill_lock);
15946 		if (ill->ill_nd_lla_mp == NULL) {
15947 			ill->ill_nd_lla_mp = copyb(mp_hw);
15948 			if (ill->ill_nd_lla_mp == NULL) {
15949 				err = ENOMEM;
15950 				mutex_exit(&ill->ill_lock);
15951 				break;
15952 			}
15953 			ill->ill_nd_lla =
15954 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
15955 			    dlp->physaddr_ack.dl_addr_offset;
15956 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
15957 		}
15958 		mutex_exit(&ill->ill_lock);
15959 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15960 			(void) ill_setdefaulttoken(ill);
15961 
15962 		/*
15963 		 * If the ill zero interface has a zero address assign
15964 		 * it the proper link local address.
15965 		 */
15966 		ASSERT(ill->ill_ipif->ipif_id == 0);
15967 		if (ipif != NULL &&
15968 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
15969 			(void) ipif_setlinklocal(ipif);
15970 		break;
15971 	}
15972 	case DL_OK_ACK:
15973 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15974 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15975 		    dloa->dl_correct_primitive));
15976 		switch (dloa->dl_correct_primitive) {
15977 		case DL_UNBIND_REQ:
15978 		case DL_ATTACH_REQ:
15979 		case DL_DETACH_REQ:
15980 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15981 			break;
15982 		}
15983 		break;
15984 	default:
15985 		break;
15986 	}
15987 
15988 	freemsg(mp);
15989 	if (mp1) {
15990 		struct iocblk *iocp;
15991 		int mode;
15992 
15993 		/*
15994 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
15995 		 * SIOCSLIFNAME do a copyout.
15996 		 */
15997 		iocp = (struct iocblk *)mp1->b_rptr;
15998 
15999 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
16000 		    iocp->ioc_cmd == SIOCSLIFNAME)
16001 			mode = COPYOUT;
16002 		else
16003 			mode = NO_COPYOUT;
16004 		/*
16005 		 * The ioctl must complete now without EINPROGRESS
16006 		 * since ipsq_pending_mp_get has removed the ioctl mblk
16007 		 * from ipsq_pending_mp. Otherwise the ioctl will be
16008 		 * stuck for ever in the ipsq.
16009 		 */
16010 		ASSERT(err != EINPROGRESS);
16011 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16012 
16013 	}
16014 }
16015 
16016 /*
16017  * ip_rput_other is called by ip_rput to handle messages modifying the global
16018  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16019  */
16020 /* ARGSUSED */
16021 void
16022 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16023 {
16024 	ill_t		*ill;
16025 	struct iocblk	*iocp;
16026 	mblk_t		*mp1;
16027 	conn_t		*connp = NULL;
16028 
16029 	ip1dbg(("ip_rput_other "));
16030 	ill = (ill_t *)q->q_ptr;
16031 	/*
16032 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16033 	 * in which case ipsq is NULL.
16034 	 */
16035 	if (ipsq != NULL) {
16036 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16037 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16038 	}
16039 
16040 	switch (mp->b_datap->db_type) {
16041 	case M_ERROR:
16042 	case M_HANGUP:
16043 		/*
16044 		 * The device has a problem.  We force the ILL down.  It can
16045 		 * be brought up again manually using SIOCSIFFLAGS (via
16046 		 * ifconfig or equivalent).
16047 		 */
16048 		ASSERT(ipsq != NULL);
16049 		if (mp->b_rptr < mp->b_wptr)
16050 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16051 		if (ill->ill_error == 0)
16052 			ill->ill_error = ENXIO;
16053 		if (!ill_down_start(q, mp))
16054 			return;
16055 		ipif_all_down_tail(ipsq, q, mp, NULL);
16056 		break;
16057 	case M_IOCACK:
16058 		iocp = (struct iocblk *)mp->b_rptr;
16059 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16060 		switch (iocp->ioc_cmd) {
16061 		case SIOCSTUNPARAM:
16062 		case OSIOCSTUNPARAM:
16063 			ASSERT(ipsq != NULL);
16064 			/*
16065 			 * Finish socket ioctl passed through to tun.
16066 			 * We should have an IOCTL waiting on this.
16067 			 */
16068 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16069 			if (ill->ill_isv6) {
16070 				struct iftun_req *ta;
16071 
16072 				/*
16073 				 * if a source or destination is
16074 				 * being set, try and set the link
16075 				 * local address for the tunnel
16076 				 */
16077 				ta = (struct iftun_req *)mp->b_cont->
16078 				    b_cont->b_rptr;
16079 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16080 					ipif_set_tun_llink(ill, ta);
16081 				}
16082 
16083 			}
16084 			if (mp1 != NULL) {
16085 				/*
16086 				 * Now copy back the b_next/b_prev used by
16087 				 * mi code for the mi_copy* functions.
16088 				 * See ip_sioctl_tunparam() for the reason.
16089 				 * Also protect against missing b_cont.
16090 				 */
16091 				if (mp->b_cont != NULL) {
16092 					mp->b_cont->b_next =
16093 					    mp1->b_cont->b_next;
16094 					mp->b_cont->b_prev =
16095 					    mp1->b_cont->b_prev;
16096 				}
16097 				inet_freemsg(mp1);
16098 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16099 				ASSERT(connp != NULL);
16100 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16101 				    iocp->ioc_error, NO_COPYOUT,
16102 				    ipsq->ipsq_current_ipif, ipsq);
16103 			} else {
16104 				ASSERT(connp == NULL);
16105 				putnext(q, mp);
16106 			}
16107 			break;
16108 		case SIOCGTUNPARAM:
16109 		case OSIOCGTUNPARAM:
16110 			/*
16111 			 * This is really M_IOCDATA from the tunnel driver.
16112 			 * convert back and complete the ioctl.
16113 			 * We should have an IOCTL waiting on this.
16114 			 */
16115 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16116 			if (mp1) {
16117 				/*
16118 				 * Now copy back the b_next/b_prev used by
16119 				 * mi code for the mi_copy* functions.
16120 				 * See ip_sioctl_tunparam() for the reason.
16121 				 * Also protect against missing b_cont.
16122 				 */
16123 				if (mp->b_cont != NULL) {
16124 					mp->b_cont->b_next =
16125 					    mp1->b_cont->b_next;
16126 					mp->b_cont->b_prev =
16127 					    mp1->b_cont->b_prev;
16128 				}
16129 				inet_freemsg(mp1);
16130 				if (iocp->ioc_error == 0)
16131 					mp->b_datap->db_type = M_IOCDATA;
16132 				ASSERT(connp != NULL);
16133 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16134 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16135 			} else {
16136 				ASSERT(connp == NULL);
16137 				putnext(q, mp);
16138 			}
16139 			break;
16140 		default:
16141 			break;
16142 		}
16143 		break;
16144 	case M_IOCNAK:
16145 		iocp = (struct iocblk *)mp->b_rptr;
16146 
16147 		switch (iocp->ioc_cmd) {
16148 		int mode;
16149 		ipif_t	*ipif;
16150 
16151 		case DL_IOC_HDR_INFO:
16152 			/*
16153 			 * If this was the first attempt turn of the
16154 			 * fastpath probing.
16155 			 */
16156 			mutex_enter(&ill->ill_lock);
16157 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16158 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16159 				mutex_exit(&ill->ill_lock);
16160 				ill_fastpath_nack(ill);
16161 				ip1dbg(("ip_rput: DLPI fastpath off on "
16162 				    "interface %s\n",
16163 				    ill->ill_name));
16164 			} else {
16165 				mutex_exit(&ill->ill_lock);
16166 			}
16167 			freemsg(mp);
16168 			break;
16169 		case SIOCSTUNPARAM:
16170 		case OSIOCSTUNPARAM:
16171 			ASSERT(ipsq != NULL);
16172 			/*
16173 			 * Finish socket ioctl passed through to tun
16174 			 * We should have an IOCTL waiting on this.
16175 			 */
16176 			/* FALLTHRU */
16177 		case SIOCGTUNPARAM:
16178 		case OSIOCGTUNPARAM:
16179 			/*
16180 			 * This is really M_IOCDATA from the tunnel driver.
16181 			 * convert back and complete the ioctl.
16182 			 * We should have an IOCTL waiting on this.
16183 			 */
16184 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16185 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16186 				mp1 = ill_pending_mp_get(ill, &connp,
16187 				    iocp->ioc_id);
16188 				mode = COPYOUT;
16189 				ipsq = NULL;
16190 				ipif = NULL;
16191 			} else {
16192 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16193 				mode = NO_COPYOUT;
16194 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16195 				ipif = ipsq->ipsq_current_ipif;
16196 			}
16197 			if (mp1 != NULL) {
16198 				/*
16199 				 * Now copy back the b_next/b_prev used by
16200 				 * mi code for the mi_copy* functions.
16201 				 * See ip_sioctl_tunparam() for the reason.
16202 				 * Also protect against missing b_cont.
16203 				 */
16204 				if (mp->b_cont != NULL) {
16205 					mp->b_cont->b_next =
16206 					    mp1->b_cont->b_next;
16207 					mp->b_cont->b_prev =
16208 					    mp1->b_cont->b_prev;
16209 				}
16210 				inet_freemsg(mp1);
16211 				if (iocp->ioc_error == 0)
16212 					iocp->ioc_error = EINVAL;
16213 				ASSERT(connp != NULL);
16214 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16215 				    iocp->ioc_error, mode, ipif, ipsq);
16216 			} else {
16217 				ASSERT(connp == NULL);
16218 				putnext(q, mp);
16219 			}
16220 			break;
16221 		default:
16222 			break;
16223 		}
16224 	default:
16225 		break;
16226 	}
16227 }
16228 
16229 /*
16230  * NOTE : This function does not ire_refrele the ire argument passed in.
16231  *
16232  * IPQoS notes
16233  * IP policy is invoked twice for a forwarded packet, once on the read side
16234  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16235  * enabled. An additional parameter, in_ill, has been added for this purpose.
16236  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16237  * because ip_mroute drops this information.
16238  *
16239  */
16240 void
16241 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16242 {
16243 	uint32_t	pkt_len;
16244 	queue_t	*q;
16245 	uint32_t	sum;
16246 #define	rptr	((uchar_t *)ipha)
16247 	uint32_t	max_frag;
16248 	uint32_t	ill_index;
16249 	ill_t		*out_ill;
16250 
16251 	/* Get the ill_index of the incoming ILL */
16252 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16253 
16254 	/* Initiate Read side IPPF processing */
16255 	if (IPP_ENABLED(IPP_FWD_IN)) {
16256 		ip_process(IPP_FWD_IN, &mp, ill_index);
16257 		if (mp == NULL) {
16258 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16259 			    "during IPPF processing\n"));
16260 			return;
16261 		}
16262 	}
16263 
16264 	pkt_len = ntohs(ipha->ipha_length);
16265 
16266 	/* Adjust the checksum to reflect the ttl decrement. */
16267 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16268 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16269 
16270 	if (ipha->ipha_ttl-- <= 1) {
16271 		if (ip_csum_hdr(ipha)) {
16272 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16273 			goto drop_pkt;
16274 		}
16275 		/*
16276 		 * Note: ire_stq this will be NULL for multicast
16277 		 * datagrams using the long path through arp (the IRE
16278 		 * is not an IRE_CACHE). This should not cause
16279 		 * problems since we don't generate ICMP errors for
16280 		 * multicast packets.
16281 		 */
16282 		q = ire->ire_stq;
16283 		if (q != NULL) {
16284 			/* Sent by forwarding path, and router is global zone */
16285 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16286 			    GLOBAL_ZONEID);
16287 		} else
16288 			freemsg(mp);
16289 		return;
16290 	}
16291 
16292 	/*
16293 	 * Don't forward if the interface is down
16294 	 */
16295 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16296 		BUMP_MIB(&ip_mib, ipInDiscards);
16297 		ip2dbg(("ip_rput_forward:interface is down\n"));
16298 		goto drop_pkt;
16299 	}
16300 
16301 	/* Get the ill_index of the outgoing ILL */
16302 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16303 
16304 	out_ill = ire->ire_ipif->ipif_ill;
16305 
16306 	DTRACE_PROBE4(ip4__forwarding__start,
16307 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16308 
16309 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16310 	    in_ill, out_ill, ipha, mp, mp);
16311 
16312 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16313 
16314 	if (mp == NULL)
16315 		return;
16316 	pkt_len = ntohs(ipha->ipha_length);
16317 
16318 	if (is_system_labeled()) {
16319 		mblk_t *mp1;
16320 
16321 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16322 			BUMP_MIB(&ip_mib, ipForwProhibits);
16323 			goto drop_pkt;
16324 		}
16325 		/* Size may have changed */
16326 		mp = mp1;
16327 		ipha = (ipha_t *)mp->b_rptr;
16328 		pkt_len = ntohs(ipha->ipha_length);
16329 	}
16330 
16331 	/* Check if there are options to update */
16332 	if (!IS_SIMPLE_IPH(ipha)) {
16333 		if (ip_csum_hdr(ipha)) {
16334 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16335 			goto drop_pkt;
16336 		}
16337 		if (ip_rput_forward_options(mp, ipha, ire)) {
16338 			return;
16339 		}
16340 
16341 		ipha->ipha_hdr_checksum = 0;
16342 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16343 	}
16344 	max_frag = ire->ire_max_frag;
16345 	if (pkt_len > max_frag) {
16346 		/*
16347 		 * It needs fragging on its way out.  We haven't
16348 		 * verified the header checksum yet.  Since we
16349 		 * are going to put a surely good checksum in the
16350 		 * outgoing header, we have to make sure that it
16351 		 * was good coming in.
16352 		 */
16353 		if (ip_csum_hdr(ipha)) {
16354 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16355 			goto drop_pkt;
16356 		}
16357 		/* Initiate Write side IPPF processing */
16358 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16359 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16360 			if (mp == NULL) {
16361 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16362 				    " during IPPF processing\n"));
16363 				return;
16364 			}
16365 		}
16366 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16367 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16368 		return;
16369 	}
16370 
16371 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16372 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16373 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16374 	    NULL, out_ill, ipha, mp, mp);
16375 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16376 	if (mp == NULL)
16377 		return;
16378 
16379 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16380 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16381 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16382 	/* ip_xmit_v4 always consumes the packet */
16383 	return;
16384 
16385 drop_pkt:;
16386 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16387 	freemsg(mp);
16388 #undef	rptr
16389 }
16390 
16391 void
16392 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16393 {
16394 	ire_t	*ire;
16395 
16396 	ASSERT(!ipif->ipif_isv6);
16397 	/*
16398 	 * Find an IRE which matches the destination and the outgoing
16399 	 * queue in the cache table. All we need is an IRE_CACHE which
16400 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16401 	 * then it is enough to have some IRE_CACHE in the group.
16402 	 */
16403 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16404 		dst = ipif->ipif_pp_dst_addr;
16405 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16406 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16407 	if (ire == NULL) {
16408 		/*
16409 		 * Mark this packet to make it be delivered to
16410 		 * ip_rput_forward after the new ire has been
16411 		 * created.
16412 		 */
16413 		mp->b_prev = NULL;
16414 		mp->b_next = mp;
16415 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16416 		    NULL, 0, GLOBAL_ZONEID);
16417 	} else {
16418 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16419 		IRE_REFRELE(ire);
16420 	}
16421 }
16422 
16423 /* Update any source route, record route or timestamp options */
16424 static int
16425 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16426 {
16427 	ipoptp_t	opts;
16428 	uchar_t		*opt;
16429 	uint8_t		optval;
16430 	uint8_t		optlen;
16431 	ipaddr_t	dst;
16432 	uint32_t	ts;
16433 	ire_t		*dst_ire = NULL;
16434 	ire_t		*tmp_ire = NULL;
16435 	timestruc_t	now;
16436 
16437 	ip2dbg(("ip_rput_forward_options\n"));
16438 	dst = ipha->ipha_dst;
16439 	for (optval = ipoptp_first(&opts, ipha);
16440 	    optval != IPOPT_EOL;
16441 	    optval = ipoptp_next(&opts)) {
16442 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16443 		opt = opts.ipoptp_cur;
16444 		optlen = opts.ipoptp_len;
16445 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16446 		    optval, opts.ipoptp_len));
16447 		switch (optval) {
16448 			uint32_t off;
16449 		case IPOPT_SSRR:
16450 		case IPOPT_LSRR:
16451 			/* Check if adminstratively disabled */
16452 			if (!ip_forward_src_routed) {
16453 				BUMP_MIB(&ip_mib, ipForwProhibits);
16454 				if (ire->ire_stq != NULL) {
16455 					/*
16456 					 * Sent by forwarding path, and router
16457 					 * is global zone
16458 					 */
16459 					icmp_unreachable(ire->ire_stq, mp,
16460 					    ICMP_SOURCE_ROUTE_FAILED,
16461 					    GLOBAL_ZONEID);
16462 				} else {
16463 					ip0dbg(("ip_rput_forward_options: "
16464 					    "unable to send unreach\n"));
16465 					freemsg(mp);
16466 				}
16467 				return (-1);
16468 			}
16469 
16470 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16471 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16472 			if (dst_ire == NULL) {
16473 				/*
16474 				 * Must be partial since ip_rput_options
16475 				 * checked for strict.
16476 				 */
16477 				break;
16478 			}
16479 			off = opt[IPOPT_OFFSET];
16480 			off--;
16481 		redo_srr:
16482 			if (optlen < IP_ADDR_LEN ||
16483 			    off > optlen - IP_ADDR_LEN) {
16484 				/* End of source route */
16485 				ip1dbg((
16486 				    "ip_rput_forward_options: end of SR\n"));
16487 				ire_refrele(dst_ire);
16488 				break;
16489 			}
16490 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16491 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16492 			    IP_ADDR_LEN);
16493 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16494 			    ntohl(dst)));
16495 
16496 			/*
16497 			 * Check if our address is present more than
16498 			 * once as consecutive hops in source route.
16499 			 */
16500 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16501 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16502 			if (tmp_ire != NULL) {
16503 				ire_refrele(tmp_ire);
16504 				off += IP_ADDR_LEN;
16505 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16506 				goto redo_srr;
16507 			}
16508 			ipha->ipha_dst = dst;
16509 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16510 			ire_refrele(dst_ire);
16511 			break;
16512 		case IPOPT_RR:
16513 			off = opt[IPOPT_OFFSET];
16514 			off--;
16515 			if (optlen < IP_ADDR_LEN ||
16516 			    off > optlen - IP_ADDR_LEN) {
16517 				/* No more room - ignore */
16518 				ip1dbg((
16519 				    "ip_rput_forward_options: end of RR\n"));
16520 				break;
16521 			}
16522 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16523 			    IP_ADDR_LEN);
16524 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16525 			break;
16526 		case IPOPT_TS:
16527 			/* Insert timestamp if there is room */
16528 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16529 			case IPOPT_TS_TSONLY:
16530 				off = IPOPT_TS_TIMELEN;
16531 				break;
16532 			case IPOPT_TS_PRESPEC:
16533 			case IPOPT_TS_PRESPEC_RFC791:
16534 				/* Verify that the address matched */
16535 				off = opt[IPOPT_OFFSET] - 1;
16536 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16537 				dst_ire = ire_ctable_lookup(dst, 0,
16538 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16539 				    MATCH_IRE_TYPE);
16540 
16541 				if (dst_ire == NULL) {
16542 					/* Not for us */
16543 					break;
16544 				}
16545 				ire_refrele(dst_ire);
16546 				/* FALLTHRU */
16547 			case IPOPT_TS_TSANDADDR:
16548 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16549 				break;
16550 			default:
16551 				/*
16552 				 * ip_*put_options should have already
16553 				 * dropped this packet.
16554 				 */
16555 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16556 				    "unknown IT - bug in ip_rput_options?\n");
16557 				return (0);	/* Keep "lint" happy */
16558 			}
16559 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16560 				/* Increase overflow counter */
16561 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16562 				opt[IPOPT_POS_OV_FLG] =
16563 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16564 				    (off << 4));
16565 				break;
16566 			}
16567 			off = opt[IPOPT_OFFSET] - 1;
16568 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16569 			case IPOPT_TS_PRESPEC:
16570 			case IPOPT_TS_PRESPEC_RFC791:
16571 			case IPOPT_TS_TSANDADDR:
16572 				bcopy(&ire->ire_src_addr,
16573 				    (char *)opt + off, IP_ADDR_LEN);
16574 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16575 				/* FALLTHRU */
16576 			case IPOPT_TS_TSONLY:
16577 				off = opt[IPOPT_OFFSET] - 1;
16578 				/* Compute # of milliseconds since midnight */
16579 				gethrestime(&now);
16580 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16581 				    now.tv_nsec / (NANOSEC / MILLISEC);
16582 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16583 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16584 				break;
16585 			}
16586 			break;
16587 		}
16588 	}
16589 	return (0);
16590 }
16591 
16592 /*
16593  * This is called after processing at least one of AH/ESP headers.
16594  *
16595  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16596  * the actual, physical interface on which the packet was received,
16597  * but, when ip_strict_dst_multihoming is set to 1, could be the
16598  * interface which had the ipha_dst configured when the packet went
16599  * through ip_rput. The ill_index corresponding to the recv_ill
16600  * is saved in ipsec_in_rill_index
16601  */
16602 void
16603 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16604 {
16605 	mblk_t *mp;
16606 	ipaddr_t dst;
16607 	in6_addr_t *v6dstp;
16608 	ipha_t *ipha;
16609 	ip6_t *ip6h;
16610 	ipsec_in_t *ii;
16611 	boolean_t ill_need_rele = B_FALSE;
16612 	boolean_t rill_need_rele = B_FALSE;
16613 	boolean_t ire_need_rele = B_FALSE;
16614 
16615 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16616 	ASSERT(ii->ipsec_in_ill_index != 0);
16617 
16618 	mp = ipsec_mp->b_cont;
16619 	ASSERT(mp != NULL);
16620 
16621 
16622 	if (ill == NULL) {
16623 		ASSERT(recv_ill == NULL);
16624 		/*
16625 		 * We need to get the original queue on which ip_rput_local
16626 		 * or ip_rput_data_v6 was called.
16627 		 */
16628 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16629 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16630 		ill_need_rele = B_TRUE;
16631 
16632 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16633 			recv_ill = ill_lookup_on_ifindex(
16634 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16635 			    NULL, NULL, NULL, NULL);
16636 			rill_need_rele = B_TRUE;
16637 		} else {
16638 			recv_ill = ill;
16639 		}
16640 
16641 		if ((ill == NULL) || (recv_ill == NULL)) {
16642 			ip0dbg(("ip_fanout_proto_again: interface "
16643 			    "disappeared\n"));
16644 			if (ill != NULL)
16645 				ill_refrele(ill);
16646 			if (recv_ill != NULL)
16647 				ill_refrele(recv_ill);
16648 			freemsg(ipsec_mp);
16649 			return;
16650 		}
16651 	}
16652 
16653 	ASSERT(ill != NULL && recv_ill != NULL);
16654 
16655 	if (mp->b_datap->db_type == M_CTL) {
16656 		/*
16657 		 * AH/ESP is returning the ICMP message after
16658 		 * removing their headers. Fanout again till
16659 		 * it gets to the right protocol.
16660 		 */
16661 		if (ii->ipsec_in_v4) {
16662 			icmph_t *icmph;
16663 			int iph_hdr_length;
16664 			int hdr_length;
16665 
16666 			ipha = (ipha_t *)mp->b_rptr;
16667 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16668 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16669 			ipha = (ipha_t *)&icmph[1];
16670 			hdr_length = IPH_HDR_LENGTH(ipha);
16671 			/*
16672 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16673 			 * Reset the type to M_DATA.
16674 			 */
16675 			mp->b_datap->db_type = M_DATA;
16676 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16677 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16678 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16679 		} else {
16680 			icmp6_t *icmp6;
16681 			int hdr_length;
16682 
16683 			ip6h = (ip6_t *)mp->b_rptr;
16684 			/* Don't call hdr_length_v6() unless you have to. */
16685 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16686 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16687 			else
16688 				hdr_length = IPV6_HDR_LEN;
16689 
16690 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16691 			/*
16692 			 * icmp_inbound_error_fanout_v6 may need to do
16693 			 * pullupmsg.  Reset the type to M_DATA.
16694 			 */
16695 			mp->b_datap->db_type = M_DATA;
16696 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16697 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16698 		}
16699 		if (ill_need_rele)
16700 			ill_refrele(ill);
16701 		if (rill_need_rele)
16702 			ill_refrele(recv_ill);
16703 		return;
16704 	}
16705 
16706 	if (ii->ipsec_in_v4) {
16707 		ipha = (ipha_t *)mp->b_rptr;
16708 		dst = ipha->ipha_dst;
16709 		if (CLASSD(dst)) {
16710 			/*
16711 			 * Multicast has to be delivered to all streams.
16712 			 */
16713 			dst = INADDR_BROADCAST;
16714 		}
16715 
16716 		if (ire == NULL) {
16717 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16718 			    MBLK_GETLABEL(mp));
16719 			if (ire == NULL) {
16720 				if (ill_need_rele)
16721 					ill_refrele(ill);
16722 				if (rill_need_rele)
16723 					ill_refrele(recv_ill);
16724 				ip1dbg(("ip_fanout_proto_again: "
16725 				    "IRE not found"));
16726 				freemsg(ipsec_mp);
16727 				return;
16728 			}
16729 			ire_need_rele = B_TRUE;
16730 		}
16731 
16732 		switch (ipha->ipha_protocol) {
16733 			case IPPROTO_UDP:
16734 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16735 				    recv_ill);
16736 				if (ire_need_rele)
16737 					ire_refrele(ire);
16738 				break;
16739 			case IPPROTO_TCP:
16740 				if (!ire_need_rele)
16741 					IRE_REFHOLD(ire);
16742 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16743 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16744 				IRE_REFRELE(ire);
16745 				if (mp != NULL)
16746 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16747 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16748 				break;
16749 			case IPPROTO_SCTP:
16750 				if (!ire_need_rele)
16751 					IRE_REFHOLD(ire);
16752 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16753 				    ipsec_mp, 0, ill->ill_rq, dst);
16754 				break;
16755 			default:
16756 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16757 				    recv_ill);
16758 				if (ire_need_rele)
16759 					ire_refrele(ire);
16760 				break;
16761 		}
16762 	} else {
16763 		uint32_t rput_flags = 0;
16764 
16765 		ip6h = (ip6_t *)mp->b_rptr;
16766 		v6dstp = &ip6h->ip6_dst;
16767 		/*
16768 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16769 		 * address.
16770 		 *
16771 		 * Currently, we don't store that state in the IPSEC_IN
16772 		 * message, and we may need to.
16773 		 */
16774 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16775 		    IP6_IN_LLMCAST : 0);
16776 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16777 		    NULL, NULL);
16778 	}
16779 	if (ill_need_rele)
16780 		ill_refrele(ill);
16781 	if (rill_need_rele)
16782 		ill_refrele(recv_ill);
16783 }
16784 
16785 /*
16786  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16787  * returns 'true' if there are still fragments left on the queue, in
16788  * which case we restart the timer.
16789  */
16790 void
16791 ill_frag_timer(void *arg)
16792 {
16793 	ill_t	*ill = (ill_t *)arg;
16794 	boolean_t frag_pending;
16795 
16796 	mutex_enter(&ill->ill_lock);
16797 	ASSERT(!ill->ill_fragtimer_executing);
16798 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16799 		ill->ill_frag_timer_id = 0;
16800 		mutex_exit(&ill->ill_lock);
16801 		return;
16802 	}
16803 	ill->ill_fragtimer_executing = 1;
16804 	mutex_exit(&ill->ill_lock);
16805 
16806 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
16807 
16808 	/*
16809 	 * Restart the timer, if we have fragments pending or if someone
16810 	 * wanted us to be scheduled again.
16811 	 */
16812 	mutex_enter(&ill->ill_lock);
16813 	ill->ill_fragtimer_executing = 0;
16814 	ill->ill_frag_timer_id = 0;
16815 	if (frag_pending || ill->ill_fragtimer_needrestart)
16816 		ill_frag_timer_start(ill);
16817 	mutex_exit(&ill->ill_lock);
16818 }
16819 
16820 void
16821 ill_frag_timer_start(ill_t *ill)
16822 {
16823 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16824 
16825 	/* If the ill is closing or opening don't proceed */
16826 	if (ill->ill_state_flags & ILL_CONDEMNED)
16827 		return;
16828 
16829 	if (ill->ill_fragtimer_executing) {
16830 		/*
16831 		 * ill_frag_timer is currently executing. Just record the
16832 		 * the fact that we want the timer to be restarted.
16833 		 * ill_frag_timer will post a timeout before it returns,
16834 		 * ensuring it will be called again.
16835 		 */
16836 		ill->ill_fragtimer_needrestart = 1;
16837 		return;
16838 	}
16839 
16840 	if (ill->ill_frag_timer_id == 0) {
16841 		/*
16842 		 * The timer is neither running nor is the timeout handler
16843 		 * executing. Post a timeout so that ill_frag_timer will be
16844 		 * called
16845 		 */
16846 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16847 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
16848 		ill->ill_fragtimer_needrestart = 0;
16849 	}
16850 }
16851 
16852 /*
16853  * This routine is needed for loopback when forwarding multicasts.
16854  *
16855  * IPQoS Notes:
16856  * IPPF processing is done in fanout routines.
16857  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16858  * processing for IPSec packets is done when it comes back in clear.
16859  * NOTE : The callers of this function need to do the ire_refrele for the
16860  *	  ire that is being passed in.
16861  */
16862 void
16863 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16864     ill_t *recv_ill)
16865 {
16866 	ill_t	*ill = (ill_t *)q->q_ptr;
16867 	uint32_t	sum;
16868 	uint32_t	u1;
16869 	uint32_t	u2;
16870 	int		hdr_length;
16871 	boolean_t	mctl_present;
16872 	mblk_t		*first_mp = mp;
16873 	mblk_t		*hada_mp = NULL;
16874 	ipha_t		*inner_ipha;
16875 
16876 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16877 	    "ip_rput_locl_start: q %p", q);
16878 
16879 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16880 
16881 
16882 #define	rptr	((uchar_t *)ipha)
16883 #define	iphs	((uint16_t *)ipha)
16884 
16885 	/*
16886 	 * no UDP or TCP packet should come here anymore.
16887 	 */
16888 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16889 	    (ipha->ipha_protocol != IPPROTO_UDP));
16890 
16891 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16892 	if (mctl_present &&
16893 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16894 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16895 
16896 		/*
16897 		 * It's an IPsec accelerated packet.
16898 		 * Keep a pointer to the data attributes around until
16899 		 * we allocate the ipsec_info_t.
16900 		 */
16901 		IPSECHW_DEBUG(IPSECHW_PKT,
16902 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16903 		hada_mp = first_mp;
16904 		hada_mp->b_cont = NULL;
16905 		/*
16906 		 * Since it is accelerated, it comes directly from
16907 		 * the ill and the data attributes is followed by
16908 		 * the packet data.
16909 		 */
16910 		ASSERT(mp->b_datap->db_type != M_CTL);
16911 		first_mp = mp;
16912 		mctl_present = B_FALSE;
16913 	}
16914 
16915 	/*
16916 	 * IF M_CTL is not present, then ipsec_in_is_secure
16917 	 * should return B_TRUE. There is a case where loopback
16918 	 * packets has an M_CTL in the front with all the
16919 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16920 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16921 	 * packets never comes here, it is safe to ASSERT the
16922 	 * following.
16923 	 */
16924 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16925 
16926 
16927 	/* u1 is # words of IP options */
16928 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16929 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16930 
16931 	if (u1) {
16932 		if (!ip_options_cksum(q, mp, ipha, ire)) {
16933 			if (hada_mp != NULL)
16934 				freemsg(hada_mp);
16935 			return;
16936 		}
16937 	} else {
16938 		/* Check the IP header checksum.  */
16939 #define	uph	((uint16_t *)ipha)
16940 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16941 		    uph[6] + uph[7] + uph[8] + uph[9];
16942 #undef  uph
16943 		/* finish doing IP checksum */
16944 		sum = (sum & 0xFFFF) + (sum >> 16);
16945 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16946 		/*
16947 		 * Don't verify header checksum if this packet is coming
16948 		 * back from AH/ESP as we already did it.
16949 		 */
16950 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16951 			BUMP_MIB(&ip_mib, ipInCksumErrs);
16952 			goto drop_pkt;
16953 		}
16954 	}
16955 
16956 	/*
16957 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16958 	 * might be called more than once for secure packets, count only
16959 	 * the first time.
16960 	 */
16961 	if (!mctl_present) {
16962 		UPDATE_IB_PKT_COUNT(ire);
16963 		ire->ire_last_used_time = lbolt;
16964 	}
16965 
16966 	/* Check for fragmentation offset. */
16967 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16968 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16969 	if (u1) {
16970 		/*
16971 		 * We re-assemble fragments before we do the AH/ESP
16972 		 * processing. Thus, M_CTL should not be present
16973 		 * while we are re-assembling.
16974 		 */
16975 		ASSERT(!mctl_present);
16976 		ASSERT(first_mp == mp);
16977 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16978 			return;
16979 		}
16980 		/*
16981 		 * Make sure that first_mp points back to mp as
16982 		 * the mp we came in with could have changed in
16983 		 * ip_rput_fragment().
16984 		 */
16985 		ipha = (ipha_t *)mp->b_rptr;
16986 		first_mp = mp;
16987 	}
16988 
16989 	/*
16990 	 * Clear hardware checksumming flag as it is currently only
16991 	 * used by TCP and UDP.
16992 	 */
16993 	DB_CKSUMFLAGS(mp) = 0;
16994 
16995 	/* Now we have a complete datagram, destined for this machine. */
16996 	u1 = IPH_HDR_LENGTH(ipha);
16997 	switch (ipha->ipha_protocol) {
16998 	case IPPROTO_ICMP: {
16999 		ire_t		*ire_zone;
17000 		ilm_t		*ilm;
17001 		mblk_t		*mp1;
17002 		zoneid_t	last_zoneid;
17003 
17004 		if (CLASSD(ipha->ipha_dst) &&
17005 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17006 			ASSERT(ire->ire_type == IRE_BROADCAST);
17007 			/*
17008 			 * In the multicast case, applications may have joined
17009 			 * the group from different zones, so we need to deliver
17010 			 * the packet to each of them. Loop through the
17011 			 * multicast memberships structures (ilm) on the receive
17012 			 * ill and send a copy of the packet up each matching
17013 			 * one. However, we don't do this for multicasts sent on
17014 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17015 			 * they must stay in the sender's zone.
17016 			 *
17017 			 * ilm_add_v6() ensures that ilms in the same zone are
17018 			 * contiguous in the ill_ilm list. We use this property
17019 			 * to avoid sending duplicates needed when two
17020 			 * applications in the same zone join the same group on
17021 			 * different logical interfaces: we ignore the ilm if
17022 			 * its zoneid is the same as the last matching one.
17023 			 * In addition, the sending of the packet for
17024 			 * ire_zoneid is delayed until all of the other ilms
17025 			 * have been exhausted.
17026 			 */
17027 			last_zoneid = -1;
17028 			ILM_WALKER_HOLD(recv_ill);
17029 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17030 			    ilm = ilm->ilm_next) {
17031 				if ((ilm->ilm_flags & ILM_DELETED) ||
17032 				    ipha->ipha_dst != ilm->ilm_addr ||
17033 				    ilm->ilm_zoneid == last_zoneid ||
17034 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17035 				    ilm->ilm_zoneid == ALL_ZONES ||
17036 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17037 					continue;
17038 				mp1 = ip_copymsg(first_mp);
17039 				if (mp1 == NULL)
17040 					continue;
17041 				icmp_inbound(q, mp1, B_TRUE, ill,
17042 				    0, sum, mctl_present, B_TRUE,
17043 				    recv_ill, ilm->ilm_zoneid);
17044 				last_zoneid = ilm->ilm_zoneid;
17045 			}
17046 			ILM_WALKER_RELE(recv_ill);
17047 		} else if (ire->ire_type == IRE_BROADCAST) {
17048 			/*
17049 			 * In the broadcast case, there may be many zones
17050 			 * which need a copy of the packet delivered to them.
17051 			 * There is one IRE_BROADCAST per broadcast address
17052 			 * and per zone; we walk those using a helper function.
17053 			 * In addition, the sending of the packet for ire is
17054 			 * delayed until all of the other ires have been
17055 			 * processed.
17056 			 */
17057 			IRB_REFHOLD(ire->ire_bucket);
17058 			ire_zone = NULL;
17059 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17060 			    ire)) != NULL) {
17061 				mp1 = ip_copymsg(first_mp);
17062 				if (mp1 == NULL)
17063 					continue;
17064 
17065 				UPDATE_IB_PKT_COUNT(ire_zone);
17066 				ire_zone->ire_last_used_time = lbolt;
17067 				icmp_inbound(q, mp1, B_TRUE, ill,
17068 				    0, sum, mctl_present, B_TRUE,
17069 				    recv_ill, ire_zone->ire_zoneid);
17070 			}
17071 			IRB_REFRELE(ire->ire_bucket);
17072 		}
17073 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17074 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17075 		    ire->ire_zoneid);
17076 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17077 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17078 		return;
17079 	}
17080 	case IPPROTO_IGMP:
17081 		/*
17082 		 * If we are not willing to accept IGMP packets in clear,
17083 		 * then check with global policy.
17084 		 */
17085 		if (igmp_accept_clear_messages == 0) {
17086 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17087 			    ipha, NULL, mctl_present);
17088 			if (first_mp == NULL)
17089 				return;
17090 		}
17091 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17092 			freemsg(first_mp);
17093 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17094 			BUMP_MIB(&ip_mib, ipInDiscards);
17095 			return;
17096 		}
17097 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17098 			/* Bad packet - discarded by igmp_input */
17099 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17100 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17101 			if (mctl_present)
17102 				freeb(first_mp);
17103 			return;
17104 		}
17105 		/*
17106 		 * igmp_input() may have returned the pulled up message.
17107 		 * So first_mp and ipha need to be reinitialized.
17108 		 */
17109 		ipha = (ipha_t *)mp->b_rptr;
17110 		if (mctl_present)
17111 			first_mp->b_cont = mp;
17112 		else
17113 			first_mp = mp;
17114 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17115 			/* No user-level listener for IGMP packets */
17116 			goto drop_pkt;
17117 		}
17118 		/* deliver to local raw users */
17119 		break;
17120 	case IPPROTO_PIM:
17121 		/*
17122 		 * If we are not willing to accept PIM packets in clear,
17123 		 * then check with global policy.
17124 		 */
17125 		if (pim_accept_clear_messages == 0) {
17126 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17127 			    ipha, NULL, mctl_present);
17128 			if (first_mp == NULL)
17129 				return;
17130 		}
17131 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17132 			freemsg(first_mp);
17133 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17134 			BUMP_MIB(&ip_mib, ipInDiscards);
17135 			return;
17136 		}
17137 		if (pim_input(q, mp) != 0) {
17138 			/* Bad packet - discarded by pim_input */
17139 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17140 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17141 			if (mctl_present)
17142 				freeb(first_mp);
17143 			return;
17144 		}
17145 
17146 		/*
17147 		 * pim_input() may have pulled up the message so ipha needs to
17148 		 * be reinitialized.
17149 		 */
17150 		ipha = (ipha_t *)mp->b_rptr;
17151 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17152 			/* No user-level listener for PIM packets */
17153 			goto drop_pkt;
17154 		}
17155 		/* deliver to local raw users */
17156 		break;
17157 	case IPPROTO_ENCAP:
17158 		/*
17159 		 * Handle self-encapsulated packets (IP-in-IP where
17160 		 * the inner addresses == the outer addresses).
17161 		 */
17162 		hdr_length = IPH_HDR_LENGTH(ipha);
17163 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17164 		    mp->b_wptr) {
17165 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17166 			    sizeof (ipha_t) - mp->b_rptr)) {
17167 				BUMP_MIB(&ip_mib, ipInDiscards);
17168 				freemsg(first_mp);
17169 				return;
17170 			}
17171 			ipha = (ipha_t *)mp->b_rptr;
17172 		}
17173 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17174 		/*
17175 		 * Check the sanity of the inner IP header.
17176 		 */
17177 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17178 			BUMP_MIB(&ip_mib, ipInDiscards);
17179 			freemsg(first_mp);
17180 			return;
17181 		}
17182 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17183 			BUMP_MIB(&ip_mib, ipInDiscards);
17184 			freemsg(first_mp);
17185 			return;
17186 		}
17187 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17188 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17189 			ipsec_in_t *ii;
17190 
17191 			/*
17192 			 * Self-encapsulated tunnel packet. Remove
17193 			 * the outer IP header and fanout again.
17194 			 * We also need to make sure that the inner
17195 			 * header is pulled up until options.
17196 			 */
17197 			mp->b_rptr = (uchar_t *)inner_ipha;
17198 			ipha = inner_ipha;
17199 			hdr_length = IPH_HDR_LENGTH(ipha);
17200 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17201 				if (!pullupmsg(mp, (uchar_t *)ipha +
17202 				    + hdr_length - mp->b_rptr)) {
17203 					freemsg(first_mp);
17204 					return;
17205 				}
17206 				ipha = (ipha_t *)mp->b_rptr;
17207 			}
17208 			if (!mctl_present) {
17209 				ASSERT(first_mp == mp);
17210 				/*
17211 				 * This means that somebody is sending
17212 				 * Self-encapsualted packets without AH/ESP.
17213 				 * If AH/ESP was present, we would have already
17214 				 * allocated the first_mp.
17215 				 */
17216 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17217 				    NULL) {
17218 					ip1dbg(("ip_proto_input: IPSEC_IN "
17219 					    "allocation failure.\n"));
17220 					BUMP_MIB(&ip_mib, ipInDiscards);
17221 					freemsg(mp);
17222 					return;
17223 				}
17224 				first_mp->b_cont = mp;
17225 			}
17226 			/*
17227 			 * We generally store the ill_index if we need to
17228 			 * do IPSEC processing as we lose the ill queue when
17229 			 * we come back. But in this case, we never should
17230 			 * have to store the ill_index here as it should have
17231 			 * been stored previously when we processed the
17232 			 * AH/ESP header in this routine or for non-ipsec
17233 			 * cases, we still have the queue. But for some bad
17234 			 * packets from the wire, we can get to IPSEC after
17235 			 * this and we better store the index for that case.
17236 			 */
17237 			ill = (ill_t *)q->q_ptr;
17238 			ii = (ipsec_in_t *)first_mp->b_rptr;
17239 			ii->ipsec_in_ill_index =
17240 			    ill->ill_phyint->phyint_ifindex;
17241 			ii->ipsec_in_rill_index =
17242 			    recv_ill->ill_phyint->phyint_ifindex;
17243 			if (ii->ipsec_in_decaps) {
17244 				/*
17245 				 * This packet is self-encapsulated multiple
17246 				 * times. We don't want to recurse infinitely.
17247 				 * To keep it simple, drop the packet.
17248 				 */
17249 				BUMP_MIB(&ip_mib, ipInDiscards);
17250 				freemsg(first_mp);
17251 				return;
17252 			}
17253 			ii->ipsec_in_decaps = B_TRUE;
17254 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17255 			    ire);
17256 			return;
17257 		}
17258 		break;
17259 	case IPPROTO_AH:
17260 	case IPPROTO_ESP: {
17261 		/*
17262 		 * Fast path for AH/ESP. If this is the first time
17263 		 * we are sending a datagram to AH/ESP, allocate
17264 		 * a IPSEC_IN message and prepend it. Otherwise,
17265 		 * just fanout.
17266 		 */
17267 
17268 		int ipsec_rc;
17269 		ipsec_in_t *ii;
17270 
17271 		IP_STAT(ipsec_proto_ahesp);
17272 		if (!mctl_present) {
17273 			ASSERT(first_mp == mp);
17274 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17275 				ip1dbg(("ip_proto_input: IPSEC_IN "
17276 				    "allocation failure.\n"));
17277 				freemsg(hada_mp); /* okay ifnull */
17278 				BUMP_MIB(&ip_mib, ipInDiscards);
17279 				freemsg(mp);
17280 				return;
17281 			}
17282 			/*
17283 			 * Store the ill_index so that when we come back
17284 			 * from IPSEC we ride on the same queue.
17285 			 */
17286 			ill = (ill_t *)q->q_ptr;
17287 			ii = (ipsec_in_t *)first_mp->b_rptr;
17288 			ii->ipsec_in_ill_index =
17289 			    ill->ill_phyint->phyint_ifindex;
17290 			ii->ipsec_in_rill_index =
17291 			    recv_ill->ill_phyint->phyint_ifindex;
17292 			first_mp->b_cont = mp;
17293 			/*
17294 			 * Cache hardware acceleration info.
17295 			 */
17296 			if (hada_mp != NULL) {
17297 				IPSECHW_DEBUG(IPSECHW_PKT,
17298 				    ("ip_rput_local: caching data attr.\n"));
17299 				ii->ipsec_in_accelerated = B_TRUE;
17300 				ii->ipsec_in_da = hada_mp;
17301 				hada_mp = NULL;
17302 			}
17303 		} else {
17304 			ii = (ipsec_in_t *)first_mp->b_rptr;
17305 		}
17306 
17307 		if (!ipsec_loaded()) {
17308 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17309 			    ire->ire_zoneid);
17310 			return;
17311 		}
17312 
17313 		/* select inbound SA and have IPsec process the pkt */
17314 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17315 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17316 			if (esph == NULL)
17317 				return;
17318 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17319 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17320 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17321 			    first_mp, esph);
17322 		} else {
17323 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17324 			if (ah == NULL)
17325 				return;
17326 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17327 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17328 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17329 			    first_mp, ah);
17330 		}
17331 
17332 		switch (ipsec_rc) {
17333 		case IPSEC_STATUS_SUCCESS:
17334 			break;
17335 		case IPSEC_STATUS_FAILED:
17336 			BUMP_MIB(&ip_mib, ipInDiscards);
17337 			/* FALLTHRU */
17338 		case IPSEC_STATUS_PENDING:
17339 			return;
17340 		}
17341 		/* we're done with IPsec processing, send it up */
17342 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17343 		return;
17344 	}
17345 	default:
17346 		break;
17347 	}
17348 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17349 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17350 		    ire->ire_zoneid));
17351 		goto drop_pkt;
17352 	}
17353 	/*
17354 	 * Handle protocols with which IP is less intimate.  There
17355 	 * can be more than one stream bound to a particular
17356 	 * protocol.  When this is the case, each one gets a copy
17357 	 * of any incoming packets.
17358 	 */
17359 	ip_fanout_proto(q, first_mp, ill, ipha,
17360 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17361 	    B_TRUE, recv_ill, ire->ire_zoneid);
17362 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17363 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17364 	return;
17365 
17366 drop_pkt:
17367 	freemsg(first_mp);
17368 	if (hada_mp != NULL)
17369 		freeb(hada_mp);
17370 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17371 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17372 #undef	rptr
17373 #undef  iphs
17374 
17375 }
17376 
17377 /*
17378  * Update any source route, record route or timestamp options.
17379  * Check that we are at end of strict source route.
17380  * The options have already been checked for sanity in ip_rput_options().
17381  */
17382 static boolean_t
17383 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17384 {
17385 	ipoptp_t	opts;
17386 	uchar_t		*opt;
17387 	uint8_t		optval;
17388 	uint8_t		optlen;
17389 	ipaddr_t	dst;
17390 	uint32_t	ts;
17391 	ire_t		*dst_ire;
17392 	timestruc_t	now;
17393 	zoneid_t	zoneid;
17394 	ill_t		*ill;
17395 
17396 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17397 
17398 	ip2dbg(("ip_rput_local_options\n"));
17399 
17400 	for (optval = ipoptp_first(&opts, ipha);
17401 	    optval != IPOPT_EOL;
17402 	    optval = ipoptp_next(&opts)) {
17403 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17404 		opt = opts.ipoptp_cur;
17405 		optlen = opts.ipoptp_len;
17406 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17407 		    optval, optlen));
17408 		switch (optval) {
17409 			uint32_t off;
17410 		case IPOPT_SSRR:
17411 		case IPOPT_LSRR:
17412 			off = opt[IPOPT_OFFSET];
17413 			off--;
17414 			if (optlen < IP_ADDR_LEN ||
17415 			    off > optlen - IP_ADDR_LEN) {
17416 				/* End of source route */
17417 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17418 				break;
17419 			}
17420 			/*
17421 			 * This will only happen if two consecutive entries
17422 			 * in the source route contains our address or if
17423 			 * it is a packet with a loose source route which
17424 			 * reaches us before consuming the whole source route
17425 			 */
17426 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17427 			if (optval == IPOPT_SSRR) {
17428 				goto bad_src_route;
17429 			}
17430 			/*
17431 			 * Hack: instead of dropping the packet truncate the
17432 			 * source route to what has been used by filling the
17433 			 * rest with IPOPT_NOP.
17434 			 */
17435 			opt[IPOPT_OLEN] = (uint8_t)off;
17436 			while (off < optlen) {
17437 				opt[off++] = IPOPT_NOP;
17438 			}
17439 			break;
17440 		case IPOPT_RR:
17441 			off = opt[IPOPT_OFFSET];
17442 			off--;
17443 			if (optlen < IP_ADDR_LEN ||
17444 			    off > optlen - IP_ADDR_LEN) {
17445 				/* No more room - ignore */
17446 				ip1dbg((
17447 				    "ip_rput_local_options: end of RR\n"));
17448 				break;
17449 			}
17450 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17451 			    IP_ADDR_LEN);
17452 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17453 			break;
17454 		case IPOPT_TS:
17455 			/* Insert timestamp if there is romm */
17456 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17457 			case IPOPT_TS_TSONLY:
17458 				off = IPOPT_TS_TIMELEN;
17459 				break;
17460 			case IPOPT_TS_PRESPEC:
17461 			case IPOPT_TS_PRESPEC_RFC791:
17462 				/* Verify that the address matched */
17463 				off = opt[IPOPT_OFFSET] - 1;
17464 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17465 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17466 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17467 				if (dst_ire == NULL) {
17468 					/* Not for us */
17469 					break;
17470 				}
17471 				ire_refrele(dst_ire);
17472 				/* FALLTHRU */
17473 			case IPOPT_TS_TSANDADDR:
17474 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17475 				break;
17476 			default:
17477 				/*
17478 				 * ip_*put_options should have already
17479 				 * dropped this packet.
17480 				 */
17481 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17482 				    "unknown IT - bug in ip_rput_options?\n");
17483 				return (B_TRUE);	/* Keep "lint" happy */
17484 			}
17485 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17486 				/* Increase overflow counter */
17487 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17488 				opt[IPOPT_POS_OV_FLG] =
17489 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17490 				    (off << 4));
17491 				break;
17492 			}
17493 			off = opt[IPOPT_OFFSET] - 1;
17494 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17495 			case IPOPT_TS_PRESPEC:
17496 			case IPOPT_TS_PRESPEC_RFC791:
17497 			case IPOPT_TS_TSANDADDR:
17498 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17499 				    IP_ADDR_LEN);
17500 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17501 				/* FALLTHRU */
17502 			case IPOPT_TS_TSONLY:
17503 				off = opt[IPOPT_OFFSET] - 1;
17504 				/* Compute # of milliseconds since midnight */
17505 				gethrestime(&now);
17506 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17507 				    now.tv_nsec / (NANOSEC / MILLISEC);
17508 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17509 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17510 				break;
17511 			}
17512 			break;
17513 		}
17514 	}
17515 	return (B_TRUE);
17516 
17517 bad_src_route:
17518 	q = WR(q);
17519 	if (q->q_next != NULL)
17520 		ill = q->q_ptr;
17521 	else
17522 		ill = NULL;
17523 
17524 	/* make sure we clear any indication of a hardware checksum */
17525 	DB_CKSUMFLAGS(mp) = 0;
17526 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17527 	if (zoneid == ALL_ZONES)
17528 		freemsg(mp);
17529 	else
17530 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17531 	return (B_FALSE);
17532 
17533 }
17534 
17535 /*
17536  * Process IP options in an inbound packet.  If an option affects the
17537  * effective destination address, return the next hop address via dstp.
17538  * Returns -1 if something fails in which case an ICMP error has been sent
17539  * and mp freed.
17540  */
17541 static int
17542 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17543 {
17544 	ipoptp_t	opts;
17545 	uchar_t		*opt;
17546 	uint8_t		optval;
17547 	uint8_t		optlen;
17548 	ipaddr_t	dst;
17549 	intptr_t	code = 0;
17550 	ire_t		*ire = NULL;
17551 	zoneid_t	zoneid;
17552 	ill_t		*ill;
17553 
17554 	ip2dbg(("ip_rput_options\n"));
17555 	dst = ipha->ipha_dst;
17556 	for (optval = ipoptp_first(&opts, ipha);
17557 	    optval != IPOPT_EOL;
17558 	    optval = ipoptp_next(&opts)) {
17559 		opt = opts.ipoptp_cur;
17560 		optlen = opts.ipoptp_len;
17561 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17562 		    optval, optlen));
17563 		/*
17564 		 * Note: we need to verify the checksum before we
17565 		 * modify anything thus this routine only extracts the next
17566 		 * hop dst from any source route.
17567 		 */
17568 		switch (optval) {
17569 			uint32_t off;
17570 		case IPOPT_SSRR:
17571 		case IPOPT_LSRR:
17572 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17573 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17574 			if (ire == NULL) {
17575 				if (optval == IPOPT_SSRR) {
17576 					ip1dbg(("ip_rput_options: not next"
17577 					    " strict source route 0x%x\n",
17578 					    ntohl(dst)));
17579 					code = (char *)&ipha->ipha_dst -
17580 					    (char *)ipha;
17581 					goto param_prob; /* RouterReq's */
17582 				}
17583 				ip2dbg(("ip_rput_options: "
17584 				    "not next source route 0x%x\n",
17585 				    ntohl(dst)));
17586 				break;
17587 			}
17588 			ire_refrele(ire);
17589 
17590 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17591 				ip1dbg((
17592 				    "ip_rput_options: bad option offset\n"));
17593 				code = (char *)&opt[IPOPT_OLEN] -
17594 				    (char *)ipha;
17595 				goto param_prob;
17596 			}
17597 			off = opt[IPOPT_OFFSET];
17598 			off--;
17599 		redo_srr:
17600 			if (optlen < IP_ADDR_LEN ||
17601 			    off > optlen - IP_ADDR_LEN) {
17602 				/* End of source route */
17603 				ip1dbg(("ip_rput_options: end of SR\n"));
17604 				break;
17605 			}
17606 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17607 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17608 			    ntohl(dst)));
17609 
17610 			/*
17611 			 * Check if our address is present more than
17612 			 * once as consecutive hops in source route.
17613 			 * XXX verify per-interface ip_forwarding
17614 			 * for source route?
17615 			 */
17616 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17617 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17618 
17619 			if (ire != NULL) {
17620 				ire_refrele(ire);
17621 				off += IP_ADDR_LEN;
17622 				goto redo_srr;
17623 			}
17624 
17625 			if (dst == htonl(INADDR_LOOPBACK)) {
17626 				ip1dbg(("ip_rput_options: loopback addr in "
17627 				    "source route!\n"));
17628 				goto bad_src_route;
17629 			}
17630 			/*
17631 			 * For strict: verify that dst is directly
17632 			 * reachable.
17633 			 */
17634 			if (optval == IPOPT_SSRR) {
17635 				ire = ire_ftable_lookup(dst, 0, 0,
17636 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17637 				    MBLK_GETLABEL(mp),
17638 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17639 				if (ire == NULL) {
17640 					ip1dbg(("ip_rput_options: SSRR not "
17641 					    "directly reachable: 0x%x\n",
17642 					    ntohl(dst)));
17643 					goto bad_src_route;
17644 				}
17645 				ire_refrele(ire);
17646 			}
17647 			/*
17648 			 * Defer update of the offset and the record route
17649 			 * until the packet is forwarded.
17650 			 */
17651 			break;
17652 		case IPOPT_RR:
17653 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17654 				ip1dbg((
17655 				    "ip_rput_options: bad option offset\n"));
17656 				code = (char *)&opt[IPOPT_OLEN] -
17657 				    (char *)ipha;
17658 				goto param_prob;
17659 			}
17660 			break;
17661 		case IPOPT_TS:
17662 			/*
17663 			 * Verify that length >= 5 and that there is either
17664 			 * room for another timestamp or that the overflow
17665 			 * counter is not maxed out.
17666 			 */
17667 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17668 			if (optlen < IPOPT_MINLEN_IT) {
17669 				goto param_prob;
17670 			}
17671 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17672 				ip1dbg((
17673 				    "ip_rput_options: bad option offset\n"));
17674 				code = (char *)&opt[IPOPT_OFFSET] -
17675 				    (char *)ipha;
17676 				goto param_prob;
17677 			}
17678 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17679 			case IPOPT_TS_TSONLY:
17680 				off = IPOPT_TS_TIMELEN;
17681 				break;
17682 			case IPOPT_TS_TSANDADDR:
17683 			case IPOPT_TS_PRESPEC:
17684 			case IPOPT_TS_PRESPEC_RFC791:
17685 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17686 				break;
17687 			default:
17688 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17689 				    (char *)ipha;
17690 				goto param_prob;
17691 			}
17692 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17693 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17694 				/*
17695 				 * No room and the overflow counter is 15
17696 				 * already.
17697 				 */
17698 				goto param_prob;
17699 			}
17700 			break;
17701 		}
17702 	}
17703 
17704 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17705 		*dstp = dst;
17706 		return (0);
17707 	}
17708 
17709 	ip1dbg(("ip_rput_options: error processing IP options."));
17710 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17711 
17712 param_prob:
17713 	q = WR(q);
17714 	if (q->q_next != NULL)
17715 		ill = q->q_ptr;
17716 	else
17717 		ill = NULL;
17718 
17719 	/* make sure we clear any indication of a hardware checksum */
17720 	DB_CKSUMFLAGS(mp) = 0;
17721 	/* Don't know whether this is for non-global or global/forwarding */
17722 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17723 	if (zoneid == ALL_ZONES)
17724 		freemsg(mp);
17725 	else
17726 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
17727 	return (-1);
17728 
17729 bad_src_route:
17730 	q = WR(q);
17731 	if (q->q_next != NULL)
17732 		ill = q->q_ptr;
17733 	else
17734 		ill = NULL;
17735 
17736 	/* make sure we clear any indication of a hardware checksum */
17737 	DB_CKSUMFLAGS(mp) = 0;
17738 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
17739 	if (zoneid == ALL_ZONES)
17740 		freemsg(mp);
17741 	else
17742 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17743 	return (-1);
17744 }
17745 
17746 /*
17747  * IP & ICMP info in >=14 msg's ...
17748  *  - ip fixed part (mib2_ip_t)
17749  *  - icmp fixed part (mib2_icmp_t)
17750  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17751  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17752  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17753  *  - ipRouteAttributeTable (ip 102)	labeled routes
17754  *  - ip multicast membership (ip_member_t)
17755  *  - ip multicast source filtering (ip_grpsrc_t)
17756  *  - igmp fixed part (struct igmpstat)
17757  *  - multicast routing stats (struct mrtstat)
17758  *  - multicast routing vifs (array of struct vifctl)
17759  *  - multicast routing routes (array of struct mfcctl)
17760  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17761  *					One per ill plus one generic
17762  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17763  *					One per ill plus one generic
17764  *  - ipv6RouteEntry			all IPv6 IREs
17765  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17766  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17767  *  - ipv6AddrEntry			all IPv6 ipifs
17768  *  - ipv6 multicast membership (ipv6_member_t)
17769  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17770  *
17771  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17772  *
17773  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17774  * already filled in by the caller.
17775  * Return value of 0 indicates that no messages were sent and caller
17776  * should free mpctl.
17777  */
17778 int
17779 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17780 {
17781 
17782 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17783 		return (0);
17784 	}
17785 
17786 	if ((mpctl = ip_snmp_get_mib2_ip(q, mpctl)) == NULL) {
17787 		return (1);
17788 	}
17789 
17790 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
17791 		return (1);
17792 	}
17793 
17794 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
17795 		return (1);
17796 	}
17797 
17798 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
17799 		return (1);
17800 	}
17801 
17802 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
17803 		return (1);
17804 	}
17805 
17806 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
17807 		return (1);
17808 	}
17809 
17810 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
17811 		return (1);
17812 	}
17813 
17814 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
17815 		return (1);
17816 	}
17817 
17818 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
17819 		return (1);
17820 	}
17821 
17822 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
17823 		return (1);
17824 	}
17825 
17826 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
17827 		return (1);
17828 	}
17829 
17830 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
17831 		return (1);
17832 	}
17833 
17834 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
17835 		return (1);
17836 	}
17837 
17838 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
17839 		return (1);
17840 	}
17841 
17842 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
17843 		return (1);
17844 	}
17845 
17846 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
17847 		return (1);
17848 	}
17849 
17850 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
17851 		return (1);
17852 	}
17853 	freemsg(mpctl);
17854 	return (1);
17855 }
17856 
17857 
17858 /* Get global IPv4 statistics */
17859 static mblk_t *
17860 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl)
17861 {
17862 	struct opthdr		*optp;
17863 	mblk_t			*mp2ctl;
17864 
17865 	/*
17866 	 * make a copy of the original message
17867 	 */
17868 	mp2ctl = copymsg(mpctl);
17869 
17870 	/* fixed length IP structure... */
17871 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17872 	optp->level = MIB2_IP;
17873 	optp->name = 0;
17874 	SET_MIB(ip_mib.ipForwarding,
17875 	    (WE_ARE_FORWARDING ? 1 : 2));
17876 	SET_MIB(ip_mib.ipDefaultTTL,
17877 	    (uint32_t)ip_def_ttl);
17878 	SET_MIB(ip_mib.ipReasmTimeout,
17879 	    ip_g_frag_timeout);
17880 	SET_MIB(ip_mib.ipAddrEntrySize,
17881 	    sizeof (mib2_ipAddrEntry_t));
17882 	SET_MIB(ip_mib.ipRouteEntrySize,
17883 	    sizeof (mib2_ipRouteEntry_t));
17884 	SET_MIB(ip_mib.ipNetToMediaEntrySize,
17885 	    sizeof (mib2_ipNetToMediaEntry_t));
17886 	SET_MIB(ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17887 	SET_MIB(ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17888 	SET_MIB(ip_mib.ipRouteAttributeSize, sizeof (mib2_ipAttributeEntry_t));
17889 	SET_MIB(ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17890 	if (!snmp_append_data(mpctl->b_cont, (char *)&ip_mib,
17891 	    (int)sizeof (ip_mib))) {
17892 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17893 		    (uint_t)sizeof (ip_mib)));
17894 	}
17895 
17896 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17897 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17898 	    (int)optp->level, (int)optp->name, (int)optp->len));
17899 	qreply(q, mpctl);
17900 	return (mp2ctl);
17901 }
17902 
17903 /* Global IPv4 ICMP statistics */
17904 static mblk_t *
17905 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
17906 {
17907 	struct opthdr		*optp;
17908 	mblk_t			*mp2ctl;
17909 
17910 	/*
17911 	 * Make a copy of the original message
17912 	 */
17913 	mp2ctl = copymsg(mpctl);
17914 
17915 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17916 	optp->level = MIB2_ICMP;
17917 	optp->name = 0;
17918 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
17919 	    (int)sizeof (icmp_mib))) {
17920 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
17921 		    (uint_t)sizeof (icmp_mib)));
17922 	}
17923 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17924 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
17925 	    (int)optp->level, (int)optp->name, (int)optp->len));
17926 	qreply(q, mpctl);
17927 	return (mp2ctl);
17928 }
17929 
17930 /* Global IPv4 IGMP statistics */
17931 static mblk_t *
17932 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
17933 {
17934 	struct opthdr		*optp;
17935 	mblk_t			*mp2ctl;
17936 
17937 	/*
17938 	 * make a copy of the original message
17939 	 */
17940 	mp2ctl = copymsg(mpctl);
17941 
17942 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17943 	optp->level = EXPER_IGMP;
17944 	optp->name = 0;
17945 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
17946 	    (int)sizeof (igmpstat))) {
17947 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
17948 		    (uint_t)sizeof (igmpstat)));
17949 	}
17950 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17951 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
17952 	    (int)optp->level, (int)optp->name, (int)optp->len));
17953 	qreply(q, mpctl);
17954 	return (mp2ctl);
17955 }
17956 
17957 /* Global IPv4 Multicast Routing statistics */
17958 static mblk_t *
17959 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
17960 {
17961 	struct opthdr		*optp;
17962 	mblk_t			*mp2ctl;
17963 
17964 	/*
17965 	 * make a copy of the original message
17966 	 */
17967 	mp2ctl = copymsg(mpctl);
17968 
17969 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17970 	optp->level = EXPER_DVMRP;
17971 	optp->name = 0;
17972 	if (!ip_mroute_stats(mpctl->b_cont)) {
17973 		ip0dbg(("ip_mroute_stats: failed\n"));
17974 	}
17975 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17976 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
17977 	    (int)optp->level, (int)optp->name, (int)optp->len));
17978 	qreply(q, mpctl);
17979 	return (mp2ctl);
17980 }
17981 
17982 /* IPv4 address information */
17983 static mblk_t *
17984 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
17985 {
17986 	struct opthdr		*optp;
17987 	mblk_t			*mp2ctl;
17988 	mblk_t			*mp_tail = NULL;
17989 	ill_t			*ill;
17990 	ipif_t			*ipif;
17991 	uint_t			bitval;
17992 	mib2_ipAddrEntry_t	mae;
17993 	zoneid_t		zoneid;
17994 	ill_walk_context_t ctx;
17995 
17996 	/*
17997 	 * make a copy of the original message
17998 	 */
17999 	mp2ctl = copymsg(mpctl);
18000 
18001 	/* ipAddrEntryTable */
18002 
18003 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18004 	optp->level = MIB2_IP;
18005 	optp->name = MIB2_IP_ADDR;
18006 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18007 
18008 	rw_enter(&ill_g_lock, RW_READER);
18009 	ill = ILL_START_WALK_V4(&ctx);
18010 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18011 		for (ipif = ill->ill_ipif; ipif != NULL;
18012 		    ipif = ipif->ipif_next) {
18013 			if (ipif->ipif_zoneid != zoneid &&
18014 			    ipif->ipif_zoneid != ALL_ZONES)
18015 				continue;
18016 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18017 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18018 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18019 
18020 			(void) ipif_get_name(ipif,
18021 			    mae.ipAdEntIfIndex.o_bytes,
18022 			    OCTET_LENGTH);
18023 			mae.ipAdEntIfIndex.o_length =
18024 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18025 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18026 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18027 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18028 			mae.ipAdEntInfo.ae_subnet_len =
18029 			    ip_mask_to_plen(ipif->ipif_net_mask);
18030 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18031 			for (bitval = 1;
18032 			    bitval &&
18033 			    !(bitval & ipif->ipif_brd_addr);
18034 			    bitval <<= 1)
18035 				noop;
18036 			mae.ipAdEntBcastAddr = bitval;
18037 			mae.ipAdEntReasmMaxSize = 65535;
18038 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18039 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18040 			mae.ipAdEntInfo.ae_broadcast_addr =
18041 			    ipif->ipif_brd_addr;
18042 			mae.ipAdEntInfo.ae_pp_dst_addr =
18043 			    ipif->ipif_pp_dst_addr;
18044 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18045 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18046 
18047 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18048 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18049 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18050 				    "allocate %u bytes\n",
18051 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18052 			}
18053 		}
18054 	}
18055 	rw_exit(&ill_g_lock);
18056 
18057 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18058 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18059 	    (int)optp->level, (int)optp->name, (int)optp->len));
18060 	qreply(q, mpctl);
18061 	return (mp2ctl);
18062 }
18063 
18064 /* IPv6 address information */
18065 static mblk_t *
18066 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18067 {
18068 	struct opthdr		*optp;
18069 	mblk_t			*mp2ctl;
18070 	mblk_t			*mp_tail = NULL;
18071 	ill_t			*ill;
18072 	ipif_t			*ipif;
18073 	mib2_ipv6AddrEntry_t	mae6;
18074 	zoneid_t		zoneid;
18075 	ill_walk_context_t	ctx;
18076 
18077 	/*
18078 	 * make a copy of the original message
18079 	 */
18080 	mp2ctl = copymsg(mpctl);
18081 
18082 	/* ipv6AddrEntryTable */
18083 
18084 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18085 	optp->level = MIB2_IP6;
18086 	optp->name = MIB2_IP6_ADDR;
18087 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18088 
18089 	rw_enter(&ill_g_lock, RW_READER);
18090 	ill = ILL_START_WALK_V6(&ctx);
18091 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18092 		for (ipif = ill->ill_ipif; ipif != NULL;
18093 		    ipif = ipif->ipif_next) {
18094 			if (ipif->ipif_zoneid != zoneid &&
18095 			    ipif->ipif_zoneid != ALL_ZONES)
18096 				continue;
18097 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18098 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18099 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18100 
18101 			(void) ipif_get_name(ipif,
18102 			    mae6.ipv6AddrIfIndex.o_bytes,
18103 			    OCTET_LENGTH);
18104 			mae6.ipv6AddrIfIndex.o_length =
18105 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18106 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18107 			mae6.ipv6AddrPfxLength =
18108 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18109 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18110 			mae6.ipv6AddrInfo.ae_subnet_len =
18111 			    mae6.ipv6AddrPfxLength;
18112 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18113 
18114 			/* Type: stateless(1), stateful(2), unknown(3) */
18115 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18116 				mae6.ipv6AddrType = 1;
18117 			else
18118 				mae6.ipv6AddrType = 2;
18119 			/* Anycast: true(1), false(2) */
18120 			if (ipif->ipif_flags & IPIF_ANYCAST)
18121 				mae6.ipv6AddrAnycastFlag = 1;
18122 			else
18123 				mae6.ipv6AddrAnycastFlag = 2;
18124 
18125 			/*
18126 			 * Address status: preferred(1), deprecated(2),
18127 			 * invalid(3), inaccessible(4), unknown(5)
18128 			 */
18129 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18130 				mae6.ipv6AddrStatus = 3;
18131 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18132 				mae6.ipv6AddrStatus = 2;
18133 			else
18134 				mae6.ipv6AddrStatus = 1;
18135 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18136 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18137 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18138 						ipif->ipif_v6pp_dst_addr;
18139 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18140 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18141 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18142 				(char *)&mae6,
18143 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18144 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18145 				    "allocate %u bytes\n",
18146 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18147 			}
18148 		}
18149 	}
18150 	rw_exit(&ill_g_lock);
18151 
18152 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18153 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18154 	    (int)optp->level, (int)optp->name, (int)optp->len));
18155 	qreply(q, mpctl);
18156 	return (mp2ctl);
18157 }
18158 
18159 /* IPv4 multicast group membership. */
18160 static mblk_t *
18161 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18162 {
18163 	struct opthdr		*optp;
18164 	mblk_t			*mp2ctl;
18165 	ill_t			*ill;
18166 	ipif_t			*ipif;
18167 	ilm_t			*ilm;
18168 	ip_member_t		ipm;
18169 	mblk_t			*mp_tail = NULL;
18170 	ill_walk_context_t	ctx;
18171 	zoneid_t		zoneid;
18172 
18173 	/*
18174 	 * make a copy of the original message
18175 	 */
18176 	mp2ctl = copymsg(mpctl);
18177 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18178 
18179 	/* ipGroupMember table */
18180 	optp = (struct opthdr *)&mpctl->b_rptr[
18181 	    sizeof (struct T_optmgmt_ack)];
18182 	optp->level = MIB2_IP;
18183 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18184 
18185 	rw_enter(&ill_g_lock, RW_READER);
18186 	ill = ILL_START_WALK_V4(&ctx);
18187 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18188 		ILM_WALKER_HOLD(ill);
18189 		for (ipif = ill->ill_ipif; ipif != NULL;
18190 		    ipif = ipif->ipif_next) {
18191 			if (ipif->ipif_zoneid != zoneid &&
18192 			    ipif->ipif_zoneid != ALL_ZONES)
18193 				continue;	/* not this zone */
18194 			(void) ipif_get_name(ipif,
18195 			    ipm.ipGroupMemberIfIndex.o_bytes,
18196 			    OCTET_LENGTH);
18197 			ipm.ipGroupMemberIfIndex.o_length =
18198 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18199 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18200 				ASSERT(ilm->ilm_ipif != NULL);
18201 				ASSERT(ilm->ilm_ill == NULL);
18202 				if (ilm->ilm_ipif != ipif)
18203 					continue;
18204 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18205 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18206 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18207 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18208 				    (char *)&ipm, (int)sizeof (ipm))) {
18209 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18210 					    "failed to allocate %u bytes\n",
18211 						(uint_t)sizeof (ipm)));
18212 				}
18213 			}
18214 		}
18215 		ILM_WALKER_RELE(ill);
18216 	}
18217 	rw_exit(&ill_g_lock);
18218 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18219 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18220 	    (int)optp->level, (int)optp->name, (int)optp->len));
18221 	qreply(q, mpctl);
18222 	return (mp2ctl);
18223 }
18224 
18225 /* IPv6 multicast group membership. */
18226 static mblk_t *
18227 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18228 {
18229 	struct opthdr		*optp;
18230 	mblk_t			*mp2ctl;
18231 	ill_t			*ill;
18232 	ilm_t			*ilm;
18233 	ipv6_member_t		ipm6;
18234 	mblk_t			*mp_tail = NULL;
18235 	ill_walk_context_t	ctx;
18236 	zoneid_t		zoneid;
18237 
18238 	/*
18239 	 * make a copy of the original message
18240 	 */
18241 	mp2ctl = copymsg(mpctl);
18242 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18243 
18244 	/* ip6GroupMember table */
18245 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18246 	optp->level = MIB2_IP6;
18247 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18248 
18249 	rw_enter(&ill_g_lock, RW_READER);
18250 	ill = ILL_START_WALK_V6(&ctx);
18251 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18252 		ILM_WALKER_HOLD(ill);
18253 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18254 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18255 			ASSERT(ilm->ilm_ipif == NULL);
18256 			ASSERT(ilm->ilm_ill != NULL);
18257 			if (ilm->ilm_zoneid != zoneid)
18258 				continue;	/* not this zone */
18259 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18260 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18261 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18262 			if (!snmp_append_data2(mpctl->b_cont,
18263 			    &mp_tail,
18264 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18265 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18266 				    "failed to allocate %u bytes\n",
18267 				    (uint_t)sizeof (ipm6)));
18268 			}
18269 		}
18270 		ILM_WALKER_RELE(ill);
18271 	}
18272 	rw_exit(&ill_g_lock);
18273 
18274 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18275 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18276 	    (int)optp->level, (int)optp->name, (int)optp->len));
18277 	qreply(q, mpctl);
18278 	return (mp2ctl);
18279 }
18280 
18281 /* IP multicast filtered sources */
18282 static mblk_t *
18283 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18284 {
18285 	struct opthdr		*optp;
18286 	mblk_t			*mp2ctl;
18287 	ill_t			*ill;
18288 	ipif_t			*ipif;
18289 	ilm_t			*ilm;
18290 	ip_grpsrc_t		ips;
18291 	mblk_t			*mp_tail = NULL;
18292 	ill_walk_context_t	ctx;
18293 	zoneid_t		zoneid;
18294 	int			i;
18295 	slist_t			*sl;
18296 
18297 	/*
18298 	 * make a copy of the original message
18299 	 */
18300 	mp2ctl = copymsg(mpctl);
18301 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18302 
18303 	/* ipGroupSource table */
18304 	optp = (struct opthdr *)&mpctl->b_rptr[
18305 	    sizeof (struct T_optmgmt_ack)];
18306 	optp->level = MIB2_IP;
18307 	optp->name = EXPER_IP_GROUP_SOURCES;
18308 
18309 	rw_enter(&ill_g_lock, RW_READER);
18310 	ill = ILL_START_WALK_V4(&ctx);
18311 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18312 		ILM_WALKER_HOLD(ill);
18313 		for (ipif = ill->ill_ipif; ipif != NULL;
18314 		    ipif = ipif->ipif_next) {
18315 			if (ipif->ipif_zoneid != zoneid)
18316 				continue;	/* not this zone */
18317 			(void) ipif_get_name(ipif,
18318 			    ips.ipGroupSourceIfIndex.o_bytes,
18319 			    OCTET_LENGTH);
18320 			ips.ipGroupSourceIfIndex.o_length =
18321 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18322 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18323 				ASSERT(ilm->ilm_ipif != NULL);
18324 				ASSERT(ilm->ilm_ill == NULL);
18325 				sl = ilm->ilm_filter;
18326 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18327 					continue;
18328 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18329 				for (i = 0; i < sl->sl_numsrc; i++) {
18330 					if (!IN6_IS_ADDR_V4MAPPED(
18331 					    &sl->sl_addr[i]))
18332 						continue;
18333 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18334 					    ips.ipGroupSourceAddress);
18335 					if (snmp_append_data2(mpctl->b_cont,
18336 					    &mp_tail, (char *)&ips,
18337 					    (int)sizeof (ips)) == 0) {
18338 						ip1dbg(("ip_snmp_get_mib2_"
18339 						    "ip_group_src: failed to "
18340 						    "allocate %u bytes\n",
18341 						    (uint_t)sizeof (ips)));
18342 					}
18343 				}
18344 			}
18345 		}
18346 		ILM_WALKER_RELE(ill);
18347 	}
18348 	rw_exit(&ill_g_lock);
18349 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18350 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18351 	    (int)optp->level, (int)optp->name, (int)optp->len));
18352 	qreply(q, mpctl);
18353 	return (mp2ctl);
18354 }
18355 
18356 /* IPv6 multicast filtered sources. */
18357 static mblk_t *
18358 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18359 {
18360 	struct opthdr		*optp;
18361 	mblk_t			*mp2ctl;
18362 	ill_t			*ill;
18363 	ilm_t			*ilm;
18364 	ipv6_grpsrc_t		ips6;
18365 	mblk_t			*mp_tail = NULL;
18366 	ill_walk_context_t	ctx;
18367 	zoneid_t		zoneid;
18368 	int			i;
18369 	slist_t			*sl;
18370 
18371 	/*
18372 	 * make a copy of the original message
18373 	 */
18374 	mp2ctl = copymsg(mpctl);
18375 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18376 
18377 	/* ip6GroupMember table */
18378 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18379 	optp->level = MIB2_IP6;
18380 	optp->name = EXPER_IP6_GROUP_SOURCES;
18381 
18382 	rw_enter(&ill_g_lock, RW_READER);
18383 	ill = ILL_START_WALK_V6(&ctx);
18384 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18385 		ILM_WALKER_HOLD(ill);
18386 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18387 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18388 			ASSERT(ilm->ilm_ipif == NULL);
18389 			ASSERT(ilm->ilm_ill != NULL);
18390 			sl = ilm->ilm_filter;
18391 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18392 				continue;
18393 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18394 			for (i = 0; i < sl->sl_numsrc; i++) {
18395 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18396 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18397 				    (char *)&ips6, (int)sizeof (ips6))) {
18398 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18399 					    "group_src: failed to allocate "
18400 					    "%u bytes\n",
18401 					    (uint_t)sizeof (ips6)));
18402 				}
18403 			}
18404 		}
18405 		ILM_WALKER_RELE(ill);
18406 	}
18407 	rw_exit(&ill_g_lock);
18408 
18409 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18410 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18411 	    (int)optp->level, (int)optp->name, (int)optp->len));
18412 	qreply(q, mpctl);
18413 	return (mp2ctl);
18414 }
18415 
18416 /* Multicast routing virtual interface table. */
18417 static mblk_t *
18418 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18419 {
18420 	struct opthdr		*optp;
18421 	mblk_t			*mp2ctl;
18422 
18423 	/*
18424 	 * make a copy of the original message
18425 	 */
18426 	mp2ctl = copymsg(mpctl);
18427 
18428 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18429 	optp->level = EXPER_DVMRP;
18430 	optp->name = EXPER_DVMRP_VIF;
18431 	if (!ip_mroute_vif(mpctl->b_cont)) {
18432 		ip0dbg(("ip_mroute_vif: failed\n"));
18433 	}
18434 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18435 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18436 	    (int)optp->level, (int)optp->name, (int)optp->len));
18437 	qreply(q, mpctl);
18438 	return (mp2ctl);
18439 }
18440 
18441 /* Multicast routing table. */
18442 static mblk_t *
18443 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18444 {
18445 	struct opthdr		*optp;
18446 	mblk_t			*mp2ctl;
18447 
18448 	/*
18449 	 * make a copy of the original message
18450 	 */
18451 	mp2ctl = copymsg(mpctl);
18452 
18453 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18454 	optp->level = EXPER_DVMRP;
18455 	optp->name = EXPER_DVMRP_MRT;
18456 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18457 		ip0dbg(("ip_mroute_mrt: failed\n"));
18458 	}
18459 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18460 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18461 	    (int)optp->level, (int)optp->name, (int)optp->len));
18462 	qreply(q, mpctl);
18463 	return (mp2ctl);
18464 }
18465 
18466 /*
18467  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18468  * in one IRE walk.
18469  */
18470 static mblk_t *
18471 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18472 {
18473 	struct opthdr	*optp;
18474 	mblk_t		*mp2ctl;	/* Returned */
18475 	mblk_t		*mp3ctl;	/* nettomedia */
18476 	mblk_t		*mp4ctl;	/* routeattrs */
18477 	iproutedata_t	ird;
18478 	zoneid_t	zoneid;
18479 
18480 	/*
18481 	 * make copies of the original message
18482 	 *	- mp2ctl is returned unchanged to the caller for his use
18483 	 *	- mpctl is sent upstream as ipRouteEntryTable
18484 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18485 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18486 	 */
18487 	mp2ctl = copymsg(mpctl);
18488 	mp3ctl = copymsg(mpctl);
18489 	mp4ctl = copymsg(mpctl);
18490 	if (mp3ctl == NULL || mp4ctl == NULL) {
18491 		freemsg(mp4ctl);
18492 		freemsg(mp3ctl);
18493 		freemsg(mp2ctl);
18494 		freemsg(mpctl);
18495 		return (NULL);
18496 	}
18497 
18498 	bzero(&ird, sizeof (ird));
18499 
18500 	ird.ird_route.lp_head = mpctl->b_cont;
18501 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18502 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18503 
18504 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18505 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18506 	if (zoneid == GLOBAL_ZONEID) {
18507 		/*
18508 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18509 		 * the sys_net_config privilege, it can only run in the global
18510 		 * zone, so we don't display these IREs in the other zones.
18511 		 */
18512 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18513 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18514 	}
18515 
18516 	/* ipRouteEntryTable in mpctl */
18517 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18518 	optp->level = MIB2_IP;
18519 	optp->name = MIB2_IP_ROUTE;
18520 	optp->len = msgdsize(ird.ird_route.lp_head);
18521 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18522 	    (int)optp->level, (int)optp->name, (int)optp->len));
18523 	qreply(q, mpctl);
18524 
18525 	/* ipNetToMediaEntryTable in mp3ctl */
18526 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18527 	optp->level = MIB2_IP;
18528 	optp->name = MIB2_IP_MEDIA;
18529 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18530 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18531 	    (int)optp->level, (int)optp->name, (int)optp->len));
18532 	qreply(q, mp3ctl);
18533 
18534 	/* ipRouteAttributeTable in mp4ctl */
18535 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18536 	optp->level = MIB2_IP;
18537 	optp->name = EXPER_IP_RTATTR;
18538 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18539 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18540 	    (int)optp->level, (int)optp->name, (int)optp->len));
18541 	if (optp->len == 0)
18542 		freemsg(mp4ctl);
18543 	else
18544 		qreply(q, mp4ctl);
18545 
18546 	return (mp2ctl);
18547 }
18548 
18549 /*
18550  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18551  * ipv6NetToMediaEntryTable in an NDP walk.
18552  */
18553 static mblk_t *
18554 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18555 {
18556 	struct opthdr	*optp;
18557 	mblk_t		*mp2ctl;	/* Returned */
18558 	mblk_t		*mp3ctl;	/* nettomedia */
18559 	mblk_t		*mp4ctl;	/* routeattrs */
18560 	iproutedata_t	ird;
18561 	zoneid_t	zoneid;
18562 
18563 	/*
18564 	 * make copies of the original message
18565 	 *	- mp2ctl is returned unchanged to the caller for his use
18566 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18567 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18568 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18569 	 */
18570 	mp2ctl = copymsg(mpctl);
18571 	mp3ctl = copymsg(mpctl);
18572 	mp4ctl = copymsg(mpctl);
18573 	if (mp3ctl == NULL || mp4ctl == NULL) {
18574 		freemsg(mp4ctl);
18575 		freemsg(mp3ctl);
18576 		freemsg(mp2ctl);
18577 		freemsg(mpctl);
18578 		return (NULL);
18579 	}
18580 
18581 	bzero(&ird, sizeof (ird));
18582 
18583 	ird.ird_route.lp_head = mpctl->b_cont;
18584 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18585 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18586 
18587 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18588 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
18589 
18590 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18591 	optp->level = MIB2_IP6;
18592 	optp->name = MIB2_IP6_ROUTE;
18593 	optp->len = msgdsize(ird.ird_route.lp_head);
18594 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18595 	    (int)optp->level, (int)optp->name, (int)optp->len));
18596 	qreply(q, mpctl);
18597 
18598 	/* ipv6NetToMediaEntryTable in mp3ctl */
18599 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
18600 
18601 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18602 	optp->level = MIB2_IP6;
18603 	optp->name = MIB2_IP6_MEDIA;
18604 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18605 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18606 	    (int)optp->level, (int)optp->name, (int)optp->len));
18607 	qreply(q, mp3ctl);
18608 
18609 	/* ipv6RouteAttributeTable in mp4ctl */
18610 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18611 	optp->level = MIB2_IP6;
18612 	optp->name = EXPER_IP_RTATTR;
18613 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18614 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18615 	    (int)optp->level, (int)optp->name, (int)optp->len));
18616 	if (optp->len == 0)
18617 		freemsg(mp4ctl);
18618 	else
18619 		qreply(q, mp4ctl);
18620 
18621 	return (mp2ctl);
18622 }
18623 
18624 /*
18625  * ICMPv6 mib: One per ill
18626  */
18627 static mblk_t *
18628 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
18629 {
18630 	struct opthdr		*optp;
18631 	mblk_t			*mp2ctl;
18632 	ill_t			*ill;
18633 	ill_walk_context_t	ctx;
18634 	mblk_t			*mp_tail = NULL;
18635 
18636 	/*
18637 	 * Make a copy of the original message
18638 	 */
18639 	mp2ctl = copymsg(mpctl);
18640 
18641 	/* fixed length IPv6 structure ... */
18642 
18643 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18644 	optp->level = MIB2_IP6;
18645 	optp->name = 0;
18646 	/* Include "unknown interface" ip6_mib */
18647 	ip6_mib.ipv6IfIndex = 0;	/* Flag to netstat */
18648 	SET_MIB(ip6_mib.ipv6Forwarding, ipv6_forward ? 1 : 2);
18649 	SET_MIB(ip6_mib.ipv6DefaultHopLimit, ipv6_def_hops);
18650 	SET_MIB(ip6_mib.ipv6IfStatsEntrySize,
18651 	    sizeof (mib2_ipv6IfStatsEntry_t));
18652 	SET_MIB(ip6_mib.ipv6AddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
18653 	SET_MIB(ip6_mib.ipv6RouteEntrySize, sizeof (mib2_ipv6RouteEntry_t));
18654 	SET_MIB(ip6_mib.ipv6NetToMediaEntrySize,
18655 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18656 	SET_MIB(ip6_mib.ipv6MemberEntrySize, sizeof (ipv6_member_t));
18657 	SET_MIB(ip6_mib.ipv6GroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
18658 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
18659 	    (int)sizeof (ip6_mib))) {
18660 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18661 		    (uint_t)sizeof (ip6_mib)));
18662 	}
18663 
18664 	rw_enter(&ill_g_lock, RW_READER);
18665 	ill = ILL_START_WALK_V6(&ctx);
18666 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18667 		ill->ill_ip6_mib->ipv6IfIndex =
18668 		    ill->ill_phyint->phyint_ifindex;
18669 		SET_MIB(ill->ill_ip6_mib->ipv6Forwarding,
18670 		    ipv6_forward ? 1 : 2);
18671 		SET_MIB(ill->ill_ip6_mib->ipv6DefaultHopLimit,
18672 		    ill->ill_max_hops);
18673 		SET_MIB(ill->ill_ip6_mib->ipv6IfStatsEntrySize,
18674 		    sizeof (mib2_ipv6IfStatsEntry_t));
18675 		SET_MIB(ill->ill_ip6_mib->ipv6AddrEntrySize,
18676 		    sizeof (mib2_ipv6AddrEntry_t));
18677 		SET_MIB(ill->ill_ip6_mib->ipv6RouteEntrySize,
18678 		    sizeof (mib2_ipv6RouteEntry_t));
18679 		SET_MIB(ill->ill_ip6_mib->ipv6NetToMediaEntrySize,
18680 		    sizeof (mib2_ipv6NetToMediaEntry_t));
18681 		SET_MIB(ill->ill_ip6_mib->ipv6MemberEntrySize,
18682 		    sizeof (ipv6_member_t));
18683 
18684 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18685 		    (char *)ill->ill_ip6_mib,
18686 		    (int)sizeof (*ill->ill_ip6_mib))) {
18687 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18688 				"%u bytes\n",
18689 				(uint_t)sizeof (*ill->ill_ip6_mib)));
18690 		}
18691 	}
18692 	rw_exit(&ill_g_lock);
18693 
18694 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18695 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18696 	    (int)optp->level, (int)optp->name, (int)optp->len));
18697 	qreply(q, mpctl);
18698 	return (mp2ctl);
18699 }
18700 
18701 /*
18702  * ICMPv6 mib: One per ill
18703  */
18704 static mblk_t *
18705 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
18706 {
18707 	struct opthdr		*optp;
18708 	mblk_t			*mp2ctl;
18709 	ill_t			*ill;
18710 	ill_walk_context_t	ctx;
18711 	mblk_t			*mp_tail = NULL;
18712 	/*
18713 	 * Make a copy of the original message
18714 	 */
18715 	mp2ctl = copymsg(mpctl);
18716 
18717 	/* fixed length ICMPv6 structure ... */
18718 
18719 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18720 	optp->level = MIB2_ICMP6;
18721 	optp->name = 0;
18722 	/* Include "unknown interface" icmp6_mib */
18723 	icmp6_mib.ipv6IfIcmpIfIndex = 0;	/* Flag to netstat */
18724 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
18725 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
18726 	    (int)sizeof (icmp6_mib))) {
18727 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18728 		    (uint_t)sizeof (icmp6_mib)));
18729 	}
18730 
18731 	rw_enter(&ill_g_lock, RW_READER);
18732 	ill = ILL_START_WALK_V6(&ctx);
18733 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18734 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18735 		    ill->ill_phyint->phyint_ifindex;
18736 		ill->ill_icmp6_mib->ipv6IfIcmpEntrySize =
18737 		    sizeof (mib2_ipv6IfIcmpEntry_t);
18738 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18739 		    (char *)ill->ill_icmp6_mib,
18740 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18741 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18742 			    "%u bytes\n",
18743 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18744 		}
18745 	}
18746 	rw_exit(&ill_g_lock);
18747 
18748 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18749 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18750 	    (int)optp->level, (int)optp->name, (int)optp->len));
18751 	qreply(q, mpctl);
18752 	return (mp2ctl);
18753 }
18754 
18755 /*
18756  * ire_walk routine to create both ipRouteEntryTable and
18757  * ipRouteAttributeTable in one IRE walk
18758  */
18759 static void
18760 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18761 {
18762 	ill_t				*ill;
18763 	ipif_t				*ipif;
18764 	mib2_ipRouteEntry_t		*re;
18765 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18766 	ipaddr_t			gw_addr;
18767 	tsol_ire_gw_secattr_t		*attrp;
18768 	tsol_gc_t			*gc = NULL;
18769 	tsol_gcgrp_t			*gcgrp = NULL;
18770 	uint_t				sacnt = 0;
18771 	int				i;
18772 
18773 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18774 
18775 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18776 		return;
18777 
18778 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18779 		mutex_enter(&attrp->igsa_lock);
18780 		if ((gc = attrp->igsa_gc) != NULL) {
18781 			gcgrp = gc->gc_grp;
18782 			ASSERT(gcgrp != NULL);
18783 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18784 			sacnt = 1;
18785 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18786 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18787 			gc = gcgrp->gcgrp_head;
18788 			sacnt = gcgrp->gcgrp_count;
18789 		}
18790 		mutex_exit(&attrp->igsa_lock);
18791 
18792 		/* do nothing if there's no gc to report */
18793 		if (gc == NULL) {
18794 			ASSERT(sacnt == 0);
18795 			if (gcgrp != NULL) {
18796 				/* we might as well drop the lock now */
18797 				rw_exit(&gcgrp->gcgrp_rwlock);
18798 				gcgrp = NULL;
18799 			}
18800 			attrp = NULL;
18801 		}
18802 
18803 		ASSERT(gc == NULL || (gcgrp != NULL &&
18804 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18805 	}
18806 	ASSERT(sacnt == 0 || gc != NULL);
18807 
18808 	if (sacnt != 0 &&
18809 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18810 		kmem_free(re, sizeof (*re));
18811 		rw_exit(&gcgrp->gcgrp_rwlock);
18812 		return;
18813 	}
18814 
18815 	/*
18816 	 * Return all IRE types for route table... let caller pick and choose
18817 	 */
18818 	re->ipRouteDest = ire->ire_addr;
18819 	ipif = ire->ire_ipif;
18820 	re->ipRouteIfIndex.o_length = 0;
18821 	if (ire->ire_type == IRE_CACHE) {
18822 		ill = (ill_t *)ire->ire_stq->q_ptr;
18823 		re->ipRouteIfIndex.o_length =
18824 		    ill->ill_name_length == 0 ? 0 :
18825 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18826 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18827 		    re->ipRouteIfIndex.o_length);
18828 	} else if (ipif != NULL) {
18829 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
18830 		    OCTET_LENGTH);
18831 		re->ipRouteIfIndex.o_length =
18832 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18833 	}
18834 	re->ipRouteMetric1 = -1;
18835 	re->ipRouteMetric2 = -1;
18836 	re->ipRouteMetric3 = -1;
18837 	re->ipRouteMetric4 = -1;
18838 
18839 	gw_addr = ire->ire_gateway_addr;
18840 
18841 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18842 		re->ipRouteNextHop = ire->ire_src_addr;
18843 	else
18844 		re->ipRouteNextHop = gw_addr;
18845 	/* indirect(4), direct(3), or invalid(2) */
18846 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18847 		re->ipRouteType = 2;
18848 	else
18849 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18850 	re->ipRouteProto = -1;
18851 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18852 	re->ipRouteMask = ire->ire_mask;
18853 	re->ipRouteMetric5 = -1;
18854 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
18855 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
18856 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
18857 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
18858 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
18859 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
18860 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
18861 	re->ipRouteInfo.re_flags	= ire->ire_flags;
18862 	re->ipRouteInfo.re_in_ill.o_length = 0;
18863 
18864 	if (ire->ire_flags & RTF_DYNAMIC) {
18865 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
18866 	} else {
18867 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
18868 	}
18869 
18870 	if (ire->ire_in_ill != NULL) {
18871 		re->ipRouteInfo.re_in_ill.o_length =
18872 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
18873 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
18874 		bcopy(ire->ire_in_ill->ill_name,
18875 		    re->ipRouteInfo.re_in_ill.o_bytes,
18876 		    re->ipRouteInfo.re_in_ill.o_length);
18877 	}
18878 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
18879 
18880 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
18881 	    (char *)re, (int)sizeof (*re))) {
18882 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18883 		    (uint_t)sizeof (*re)));
18884 	}
18885 
18886 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
18887 		iaeptr->iae_routeidx = ird->ird_idx;
18888 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
18889 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
18890 	}
18891 
18892 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
18893 	    (char *)iae, sacnt * sizeof (*iae))) {
18894 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
18895 		    (unsigned)(sacnt * sizeof (*iae))));
18896 	}
18897 
18898 	/* bump route index for next pass */
18899 	ird->ird_idx++;
18900 
18901 	kmem_free(re, sizeof (*re));
18902 	if (sacnt != 0)
18903 		kmem_free(iae, sacnt * sizeof (*iae));
18904 
18905 	if (gcgrp != NULL)
18906 		rw_exit(&gcgrp->gcgrp_rwlock);
18907 }
18908 
18909 /*
18910  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
18911  */
18912 static void
18913 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
18914 {
18915 	ill_t				*ill;
18916 	ipif_t				*ipif;
18917 	mib2_ipv6RouteEntry_t		*re;
18918 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18919 	in6_addr_t			gw_addr_v6;
18920 	tsol_ire_gw_secattr_t		*attrp;
18921 	tsol_gc_t			*gc = NULL;
18922 	tsol_gcgrp_t			*gcgrp = NULL;
18923 	uint_t				sacnt = 0;
18924 	int				i;
18925 
18926 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
18927 
18928 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18929 		return;
18930 
18931 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18932 		mutex_enter(&attrp->igsa_lock);
18933 		if ((gc = attrp->igsa_gc) != NULL) {
18934 			gcgrp = gc->gc_grp;
18935 			ASSERT(gcgrp != NULL);
18936 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18937 			sacnt = 1;
18938 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18939 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18940 			gc = gcgrp->gcgrp_head;
18941 			sacnt = gcgrp->gcgrp_count;
18942 		}
18943 		mutex_exit(&attrp->igsa_lock);
18944 
18945 		/* do nothing if there's no gc to report */
18946 		if (gc == NULL) {
18947 			ASSERT(sacnt == 0);
18948 			if (gcgrp != NULL) {
18949 				/* we might as well drop the lock now */
18950 				rw_exit(&gcgrp->gcgrp_rwlock);
18951 				gcgrp = NULL;
18952 			}
18953 			attrp = NULL;
18954 		}
18955 
18956 		ASSERT(gc == NULL || (gcgrp != NULL &&
18957 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18958 	}
18959 	ASSERT(sacnt == 0 || gc != NULL);
18960 
18961 	if (sacnt != 0 &&
18962 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18963 		kmem_free(re, sizeof (*re));
18964 		rw_exit(&gcgrp->gcgrp_rwlock);
18965 		return;
18966 	}
18967 
18968 	/*
18969 	 * Return all IRE types for route table... let caller pick and choose
18970 	 */
18971 	re->ipv6RouteDest = ire->ire_addr_v6;
18972 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
18973 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
18974 	re->ipv6RouteIfIndex.o_length = 0;
18975 	ipif = ire->ire_ipif;
18976 	if (ire->ire_type == IRE_CACHE) {
18977 		ill = (ill_t *)ire->ire_stq->q_ptr;
18978 		re->ipv6RouteIfIndex.o_length =
18979 		    ill->ill_name_length == 0 ? 0 :
18980 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18981 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
18982 		    re->ipv6RouteIfIndex.o_length);
18983 	} else if (ipif != NULL) {
18984 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
18985 		    OCTET_LENGTH);
18986 		re->ipv6RouteIfIndex.o_length =
18987 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
18988 	}
18989 
18990 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
18991 
18992 	mutex_enter(&ire->ire_lock);
18993 	gw_addr_v6 = ire->ire_gateway_addr_v6;
18994 	mutex_exit(&ire->ire_lock);
18995 
18996 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
18997 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
18998 	else
18999 		re->ipv6RouteNextHop = gw_addr_v6;
19000 
19001 	/* remote(4), local(3), or discard(2) */
19002 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19003 		re->ipv6RouteType = 2;
19004 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19005 		re->ipv6RouteType = 3;
19006 	else
19007 		re->ipv6RouteType = 4;
19008 
19009 	re->ipv6RouteProtocol	= -1;
19010 	re->ipv6RoutePolicy	= 0;
19011 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19012 	re->ipv6RouteNextHopRDI	= 0;
19013 	re->ipv6RouteWeight	= 0;
19014 	re->ipv6RouteMetric	= 0;
19015 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19016 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19017 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19018 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19019 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19020 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19021 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19022 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19023 
19024 	if (ire->ire_flags & RTF_DYNAMIC) {
19025 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19026 	} else {
19027 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19028 	}
19029 
19030 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19031 	    (char *)re, (int)sizeof (*re))) {
19032 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19033 		    (uint_t)sizeof (*re)));
19034 	}
19035 
19036 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19037 		iaeptr->iae_routeidx = ird->ird_idx;
19038 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19039 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19040 	}
19041 
19042 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19043 	    (char *)iae, sacnt * sizeof (*iae))) {
19044 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19045 		    (unsigned)(sacnt * sizeof (*iae))));
19046 	}
19047 
19048 	/* bump route index for next pass */
19049 	ird->ird_idx++;
19050 
19051 	kmem_free(re, sizeof (*re));
19052 	if (sacnt != 0)
19053 		kmem_free(iae, sacnt * sizeof (*iae));
19054 
19055 	if (gcgrp != NULL)
19056 		rw_exit(&gcgrp->gcgrp_rwlock);
19057 }
19058 
19059 /*
19060  * ndp_walk routine to create ipv6NetToMediaEntryTable
19061  */
19062 static int
19063 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19064 {
19065 	ill_t				*ill;
19066 	mib2_ipv6NetToMediaEntry_t	ntme;
19067 	dl_unitdata_req_t		*dl;
19068 
19069 	ill = nce->nce_ill;
19070 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19071 		return (0);
19072 
19073 	/*
19074 	 * Neighbor cache entry attached to IRE with on-link
19075 	 * destination.
19076 	 */
19077 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19078 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19079 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19080 	    (nce->nce_res_mp != NULL)) {
19081 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19082 		ntme.ipv6NetToMediaPhysAddress.o_length =
19083 		    dl->dl_dest_addr_length;
19084 	} else {
19085 		ntme.ipv6NetToMediaPhysAddress.o_length =
19086 		    ill->ill_phys_addr_length;
19087 	}
19088 	if (nce->nce_res_mp != NULL) {
19089 		bcopy((char *)nce->nce_res_mp->b_rptr +
19090 		    NCE_LL_ADDR_OFFSET(ill),
19091 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19092 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19093 	} else {
19094 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19095 		    ill->ill_phys_addr_length);
19096 	}
19097 	/*
19098 	 * Note: Returns ND_* states. Should be:
19099 	 * reachable(1), stale(2), delay(3), probe(4),
19100 	 * invalid(5), unknown(6)
19101 	 */
19102 	ntme.ipv6NetToMediaState = nce->nce_state;
19103 	ntme.ipv6NetToMediaLastUpdated = 0;
19104 
19105 	/* other(1), dynamic(2), static(3), local(4) */
19106 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19107 		ntme.ipv6NetToMediaType = 4;
19108 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19109 		ntme.ipv6NetToMediaType = 1;
19110 	} else {
19111 		ntme.ipv6NetToMediaType = 2;
19112 	}
19113 
19114 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19115 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19116 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19117 		    (uint_t)sizeof (ntme)));
19118 	}
19119 	return (0);
19120 }
19121 
19122 /*
19123  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19124  */
19125 /* ARGSUSED */
19126 int
19127 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19128 {
19129 	switch (level) {
19130 	case MIB2_IP:
19131 	case MIB2_ICMP:
19132 		switch (name) {
19133 		default:
19134 			break;
19135 		}
19136 		return (1);
19137 	default:
19138 		return (1);
19139 	}
19140 }
19141 
19142 /*
19143  * Called before the options are updated to check if this packet will
19144  * be source routed from here.
19145  * This routine assumes that the options are well formed i.e. that they
19146  * have already been checked.
19147  */
19148 static boolean_t
19149 ip_source_routed(ipha_t *ipha)
19150 {
19151 	ipoptp_t	opts;
19152 	uchar_t		*opt;
19153 	uint8_t		optval;
19154 	uint8_t		optlen;
19155 	ipaddr_t	dst;
19156 	ire_t		*ire;
19157 
19158 	if (IS_SIMPLE_IPH(ipha)) {
19159 		ip2dbg(("not source routed\n"));
19160 		return (B_FALSE);
19161 	}
19162 	dst = ipha->ipha_dst;
19163 	for (optval = ipoptp_first(&opts, ipha);
19164 	    optval != IPOPT_EOL;
19165 	    optval = ipoptp_next(&opts)) {
19166 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19167 		opt = opts.ipoptp_cur;
19168 		optlen = opts.ipoptp_len;
19169 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19170 		    optval, optlen));
19171 		switch (optval) {
19172 			uint32_t off;
19173 		case IPOPT_SSRR:
19174 		case IPOPT_LSRR:
19175 			/*
19176 			 * If dst is one of our addresses and there are some
19177 			 * entries left in the source route return (true).
19178 			 */
19179 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19180 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19181 			if (ire == NULL) {
19182 				ip2dbg(("ip_source_routed: not next"
19183 				    " source route 0x%x\n",
19184 				    ntohl(dst)));
19185 				return (B_FALSE);
19186 			}
19187 			ire_refrele(ire);
19188 			off = opt[IPOPT_OFFSET];
19189 			off--;
19190 			if (optlen < IP_ADDR_LEN ||
19191 			    off > optlen - IP_ADDR_LEN) {
19192 				/* End of source route */
19193 				ip1dbg(("ip_source_routed: end of SR\n"));
19194 				return (B_FALSE);
19195 			}
19196 			return (B_TRUE);
19197 		}
19198 	}
19199 	ip2dbg(("not source routed\n"));
19200 	return (B_FALSE);
19201 }
19202 
19203 /*
19204  * Check if the packet contains any source route.
19205  */
19206 static boolean_t
19207 ip_source_route_included(ipha_t *ipha)
19208 {
19209 	ipoptp_t	opts;
19210 	uint8_t		optval;
19211 
19212 	if (IS_SIMPLE_IPH(ipha))
19213 		return (B_FALSE);
19214 	for (optval = ipoptp_first(&opts, ipha);
19215 	    optval != IPOPT_EOL;
19216 	    optval = ipoptp_next(&opts)) {
19217 		switch (optval) {
19218 		case IPOPT_SSRR:
19219 		case IPOPT_LSRR:
19220 			return (B_TRUE);
19221 		}
19222 	}
19223 	return (B_FALSE);
19224 }
19225 
19226 /*
19227  * Called when the IRE expiration timer fires.
19228  */
19229 /* ARGSUSED */
19230 void
19231 ip_trash_timer_expire(void *args)
19232 {
19233 	int	flush_flag = 0;
19234 
19235 	/*
19236 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19237 	 * This lock makes sure that a new invocation of this function
19238 	 * that occurs due to an almost immediate timer firing will not
19239 	 * progress beyond this point until the current invocation is done
19240 	 */
19241 	mutex_enter(&ip_trash_timer_lock);
19242 	ip_ire_expire_id = 0;
19243 	mutex_exit(&ip_trash_timer_lock);
19244 
19245 	/* Periodic timer */
19246 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19247 		/*
19248 		 * Remove all IRE_CACHE entries since they might
19249 		 * contain arp information.
19250 		 */
19251 		flush_flag |= FLUSH_ARP_TIME;
19252 		ip_ire_arp_time_elapsed = 0;
19253 		IP_STAT(ip_ire_arp_timer_expired);
19254 	}
19255 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19256 		/* Remove all redirects */
19257 		flush_flag |= FLUSH_REDIRECT_TIME;
19258 		ip_ire_rd_time_elapsed = 0;
19259 		IP_STAT(ip_ire_redirect_timer_expired);
19260 	}
19261 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19262 		/* Increase path mtu */
19263 		flush_flag |= FLUSH_MTU_TIME;
19264 		ip_ire_pmtu_time_elapsed = 0;
19265 		IP_STAT(ip_ire_pmtu_timer_expired);
19266 	}
19267 
19268 	/*
19269 	 * Optimize for the case when there are no redirects in the
19270 	 * ftable, that is, no need to walk the ftable in that case.
19271 	 */
19272 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19273 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19274 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19275 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19276 	}
19277 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19278 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19279 		    ire_expire, (char *)(uintptr_t)flush_flag,
19280 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19281 	}
19282 	if (flush_flag & FLUSH_MTU_TIME) {
19283 		/*
19284 		 * Walk all IPv6 IRE's and update them
19285 		 * Note that ARP and redirect timers are not
19286 		 * needed since NUD handles stale entries.
19287 		 */
19288 		flush_flag = FLUSH_MTU_TIME;
19289 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19290 		    ALL_ZONES);
19291 	}
19292 
19293 	ip_ire_arp_time_elapsed += ip_timer_interval;
19294 	ip_ire_rd_time_elapsed += ip_timer_interval;
19295 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19296 
19297 	/*
19298 	 * Hold the lock to serialize timeout calls and prevent
19299 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19300 	 * for the timer to fire and a new invocation of this function
19301 	 * to start before the return value of timeout has been stored
19302 	 * in ip_ire_expire_id by the current invocation.
19303 	 */
19304 	mutex_enter(&ip_trash_timer_lock);
19305 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19306 	    MSEC_TO_TICK(ip_timer_interval));
19307 	mutex_exit(&ip_trash_timer_lock);
19308 }
19309 
19310 /*
19311  * Called by the memory allocator subsystem directly, when the system
19312  * is running low on memory.
19313  */
19314 /* ARGSUSED */
19315 void
19316 ip_trash_ire_reclaim(void *args)
19317 {
19318 	ire_cache_count_t icc;
19319 	ire_cache_reclaim_t icr;
19320 	ncc_cache_count_t ncc;
19321 	nce_cache_reclaim_t ncr;
19322 	uint_t delete_cnt;
19323 	/*
19324 	 * Memory reclaim call back.
19325 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19326 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19327 	 * entries, determine what fraction to free for
19328 	 * each category of IRE_CACHE entries giving absolute priority
19329 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19330 	 * entry will be freed unless all offlink entries are freed).
19331 	 */
19332 	icc.icc_total = 0;
19333 	icc.icc_unused = 0;
19334 	icc.icc_offlink = 0;
19335 	icc.icc_pmtu = 0;
19336 	icc.icc_onlink = 0;
19337 	ire_walk(ire_cache_count, (char *)&icc);
19338 
19339 	/*
19340 	 * Free NCEs for IPv6 like the onlink ires.
19341 	 */
19342 	ncc.ncc_total = 0;
19343 	ncc.ncc_host = 0;
19344 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19345 
19346 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19347 	    icc.icc_pmtu + icc.icc_onlink);
19348 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19349 	IP_STAT(ip_trash_ire_reclaim_calls);
19350 	if (delete_cnt == 0)
19351 		return;
19352 	IP_STAT(ip_trash_ire_reclaim_success);
19353 	/* Always delete all unused offlink entries */
19354 	icr.icr_unused = 1;
19355 	if (delete_cnt <= icc.icc_unused) {
19356 		/*
19357 		 * Only need to free unused entries.  In other words,
19358 		 * there are enough unused entries to free to meet our
19359 		 * target number of freed ire cache entries.
19360 		 */
19361 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19362 		ncr.ncr_host = 0;
19363 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19364 		/*
19365 		 * Only need to free unused entries, plus a fraction of offlink
19366 		 * entries.  It follows from the first if statement that
19367 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19368 		 */
19369 		delete_cnt -= icc.icc_unused;
19370 		/* Round up # deleted by truncating fraction */
19371 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19372 		icr.icr_pmtu = icr.icr_onlink = 0;
19373 		ncr.ncr_host = 0;
19374 	} else if (delete_cnt <=
19375 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19376 		/*
19377 		 * Free all unused and offlink entries, plus a fraction of
19378 		 * pmtu entries.  It follows from the previous if statement
19379 		 * that icc_pmtu is non-zero, and that
19380 		 * delete_cnt != icc_unused + icc_offlink.
19381 		 */
19382 		icr.icr_offlink = 1;
19383 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19384 		/* Round up # deleted by truncating fraction */
19385 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19386 		icr.icr_onlink = 0;
19387 		ncr.ncr_host = 0;
19388 	} else {
19389 		/*
19390 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19391 		 * of onlink entries.  If we're here, then we know that
19392 		 * icc_onlink is non-zero, and that
19393 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19394 		 */
19395 		icr.icr_offlink = icr.icr_pmtu = 1;
19396 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19397 		    icc.icc_pmtu;
19398 		/* Round up # deleted by truncating fraction */
19399 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19400 		/* Using the same delete fraction as for onlink IREs */
19401 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19402 	}
19403 #ifdef DEBUG
19404 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19405 	    "fractions %d/%d/%d/%d\n",
19406 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19407 	    icc.icc_unused, icc.icc_offlink,
19408 	    icc.icc_pmtu, icc.icc_onlink,
19409 	    icr.icr_unused, icr.icr_offlink,
19410 	    icr.icr_pmtu, icr.icr_onlink));
19411 #endif
19412 	ire_walk(ire_cache_reclaim, (char *)&icr);
19413 	if (ncr.ncr_host != 0)
19414 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19415 		    (uchar_t *)&ncr);
19416 #ifdef DEBUG
19417 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19418 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19419 	ire_walk(ire_cache_count, (char *)&icc);
19420 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19421 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19422 	    icc.icc_pmtu, icc.icc_onlink));
19423 #endif
19424 }
19425 
19426 /*
19427  * ip_unbind is called when a copy of an unbind request is received from the
19428  * upper level protocol.  We remove this conn from any fanout hash list it is
19429  * on, and zero out the bind information.  No reply is expected up above.
19430  */
19431 mblk_t *
19432 ip_unbind(queue_t *q, mblk_t *mp)
19433 {
19434 	conn_t	*connp = Q_TO_CONN(q);
19435 
19436 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19437 
19438 	if (is_system_labeled() && connp->conn_anon_port) {
19439 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19440 		    connp->conn_mlp_type, connp->conn_ulp,
19441 		    ntohs(connp->conn_lport), B_FALSE);
19442 		connp->conn_anon_port = 0;
19443 	}
19444 	connp->conn_mlp_type = mlptSingle;
19445 
19446 	ipcl_hash_remove(connp);
19447 
19448 	ASSERT(mp->b_cont == NULL);
19449 	/*
19450 	 * Convert mp into a T_OK_ACK
19451 	 */
19452 	mp = mi_tpi_ok_ack_alloc(mp);
19453 
19454 	/*
19455 	 * should not happen in practice... T_OK_ACK is smaller than the
19456 	 * original message.
19457 	 */
19458 	if (mp == NULL)
19459 		return (NULL);
19460 
19461 	/*
19462 	 * Don't bzero the ports if its TCP since TCP still needs the
19463 	 * lport to remove it from its own bind hash. TCP will do the
19464 	 * cleanup.
19465 	 */
19466 	if (!IPCL_IS_TCP(connp))
19467 		bzero(&connp->u_port, sizeof (connp->u_port));
19468 
19469 	return (mp);
19470 }
19471 
19472 /*
19473  * Write side put procedure.  Outbound data, IOCTLs, responses from
19474  * resolvers, etc, come down through here.
19475  *
19476  * arg2 is always a queue_t *.
19477  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19478  * the zoneid.
19479  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19480  */
19481 void
19482 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19483 {
19484 	conn_t		*connp = NULL;
19485 	queue_t		*q = (queue_t *)arg2;
19486 	ipha_t		*ipha;
19487 #define	rptr	((uchar_t *)ipha)
19488 	ire_t		*ire = NULL;
19489 	ire_t		*sctp_ire = NULL;
19490 	uint32_t	v_hlen_tos_len;
19491 	ipaddr_t	dst;
19492 	mblk_t		*first_mp = NULL;
19493 	boolean_t	mctl_present;
19494 	ipsec_out_t	*io;
19495 	int		match_flags;
19496 	ill_t		*attach_ill = NULL;
19497 					/* Bind to IPIF_NOFAILOVER ill etc. */
19498 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19499 	ipif_t		*dst_ipif;
19500 	boolean_t	multirt_need_resolve = B_FALSE;
19501 	mblk_t		*copy_mp = NULL;
19502 	int		err;
19503 	zoneid_t	zoneid;
19504 	int	adjust;
19505 	uint16_t iplen;
19506 	boolean_t	need_decref = B_FALSE;
19507 	boolean_t	ignore_dontroute = B_FALSE;
19508 	boolean_t	ignore_nexthop = B_FALSE;
19509 	boolean_t	ip_nexthop = B_FALSE;
19510 	ipaddr_t	nexthop_addr;
19511 
19512 #ifdef	_BIG_ENDIAN
19513 #define	V_HLEN	(v_hlen_tos_len >> 24)
19514 #else
19515 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19516 #endif
19517 
19518 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19519 	    "ip_wput_start: q %p", q);
19520 
19521 	/*
19522 	 * ip_wput fast path
19523 	 */
19524 
19525 	/* is packet from ARP ? */
19526 	if (q->q_next != NULL) {
19527 		zoneid = (zoneid_t)(uintptr_t)arg;
19528 		goto qnext;
19529 	}
19530 
19531 	connp = (conn_t *)arg;
19532 	ASSERT(connp != NULL);
19533 	zoneid = connp->conn_zoneid;
19534 
19535 	/* is queue flow controlled? */
19536 	if ((q->q_first != NULL || connp->conn_draining) &&
19537 	    (caller == IP_WPUT)) {
19538 		ASSERT(!need_decref);
19539 		(void) putq(q, mp);
19540 		return;
19541 	}
19542 
19543 	/* Multidata transmit? */
19544 	if (DB_TYPE(mp) == M_MULTIDATA) {
19545 		/*
19546 		 * We should never get here, since all Multidata messages
19547 		 * originating from tcp should have been directed over to
19548 		 * tcp_multisend() in the first place.
19549 		 */
19550 		BUMP_MIB(&ip_mib, ipOutDiscards);
19551 		freemsg(mp);
19552 		return;
19553 	} else if (DB_TYPE(mp) != M_DATA)
19554 		goto notdata;
19555 
19556 	if (mp->b_flag & MSGHASREF) {
19557 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19558 		mp->b_flag &= ~MSGHASREF;
19559 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19560 		need_decref = B_TRUE;
19561 	}
19562 	ipha = (ipha_t *)mp->b_rptr;
19563 
19564 	/* is IP header non-aligned or mblk smaller than basic IP header */
19565 #ifndef SAFETY_BEFORE_SPEED
19566 	if (!OK_32PTR(rptr) ||
19567 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19568 		goto hdrtoosmall;
19569 #endif
19570 
19571 	ASSERT(OK_32PTR(ipha));
19572 
19573 	/*
19574 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19575 	 * wrong version, we'll catch it again in ip_output_v6.
19576 	 *
19577 	 * Note that this is *only* locally-generated output here, and never
19578 	 * forwarded data, and that we need to deal only with transports that
19579 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19580 	 * label.)
19581 	 */
19582 	if (is_system_labeled() &&
19583 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19584 	    !connp->conn_ulp_labeled) {
19585 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19586 		    connp->conn_mac_exempt);
19587 		ipha = (ipha_t *)mp->b_rptr;
19588 		if (err != 0) {
19589 			first_mp = mp;
19590 			if (err == EINVAL)
19591 				goto icmp_parameter_problem;
19592 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19593 			goto drop_pkt;
19594 		}
19595 		iplen = ntohs(ipha->ipha_length) + adjust;
19596 		ipha->ipha_length = htons(iplen);
19597 	}
19598 
19599 	/*
19600 	 * If there is a policy, try to attach an ipsec_out in
19601 	 * the front. At the end, first_mp either points to a
19602 	 * M_DATA message or IPSEC_OUT message linked to a
19603 	 * M_DATA message. We have to do it now as we might
19604 	 * lose the "conn" if we go through ip_newroute.
19605 	 */
19606 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19607 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
19608 		    ipha->ipha_protocol)) == NULL)) {
19609 			if (need_decref)
19610 				CONN_DEC_REF(connp);
19611 			return;
19612 		} else {
19613 			ASSERT(mp->b_datap->db_type == M_CTL);
19614 			first_mp = mp;
19615 			mp = mp->b_cont;
19616 			mctl_present = B_TRUE;
19617 		}
19618 	} else {
19619 		first_mp = mp;
19620 		mctl_present = B_FALSE;
19621 	}
19622 
19623 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19624 
19625 	/* is wrong version or IP options present */
19626 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19627 		goto version_hdrlen_check;
19628 	dst = ipha->ipha_dst;
19629 
19630 	if (connp->conn_nofailover_ill != NULL) {
19631 		attach_ill = conn_get_held_ill(connp,
19632 		    &connp->conn_nofailover_ill, &err);
19633 		if (err == ILL_LOOKUP_FAILED) {
19634 			if (need_decref)
19635 				CONN_DEC_REF(connp);
19636 			freemsg(first_mp);
19637 			return;
19638 		}
19639 	}
19640 
19641 	/* is packet multicast? */
19642 	if (CLASSD(dst))
19643 		goto multicast;
19644 
19645 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19646 	    (connp->conn_nexthop_set)) {
19647 		/*
19648 		 * If the destination is a broadcast or a loopback
19649 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
19650 		 * through the standard path. But in the case of local
19651 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
19652 		 * the standard path not IP_XMIT_IF.
19653 		 */
19654 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19655 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
19656 		    (ire->ire_type != IRE_LOOPBACK))) {
19657 			if ((connp->conn_dontroute ||
19658 			    connp->conn_nexthop_set) && (ire != NULL) &&
19659 			    (ire->ire_type == IRE_LOCAL))
19660 				goto standard_path;
19661 
19662 			if (ire != NULL) {
19663 				ire_refrele(ire);
19664 				/* No more access to ire */
19665 				ire = NULL;
19666 			}
19667 			/*
19668 			 * bypass routing checks and go directly to
19669 			 * interface.
19670 			 */
19671 			if (connp->conn_dontroute) {
19672 				goto dontroute;
19673 			} else if (connp->conn_nexthop_set) {
19674 				ip_nexthop = B_TRUE;
19675 				nexthop_addr = connp->conn_nexthop_v4;
19676 				goto send_from_ill;
19677 			}
19678 
19679 			/*
19680 			 * If IP_XMIT_IF socket option is set,
19681 			 * then we allow unicast and multicast
19682 			 * packets to go through the ill. It is
19683 			 * quite possible that the destination
19684 			 * is not in the ire cache table and we
19685 			 * do not want to go to ip_newroute()
19686 			 * instead we call ip_newroute_ipif.
19687 			 */
19688 			xmit_ill = conn_get_held_ill(connp,
19689 			    &connp->conn_xmit_if_ill, &err);
19690 			if (err == ILL_LOOKUP_FAILED) {
19691 				if (attach_ill != NULL)
19692 					ill_refrele(attach_ill);
19693 				if (need_decref)
19694 					CONN_DEC_REF(connp);
19695 				freemsg(first_mp);
19696 				return;
19697 			}
19698 			goto send_from_ill;
19699 		}
19700 standard_path:
19701 		/* Must be a broadcast, a loopback or a local ire */
19702 		if (ire != NULL) {
19703 			ire_refrele(ire);
19704 			/* No more access to ire */
19705 			ire = NULL;
19706 		}
19707 	}
19708 
19709 	if (attach_ill != NULL)
19710 		goto send_from_ill;
19711 
19712 	/*
19713 	 * We cache IRE_CACHEs to avoid lookups. We don't do
19714 	 * this for the tcp global queue and listen end point
19715 	 * as it does not really have a real destination to
19716 	 * talk to.  This is also true for SCTP.
19717 	 */
19718 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
19719 	    !connp->conn_fully_bound) {
19720 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19721 		if (ire == NULL)
19722 			goto noirefound;
19723 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19724 		    "ip_wput_end: q %p (%S)", q, "end");
19725 
19726 		/*
19727 		 * Check if the ire has the RTF_MULTIRT flag, inherited
19728 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19729 		 */
19730 		if (ire->ire_flags & RTF_MULTIRT) {
19731 
19732 			/*
19733 			 * Force the TTL of multirouted packets if required.
19734 			 * The TTL of such packets is bounded by the
19735 			 * ip_multirt_ttl ndd variable.
19736 			 */
19737 			if ((ip_multirt_ttl > 0) &&
19738 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
19739 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
19740 				    "(was %d), dst 0x%08x\n",
19741 				    ip_multirt_ttl, ipha->ipha_ttl,
19742 				    ntohl(ire->ire_addr)));
19743 				ipha->ipha_ttl = ip_multirt_ttl;
19744 			}
19745 			/*
19746 			 * We look at this point if there are pending
19747 			 * unresolved routes. ire_multirt_resolvable()
19748 			 * checks in O(n) that all IRE_OFFSUBNET ire
19749 			 * entries for the packet's destination and
19750 			 * flagged RTF_MULTIRT are currently resolved.
19751 			 * If some remain unresolved, we make a copy
19752 			 * of the current message. It will be used
19753 			 * to initiate additional route resolutions.
19754 			 */
19755 			multirt_need_resolve =
19756 			    ire_multirt_need_resolve(ire->ire_addr,
19757 			    MBLK_GETLABEL(first_mp));
19758 			ip2dbg(("ip_wput[TCP]: ire %p, "
19759 			    "multirt_need_resolve %d, first_mp %p\n",
19760 			    (void *)ire, multirt_need_resolve,
19761 			    (void *)first_mp));
19762 			if (multirt_need_resolve) {
19763 				copy_mp = copymsg(first_mp);
19764 				if (copy_mp != NULL) {
19765 					MULTIRT_DEBUG_TAG(copy_mp);
19766 				}
19767 			}
19768 		}
19769 
19770 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19771 
19772 		/*
19773 		 * Try to resolve another multiroute if
19774 		 * ire_multirt_need_resolve() deemed it necessary.
19775 		 */
19776 		if (copy_mp != NULL) {
19777 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19778 		}
19779 		if (need_decref)
19780 			CONN_DEC_REF(connp);
19781 		return;
19782 	}
19783 
19784 	/*
19785 	 * Access to conn_ire_cache. (protected by conn_lock)
19786 	 *
19787 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
19788 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
19789 	 * send a packet or two with the IRE_CACHE that is going away.
19790 	 * Access to the ire requires an ire refhold on the ire prior to
19791 	 * its use since an interface unplumb thread may delete the cached
19792 	 * ire and release the refhold at any time.
19793 	 *
19794 	 * Caching an ire in the conn_ire_cache
19795 	 *
19796 	 * o Caching an ire pointer in the conn requires a strict check for
19797 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
19798 	 * ires  before cleaning up the conns. So the caching of an ire pointer
19799 	 * in the conn is done after making sure under the bucket lock that the
19800 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
19801 	 * caching an ire after the unplumb thread has cleaned up the conn.
19802 	 * If the conn does not send a packet subsequently the unplumb thread
19803 	 * will be hanging waiting for the ire count to drop to zero.
19804 	 *
19805 	 * o We also need to atomically test for a null conn_ire_cache and
19806 	 * set the conn_ire_cache under the the protection of the conn_lock
19807 	 * to avoid races among concurrent threads trying to simultaneously
19808 	 * cache an ire in the conn_ire_cache.
19809 	 */
19810 	mutex_enter(&connp->conn_lock);
19811 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
19812 
19813 	if (ire != NULL && ire->ire_addr == dst &&
19814 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19815 
19816 		IRE_REFHOLD(ire);
19817 		mutex_exit(&connp->conn_lock);
19818 
19819 	} else {
19820 		boolean_t cached = B_FALSE;
19821 		connp->conn_ire_cache = NULL;
19822 		mutex_exit(&connp->conn_lock);
19823 		/* Release the old ire */
19824 		if (ire != NULL && sctp_ire == NULL)
19825 			IRE_REFRELE_NOTR(ire);
19826 
19827 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
19828 		if (ire == NULL)
19829 			goto noirefound;
19830 		IRE_REFHOLD_NOTR(ire);
19831 
19832 		mutex_enter(&connp->conn_lock);
19833 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
19834 		    connp->conn_ire_cache == NULL) {
19835 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19836 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19837 				connp->conn_ire_cache = ire;
19838 				cached = B_TRUE;
19839 			}
19840 			rw_exit(&ire->ire_bucket->irb_lock);
19841 		}
19842 		mutex_exit(&connp->conn_lock);
19843 
19844 		/*
19845 		 * We can continue to use the ire but since it was
19846 		 * not cached, we should drop the extra reference.
19847 		 */
19848 		if (!cached)
19849 			IRE_REFRELE_NOTR(ire);
19850 	}
19851 
19852 
19853 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
19854 	    "ip_wput_end: q %p (%S)", q, "end");
19855 
19856 	/*
19857 	 * Check if the ire has the RTF_MULTIRT flag, inherited
19858 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
19859 	 */
19860 	if (ire->ire_flags & RTF_MULTIRT) {
19861 
19862 		/*
19863 		 * Force the TTL of multirouted packets if required.
19864 		 * The TTL of such packets is bounded by the
19865 		 * ip_multirt_ttl ndd variable.
19866 		 */
19867 		if ((ip_multirt_ttl > 0) &&
19868 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
19869 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
19870 			    "(was %d), dst 0x%08x\n",
19871 			    ip_multirt_ttl, ipha->ipha_ttl,
19872 			    ntohl(ire->ire_addr)));
19873 			ipha->ipha_ttl = ip_multirt_ttl;
19874 		}
19875 
19876 		/*
19877 		 * At this point, we check to see if there are any pending
19878 		 * unresolved routes. ire_multirt_resolvable()
19879 		 * checks in O(n) that all IRE_OFFSUBNET ire
19880 		 * entries for the packet's destination and
19881 		 * flagged RTF_MULTIRT are currently resolved.
19882 		 * If some remain unresolved, we make a copy
19883 		 * of the current message. It will be used
19884 		 * to initiate additional route resolutions.
19885 		 */
19886 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
19887 		    MBLK_GETLABEL(first_mp));
19888 		ip2dbg(("ip_wput[not TCP]: ire %p, "
19889 		    "multirt_need_resolve %d, first_mp %p\n",
19890 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
19891 		if (multirt_need_resolve) {
19892 			copy_mp = copymsg(first_mp);
19893 			if (copy_mp != NULL) {
19894 				MULTIRT_DEBUG_TAG(copy_mp);
19895 			}
19896 		}
19897 	}
19898 
19899 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
19900 
19901 	/*
19902 	 * Try to resolve another multiroute if
19903 	 * ire_multirt_resolvable() deemed it necessary
19904 	 */
19905 	if (copy_mp != NULL) {
19906 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
19907 	}
19908 	if (need_decref)
19909 		CONN_DEC_REF(connp);
19910 	return;
19911 
19912 qnext:
19913 	/*
19914 	 * Upper Level Protocols pass down complete IP datagrams
19915 	 * as M_DATA messages.	Everything else is a sideshow.
19916 	 *
19917 	 * 1) We could be re-entering ip_wput because of ip_neworute
19918 	 *    in which case we could have a IPSEC_OUT message. We
19919 	 *    need to pass through ip_wput like other datagrams and
19920 	 *    hence cannot branch to ip_wput_nondata.
19921 	 *
19922 	 * 2) ARP, AH, ESP, and other clients who are on the module
19923 	 *    instance of IP stream, give us something to deal with.
19924 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
19925 	 *
19926 	 * 3) ICMP replies also could come here.
19927 	 */
19928 	if (DB_TYPE(mp) != M_DATA) {
19929 	    notdata:
19930 		if (DB_TYPE(mp) == M_CTL) {
19931 			/*
19932 			 * M_CTL messages are used by ARP, AH and ESP to
19933 			 * communicate with IP. We deal with IPSEC_IN and
19934 			 * IPSEC_OUT here. ip_wput_nondata handles other
19935 			 * cases.
19936 			 */
19937 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
19938 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
19939 				first_mp = mp->b_cont;
19940 				first_mp->b_flag &= ~MSGHASREF;
19941 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19942 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
19943 				CONN_DEC_REF(connp);
19944 				connp = NULL;
19945 			}
19946 			if (ii->ipsec_info_type == IPSEC_IN) {
19947 				/*
19948 				 * Either this message goes back to
19949 				 * IPSEC for further processing or to
19950 				 * ULP after policy checks.
19951 				 */
19952 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
19953 				return;
19954 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
19955 				io = (ipsec_out_t *)ii;
19956 				if (io->ipsec_out_proc_begin) {
19957 					/*
19958 					 * IPSEC processing has already started.
19959 					 * Complete it.
19960 					 * IPQoS notes: We don't care what is
19961 					 * in ipsec_out_ill_index since this
19962 					 * won't be processed for IPQoS policies
19963 					 * in ipsec_out_process.
19964 					 */
19965 					ipsec_out_process(q, mp, NULL,
19966 					    io->ipsec_out_ill_index);
19967 					return;
19968 				} else {
19969 					connp = (q->q_next != NULL) ?
19970 					    NULL : Q_TO_CONN(q);
19971 					first_mp = mp;
19972 					mp = mp->b_cont;
19973 					mctl_present = B_TRUE;
19974 				}
19975 				zoneid = io->ipsec_out_zoneid;
19976 				ASSERT(zoneid != ALL_ZONES);
19977 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
19978 				/*
19979 				 * It's an IPsec control message requesting
19980 				 * an SADB update to be sent to the IPsec
19981 				 * hardware acceleration capable ills.
19982 				 */
19983 				ipsec_ctl_t *ipsec_ctl =
19984 				    (ipsec_ctl_t *)mp->b_rptr;
19985 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
19986 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
19987 				mblk_t *cmp = mp->b_cont;
19988 
19989 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
19990 				ASSERT(cmp != NULL);
19991 
19992 				freeb(mp);
19993 				ill_ipsec_capab_send_all(satype, cmp, sa);
19994 				return;
19995 			} else {
19996 				/*
19997 				 * This must be ARP or special TSOL signaling.
19998 				 */
19999 				ip_wput_nondata(NULL, q, mp, NULL);
20000 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20001 				    "ip_wput_end: q %p (%S)", q, "nondata");
20002 				return;
20003 			}
20004 		} else {
20005 			/*
20006 			 * This must be non-(ARP/AH/ESP) messages.
20007 			 */
20008 			ASSERT(!need_decref);
20009 			ip_wput_nondata(NULL, q, mp, NULL);
20010 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20011 			    "ip_wput_end: q %p (%S)", q, "nondata");
20012 			return;
20013 		}
20014 	} else {
20015 		first_mp = mp;
20016 		mctl_present = B_FALSE;
20017 	}
20018 
20019 	ASSERT(first_mp != NULL);
20020 	/*
20021 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20022 	 * to make sure that this packet goes out on the same interface it
20023 	 * came in. We handle that here.
20024 	 */
20025 	if (mctl_present) {
20026 		uint_t ifindex;
20027 
20028 		io = (ipsec_out_t *)first_mp->b_rptr;
20029 		if (io->ipsec_out_attach_if ||
20030 		    io->ipsec_out_xmit_if ||
20031 		    io->ipsec_out_ip_nexthop) {
20032 			ill_t	*ill;
20033 
20034 			/*
20035 			 * We may have lost the conn context if we are
20036 			 * coming here from ip_newroute(). Copy the
20037 			 * nexthop information.
20038 			 */
20039 			if (io->ipsec_out_ip_nexthop) {
20040 				ip_nexthop = B_TRUE;
20041 				nexthop_addr = io->ipsec_out_nexthop_addr;
20042 
20043 				ipha = (ipha_t *)mp->b_rptr;
20044 				dst = ipha->ipha_dst;
20045 				goto send_from_ill;
20046 			} else {
20047 				ASSERT(io->ipsec_out_ill_index != 0);
20048 				ifindex = io->ipsec_out_ill_index;
20049 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20050 				    NULL, NULL, NULL, NULL);
20051 				/*
20052 				 * ipsec_out_xmit_if bit is used to tell
20053 				 * ip_wput to use the ill to send outgoing data
20054 				 * as we have no conn when data comes from ICMP
20055 				 * error msg routines. Currently this feature is
20056 				 * only used by ip_mrtun_forward routine.
20057 				 */
20058 				if (io->ipsec_out_xmit_if) {
20059 					xmit_ill = ill;
20060 					if (xmit_ill == NULL) {
20061 						ip1dbg(("ip_output:bad ifindex "
20062 						    "for xmit_ill %d\n",
20063 						    ifindex));
20064 						freemsg(first_mp);
20065 						BUMP_MIB(&ip_mib,
20066 						    ipOutDiscards);
20067 						ASSERT(!need_decref);
20068 						return;
20069 					}
20070 					/* Free up the ipsec_out_t mblk */
20071 					ASSERT(first_mp->b_cont == mp);
20072 					first_mp->b_cont = NULL;
20073 					freeb(first_mp);
20074 					/* Just send the IP header+ICMP+data */
20075 					first_mp = mp;
20076 					ipha = (ipha_t *)mp->b_rptr;
20077 					dst = ipha->ipha_dst;
20078 					goto send_from_ill;
20079 				} else {
20080 					attach_ill = ill;
20081 				}
20082 
20083 				if (attach_ill == NULL) {
20084 					ASSERT(xmit_ill == NULL);
20085 					ip1dbg(("ip_output: bad ifindex for "
20086 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20087 					    ifindex));
20088 					freemsg(first_mp);
20089 					BUMP_MIB(&ip_mib, ipOutDiscards);
20090 					ASSERT(!need_decref);
20091 					return;
20092 				}
20093 			}
20094 		}
20095 	}
20096 
20097 	ASSERT(xmit_ill == NULL);
20098 
20099 	/* We have a complete IP datagram heading outbound. */
20100 	ipha = (ipha_t *)mp->b_rptr;
20101 
20102 #ifndef SPEED_BEFORE_SAFETY
20103 	/*
20104 	 * Make sure we have a full-word aligned message and that at least
20105 	 * a simple IP header is accessible in the first message.  If not,
20106 	 * try a pullup.
20107 	 */
20108 	if (!OK_32PTR(rptr) ||
20109 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20110 	    hdrtoosmall:
20111 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20112 			BUMP_MIB(&ip_mib, ipOutDiscards);
20113 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20114 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20115 			if (first_mp == NULL)
20116 				first_mp = mp;
20117 			goto drop_pkt;
20118 		}
20119 
20120 		/* This function assumes that mp points to an IPv4 packet. */
20121 		if (is_system_labeled() && q->q_next == NULL &&
20122 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20123 		    !connp->conn_ulp_labeled) {
20124 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20125 			    &adjust, connp->conn_mac_exempt);
20126 			ipha = (ipha_t *)mp->b_rptr;
20127 			if (first_mp != NULL)
20128 				first_mp->b_cont = mp;
20129 			if (err != 0) {
20130 				if (first_mp == NULL)
20131 					first_mp = mp;
20132 				if (err == EINVAL)
20133 					goto icmp_parameter_problem;
20134 				ip2dbg(("ip_wput: label check failed (%d)\n",
20135 				    err));
20136 				goto drop_pkt;
20137 			}
20138 			iplen = ntohs(ipha->ipha_length) + adjust;
20139 			ipha->ipha_length = htons(iplen);
20140 		}
20141 
20142 		ipha = (ipha_t *)mp->b_rptr;
20143 		if (first_mp == NULL) {
20144 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20145 			/*
20146 			 * If we got here because of "goto hdrtoosmall"
20147 			 * We need to attach a IPSEC_OUT.
20148 			 */
20149 			if (connp->conn_out_enforce_policy) {
20150 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20151 				    NULL, ipha->ipha_protocol)) == NULL)) {
20152 					if (need_decref)
20153 						CONN_DEC_REF(connp);
20154 					return;
20155 				} else {
20156 					ASSERT(mp->b_datap->db_type == M_CTL);
20157 					first_mp = mp;
20158 					mp = mp->b_cont;
20159 					mctl_present = B_TRUE;
20160 				}
20161 			} else {
20162 				first_mp = mp;
20163 				mctl_present = B_FALSE;
20164 			}
20165 		}
20166 	}
20167 #endif
20168 
20169 	/* Most of the code below is written for speed, not readability */
20170 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20171 
20172 	/*
20173 	 * If ip_newroute() fails, we're going to need a full
20174 	 * header for the icmp wraparound.
20175 	 */
20176 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20177 		uint_t	v_hlen;
20178 	    version_hdrlen_check:
20179 		ASSERT(first_mp != NULL);
20180 		v_hlen = V_HLEN;
20181 		/*
20182 		 * siphon off IPv6 packets coming down from transport
20183 		 * layer modules here.
20184 		 * Note: high-order bit carries NUD reachability confirmation
20185 		 */
20186 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20187 			/*
20188 			 * XXX implement a IPv4 and IPv6 packet counter per
20189 			 * conn and switch when ratio exceeds e.g. 10:1
20190 			 */
20191 #ifdef notyet
20192 			if (q->q_next == NULL) /* Avoid ill queue */
20193 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20194 #endif
20195 			BUMP_MIB(&ip_mib, ipOutIPv6);
20196 			ASSERT(xmit_ill == NULL);
20197 			if (attach_ill != NULL)
20198 				ill_refrele(attach_ill);
20199 			if (need_decref)
20200 				mp->b_flag |= MSGHASREF;
20201 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20202 			return;
20203 		}
20204 
20205 		if ((v_hlen >> 4) != IP_VERSION) {
20206 			BUMP_MIB(&ip_mib, ipOutDiscards);
20207 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20208 			    "ip_wput_end: q %p (%S)", q, "badvers");
20209 			goto drop_pkt;
20210 		}
20211 		/*
20212 		 * Is the header length at least 20 bytes?
20213 		 *
20214 		 * Are there enough bytes accessible in the header?  If
20215 		 * not, try a pullup.
20216 		 */
20217 		v_hlen &= 0xF;
20218 		v_hlen <<= 2;
20219 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20220 			BUMP_MIB(&ip_mib, ipOutDiscards);
20221 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20222 			    "ip_wput_end: q %p (%S)", q, "badlen");
20223 			goto drop_pkt;
20224 		}
20225 		if (v_hlen > (mp->b_wptr - rptr)) {
20226 			if (!pullupmsg(mp, v_hlen)) {
20227 				BUMP_MIB(&ip_mib, ipOutDiscards);
20228 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20229 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20230 				goto drop_pkt;
20231 			}
20232 			ipha = (ipha_t *)mp->b_rptr;
20233 		}
20234 		/*
20235 		 * Move first entry from any source route into ipha_dst and
20236 		 * verify the options
20237 		 */
20238 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20239 			ASSERT(xmit_ill == NULL);
20240 			if (attach_ill != NULL)
20241 				ill_refrele(attach_ill);
20242 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20243 			    "ip_wput_end: q %p (%S)", q, "badopts");
20244 			if (need_decref)
20245 				CONN_DEC_REF(connp);
20246 			return;
20247 		}
20248 	}
20249 	dst = ipha->ipha_dst;
20250 
20251 	/*
20252 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20253 	 * we have to run the packet through ip_newroute which will take
20254 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20255 	 * a resolver, or assigning a default gateway, etc.
20256 	 */
20257 	if (CLASSD(dst)) {
20258 		ipif_t	*ipif;
20259 		uint32_t setsrc = 0;
20260 
20261 	    multicast:
20262 		ASSERT(first_mp != NULL);
20263 		ASSERT(xmit_ill == NULL);
20264 		ip2dbg(("ip_wput: CLASSD\n"));
20265 		if (connp == NULL) {
20266 			/*
20267 			 * Use the first good ipif on the ill.
20268 			 * XXX Should this ever happen? (Appears
20269 			 * to show up with just ppp and no ethernet due
20270 			 * to in.rdisc.)
20271 			 * However, ire_send should be able to
20272 			 * call ip_wput_ire directly.
20273 			 *
20274 			 * XXX Also, this can happen for ICMP and other packets
20275 			 * with multicast source addresses.  Perhaps we should
20276 			 * fix things so that we drop the packet in question,
20277 			 * but for now, just run with it.
20278 			 */
20279 			ill_t *ill = (ill_t *)q->q_ptr;
20280 
20281 			/*
20282 			 * Don't honor attach_if for this case. If ill
20283 			 * is part of the group, ipif could belong to
20284 			 * any ill and we cannot maintain attach_ill
20285 			 * and ipif_ill same anymore and the assert
20286 			 * below would fail.
20287 			 */
20288 			if (mctl_present && io->ipsec_out_attach_if) {
20289 				io->ipsec_out_ill_index = 0;
20290 				io->ipsec_out_attach_if = B_FALSE;
20291 				ASSERT(attach_ill != NULL);
20292 				ill_refrele(attach_ill);
20293 				attach_ill = NULL;
20294 			}
20295 
20296 			ASSERT(attach_ill == NULL);
20297 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20298 			if (ipif == NULL) {
20299 				if (need_decref)
20300 					CONN_DEC_REF(connp);
20301 				freemsg(first_mp);
20302 				return;
20303 			}
20304 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20305 			    ntohl(dst), ill->ill_name));
20306 		} else {
20307 			/*
20308 			 * If both IP_MULTICAST_IF and IP_XMIT_IF are set,
20309 			 * IP_XMIT_IF is honoured.
20310 			 * Block comment above this function explains the
20311 			 * locking mechanism used here
20312 			 */
20313 			xmit_ill = conn_get_held_ill(connp,
20314 			    &connp->conn_xmit_if_ill, &err);
20315 			if (err == ILL_LOOKUP_FAILED) {
20316 				ip1dbg(("ip_wput: No ill for IP_XMIT_IF\n"));
20317 				goto drop_pkt;
20318 			}
20319 			if (xmit_ill == NULL) {
20320 				ipif = conn_get_held_ipif(connp,
20321 				    &connp->conn_multicast_ipif, &err);
20322 				if (err == IPIF_LOOKUP_FAILED) {
20323 					ip1dbg(("ip_wput: No ipif for "
20324 					    "multicast\n"));
20325 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20326 					goto drop_pkt;
20327 				}
20328 			}
20329 			if (xmit_ill != NULL) {
20330 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20331 				if (ipif == NULL) {
20332 					ip1dbg(("ip_wput: No ipif for "
20333 					    "IP_XMIT_IF\n"));
20334 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20335 					goto drop_pkt;
20336 				}
20337 			} else if (ipif == NULL || ipif->ipif_isv6) {
20338 				/*
20339 				 * We must do this ipif determination here
20340 				 * else we could pass through ip_newroute
20341 				 * and come back here without the conn context.
20342 				 *
20343 				 * Note: we do late binding i.e. we bind to
20344 				 * the interface when the first packet is sent.
20345 				 * For performance reasons we do not rebind on
20346 				 * each packet but keep the binding until the
20347 				 * next IP_MULTICAST_IF option.
20348 				 *
20349 				 * conn_multicast_{ipif,ill} are shared between
20350 				 * IPv4 and IPv6 and AF_INET6 sockets can
20351 				 * send both IPv4 and IPv6 packets. Hence
20352 				 * we have to check that "isv6" matches above.
20353 				 */
20354 				if (ipif != NULL)
20355 					ipif_refrele(ipif);
20356 				ipif = ipif_lookup_group(dst, zoneid);
20357 				if (ipif == NULL) {
20358 					ip1dbg(("ip_wput: No ipif for "
20359 					    "multicast\n"));
20360 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20361 					goto drop_pkt;
20362 				}
20363 				err = conn_set_held_ipif(connp,
20364 				    &connp->conn_multicast_ipif, ipif);
20365 				if (err == IPIF_LOOKUP_FAILED) {
20366 					ipif_refrele(ipif);
20367 					ip1dbg(("ip_wput: No ipif for "
20368 					    "multicast\n"));
20369 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20370 					goto drop_pkt;
20371 				}
20372 			}
20373 		}
20374 		ASSERT(!ipif->ipif_isv6);
20375 		/*
20376 		 * As we may lose the conn by the time we reach ip_wput_ire,
20377 		 * we copy conn_multicast_loop and conn_dontroute on to an
20378 		 * ipsec_out. In case if this datagram goes out secure,
20379 		 * we need the ill_index also. Copy that also into the
20380 		 * ipsec_out.
20381 		 */
20382 		if (mctl_present) {
20383 			io = (ipsec_out_t *)first_mp->b_rptr;
20384 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20385 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20386 		} else {
20387 			ASSERT(mp == first_mp);
20388 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20389 			    BPRI_HI)) == NULL) {
20390 				ipif_refrele(ipif);
20391 				first_mp = mp;
20392 				goto drop_pkt;
20393 			}
20394 			first_mp->b_datap->db_type = M_CTL;
20395 			first_mp->b_wptr += sizeof (ipsec_info_t);
20396 			/* ipsec_out_secure is B_FALSE now */
20397 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20398 			io = (ipsec_out_t *)first_mp->b_rptr;
20399 			io->ipsec_out_type = IPSEC_OUT;
20400 			io->ipsec_out_len = sizeof (ipsec_out_t);
20401 			io->ipsec_out_use_global_policy = B_TRUE;
20402 			first_mp->b_cont = mp;
20403 			mctl_present = B_TRUE;
20404 		}
20405 		if (attach_ill != NULL) {
20406 			ASSERT(attach_ill == ipif->ipif_ill);
20407 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20408 
20409 			/*
20410 			 * Check if we need an ire that will not be
20411 			 * looked up by anybody else i.e. HIDDEN.
20412 			 */
20413 			if (ill_is_probeonly(attach_ill)) {
20414 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20415 			}
20416 			io->ipsec_out_ill_index =
20417 			    attach_ill->ill_phyint->phyint_ifindex;
20418 			io->ipsec_out_attach_if = B_TRUE;
20419 		} else {
20420 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20421 			io->ipsec_out_ill_index =
20422 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20423 		}
20424 		if (connp != NULL) {
20425 			io->ipsec_out_multicast_loop =
20426 			    connp->conn_multicast_loop;
20427 			io->ipsec_out_dontroute = connp->conn_dontroute;
20428 			io->ipsec_out_zoneid = connp->conn_zoneid;
20429 		}
20430 		/*
20431 		 * If the application uses IP_MULTICAST_IF with
20432 		 * different logical addresses of the same ILL, we
20433 		 * need to make sure that the soruce address of
20434 		 * the packet matches the logical IP address used
20435 		 * in the option. We do it by initializing ipha_src
20436 		 * here. This should keep IPSEC also happy as
20437 		 * when we return from IPSEC processing, we don't
20438 		 * have to worry about getting the right address on
20439 		 * the packet. Thus it is sufficient to look for
20440 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20441 		 * MATCH_IRE_IPIF.
20442 		 *
20443 		 * NOTE : We need to do it for non-secure case also as
20444 		 * this might go out secure if there is a global policy
20445 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20446 		 * address, the source should be initialized already and
20447 		 * hence we won't be initializing here.
20448 		 *
20449 		 * As we do not have the ire yet, it is possible that
20450 		 * we set the source address here and then later discover
20451 		 * that the ire implies the source address to be assigned
20452 		 * through the RTF_SETSRC flag.
20453 		 * In that case, the setsrc variable will remind us
20454 		 * that overwritting the source address by the one
20455 		 * of the RTF_SETSRC-flagged ire is allowed.
20456 		 */
20457 		if (ipha->ipha_src == INADDR_ANY &&
20458 		    (connp == NULL || !connp->conn_unspec_src)) {
20459 			ipha->ipha_src = ipif->ipif_src_addr;
20460 			setsrc = RTF_SETSRC;
20461 		}
20462 		/*
20463 		 * Find an IRE which matches the destination and the outgoing
20464 		 * queue (i.e. the outgoing interface.)
20465 		 * For loopback use a unicast IP address for
20466 		 * the ire lookup.
20467 		 */
20468 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
20469 		    PHYI_LOOPBACK) {
20470 			dst = ipif->ipif_lcl_addr;
20471 		}
20472 		/*
20473 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20474 		 * We don't need to lookup ire in ctable as the packet
20475 		 * needs to be sent to the destination through the specified
20476 		 * ill irrespective of ires in the cache table.
20477 		 */
20478 		ire = NULL;
20479 		if (xmit_ill == NULL) {
20480 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20481 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20482 		}
20483 
20484 		/*
20485 		 * refrele attach_ill as its not needed anymore.
20486 		 */
20487 		if (attach_ill != NULL) {
20488 			ill_refrele(attach_ill);
20489 			attach_ill = NULL;
20490 		}
20491 
20492 		if (ire == NULL) {
20493 			/*
20494 			 * Multicast loopback and multicast forwarding is
20495 			 * done in ip_wput_ire.
20496 			 *
20497 			 * Mark this packet to make it be delivered to
20498 			 * ip_wput_ire after the new ire has been
20499 			 * created.
20500 			 *
20501 			 * The call to ip_newroute_ipif takes into account
20502 			 * the setsrc reminder. In any case, we take care
20503 			 * of the RTF_MULTIRT flag.
20504 			 */
20505 			mp->b_prev = mp->b_next = NULL;
20506 			if (xmit_ill == NULL ||
20507 			    xmit_ill->ill_ipif_up_count > 0) {
20508 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20509 				    setsrc | RTF_MULTIRT, zoneid);
20510 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20511 				    "ip_wput_end: q %p (%S)", q, "noire");
20512 			} else {
20513 				freemsg(first_mp);
20514 			}
20515 			ipif_refrele(ipif);
20516 			if (xmit_ill != NULL)
20517 				ill_refrele(xmit_ill);
20518 			if (need_decref)
20519 				CONN_DEC_REF(connp);
20520 			return;
20521 		}
20522 
20523 		ipif_refrele(ipif);
20524 		ipif = NULL;
20525 		ASSERT(xmit_ill == NULL);
20526 
20527 		/*
20528 		 * Honor the RTF_SETSRC flag for multicast packets,
20529 		 * if allowed by the setsrc reminder.
20530 		 */
20531 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20532 			ipha->ipha_src = ire->ire_src_addr;
20533 		}
20534 
20535 		/*
20536 		 * Unconditionally force the TTL to 1 for
20537 		 * multirouted multicast packets:
20538 		 * multirouted multicast should not cross
20539 		 * multicast routers.
20540 		 */
20541 		if (ire->ire_flags & RTF_MULTIRT) {
20542 			if (ipha->ipha_ttl > 1) {
20543 				ip2dbg(("ip_wput: forcing multicast "
20544 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20545 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20546 				ipha->ipha_ttl = 1;
20547 			}
20548 		}
20549 	} else {
20550 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20551 		if ((ire != NULL) && (ire->ire_type &
20552 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20553 			ignore_dontroute = B_TRUE;
20554 			ignore_nexthop = B_TRUE;
20555 		}
20556 		if (ire != NULL) {
20557 			ire_refrele(ire);
20558 			ire = NULL;
20559 		}
20560 		/*
20561 		 * Guard against coming in from arp in which case conn is NULL.
20562 		 * Also guard against non M_DATA with dontroute set but
20563 		 * destined to local, loopback or broadcast addresses.
20564 		 */
20565 		if (connp != NULL && connp->conn_dontroute &&
20566 		    !ignore_dontroute) {
20567 dontroute:
20568 			/*
20569 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20570 			 * routing protocols from seeing false direct
20571 			 * connectivity.
20572 			 */
20573 			ipha->ipha_ttl = 1;
20574 			/*
20575 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20576 			 * along with SO_DONTROUTE, higher precedence is
20577 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20578 			 */
20579 			if (connp->conn_xmit_if_ill == NULL) {
20580 				/* If suitable ipif not found, drop packet */
20581 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
20582 				if (dst_ipif == NULL) {
20583 					ip1dbg(("ip_wput: no route for "
20584 					    "dst using SO_DONTROUTE\n"));
20585 					BUMP_MIB(&ip_mib, ipOutNoRoutes);
20586 					mp->b_prev = mp->b_next = NULL;
20587 					if (first_mp == NULL)
20588 						first_mp = mp;
20589 					goto drop_pkt;
20590 				} else {
20591 					/*
20592 					 * If suitable ipif has been found, set
20593 					 * xmit_ill to the corresponding
20594 					 * ipif_ill because we'll be following
20595 					 * the IP_XMIT_IF logic.
20596 					 */
20597 					ASSERT(xmit_ill == NULL);
20598 					xmit_ill = dst_ipif->ipif_ill;
20599 					mutex_enter(&xmit_ill->ill_lock);
20600 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20601 						mutex_exit(&xmit_ill->ill_lock);
20602 						xmit_ill = NULL;
20603 						ipif_refrele(dst_ipif);
20604 						ip1dbg(("ip_wput: no route for"
20605 						    " dst using"
20606 						    " SO_DONTROUTE\n"));
20607 						BUMP_MIB(&ip_mib,
20608 						    ipOutNoRoutes);
20609 						mp->b_prev = mp->b_next = NULL;
20610 						if (first_mp == NULL)
20611 							first_mp = mp;
20612 						goto drop_pkt;
20613 					}
20614 					ill_refhold_locked(xmit_ill);
20615 					mutex_exit(&xmit_ill->ill_lock);
20616 					ipif_refrele(dst_ipif);
20617 				}
20618 			}
20619 
20620 		}
20621 		/*
20622 		 * If we are bound to IPIF_NOFAILOVER address, look for
20623 		 * an IRE_CACHE matching the ill.
20624 		 */
20625 send_from_ill:
20626 		if (attach_ill != NULL) {
20627 			ipif_t	*attach_ipif;
20628 
20629 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20630 
20631 			/*
20632 			 * Check if we need an ire that will not be
20633 			 * looked up by anybody else i.e. HIDDEN.
20634 			 */
20635 			if (ill_is_probeonly(attach_ill)) {
20636 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20637 			}
20638 
20639 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20640 			if (attach_ipif == NULL) {
20641 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20642 				goto drop_pkt;
20643 			}
20644 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20645 			    zoneid, MBLK_GETLABEL(mp), match_flags);
20646 			ipif_refrele(attach_ipif);
20647 		} else if (xmit_ill != NULL || (connp != NULL &&
20648 			    connp->conn_xmit_if_ill != NULL)) {
20649 			/*
20650 			 * Mark this packet as originated locally
20651 			 */
20652 			mp->b_prev = mp->b_next = NULL;
20653 			/*
20654 			 * xmit_ill could be NULL if SO_DONTROUTE
20655 			 * is also set.
20656 			 */
20657 			if (xmit_ill == NULL) {
20658 				xmit_ill = conn_get_held_ill(connp,
20659 				    &connp->conn_xmit_if_ill, &err);
20660 				if (err == ILL_LOOKUP_FAILED) {
20661 					if (need_decref)
20662 						CONN_DEC_REF(connp);
20663 					freemsg(first_mp);
20664 					return;
20665 				}
20666 				if (xmit_ill == NULL) {
20667 					if (connp->conn_dontroute)
20668 						goto dontroute;
20669 					goto send_from_ill;
20670 				}
20671 			}
20672 			/*
20673 			 * could be SO_DONTROUTE case also.
20674 			 * check at least one interface is UP as
20675 			 * spcified by this ILL, and then call
20676 			 * ip_newroute_ipif()
20677 			 */
20678 			if (xmit_ill->ill_ipif_up_count > 0) {
20679 				ipif_t *ipif;
20680 
20681 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20682 				if (ipif != NULL) {
20683 					ip_newroute_ipif(q, first_mp, ipif,
20684 					    dst, connp, 0, zoneid);
20685 					ipif_refrele(ipif);
20686 					ip1dbg(("ip_wput: ip_unicast_if\n"));
20687 				}
20688 			} else {
20689 				freemsg(first_mp);
20690 			}
20691 			ill_refrele(xmit_ill);
20692 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20693 			    "ip_wput_end: q %p (%S)", q, "unicast_if");
20694 			if (need_decref)
20695 				CONN_DEC_REF(connp);
20696 			return;
20697 		} else if (ip_nexthop || (connp != NULL &&
20698 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
20699 			if (!ip_nexthop) {
20700 				ip_nexthop = B_TRUE;
20701 				nexthop_addr = connp->conn_nexthop_v4;
20702 			}
20703 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
20704 			    MATCH_IRE_GW;
20705 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
20706 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
20707 		} else {
20708 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20709 		}
20710 		if (!ire) {
20711 			/*
20712 			 * Make sure we don't load spread if this
20713 			 * is IPIF_NOFAILOVER case.
20714 			 */
20715 			if ((attach_ill != NULL) ||
20716 			    (ip_nexthop && !ignore_nexthop)) {
20717 				if (mctl_present) {
20718 					io = (ipsec_out_t *)first_mp->b_rptr;
20719 					ASSERT(first_mp->b_datap->db_type ==
20720 					    M_CTL);
20721 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
20722 				} else {
20723 					ASSERT(mp == first_mp);
20724 					first_mp = allocb(
20725 					    sizeof (ipsec_info_t), BPRI_HI);
20726 					if (first_mp == NULL) {
20727 						first_mp = mp;
20728 						goto drop_pkt;
20729 					}
20730 					first_mp->b_datap->db_type = M_CTL;
20731 					first_mp->b_wptr +=
20732 					    sizeof (ipsec_info_t);
20733 					/* ipsec_out_secure is B_FALSE now */
20734 					bzero(first_mp->b_rptr,
20735 					    sizeof (ipsec_info_t));
20736 					io = (ipsec_out_t *)first_mp->b_rptr;
20737 					io->ipsec_out_type = IPSEC_OUT;
20738 					io->ipsec_out_len =
20739 					    sizeof (ipsec_out_t);
20740 					io->ipsec_out_use_global_policy =
20741 					    B_TRUE;
20742 					first_mp->b_cont = mp;
20743 					mctl_present = B_TRUE;
20744 				}
20745 				if (attach_ill != NULL) {
20746 					io->ipsec_out_ill_index = attach_ill->
20747 					    ill_phyint->phyint_ifindex;
20748 					io->ipsec_out_attach_if = B_TRUE;
20749 				} else {
20750 					io->ipsec_out_ip_nexthop = ip_nexthop;
20751 					io->ipsec_out_nexthop_addr =
20752 					    nexthop_addr;
20753 				}
20754 			}
20755 noirefound:
20756 			/*
20757 			 * Mark this packet as having originated on
20758 			 * this machine.  This will be noted in
20759 			 * ire_add_then_send, which needs to know
20760 			 * whether to run it back through ip_wput or
20761 			 * ip_rput following successful resolution.
20762 			 */
20763 			mp->b_prev = NULL;
20764 			mp->b_next = NULL;
20765 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
20766 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20767 			    "ip_wput_end: q %p (%S)", q, "newroute");
20768 			if (attach_ill != NULL)
20769 				ill_refrele(attach_ill);
20770 			if (xmit_ill != NULL)
20771 				ill_refrele(xmit_ill);
20772 			if (need_decref)
20773 				CONN_DEC_REF(connp);
20774 			return;
20775 		}
20776 	}
20777 
20778 	/* We now know where we are going with it. */
20779 
20780 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20781 	    "ip_wput_end: q %p (%S)", q, "end");
20782 
20783 	/*
20784 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20785 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
20786 	 */
20787 	if (ire->ire_flags & RTF_MULTIRT) {
20788 		/*
20789 		 * Force the TTL of multirouted packets if required.
20790 		 * The TTL of such packets is bounded by the
20791 		 * ip_multirt_ttl ndd variable.
20792 		 */
20793 		if ((ip_multirt_ttl > 0) &&
20794 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20795 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20796 			    "(was %d), dst 0x%08x\n",
20797 			    ip_multirt_ttl, ipha->ipha_ttl,
20798 			    ntohl(ire->ire_addr)));
20799 			ipha->ipha_ttl = ip_multirt_ttl;
20800 		}
20801 		/*
20802 		 * At this point, we check to see if there are any pending
20803 		 * unresolved routes. ire_multirt_resolvable()
20804 		 * checks in O(n) that all IRE_OFFSUBNET ire
20805 		 * entries for the packet's destination and
20806 		 * flagged RTF_MULTIRT are currently resolved.
20807 		 * If some remain unresolved, we make a copy
20808 		 * of the current message. It will be used
20809 		 * to initiate additional route resolutions.
20810 		 */
20811 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20812 		    MBLK_GETLABEL(first_mp));
20813 		ip2dbg(("ip_wput[noirefound]: ire %p, "
20814 		    "multirt_need_resolve %d, first_mp %p\n",
20815 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20816 		if (multirt_need_resolve) {
20817 			copy_mp = copymsg(first_mp);
20818 			if (copy_mp != NULL) {
20819 				MULTIRT_DEBUG_TAG(copy_mp);
20820 			}
20821 		}
20822 	}
20823 
20824 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20825 	/*
20826 	 * Try to resolve another multiroute if
20827 	 * ire_multirt_resolvable() deemed it necessary.
20828 	 * At this point, we need to distinguish
20829 	 * multicasts from other packets. For multicasts,
20830 	 * we call ip_newroute_ipif() and request that both
20831 	 * multirouting and setsrc flags are checked.
20832 	 */
20833 	if (copy_mp != NULL) {
20834 		if (CLASSD(dst)) {
20835 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
20836 			if (ipif) {
20837 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
20838 				    RTF_SETSRC | RTF_MULTIRT, zoneid);
20839 				ipif_refrele(ipif);
20840 			} else {
20841 				MULTIRT_DEBUG_UNTAG(copy_mp);
20842 				freemsg(copy_mp);
20843 				copy_mp = NULL;
20844 			}
20845 		} else {
20846 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20847 		}
20848 	}
20849 	if (attach_ill != NULL)
20850 		ill_refrele(attach_ill);
20851 	if (xmit_ill != NULL)
20852 		ill_refrele(xmit_ill);
20853 	if (need_decref)
20854 		CONN_DEC_REF(connp);
20855 	return;
20856 
20857 icmp_parameter_problem:
20858 	/* could not have originated externally */
20859 	ASSERT(mp->b_prev == NULL);
20860 	if (ip_hdr_complete(ipha, zoneid) == 0) {
20861 		BUMP_MIB(&ip_mib, ipOutNoRoutes);
20862 		/* it's the IP header length that's in trouble */
20863 		icmp_param_problem(q, first_mp, 0, zoneid);
20864 		first_mp = NULL;
20865 	}
20866 
20867 drop_pkt:
20868 	ip1dbg(("ip_wput: dropped packet\n"));
20869 	if (ire != NULL)
20870 		ire_refrele(ire);
20871 	if (need_decref)
20872 		CONN_DEC_REF(connp);
20873 	freemsg(first_mp);
20874 	if (attach_ill != NULL)
20875 		ill_refrele(attach_ill);
20876 	if (xmit_ill != NULL)
20877 		ill_refrele(xmit_ill);
20878 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20879 	    "ip_wput_end: q %p (%S)", q, "droppkt");
20880 }
20881 
20882 /*
20883  * If this is a conn_t queue, then we pass in the conn. This includes the
20884  * zoneid.
20885  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
20886  * in which case we use the global zoneid since those are all part of
20887  * the global zone.
20888  */
20889 void
20890 ip_wput(queue_t *q, mblk_t *mp)
20891 {
20892 	if (CONN_Q(q))
20893 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
20894 	else
20895 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
20896 }
20897 
20898 /*
20899  *
20900  * The following rules must be observed when accessing any ipif or ill
20901  * that has been cached in the conn. Typically conn_nofailover_ill,
20902  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
20903  *
20904  * Access: The ipif or ill pointed to from the conn can be accessed under
20905  * the protection of the conn_lock or after it has been refheld under the
20906  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
20907  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
20908  * The reason for this is that a concurrent unplumb could actually be
20909  * cleaning up these cached pointers by walking the conns and might have
20910  * finished cleaning up the conn in question. The macros check that an
20911  * unplumb has not yet started on the ipif or ill.
20912  *
20913  * Caching: An ipif or ill pointer may be cached in the conn only after
20914  * making sure that an unplumb has not started. So the caching is done
20915  * while holding both the conn_lock and the ill_lock and after using the
20916  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
20917  * flag before starting the cleanup of conns.
20918  *
20919  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
20920  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
20921  * or a reference to the ipif or a reference to an ire that references the
20922  * ipif. An ipif does not change its ill except for failover/failback. Since
20923  * failover/failback happens only after bringing down the ipif and making sure
20924  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
20925  * the above holds.
20926  */
20927 ipif_t *
20928 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
20929 {
20930 	ipif_t	*ipif;
20931 	ill_t	*ill;
20932 
20933 	*err = 0;
20934 	rw_enter(&ill_g_lock, RW_READER);
20935 	mutex_enter(&connp->conn_lock);
20936 	ipif = *ipifp;
20937 	if (ipif != NULL) {
20938 		ill = ipif->ipif_ill;
20939 		mutex_enter(&ill->ill_lock);
20940 		if (IPIF_CAN_LOOKUP(ipif)) {
20941 			ipif_refhold_locked(ipif);
20942 			mutex_exit(&ill->ill_lock);
20943 			mutex_exit(&connp->conn_lock);
20944 			rw_exit(&ill_g_lock);
20945 			return (ipif);
20946 		} else {
20947 			*err = IPIF_LOOKUP_FAILED;
20948 		}
20949 		mutex_exit(&ill->ill_lock);
20950 	}
20951 	mutex_exit(&connp->conn_lock);
20952 	rw_exit(&ill_g_lock);
20953 	return (NULL);
20954 }
20955 
20956 ill_t *
20957 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
20958 {
20959 	ill_t	*ill;
20960 
20961 	*err = 0;
20962 	mutex_enter(&connp->conn_lock);
20963 	ill = *illp;
20964 	if (ill != NULL) {
20965 		mutex_enter(&ill->ill_lock);
20966 		if (ILL_CAN_LOOKUP(ill)) {
20967 			ill_refhold_locked(ill);
20968 			mutex_exit(&ill->ill_lock);
20969 			mutex_exit(&connp->conn_lock);
20970 			return (ill);
20971 		} else {
20972 			*err = ILL_LOOKUP_FAILED;
20973 		}
20974 		mutex_exit(&ill->ill_lock);
20975 	}
20976 	mutex_exit(&connp->conn_lock);
20977 	return (NULL);
20978 }
20979 
20980 static int
20981 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
20982 {
20983 	ill_t	*ill;
20984 
20985 	ill = ipif->ipif_ill;
20986 	mutex_enter(&connp->conn_lock);
20987 	mutex_enter(&ill->ill_lock);
20988 	if (IPIF_CAN_LOOKUP(ipif)) {
20989 		*ipifp = ipif;
20990 		mutex_exit(&ill->ill_lock);
20991 		mutex_exit(&connp->conn_lock);
20992 		return (0);
20993 	}
20994 	mutex_exit(&ill->ill_lock);
20995 	mutex_exit(&connp->conn_lock);
20996 	return (IPIF_LOOKUP_FAILED);
20997 }
20998 
20999 /*
21000  * This is called if the outbound datagram needs fragmentation.
21001  *
21002  * NOTE : This function does not ire_refrele the ire argument passed in.
21003  */
21004 static void
21005 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21006 {
21007 	ipha_t		*ipha;
21008 	mblk_t		*mp;
21009 	uint32_t	v_hlen_tos_len;
21010 	uint32_t	max_frag;
21011 	uint32_t	frag_flag;
21012 	boolean_t	dont_use;
21013 
21014 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21015 		mp = ipsec_mp->b_cont;
21016 	} else {
21017 		mp = ipsec_mp;
21018 	}
21019 
21020 	ipha = (ipha_t *)mp->b_rptr;
21021 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21022 
21023 #ifdef	_BIG_ENDIAN
21024 #define	V_HLEN	(v_hlen_tos_len >> 24)
21025 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21026 #else
21027 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21028 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21029 #endif
21030 
21031 #ifndef SPEED_BEFORE_SAFETY
21032 	/*
21033 	 * Check that ipha_length is consistent with
21034 	 * the mblk length
21035 	 */
21036 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21037 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21038 		    LENGTH, msgdsize(mp)));
21039 		freemsg(ipsec_mp);
21040 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21041 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21042 		    "packet length mismatch");
21043 		return;
21044 	}
21045 #endif
21046 	/*
21047 	 * Don't use frag_flag if pre-built packet or source
21048 	 * routed or if multicast (since multicast packets do not solicit
21049 	 * ICMP "packet too big" messages). Get the values of
21050 	 * max_frag and frag_flag atomically by acquiring the
21051 	 * ire_lock.
21052 	 */
21053 	mutex_enter(&ire->ire_lock);
21054 	max_frag = ire->ire_max_frag;
21055 	frag_flag = ire->ire_frag_flag;
21056 	mutex_exit(&ire->ire_lock);
21057 
21058 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21059 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21060 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21061 
21062 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21063 	    (dont_use ? 0 : frag_flag), zoneid);
21064 }
21065 
21066 /*
21067  * Used for deciding the MSS size for the upper layer. Thus
21068  * we need to check the outbound policy values in the conn.
21069  */
21070 int
21071 conn_ipsec_length(conn_t *connp)
21072 {
21073 	ipsec_latch_t *ipl;
21074 
21075 	ipl = connp->conn_latch;
21076 	if (ipl == NULL)
21077 		return (0);
21078 
21079 	if (ipl->ipl_out_policy == NULL)
21080 		return (0);
21081 
21082 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21083 }
21084 
21085 /*
21086  * Returns an estimate of the IPSEC headers size. This is used if
21087  * we don't want to call into IPSEC to get the exact size.
21088  */
21089 int
21090 ipsec_out_extra_length(mblk_t *ipsec_mp)
21091 {
21092 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21093 	ipsec_action_t *a;
21094 
21095 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21096 	if (!io->ipsec_out_secure)
21097 		return (0);
21098 
21099 	a = io->ipsec_out_act;
21100 
21101 	if (a == NULL) {
21102 		ASSERT(io->ipsec_out_policy != NULL);
21103 		a = io->ipsec_out_policy->ipsp_act;
21104 	}
21105 	ASSERT(a != NULL);
21106 
21107 	return (a->ipa_ovhd);
21108 }
21109 
21110 /*
21111  * Returns an estimate of the IPSEC headers size. This is used if
21112  * we don't want to call into IPSEC to get the exact size.
21113  */
21114 int
21115 ipsec_in_extra_length(mblk_t *ipsec_mp)
21116 {
21117 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21118 	ipsec_action_t *a;
21119 
21120 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21121 
21122 	a = ii->ipsec_in_action;
21123 	return (a == NULL ? 0 : a->ipa_ovhd);
21124 }
21125 
21126 /*
21127  * If there are any source route options, return the true final
21128  * destination. Otherwise, return the destination.
21129  */
21130 ipaddr_t
21131 ip_get_dst(ipha_t *ipha)
21132 {
21133 	ipoptp_t	opts;
21134 	uchar_t		*opt;
21135 	uint8_t		optval;
21136 	uint8_t		optlen;
21137 	ipaddr_t	dst;
21138 	uint32_t off;
21139 
21140 	dst = ipha->ipha_dst;
21141 
21142 	if (IS_SIMPLE_IPH(ipha))
21143 		return (dst);
21144 
21145 	for (optval = ipoptp_first(&opts, ipha);
21146 	    optval != IPOPT_EOL;
21147 	    optval = ipoptp_next(&opts)) {
21148 		opt = opts.ipoptp_cur;
21149 		optlen = opts.ipoptp_len;
21150 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21151 		switch (optval) {
21152 		case IPOPT_SSRR:
21153 		case IPOPT_LSRR:
21154 			off = opt[IPOPT_OFFSET];
21155 			/*
21156 			 * If one of the conditions is true, it means
21157 			 * end of options and dst already has the right
21158 			 * value.
21159 			 */
21160 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21161 				off = optlen - IP_ADDR_LEN;
21162 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21163 			}
21164 			return (dst);
21165 		default:
21166 			break;
21167 		}
21168 	}
21169 
21170 	return (dst);
21171 }
21172 
21173 mblk_t *
21174 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21175     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21176 {
21177 	ipsec_out_t	*io;
21178 	mblk_t		*first_mp;
21179 	boolean_t policy_present;
21180 
21181 	first_mp = mp;
21182 	if (mp->b_datap->db_type == M_CTL) {
21183 		io = (ipsec_out_t *)first_mp->b_rptr;
21184 		/*
21185 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21186 		 *
21187 		 * 1) There is per-socket policy (including cached global
21188 		 *    policy) or a policy on the IP-in-IP tunnel.
21189 		 * 2) There is no per-socket policy, but it is
21190 		 *    a multicast packet that needs to go out
21191 		 *    on a specific interface. This is the case
21192 		 *    where (ip_wput and ip_wput_multicast) attaches
21193 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21194 		 *
21195 		 * In case (2) we check with global policy to
21196 		 * see if there is a match and set the ill_index
21197 		 * appropriately so that we can lookup the ire
21198 		 * properly in ip_wput_ipsec_out.
21199 		 */
21200 
21201 		/*
21202 		 * ipsec_out_use_global_policy is set to B_FALSE
21203 		 * in ipsec_in_to_out(). Refer to that function for
21204 		 * details.
21205 		 */
21206 		if ((io->ipsec_out_latch == NULL) &&
21207 		    (io->ipsec_out_use_global_policy)) {
21208 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21209 				    ire, connp, unspec_src, zoneid));
21210 		}
21211 		if (!io->ipsec_out_secure) {
21212 			/*
21213 			 * If this is not a secure packet, drop
21214 			 * the IPSEC_OUT mp and treat it as a clear
21215 			 * packet. This happens when we are sending
21216 			 * a ICMP reply back to a clear packet. See
21217 			 * ipsec_in_to_out() for details.
21218 			 */
21219 			mp = first_mp->b_cont;
21220 			freeb(first_mp);
21221 		}
21222 		return (mp);
21223 	}
21224 	/*
21225 	 * See whether we need to attach a global policy here. We
21226 	 * don't depend on the conn (as it could be null) for deciding
21227 	 * what policy this datagram should go through because it
21228 	 * should have happened in ip_wput if there was some
21229 	 * policy. This normally happens for connections which are not
21230 	 * fully bound preventing us from caching policies in
21231 	 * ip_bind. Packets coming from the TCP listener/global queue
21232 	 * - which are non-hard_bound - could also be affected by
21233 	 * applying policy here.
21234 	 *
21235 	 * If this packet is coming from tcp global queue or listener,
21236 	 * we will be applying policy here.  This may not be *right*
21237 	 * if these packets are coming from the detached connection as
21238 	 * it could have gone in clear before. This happens only if a
21239 	 * TCP connection started when there is no policy and somebody
21240 	 * added policy before it became detached. Thus packets of the
21241 	 * detached connection could go out secure and the other end
21242 	 * would drop it because it will be expecting in clear. The
21243 	 * converse is not true i.e if somebody starts a TCP
21244 	 * connection and deletes the policy, all the packets will
21245 	 * still go out with the policy that existed before deleting
21246 	 * because ip_unbind sends up policy information which is used
21247 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21248 	 * TCP to attach a dummy IPSEC_OUT and set
21249 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21250 	 * affect performance for normal cases, we are not doing it.
21251 	 * Thus, set policy before starting any TCP connections.
21252 	 *
21253 	 * NOTE - We might apply policy even for a hard bound connection
21254 	 * - for which we cached policy in ip_bind - if somebody added
21255 	 * global policy after we inherited the policy in ip_bind.
21256 	 * This means that the packets that were going out in clear
21257 	 * previously would start going secure and hence get dropped
21258 	 * on the other side. To fix this, TCP attaches a dummy
21259 	 * ipsec_out and make sure that we don't apply global policy.
21260 	 */
21261 	if (ipha != NULL)
21262 		policy_present = ipsec_outbound_v4_policy_present;
21263 	else
21264 		policy_present = ipsec_outbound_v6_policy_present;
21265 	if (!policy_present)
21266 		return (mp);
21267 
21268 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21269 		    zoneid));
21270 }
21271 
21272 ire_t *
21273 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21274 {
21275 	ipaddr_t addr;
21276 	ire_t *save_ire;
21277 	irb_t *irb;
21278 	ill_group_t *illgrp;
21279 	int	err;
21280 
21281 	save_ire = ire;
21282 	addr = ire->ire_addr;
21283 
21284 	ASSERT(ire->ire_type == IRE_BROADCAST);
21285 
21286 	illgrp = connp->conn_outgoing_ill->ill_group;
21287 	if (illgrp == NULL) {
21288 		*conn_outgoing_ill = conn_get_held_ill(connp,
21289 		    &connp->conn_outgoing_ill, &err);
21290 		if (err == ILL_LOOKUP_FAILED) {
21291 			ire_refrele(save_ire);
21292 			return (NULL);
21293 		}
21294 		return (save_ire);
21295 	}
21296 	/*
21297 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21298 	 * If it is part of the group, we need to send on the ire
21299 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21300 	 * to this group. This is okay as IP_BOUND_IF really means
21301 	 * any ill in the group. We depend on the fact that the
21302 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21303 	 * if such an ire exists. This is possible only if you have
21304 	 * at least one ill in the group that has not failed.
21305 	 *
21306 	 * First get to the ire that matches the address and group.
21307 	 *
21308 	 * We don't look for an ire with a matching zoneid because a given zone
21309 	 * won't always have broadcast ires on all ills in the group.
21310 	 */
21311 	irb = ire->ire_bucket;
21312 	rw_enter(&irb->irb_lock, RW_READER);
21313 	if (ire->ire_marks & IRE_MARK_NORECV) {
21314 		/*
21315 		 * If the current zone only has an ire broadcast for this
21316 		 * address marked NORECV, the ire we want is ahead in the
21317 		 * bucket, so we look it up deliberately ignoring the zoneid.
21318 		 */
21319 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21320 			if (ire->ire_addr != addr)
21321 				continue;
21322 			/* skip over deleted ires */
21323 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21324 				continue;
21325 		}
21326 	}
21327 	while (ire != NULL) {
21328 		/*
21329 		 * If a new interface is coming up, we could end up
21330 		 * seeing the loopback ire and the non-loopback ire
21331 		 * may not have been added yet. So check for ire_stq
21332 		 */
21333 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21334 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21335 			break;
21336 		}
21337 		ire = ire->ire_next;
21338 	}
21339 	if (ire != NULL && ire->ire_addr == addr &&
21340 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21341 		IRE_REFHOLD(ire);
21342 		rw_exit(&irb->irb_lock);
21343 		ire_refrele(save_ire);
21344 		*conn_outgoing_ill = ire_to_ill(ire);
21345 		/*
21346 		 * Refhold the ill to make the conn_outgoing_ill
21347 		 * independent of the ire. ip_wput_ire goes in a loop
21348 		 * and may refrele the ire. Since we have an ire at this
21349 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21350 		 */
21351 		ill_refhold(*conn_outgoing_ill);
21352 		return (ire);
21353 	}
21354 	rw_exit(&irb->irb_lock);
21355 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21356 	/*
21357 	 * If we can't find a suitable ire, return the original ire.
21358 	 */
21359 	return (save_ire);
21360 }
21361 
21362 /*
21363  * This function does the ire_refrele of the ire passed in as the
21364  * argument. As this function looks up more ires i.e broadcast ires,
21365  * it needs to REFRELE them. Currently, for simplicity we don't
21366  * differentiate the one passed in and looked up here. We always
21367  * REFRELE.
21368  * IPQoS Notes:
21369  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21370  * IPSec packets are done in ipsec_out_process.
21371  *
21372  */
21373 void
21374 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21375     zoneid_t zoneid)
21376 {
21377 	ipha_t		*ipha;
21378 #define	rptr	((uchar_t *)ipha)
21379 	queue_t		*stq;
21380 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21381 	uint32_t	v_hlen_tos_len;
21382 	uint32_t	ttl_protocol;
21383 	ipaddr_t	src;
21384 	ipaddr_t	dst;
21385 	uint32_t	cksum;
21386 	ipaddr_t	orig_src;
21387 	ire_t		*ire1;
21388 	mblk_t		*next_mp;
21389 	uint_t		hlen;
21390 	uint16_t	*up;
21391 	uint32_t	max_frag = ire->ire_max_frag;
21392 	ill_t		*ill = ire_to_ill(ire);
21393 	int		clusterwide;
21394 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21395 	int		ipsec_len;
21396 	mblk_t		*first_mp;
21397 	ipsec_out_t	*io;
21398 	boolean_t	conn_dontroute;		/* conn value for multicast */
21399 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21400 	boolean_t	multicast_forward;	/* Should we forward ? */
21401 	boolean_t	unspec_src;
21402 	ill_t		*conn_outgoing_ill = NULL;
21403 	ill_t		*ire_ill;
21404 	ill_t		*ire1_ill;
21405 	ill_t		*out_ill;
21406 	uint32_t 	ill_index = 0;
21407 	boolean_t	multirt_send = B_FALSE;
21408 	int		err;
21409 	ipxmit_state_t	pktxmit_state;
21410 
21411 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21412 	    "ip_wput_ire_start: q %p", q);
21413 
21414 	multicast_forward = B_FALSE;
21415 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21416 
21417 	if (ire->ire_flags & RTF_MULTIRT) {
21418 		/*
21419 		 * Multirouting case. The bucket where ire is stored
21420 		 * probably holds other RTF_MULTIRT flagged ire
21421 		 * to the destination. In this call to ip_wput_ire,
21422 		 * we attempt to send the packet through all
21423 		 * those ires. Thus, we first ensure that ire is the
21424 		 * first RTF_MULTIRT ire in the bucket,
21425 		 * before walking the ire list.
21426 		 */
21427 		ire_t *first_ire;
21428 		irb_t *irb = ire->ire_bucket;
21429 		ASSERT(irb != NULL);
21430 
21431 		/* Make sure we do not omit any multiroute ire. */
21432 		IRB_REFHOLD(irb);
21433 		for (first_ire = irb->irb_ire;
21434 		    first_ire != NULL;
21435 		    first_ire = first_ire->ire_next) {
21436 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21437 			    (first_ire->ire_addr == ire->ire_addr) &&
21438 			    !(first_ire->ire_marks &
21439 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
21440 				break;
21441 		}
21442 
21443 		if ((first_ire != NULL) && (first_ire != ire)) {
21444 			IRE_REFHOLD(first_ire);
21445 			ire_refrele(ire);
21446 			ire = first_ire;
21447 			ill = ire_to_ill(ire);
21448 		}
21449 		IRB_REFRELE(irb);
21450 	}
21451 
21452 	/*
21453 	 * conn_outgoing_ill is used only in the broadcast loop.
21454 	 * for performance we don't grab the mutexs in the fastpath
21455 	 */
21456 	if ((connp != NULL) &&
21457 	    (connp->conn_xmit_if_ill == NULL) &&
21458 	    (ire->ire_type == IRE_BROADCAST) &&
21459 	    ((connp->conn_nofailover_ill != NULL) ||
21460 	    (connp->conn_outgoing_ill != NULL))) {
21461 		/*
21462 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21463 		 * option. So, see if this endpoint is bound to a
21464 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21465 		 * that if the interface is failed, we will still send
21466 		 * the packet on the same ill which is what we want.
21467 		 */
21468 		conn_outgoing_ill = conn_get_held_ill(connp,
21469 		    &connp->conn_nofailover_ill, &err);
21470 		if (err == ILL_LOOKUP_FAILED) {
21471 			ire_refrele(ire);
21472 			freemsg(mp);
21473 			return;
21474 		}
21475 		if (conn_outgoing_ill == NULL) {
21476 			/*
21477 			 * Choose a good ill in the group to send the
21478 			 * packets on.
21479 			 */
21480 			ire = conn_set_outgoing_ill(connp, ire,
21481 			    &conn_outgoing_ill);
21482 			if (ire == NULL) {
21483 				freemsg(mp);
21484 				return;
21485 			}
21486 		}
21487 	}
21488 
21489 	if (mp->b_datap->db_type != M_CTL) {
21490 		ipha = (ipha_t *)mp->b_rptr;
21491 	} else {
21492 		io = (ipsec_out_t *)mp->b_rptr;
21493 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21494 		ASSERT(zoneid == io->ipsec_out_zoneid);
21495 		ASSERT(zoneid != ALL_ZONES);
21496 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21497 		dst = ipha->ipha_dst;
21498 		/*
21499 		 * For the multicast case, ipsec_out carries conn_dontroute and
21500 		 * conn_multicast_loop as conn may not be available here. We
21501 		 * need this for multicast loopback and forwarding which is done
21502 		 * later in the code.
21503 		 */
21504 		if (CLASSD(dst)) {
21505 			conn_dontroute = io->ipsec_out_dontroute;
21506 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21507 			/*
21508 			 * If conn_dontroute is not set or conn_multicast_loop
21509 			 * is set, we need to do forwarding/loopback. For
21510 			 * datagrams from ip_wput_multicast, conn_dontroute is
21511 			 * set to B_TRUE and conn_multicast_loop is set to
21512 			 * B_FALSE so that we neither do forwarding nor
21513 			 * loopback.
21514 			 */
21515 			if (!conn_dontroute || conn_multicast_loop)
21516 				multicast_forward = B_TRUE;
21517 		}
21518 	}
21519 
21520 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21521 	    ire->ire_zoneid != ALL_ZONES) {
21522 		/*
21523 		 * When a zone sends a packet to another zone, we try to deliver
21524 		 * the packet under the same conditions as if the destination
21525 		 * was a real node on the network. To do so, we look for a
21526 		 * matching route in the forwarding table.
21527 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21528 		 * ip_newroute() does.
21529 		 * Note that IRE_LOCAL are special, since they are used
21530 		 * when the zoneid doesn't match in some cases. This means that
21531 		 * we need to handle ipha_src differently since ire_src_addr
21532 		 * belongs to the receiving zone instead of the sending zone.
21533 		 * When ip_restrict_interzone_loopback is set, then
21534 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21535 		 * for loopback between zones when the logical "Ethernet" would
21536 		 * have looped them back.
21537 		 */
21538 		ire_t *src_ire;
21539 
21540 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21541 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21542 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
21543 		if (src_ire != NULL &&
21544 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21545 		    (!ip_restrict_interzone_loopback ||
21546 		    ire_local_same_ill_group(ire, src_ire))) {
21547 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21548 				ipha->ipha_src = src_ire->ire_src_addr;
21549 			ire_refrele(src_ire);
21550 		} else {
21551 			ire_refrele(ire);
21552 			if (conn_outgoing_ill != NULL)
21553 				ill_refrele(conn_outgoing_ill);
21554 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
21555 			if (src_ire != NULL) {
21556 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21557 					ire_refrele(src_ire);
21558 					freemsg(mp);
21559 					return;
21560 				}
21561 				ire_refrele(src_ire);
21562 			}
21563 			if (ip_hdr_complete(ipha, zoneid)) {
21564 				/* Failed */
21565 				freemsg(mp);
21566 				return;
21567 			}
21568 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
21569 			return;
21570 		}
21571 	}
21572 
21573 	if (mp->b_datap->db_type == M_CTL ||
21574 	    ipsec_outbound_v4_policy_present) {
21575 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21576 		    unspec_src, zoneid);
21577 		if (mp == NULL) {
21578 			ire_refrele(ire);
21579 			if (conn_outgoing_ill != NULL)
21580 				ill_refrele(conn_outgoing_ill);
21581 			return;
21582 		}
21583 	}
21584 
21585 	first_mp = mp;
21586 	ipsec_len = 0;
21587 
21588 	if (first_mp->b_datap->db_type == M_CTL) {
21589 		io = (ipsec_out_t *)first_mp->b_rptr;
21590 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21591 		mp = first_mp->b_cont;
21592 		ipsec_len = ipsec_out_extra_length(first_mp);
21593 		ASSERT(ipsec_len >= 0);
21594 		/* We already picked up the zoneid from the M_CTL above */
21595 		ASSERT(zoneid == io->ipsec_out_zoneid);
21596 		ASSERT(zoneid != ALL_ZONES);
21597 
21598 		/*
21599 		 * Drop M_CTL here if IPsec processing is not needed.
21600 		 * (Non-IPsec use of M_CTL extracted any information it
21601 		 * needed above).
21602 		 */
21603 		if (ipsec_len == 0) {
21604 			freeb(first_mp);
21605 			first_mp = mp;
21606 		}
21607 	}
21608 
21609 	/*
21610 	 * Fast path for ip_wput_ire
21611 	 */
21612 
21613 	ipha = (ipha_t *)mp->b_rptr;
21614 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21615 	dst = ipha->ipha_dst;
21616 
21617 	/*
21618 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21619 	 * if the socket is a SOCK_RAW type. The transport checksum should
21620 	 * be provided in the pre-built packet, so we don't need to compute it.
21621 	 * Also, other application set flags, like DF, should not be altered.
21622 	 * Other transport MUST pass down zero.
21623 	 */
21624 	ip_hdr_included = ipha->ipha_ident;
21625 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21626 
21627 	if (CLASSD(dst)) {
21628 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
21629 		    ntohl(dst),
21630 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
21631 		    ntohl(ire->ire_addr)));
21632 	}
21633 
21634 /* Macros to extract header fields from data already in registers */
21635 #ifdef	_BIG_ENDIAN
21636 #define	V_HLEN	(v_hlen_tos_len >> 24)
21637 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21638 #define	PROTO	(ttl_protocol & 0xFF)
21639 #else
21640 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21641 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21642 #define	PROTO	(ttl_protocol >> 8)
21643 #endif
21644 
21645 
21646 	orig_src = src = ipha->ipha_src;
21647 	/* (The loop back to "another" is explained down below.) */
21648 another:;
21649 	/*
21650 	 * Assign an ident value for this packet.  We assign idents on
21651 	 * a per destination basis out of the IRE.  There could be
21652 	 * other threads targeting the same destination, so we have to
21653 	 * arrange for a atomic increment.  Note that we use a 32-bit
21654 	 * atomic add because it has better performance than its
21655 	 * 16-bit sibling.
21656 	 *
21657 	 * If running in cluster mode and if the source address
21658 	 * belongs to a replicated service then vector through
21659 	 * cl_inet_ipident vector to allocate ip identifier
21660 	 * NOTE: This is a contract private interface with the
21661 	 * clustering group.
21662 	 */
21663 	clusterwide = 0;
21664 	if (cl_inet_ipident) {
21665 		ASSERT(cl_inet_isclusterwide);
21666 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21667 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
21668 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
21669 			    AF_INET, (uint8_t *)(uintptr_t)src,
21670 			    (uint8_t *)(uintptr_t)dst);
21671 			clusterwide = 1;
21672 		}
21673 	}
21674 	if (!clusterwide) {
21675 		ipha->ipha_ident =
21676 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
21677 	}
21678 
21679 #ifndef _BIG_ENDIAN
21680 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21681 #endif
21682 
21683 	/*
21684 	 * Set source address unless sent on an ill or conn_unspec_src is set.
21685 	 * This is needed to obey conn_unspec_src when packets go through
21686 	 * ip_newroute + arp.
21687 	 * Assumes ip_newroute{,_multi} sets the source address as well.
21688 	 */
21689 	if (src == INADDR_ANY && !unspec_src) {
21690 		/*
21691 		 * Assign the appropriate source address from the IRE if none
21692 		 * was specified.
21693 		 */
21694 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
21695 
21696 		/*
21697 		 * With IP multipathing, broadcast packets are sent on the ire
21698 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
21699 		 * the group. However, this ire might not be in the same zone so
21700 		 * we can't always use its source address. We look for a
21701 		 * broadcast ire in the same group and in the right zone.
21702 		 */
21703 		if (ire->ire_type == IRE_BROADCAST &&
21704 		    ire->ire_zoneid != zoneid) {
21705 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
21706 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
21707 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
21708 			if (src_ire != NULL) {
21709 				src = src_ire->ire_src_addr;
21710 				ire_refrele(src_ire);
21711 			} else {
21712 				ire_refrele(ire);
21713 				if (conn_outgoing_ill != NULL)
21714 					ill_refrele(conn_outgoing_ill);
21715 				freemsg(first_mp);
21716 				BUMP_MIB(&ip_mib, ipOutDiscards);
21717 				return;
21718 			}
21719 		} else {
21720 			src = ire->ire_src_addr;
21721 		}
21722 
21723 		if (connp == NULL) {
21724 			ip1dbg(("ip_wput_ire: no connp and no src "
21725 			    "address for dst 0x%x, using src 0x%x\n",
21726 			    ntohl(dst),
21727 			    ntohl(src)));
21728 		}
21729 		ipha->ipha_src = src;
21730 	}
21731 	stq = ire->ire_stq;
21732 
21733 	/*
21734 	 * We only allow ire chains for broadcasts since there will
21735 	 * be multiple IRE_CACHE entries for the same multicast
21736 	 * address (one per ipif).
21737 	 */
21738 	next_mp = NULL;
21739 
21740 	/* broadcast packet */
21741 	if (ire->ire_type == IRE_BROADCAST)
21742 		goto broadcast;
21743 
21744 	/* loopback ? */
21745 	if (stq == NULL)
21746 		goto nullstq;
21747 
21748 	/* The ill_index for outbound ILL */
21749 	ill_index = Q_TO_INDEX(stq);
21750 
21751 	BUMP_MIB(&ip_mib, ipOutRequests);
21752 	ttl_protocol = ((uint16_t *)ipha)[4];
21753 
21754 	/* pseudo checksum (do it in parts for IP header checksum) */
21755 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21756 
21757 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
21758 		queue_t *dev_q = stq->q_next;
21759 
21760 		/* flow controlled */
21761 		if ((dev_q->q_next || dev_q->q_first) &&
21762 		    !canput(dev_q))
21763 			goto blocked;
21764 		if ((PROTO == IPPROTO_UDP) &&
21765 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
21766 			hlen = (V_HLEN & 0xF) << 2;
21767 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
21768 			if (*up != 0) {
21769 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
21770 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
21771 				/* Software checksum? */
21772 				if (DB_CKSUMFLAGS(mp) == 0) {
21773 					IP_STAT(ip_out_sw_cksum);
21774 					IP_STAT_UPDATE(
21775 					    ip_udp_out_sw_cksum_bytes,
21776 					    LENGTH - hlen);
21777 				}
21778 			}
21779 		}
21780 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
21781 		hlen = (V_HLEN & 0xF) << 2;
21782 		if (PROTO == IPPROTO_TCP) {
21783 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
21784 			/*
21785 			 * The packet header is processed once and for all, even
21786 			 * in the multirouting case. We disable hardware
21787 			 * checksum if the packet is multirouted, as it will be
21788 			 * replicated via several interfaces, and not all of
21789 			 * them may have this capability.
21790 			 */
21791 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
21792 			    LENGTH, max_frag, ipsec_len, cksum);
21793 			/* Software checksum? */
21794 			if (DB_CKSUMFLAGS(mp) == 0) {
21795 				IP_STAT(ip_out_sw_cksum);
21796 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
21797 				    LENGTH - hlen);
21798 			}
21799 		} else {
21800 			sctp_hdr_t	*sctph;
21801 
21802 			ASSERT(PROTO == IPPROTO_SCTP);
21803 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
21804 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
21805 			/*
21806 			 * Zero out the checksum field to ensure proper
21807 			 * checksum calculation.
21808 			 */
21809 			sctph->sh_chksum = 0;
21810 #ifdef	DEBUG
21811 			if (!skip_sctp_cksum)
21812 #endif
21813 				sctph->sh_chksum = sctp_cksum(mp, hlen);
21814 		}
21815 	}
21816 
21817 	/*
21818 	 * If this is a multicast packet and originated from ip_wput
21819 	 * we need to do loopback and forwarding checks. If it comes
21820 	 * from ip_wput_multicast, we SHOULD not do this.
21821 	 */
21822 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
21823 
21824 	/* checksum */
21825 	cksum += ttl_protocol;
21826 
21827 	/* fragment the packet */
21828 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
21829 		goto fragmentit;
21830 	/*
21831 	 * Don't use frag_flag if packet is pre-built or source
21832 	 * routed or if multicast (since multicast packets do
21833 	 * not solicit ICMP "packet too big" messages).
21834 	 */
21835 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
21836 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
21837 	    !ip_source_route_included(ipha)) &&
21838 	    !CLASSD(ipha->ipha_dst))
21839 		ipha->ipha_fragment_offset_and_flags |=
21840 		    htons(ire->ire_frag_flag);
21841 
21842 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
21843 		/* calculate IP header checksum */
21844 		cksum += ipha->ipha_ident;
21845 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
21846 		cksum += ipha->ipha_fragment_offset_and_flags;
21847 
21848 		/* IP options present */
21849 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
21850 		if (hlen)
21851 			goto checksumoptions;
21852 
21853 		/* calculate hdr checksum */
21854 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
21855 		cksum = ~(cksum + (cksum >> 16));
21856 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
21857 	}
21858 	if (ipsec_len != 0) {
21859 		/*
21860 		 * We will do the rest of the processing after
21861 		 * we come back from IPSEC in ip_wput_ipsec_out().
21862 		 */
21863 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
21864 
21865 		io = (ipsec_out_t *)first_mp->b_rptr;
21866 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
21867 				ill_phyint->phyint_ifindex;
21868 
21869 		ipsec_out_process(q, first_mp, ire, ill_index);
21870 		ire_refrele(ire);
21871 		if (conn_outgoing_ill != NULL)
21872 			ill_refrele(conn_outgoing_ill);
21873 		return;
21874 	}
21875 
21876 	/*
21877 	 * In most cases, the emission loop below is entered only
21878 	 * once. Only in the case where the ire holds the
21879 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
21880 	 * flagged ires in the bucket, and send the packet
21881 	 * through all crossed RTF_MULTIRT routes.
21882 	 */
21883 	if (ire->ire_flags & RTF_MULTIRT) {
21884 		multirt_send = B_TRUE;
21885 	}
21886 	do {
21887 		if (multirt_send) {
21888 			irb_t *irb;
21889 			/*
21890 			 * We are in a multiple send case, need to get
21891 			 * the next ire and make a duplicate of the packet.
21892 			 * ire1 holds here the next ire to process in the
21893 			 * bucket. If multirouting is expected,
21894 			 * any non-RTF_MULTIRT ire that has the
21895 			 * right destination address is ignored.
21896 			 */
21897 			irb = ire->ire_bucket;
21898 			ASSERT(irb != NULL);
21899 
21900 			IRB_REFHOLD(irb);
21901 			for (ire1 = ire->ire_next;
21902 			    ire1 != NULL;
21903 			    ire1 = ire1->ire_next) {
21904 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
21905 					continue;
21906 				if (ire1->ire_addr != ire->ire_addr)
21907 					continue;
21908 				if (ire1->ire_marks &
21909 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
21910 					continue;
21911 
21912 				/* Got one */
21913 				IRE_REFHOLD(ire1);
21914 				break;
21915 			}
21916 			IRB_REFRELE(irb);
21917 
21918 			if (ire1 != NULL) {
21919 				next_mp = copyb(mp);
21920 				if ((next_mp == NULL) ||
21921 				    ((mp->b_cont != NULL) &&
21922 				    ((next_mp->b_cont =
21923 				    dupmsg(mp->b_cont)) == NULL))) {
21924 					freemsg(next_mp);
21925 					next_mp = NULL;
21926 					ire_refrele(ire1);
21927 					ire1 = NULL;
21928 				}
21929 			}
21930 
21931 			/* Last multiroute ire; don't loop anymore. */
21932 			if (ire1 == NULL) {
21933 				multirt_send = B_FALSE;
21934 			}
21935 		}
21936 
21937 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
21938 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
21939 		    mblk_t *, mp);
21940 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
21941 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
21942 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21943 		if (mp == NULL)
21944 			goto release_ire_and_ill;
21945 
21946 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
21947 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
21948 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
21949 		if ((pktxmit_state == SEND_FAILED) ||
21950 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
21951 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
21952 			    "- packet dropped\n"));
21953 release_ire_and_ill:
21954 			ire_refrele(ire);
21955 			if (next_mp != NULL) {
21956 				freemsg(next_mp);
21957 				ire_refrele(ire1);
21958 			}
21959 			if (conn_outgoing_ill != NULL)
21960 				ill_refrele(conn_outgoing_ill);
21961 			return;
21962 		}
21963 
21964 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21965 		    "ip_wput_ire_end: q %p (%S)",
21966 		    q, "last copy out");
21967 		IRE_REFRELE(ire);
21968 
21969 		if (multirt_send) {
21970 			ASSERT(ire1);
21971 			/*
21972 			 * Proceed with the next RTF_MULTIRT ire,
21973 			 * Also set up the send-to queue accordingly.
21974 			 */
21975 			ire = ire1;
21976 			ire1 = NULL;
21977 			stq = ire->ire_stq;
21978 			mp = next_mp;
21979 			next_mp = NULL;
21980 			ipha = (ipha_t *)mp->b_rptr;
21981 			ill_index = Q_TO_INDEX(stq);
21982 		}
21983 	} while (multirt_send);
21984 	if (conn_outgoing_ill != NULL)
21985 		ill_refrele(conn_outgoing_ill);
21986 	return;
21987 
21988 	/*
21989 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
21990 	 */
21991 broadcast:
21992 	{
21993 		/*
21994 		 * Avoid broadcast storms by setting the ttl to 1
21995 		 * for broadcasts. This parameter can be set
21996 		 * via ndd, so make sure that for the SO_DONTROUTE
21997 		 * case that ipha_ttl is always set to 1.
21998 		 * In the event that we are replying to incoming
21999 		 * ICMP packets, conn could be NULL.
22000 		 */
22001 		if ((connp != NULL) && connp->conn_dontroute)
22002 			ipha->ipha_ttl = 1;
22003 		else
22004 			ipha->ipha_ttl = ip_broadcast_ttl;
22005 
22006 		/*
22007 		 * Note that we are not doing a IRB_REFHOLD here.
22008 		 * Actually we don't care if the list changes i.e
22009 		 * if somebody deletes an IRE from the list while
22010 		 * we drop the lock, the next time we come around
22011 		 * ire_next will be NULL and hence we won't send
22012 		 * out multiple copies which is fine.
22013 		 */
22014 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22015 		ire1 = ire->ire_next;
22016 		if (conn_outgoing_ill != NULL) {
22017 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22018 				ASSERT(ire1 == ire->ire_next);
22019 				if (ire1 != NULL && ire1->ire_addr == dst) {
22020 					ire_refrele(ire);
22021 					ire = ire1;
22022 					IRE_REFHOLD(ire);
22023 					ire1 = ire->ire_next;
22024 					continue;
22025 				}
22026 				rw_exit(&ire->ire_bucket->irb_lock);
22027 				/* Did not find a matching ill */
22028 				ip1dbg(("ip_wput_ire: broadcast with no "
22029 				    "matching IP_BOUND_IF ill %s\n",
22030 				    conn_outgoing_ill->ill_name));
22031 				freemsg(first_mp);
22032 				if (ire != NULL)
22033 					ire_refrele(ire);
22034 				ill_refrele(conn_outgoing_ill);
22035 				return;
22036 			}
22037 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22038 			/*
22039 			 * If the next IRE has the same address and is not one
22040 			 * of the two copies that we need to send, try to see
22041 			 * whether this copy should be sent at all. This
22042 			 * assumes that we insert loopbacks first and then
22043 			 * non-loopbacks. This is acheived by inserting the
22044 			 * loopback always before non-loopback.
22045 			 * This is used to send a single copy of a broadcast
22046 			 * packet out all physical interfaces that have an
22047 			 * matching IRE_BROADCAST while also looping
22048 			 * back one copy (to ip_wput_local) for each
22049 			 * matching physical interface. However, we avoid
22050 			 * sending packets out different logical that match by
22051 			 * having ipif_up/ipif_down supress duplicate
22052 			 * IRE_BROADCASTS.
22053 			 *
22054 			 * This feature is currently used to get broadcasts
22055 			 * sent to multiple interfaces, when the broadcast
22056 			 * address being used applies to multiple interfaces.
22057 			 * For example, a whole net broadcast will be
22058 			 * replicated on every connected subnet of
22059 			 * the target net.
22060 			 *
22061 			 * Each zone has its own set of IRE_BROADCASTs, so that
22062 			 * we're able to distribute inbound packets to multiple
22063 			 * zones who share a broadcast address. We avoid looping
22064 			 * back outbound packets in different zones but on the
22065 			 * same ill, as the application would see duplicates.
22066 			 *
22067 			 * If the interfaces are part of the same group,
22068 			 * we would want to send only one copy out for
22069 			 * whole group.
22070 			 *
22071 			 * This logic assumes that ire_add_v4() groups the
22072 			 * IRE_BROADCAST entries so that those with the same
22073 			 * ire_addr and ill_group are kept together.
22074 			 */
22075 			ire_ill = ire->ire_ipif->ipif_ill;
22076 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22077 				if (ire_ill->ill_group != NULL &&
22078 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22079 					/*
22080 					 * If the current zone only has an ire
22081 					 * broadcast for this address marked
22082 					 * NORECV, the ire we want is ahead in
22083 					 * the bucket, so we look it up
22084 					 * deliberately ignoring the zoneid.
22085 					 */
22086 					for (ire1 = ire->ire_bucket->irb_ire;
22087 					    ire1 != NULL;
22088 					    ire1 = ire1->ire_next) {
22089 						ire1_ill =
22090 						    ire1->ire_ipif->ipif_ill;
22091 						if (ire1->ire_addr != dst)
22092 							continue;
22093 						/* skip over the current ire */
22094 						if (ire1 == ire)
22095 							continue;
22096 						/* skip over deleted ires */
22097 						if (ire1->ire_marks &
22098 						    IRE_MARK_CONDEMNED)
22099 							continue;
22100 						/*
22101 						 * non-loopback ire in our
22102 						 * group: use it for the next
22103 						 * pass in the loop
22104 						 */
22105 						if (ire1->ire_stq != NULL &&
22106 						    ire1_ill->ill_group ==
22107 						    ire_ill->ill_group)
22108 							break;
22109 					}
22110 				}
22111 			} else {
22112 				while (ire1 != NULL && ire1->ire_addr == dst) {
22113 					ire1_ill = ire1->ire_ipif->ipif_ill;
22114 					/*
22115 					 * We can have two broadcast ires on the
22116 					 * same ill in different zones; here
22117 					 * we'll send a copy of the packet on
22118 					 * each ill and the fanout code will
22119 					 * call conn_wantpacket() to check that
22120 					 * the zone has the broadcast address
22121 					 * configured on the ill. If the two
22122 					 * ires are in the same group we only
22123 					 * send one copy up.
22124 					 */
22125 					if (ire1_ill != ire_ill &&
22126 					    (ire1_ill->ill_group == NULL ||
22127 					    ire_ill->ill_group == NULL ||
22128 					    ire1_ill->ill_group !=
22129 					    ire_ill->ill_group)) {
22130 						break;
22131 					}
22132 					ire1 = ire1->ire_next;
22133 				}
22134 			}
22135 		}
22136 		ASSERT(multirt_send == B_FALSE);
22137 		if (ire1 != NULL && ire1->ire_addr == dst) {
22138 			if ((ire->ire_flags & RTF_MULTIRT) &&
22139 			    (ire1->ire_flags & RTF_MULTIRT)) {
22140 				/*
22141 				 * We are in the multirouting case.
22142 				 * The message must be sent at least
22143 				 * on both ires. These ires have been
22144 				 * inserted AFTER the standard ones
22145 				 * in ip_rt_add(). There are thus no
22146 				 * other ire entries for the destination
22147 				 * address in the rest of the bucket
22148 				 * that do not have the RTF_MULTIRT
22149 				 * flag. We don't process a copy
22150 				 * of the message here. This will be
22151 				 * done in the final sending loop.
22152 				 */
22153 				multirt_send = B_TRUE;
22154 			} else {
22155 				next_mp = ip_copymsg(first_mp);
22156 				if (next_mp != NULL)
22157 					IRE_REFHOLD(ire1);
22158 			}
22159 		}
22160 		rw_exit(&ire->ire_bucket->irb_lock);
22161 	}
22162 
22163 	if (stq) {
22164 		/*
22165 		 * A non-NULL send-to queue means this packet is going
22166 		 * out of this machine.
22167 		 */
22168 
22169 		BUMP_MIB(&ip_mib, ipOutRequests);
22170 		ttl_protocol = ((uint16_t *)ipha)[4];
22171 		/*
22172 		 * We accumulate the pseudo header checksum in cksum.
22173 		 * This is pretty hairy code, so watch close.  One
22174 		 * thing to keep in mind is that UDP and TCP have
22175 		 * stored their respective datagram lengths in their
22176 		 * checksum fields.  This lines things up real nice.
22177 		 */
22178 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22179 		    (src >> 16) + (src & 0xFFFF);
22180 		/*
22181 		 * We assume the udp checksum field contains the
22182 		 * length, so to compute the pseudo header checksum,
22183 		 * all we need is the protocol number and src/dst.
22184 		 */
22185 		/* Provide the checksums for UDP and TCP. */
22186 		if ((PROTO == IPPROTO_TCP) &&
22187 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22188 			/* hlen gets the number of uchar_ts in the IP header */
22189 			hlen = (V_HLEN & 0xF) << 2;
22190 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22191 			IP_STAT(ip_out_sw_cksum);
22192 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22193 			    LENGTH - hlen);
22194 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22195 			if (*up == 0)
22196 				*up = 0xFFFF;
22197 		} else if (PROTO == IPPROTO_SCTP &&
22198 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22199 			sctp_hdr_t	*sctph;
22200 
22201 			hlen = (V_HLEN & 0xF) << 2;
22202 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22203 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22204 			sctph->sh_chksum = 0;
22205 #ifdef	DEBUG
22206 			if (!skip_sctp_cksum)
22207 #endif
22208 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22209 		} else {
22210 			queue_t *dev_q = stq->q_next;
22211 
22212 			if ((dev_q->q_next || dev_q->q_first) &&
22213 			    !canput(dev_q)) {
22214 			    blocked:
22215 				ipha->ipha_ident = ip_hdr_included;
22216 				/*
22217 				 * If we don't have a conn to apply
22218 				 * backpressure, free the message.
22219 				 * In the ire_send path, we don't know
22220 				 * the position to requeue the packet. Rather
22221 				 * than reorder packets, we just drop this
22222 				 * packet.
22223 				 */
22224 				if (ip_output_queue && connp != NULL &&
22225 				    caller != IRE_SEND) {
22226 					if (caller == IP_WSRV) {
22227 						connp->conn_did_putbq = 1;
22228 						(void) putbq(connp->conn_wq,
22229 						    first_mp);
22230 						conn_drain_insert(connp);
22231 						/*
22232 						 * This is the service thread,
22233 						 * and the queue is already
22234 						 * noenabled. The check for
22235 						 * canput and the putbq is not
22236 						 * atomic. So we need to check
22237 						 * again.
22238 						 */
22239 						if (canput(stq->q_next))
22240 							connp->conn_did_putbq
22241 							    = 0;
22242 						IP_STAT(ip_conn_flputbq);
22243 					} else {
22244 						/*
22245 						 * We are not the service proc.
22246 						 * ip_wsrv will be scheduled or
22247 						 * is already running.
22248 						 */
22249 						(void) putq(connp->conn_wq,
22250 						    first_mp);
22251 					}
22252 				} else {
22253 					BUMP_MIB(&ip_mib, ipOutDiscards);
22254 					freemsg(first_mp);
22255 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22256 					    "ip_wput_ire_end: q %p (%S)",
22257 					    q, "discard");
22258 				}
22259 				ire_refrele(ire);
22260 				if (next_mp) {
22261 					ire_refrele(ire1);
22262 					freemsg(next_mp);
22263 				}
22264 				if (conn_outgoing_ill != NULL)
22265 					ill_refrele(conn_outgoing_ill);
22266 				return;
22267 			}
22268 			if ((PROTO == IPPROTO_UDP) &&
22269 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22270 				/*
22271 				 * hlen gets the number of uchar_ts in the
22272 				 * IP header
22273 				 */
22274 				hlen = (V_HLEN & 0xF) << 2;
22275 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22276 				max_frag = ire->ire_max_frag;
22277 				if (*up != 0) {
22278 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22279 					    up, PROTO, hlen, LENGTH, max_frag,
22280 					    ipsec_len, cksum);
22281 					/* Software checksum? */
22282 					if (DB_CKSUMFLAGS(mp) == 0) {
22283 						IP_STAT(ip_out_sw_cksum);
22284 						IP_STAT_UPDATE(
22285 						    ip_udp_out_sw_cksum_bytes,
22286 						    LENGTH - hlen);
22287 					}
22288 				}
22289 			}
22290 		}
22291 		/*
22292 		 * Need to do this even when fragmenting. The local
22293 		 * loopback can be done without computing checksums
22294 		 * but forwarding out other interface must be done
22295 		 * after the IP checksum (and ULP checksums) have been
22296 		 * computed.
22297 		 *
22298 		 * NOTE : multicast_forward is set only if this packet
22299 		 * originated from ip_wput. For packets originating from
22300 		 * ip_wput_multicast, it is not set.
22301 		 */
22302 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22303 		    multi_loopback:
22304 			ip2dbg(("ip_wput: multicast, loop %d\n",
22305 			    conn_multicast_loop));
22306 
22307 			/*  Forget header checksum offload */
22308 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22309 
22310 			/*
22311 			 * Local loopback of multicasts?  Check the
22312 			 * ill.
22313 			 *
22314 			 * Note that the loopback function will not come
22315 			 * in through ip_rput - it will only do the
22316 			 * client fanout thus we need to do an mforward
22317 			 * as well.  The is different from the BSD
22318 			 * logic.
22319 			 */
22320 			if (ill != NULL) {
22321 				ilm_t	*ilm;
22322 
22323 				ILM_WALKER_HOLD(ill);
22324 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22325 				    ALL_ZONES);
22326 				ILM_WALKER_RELE(ill);
22327 				if (ilm != NULL) {
22328 					/*
22329 					 * Pass along the virtual output q.
22330 					 * ip_wput_local() will distribute the
22331 					 * packet to all the matching zones,
22332 					 * except the sending zone when
22333 					 * IP_MULTICAST_LOOP is false.
22334 					 */
22335 					ip_multicast_loopback(q, ill, first_mp,
22336 					    conn_multicast_loop ? 0 :
22337 					    IP_FF_NO_MCAST_LOOP, zoneid);
22338 				}
22339 			}
22340 			if (ipha->ipha_ttl == 0) {
22341 				/*
22342 				 * 0 => only to this host i.e. we are
22343 				 * done. We are also done if this was the
22344 				 * loopback interface since it is sufficient
22345 				 * to loopback one copy of a multicast packet.
22346 				 */
22347 				freemsg(first_mp);
22348 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22349 				    "ip_wput_ire_end: q %p (%S)",
22350 				    q, "loopback");
22351 				ire_refrele(ire);
22352 				if (conn_outgoing_ill != NULL)
22353 					ill_refrele(conn_outgoing_ill);
22354 				return;
22355 			}
22356 			/*
22357 			 * ILLF_MULTICAST is checked in ip_newroute
22358 			 * i.e. we don't need to check it here since
22359 			 * all IRE_CACHEs come from ip_newroute.
22360 			 * For multicast traffic, SO_DONTROUTE is interpreted
22361 			 * to mean only send the packet out the interface
22362 			 * (optionally specified with IP_MULTICAST_IF)
22363 			 * and do not forward it out additional interfaces.
22364 			 * RSVP and the rsvp daemon is an example of a
22365 			 * protocol and user level process that
22366 			 * handles it's own routing. Hence, it uses the
22367 			 * SO_DONTROUTE option to accomplish this.
22368 			 */
22369 
22370 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
22371 				/* Unconditionally redo the checksum */
22372 				ipha->ipha_hdr_checksum = 0;
22373 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22374 
22375 				/*
22376 				 * If this needs to go out secure, we need
22377 				 * to wait till we finish the IPSEC
22378 				 * processing.
22379 				 */
22380 				if (ipsec_len == 0 &&
22381 				    ip_mforward(ill, ipha, mp)) {
22382 					freemsg(first_mp);
22383 					ip1dbg(("ip_wput: mforward failed\n"));
22384 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22385 					    "ip_wput_ire_end: q %p (%S)",
22386 					    q, "mforward failed");
22387 					ire_refrele(ire);
22388 					if (conn_outgoing_ill != NULL)
22389 						ill_refrele(conn_outgoing_ill);
22390 					return;
22391 				}
22392 			}
22393 		}
22394 		max_frag = ire->ire_max_frag;
22395 		cksum += ttl_protocol;
22396 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22397 			/* No fragmentation required for this one. */
22398 			/*
22399 			 * Don't use frag_flag if packet is pre-built or source
22400 			 * routed or if multicast (since multicast packets do
22401 			 * not solicit ICMP "packet too big" messages).
22402 			 */
22403 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22404 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22405 			    !ip_source_route_included(ipha)) &&
22406 			    !CLASSD(ipha->ipha_dst))
22407 				ipha->ipha_fragment_offset_and_flags |=
22408 				    htons(ire->ire_frag_flag);
22409 
22410 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22411 				/* Complete the IP header checksum. */
22412 				cksum += ipha->ipha_ident;
22413 				cksum += (v_hlen_tos_len >> 16)+
22414 				    (v_hlen_tos_len & 0xFFFF);
22415 				cksum += ipha->ipha_fragment_offset_and_flags;
22416 				hlen = (V_HLEN & 0xF) -
22417 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22418 				if (hlen) {
22419 				    checksumoptions:
22420 					/*
22421 					 * Account for the IP Options in the IP
22422 					 * header checksum.
22423 					 */
22424 					up = (uint16_t *)(rptr+
22425 					    IP_SIMPLE_HDR_LENGTH);
22426 					do {
22427 						cksum += up[0];
22428 						cksum += up[1];
22429 						up += 2;
22430 					} while (--hlen);
22431 				}
22432 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22433 				cksum = ~(cksum + (cksum >> 16));
22434 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22435 			}
22436 			if (ipsec_len != 0) {
22437 				ipsec_out_process(q, first_mp, ire, ill_index);
22438 				if (!next_mp) {
22439 					ire_refrele(ire);
22440 					if (conn_outgoing_ill != NULL)
22441 						ill_refrele(conn_outgoing_ill);
22442 					return;
22443 				}
22444 				goto next;
22445 			}
22446 
22447 			/*
22448 			 * multirt_send has already been handled
22449 			 * for broadcast, but not yet for multicast
22450 			 * or IP options.
22451 			 */
22452 			if (next_mp == NULL) {
22453 				if (ire->ire_flags & RTF_MULTIRT) {
22454 					multirt_send = B_TRUE;
22455 				}
22456 			}
22457 
22458 			/*
22459 			 * In most cases, the emission loop below is
22460 			 * entered only once. Only in the case where
22461 			 * the ire holds the RTF_MULTIRT flag, do we loop
22462 			 * to process all RTF_MULTIRT ires in the bucket,
22463 			 * and send the packet through all crossed
22464 			 * RTF_MULTIRT routes.
22465 			 */
22466 			do {
22467 				if (multirt_send) {
22468 					irb_t *irb;
22469 
22470 					irb = ire->ire_bucket;
22471 					ASSERT(irb != NULL);
22472 					/*
22473 					 * We are in a multiple send case,
22474 					 * need to get the next IRE and make
22475 					 * a duplicate of the packet.
22476 					 */
22477 					IRB_REFHOLD(irb);
22478 					for (ire1 = ire->ire_next;
22479 					    ire1 != NULL;
22480 					    ire1 = ire1->ire_next) {
22481 						if (!(ire1->ire_flags &
22482 						    RTF_MULTIRT))
22483 							continue;
22484 						if (ire1->ire_addr !=
22485 						    ire->ire_addr)
22486 							continue;
22487 						if (ire1->ire_marks &
22488 						    (IRE_MARK_CONDEMNED|
22489 							IRE_MARK_HIDDEN))
22490 							continue;
22491 
22492 						/* Got one */
22493 						IRE_REFHOLD(ire1);
22494 						break;
22495 					}
22496 					IRB_REFRELE(irb);
22497 
22498 					if (ire1 != NULL) {
22499 						next_mp = copyb(mp);
22500 						if ((next_mp == NULL) ||
22501 						    ((mp->b_cont != NULL) &&
22502 						    ((next_mp->b_cont =
22503 						    dupmsg(mp->b_cont))
22504 						    == NULL))) {
22505 							freemsg(next_mp);
22506 							next_mp = NULL;
22507 							ire_refrele(ire1);
22508 							ire1 = NULL;
22509 						}
22510 					}
22511 
22512 					/*
22513 					 * Last multiroute ire; don't loop
22514 					 * anymore. The emission is over
22515 					 * and next_mp is NULL.
22516 					 */
22517 					if (ire1 == NULL) {
22518 						multirt_send = B_FALSE;
22519 					}
22520 				}
22521 
22522 				out_ill = ire->ire_ipif->ipif_ill;
22523 				DTRACE_PROBE4(ip4__physical__out__start,
22524 				    ill_t *, NULL,
22525 				    ill_t *, out_ill,
22526 				    ipha_t *, ipha, mblk_t *, mp);
22527 				FW_HOOKS(ip4_physical_out_event,
22528 				    ipv4firewall_physical_out,
22529 				    NULL, out_ill, ipha, mp, mp);
22530 				DTRACE_PROBE1(ip4__physical__out__end,
22531 				    mblk_t *, mp);
22532 				if (mp == NULL)
22533 					goto release_ire_and_ill_2;
22534 
22535 				ASSERT(ipsec_len == 0);
22536 				mp->b_prev =
22537 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22538 				DTRACE_PROBE2(ip__xmit__2,
22539 				    mblk_t *, mp, ire_t *, ire);
22540 				pktxmit_state = ip_xmit_v4(mp, ire,
22541 				    NULL, B_TRUE);
22542 				if ((pktxmit_state == SEND_FAILED) ||
22543 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22544 release_ire_and_ill_2:
22545 					if (next_mp) {
22546 						freemsg(next_mp);
22547 						ire_refrele(ire1);
22548 					}
22549 					ire_refrele(ire);
22550 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22551 					    "ip_wput_ire_end: q %p (%S)",
22552 					    q, "discard MDATA");
22553 					if (conn_outgoing_ill != NULL)
22554 						ill_refrele(conn_outgoing_ill);
22555 					return;
22556 				}
22557 
22558 				if (multirt_send) {
22559 					/*
22560 					 * We are in a multiple send case,
22561 					 * need to re-enter the sending loop
22562 					 * using the next ire.
22563 					 */
22564 					ire_refrele(ire);
22565 					ire = ire1;
22566 					stq = ire->ire_stq;
22567 					mp = next_mp;
22568 					next_mp = NULL;
22569 					ipha = (ipha_t *)mp->b_rptr;
22570 					ill_index = Q_TO_INDEX(stq);
22571 				}
22572 			} while (multirt_send);
22573 
22574 			if (!next_mp) {
22575 				/*
22576 				 * Last copy going out (the ultra-common
22577 				 * case).  Note that we intentionally replicate
22578 				 * the putnext rather than calling it before
22579 				 * the next_mp check in hopes of a little
22580 				 * tail-call action out of the compiler.
22581 				 */
22582 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22583 				    "ip_wput_ire_end: q %p (%S)",
22584 				    q, "last copy out(1)");
22585 				ire_refrele(ire);
22586 				if (conn_outgoing_ill != NULL)
22587 					ill_refrele(conn_outgoing_ill);
22588 				return;
22589 			}
22590 			/* More copies going out below. */
22591 		} else {
22592 			int offset;
22593 		    fragmentit:
22594 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
22595 			/*
22596 			 * If this would generate a icmp_frag_needed message,
22597 			 * we need to handle it before we do the IPSEC
22598 			 * processing. Otherwise, we need to strip the IPSEC
22599 			 * headers before we send up the message to the ULPs
22600 			 * which becomes messy and difficult.
22601 			 */
22602 			if (ipsec_len != 0) {
22603 				if ((max_frag < (unsigned int)(LENGTH +
22604 				    ipsec_len)) && (offset & IPH_DF)) {
22605 
22606 					BUMP_MIB(&ip_mib, ipFragFails);
22607 					ipha->ipha_hdr_checksum = 0;
22608 					ipha->ipha_hdr_checksum =
22609 					    (uint16_t)ip_csum_hdr(ipha);
22610 					icmp_frag_needed(ire->ire_stq, first_mp,
22611 					    max_frag, zoneid);
22612 					if (!next_mp) {
22613 						ire_refrele(ire);
22614 						if (conn_outgoing_ill != NULL) {
22615 							ill_refrele(
22616 							    conn_outgoing_ill);
22617 						}
22618 						return;
22619 					}
22620 				} else {
22621 					/*
22622 					 * This won't cause a icmp_frag_needed
22623 					 * message. to be gnerated. Send it on
22624 					 * the wire. Note that this could still
22625 					 * cause fragmentation and all we
22626 					 * do is the generation of the message
22627 					 * to the ULP if needed before IPSEC.
22628 					 */
22629 					if (!next_mp) {
22630 						ipsec_out_process(q, first_mp,
22631 						    ire, ill_index);
22632 						TRACE_2(TR_FAC_IP,
22633 						    TR_IP_WPUT_IRE_END,
22634 						    "ip_wput_ire_end: q %p "
22635 						    "(%S)", q,
22636 						    "last ipsec_out_process");
22637 						ire_refrele(ire);
22638 						if (conn_outgoing_ill != NULL) {
22639 							ill_refrele(
22640 							    conn_outgoing_ill);
22641 						}
22642 						return;
22643 					}
22644 					ipsec_out_process(q, first_mp,
22645 					    ire, ill_index);
22646 				}
22647 			} else {
22648 				/*
22649 				 * Initiate IPPF processing. For
22650 				 * fragmentable packets we finish
22651 				 * all QOS packet processing before
22652 				 * calling:
22653 				 * ip_wput_ire_fragmentit->ip_wput_frag
22654 				 */
22655 
22656 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22657 					ip_process(IPP_LOCAL_OUT, &mp,
22658 					    ill_index);
22659 					if (mp == NULL) {
22660 						BUMP_MIB(&ip_mib,
22661 						    ipOutDiscards);
22662 						if (next_mp != NULL) {
22663 							freemsg(next_mp);
22664 							ire_refrele(ire1);
22665 						}
22666 						ire_refrele(ire);
22667 						TRACE_2(TR_FAC_IP,
22668 						    TR_IP_WPUT_IRE_END,
22669 						    "ip_wput_ire: q %p (%S)",
22670 						    q, "discard MDATA");
22671 						if (conn_outgoing_ill != NULL) {
22672 							ill_refrele(
22673 							    conn_outgoing_ill);
22674 						}
22675 						return;
22676 					}
22677 				}
22678 				if (!next_mp) {
22679 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22680 					    "ip_wput_ire_end: q %p (%S)",
22681 					    q, "last fragmentation");
22682 					ip_wput_ire_fragmentit(mp, ire,
22683 					    zoneid);
22684 					ire_refrele(ire);
22685 					if (conn_outgoing_ill != NULL)
22686 						ill_refrele(conn_outgoing_ill);
22687 					return;
22688 				}
22689 				ip_wput_ire_fragmentit(mp, ire, zoneid);
22690 			}
22691 		}
22692 	} else {
22693 	    nullstq:
22694 		/* A NULL stq means the destination address is local. */
22695 		UPDATE_OB_PKT_COUNT(ire);
22696 		ire->ire_last_used_time = lbolt;
22697 		ASSERT(ire->ire_ipif != NULL);
22698 		if (!next_mp) {
22699 			/*
22700 			 * Is there an "in" and "out" for traffic local
22701 			 * to a host (loopback)?  The code in Solaris doesn't
22702 			 * explicitly draw a line in its code for in vs out,
22703 			 * so we've had to draw a line in the sand: ip_wput_ire
22704 			 * is considered to be the "output" side and
22705 			 * ip_wput_local to be the "input" side.
22706 			 */
22707 			out_ill = ire->ire_ipif->ipif_ill;
22708 
22709 			DTRACE_PROBE4(ip4__loopback__out__start,
22710 			    ill_t *, NULL, ill_t *, out_ill,
22711 			    ipha_t *, ipha, mblk_t *, first_mp);
22712 
22713 			FW_HOOKS(ip4_loopback_out_event,
22714 			    ipv4firewall_loopback_out,
22715 			    NULL, out_ill, ipha, first_mp, mp);
22716 
22717 			DTRACE_PROBE1(ip4__loopback__out_end,
22718 			    mblk_t *, first_mp);
22719 
22720 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22721 			    "ip_wput_ire_end: q %p (%S)",
22722 			    q, "local address");
22723 
22724 			if (first_mp != NULL)
22725 				ip_wput_local(q, out_ill, ipha,
22726 				    first_mp, ire, 0, ire->ire_zoneid);
22727 			ire_refrele(ire);
22728 			if (conn_outgoing_ill != NULL)
22729 				ill_refrele(conn_outgoing_ill);
22730 			return;
22731 		}
22732 
22733 		out_ill = ire->ire_ipif->ipif_ill;
22734 
22735 		DTRACE_PROBE4(ip4__loopback__out__start,
22736 		    ill_t *, NULL, ill_t *, out_ill,
22737 		    ipha_t *, ipha, mblk_t *, first_mp);
22738 
22739 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
22740 		    NULL, out_ill, ipha, first_mp, mp);
22741 
22742 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
22743 
22744 		if (first_mp != NULL)
22745 			ip_wput_local(q, out_ill, ipha,
22746 			    first_mp, ire, 0, ire->ire_zoneid);
22747 	}
22748 next:
22749 	/*
22750 	 * More copies going out to additional interfaces.
22751 	 * ire1 has already been held. We don't need the
22752 	 * "ire" anymore.
22753 	 */
22754 	ire_refrele(ire);
22755 	ire = ire1;
22756 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
22757 	mp = next_mp;
22758 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
22759 	ill = ire_to_ill(ire);
22760 	first_mp = mp;
22761 	if (ipsec_len != 0) {
22762 		ASSERT(first_mp->b_datap->db_type == M_CTL);
22763 		mp = mp->b_cont;
22764 	}
22765 	dst = ire->ire_addr;
22766 	ipha = (ipha_t *)mp->b_rptr;
22767 	/*
22768 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
22769 	 * Restore ipha_ident "no checksum" flag.
22770 	 */
22771 	src = orig_src;
22772 	ipha->ipha_ident = ip_hdr_included;
22773 	goto another;
22774 
22775 #undef	rptr
22776 #undef	Q_TO_INDEX
22777 }
22778 
22779 /*
22780  * Routine to allocate a message that is used to notify the ULP about MDT.
22781  * The caller may provide a pointer to the link-layer MDT capabilities,
22782  * or NULL if MDT is to be disabled on the stream.
22783  */
22784 mblk_t *
22785 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
22786 {
22787 	mblk_t *mp;
22788 	ip_mdt_info_t *mdti;
22789 	ill_mdt_capab_t *idst;
22790 
22791 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
22792 		DB_TYPE(mp) = M_CTL;
22793 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
22794 		mdti = (ip_mdt_info_t *)mp->b_rptr;
22795 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
22796 		idst = &(mdti->mdt_capab);
22797 
22798 		/*
22799 		 * If the caller provides us with the capability, copy
22800 		 * it over into our notification message; otherwise
22801 		 * we zero out the capability portion.
22802 		 */
22803 		if (isrc != NULL)
22804 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
22805 		else
22806 			bzero((caddr_t)idst, sizeof (*idst));
22807 	}
22808 	return (mp);
22809 }
22810 
22811 /*
22812  * Routine which determines whether MDT can be enabled on the destination
22813  * IRE and IPC combination, and if so, allocates and returns the MDT
22814  * notification mblk that may be used by ULP.  We also check if we need to
22815  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
22816  * MDT usage in the past have been lifted.  This gets called during IP
22817  * and ULP binding.
22818  */
22819 mblk_t *
22820 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
22821     ill_mdt_capab_t *mdt_cap)
22822 {
22823 	mblk_t *mp;
22824 	boolean_t rc = B_FALSE;
22825 
22826 	ASSERT(dst_ire != NULL);
22827 	ASSERT(connp != NULL);
22828 	ASSERT(mdt_cap != NULL);
22829 
22830 	/*
22831 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
22832 	 * Multidata, which is handled in tcp_multisend().  This
22833 	 * is the reason why we do all these checks here, to ensure
22834 	 * that we don't enable Multidata for the cases which we
22835 	 * can't handle at the moment.
22836 	 */
22837 	do {
22838 		/* Only do TCP at the moment */
22839 		if (connp->conn_ulp != IPPROTO_TCP)
22840 			break;
22841 
22842 		/*
22843 		 * IPSEC outbound policy present?  Note that we get here
22844 		 * after calling ipsec_conn_cache_policy() where the global
22845 		 * policy checking is performed.  conn_latch will be
22846 		 * non-NULL as long as there's a policy defined,
22847 		 * i.e. conn_out_enforce_policy may be NULL in such case
22848 		 * when the connection is non-secure, and hence we check
22849 		 * further if the latch refers to an outbound policy.
22850 		 */
22851 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
22852 			break;
22853 
22854 		/* CGTP (multiroute) is enabled? */
22855 		if (dst_ire->ire_flags & RTF_MULTIRT)
22856 			break;
22857 
22858 		/* Outbound IPQoS enabled? */
22859 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
22860 			/*
22861 			 * In this case, we disable MDT for this and all
22862 			 * future connections going over the interface.
22863 			 */
22864 			mdt_cap->ill_mdt_on = 0;
22865 			break;
22866 		}
22867 
22868 		/* socket option(s) present? */
22869 		if (!CONN_IS_MD_FASTPATH(connp))
22870 			break;
22871 
22872 		rc = B_TRUE;
22873 	/* CONSTCOND */
22874 	} while (0);
22875 
22876 	/* Remember the result */
22877 	connp->conn_mdt_ok = rc;
22878 
22879 	if (!rc)
22880 		return (NULL);
22881 	else if (!mdt_cap->ill_mdt_on) {
22882 		/*
22883 		 * If MDT has been previously turned off in the past, and we
22884 		 * currently can do MDT (due to IPQoS policy removal, etc.)
22885 		 * then enable it for this interface.
22886 		 */
22887 		mdt_cap->ill_mdt_on = 1;
22888 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
22889 		    "interface %s\n", ill_name));
22890 	}
22891 
22892 	/* Allocate the MDT info mblk */
22893 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
22894 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
22895 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
22896 		return (NULL);
22897 	}
22898 	return (mp);
22899 }
22900 
22901 /*
22902  * Create destination address attribute, and fill it with the physical
22903  * destination address and SAP taken from the template DL_UNITDATA_REQ
22904  * message block.
22905  */
22906 boolean_t
22907 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
22908 {
22909 	dl_unitdata_req_t *dlurp;
22910 	pattr_t *pa;
22911 	pattrinfo_t pa_info;
22912 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
22913 	uint_t das_len, das_off;
22914 
22915 	ASSERT(dlmp != NULL);
22916 
22917 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
22918 	das_len = dlurp->dl_dest_addr_length;
22919 	das_off = dlurp->dl_dest_addr_offset;
22920 
22921 	pa_info.type = PATTR_DSTADDRSAP;
22922 	pa_info.len = sizeof (**das) + das_len - 1;
22923 
22924 	/* create and associate the attribute */
22925 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22926 	if (pa != NULL) {
22927 		ASSERT(*das != NULL);
22928 		(*das)->addr_is_group = 0;
22929 		(*das)->addr_len = (uint8_t)das_len;
22930 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
22931 	}
22932 
22933 	return (pa != NULL);
22934 }
22935 
22936 /*
22937  * Create hardware checksum attribute and fill it with the values passed.
22938  */
22939 boolean_t
22940 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
22941     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
22942 {
22943 	pattr_t *pa;
22944 	pattrinfo_t pa_info;
22945 
22946 	ASSERT(mmd != NULL);
22947 
22948 	pa_info.type = PATTR_HCKSUM;
22949 	pa_info.len = sizeof (pattr_hcksum_t);
22950 
22951 	/* create and associate the attribute */
22952 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22953 	if (pa != NULL) {
22954 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
22955 
22956 		hck->hcksum_start_offset = start_offset;
22957 		hck->hcksum_stuff_offset = stuff_offset;
22958 		hck->hcksum_end_offset = end_offset;
22959 		hck->hcksum_flags = flags;
22960 	}
22961 	return (pa != NULL);
22962 }
22963 
22964 /*
22965  * Create zerocopy attribute and fill it with the specified flags
22966  */
22967 boolean_t
22968 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
22969 {
22970 	pattr_t *pa;
22971 	pattrinfo_t pa_info;
22972 
22973 	ASSERT(mmd != NULL);
22974 	pa_info.type = PATTR_ZCOPY;
22975 	pa_info.len = sizeof (pattr_zcopy_t);
22976 
22977 	/* create and associate the attribute */
22978 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
22979 	if (pa != NULL) {
22980 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
22981 
22982 		zcopy->zcopy_flags = flags;
22983 	}
22984 	return (pa != NULL);
22985 }
22986 
22987 /*
22988  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
22989  * block chain. We could rewrite to handle arbitrary message block chains but
22990  * that would make the code complicated and slow. Right now there three
22991  * restrictions:
22992  *
22993  *   1. The first message block must contain the complete IP header and
22994  *	at least 1 byte of payload data.
22995  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
22996  *	so that we can use a single Multidata message.
22997  *   3. No frag must be distributed over two or more message blocks so
22998  *	that we don't need more than two packet descriptors per frag.
22999  *
23000  * The above restrictions allow us to support userland applications (which
23001  * will send down a single message block) and NFS over UDP (which will
23002  * send down a chain of at most three message blocks).
23003  *
23004  * We also don't use MDT for payloads with less than or equal to
23005  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23006  */
23007 boolean_t
23008 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23009 {
23010 	int	blocks;
23011 	ssize_t	total, missing, size;
23012 
23013 	ASSERT(mp != NULL);
23014 	ASSERT(hdr_len > 0);
23015 
23016 	size = MBLKL(mp) - hdr_len;
23017 	if (size <= 0)
23018 		return (B_FALSE);
23019 
23020 	/* The first mblk contains the header and some payload. */
23021 	blocks = 1;
23022 	total = size;
23023 	size %= len;
23024 	missing = (size == 0) ? 0 : (len - size);
23025 	mp = mp->b_cont;
23026 
23027 	while (mp != NULL) {
23028 		/*
23029 		 * Give up if we encounter a zero length message block.
23030 		 * In practice, this should rarely happen and therefore
23031 		 * not worth the trouble of freeing and re-linking the
23032 		 * mblk from the chain to handle such case.
23033 		 */
23034 		if ((size = MBLKL(mp)) == 0)
23035 			return (B_FALSE);
23036 
23037 		/* Too many payload buffers for a single Multidata message? */
23038 		if (++blocks > MULTIDATA_MAX_PBUFS)
23039 			return (B_FALSE);
23040 
23041 		total += size;
23042 		/* Is a frag distributed over two or more message blocks? */
23043 		if (missing > size)
23044 			return (B_FALSE);
23045 		size -= missing;
23046 
23047 		size %= len;
23048 		missing = (size == 0) ? 0 : (len - size);
23049 
23050 		mp = mp->b_cont;
23051 	}
23052 
23053 	return (total > ip_wput_frag_mdt_min);
23054 }
23055 
23056 /*
23057  * Outbound IPv4 fragmentation routine using MDT.
23058  */
23059 static void
23060 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23061     uint32_t frag_flag, int offset)
23062 {
23063 	ipha_t		*ipha_orig;
23064 	int		i1, ip_data_end;
23065 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23066 	mblk_t		*hdr_mp, *md_mp = NULL;
23067 	unsigned char	*hdr_ptr, *pld_ptr;
23068 	multidata_t	*mmd;
23069 	ip_pdescinfo_t	pdi;
23070 
23071 	ASSERT(DB_TYPE(mp) == M_DATA);
23072 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23073 
23074 	ipha_orig = (ipha_t *)mp->b_rptr;
23075 	mp->b_rptr += sizeof (ipha_t);
23076 
23077 	/* Calculate how many packets we will send out */
23078 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23079 	pkts = (i1 + len - 1) / len;
23080 	ASSERT(pkts > 1);
23081 
23082 	/* Allocate a message block which will hold all the IP Headers. */
23083 	wroff = ip_wroff_extra;
23084 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23085 
23086 	i1 = pkts * hdr_chunk_len;
23087 	/*
23088 	 * Create the header buffer, Multidata and destination address
23089 	 * and SAP attribute that should be associated with it.
23090 	 */
23091 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23092 	    ((hdr_mp->b_wptr += i1),
23093 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23094 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23095 		freemsg(mp);
23096 		if (md_mp == NULL) {
23097 			freemsg(hdr_mp);
23098 		} else {
23099 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23100 			freemsg(md_mp);
23101 		}
23102 		IP_STAT(ip_frag_mdt_allocfail);
23103 		UPDATE_MIB(&ip_mib, ipOutDiscards, pkts);
23104 		return;
23105 	}
23106 	IP_STAT(ip_frag_mdt_allocd);
23107 
23108 	/*
23109 	 * Add a payload buffer to the Multidata; this operation must not
23110 	 * fail, or otherwise our logic in this routine is broken.  There
23111 	 * is no memory allocation done by the routine, so any returned
23112 	 * failure simply tells us that we've done something wrong.
23113 	 *
23114 	 * A failure tells us that either we're adding the same payload
23115 	 * buffer more than once, or we're trying to add more buffers than
23116 	 * allowed.  None of the above cases should happen, and we panic
23117 	 * because either there's horrible heap corruption, and/or
23118 	 * programming mistake.
23119 	 */
23120 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23121 		goto pbuf_panic;
23122 
23123 	hdr_ptr = hdr_mp->b_rptr;
23124 	pld_ptr = mp->b_rptr;
23125 
23126 	/* Establish the ending byte offset, based on the starting offset. */
23127 	offset <<= 3;
23128 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23129 	    IP_SIMPLE_HDR_LENGTH;
23130 
23131 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23132 
23133 	while (pld_ptr < mp->b_wptr) {
23134 		ipha_t		*ipha;
23135 		uint16_t	offset_and_flags;
23136 		uint16_t	ip_len;
23137 		int		error;
23138 
23139 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23140 		ipha = (ipha_t *)(hdr_ptr + wroff);
23141 		ASSERT(OK_32PTR(ipha));
23142 		*ipha = *ipha_orig;
23143 
23144 		if (ip_data_end - offset > len) {
23145 			offset_and_flags = IPH_MF;
23146 		} else {
23147 			/*
23148 			 * Last frag. Set len to the length of this last piece.
23149 			 */
23150 			len = ip_data_end - offset;
23151 			/* A frag of a frag might have IPH_MF non-zero */
23152 			offset_and_flags =
23153 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23154 			    IPH_MF;
23155 		}
23156 		offset_and_flags |= (uint16_t)(offset >> 3);
23157 		offset_and_flags |= (uint16_t)frag_flag;
23158 		/* Store the offset and flags in the IP header. */
23159 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23160 
23161 		/* Store the length in the IP header. */
23162 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23163 		ipha->ipha_length = htons(ip_len);
23164 
23165 		/*
23166 		 * Set the IP header checksum.  Note that mp is just
23167 		 * the header, so this is easy to pass to ip_csum.
23168 		 */
23169 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23170 
23171 		/*
23172 		 * Record offset and size of header and data of the next packet
23173 		 * in the multidata message.
23174 		 */
23175 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23176 		PDESC_PLD_INIT(&pdi);
23177 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23178 		ASSERT(i1 > 0);
23179 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23180 		if (i1 == len) {
23181 			pld_ptr += len;
23182 		} else {
23183 			i1 = len - i1;
23184 			mp = mp->b_cont;
23185 			ASSERT(mp != NULL);
23186 			ASSERT(MBLKL(mp) >= i1);
23187 			/*
23188 			 * Attach the next payload message block to the
23189 			 * multidata message.
23190 			 */
23191 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23192 				goto pbuf_panic;
23193 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23194 			pld_ptr = mp->b_rptr + i1;
23195 		}
23196 
23197 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23198 		    KM_NOSLEEP)) == NULL) {
23199 			/*
23200 			 * Any failure other than ENOMEM indicates that we
23201 			 * have passed in invalid pdesc info or parameters
23202 			 * to mmd_addpdesc, which must not happen.
23203 			 *
23204 			 * EINVAL is a result of failure on boundary checks
23205 			 * against the pdesc info contents.  It should not
23206 			 * happen, and we panic because either there's
23207 			 * horrible heap corruption, and/or programming
23208 			 * mistake.
23209 			 */
23210 			if (error != ENOMEM) {
23211 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23212 				    "pdesc logic error detected for "
23213 				    "mmd %p pinfo %p (%d)\n",
23214 				    (void *)mmd, (void *)&pdi, error);
23215 				/* NOTREACHED */
23216 			}
23217 			IP_STAT(ip_frag_mdt_addpdescfail);
23218 			/* Free unattached payload message blocks as well */
23219 			md_mp->b_cont = mp->b_cont;
23220 			goto free_mmd;
23221 		}
23222 
23223 		/* Advance fragment offset. */
23224 		offset += len;
23225 
23226 		/* Advance to location for next header in the buffer. */
23227 		hdr_ptr += hdr_chunk_len;
23228 
23229 		/* Did we reach the next payload message block? */
23230 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23231 			mp = mp->b_cont;
23232 			/*
23233 			 * Attach the next message block with payload
23234 			 * data to the multidata message.
23235 			 */
23236 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23237 				goto pbuf_panic;
23238 			pld_ptr = mp->b_rptr;
23239 		}
23240 	}
23241 
23242 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23243 	ASSERT(mp->b_wptr == pld_ptr);
23244 
23245 	/* Update IP statistics */
23246 	UPDATE_MIB(&ip_mib, ipFragCreates, pkts);
23247 	BUMP_MIB(&ip_mib, ipFragOKs);
23248 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
23249 
23250 	if (pkt_type == OB_PKT) {
23251 		ire->ire_ob_pkt_count += pkts;
23252 		if (ire->ire_ipif != NULL)
23253 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23254 	} else {
23255 		/*
23256 		 * The type is IB_PKT in the forwarding path and in
23257 		 * the mobile IP case when the packet is being reverse-
23258 		 * tunneled to the home agent.
23259 		 */
23260 		ire->ire_ib_pkt_count += pkts;
23261 		ASSERT(!IRE_IS_LOCAL(ire));
23262 		if (ire->ire_type & IRE_BROADCAST)
23263 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23264 		else
23265 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23266 	}
23267 	ire->ire_last_used_time = lbolt;
23268 	/* Send it down */
23269 	putnext(ire->ire_stq, md_mp);
23270 	return;
23271 
23272 pbuf_panic:
23273 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23274 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23275 	    pbuf_idx);
23276 	/* NOTREACHED */
23277 }
23278 
23279 /*
23280  * Outbound IP fragmentation routine.
23281  *
23282  * NOTE : This routine does not ire_refrele the ire that is passed in
23283  * as the argument.
23284  */
23285 static void
23286 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23287     uint32_t frag_flag, zoneid_t zoneid)
23288 {
23289 	int		i1;
23290 	mblk_t		*ll_hdr_mp;
23291 	int 		ll_hdr_len;
23292 	int		hdr_len;
23293 	mblk_t		*hdr_mp;
23294 	ipha_t		*ipha;
23295 	int		ip_data_end;
23296 	int		len;
23297 	mblk_t		*mp = mp_orig, *mp1;
23298 	int		offset;
23299 	queue_t		*q;
23300 	uint32_t	v_hlen_tos_len;
23301 	mblk_t		*first_mp;
23302 	boolean_t	mctl_present;
23303 	ill_t		*ill;
23304 	ill_t		*out_ill;
23305 	mblk_t		*xmit_mp;
23306 	mblk_t		*carve_mp;
23307 	ire_t		*ire1 = NULL;
23308 	ire_t		*save_ire = NULL;
23309 	mblk_t  	*next_mp = NULL;
23310 	boolean_t	last_frag = B_FALSE;
23311 	boolean_t	multirt_send = B_FALSE;
23312 	ire_t		*first_ire = NULL;
23313 	irb_t		*irb = NULL;
23314 
23315 	/*
23316 	 * IPSEC does not allow hw accelerated packets to be fragmented
23317 	 * This check is made in ip_wput_ipsec_out prior to coming here
23318 	 * via ip_wput_ire_fragmentit.
23319 	 *
23320 	 * If at this point we have an ire whose ARP request has not
23321 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23322 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23323 	 * This packet and all fragmentable packets for this ire will
23324 	 * continue to get dropped while ire_nce->nce_state remains in
23325 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23326 	 * ND_REACHABLE, all subsquent large packets for this ire will
23327 	 * get fragemented and sent out by this function.
23328 	 */
23329 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23330 		/* If nce_state is ND_INITIAL, trigger ARP query */
23331 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23332 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23333 		    " -  dropping packet\n"));
23334 		BUMP_MIB(&ip_mib, ipFragFails);
23335 		freemsg(mp);
23336 		return;
23337 	}
23338 
23339 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23340 	    "ip_wput_frag_start:");
23341 
23342 	if (mp->b_datap->db_type == M_CTL) {
23343 		first_mp = mp;
23344 		mp_orig = mp = mp->b_cont;
23345 		mctl_present = B_TRUE;
23346 	} else {
23347 		first_mp = mp;
23348 		mctl_present = B_FALSE;
23349 	}
23350 
23351 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23352 	ipha = (ipha_t *)mp->b_rptr;
23353 
23354 	/*
23355 	 * If the Don't Fragment flag is on, generate an ICMP destination
23356 	 * unreachable, fragmentation needed.
23357 	 */
23358 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23359 	if (offset & IPH_DF) {
23360 		BUMP_MIB(&ip_mib, ipFragFails);
23361 		/*
23362 		 * Need to compute hdr checksum if called from ip_wput_ire.
23363 		 * Note that ip_rput_forward verifies the checksum before
23364 		 * calling this routine so in that case this is a noop.
23365 		 */
23366 		ipha->ipha_hdr_checksum = 0;
23367 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23368 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
23369 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23370 		    "ip_wput_frag_end:(%S)",
23371 		    "don't fragment");
23372 		return;
23373 	}
23374 	if (mctl_present)
23375 		freeb(first_mp);
23376 	/*
23377 	 * Establish the starting offset.  May not be zero if we are fragging
23378 	 * a fragment that is being forwarded.
23379 	 */
23380 	offset = offset & IPH_OFFSET;
23381 
23382 	/* TODO why is this test needed? */
23383 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23384 	if (((max_frag - LENGTH) & ~7) < 8) {
23385 		/* TODO: notify ulp somehow */
23386 		BUMP_MIB(&ip_mib, ipFragFails);
23387 		freemsg(mp);
23388 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23389 		    "ip_wput_frag_end:(%S)",
23390 		    "len < 8");
23391 		return;
23392 	}
23393 
23394 	hdr_len = (V_HLEN & 0xF) << 2;
23395 
23396 	ipha->ipha_hdr_checksum = 0;
23397 
23398 	/*
23399 	 * Establish the number of bytes maximum per frag, after putting
23400 	 * in the header.
23401 	 */
23402 	len = (max_frag - hdr_len) & ~7;
23403 
23404 	/* Check if we can use MDT to send out the frags. */
23405 	ASSERT(!IRE_IS_LOCAL(ire));
23406 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
23407 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
23408 	    (ill = ire_to_ill(ire)) != NULL && ILL_MDT_CAPABLE(ill) &&
23409 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23410 		ASSERT(ill->ill_mdt_capab != NULL);
23411 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23412 			/*
23413 			 * If MDT has been previously turned off in the past,
23414 			 * and we currently can do MDT (due to IPQoS policy
23415 			 * removal, etc.) then enable it for this interface.
23416 			 */
23417 			ill->ill_mdt_capab->ill_mdt_on = 1;
23418 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23419 			    ill->ill_name));
23420 		}
23421 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23422 		    offset);
23423 		return;
23424 	}
23425 
23426 	/* Get a copy of the header for the trailing frags */
23427 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
23428 	if (!hdr_mp) {
23429 		BUMP_MIB(&ip_mib, ipOutDiscards);
23430 		freemsg(mp);
23431 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23432 		    "ip_wput_frag_end:(%S)",
23433 		    "couldn't copy hdr");
23434 		return;
23435 	}
23436 	if (DB_CRED(mp) != NULL)
23437 		mblk_setcred(hdr_mp, DB_CRED(mp));
23438 
23439 	/* Store the starting offset, with the MoreFrags flag. */
23440 	i1 = offset | IPH_MF | frag_flag;
23441 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23442 
23443 	/* Establish the ending byte offset, based on the starting offset. */
23444 	offset <<= 3;
23445 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23446 
23447 	/* Store the length of the first fragment in the IP header. */
23448 	i1 = len + hdr_len;
23449 	ASSERT(i1 <= IP_MAXPACKET);
23450 	ipha->ipha_length = htons((uint16_t)i1);
23451 
23452 	/*
23453 	 * Compute the IP header checksum for the first frag.  We have to
23454 	 * watch out that we stop at the end of the header.
23455 	 */
23456 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23457 
23458 	/*
23459 	 * Now carve off the first frag.  Note that this will include the
23460 	 * original IP header.
23461 	 */
23462 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
23463 		BUMP_MIB(&ip_mib, ipOutDiscards);
23464 		freeb(hdr_mp);
23465 		freemsg(mp_orig);
23466 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23467 		    "ip_wput_frag_end:(%S)",
23468 		    "couldn't carve first");
23469 		return;
23470 	}
23471 
23472 	/*
23473 	 * Multirouting case. Each fragment is replicated
23474 	 * via all non-condemned RTF_MULTIRT routes
23475 	 * currently resolved.
23476 	 * We ensure that first_ire is the first RTF_MULTIRT
23477 	 * ire in the bucket.
23478 	 */
23479 	if (ire->ire_flags & RTF_MULTIRT) {
23480 		irb = ire->ire_bucket;
23481 		ASSERT(irb != NULL);
23482 
23483 		multirt_send = B_TRUE;
23484 
23485 		/* Make sure we do not omit any multiroute ire. */
23486 		IRB_REFHOLD(irb);
23487 		for (first_ire = irb->irb_ire;
23488 		    first_ire != NULL;
23489 		    first_ire = first_ire->ire_next) {
23490 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
23491 			    (first_ire->ire_addr == ire->ire_addr) &&
23492 			    !(first_ire->ire_marks &
23493 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
23494 				break;
23495 		}
23496 
23497 		if (first_ire != NULL) {
23498 			if (first_ire != ire) {
23499 				IRE_REFHOLD(first_ire);
23500 				/*
23501 				 * Do not release the ire passed in
23502 				 * as the argument.
23503 				 */
23504 				ire = first_ire;
23505 			} else {
23506 				first_ire = NULL;
23507 			}
23508 		}
23509 		IRB_REFRELE(irb);
23510 
23511 		/*
23512 		 * Save the first ire; we will need to restore it
23513 		 * for the trailing frags.
23514 		 * We REFHOLD save_ire, as each iterated ire will be
23515 		 * REFRELEd.
23516 		 */
23517 		save_ire = ire;
23518 		IRE_REFHOLD(save_ire);
23519 	}
23520 
23521 	/*
23522 	 * First fragment emission loop.
23523 	 * In most cases, the emission loop below is entered only
23524 	 * once. Only in the case where the ire holds the RTF_MULTIRT
23525 	 * flag, do we loop to process all RTF_MULTIRT ires in the
23526 	 * bucket, and send the fragment through all crossed
23527 	 * RTF_MULTIRT routes.
23528 	 */
23529 	do {
23530 		if (ire->ire_flags & RTF_MULTIRT) {
23531 			/*
23532 			 * We are in a multiple send case, need to get
23533 			 * the next ire and make a copy of the packet.
23534 			 * ire1 holds here the next ire to process in the
23535 			 * bucket. If multirouting is expected,
23536 			 * any non-RTF_MULTIRT ire that has the
23537 			 * right destination address is ignored.
23538 			 *
23539 			 * We have to take into account the MTU of
23540 			 * each walked ire. max_frag is set by the
23541 			 * the caller and generally refers to
23542 			 * the primary ire entry. Here we ensure that
23543 			 * no route with a lower MTU will be used, as
23544 			 * fragments are carved once for all ires,
23545 			 * then replicated.
23546 			 */
23547 			ASSERT(irb != NULL);
23548 			IRB_REFHOLD(irb);
23549 			for (ire1 = ire->ire_next;
23550 			    ire1 != NULL;
23551 			    ire1 = ire1->ire_next) {
23552 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
23553 					continue;
23554 				if (ire1->ire_addr != ire->ire_addr)
23555 					continue;
23556 				if (ire1->ire_marks &
23557 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
23558 					continue;
23559 				/*
23560 				 * Ensure we do not exceed the MTU
23561 				 * of the next route.
23562 				 */
23563 				if (ire1->ire_max_frag < max_frag) {
23564 					ip_multirt_bad_mtu(ire1, max_frag);
23565 					continue;
23566 				}
23567 
23568 				/* Got one. */
23569 				IRE_REFHOLD(ire1);
23570 				break;
23571 			}
23572 			IRB_REFRELE(irb);
23573 
23574 			if (ire1 != NULL) {
23575 				next_mp = copyb(mp);
23576 				if ((next_mp == NULL) ||
23577 				    ((mp->b_cont != NULL) &&
23578 				    ((next_mp->b_cont =
23579 				    dupmsg(mp->b_cont)) == NULL))) {
23580 					freemsg(next_mp);
23581 					next_mp = NULL;
23582 					ire_refrele(ire1);
23583 					ire1 = NULL;
23584 				}
23585 			}
23586 
23587 			/* Last multiroute ire; don't loop anymore. */
23588 			if (ire1 == NULL) {
23589 				multirt_send = B_FALSE;
23590 			}
23591 		}
23592 
23593 		ll_hdr_len = 0;
23594 		LOCK_IRE_FP_MP(ire);
23595 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23596 		if (ll_hdr_mp != NULL) {
23597 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23598 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
23599 		} else {
23600 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
23601 		}
23602 
23603 		/* If there is a transmit header, get a copy for this frag. */
23604 		/*
23605 		 * TODO: should check db_ref before calling ip_carve_mp since
23606 		 * it might give us a dup.
23607 		 */
23608 		if (!ll_hdr_mp) {
23609 			/* No xmit header. */
23610 			xmit_mp = mp;
23611 
23612 		/* We have a link-layer header that can fit in our mblk. */
23613 		} else if (mp->b_datap->db_ref == 1 &&
23614 		    ll_hdr_len != 0 &&
23615 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23616 			/* M_DATA fastpath */
23617 			mp->b_rptr -= ll_hdr_len;
23618 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
23619 			xmit_mp = mp;
23620 
23621 		/* Corner case if copyb has failed */
23622 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
23623 			UNLOCK_IRE_FP_MP(ire);
23624 			BUMP_MIB(&ip_mib, ipOutDiscards);
23625 			freeb(hdr_mp);
23626 			freemsg(mp);
23627 			freemsg(mp_orig);
23628 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23629 			    "ip_wput_frag_end:(%S)",
23630 			    "discard");
23631 
23632 			if (multirt_send) {
23633 				ASSERT(ire1);
23634 				ASSERT(next_mp);
23635 
23636 				freemsg(next_mp);
23637 				ire_refrele(ire1);
23638 			}
23639 			if (save_ire != NULL)
23640 				IRE_REFRELE(save_ire);
23641 
23642 			if (first_ire != NULL)
23643 				ire_refrele(first_ire);
23644 			return;
23645 
23646 		/*
23647 		 * Case of res_mp OR the fastpath mp can't fit
23648 		 * in the mblk
23649 		 */
23650 		} else {
23651 			xmit_mp->b_cont = mp;
23652 			if (DB_CRED(mp) != NULL)
23653 				mblk_setcred(xmit_mp, DB_CRED(mp));
23654 			/*
23655 			 * Get priority marking, if any.
23656 			 * We propagate the CoS marking from the
23657 			 * original packet that went to QoS processing
23658 			 * in ip_wput_ire to the newly carved mp.
23659 			 */
23660 			if (DB_TYPE(xmit_mp) == M_DATA)
23661 				xmit_mp->b_band = mp->b_band;
23662 		}
23663 		UNLOCK_IRE_FP_MP(ire);
23664 		q = ire->ire_stq;
23665 		BUMP_MIB(&ip_mib, ipFragCreates);
23666 
23667 		out_ill = (ill_t *)q->q_ptr;
23668 
23669 		DTRACE_PROBE4(ip4__physical__out__start,
23670 		    ill_t *, NULL, ill_t *, out_ill,
23671 		    ipha_t *, ipha, mblk_t *, xmit_mp);
23672 
23673 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
23674 		    NULL, out_ill, ipha, xmit_mp, mp);
23675 
23676 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
23677 
23678 		if (xmit_mp != NULL) {
23679 			putnext(q, xmit_mp);
23680 			if (pkt_type != OB_PKT) {
23681 				/*
23682 				 * Update the packet count of trailing
23683 				 * RTF_MULTIRT ires.
23684 				 */
23685 				UPDATE_OB_PKT_COUNT(ire);
23686 			}
23687 		}
23688 
23689 		if (multirt_send) {
23690 			/*
23691 			 * We are in a multiple send case; look for
23692 			 * the next ire and re-enter the loop.
23693 			 */
23694 			ASSERT(ire1);
23695 			ASSERT(next_mp);
23696 			/* REFRELE the current ire before looping */
23697 			ire_refrele(ire);
23698 			ire = ire1;
23699 			ire1 = NULL;
23700 			mp = next_mp;
23701 			next_mp = NULL;
23702 		}
23703 	} while (multirt_send);
23704 
23705 	ASSERT(ire1 == NULL);
23706 
23707 	/* Restore the original ire; we need it for the trailing frags */
23708 	if (save_ire != NULL) {
23709 		/* REFRELE the last iterated ire */
23710 		ire_refrele(ire);
23711 		/* save_ire has been REFHOLDed */
23712 		ire = save_ire;
23713 		save_ire = NULL;
23714 		q = ire->ire_stq;
23715 	}
23716 
23717 	if (pkt_type == OB_PKT) {
23718 		UPDATE_OB_PKT_COUNT(ire);
23719 	} else {
23720 		UPDATE_IB_PKT_COUNT(ire);
23721 	}
23722 
23723 	/* Advance the offset to the second frag starting point. */
23724 	offset += len;
23725 	/*
23726 	 * Update hdr_len from the copied header - there might be less options
23727 	 * in the later fragments.
23728 	 */
23729 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
23730 	/* Loop until done. */
23731 	for (;;) {
23732 		uint16_t	offset_and_flags;
23733 		uint16_t	ip_len;
23734 
23735 		if (ip_data_end - offset > len) {
23736 			/*
23737 			 * Carve off the appropriate amount from the original
23738 			 * datagram.
23739 			 */
23740 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23741 				mp = NULL;
23742 				break;
23743 			}
23744 			/*
23745 			 * More frags after this one.  Get another copy
23746 			 * of the header.
23747 			 */
23748 			if (carve_mp->b_datap->db_ref == 1 &&
23749 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23750 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23751 				/* Inline IP header */
23752 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23753 				    hdr_mp->b_rptr;
23754 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23755 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23756 				mp = carve_mp;
23757 			} else {
23758 				if (!(mp = copyb(hdr_mp))) {
23759 					freemsg(carve_mp);
23760 					break;
23761 				}
23762 				/* Get priority marking, if any. */
23763 				mp->b_band = carve_mp->b_band;
23764 				mp->b_cont = carve_mp;
23765 			}
23766 			ipha = (ipha_t *)mp->b_rptr;
23767 			offset_and_flags = IPH_MF;
23768 		} else {
23769 			/*
23770 			 * Last frag.  Consume the header. Set len to
23771 			 * the length of this last piece.
23772 			 */
23773 			len = ip_data_end - offset;
23774 
23775 			/*
23776 			 * Carve off the appropriate amount from the original
23777 			 * datagram.
23778 			 */
23779 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
23780 				mp = NULL;
23781 				break;
23782 			}
23783 			if (carve_mp->b_datap->db_ref == 1 &&
23784 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
23785 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
23786 				/* Inline IP header */
23787 				carve_mp->b_rptr -= hdr_mp->b_wptr -
23788 				    hdr_mp->b_rptr;
23789 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
23790 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
23791 				mp = carve_mp;
23792 				freeb(hdr_mp);
23793 				hdr_mp = mp;
23794 			} else {
23795 				mp = hdr_mp;
23796 				/* Get priority marking, if any. */
23797 				mp->b_band = carve_mp->b_band;
23798 				mp->b_cont = carve_mp;
23799 			}
23800 			ipha = (ipha_t *)mp->b_rptr;
23801 			/* A frag of a frag might have IPH_MF non-zero */
23802 			offset_and_flags =
23803 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23804 			    IPH_MF;
23805 		}
23806 		offset_and_flags |= (uint16_t)(offset >> 3);
23807 		offset_and_flags |= (uint16_t)frag_flag;
23808 		/* Store the offset and flags in the IP header. */
23809 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23810 
23811 		/* Store the length in the IP header. */
23812 		ip_len = (uint16_t)(len + hdr_len);
23813 		ipha->ipha_length = htons(ip_len);
23814 
23815 		/*
23816 		 * Set the IP header checksum.	Note that mp is just
23817 		 * the header, so this is easy to pass to ip_csum.
23818 		 */
23819 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23820 
23821 		/* Attach a transmit header, if any, and ship it. */
23822 		if (pkt_type == OB_PKT) {
23823 			UPDATE_OB_PKT_COUNT(ire);
23824 		} else {
23825 			UPDATE_IB_PKT_COUNT(ire);
23826 		}
23827 
23828 		if (ire->ire_flags & RTF_MULTIRT) {
23829 			irb = ire->ire_bucket;
23830 			ASSERT(irb != NULL);
23831 
23832 			multirt_send = B_TRUE;
23833 
23834 			/*
23835 			 * Save the original ire; we will need to restore it
23836 			 * for the tailing frags.
23837 			 */
23838 			save_ire = ire;
23839 			IRE_REFHOLD(save_ire);
23840 		}
23841 		/*
23842 		 * Emission loop for this fragment, similar
23843 		 * to what is done for the first fragment.
23844 		 */
23845 		do {
23846 			if (multirt_send) {
23847 				/*
23848 				 * We are in a multiple send case, need to get
23849 				 * the next ire and make a copy of the packet.
23850 				 */
23851 				ASSERT(irb != NULL);
23852 				IRB_REFHOLD(irb);
23853 				for (ire1 = ire->ire_next;
23854 				    ire1 != NULL;
23855 				    ire1 = ire1->ire_next) {
23856 					if (!(ire1->ire_flags & RTF_MULTIRT))
23857 						continue;
23858 					if (ire1->ire_addr != ire->ire_addr)
23859 						continue;
23860 					if (ire1->ire_marks &
23861 					    (IRE_MARK_CONDEMNED|
23862 						IRE_MARK_HIDDEN))
23863 						continue;
23864 					/*
23865 					 * Ensure we do not exceed the MTU
23866 					 * of the next route.
23867 					 */
23868 					if (ire1->ire_max_frag < max_frag) {
23869 						ip_multirt_bad_mtu(ire1,
23870 						    max_frag);
23871 						continue;
23872 					}
23873 
23874 					/* Got one. */
23875 					IRE_REFHOLD(ire1);
23876 					break;
23877 				}
23878 				IRB_REFRELE(irb);
23879 
23880 				if (ire1 != NULL) {
23881 					next_mp = copyb(mp);
23882 					if ((next_mp == NULL) ||
23883 					    ((mp->b_cont != NULL) &&
23884 					    ((next_mp->b_cont =
23885 					    dupmsg(mp->b_cont)) == NULL))) {
23886 						freemsg(next_mp);
23887 						next_mp = NULL;
23888 						ire_refrele(ire1);
23889 						ire1 = NULL;
23890 					}
23891 				}
23892 
23893 				/* Last multiroute ire; don't loop anymore. */
23894 				if (ire1 == NULL) {
23895 					multirt_send = B_FALSE;
23896 				}
23897 			}
23898 
23899 			/* Update transmit header */
23900 			ll_hdr_len = 0;
23901 			LOCK_IRE_FP_MP(ire);
23902 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
23903 			if (ll_hdr_mp != NULL) {
23904 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
23905 				ll_hdr_len = MBLKL(ll_hdr_mp);
23906 			} else {
23907 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
23908 			}
23909 
23910 			if (!ll_hdr_mp) {
23911 				xmit_mp = mp;
23912 
23913 			/*
23914 			 * We have link-layer header that can fit in
23915 			 * our mblk.
23916 			 */
23917 			} else if (mp->b_datap->db_ref == 1 &&
23918 			    ll_hdr_len != 0 &&
23919 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
23920 				/* M_DATA fastpath */
23921 				mp->b_rptr -= ll_hdr_len;
23922 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
23923 				    ll_hdr_len);
23924 				xmit_mp = mp;
23925 
23926 			/*
23927 			 * Case of res_mp OR the fastpath mp can't fit
23928 			 * in the mblk
23929 			 */
23930 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
23931 				xmit_mp->b_cont = mp;
23932 				if (DB_CRED(mp) != NULL)
23933 					mblk_setcred(xmit_mp, DB_CRED(mp));
23934 				/* Get priority marking, if any. */
23935 				if (DB_TYPE(xmit_mp) == M_DATA)
23936 					xmit_mp->b_band = mp->b_band;
23937 
23938 			/* Corner case if copyb failed */
23939 			} else {
23940 				/*
23941 				 * Exit both the replication and
23942 				 * fragmentation loops.
23943 				 */
23944 				UNLOCK_IRE_FP_MP(ire);
23945 				goto drop_pkt;
23946 			}
23947 			UNLOCK_IRE_FP_MP(ire);
23948 			BUMP_MIB(&ip_mib, ipFragCreates);
23949 
23950 			mp1 = mp;
23951 			out_ill = (ill_t *)q->q_ptr;
23952 
23953 			DTRACE_PROBE4(ip4__physical__out__start,
23954 			    ill_t *, NULL, ill_t *, out_ill,
23955 			    ipha_t *, ipha, mblk_t *, xmit_mp);
23956 
23957 			FW_HOOKS(ip4_physical_out_event,
23958 			    ipv4firewall_physical_out,
23959 			    NULL, out_ill, ipha, xmit_mp, mp);
23960 
23961 			DTRACE_PROBE1(ip4__physical__out__end,
23962 			    mblk_t *, xmit_mp);
23963 
23964 			if (mp != mp1 && hdr_mp == mp1)
23965 				hdr_mp = mp;
23966 			if (mp != mp1 && mp_orig == mp1)
23967 				mp_orig = mp;
23968 
23969 			if (xmit_mp != NULL) {
23970 				putnext(q, xmit_mp);
23971 
23972 				if (pkt_type != OB_PKT) {
23973 					/*
23974 					 * Update the packet count of trailing
23975 					 * RTF_MULTIRT ires.
23976 					 */
23977 					UPDATE_OB_PKT_COUNT(ire);
23978 				}
23979 			}
23980 
23981 			/* All done if we just consumed the hdr_mp. */
23982 			if (mp == hdr_mp) {
23983 				last_frag = B_TRUE;
23984 			}
23985 
23986 			if (multirt_send) {
23987 				/*
23988 				 * We are in a multiple send case; look for
23989 				 * the next ire and re-enter the loop.
23990 				 */
23991 				ASSERT(ire1);
23992 				ASSERT(next_mp);
23993 				/* REFRELE the current ire before looping */
23994 				ire_refrele(ire);
23995 				ire = ire1;
23996 				ire1 = NULL;
23997 				q = ire->ire_stq;
23998 				mp = next_mp;
23999 				next_mp = NULL;
24000 			}
24001 		} while (multirt_send);
24002 		/*
24003 		 * Restore the original ire; we need it for the
24004 		 * trailing frags
24005 		 */
24006 		if (save_ire != NULL) {
24007 			ASSERT(ire1 == NULL);
24008 			/* REFRELE the last iterated ire */
24009 			ire_refrele(ire);
24010 			/* save_ire has been REFHOLDed */
24011 			ire = save_ire;
24012 			q = ire->ire_stq;
24013 			save_ire = NULL;
24014 		}
24015 
24016 		if (last_frag) {
24017 			BUMP_MIB(&ip_mib, ipFragOKs);
24018 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24019 			    "ip_wput_frag_end:(%S)",
24020 			    "consumed hdr_mp");
24021 
24022 			if (first_ire != NULL)
24023 				ire_refrele(first_ire);
24024 			return;
24025 		}
24026 		/* Otherwise, advance and loop. */
24027 		offset += len;
24028 	}
24029 
24030 drop_pkt:
24031 	/* Clean up following allocation failure. */
24032 	BUMP_MIB(&ip_mib, ipOutDiscards);
24033 	freemsg(mp);
24034 	if (mp != hdr_mp)
24035 		freeb(hdr_mp);
24036 	if (mp != mp_orig)
24037 		freemsg(mp_orig);
24038 
24039 	if (save_ire != NULL)
24040 		IRE_REFRELE(save_ire);
24041 	if (first_ire != NULL)
24042 		ire_refrele(first_ire);
24043 
24044 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24045 	    "ip_wput_frag_end:(%S)",
24046 	    "end--alloc failure");
24047 }
24048 
24049 /*
24050  * Copy the header plus those options which have the copy bit set
24051  */
24052 static mblk_t *
24053 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24054 {
24055 	mblk_t	*mp;
24056 	uchar_t	*up;
24057 
24058 	/*
24059 	 * Quick check if we need to look for options without the copy bit
24060 	 * set
24061 	 */
24062 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24063 	if (!mp)
24064 		return (mp);
24065 	mp->b_rptr += ip_wroff_extra;
24066 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24067 		bcopy(rptr, mp->b_rptr, hdr_len);
24068 		mp->b_wptr += hdr_len + ip_wroff_extra;
24069 		return (mp);
24070 	}
24071 	up  = mp->b_rptr;
24072 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24073 	up += IP_SIMPLE_HDR_LENGTH;
24074 	rptr += IP_SIMPLE_HDR_LENGTH;
24075 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24076 	while (hdr_len > 0) {
24077 		uint32_t optval;
24078 		uint32_t optlen;
24079 
24080 		optval = *rptr;
24081 		if (optval == IPOPT_EOL)
24082 			break;
24083 		if (optval == IPOPT_NOP)
24084 			optlen = 1;
24085 		else
24086 			optlen = rptr[1];
24087 		if (optval & IPOPT_COPY) {
24088 			bcopy(rptr, up, optlen);
24089 			up += optlen;
24090 		}
24091 		rptr += optlen;
24092 		hdr_len -= optlen;
24093 	}
24094 	/*
24095 	 * Make sure that we drop an even number of words by filling
24096 	 * with EOL to the next word boundary.
24097 	 */
24098 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24099 	    hdr_len & 0x3; hdr_len++)
24100 		*up++ = IPOPT_EOL;
24101 	mp->b_wptr = up;
24102 	/* Update header length */
24103 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24104 	return (mp);
24105 }
24106 
24107 /*
24108  * Delivery to local recipients including fanout to multiple recipients.
24109  * Does not do checksumming of UDP/TCP.
24110  * Note: q should be the read side queue for either the ill or conn.
24111  * Note: rq should be the read side q for the lower (ill) stream.
24112  * We don't send packets to IPPF processing, thus the last argument
24113  * to all the fanout calls are B_FALSE.
24114  */
24115 void
24116 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24117     int fanout_flags, zoneid_t zoneid)
24118 {
24119 	uint32_t	protocol;
24120 	mblk_t		*first_mp;
24121 	boolean_t	mctl_present;
24122 	int		ire_type;
24123 #define	rptr	((uchar_t *)ipha)
24124 
24125 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24126 	    "ip_wput_local_start: q %p", q);
24127 
24128 	if (ire != NULL) {
24129 		ire_type = ire->ire_type;
24130 	} else {
24131 		/*
24132 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24133 		 * packet is not multicast, we can't tell the ire type.
24134 		 */
24135 		ASSERT(CLASSD(ipha->ipha_dst));
24136 		ire_type = IRE_BROADCAST;
24137 	}
24138 
24139 	first_mp = mp;
24140 	if (first_mp->b_datap->db_type == M_CTL) {
24141 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24142 		if (!io->ipsec_out_secure) {
24143 			/*
24144 			 * This ipsec_out_t was allocated in ip_wput
24145 			 * for multicast packets to store the ill_index.
24146 			 * As this is being delivered locally, we don't
24147 			 * need this anymore.
24148 			 */
24149 			mp = first_mp->b_cont;
24150 			freeb(first_mp);
24151 			first_mp = mp;
24152 			mctl_present = B_FALSE;
24153 		} else {
24154 			/*
24155 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24156 			 * security properties for the looped-back packet.
24157 			 */
24158 			mctl_present = B_TRUE;
24159 			mp = first_mp->b_cont;
24160 			ASSERT(mp != NULL);
24161 			ipsec_out_to_in(first_mp);
24162 		}
24163 	} else {
24164 		mctl_present = B_FALSE;
24165 	}
24166 
24167 	DTRACE_PROBE4(ip4__loopback__in__start,
24168 	    ill_t *, ill, ill_t *, NULL,
24169 	    ipha_t *, ipha, mblk_t *, first_mp);
24170 
24171 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24172 	    ill, NULL, ipha, first_mp, mp);
24173 
24174 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24175 
24176 	if (first_mp == NULL)
24177 		return;
24178 
24179 	loopback_packets++;
24180 
24181 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24182 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24183 	if (!IS_SIMPLE_IPH(ipha)) {
24184 		ip_wput_local_options(ipha);
24185 	}
24186 
24187 	protocol = ipha->ipha_protocol;
24188 	switch (protocol) {
24189 	case IPPROTO_ICMP: {
24190 		ire_t		*ire_zone;
24191 		ilm_t		*ilm;
24192 		mblk_t		*mp1;
24193 		zoneid_t	last_zoneid;
24194 
24195 		if (CLASSD(ipha->ipha_dst) &&
24196 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
24197 			ASSERT(ire_type == IRE_BROADCAST);
24198 			/*
24199 			 * In the multicast case, applications may have joined
24200 			 * the group from different zones, so we need to deliver
24201 			 * the packet to each of them. Loop through the
24202 			 * multicast memberships structures (ilm) on the receive
24203 			 * ill and send a copy of the packet up each matching
24204 			 * one. However, we don't do this for multicasts sent on
24205 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24206 			 * they must stay in the sender's zone.
24207 			 *
24208 			 * ilm_add_v6() ensures that ilms in the same zone are
24209 			 * contiguous in the ill_ilm list. We use this property
24210 			 * to avoid sending duplicates needed when two
24211 			 * applications in the same zone join the same group on
24212 			 * different logical interfaces: we ignore the ilm if
24213 			 * it's zoneid is the same as the last matching one.
24214 			 * In addition, the sending of the packet for
24215 			 * ire_zoneid is delayed until all of the other ilms
24216 			 * have been exhausted.
24217 			 */
24218 			last_zoneid = -1;
24219 			ILM_WALKER_HOLD(ill);
24220 			for (ilm = ill->ill_ilm; ilm != NULL;
24221 			    ilm = ilm->ilm_next) {
24222 				if ((ilm->ilm_flags & ILM_DELETED) ||
24223 				    ipha->ipha_dst != ilm->ilm_addr ||
24224 				    ilm->ilm_zoneid == last_zoneid ||
24225 				    ilm->ilm_zoneid == zoneid ||
24226 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24227 					continue;
24228 				mp1 = ip_copymsg(first_mp);
24229 				if (mp1 == NULL)
24230 					continue;
24231 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24232 				    mctl_present, B_FALSE, ill,
24233 				    ilm->ilm_zoneid);
24234 				last_zoneid = ilm->ilm_zoneid;
24235 			}
24236 			ILM_WALKER_RELE(ill);
24237 			/*
24238 			 * Loopback case: the sending endpoint has
24239 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24240 			 * dispatch the multicast packet to the sending zone.
24241 			 */
24242 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24243 				freemsg(first_mp);
24244 				return;
24245 			}
24246 		} else if (ire_type == IRE_BROADCAST) {
24247 			/*
24248 			 * In the broadcast case, there may be many zones
24249 			 * which need a copy of the packet delivered to them.
24250 			 * There is one IRE_BROADCAST per broadcast address
24251 			 * and per zone; we walk those using a helper function.
24252 			 * In addition, the sending of the packet for zoneid is
24253 			 * delayed until all of the other ires have been
24254 			 * processed.
24255 			 */
24256 			IRB_REFHOLD(ire->ire_bucket);
24257 			ire_zone = NULL;
24258 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24259 			    ire)) != NULL) {
24260 				mp1 = ip_copymsg(first_mp);
24261 				if (mp1 == NULL)
24262 					continue;
24263 
24264 				UPDATE_IB_PKT_COUNT(ire_zone);
24265 				ire_zone->ire_last_used_time = lbolt;
24266 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24267 				    mctl_present, B_FALSE, ill,
24268 				    ire_zone->ire_zoneid);
24269 			}
24270 			IRB_REFRELE(ire->ire_bucket);
24271 		}
24272 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24273 		    0, mctl_present, B_FALSE, ill, zoneid);
24274 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24275 		    "ip_wput_local_end: q %p (%S)",
24276 		    q, "icmp");
24277 		return;
24278 	}
24279 	case IPPROTO_IGMP:
24280 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24281 			/* Bad packet - discarded by igmp_input */
24282 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24283 			    "ip_wput_local_end: q %p (%S)",
24284 			    q, "igmp_input--bad packet");
24285 			if (mctl_present)
24286 				freeb(first_mp);
24287 			return;
24288 		}
24289 		/*
24290 		 * igmp_input() may have returned the pulled up message.
24291 		 * So first_mp and ipha need to be reinitialized.
24292 		 */
24293 		ipha = (ipha_t *)mp->b_rptr;
24294 		if (mctl_present)
24295 			first_mp->b_cont = mp;
24296 		else
24297 			first_mp = mp;
24298 		/* deliver to local raw users */
24299 		break;
24300 	case IPPROTO_ENCAP:
24301 		/*
24302 		 * This case is covered by either ip_fanout_proto, or by
24303 		 * the above security processing for self-tunneled packets.
24304 		 */
24305 		break;
24306 	case IPPROTO_UDP: {
24307 		uint16_t	*up;
24308 		uint32_t	ports;
24309 
24310 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24311 		    UDP_PORTS_OFFSET);
24312 		/* Force a 'valid' checksum. */
24313 		up[3] = 0;
24314 
24315 		ports = *(uint32_t *)up;
24316 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24317 		    (ire_type == IRE_BROADCAST),
24318 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24319 		    IP_FF_SEND_SLLA | IP_FF_IP6INFO, mctl_present, B_FALSE,
24320 		    ill, zoneid);
24321 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24322 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24323 		return;
24324 	}
24325 	case IPPROTO_TCP: {
24326 
24327 		/*
24328 		 * For TCP, discard broadcast packets.
24329 		 */
24330 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24331 			freemsg(first_mp);
24332 			BUMP_MIB(&ip_mib, ipInDiscards);
24333 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24334 			return;
24335 		}
24336 
24337 		if (mp->b_datap->db_type == M_DATA) {
24338 			/*
24339 			 * M_DATA mblk, so init mblk (chain) for no struio().
24340 			 */
24341 			mblk_t	*mp1 = mp;
24342 
24343 			do
24344 				mp1->b_datap->db_struioflag = 0;
24345 			while ((mp1 = mp1->b_cont) != NULL);
24346 		}
24347 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24348 		    <= mp->b_wptr);
24349 		ip_fanout_tcp(q, first_mp, ill, ipha,
24350 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24351 		    IP_FF_SYN_ADDIRE | IP_FF_IP6INFO,
24352 		    mctl_present, B_FALSE, zoneid);
24353 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24354 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24355 		return;
24356 	}
24357 	case IPPROTO_SCTP:
24358 	{
24359 		uint32_t	ports;
24360 
24361 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24362 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24363 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24364 		    IP_FF_IP6INFO,
24365 		    mctl_present, B_FALSE, 0, zoneid);
24366 		return;
24367 	}
24368 
24369 	default:
24370 		break;
24371 	}
24372 	/*
24373 	 * Find a client for some other protocol.  We give
24374 	 * copies to multiple clients, if more than one is
24375 	 * bound.
24376 	 */
24377 	ip_fanout_proto(q, first_mp, ill, ipha,
24378 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24379 	    mctl_present, B_FALSE, ill, zoneid);
24380 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24381 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24382 #undef	rptr
24383 }
24384 
24385 /*
24386  * Update any source route, record route, or timestamp options.
24387  * Check that we are at end of strict source route.
24388  * The options have been sanity checked by ip_wput_options().
24389  */
24390 static void
24391 ip_wput_local_options(ipha_t *ipha)
24392 {
24393 	ipoptp_t	opts;
24394 	uchar_t		*opt;
24395 	uint8_t		optval;
24396 	uint8_t		optlen;
24397 	ipaddr_t	dst;
24398 	uint32_t	ts;
24399 	ire_t		*ire;
24400 	timestruc_t	now;
24401 
24402 	ip2dbg(("ip_wput_local_options\n"));
24403 	for (optval = ipoptp_first(&opts, ipha);
24404 	    optval != IPOPT_EOL;
24405 	    optval = ipoptp_next(&opts)) {
24406 		opt = opts.ipoptp_cur;
24407 		optlen = opts.ipoptp_len;
24408 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24409 		switch (optval) {
24410 			uint32_t off;
24411 		case IPOPT_SSRR:
24412 		case IPOPT_LSRR:
24413 			off = opt[IPOPT_OFFSET];
24414 			off--;
24415 			if (optlen < IP_ADDR_LEN ||
24416 			    off > optlen - IP_ADDR_LEN) {
24417 				/* End of source route */
24418 				break;
24419 			}
24420 			/*
24421 			 * This will only happen if two consecutive entries
24422 			 * in the source route contains our address or if
24423 			 * it is a packet with a loose source route which
24424 			 * reaches us before consuming the whole source route
24425 			 */
24426 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24427 			if (optval == IPOPT_SSRR) {
24428 				return;
24429 			}
24430 			/*
24431 			 * Hack: instead of dropping the packet truncate the
24432 			 * source route to what has been used by filling the
24433 			 * rest with IPOPT_NOP.
24434 			 */
24435 			opt[IPOPT_OLEN] = (uint8_t)off;
24436 			while (off < optlen) {
24437 				opt[off++] = IPOPT_NOP;
24438 			}
24439 			break;
24440 		case IPOPT_RR:
24441 			off = opt[IPOPT_OFFSET];
24442 			off--;
24443 			if (optlen < IP_ADDR_LEN ||
24444 			    off > optlen - IP_ADDR_LEN) {
24445 				/* No more room - ignore */
24446 				ip1dbg((
24447 				    "ip_wput_forward_options: end of RR\n"));
24448 				break;
24449 			}
24450 			dst = htonl(INADDR_LOOPBACK);
24451 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24452 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24453 			break;
24454 		case IPOPT_TS:
24455 			/* Insert timestamp if there is romm */
24456 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24457 			case IPOPT_TS_TSONLY:
24458 				off = IPOPT_TS_TIMELEN;
24459 				break;
24460 			case IPOPT_TS_PRESPEC:
24461 			case IPOPT_TS_PRESPEC_RFC791:
24462 				/* Verify that the address matched */
24463 				off = opt[IPOPT_OFFSET] - 1;
24464 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
24465 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
24466 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
24467 				if (ire == NULL) {
24468 					/* Not for us */
24469 					break;
24470 				}
24471 				ire_refrele(ire);
24472 				/* FALLTHRU */
24473 			case IPOPT_TS_TSANDADDR:
24474 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
24475 				break;
24476 			default:
24477 				/*
24478 				 * ip_*put_options should have already
24479 				 * dropped this packet.
24480 				 */
24481 				cmn_err(CE_PANIC, "ip_wput_local_options: "
24482 				    "unknown IT - bug in ip_wput_options?\n");
24483 				return;	/* Keep "lint" happy */
24484 			}
24485 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
24486 				/* Increase overflow counter */
24487 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
24488 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
24489 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
24490 				    (off << 4);
24491 				break;
24492 			}
24493 			off = opt[IPOPT_OFFSET] - 1;
24494 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
24495 			case IPOPT_TS_PRESPEC:
24496 			case IPOPT_TS_PRESPEC_RFC791:
24497 			case IPOPT_TS_TSANDADDR:
24498 				dst = htonl(INADDR_LOOPBACK);
24499 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
24500 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
24501 				/* FALLTHRU */
24502 			case IPOPT_TS_TSONLY:
24503 				off = opt[IPOPT_OFFSET] - 1;
24504 				/* Compute # of milliseconds since midnight */
24505 				gethrestime(&now);
24506 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
24507 				    now.tv_nsec / (NANOSEC / MILLISEC);
24508 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
24509 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
24510 				break;
24511 			}
24512 			break;
24513 		}
24514 	}
24515 }
24516 
24517 /*
24518  * Send out a multicast packet on interface ipif.
24519  * The sender does not have an conn.
24520  * Caller verifies that this isn't a PHYI_LOOPBACK.
24521  */
24522 void
24523 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
24524 {
24525 	ipha_t	*ipha;
24526 	ire_t	*ire;
24527 	ipaddr_t	dst;
24528 	mblk_t		*first_mp;
24529 
24530 	/* igmp_sendpkt always allocates a ipsec_out_t */
24531 	ASSERT(mp->b_datap->db_type == M_CTL);
24532 	ASSERT(!ipif->ipif_isv6);
24533 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
24534 
24535 	first_mp = mp;
24536 	mp = first_mp->b_cont;
24537 	ASSERT(mp->b_datap->db_type == M_DATA);
24538 	ipha = (ipha_t *)mp->b_rptr;
24539 
24540 	/*
24541 	 * Find an IRE which matches the destination and the outgoing
24542 	 * queue (i.e. the outgoing interface.)
24543 	 */
24544 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
24545 		dst = ipif->ipif_pp_dst_addr;
24546 	else
24547 		dst = ipha->ipha_dst;
24548 	/*
24549 	 * The source address has already been initialized by the
24550 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
24551 	 * be sufficient rather than MATCH_IRE_IPIF.
24552 	 *
24553 	 * This function is used for sending IGMP packets. We need
24554 	 * to make sure that we send the packet out of the interface
24555 	 * (ipif->ipif_ill) where we joined the group. This is to
24556 	 * prevent from switches doing IGMP snooping to send us multicast
24557 	 * packets for a given group on the interface we have joined.
24558 	 * If we can't find an ire, igmp_sendpkt has already initialized
24559 	 * ipsec_out_attach_if so that this will not be load spread in
24560 	 * ip_newroute_ipif.
24561 	 */
24562 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
24563 	    MATCH_IRE_ILL);
24564 	if (!ire) {
24565 		/*
24566 		 * Mark this packet to make it be delivered to
24567 		 * ip_wput_ire after the new ire has been
24568 		 * created.
24569 		 */
24570 		mp->b_prev = NULL;
24571 		mp->b_next = NULL;
24572 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
24573 		    zoneid);
24574 		return;
24575 	}
24576 
24577 	/*
24578 	 * Honor the RTF_SETSRC flag; this is the only case
24579 	 * where we force this addr whatever the current src addr is,
24580 	 * because this address is set by igmp_sendpkt(), and
24581 	 * cannot be specified by any user.
24582 	 */
24583 	if (ire->ire_flags & RTF_SETSRC) {
24584 		ipha->ipha_src = ire->ire_src_addr;
24585 	}
24586 
24587 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
24588 }
24589 
24590 /*
24591  * NOTE : This function does not ire_refrele the ire argument passed in.
24592  *
24593  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
24594  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
24595  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
24596  * the ire_lock to access the nce_fp_mp in this case.
24597  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
24598  * prepending a fastpath message IPQoS processing must precede it, we also set
24599  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
24600  * (IPQoS might have set the b_band for CoS marking).
24601  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
24602  * must follow it so that IPQoS can mark the dl_priority field for CoS
24603  * marking, if needed.
24604  */
24605 static mblk_t *
24606 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
24607 {
24608 	uint_t	hlen;
24609 	ipha_t *ipha;
24610 	mblk_t *mp1;
24611 	boolean_t qos_done = B_FALSE;
24612 	uchar_t	*ll_hdr;
24613 
24614 #define	rptr	((uchar_t *)ipha)
24615 
24616 	ipha = (ipha_t *)mp->b_rptr;
24617 	hlen = 0;
24618 	LOCK_IRE_FP_MP(ire);
24619 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
24620 		ASSERT(DB_TYPE(mp1) == M_DATA);
24621 		/* Initiate IPPF processing */
24622 		if ((proc != 0) && IPP_ENABLED(proc)) {
24623 			UNLOCK_IRE_FP_MP(ire);
24624 			ip_process(proc, &mp, ill_index);
24625 			if (mp == NULL)
24626 				return (NULL);
24627 
24628 			ipha = (ipha_t *)mp->b_rptr;
24629 			LOCK_IRE_FP_MP(ire);
24630 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
24631 				qos_done = B_TRUE;
24632 				goto no_fp_mp;
24633 			}
24634 			ASSERT(DB_TYPE(mp1) == M_DATA);
24635 		}
24636 		hlen = MBLKL(mp1);
24637 		/*
24638 		 * Check if we have enough room to prepend fastpath
24639 		 * header
24640 		 */
24641 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
24642 			ll_hdr = rptr - hlen;
24643 			bcopy(mp1->b_rptr, ll_hdr, hlen);
24644 			/*
24645 			 * Set the b_rptr to the start of the link layer
24646 			 * header
24647 			 */
24648 			mp->b_rptr = ll_hdr;
24649 			mp1 = mp;
24650 		} else {
24651 			mp1 = copyb(mp1);
24652 			if (mp1 == NULL)
24653 				goto unlock_err;
24654 			mp1->b_band = mp->b_band;
24655 			mp1->b_cont = mp;
24656 			/*
24657 			 * certain system generated traffic may not
24658 			 * have cred/label in ip header block. This
24659 			 * is true even for a labeled system. But for
24660 			 * labeled traffic, inherit the label in the
24661 			 * new header.
24662 			 */
24663 			if (DB_CRED(mp) != NULL)
24664 				mblk_setcred(mp1, DB_CRED(mp));
24665 			/*
24666 			 * XXX disable ICK_VALID and compute checksum
24667 			 * here; can happen if nce_fp_mp changes and
24668 			 * it can't be copied now due to insufficient
24669 			 * space. (unlikely, fp mp can change, but it
24670 			 * does not increase in length)
24671 			 */
24672 		}
24673 		UNLOCK_IRE_FP_MP(ire);
24674 	} else {
24675 no_fp_mp:
24676 		mp1 = copyb(ire->ire_nce->nce_res_mp);
24677 		if (mp1 == NULL) {
24678 unlock_err:
24679 			UNLOCK_IRE_FP_MP(ire);
24680 			freemsg(mp);
24681 			return (NULL);
24682 		}
24683 		UNLOCK_IRE_FP_MP(ire);
24684 		mp1->b_cont = mp;
24685 		/*
24686 		 * certain system generated traffic may not
24687 		 * have cred/label in ip header block. This
24688 		 * is true even for a labeled system. But for
24689 		 * labeled traffic, inherit the label in the
24690 		 * new header.
24691 		 */
24692 		if (DB_CRED(mp) != NULL)
24693 			mblk_setcred(mp1, DB_CRED(mp));
24694 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
24695 			ip_process(proc, &mp1, ill_index);
24696 			if (mp1 == NULL)
24697 				return (NULL);
24698 		}
24699 	}
24700 	return (mp1);
24701 #undef rptr
24702 }
24703 
24704 /*
24705  * Finish the outbound IPsec processing for an IPv6 packet. This function
24706  * is called from ipsec_out_process() if the IPsec packet was processed
24707  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
24708  * asynchronously.
24709  */
24710 void
24711 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
24712     ire_t *ire_arg)
24713 {
24714 	in6_addr_t *v6dstp;
24715 	ire_t *ire;
24716 	mblk_t *mp;
24717 	ip6_t *ip6h1;
24718 	uint_t	ill_index;
24719 	ipsec_out_t *io;
24720 	boolean_t attach_if, hwaccel;
24721 	uint32_t flags = IP6_NO_IPPOLICY;
24722 	int match_flags;
24723 	zoneid_t zoneid;
24724 	boolean_t ill_need_rele = B_FALSE;
24725 	boolean_t ire_need_rele = B_FALSE;
24726 
24727 	mp = ipsec_mp->b_cont;
24728 	ip6h1 = (ip6_t *)mp->b_rptr;
24729 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
24730 	ill_index = io->ipsec_out_ill_index;
24731 	if (io->ipsec_out_reachable) {
24732 		flags |= IPV6_REACHABILITY_CONFIRMATION;
24733 	}
24734 	attach_if = io->ipsec_out_attach_if;
24735 	hwaccel = io->ipsec_out_accelerated;
24736 	zoneid = io->ipsec_out_zoneid;
24737 	ASSERT(zoneid != ALL_ZONES);
24738 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
24739 	/* Multicast addresses should have non-zero ill_index. */
24740 	v6dstp = &ip6h->ip6_dst;
24741 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
24742 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
24743 	ASSERT(!attach_if || ill_index != 0);
24744 	if (ill_index != 0) {
24745 		if (ill == NULL) {
24746 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
24747 			    B_TRUE);
24748 
24749 			/* Failure case frees things for us. */
24750 			if (ill == NULL)
24751 				return;
24752 
24753 			ill_need_rele = B_TRUE;
24754 		}
24755 		/*
24756 		 * If this packet needs to go out on a particular interface
24757 		 * honor it.
24758 		 */
24759 		if (attach_if) {
24760 			match_flags = MATCH_IRE_ILL;
24761 
24762 			/*
24763 			 * Check if we need an ire that will not be
24764 			 * looked up by anybody else i.e. HIDDEN.
24765 			 */
24766 			if (ill_is_probeonly(ill)) {
24767 				match_flags |= MATCH_IRE_MARK_HIDDEN;
24768 			}
24769 		}
24770 	}
24771 	ASSERT(mp != NULL);
24772 
24773 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
24774 		boolean_t unspec_src;
24775 		ipif_t	*ipif;
24776 
24777 		/*
24778 		 * Use the ill_index to get the right ill.
24779 		 */
24780 		unspec_src = io->ipsec_out_unspec_src;
24781 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
24782 		if (ipif == NULL) {
24783 			if (ill_need_rele)
24784 				ill_refrele(ill);
24785 			freemsg(ipsec_mp);
24786 			return;
24787 		}
24788 
24789 		if (ire_arg != NULL) {
24790 			ire = ire_arg;
24791 		} else {
24792 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24793 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24794 			ire_need_rele = B_TRUE;
24795 		}
24796 		if (ire != NULL) {
24797 			ipif_refrele(ipif);
24798 			/*
24799 			 * XXX Do the multicast forwarding now, as the IPSEC
24800 			 * processing has been done.
24801 			 */
24802 			goto send;
24803 		}
24804 
24805 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
24806 		mp->b_prev = NULL;
24807 		mp->b_next = NULL;
24808 
24809 		/*
24810 		 * If the IPsec packet was processed asynchronously,
24811 		 * drop it now.
24812 		 */
24813 		if (q == NULL) {
24814 			if (ill_need_rele)
24815 				ill_refrele(ill);
24816 			freemsg(ipsec_mp);
24817 			return;
24818 		}
24819 
24820 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
24821 		    unspec_src, zoneid);
24822 		ipif_refrele(ipif);
24823 	} else {
24824 		if (attach_if) {
24825 			ipif_t	*ipif;
24826 
24827 			ipif = ipif_get_next_ipif(NULL, ill);
24828 			if (ipif == NULL) {
24829 				if (ill_need_rele)
24830 					ill_refrele(ill);
24831 				freemsg(ipsec_mp);
24832 				return;
24833 			}
24834 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
24835 			    zoneid, MBLK_GETLABEL(mp), match_flags);
24836 			ire_need_rele = B_TRUE;
24837 			ipif_refrele(ipif);
24838 		} else {
24839 			if (ire_arg != NULL) {
24840 				ire = ire_arg;
24841 			} else {
24842 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
24843 				ire_need_rele = B_TRUE;
24844 			}
24845 		}
24846 		if (ire != NULL)
24847 			goto send;
24848 		/*
24849 		 * ire disappeared underneath.
24850 		 *
24851 		 * What we need to do here is the ip_newroute
24852 		 * logic to get the ire without doing the IPSEC
24853 		 * processing. Follow the same old path. But this
24854 		 * time, ip_wput or ire_add_then_send will call us
24855 		 * directly as all the IPSEC operations are done.
24856 		 */
24857 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
24858 		mp->b_prev = NULL;
24859 		mp->b_next = NULL;
24860 
24861 		/*
24862 		 * If the IPsec packet was processed asynchronously,
24863 		 * drop it now.
24864 		 */
24865 		if (q == NULL) {
24866 			if (ill_need_rele)
24867 				ill_refrele(ill);
24868 			freemsg(ipsec_mp);
24869 			return;
24870 		}
24871 
24872 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
24873 		    zoneid);
24874 	}
24875 	if (ill != NULL && ill_need_rele)
24876 		ill_refrele(ill);
24877 	return;
24878 send:
24879 	if (ill != NULL && ill_need_rele)
24880 		ill_refrele(ill);
24881 
24882 	/* Local delivery */
24883 	if (ire->ire_stq == NULL) {
24884 		ill_t	*out_ill;
24885 		ASSERT(q != NULL);
24886 
24887 		/* PFHooks: LOOPBACK_OUT */
24888 		out_ill = ire->ire_ipif->ipif_ill;
24889 
24890 		DTRACE_PROBE4(ip6__loopback__out__start,
24891 		    ill_t *, NULL, ill_t *, out_ill,
24892 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
24893 
24894 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
24895 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
24896 
24897 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
24898 
24899 		if (ipsec_mp != NULL)
24900 			ip_wput_local_v6(RD(q), out_ill,
24901 			    ip6h, ipsec_mp, ire, 0);
24902 		if (ire_need_rele)
24903 			ire_refrele(ire);
24904 		return;
24905 	}
24906 	/*
24907 	 * Everything is done. Send it out on the wire.
24908 	 * We force the insertion of a fragment header using the
24909 	 * IPH_FRAG_HDR flag in two cases:
24910 	 * - after reception of an ICMPv6 "packet too big" message
24911 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
24912 	 * - for multirouted IPv6 packets, so that the receiver can
24913 	 *   discard duplicates according to their fragment identifier
24914 	 */
24915 	/* XXX fix flow control problems. */
24916 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
24917 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
24918 		if (hwaccel) {
24919 			/*
24920 			 * hardware acceleration does not handle these
24921 			 * "slow path" cases.
24922 			 */
24923 			/* IPsec KSTATS: should bump bean counter here. */
24924 			if (ire_need_rele)
24925 				ire_refrele(ire);
24926 			freemsg(ipsec_mp);
24927 			return;
24928 		}
24929 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
24930 		    (mp->b_cont ? msgdsize(mp) :
24931 		    mp->b_wptr - (uchar_t *)ip6h)) {
24932 			/* IPsec KSTATS: should bump bean counter here. */
24933 			ip0dbg(("Packet length mismatch: %d, %ld\n",
24934 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
24935 			    msgdsize(mp)));
24936 			if (ire_need_rele)
24937 				ire_refrele(ire);
24938 			freemsg(ipsec_mp);
24939 			return;
24940 		}
24941 		ASSERT(mp->b_prev == NULL);
24942 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
24943 		    ntohs(ip6h->ip6_plen) +
24944 		    IPV6_HDR_LEN, ire->ire_max_frag));
24945 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
24946 		    ire->ire_max_frag);
24947 	} else {
24948 		UPDATE_OB_PKT_COUNT(ire);
24949 		ire->ire_last_used_time = lbolt;
24950 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
24951 	}
24952 	if (ire_need_rele)
24953 		ire_refrele(ire);
24954 	freeb(ipsec_mp);
24955 }
24956 
24957 void
24958 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
24959 {
24960 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
24961 	da_ipsec_t *hada;	/* data attributes */
24962 	ill_t *ill = (ill_t *)q->q_ptr;
24963 
24964 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
24965 
24966 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
24967 		/* IPsec KSTATS: Bump lose counter here! */
24968 		freemsg(mp);
24969 		return;
24970 	}
24971 
24972 	/*
24973 	 * It's an IPsec packet that must be
24974 	 * accelerated by the Provider, and the
24975 	 * outbound ill is IPsec acceleration capable.
24976 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
24977 	 * to the ill.
24978 	 * IPsec KSTATS: should bump packet counter here.
24979 	 */
24980 
24981 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
24982 	if (hada_mp == NULL) {
24983 		/* IPsec KSTATS: should bump packet counter here. */
24984 		freemsg(mp);
24985 		return;
24986 	}
24987 
24988 	hada_mp->b_datap->db_type = M_CTL;
24989 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
24990 	hada_mp->b_cont = mp;
24991 
24992 	hada = (da_ipsec_t *)hada_mp->b_rptr;
24993 	bzero(hada, sizeof (da_ipsec_t));
24994 	hada->da_type = IPHADA_M_CTL;
24995 
24996 	putnext(q, hada_mp);
24997 }
24998 
24999 /*
25000  * Finish the outbound IPsec processing. This function is called from
25001  * ipsec_out_process() if the IPsec packet was processed
25002  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25003  * asynchronously.
25004  */
25005 void
25006 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25007     ire_t *ire_arg)
25008 {
25009 	uint32_t v_hlen_tos_len;
25010 	ipaddr_t	dst;
25011 	ipif_t	*ipif = NULL;
25012 	ire_t *ire;
25013 	ire_t *ire1 = NULL;
25014 	mblk_t *next_mp = NULL;
25015 	uint32_t max_frag;
25016 	boolean_t multirt_send = B_FALSE;
25017 	mblk_t *mp;
25018 	mblk_t *mp1;
25019 	ipha_t *ipha1;
25020 	uint_t	ill_index;
25021 	ipsec_out_t *io;
25022 	boolean_t attach_if;
25023 	int match_flags, offset;
25024 	irb_t *irb = NULL;
25025 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25026 	zoneid_t zoneid;
25027 	uint32_t cksum;
25028 	uint16_t *up;
25029 	ipxmit_state_t	pktxmit_state;
25030 #ifdef	_BIG_ENDIAN
25031 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25032 #else
25033 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25034 #endif
25035 
25036 	mp = ipsec_mp->b_cont;
25037 	ipha1 = (ipha_t *)mp->b_rptr;
25038 	ASSERT(mp != NULL);
25039 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25040 	dst = ipha->ipha_dst;
25041 
25042 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25043 	ill_index = io->ipsec_out_ill_index;
25044 	attach_if = io->ipsec_out_attach_if;
25045 	zoneid = io->ipsec_out_zoneid;
25046 	ASSERT(zoneid != ALL_ZONES);
25047 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25048 	if (ill_index != 0) {
25049 		if (ill == NULL) {
25050 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25051 			    ill_index, B_FALSE);
25052 
25053 			/* Failure case frees things for us. */
25054 			if (ill == NULL)
25055 				return;
25056 
25057 			ill_need_rele = B_TRUE;
25058 		}
25059 		/*
25060 		 * If this packet needs to go out on a particular interface
25061 		 * honor it.
25062 		 */
25063 		if (attach_if) {
25064 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25065 
25066 			/*
25067 			 * Check if we need an ire that will not be
25068 			 * looked up by anybody else i.e. HIDDEN.
25069 			 */
25070 			if (ill_is_probeonly(ill)) {
25071 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25072 			}
25073 		}
25074 	}
25075 
25076 	if (CLASSD(dst)) {
25077 		boolean_t conn_dontroute;
25078 		/*
25079 		 * Use the ill_index to get the right ipif.
25080 		 */
25081 		conn_dontroute = io->ipsec_out_dontroute;
25082 		if (ill_index == 0)
25083 			ipif = ipif_lookup_group(dst, zoneid);
25084 		else
25085 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25086 		if (ipif == NULL) {
25087 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25088 			    " multicast\n"));
25089 			BUMP_MIB(&ip_mib, ipOutNoRoutes);
25090 			freemsg(ipsec_mp);
25091 			goto done;
25092 		}
25093 		/*
25094 		 * ipha_src has already been intialized with the
25095 		 * value of the ipif in ip_wput. All we need now is
25096 		 * an ire to send this downstream.
25097 		 */
25098 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25099 		    MBLK_GETLABEL(mp), match_flags);
25100 		if (ire != NULL) {
25101 			ill_t *ill1;
25102 			/*
25103 			 * Do the multicast forwarding now, as the IPSEC
25104 			 * processing has been done.
25105 			 */
25106 			if (ip_g_mrouter && !conn_dontroute &&
25107 			    (ill1 = ire_to_ill(ire))) {
25108 				if (ip_mforward(ill1, ipha, mp)) {
25109 					freemsg(ipsec_mp);
25110 					ip1dbg(("ip_wput_ipsec_out: mforward "
25111 					    "failed\n"));
25112 					ire_refrele(ire);
25113 					goto done;
25114 				}
25115 			}
25116 			goto send;
25117 		}
25118 
25119 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25120 		mp->b_prev = NULL;
25121 		mp->b_next = NULL;
25122 
25123 		/*
25124 		 * If the IPsec packet was processed asynchronously,
25125 		 * drop it now.
25126 		 */
25127 		if (q == NULL) {
25128 			freemsg(ipsec_mp);
25129 			goto done;
25130 		}
25131 
25132 		/*
25133 		 * We may be using a wrong ipif to create the ire.
25134 		 * But it is okay as the source address is assigned
25135 		 * for the packet already. Next outbound packet would
25136 		 * create the IRE with the right IPIF in ip_wput.
25137 		 *
25138 		 * Also handle RTF_MULTIRT routes.
25139 		 */
25140 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25141 		    zoneid);
25142 	} else {
25143 		if (attach_if) {
25144 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25145 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25146 		} else {
25147 			if (ire_arg != NULL) {
25148 				ire = ire_arg;
25149 				ire_need_rele = B_FALSE;
25150 			} else {
25151 				ire = ire_cache_lookup(dst, zoneid,
25152 				    MBLK_GETLABEL(mp));
25153 			}
25154 		}
25155 		if (ire != NULL) {
25156 			goto send;
25157 		}
25158 
25159 		/*
25160 		 * ire disappeared underneath.
25161 		 *
25162 		 * What we need to do here is the ip_newroute
25163 		 * logic to get the ire without doing the IPSEC
25164 		 * processing. Follow the same old path. But this
25165 		 * time, ip_wput or ire_add_then_put will call us
25166 		 * directly as all the IPSEC operations are done.
25167 		 */
25168 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25169 		mp->b_prev = NULL;
25170 		mp->b_next = NULL;
25171 
25172 		/*
25173 		 * If the IPsec packet was processed asynchronously,
25174 		 * drop it now.
25175 		 */
25176 		if (q == NULL) {
25177 			freemsg(ipsec_mp);
25178 			goto done;
25179 		}
25180 
25181 		/*
25182 		 * Since we're going through ip_newroute() again, we
25183 		 * need to make sure we don't:
25184 		 *
25185 		 *	1.) Trigger the ASSERT() with the ipha_ident
25186 		 *	    overloading.
25187 		 *	2.) Redo transport-layer checksumming, since we've
25188 		 *	    already done all that to get this far.
25189 		 *
25190 		 * The easiest way not do either of the above is to set
25191 		 * the ipha_ident field to IP_HDR_INCLUDED.
25192 		 */
25193 		ipha->ipha_ident = IP_HDR_INCLUDED;
25194 		ip_newroute(q, ipsec_mp, dst, NULL,
25195 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
25196 	}
25197 	goto done;
25198 send:
25199 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
25200 		/*
25201 		 * ESP NAT-Traversal packet.
25202 		 *
25203 		 * Just do software checksum for now.
25204 		 */
25205 
25206 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25207 		IP_STAT(ip_out_sw_cksum);
25208 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
25209 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25210 #define	iphs	((uint16_t *)ipha)
25211 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25212 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25213 		    IP_SIMPLE_HDR_LENGTH);
25214 #undef iphs
25215 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
25216 			cksum = 0xFFFF;
25217 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25218 			if (mp1->b_wptr - mp1->b_rptr >=
25219 			    offset + sizeof (uint16_t)) {
25220 				up = (uint16_t *)(mp1->b_rptr + offset);
25221 				*up = cksum;
25222 				break;	/* out of for loop */
25223 			} else {
25224 				offset -= (mp->b_wptr - mp->b_rptr);
25225 			}
25226 	} /* Otherwise, just keep the all-zero checksum. */
25227 
25228 	if (ire->ire_stq == NULL) {
25229 		ill_t	*out_ill;
25230 		/*
25231 		 * Loopbacks go through ip_wput_local except for one case.
25232 		 * We come here if we generate a icmp_frag_needed message
25233 		 * after IPSEC processing is over. When this function calls
25234 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25235 		 * icmp_frag_needed. The message generated comes back here
25236 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25237 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25238 		 * source address as it is usually set in ip_wput_ire. As
25239 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25240 		 * and we end up here. We can't enter ip_wput_ire once the
25241 		 * IPSEC processing is over and hence we need to do it here.
25242 		 */
25243 		ASSERT(q != NULL);
25244 		UPDATE_OB_PKT_COUNT(ire);
25245 		ire->ire_last_used_time = lbolt;
25246 		if (ipha->ipha_src == 0)
25247 			ipha->ipha_src = ire->ire_src_addr;
25248 
25249 		/* PFHooks: LOOPBACK_OUT */
25250 		out_ill = ire->ire_ipif->ipif_ill;
25251 
25252 		DTRACE_PROBE4(ip4__loopback__out__start,
25253 		    ill_t *, NULL, ill_t *, out_ill,
25254 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25255 
25256 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
25257 		    NULL, out_ill, ipha1, ipsec_mp, mp);
25258 
25259 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25260 
25261 		if (ipsec_mp != NULL)
25262 			ip_wput_local(RD(q), out_ill,
25263 			    ipha, ipsec_mp, ire, 0, zoneid);
25264 		if (ire_need_rele)
25265 			ire_refrele(ire);
25266 		goto done;
25267 	}
25268 
25269 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25270 		/*
25271 		 * We are through with IPSEC processing.
25272 		 * Fragment this and send it on the wire.
25273 		 */
25274 		if (io->ipsec_out_accelerated) {
25275 			/*
25276 			 * The packet has been accelerated but must
25277 			 * be fragmented. This should not happen
25278 			 * since AH and ESP must not accelerate
25279 			 * packets that need fragmentation, however
25280 			 * the configuration could have changed
25281 			 * since the AH or ESP processing.
25282 			 * Drop packet.
25283 			 * IPsec KSTATS: bump bean counter here.
25284 			 */
25285 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25286 			    "fragmented accelerated packet!\n"));
25287 			freemsg(ipsec_mp);
25288 		} else {
25289 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
25290 		}
25291 		if (ire_need_rele)
25292 			ire_refrele(ire);
25293 		goto done;
25294 	}
25295 
25296 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25297 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25298 	    (void *)ire->ire_ipif, (void *)ipif));
25299 
25300 	/*
25301 	 * Multiroute the secured packet, unless IPsec really
25302 	 * requires the packet to go out only through a particular
25303 	 * interface.
25304 	 */
25305 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25306 		ire_t *first_ire;
25307 		irb = ire->ire_bucket;
25308 		ASSERT(irb != NULL);
25309 		/*
25310 		 * This ire has been looked up as the one that
25311 		 * goes through the given ipif;
25312 		 * make sure we do not omit any other multiroute ire
25313 		 * that may be present in the bucket before this one.
25314 		 */
25315 		IRB_REFHOLD(irb);
25316 		for (first_ire = irb->irb_ire;
25317 		    first_ire != NULL;
25318 		    first_ire = first_ire->ire_next) {
25319 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25320 			    (first_ire->ire_addr == ire->ire_addr) &&
25321 			    !(first_ire->ire_marks &
25322 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
25323 				break;
25324 		}
25325 
25326 		if ((first_ire != NULL) && (first_ire != ire)) {
25327 			/*
25328 			 * Don't change the ire if the packet must
25329 			 * be fragmented if sent via this new one.
25330 			 */
25331 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25332 				IRE_REFHOLD(first_ire);
25333 				if (ire_need_rele)
25334 					ire_refrele(ire);
25335 				else
25336 					ire_need_rele = B_TRUE;
25337 				ire = first_ire;
25338 			}
25339 		}
25340 		IRB_REFRELE(irb);
25341 
25342 		multirt_send = B_TRUE;
25343 		max_frag = ire->ire_max_frag;
25344 	} else {
25345 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25346 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25347 			    "flag, attach_if %d\n", attach_if));
25348 		}
25349 	}
25350 
25351 	/*
25352 	 * In most cases, the emission loop below is entered only once.
25353 	 * Only in the case where the ire holds the RTF_MULTIRT
25354 	 * flag, we loop to process all RTF_MULTIRT ires in the
25355 	 * bucket, and send the packet through all crossed
25356 	 * RTF_MULTIRT routes.
25357 	 */
25358 	do {
25359 		if (multirt_send) {
25360 			/*
25361 			 * ire1 holds here the next ire to process in the
25362 			 * bucket. If multirouting is expected,
25363 			 * any non-RTF_MULTIRT ire that has the
25364 			 * right destination address is ignored.
25365 			 */
25366 			ASSERT(irb != NULL);
25367 			IRB_REFHOLD(irb);
25368 			for (ire1 = ire->ire_next;
25369 			    ire1 != NULL;
25370 			    ire1 = ire1->ire_next) {
25371 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25372 					continue;
25373 				if (ire1->ire_addr != ire->ire_addr)
25374 					continue;
25375 				if (ire1->ire_marks &
25376 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25377 					continue;
25378 				/* No loopback here */
25379 				if (ire1->ire_stq == NULL)
25380 					continue;
25381 				/*
25382 				 * Ensure we do not exceed the MTU
25383 				 * of the next route.
25384 				 */
25385 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25386 					ip_multirt_bad_mtu(ire1, max_frag);
25387 					continue;
25388 				}
25389 
25390 				IRE_REFHOLD(ire1);
25391 				break;
25392 			}
25393 			IRB_REFRELE(irb);
25394 			if (ire1 != NULL) {
25395 				/*
25396 				 * We are in a multiple send case, need to
25397 				 * make a copy of the packet.
25398 				 */
25399 				next_mp = copymsg(ipsec_mp);
25400 				if (next_mp == NULL) {
25401 					ire_refrele(ire1);
25402 					ire1 = NULL;
25403 				}
25404 			}
25405 		}
25406 		/*
25407 		 * Everything is done. Send it out on the wire
25408 		 *
25409 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25410 		 * either send it on the wire or, in the case of
25411 		 * HW acceleration, call ipsec_hw_putnext.
25412 		 */
25413 		if (ire->ire_nce &&
25414 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25415 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25416 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25417 			/*
25418 			 * If ire's link-layer is unresolved (this
25419 			 * would only happen if the incomplete ire
25420 			 * was added to cachetable via forwarding path)
25421 			 * don't bother going to ip_xmit_v4. Just drop the
25422 			 * packet.
25423 			 * There is a slight risk here, in that, if we
25424 			 * have the forwarding path create an incomplete
25425 			 * IRE, then until the IRE is completed, any
25426 			 * transmitted IPSEC packets will be dropped
25427 			 * instead of being queued waiting for resolution.
25428 			 *
25429 			 * But the likelihood of a forwarding packet and a wput
25430 			 * packet sending to the same dst at the same time
25431 			 * and there not yet be an ARP entry for it is small.
25432 			 * Furthermore, if this actually happens, it might
25433 			 * be likely that wput would generate multiple
25434 			 * packets (and forwarding would also have a train
25435 			 * of packets) for that destination. If this is
25436 			 * the case, some of them would have been dropped
25437 			 * anyway, since ARP only queues a few packets while
25438 			 * waiting for resolution
25439 			 *
25440 			 * NOTE: We should really call ip_xmit_v4,
25441 			 * and let it queue the packet and send the
25442 			 * ARP query and have ARP come back thus:
25443 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
25444 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
25445 			 * hw accel work. But it's too complex to get
25446 			 * the IPsec hw  acceleration approach to fit
25447 			 * well with ip_xmit_v4 doing ARP without
25448 			 * doing IPSEC simplification. For now, we just
25449 			 * poke ip_xmit_v4 to trigger the arp resolve, so
25450 			 * that we can continue with the send on the next
25451 			 * attempt.
25452 			 *
25453 			 * XXX THis should be revisited, when
25454 			 * the IPsec/IP interaction is cleaned up
25455 			 */
25456 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
25457 			    " - dropping packet\n"));
25458 			freemsg(ipsec_mp);
25459 			/*
25460 			 * Call ip_xmit_v4() to trigger ARP query
25461 			 * in case the nce_state is ND_INITIAL
25462 			 */
25463 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
25464 			goto drop_pkt;
25465 		}
25466 
25467 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
25468 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
25469 		    mblk_t *, mp);
25470 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
25471 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
25472 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
25473 		if (mp == NULL)
25474 			goto drop_pkt;
25475 
25476 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
25477 		pktxmit_state = ip_xmit_v4(mp, ire,
25478 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
25479 
25480 		if ((pktxmit_state ==  SEND_FAILED) ||
25481 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
25482 
25483 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
25484 drop_pkt:
25485 			BUMP_MIB(&ip_mib, ipOutDiscards);
25486 			if (ire_need_rele)
25487 				ire_refrele(ire);
25488 			if (ire1 != NULL) {
25489 				ire_refrele(ire1);
25490 				freemsg(next_mp);
25491 			}
25492 			goto done;
25493 		}
25494 
25495 		freeb(ipsec_mp);
25496 		if (ire_need_rele)
25497 			ire_refrele(ire);
25498 
25499 		if (ire1 != NULL) {
25500 			ire = ire1;
25501 			ire_need_rele = B_TRUE;
25502 			ASSERT(next_mp);
25503 			ipsec_mp = next_mp;
25504 			mp = ipsec_mp->b_cont;
25505 			ire1 = NULL;
25506 			next_mp = NULL;
25507 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
25508 		} else {
25509 			multirt_send = B_FALSE;
25510 		}
25511 	} while (multirt_send);
25512 done:
25513 	if (ill != NULL && ill_need_rele)
25514 		ill_refrele(ill);
25515 	if (ipif != NULL)
25516 		ipif_refrele(ipif);
25517 }
25518 
25519 /*
25520  * Get the ill corresponding to the specified ire, and compare its
25521  * capabilities with the protocol and algorithms specified by the
25522  * the SA obtained from ipsec_out. If they match, annotate the
25523  * ipsec_out structure to indicate that the packet needs acceleration.
25524  *
25525  *
25526  * A packet is eligible for outbound hardware acceleration if the
25527  * following conditions are satisfied:
25528  *
25529  * 1. the packet will not be fragmented
25530  * 2. the provider supports the algorithm
25531  * 3. there is no pending control message being exchanged
25532  * 4. snoop is not attached
25533  * 5. the destination address is not a broadcast or multicast address.
25534  *
25535  * Rationale:
25536  *	- Hardware drivers do not support fragmentation with
25537  *	  the current interface.
25538  *	- snoop, multicast, and broadcast may result in exposure of
25539  *	  a cleartext datagram.
25540  * We check all five of these conditions here.
25541  *
25542  * XXX would like to nuke "ire_t *" parameter here; problem is that
25543  * IRE is only way to figure out if a v4 address is a broadcast and
25544  * thus ineligible for acceleration...
25545  */
25546 static void
25547 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
25548 {
25549 	ipsec_out_t *io;
25550 	mblk_t *data_mp;
25551 	uint_t plen, overhead;
25552 
25553 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
25554 		return;
25555 
25556 	if (ill == NULL)
25557 		return;
25558 
25559 	/*
25560 	 * Destination address is a broadcast or multicast.  Punt.
25561 	 */
25562 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
25563 	    IRE_LOCAL)))
25564 		return;
25565 
25566 	data_mp = ipsec_mp->b_cont;
25567 
25568 	if (ill->ill_isv6) {
25569 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
25570 
25571 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
25572 			return;
25573 
25574 		plen = ip6h->ip6_plen;
25575 	} else {
25576 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
25577 
25578 		if (CLASSD(ipha->ipha_dst))
25579 			return;
25580 
25581 		plen = ipha->ipha_length;
25582 	}
25583 	/*
25584 	 * Is there a pending DLPI control message being exchanged
25585 	 * between IP/IPsec and the DLS Provider? If there is, it
25586 	 * could be a SADB update, and the state of the DLS Provider
25587 	 * SADB might not be in sync with the SADB maintained by
25588 	 * IPsec. To avoid dropping packets or using the wrong keying
25589 	 * material, we do not accelerate this packet.
25590 	 */
25591 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
25592 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25593 		    "ill_dlpi_pending! don't accelerate packet\n"));
25594 		return;
25595 	}
25596 
25597 	/*
25598 	 * Is the Provider in promiscous mode? If it does, we don't
25599 	 * accelerate the packet since it will bounce back up to the
25600 	 * listeners in the clear.
25601 	 */
25602 	if (ill->ill_promisc_on_phys) {
25603 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
25604 		    "ill in promiscous mode, don't accelerate packet\n"));
25605 		return;
25606 	}
25607 
25608 	/*
25609 	 * Will the packet require fragmentation?
25610 	 */
25611 
25612 	/*
25613 	 * IPsec ESP note: this is a pessimistic estimate, but the same
25614 	 * as is used elsewhere.
25615 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
25616 	 *	+ 2-byte trailer
25617 	 */
25618 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
25619 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
25620 
25621 	if ((plen + overhead) > ill->ill_max_mtu)
25622 		return;
25623 
25624 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25625 
25626 	/*
25627 	 * Can the ill accelerate this IPsec protocol and algorithm
25628 	 * specified by the SA?
25629 	 */
25630 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
25631 	    ill->ill_isv6, sa)) {
25632 		return;
25633 	}
25634 
25635 	/*
25636 	 * Tell AH or ESP that the outbound ill is capable of
25637 	 * accelerating this packet.
25638 	 */
25639 	io->ipsec_out_is_capab_ill = B_TRUE;
25640 }
25641 
25642 /*
25643  * Select which AH & ESP SA's to use (if any) for the outbound packet.
25644  *
25645  * If this function returns B_TRUE, the requested SA's have been filled
25646  * into the ipsec_out_*_sa pointers.
25647  *
25648  * If the function returns B_FALSE, the packet has been "consumed", most
25649  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
25650  *
25651  * The SA references created by the protocol-specific "select"
25652  * function will be released when the ipsec_mp is freed, thanks to the
25653  * ipsec_out_free destructor -- see spd.c.
25654  */
25655 static boolean_t
25656 ipsec_out_select_sa(mblk_t *ipsec_mp)
25657 {
25658 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
25659 	ipsec_out_t *io;
25660 	ipsec_policy_t *pp;
25661 	ipsec_action_t *ap;
25662 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25663 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25664 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25665 
25666 	if (!io->ipsec_out_secure) {
25667 		/*
25668 		 * We came here by mistake.
25669 		 * Don't bother with ipsec processing
25670 		 * We should "discourage" this path in the future.
25671 		 */
25672 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25673 		return (B_FALSE);
25674 	}
25675 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25676 	ASSERT((io->ipsec_out_policy != NULL) ||
25677 	    (io->ipsec_out_act != NULL));
25678 
25679 	ASSERT(io->ipsec_out_failed == B_FALSE);
25680 
25681 	/*
25682 	 * IPSEC processing has started.
25683 	 */
25684 	io->ipsec_out_proc_begin = B_TRUE;
25685 	ap = io->ipsec_out_act;
25686 	if (ap == NULL) {
25687 		pp = io->ipsec_out_policy;
25688 		ASSERT(pp != NULL);
25689 		ap = pp->ipsp_act;
25690 		ASSERT(ap != NULL);
25691 	}
25692 
25693 	/*
25694 	 * We have an action.  now, let's select SA's.
25695 	 * (In the future, we can cache this in the conn_t..)
25696 	 */
25697 	if (ap->ipa_want_esp) {
25698 		if (io->ipsec_out_esp_sa == NULL) {
25699 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
25700 			    IPPROTO_ESP);
25701 		}
25702 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
25703 	}
25704 
25705 	if (ap->ipa_want_ah) {
25706 		if (io->ipsec_out_ah_sa == NULL) {
25707 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
25708 			    IPPROTO_AH);
25709 		}
25710 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
25711 		/*
25712 		 * The ESP and AH processing order needs to be preserved
25713 		 * when both protocols are required (ESP should be applied
25714 		 * before AH for an outbound packet). Force an ESP ACQUIRE
25715 		 * when both ESP and AH are required, and an AH ACQUIRE
25716 		 * is needed.
25717 		 */
25718 		if (ap->ipa_want_esp && need_ah_acquire)
25719 			need_esp_acquire = B_TRUE;
25720 	}
25721 
25722 	/*
25723 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
25724 	 * Release SAs that got referenced, but will not be used until we
25725 	 * acquire _all_ of the SAs we need.
25726 	 */
25727 	if (need_ah_acquire || need_esp_acquire) {
25728 		if (io->ipsec_out_ah_sa != NULL) {
25729 			IPSA_REFRELE(io->ipsec_out_ah_sa);
25730 			io->ipsec_out_ah_sa = NULL;
25731 		}
25732 		if (io->ipsec_out_esp_sa != NULL) {
25733 			IPSA_REFRELE(io->ipsec_out_esp_sa);
25734 			io->ipsec_out_esp_sa = NULL;
25735 		}
25736 
25737 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
25738 		return (B_FALSE);
25739 	}
25740 
25741 	return (B_TRUE);
25742 }
25743 
25744 /*
25745  * Process an IPSEC_OUT message and see what you can
25746  * do with it.
25747  * IPQoS Notes:
25748  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
25749  * IPSec.
25750  * XXX would like to nuke ire_t.
25751  * XXX ill_index better be "real"
25752  */
25753 void
25754 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
25755 {
25756 	ipsec_out_t *io;
25757 	ipsec_policy_t *pp;
25758 	ipsec_action_t *ap;
25759 	ipha_t *ipha;
25760 	ip6_t *ip6h;
25761 	mblk_t *mp;
25762 	ill_t *ill;
25763 	zoneid_t zoneid;
25764 	ipsec_status_t ipsec_rc;
25765 	boolean_t ill_need_rele = B_FALSE;
25766 
25767 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25768 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
25769 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
25770 	mp = ipsec_mp->b_cont;
25771 
25772 	/*
25773 	 * Initiate IPPF processing. We do it here to account for packets
25774 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
25775 	 * We can check for ipsec_out_proc_begin even for such packets, as
25776 	 * they will always be false (asserted below).
25777 	 */
25778 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
25779 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
25780 		    io->ipsec_out_ill_index : ill_index);
25781 		if (mp == NULL) {
25782 			ip2dbg(("ipsec_out_process: packet dropped "\
25783 			    "during IPPF processing\n"));
25784 			freeb(ipsec_mp);
25785 			BUMP_MIB(&ip_mib, ipOutDiscards);
25786 			return;
25787 		}
25788 	}
25789 
25790 	if (!io->ipsec_out_secure) {
25791 		/*
25792 		 * We came here by mistake.
25793 		 * Don't bother with ipsec processing
25794 		 * Should "discourage" this path in the future.
25795 		 */
25796 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
25797 		goto done;
25798 	}
25799 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
25800 	ASSERT((io->ipsec_out_policy != NULL) ||
25801 	    (io->ipsec_out_act != NULL));
25802 	ASSERT(io->ipsec_out_failed == B_FALSE);
25803 
25804 	if (!ipsec_loaded()) {
25805 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
25806 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25807 			BUMP_MIB(&ip_mib, ipOutDiscards);
25808 		} else {
25809 			BUMP_MIB(&ip6_mib, ipv6OutDiscards);
25810 		}
25811 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
25812 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
25813 		return;
25814 	}
25815 
25816 	/*
25817 	 * IPSEC processing has started.
25818 	 */
25819 	io->ipsec_out_proc_begin = B_TRUE;
25820 	ap = io->ipsec_out_act;
25821 	if (ap == NULL) {
25822 		pp = io->ipsec_out_policy;
25823 		ASSERT(pp != NULL);
25824 		ap = pp->ipsp_act;
25825 		ASSERT(ap != NULL);
25826 	}
25827 
25828 	/*
25829 	 * Save the outbound ill index. When the packet comes back
25830 	 * from IPsec, we make sure the ill hasn't changed or disappeared
25831 	 * before sending it the accelerated packet.
25832 	 */
25833 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
25834 		int ifindex;
25835 		ill = ire_to_ill(ire);
25836 		ifindex = ill->ill_phyint->phyint_ifindex;
25837 		io->ipsec_out_capab_ill_index = ifindex;
25838 	}
25839 
25840 	/*
25841 	 * The order of processing is first insert a IP header if needed.
25842 	 * Then insert the ESP header and then the AH header.
25843 	 */
25844 	if ((io->ipsec_out_se_done == B_FALSE) &&
25845 	    (ap->ipa_want_se)) {
25846 		/*
25847 		 * First get the outer IP header before sending
25848 		 * it to ESP.
25849 		 */
25850 		ipha_t *oipha, *iipha;
25851 		mblk_t *outer_mp, *inner_mp;
25852 
25853 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
25854 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
25855 			    "ipsec_out_process: "
25856 			    "Self-Encapsulation failed: Out of memory\n");
25857 			freemsg(ipsec_mp);
25858 			BUMP_MIB(&ip_mib, ipOutDiscards);
25859 			return;
25860 		}
25861 		inner_mp = ipsec_mp->b_cont;
25862 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
25863 		oipha = (ipha_t *)outer_mp->b_rptr;
25864 		iipha = (ipha_t *)inner_mp->b_rptr;
25865 		*oipha = *iipha;
25866 		outer_mp->b_wptr += sizeof (ipha_t);
25867 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
25868 		    sizeof (ipha_t));
25869 		oipha->ipha_protocol = IPPROTO_ENCAP;
25870 		oipha->ipha_version_and_hdr_length =
25871 		    IP_SIMPLE_HDR_VERSION;
25872 		oipha->ipha_hdr_checksum = 0;
25873 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
25874 		outer_mp->b_cont = inner_mp;
25875 		ipsec_mp->b_cont = outer_mp;
25876 
25877 		io->ipsec_out_se_done = B_TRUE;
25878 		io->ipsec_out_tunnel = B_TRUE;
25879 	}
25880 
25881 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
25882 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
25883 	    !ipsec_out_select_sa(ipsec_mp))
25884 		return;
25885 
25886 	/*
25887 	 * By now, we know what SA's to use.  Toss over to ESP & AH
25888 	 * to do the heavy lifting.
25889 	 */
25890 	zoneid = io->ipsec_out_zoneid;
25891 	ASSERT(zoneid != ALL_ZONES);
25892 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
25893 		ASSERT(io->ipsec_out_esp_sa != NULL);
25894 		io->ipsec_out_esp_done = B_TRUE;
25895 		/*
25896 		 * Note that since hw accel can only apply one transform,
25897 		 * not two, we skip hw accel for ESP if we also have AH
25898 		 * This is an design limitation of the interface
25899 		 * which should be revisited.
25900 		 */
25901 		ASSERT(ire != NULL);
25902 		if (io->ipsec_out_ah_sa == NULL) {
25903 			ill = (ill_t *)ire->ire_stq->q_ptr;
25904 			ipsec_out_is_accelerated(ipsec_mp,
25905 			    io->ipsec_out_esp_sa, ill, ire);
25906 		}
25907 
25908 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
25909 		switch (ipsec_rc) {
25910 		case IPSEC_STATUS_SUCCESS:
25911 			break;
25912 		case IPSEC_STATUS_FAILED:
25913 			BUMP_MIB(&ip_mib, ipOutDiscards);
25914 			/* FALLTHRU */
25915 		case IPSEC_STATUS_PENDING:
25916 			return;
25917 		}
25918 	}
25919 
25920 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
25921 		ASSERT(io->ipsec_out_ah_sa != NULL);
25922 		io->ipsec_out_ah_done = B_TRUE;
25923 		if (ire == NULL) {
25924 			int idx = io->ipsec_out_capab_ill_index;
25925 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
25926 			    NULL, NULL, NULL, NULL);
25927 			ill_need_rele = B_TRUE;
25928 		} else {
25929 			ill = (ill_t *)ire->ire_stq->q_ptr;
25930 		}
25931 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
25932 		    ire);
25933 
25934 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
25935 		switch (ipsec_rc) {
25936 		case IPSEC_STATUS_SUCCESS:
25937 			break;
25938 		case IPSEC_STATUS_FAILED:
25939 			BUMP_MIB(&ip_mib, ipOutDiscards);
25940 			/* FALLTHRU */
25941 		case IPSEC_STATUS_PENDING:
25942 			if (ill != NULL && ill_need_rele)
25943 				ill_refrele(ill);
25944 			return;
25945 		}
25946 	}
25947 	/*
25948 	 * We are done with IPSEC processing. Send it over
25949 	 * the wire.
25950 	 */
25951 done:
25952 	mp = ipsec_mp->b_cont;
25953 	ipha = (ipha_t *)mp->b_rptr;
25954 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
25955 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
25956 	} else {
25957 		ip6h = (ip6_t *)ipha;
25958 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
25959 	}
25960 	if (ill != NULL && ill_need_rele)
25961 		ill_refrele(ill);
25962 }
25963 
25964 /* ARGSUSED */
25965 void
25966 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
25967 {
25968 	opt_restart_t	*or;
25969 	int	err;
25970 	conn_t	*connp;
25971 
25972 	ASSERT(CONN_Q(q));
25973 	connp = Q_TO_CONN(q);
25974 
25975 	ASSERT(first_mp->b_datap->db_type == M_CTL);
25976 	or = (opt_restart_t *)first_mp->b_rptr;
25977 	/*
25978 	 * We don't need to pass any credentials here since this is just
25979 	 * a restart. The credentials are passed in when svr4_optcom_req
25980 	 * is called the first time (from ip_wput_nondata).
25981 	 */
25982 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
25983 		err = svr4_optcom_req(q, first_mp, NULL,
25984 		    &ip_opt_obj);
25985 	} else {
25986 		ASSERT(or->or_type == T_OPTMGMT_REQ);
25987 		err = tpi_optcom_req(q, first_mp, NULL,
25988 		    &ip_opt_obj);
25989 	}
25990 	if (err != EINPROGRESS) {
25991 		/* operation is done */
25992 		CONN_OPER_PENDING_DONE(connp);
25993 	}
25994 }
25995 
25996 /*
25997  * ioctls that go through a down/up sequence may need to wait for the down
25998  * to complete. This involves waiting for the ire and ipif refcnts to go down
25999  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26000  */
26001 /* ARGSUSED */
26002 void
26003 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26004 {
26005 	struct iocblk *iocp;
26006 	mblk_t *mp1;
26007 	ipif_t	*ipif;
26008 	ip_ioctl_cmd_t *ipip;
26009 	int err;
26010 	sin_t	*sin;
26011 	struct lifreq *lifr;
26012 	struct ifreq *ifr;
26013 
26014 	iocp = (struct iocblk *)mp->b_rptr;
26015 	ASSERT(ipsq != NULL);
26016 	/* Existence of mp1 verified in ip_wput_nondata */
26017 	mp1 = mp->b_cont->b_cont;
26018 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26019 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26020 		ill_t *ill;
26021 		/*
26022 		 * Special case where ipsq_current_ipif may not be set.
26023 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26024 		 * ill could also have become part of a ipmp group in the
26025 		 * process, we are here as were not able to complete the
26026 		 * operation in ipif_set_values because we could not become
26027 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26028 		 * will not be set so we need to set it.
26029 		 */
26030 		ill = (ill_t *)q->q_ptr;
26031 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26032 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26033 	}
26034 
26035 	ipif = ipsq->ipsq_current_ipif;
26036 	ASSERT(ipif != NULL);
26037 	if (ipip->ipi_cmd_type == IF_CMD) {
26038 		/* This a old style SIOC[GS]IF* command */
26039 		ifr = (struct ifreq *)mp1->b_rptr;
26040 		sin = (sin_t *)&ifr->ifr_addr;
26041 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26042 		/* This a new style SIOC[GS]LIF* command */
26043 		lifr = (struct lifreq *)mp1->b_rptr;
26044 		sin = (sin_t *)&lifr->lifr_addr;
26045 	} else {
26046 		sin = NULL;
26047 	}
26048 
26049 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26050 	    (void *)mp1->b_rptr);
26051 
26052 	/* SIOCLIFREMOVEIF could have removed the ipif */
26053 	ip_ioctl_finish(q, mp, err,
26054 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26055 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26056 }
26057 
26058 /*
26059  * ioctl processing
26060  *
26061  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26062  * the ioctl command in the ioctl tables and determines the copyin data size
26063  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26064  * size.
26065  *
26066  * ioctl processing then continues when the M_IOCDATA makes its way down.
26067  * Now the ioctl is looked up again in the ioctl table, and its properties are
26068  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26069  * and the general ioctl processing function ip_process_ioctl is called.
26070  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26071  * so goes thru the serialization primitive ipsq_try_enter. Then the
26072  * appropriate function to handle the ioctl is called based on the entry in
26073  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26074  * which also refreleases the 'conn' that was refheld at the start of the
26075  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26076  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26077  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26078  *
26079  * Many exclusive ioctls go thru an internal down up sequence as part of
26080  * the operation. For example an attempt to change the IP address of an
26081  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26082  * does all the cleanup such as deleting all ires that use this address.
26083  * Then we need to wait till all references to the interface go away.
26084  */
26085 void
26086 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26087 {
26088 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26089 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26090 	cmd_info_t ci;
26091 	int err;
26092 	boolean_t entered_ipsq = B_FALSE;
26093 
26094 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26095 
26096 	if (ipip == NULL)
26097 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26098 
26099 	/*
26100 	 * SIOCLIFADDIF needs to go thru a special path since the
26101 	 * ill may not exist yet. This happens in the case of lo0
26102 	 * which is created using this ioctl.
26103 	 */
26104 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26105 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26106 		ip_ioctl_finish(q, mp, err,
26107 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26108 		    NULL, NULL);
26109 		return;
26110 	}
26111 
26112 	ci.ci_ipif = NULL;
26113 	switch (ipip->ipi_cmd_type) {
26114 	case IF_CMD:
26115 	case LIF_CMD:
26116 		/*
26117 		 * ioctls that pass in a [l]ifreq appear here.
26118 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26119 		 * ci.ci_ipif
26120 		 */
26121 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26122 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26123 		if (err != 0) {
26124 			ip_ioctl_finish(q, mp, err,
26125 			    ipip->ipi_flags & IPI_GET_CMD ?
26126 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26127 			return;
26128 		}
26129 		ASSERT(ci.ci_ipif != NULL);
26130 		break;
26131 
26132 	case TUN_CMD:
26133 		/*
26134 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26135 		 * a refheld ipif in ci.ci_ipif
26136 		 */
26137 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26138 		if (err != 0) {
26139 			ip_ioctl_finish(q, mp, err,
26140 			    ipip->ipi_flags & IPI_GET_CMD ?
26141 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26142 			return;
26143 		}
26144 		ASSERT(ci.ci_ipif != NULL);
26145 		break;
26146 
26147 	case MISC_CMD:
26148 		/*
26149 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26150 		 * For eg. SIOCGLIFCONF will appear here.
26151 		 */
26152 		switch (ipip->ipi_cmd) {
26153 		case IF_UNITSEL:
26154 			/* ioctl comes down the ill */
26155 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26156 			ipif_refhold(ci.ci_ipif);
26157 			break;
26158 		case SIOCGMSFILTER:
26159 		case SIOCSMSFILTER:
26160 		case SIOCGIPMSFILTER:
26161 		case SIOCSIPMSFILTER:
26162 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26163 			    ip_process_ioctl);
26164 			if (err != 0) {
26165 				ip_ioctl_finish(q, mp, err,
26166 				    ipip->ipi_flags & IPI_GET_CMD ?
26167 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26168 				return;
26169 			}
26170 			break;
26171 		}
26172 		err = 0;
26173 		ci.ci_sin = NULL;
26174 		ci.ci_sin6 = NULL;
26175 		ci.ci_lifr = NULL;
26176 		break;
26177 	}
26178 
26179 	/*
26180 	 * If ipsq is non-null, we are already being called exclusively
26181 	 */
26182 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26183 	if (!(ipip->ipi_flags & IPI_WR)) {
26184 		/*
26185 		 * A return value of EINPROGRESS means the ioctl is
26186 		 * either queued and waiting for some reason or has
26187 		 * already completed.
26188 		 */
26189 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26190 		    ci.ci_lifr);
26191 		if (ci.ci_ipif != NULL)
26192 			ipif_refrele(ci.ci_ipif);
26193 		ip_ioctl_finish(q, mp, err,
26194 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26195 		    NULL, NULL);
26196 		return;
26197 	}
26198 
26199 	ASSERT(ci.ci_ipif != NULL);
26200 
26201 	if (ipsq == NULL) {
26202 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26203 		    ip_process_ioctl, NEW_OP, B_TRUE);
26204 		entered_ipsq = B_TRUE;
26205 	}
26206 	/*
26207 	 * Release the ipif so that ipif_down and friends that wait for
26208 	 * references to go away are not misled about the current ipif_refcnt
26209 	 * values. We are writer so we can access the ipif even after releasing
26210 	 * the ipif.
26211 	 */
26212 	ipif_refrele(ci.ci_ipif);
26213 	if (ipsq == NULL)
26214 		return;
26215 
26216 	mutex_enter(&ipsq->ipsq_lock);
26217 	ASSERT(ipsq->ipsq_current_ipif == NULL);
26218 	ipsq->ipsq_current_ipif = ci.ci_ipif;
26219 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26220 	mutex_exit(&ipsq->ipsq_lock);
26221 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26222 	/*
26223 	 * For most set ioctls that come here, this serves as a single point
26224 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26225 	 * be any new references to the ipif. This helps functions that go
26226 	 * through this path and end up trying to wait for the refcnts
26227 	 * associated with the ipif to go down to zero. Some exceptions are
26228 	 * Failover, Failback, and Groupname commands that operate on more than
26229 	 * just the ci.ci_ipif. These commands internally determine the
26230 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26231 	 * flags on that set. Another exception is the Removeif command that
26232 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26233 	 * ipif to operate on.
26234 	 */
26235 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26236 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26237 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26238 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26239 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26240 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26241 
26242 	/*
26243 	 * A return value of EINPROGRESS means the ioctl is
26244 	 * either queued and waiting for some reason or has
26245 	 * already completed.
26246 	 */
26247 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26248 	    ci.ci_lifr);
26249 
26250 	/* SIOCLIFREMOVEIF could have removed the ipif */
26251 	ip_ioctl_finish(q, mp, err,
26252 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26253 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
26254 
26255 	if (entered_ipsq)
26256 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26257 }
26258 
26259 /*
26260  * Complete the ioctl. Typically ioctls use the mi package and need to
26261  * do mi_copyout/mi_copy_done.
26262  */
26263 void
26264 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
26265     ipif_t *ipif, ipsq_t *ipsq)
26266 {
26267 	conn_t	*connp = NULL;
26268 	hook_nic_event_t *info;
26269 
26270 	if (err == EINPROGRESS)
26271 		return;
26272 
26273 	if (CONN_Q(q)) {
26274 		connp = Q_TO_CONN(q);
26275 		ASSERT(connp->conn_ref >= 2);
26276 	}
26277 
26278 	switch (mode) {
26279 	case COPYOUT:
26280 		if (err == 0)
26281 			mi_copyout(q, mp);
26282 		else
26283 			mi_copy_done(q, mp, err);
26284 		break;
26285 
26286 	case NO_COPYOUT:
26287 		mi_copy_done(q, mp, err);
26288 		break;
26289 
26290 	default:
26291 		/* An ioctl aborted through a conn close would take this path */
26292 		break;
26293 	}
26294 
26295 	/*
26296 	 * The refhold placed at the start of the ioctl is released here.
26297 	 */
26298 	if (connp != NULL)
26299 		CONN_OPER_PENDING_DONE(connp);
26300 
26301 	/*
26302 	 * If the ioctl were an exclusive ioctl it would have set
26303 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
26304 	 */
26305 	if (ipif != NULL) {
26306 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
26307 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
26308 
26309 		/*
26310 		 * Unhook the nic event message from the ill and enqueue it into
26311 		 * the nic event taskq.
26312 		 */
26313 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
26314 			if (ddi_taskq_dispatch(eventq_queue_nic,
26315 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
26316 			    == DDI_FAILURE) {
26317 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
26318 				    "failed\n"));
26319 				if (info->hne_data != NULL)
26320 					kmem_free(info->hne_data,
26321 					    info->hne_datalen);
26322 				kmem_free(info, sizeof (hook_nic_event_t));
26323 			}
26324 
26325 			ipif->ipif_ill->ill_nic_event_info = NULL;
26326 		}
26327 
26328 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
26329 	}
26330 
26331 	/*
26332 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
26333 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
26334 	 * entering the ipsq
26335 	 */
26336 	if (ipsq != NULL) {
26337 		mutex_enter(&ipsq->ipsq_lock);
26338 		ipsq->ipsq_current_ipif = NULL;
26339 		mutex_exit(&ipsq->ipsq_lock);
26340 	}
26341 }
26342 
26343 /*
26344  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26345  */
26346 /* ARGSUSED */
26347 void
26348 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26349 {
26350 	conn_t *connp = arg;
26351 	tcp_t	*tcp;
26352 
26353 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26354 	tcp = connp->conn_tcp;
26355 
26356 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26357 		freemsg(mp);
26358 	else
26359 		tcp_rput_other(tcp, mp);
26360 	CONN_OPER_PENDING_DONE(connp);
26361 }
26362 
26363 /* Called from ip_wput for all non data messages */
26364 /* ARGSUSED */
26365 void
26366 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26367 {
26368 	mblk_t		*mp1;
26369 	ire_t		*ire, *fake_ire;
26370 	ill_t		*ill;
26371 	struct iocblk	*iocp;
26372 	ip_ioctl_cmd_t	*ipip;
26373 	cred_t		*cr;
26374 	conn_t		*connp = NULL;
26375 	int		cmd, err;
26376 	nce_t		*nce;
26377 	ipif_t		*ipif;
26378 
26379 	if (CONN_Q(q))
26380 		connp = Q_TO_CONN(q);
26381 
26382 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26383 
26384 	/* Check if it is a queue to /dev/sctp. */
26385 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26386 	    connp->conn_rq == NULL) {
26387 		sctp_wput(q, mp);
26388 		return;
26389 	}
26390 
26391 	switch (DB_TYPE(mp)) {
26392 	case M_IOCTL:
26393 		/*
26394 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26395 		 * will arrange to copy in associated control structures.
26396 		 */
26397 		ip_sioctl_copyin_setup(q, mp);
26398 		return;
26399 	case M_IOCDATA:
26400 		/*
26401 		 * Ensure that this is associated with one of our trans-
26402 		 * parent ioctls.  If it's not ours, discard it if we're
26403 		 * running as a driver, or pass it on if we're a module.
26404 		 */
26405 		iocp = (struct iocblk *)mp->b_rptr;
26406 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26407 		if (ipip == NULL) {
26408 			if (q->q_next == NULL) {
26409 				goto nak;
26410 			} else {
26411 				putnext(q, mp);
26412 			}
26413 			return;
26414 		} else if ((q->q_next != NULL) &&
26415 		    !(ipip->ipi_flags & IPI_MODOK)) {
26416 			/*
26417 			 * the ioctl is one we recognise, but is not
26418 			 * consumed by IP as a module, pass M_IOCDATA
26419 			 * for processing downstream, but only for
26420 			 * common Streams ioctls.
26421 			 */
26422 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26423 				putnext(q, mp);
26424 				return;
26425 			} else {
26426 				goto nak;
26427 			}
26428 		}
26429 
26430 		/* IOCTL continuation following copyin or copyout. */
26431 		if (mi_copy_state(q, mp, NULL) == -1) {
26432 			/*
26433 			 * The copy operation failed.  mi_copy_state already
26434 			 * cleaned up, so we're out of here.
26435 			 */
26436 			return;
26437 		}
26438 		/*
26439 		 * If we just completed a copy in, we become writer and
26440 		 * continue processing in ip_sioctl_copyin_done.  If it
26441 		 * was a copy out, we call mi_copyout again.  If there is
26442 		 * nothing more to copy out, it will complete the IOCTL.
26443 		 */
26444 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26445 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26446 				mi_copy_done(q, mp, EPROTO);
26447 				return;
26448 			}
26449 			/*
26450 			 * Check for cases that need more copying.  A return
26451 			 * value of 0 means a second copyin has been started,
26452 			 * so we return; a return value of 1 means no more
26453 			 * copying is needed, so we continue.
26454 			 */
26455 			cmd = iocp->ioc_cmd;
26456 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
26457 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
26458 			    MI_COPY_COUNT(mp) == 1) {
26459 				if (ip_copyin_msfilter(q, mp) == 0)
26460 					return;
26461 			}
26462 			/*
26463 			 * Refhold the conn, till the ioctl completes. This is
26464 			 * needed in case the ioctl ends up in the pending mp
26465 			 * list. Every mp in the ill_pending_mp list and
26466 			 * the ipsq_pending_mp must have a refhold on the conn
26467 			 * to resume processing. The refhold is released when
26468 			 * the ioctl completes. (normally or abnormally)
26469 			 * In all cases ip_ioctl_finish is called to finish
26470 			 * the ioctl.
26471 			 */
26472 			if (connp != NULL) {
26473 				/* This is not a reentry */
26474 				ASSERT(ipsq == NULL);
26475 				CONN_INC_REF(connp);
26476 			} else {
26477 				if (!(ipip->ipi_flags & IPI_MODOK)) {
26478 					mi_copy_done(q, mp, EINVAL);
26479 					return;
26480 				}
26481 			}
26482 
26483 			ip_process_ioctl(ipsq, q, mp, ipip);
26484 
26485 		} else {
26486 			mi_copyout(q, mp);
26487 		}
26488 		return;
26489 nak:
26490 		iocp->ioc_error = EINVAL;
26491 		mp->b_datap->db_type = M_IOCNAK;
26492 		iocp->ioc_count = 0;
26493 		qreply(q, mp);
26494 		return;
26495 
26496 	case M_IOCNAK:
26497 		/*
26498 		 * The only way we could get here is if a resolver didn't like
26499 		 * an IOCTL we sent it.	 This shouldn't happen.
26500 		 */
26501 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
26502 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
26503 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
26504 		freemsg(mp);
26505 		return;
26506 	case M_IOCACK:
26507 		/* Finish socket ioctls passed through to ARP. */
26508 		ip_sioctl_iocack(q, mp);
26509 		return;
26510 	case M_FLUSH:
26511 		if (*mp->b_rptr & FLUSHW)
26512 			flushq(q, FLUSHALL);
26513 		if (q->q_next) {
26514 			/*
26515 			 * M_FLUSH is sent up to IP by some drivers during
26516 			 * unbind. ip_rput has already replied to it. We are
26517 			 * here for the M_FLUSH that we originated in IP
26518 			 * before sending the unbind request to the driver.
26519 			 * Just free it as we don't queue packets in IP
26520 			 * on the write side of the device instance.
26521 			 */
26522 			freemsg(mp);
26523 			return;
26524 		}
26525 		if (*mp->b_rptr & FLUSHR) {
26526 			*mp->b_rptr &= ~FLUSHW;
26527 			qreply(q, mp);
26528 			return;
26529 		}
26530 		freemsg(mp);
26531 		return;
26532 	case IRE_DB_REQ_TYPE:
26533 		/* An Upper Level Protocol wants a copy of an IRE. */
26534 		ip_ire_req(q, mp);
26535 		return;
26536 	case M_CTL:
26537 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
26538 			break;
26539 
26540 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
26541 		    TUN_HELLO) {
26542 			ASSERT(connp != NULL);
26543 			connp->conn_flags |= IPCL_IPTUN;
26544 			freeb(mp);
26545 			return;
26546 		}
26547 
26548 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
26549 		    IP_ULP_OUT_LABELED) {
26550 			out_labeled_t *olp;
26551 
26552 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
26553 				break;
26554 			olp = (out_labeled_t *)mp->b_rptr;
26555 			connp->conn_ulp_labeled = olp->out_qnext == q;
26556 			freemsg(mp);
26557 			return;
26558 		}
26559 
26560 		/* M_CTL messages are used by ARP to tell us things. */
26561 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
26562 			break;
26563 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
26564 		case AR_ENTRY_SQUERY:
26565 			ip_wput_ctl(q, mp);
26566 			return;
26567 		case AR_CLIENT_NOTIFY:
26568 			ip_arp_news(q, mp);
26569 			return;
26570 		case AR_DLPIOP_DONE:
26571 			ASSERT(q->q_next != NULL);
26572 			ill = (ill_t *)q->q_ptr;
26573 			/* qwriter_ip releases the refhold */
26574 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
26575 			ill_refhold(ill);
26576 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
26577 			    CUR_OP, B_FALSE);
26578 			return;
26579 		case AR_ARP_CLOSING:
26580 			/*
26581 			 * ARP (above us) is closing. If no ARP bringup is
26582 			 * currently pending, ack the message so that ARP
26583 			 * can complete its close. Also mark ill_arp_closing
26584 			 * so that new ARP bringups will fail. If any
26585 			 * ARP bringup is currently in progress, we will
26586 			 * ack this when the current ARP bringup completes.
26587 			 */
26588 			ASSERT(q->q_next != NULL);
26589 			ill = (ill_t *)q->q_ptr;
26590 			mutex_enter(&ill->ill_lock);
26591 			ill->ill_arp_closing = 1;
26592 			if (!ill->ill_arp_bringup_pending) {
26593 				mutex_exit(&ill->ill_lock);
26594 				qreply(q, mp);
26595 			} else {
26596 				mutex_exit(&ill->ill_lock);
26597 				freemsg(mp);
26598 			}
26599 			return;
26600 		case AR_ARP_EXTEND:
26601 			/*
26602 			 * The ARP module above us is capable of duplicate
26603 			 * address detection.  Old ATM drivers will not send
26604 			 * this message.
26605 			 */
26606 			ASSERT(q->q_next != NULL);
26607 			ill = (ill_t *)q->q_ptr;
26608 			ill->ill_arp_extend = B_TRUE;
26609 			freemsg(mp);
26610 			return;
26611 		default:
26612 			break;
26613 		}
26614 		break;
26615 	case M_PROTO:
26616 	case M_PCPROTO:
26617 		/*
26618 		 * The only PROTO messages we expect are ULP binds and
26619 		 * copies of option negotiation acknowledgements.
26620 		 */
26621 		switch (((union T_primitives *)mp->b_rptr)->type) {
26622 		case O_T_BIND_REQ:
26623 		case T_BIND_REQ: {
26624 			/* Request can get queued in bind */
26625 			ASSERT(connp != NULL);
26626 			/*
26627 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
26628 			 * instead of going through this path.  We only get
26629 			 * here in the following cases:
26630 			 *
26631 			 * a. Bind retries, where ipsq is non-NULL.
26632 			 * b. T_BIND_REQ is issued from non TCP/UDP
26633 			 *    transport, e.g. icmp for raw socket,
26634 			 *    in which case ipsq will be NULL.
26635 			 */
26636 			ASSERT(ipsq != NULL ||
26637 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
26638 
26639 			/* Don't increment refcnt if this is a re-entry */
26640 			if (ipsq == NULL)
26641 				CONN_INC_REF(connp);
26642 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
26643 			    connp, NULL) : ip_bind_v4(q, mp, connp);
26644 			if (mp == NULL)
26645 				return;
26646 			if (IPCL_IS_TCP(connp)) {
26647 				/*
26648 				 * In the case of TCP endpoint we
26649 				 * come here only for bind retries
26650 				 */
26651 				ASSERT(ipsq != NULL);
26652 				CONN_INC_REF(connp);
26653 				squeue_fill(connp->conn_sqp, mp,
26654 				    ip_resume_tcp_bind, connp,
26655 				    SQTAG_BIND_RETRY);
26656 				return;
26657 			} else if (IPCL_IS_UDP(connp)) {
26658 				/*
26659 				 * In the case of UDP endpoint we
26660 				 * come here only for bind retries
26661 				 */
26662 				ASSERT(ipsq != NULL);
26663 				udp_resume_bind(connp, mp);
26664 				return;
26665 			}
26666 			qreply(q, mp);
26667 			CONN_OPER_PENDING_DONE(connp);
26668 			return;
26669 		}
26670 		case T_SVR4_OPTMGMT_REQ:
26671 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
26672 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
26673 
26674 			ASSERT(connp != NULL);
26675 			if (!snmpcom_req(q, mp, ip_snmp_set,
26676 			    ip_snmp_get, cr)) {
26677 				/*
26678 				 * Call svr4_optcom_req so that it can
26679 				 * generate the ack. We don't come here
26680 				 * if this operation is being restarted.
26681 				 * ip_restart_optmgmt will drop the conn ref.
26682 				 * In the case of ipsec option after the ipsec
26683 				 * load is complete conn_restart_ipsec_waiter
26684 				 * drops the conn ref.
26685 				 */
26686 				ASSERT(ipsq == NULL);
26687 				CONN_INC_REF(connp);
26688 				if (ip_check_for_ipsec_opt(q, mp))
26689 					return;
26690 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
26691 				if (err != EINPROGRESS) {
26692 					/* Operation is done */
26693 					CONN_OPER_PENDING_DONE(connp);
26694 				}
26695 			}
26696 			return;
26697 		case T_OPTMGMT_REQ:
26698 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
26699 			/*
26700 			 * Note: No snmpcom_req support through new
26701 			 * T_OPTMGMT_REQ.
26702 			 * Call tpi_optcom_req so that it can
26703 			 * generate the ack.
26704 			 */
26705 			ASSERT(connp != NULL);
26706 			ASSERT(ipsq == NULL);
26707 			/*
26708 			 * We don't come here for restart. ip_restart_optmgmt
26709 			 * will drop the conn ref. In the case of ipsec option
26710 			 * after the ipsec load is complete
26711 			 * conn_restart_ipsec_waiter drops the conn ref.
26712 			 */
26713 			CONN_INC_REF(connp);
26714 			if (ip_check_for_ipsec_opt(q, mp))
26715 				return;
26716 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
26717 			if (err != EINPROGRESS) {
26718 				/* Operation is done */
26719 				CONN_OPER_PENDING_DONE(connp);
26720 			}
26721 			return;
26722 		case T_UNBIND_REQ:
26723 			mp = ip_unbind(q, mp);
26724 			qreply(q, mp);
26725 			return;
26726 		default:
26727 			/*
26728 			 * Have to drop any DLPI messages coming down from
26729 			 * arp (such as an info_req which would cause ip
26730 			 * to receive an extra info_ack if it was passed
26731 			 * through.
26732 			 */
26733 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
26734 			    (int)*(uint_t *)mp->b_rptr));
26735 			freemsg(mp);
26736 			return;
26737 		}
26738 		/* NOTREACHED */
26739 	case IRE_DB_TYPE: {
26740 		nce_t		*nce;
26741 		ill_t		*ill;
26742 		in6_addr_t	gw_addr_v6;
26743 
26744 
26745 		/*
26746 		 * This is a response back from a resolver.  It
26747 		 * consists of a message chain containing:
26748 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
26749 		 * The IRE_MBLK is the one we allocated in ip_newroute.
26750 		 * The LL_HDR_MBLK is the DLPI header to use to get
26751 		 * the attached packet, and subsequent ones for the
26752 		 * same destination, transmitted.
26753 		 */
26754 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
26755 			break;
26756 		/*
26757 		 * First, check to make sure the resolution succeeded.
26758 		 * If it failed, the second mblk will be empty.
26759 		 * If it is, free the chain, dropping the packet.
26760 		 * (We must ire_delete the ire; that frees the ire mblk)
26761 		 * We're doing this now to support PVCs for ATM; it's
26762 		 * a partial xresolv implementation. When we fully implement
26763 		 * xresolv interfaces, instead of freeing everything here
26764 		 * we'll initiate neighbor discovery.
26765 		 *
26766 		 * For v4 (ARP and other external resolvers) the resolver
26767 		 * frees the message, so no check is needed. This check
26768 		 * is required, though, for a full xresolve implementation.
26769 		 * Including this code here now both shows how external
26770 		 * resolvers can NACK a resolution request using an
26771 		 * existing design that has no specific provisions for NACKs,
26772 		 * and also takes into account that the current non-ARP
26773 		 * external resolver has been coded to use this method of
26774 		 * NACKing for all IPv6 (xresolv) cases,
26775 		 * whether our xresolv implementation is complete or not.
26776 		 *
26777 		 */
26778 		ire = (ire_t *)mp->b_rptr;
26779 		ill = ire_to_ill(ire);
26780 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26781 		if (mp1->b_rptr == mp1->b_wptr) {
26782 			if (ire->ire_ipversion == IPV6_VERSION) {
26783 				/*
26784 				 * XRESOLV interface.
26785 				 */
26786 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
26787 				mutex_enter(&ire->ire_lock);
26788 				gw_addr_v6 = ire->ire_gateway_addr_v6;
26789 				mutex_exit(&ire->ire_lock);
26790 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26791 					nce = ndp_lookup_v6(ill,
26792 					    &ire->ire_addr_v6, B_FALSE);
26793 				} else {
26794 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
26795 					    B_FALSE);
26796 				}
26797 				if (nce != NULL) {
26798 					nce_resolv_failed(nce);
26799 					ndp_delete(nce);
26800 					NCE_REFRELE(nce);
26801 				}
26802 			}
26803 			mp->b_cont = NULL;
26804 			freemsg(mp1);		/* frees the pkt as well */
26805 			ASSERT(ire->ire_nce == NULL);
26806 			ire_delete((ire_t *)mp->b_rptr);
26807 			return;
26808 		}
26809 
26810 		/*
26811 		 * Split them into IRE_MBLK and pkt and feed it into
26812 		 * ire_add_then_send. Then in ire_add_then_send
26813 		 * the IRE will be added, and then the packet will be
26814 		 * run back through ip_wput. This time it will make
26815 		 * it to the wire.
26816 		 */
26817 		mp->b_cont = NULL;
26818 		mp = mp1->b_cont;		/* now, mp points to pkt */
26819 		mp1->b_cont = NULL;
26820 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
26821 		if (ire->ire_ipversion == IPV6_VERSION) {
26822 			/*
26823 			 * XRESOLV interface. Find the nce and put a copy
26824 			 * of the dl_unitdata_req in nce_res_mp
26825 			 */
26826 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
26827 			mutex_enter(&ire->ire_lock);
26828 			gw_addr_v6 = ire->ire_gateway_addr_v6;
26829 			mutex_exit(&ire->ire_lock);
26830 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
26831 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
26832 				    B_FALSE);
26833 			} else {
26834 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
26835 			}
26836 			if (nce != NULL) {
26837 				/*
26838 				 * We have to protect nce_res_mp here
26839 				 * from being accessed by other threads
26840 				 * while we change the mblk pointer.
26841 				 * Other functions will also lock the nce when
26842 				 * accessing nce_res_mp.
26843 				 *
26844 				 * The reason we change the mblk pointer
26845 				 * here rather than copying the resolved address
26846 				 * into the template is that, unlike with
26847 				 * ethernet, we have no guarantee that the
26848 				 * resolved address length will be
26849 				 * smaller than or equal to the lla length
26850 				 * with which the template was allocated,
26851 				 * (for ethernet, they're equal)
26852 				 * so we have to use the actual resolved
26853 				 * address mblk - which holds the real
26854 				 * dl_unitdata_req with the resolved address.
26855 				 *
26856 				 * Doing this is the same behavior as was
26857 				 * previously used in the v4 ARP case.
26858 				 */
26859 				mutex_enter(&nce->nce_lock);
26860 				if (nce->nce_res_mp != NULL)
26861 					freemsg(nce->nce_res_mp);
26862 				nce->nce_res_mp = mp1;
26863 				mutex_exit(&nce->nce_lock);
26864 				/*
26865 				 * We do a fastpath probe here because
26866 				 * we have resolved the address without
26867 				 * using Neighbor Discovery.
26868 				 * In the non-XRESOLV v6 case, the fastpath
26869 				 * probe is done right after neighbor
26870 				 * discovery completes.
26871 				 */
26872 				if (nce->nce_res_mp != NULL) {
26873 					int res;
26874 					nce_fastpath_list_add(nce);
26875 					res = ill_fastpath_probe(ill,
26876 					    nce->nce_res_mp);
26877 					if (res != 0 && res != EAGAIN)
26878 						nce_fastpath_list_delete(nce);
26879 				}
26880 
26881 				ire_add_then_send(q, ire, mp);
26882 				/*
26883 				 * Now we have to clean out any packets
26884 				 * that may have been queued on the nce
26885 				 * while it was waiting for address resolution
26886 				 * to complete.
26887 				 */
26888 				mutex_enter(&nce->nce_lock);
26889 				mp1 = nce->nce_qd_mp;
26890 				nce->nce_qd_mp = NULL;
26891 				mutex_exit(&nce->nce_lock);
26892 				while (mp1 != NULL) {
26893 					mblk_t *nxt_mp;
26894 					queue_t *fwdq = NULL;
26895 					ill_t   *inbound_ill;
26896 					uint_t ifindex;
26897 
26898 					nxt_mp = mp1->b_next;
26899 					mp1->b_next = NULL;
26900 					/*
26901 					 * Retrieve ifindex stored in
26902 					 * ip_rput_data_v6()
26903 					 */
26904 					ifindex =
26905 					    (uint_t)(uintptr_t)mp1->b_prev;
26906 					inbound_ill =
26907 						ill_lookup_on_ifindex(ifindex,
26908 						    B_TRUE, NULL, NULL, NULL,
26909 						    NULL);
26910 					mp1->b_prev = NULL;
26911 					if (inbound_ill != NULL)
26912 						fwdq = inbound_ill->ill_rq;
26913 
26914 					if (fwdq != NULL) {
26915 						put(fwdq, mp1);
26916 						ill_refrele(inbound_ill);
26917 					} else
26918 						put(WR(ill->ill_rq), mp1);
26919 					mp1 = nxt_mp;
26920 				}
26921 				NCE_REFRELE(nce);
26922 			} else {	/* nce is NULL; clean up */
26923 				ire_delete(ire);
26924 				freemsg(mp);
26925 				freemsg(mp1);
26926 				return;
26927 			}
26928 		} else {
26929 			nce_t *arpce;
26930 			/*
26931 			 * Link layer resolution succeeded. Recompute the
26932 			 * ire_nce.
26933 			 */
26934 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
26935 			if ((arpce = ndp_lookup_v4(ill,
26936 			    (ire->ire_gateway_addr != INADDR_ANY ?
26937 			    &ire->ire_gateway_addr : &ire->ire_addr),
26938 			    B_FALSE)) == NULL) {
26939 				freeb(ire->ire_mp);
26940 				freeb(mp1);
26941 				freemsg(mp);
26942 				return;
26943 			}
26944 			mutex_enter(&arpce->nce_lock);
26945 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
26946 			if (arpce->nce_state == ND_REACHABLE) {
26947 				/*
26948 				 * Someone resolved this before us;
26949 				 * cleanup the res_mp. Since ire has
26950 				 * not been added yet, the call to ire_add_v4
26951 				 * from ire_add_then_send (when a dup is
26952 				 * detected) will clean up the ire.
26953 				 */
26954 				freeb(mp1);
26955 			} else {
26956 				if (arpce->nce_res_mp != NULL)
26957 					freemsg(arpce->nce_res_mp);
26958 				arpce->nce_res_mp = mp1;
26959 				arpce->nce_state = ND_REACHABLE;
26960 			}
26961 			mutex_exit(&arpce->nce_lock);
26962 			if (ire->ire_marks & IRE_MARK_NOADD) {
26963 				/*
26964 				 * this ire will not be added to the ire
26965 				 * cache table, so we can set the ire_nce
26966 				 * here, as there are no atomicity constraints.
26967 				 */
26968 				ire->ire_nce = arpce;
26969 				/*
26970 				 * We are associating this nce with the ire
26971 				 * so change the nce ref taken in
26972 				 * ndp_lookup_v4() from
26973 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
26974 				 */
26975 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
26976 			} else {
26977 				NCE_REFRELE(arpce);
26978 			}
26979 			ire_add_then_send(q, ire, mp);
26980 		}
26981 		return;	/* All is well, the packet has been sent. */
26982 	}
26983 	case IRE_ARPRESOLVE_TYPE: {
26984 
26985 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
26986 			break;
26987 		mp1 = mp->b_cont;		/* dl_unitdata_req */
26988 		mp->b_cont = NULL;
26989 		/*
26990 		 * First, check to make sure the resolution succeeded.
26991 		 * If it failed, the second mblk will be empty.
26992 		 */
26993 		if (mp1->b_rptr == mp1->b_wptr) {
26994 			/* cleanup  the incomplete ire, free queued packets */
26995 			freemsg(mp); /* fake ire */
26996 			freeb(mp1);  /* dl_unitdata response */
26997 			return;
26998 		}
26999 
27000 		/*
27001 		 * update any incomplete nce_t found. we lookup the ctable
27002 		 * and find the nce from the ire->ire_nce because we need
27003 		 * to pass the ire to ip_xmit_v4 later, and can find both
27004 		 * ire and nce in one lookup from the ctable.
27005 		 */
27006 		fake_ire = (ire_t *)mp->b_rptr;
27007 		/*
27008 		 * By the time we come back here from ARP
27009 		 * the logical outgoing interface  of the incomplete ire
27010 		 * we added in ire_forward could have disappeared,
27011 		 * causing the incomplete ire to also have
27012 		 * dissapeared. So we need to retreive the
27013 		 * proper ipif for the ire  before looking
27014 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27015 		 */
27016 		ill = q->q_ptr;
27017 
27018 		/* Get the outgoing ipif */
27019 		mutex_enter(&ill->ill_lock);
27020 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27021 			mutex_exit(&ill->ill_lock);
27022 			freemsg(mp); /* fake ire */
27023 			freeb(mp1);  /* dl_unitdata response */
27024 			return;
27025 		}
27026 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27027 
27028 		if (ipif == NULL) {
27029 			mutex_exit(&ill->ill_lock);
27030 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27031 			freemsg(mp);
27032 			freeb(mp1);
27033 			return;
27034 		}
27035 		ipif_refhold_locked(ipif);
27036 		mutex_exit(&ill->ill_lock);
27037 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27038 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27039 		    ipif, fake_ire->ire_zoneid, NULL,
27040 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27041 		ipif_refrele(ipif);
27042 		if (ire == NULL) {
27043 			/*
27044 			 * no ire was found; check if there is an nce
27045 			 * for this lookup; if it has no ire's pointing at it
27046 			 * cleanup.
27047 			 */
27048 			if ((nce = ndp_lookup_v4(ill,
27049 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27050 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27051 			    B_FALSE)) != NULL) {
27052 				/*
27053 				 * cleanup: just reset nce.
27054 				 * We check for refcnt 2 (one for the nce
27055 				 * hash list + 1 for the ref taken by
27056 				 * ndp_lookup_v4) to ensure that there are
27057 				 * no ire's pointing at the nce.
27058 				 */
27059 				if (nce->nce_refcnt == 2) {
27060 					nce = nce_reinit(nce);
27061 				}
27062 				if (nce != NULL)
27063 					NCE_REFRELE(nce);
27064 			}
27065 			freeb(mp1);  /* dl_unitdata response */
27066 			freemsg(mp); /* fake ire */
27067 			return;
27068 		}
27069 		nce = ire->ire_nce;
27070 		DTRACE_PROBE2(ire__arpresolve__type,
27071 		    ire_t *, ire, nce_t *, nce);
27072 		ASSERT(nce->nce_state != ND_INITIAL);
27073 		mutex_enter(&nce->nce_lock);
27074 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27075 		if (nce->nce_state == ND_REACHABLE) {
27076 			/*
27077 			 * Someone resolved this before us;
27078 			 * our response is not needed any more.
27079 			 */
27080 			mutex_exit(&nce->nce_lock);
27081 			freeb(mp1);  /* dl_unitdata response */
27082 		} else {
27083 			if (nce->nce_res_mp != NULL) {
27084 				freemsg(nce->nce_res_mp);
27085 				/* existing dl_unitdata template */
27086 			}
27087 			nce->nce_res_mp = mp1;
27088 			nce->nce_state = ND_REACHABLE;
27089 			mutex_exit(&nce->nce_lock);
27090 			ire_fastpath(ire);
27091 		}
27092 		/*
27093 		 * The cached nce_t has been updated to be reachable;
27094 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27095 		 */
27096 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27097 		freemsg(mp);
27098 		/*
27099 		 * send out queued packets.
27100 		 */
27101 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27102 
27103 		IRE_REFRELE(ire);
27104 		return;
27105 	}
27106 	default:
27107 		break;
27108 	}
27109 	if (q->q_next) {
27110 		putnext(q, mp);
27111 	} else
27112 		freemsg(mp);
27113 }
27114 
27115 /*
27116  * Process IP options in an outbound packet.  Modify the destination if there
27117  * is a source route option.
27118  * Returns non-zero if something fails in which case an ICMP error has been
27119  * sent and mp freed.
27120  */
27121 static int
27122 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27123     boolean_t mctl_present, zoneid_t zoneid)
27124 {
27125 	ipoptp_t	opts;
27126 	uchar_t		*opt;
27127 	uint8_t		optval;
27128 	uint8_t		optlen;
27129 	ipaddr_t	dst;
27130 	intptr_t	code = 0;
27131 	mblk_t		*mp;
27132 	ire_t		*ire = NULL;
27133 
27134 	ip2dbg(("ip_wput_options\n"));
27135 	mp = ipsec_mp;
27136 	if (mctl_present) {
27137 		mp = ipsec_mp->b_cont;
27138 	}
27139 
27140 	dst = ipha->ipha_dst;
27141 	for (optval = ipoptp_first(&opts, ipha);
27142 	    optval != IPOPT_EOL;
27143 	    optval = ipoptp_next(&opts)) {
27144 		opt = opts.ipoptp_cur;
27145 		optlen = opts.ipoptp_len;
27146 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27147 		    optval, optlen));
27148 		switch (optval) {
27149 			uint32_t off;
27150 		case IPOPT_SSRR:
27151 		case IPOPT_LSRR:
27152 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27153 				ip1dbg((
27154 				    "ip_wput_options: bad option offset\n"));
27155 				code = (char *)&opt[IPOPT_OLEN] -
27156 				    (char *)ipha;
27157 				goto param_prob;
27158 			}
27159 			off = opt[IPOPT_OFFSET];
27160 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27161 			    ntohl(dst)));
27162 			/*
27163 			 * For strict: verify that dst is directly
27164 			 * reachable.
27165 			 */
27166 			if (optval == IPOPT_SSRR) {
27167 				ire = ire_ftable_lookup(dst, 0, 0,
27168 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27169 				    MBLK_GETLABEL(mp),
27170 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27171 				if (ire == NULL) {
27172 					ip1dbg(("ip_wput_options: SSRR not"
27173 					    " directly reachable: 0x%x\n",
27174 					    ntohl(dst)));
27175 					goto bad_src_route;
27176 				}
27177 				ire_refrele(ire);
27178 			}
27179 			break;
27180 		case IPOPT_RR:
27181 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27182 				ip1dbg((
27183 				    "ip_wput_options: bad option offset\n"));
27184 				code = (char *)&opt[IPOPT_OLEN] -
27185 				    (char *)ipha;
27186 				goto param_prob;
27187 			}
27188 			break;
27189 		case IPOPT_TS:
27190 			/*
27191 			 * Verify that length >=5 and that there is either
27192 			 * room for another timestamp or that the overflow
27193 			 * counter is not maxed out.
27194 			 */
27195 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27196 			if (optlen < IPOPT_MINLEN_IT) {
27197 				goto param_prob;
27198 			}
27199 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27200 				ip1dbg((
27201 				    "ip_wput_options: bad option offset\n"));
27202 				code = (char *)&opt[IPOPT_OFFSET] -
27203 				    (char *)ipha;
27204 				goto param_prob;
27205 			}
27206 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27207 			case IPOPT_TS_TSONLY:
27208 				off = IPOPT_TS_TIMELEN;
27209 				break;
27210 			case IPOPT_TS_TSANDADDR:
27211 			case IPOPT_TS_PRESPEC:
27212 			case IPOPT_TS_PRESPEC_RFC791:
27213 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27214 				break;
27215 			default:
27216 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27217 				    (char *)ipha;
27218 				goto param_prob;
27219 			}
27220 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27221 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27222 				/*
27223 				 * No room and the overflow counter is 15
27224 				 * already.
27225 				 */
27226 				goto param_prob;
27227 			}
27228 			break;
27229 		}
27230 	}
27231 
27232 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27233 		return (0);
27234 
27235 	ip1dbg(("ip_wput_options: error processing IP options."));
27236 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27237 
27238 param_prob:
27239 	/*
27240 	 * Since ip_wput() isn't close to finished, we fill
27241 	 * in enough of the header for credible error reporting.
27242 	 */
27243 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27244 		/* Failed */
27245 		freemsg(ipsec_mp);
27246 		return (-1);
27247 	}
27248 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
27249 	return (-1);
27250 
27251 bad_src_route:
27252 	/*
27253 	 * Since ip_wput() isn't close to finished, we fill
27254 	 * in enough of the header for credible error reporting.
27255 	 */
27256 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
27257 		/* Failed */
27258 		freemsg(ipsec_mp);
27259 		return (-1);
27260 	}
27261 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
27262 	return (-1);
27263 }
27264 
27265 /*
27266  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27267  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27268  * thru /etc/system.
27269  */
27270 #define	CONN_MAXDRAINCNT	64
27271 
27272 static void
27273 conn_drain_init(void)
27274 {
27275 	int i;
27276 
27277 	conn_drain_list_cnt = conn_drain_nthreads;
27278 
27279 	if ((conn_drain_list_cnt == 0) ||
27280 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27281 		/*
27282 		 * Default value of the number of drainers is the
27283 		 * number of cpus, subject to maximum of 8 drainers.
27284 		 */
27285 		if (boot_max_ncpus != -1)
27286 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27287 		else
27288 			conn_drain_list_cnt = MIN(max_ncpus, 8);
27289 	}
27290 
27291 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
27292 	    KM_SLEEP);
27293 
27294 	for (i = 0; i < conn_drain_list_cnt; i++) {
27295 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
27296 		    MUTEX_DEFAULT, NULL);
27297 	}
27298 }
27299 
27300 static void
27301 conn_drain_fini(void)
27302 {
27303 	int i;
27304 
27305 	for (i = 0; i < conn_drain_list_cnt; i++)
27306 		mutex_destroy(&conn_drain_list[i].idl_lock);
27307 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
27308 	conn_drain_list = NULL;
27309 }
27310 
27311 /*
27312  * Note: For an overview of how flowcontrol is handled in IP please see the
27313  * IP Flowcontrol notes at the top of this file.
27314  *
27315  * Flow control has blocked us from proceeding. Insert the given conn in one
27316  * of the conn drain lists. These conn wq's will be qenabled later on when
27317  * STREAMS flow control does a backenable. conn_walk_drain will enable
27318  * the first conn in each of these drain lists. Each of these qenabled conns
27319  * in turn enables the next in the list, after it runs, or when it closes,
27320  * thus sustaining the drain process.
27321  *
27322  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27323  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27324  * running at any time, on a given conn, since there can be only 1 service proc
27325  * running on a queue at any time.
27326  */
27327 void
27328 conn_drain_insert(conn_t *connp)
27329 {
27330 	idl_t	*idl;
27331 	uint_t	index;
27332 
27333 	mutex_enter(&connp->conn_lock);
27334 	if (connp->conn_state_flags & CONN_CLOSING) {
27335 		/*
27336 		 * The conn is closing as a result of which CONN_CLOSING
27337 		 * is set. Return.
27338 		 */
27339 		mutex_exit(&connp->conn_lock);
27340 		return;
27341 	} else if (connp->conn_idl == NULL) {
27342 		/*
27343 		 * Assign the next drain list round robin. We dont' use
27344 		 * a lock, and thus it may not be strictly round robin.
27345 		 * Atomicity of load/stores is enough to make sure that
27346 		 * conn_drain_list_index is always within bounds.
27347 		 */
27348 		index = conn_drain_list_index;
27349 		ASSERT(index < conn_drain_list_cnt);
27350 		connp->conn_idl = &conn_drain_list[index];
27351 		index++;
27352 		if (index == conn_drain_list_cnt)
27353 			index = 0;
27354 		conn_drain_list_index = index;
27355 	}
27356 	mutex_exit(&connp->conn_lock);
27357 
27358 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27359 	if ((connp->conn_drain_prev != NULL) ||
27360 	    (connp->conn_state_flags & CONN_CLOSING)) {
27361 		/*
27362 		 * The conn is already in the drain list, OR
27363 		 * the conn is closing. We need to check again for
27364 		 * the closing case again since close can happen
27365 		 * after we drop the conn_lock, and before we
27366 		 * acquire the CONN_DRAIN_LIST_LOCK.
27367 		 */
27368 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27369 		return;
27370 	} else {
27371 		idl = connp->conn_idl;
27372 	}
27373 
27374 	/*
27375 	 * The conn is not in the drain list. Insert it at the
27376 	 * tail of the drain list. The drain list is circular
27377 	 * and doubly linked. idl_conn points to the 1st element
27378 	 * in the list.
27379 	 */
27380 	if (idl->idl_conn == NULL) {
27381 		idl->idl_conn = connp;
27382 		connp->conn_drain_next = connp;
27383 		connp->conn_drain_prev = connp;
27384 	} else {
27385 		conn_t *head = idl->idl_conn;
27386 
27387 		connp->conn_drain_next = head;
27388 		connp->conn_drain_prev = head->conn_drain_prev;
27389 		head->conn_drain_prev->conn_drain_next = connp;
27390 		head->conn_drain_prev = connp;
27391 	}
27392 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27393 }
27394 
27395 /*
27396  * This conn is closing, and we are called from ip_close. OR
27397  * This conn has been serviced by ip_wsrv, and we need to do the tail
27398  * processing.
27399  * If this conn is part of the drain list, we may need to sustain the drain
27400  * process by qenabling the next conn in the drain list. We may also need to
27401  * remove this conn from the list, if it is done.
27402  */
27403 static void
27404 conn_drain_tail(conn_t *connp, boolean_t closing)
27405 {
27406 	idl_t *idl;
27407 
27408 	/*
27409 	 * connp->conn_idl is stable at this point, and no lock is needed
27410 	 * to check it. If we are called from ip_close, close has already
27411 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27412 	 * called us only because conn_idl is non-null. If we are called thru
27413 	 * service, conn_idl could be null, but it cannot change because
27414 	 * service is single-threaded per queue, and there cannot be another
27415 	 * instance of service trying to call conn_drain_insert on this conn
27416 	 * now.
27417 	 */
27418 	ASSERT(!closing || (connp->conn_idl != NULL));
27419 
27420 	/*
27421 	 * If connp->conn_idl is null, the conn has not been inserted into any
27422 	 * drain list even once since creation of the conn. Just return.
27423 	 */
27424 	if (connp->conn_idl == NULL)
27425 		return;
27426 
27427 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27428 
27429 	if (connp->conn_drain_prev == NULL) {
27430 		/* This conn is currently not in the drain list.  */
27431 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27432 		return;
27433 	}
27434 	idl = connp->conn_idl;
27435 	if (idl->idl_conn_draining == connp) {
27436 		/*
27437 		 * This conn is the current drainer. If this is the last conn
27438 		 * in the drain list, we need to do more checks, in the 'if'
27439 		 * below. Otherwwise we need to just qenable the next conn,
27440 		 * to sustain the draining, and is handled in the 'else'
27441 		 * below.
27442 		 */
27443 		if (connp->conn_drain_next == idl->idl_conn) {
27444 			/*
27445 			 * This conn is the last in this list. This round
27446 			 * of draining is complete. If idl_repeat is set,
27447 			 * it means another flow enabling has happened from
27448 			 * the driver/streams and we need to another round
27449 			 * of draining.
27450 			 * If there are more than 2 conns in the drain list,
27451 			 * do a left rotate by 1, so that all conns except the
27452 			 * conn at the head move towards the head by 1, and the
27453 			 * the conn at the head goes to the tail. This attempts
27454 			 * a more even share for all queues that are being
27455 			 * drained.
27456 			 */
27457 			if ((connp->conn_drain_next != connp) &&
27458 			    (idl->idl_conn->conn_drain_next != connp)) {
27459 				idl->idl_conn = idl->idl_conn->conn_drain_next;
27460 			}
27461 			if (idl->idl_repeat) {
27462 				qenable(idl->idl_conn->conn_wq);
27463 				idl->idl_conn_draining = idl->idl_conn;
27464 				idl->idl_repeat = 0;
27465 			} else {
27466 				idl->idl_conn_draining = NULL;
27467 			}
27468 		} else {
27469 			/*
27470 			 * If the next queue that we are now qenable'ing,
27471 			 * is closing, it will remove itself from this list
27472 			 * and qenable the subsequent queue in ip_close().
27473 			 * Serialization is acheived thru idl_lock.
27474 			 */
27475 			qenable(connp->conn_drain_next->conn_wq);
27476 			idl->idl_conn_draining = connp->conn_drain_next;
27477 		}
27478 	}
27479 	if (!connp->conn_did_putbq || closing) {
27480 		/*
27481 		 * Remove ourself from the drain list, if we did not do
27482 		 * a putbq, or if the conn is closing.
27483 		 * Note: It is possible that q->q_first is non-null. It means
27484 		 * that these messages landed after we did a enableok() in
27485 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
27486 		 * service them.
27487 		 */
27488 		if (connp->conn_drain_next == connp) {
27489 			/* Singleton in the list */
27490 			ASSERT(connp->conn_drain_prev == connp);
27491 			idl->idl_conn = NULL;
27492 			idl->idl_conn_draining = NULL;
27493 		} else {
27494 			connp->conn_drain_prev->conn_drain_next =
27495 			    connp->conn_drain_next;
27496 			connp->conn_drain_next->conn_drain_prev =
27497 			    connp->conn_drain_prev;
27498 			if (idl->idl_conn == connp)
27499 				idl->idl_conn = connp->conn_drain_next;
27500 			ASSERT(idl->idl_conn_draining != connp);
27501 
27502 		}
27503 		connp->conn_drain_next = NULL;
27504 		connp->conn_drain_prev = NULL;
27505 	}
27506 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27507 }
27508 
27509 /*
27510  * Write service routine. Shared perimeter entry point.
27511  * ip_wsrv can be called in any of the following ways.
27512  * 1. The device queue's messages has fallen below the low water mark
27513  *    and STREAMS has backenabled the ill_wq. We walk thru all the
27514  *    the drain lists and backenable the first conn in each list.
27515  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
27516  *    qenabled non-tcp upper layers. We start dequeing messages and call
27517  *    ip_wput for each message.
27518  */
27519 
27520 void
27521 ip_wsrv(queue_t *q)
27522 {
27523 	conn_t	*connp;
27524 	ill_t	*ill;
27525 	mblk_t	*mp;
27526 
27527 	if (q->q_next) {
27528 		ill = (ill_t *)q->q_ptr;
27529 		if (ill->ill_state_flags == 0) {
27530 			/*
27531 			 * The device flow control has opened up.
27532 			 * Walk through conn drain lists and qenable the
27533 			 * first conn in each list. This makes sense only
27534 			 * if the stream is fully plumbed and setup.
27535 			 * Hence the if check above.
27536 			 */
27537 			ip1dbg(("ip_wsrv: walking\n"));
27538 			conn_walk_drain();
27539 		}
27540 		return;
27541 	}
27542 
27543 	connp = Q_TO_CONN(q);
27544 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
27545 
27546 	/*
27547 	 * 1. Set conn_draining flag to signal that service is active.
27548 	 *
27549 	 * 2. ip_output determines whether it has been called from service,
27550 	 *    based on the last parameter. If it is IP_WSRV it concludes it
27551 	 *    has been called from service.
27552 	 *
27553 	 * 3. Message ordering is preserved by the following logic.
27554 	 *    i. A directly called ip_output (i.e. not thru service) will queue
27555 	 *    the message at the tail, if conn_draining is set (i.e. service
27556 	 *    is running) or if q->q_first is non-null.
27557 	 *
27558 	 *    ii. If ip_output is called from service, and if ip_output cannot
27559 	 *    putnext due to flow control, it does a putbq.
27560 	 *
27561 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
27562 	 *    (causing an infinite loop).
27563 	 */
27564 	ASSERT(!connp->conn_did_putbq);
27565 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
27566 		connp->conn_draining = 1;
27567 		noenable(q);
27568 		while ((mp = getq(q)) != NULL) {
27569 			ASSERT(CONN_Q(q));
27570 
27571 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
27572 			if (connp->conn_did_putbq) {
27573 				/* ip_wput did a putbq */
27574 				break;
27575 			}
27576 		}
27577 		/*
27578 		 * At this point, a thread coming down from top, calling
27579 		 * ip_wput, may end up queueing the message. We have not yet
27580 		 * enabled the queue, so ip_wsrv won't be called again.
27581 		 * To avoid this race, check q->q_first again (in the loop)
27582 		 * If the other thread queued the message before we call
27583 		 * enableok(), we will catch it in the q->q_first check.
27584 		 * If the other thread queues the message after we call
27585 		 * enableok(), ip_wsrv will be called again by STREAMS.
27586 		 */
27587 		connp->conn_draining = 0;
27588 		enableok(q);
27589 	}
27590 
27591 	/* Enable the next conn for draining */
27592 	conn_drain_tail(connp, B_FALSE);
27593 
27594 	connp->conn_did_putbq = 0;
27595 }
27596 
27597 /*
27598  * Walk the list of all conn's calling the function provided with the
27599  * specified argument for each.	 Note that this only walks conn's that
27600  * have been bound.
27601  * Applies to both IPv4 and IPv6.
27602  */
27603 static void
27604 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
27605 {
27606 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
27607 	    func, arg, zoneid);
27608 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
27609 	    func, arg, zoneid);
27610 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
27611 	    func, arg, zoneid);
27612 	conn_walk_fanout_table(ipcl_proto_fanout,
27613 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
27614 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
27615 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
27616 }
27617 
27618 /*
27619  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
27620  * of conns that need to be drained, check if drain is already in progress.
27621  * If so set the idl_repeat bit, indicating that the last conn in the list
27622  * needs to reinitiate the drain once again, for the list. If drain is not
27623  * in progress for the list, initiate the draining, by qenabling the 1st
27624  * conn in the list. The drain is self-sustaining, each qenabled conn will
27625  * in turn qenable the next conn, when it is done/blocked/closing.
27626  */
27627 static void
27628 conn_walk_drain(void)
27629 {
27630 	int i;
27631 	idl_t *idl;
27632 
27633 	IP_STAT(ip_conn_walk_drain);
27634 
27635 	for (i = 0; i < conn_drain_list_cnt; i++) {
27636 		idl = &conn_drain_list[i];
27637 		mutex_enter(&idl->idl_lock);
27638 		if (idl->idl_conn == NULL) {
27639 			mutex_exit(&idl->idl_lock);
27640 			continue;
27641 		}
27642 		/*
27643 		 * If this list is not being drained currently by
27644 		 * an ip_wsrv thread, start the process.
27645 		 */
27646 		if (idl->idl_conn_draining == NULL) {
27647 			ASSERT(idl->idl_repeat == 0);
27648 			qenable(idl->idl_conn->conn_wq);
27649 			idl->idl_conn_draining = idl->idl_conn;
27650 		} else {
27651 			idl->idl_repeat = 1;
27652 		}
27653 		mutex_exit(&idl->idl_lock);
27654 	}
27655 }
27656 
27657 /*
27658  * Walk an conn hash table of `count' buckets, calling func for each entry.
27659  */
27660 static void
27661 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
27662     zoneid_t zoneid)
27663 {
27664 	conn_t	*connp;
27665 
27666 	while (count-- > 0) {
27667 		mutex_enter(&connfp->connf_lock);
27668 		for (connp = connfp->connf_head; connp != NULL;
27669 		    connp = connp->conn_next) {
27670 			if (zoneid == GLOBAL_ZONEID ||
27671 			    zoneid == connp->conn_zoneid) {
27672 				CONN_INC_REF(connp);
27673 				mutex_exit(&connfp->connf_lock);
27674 				(*func)(connp, arg);
27675 				mutex_enter(&connfp->connf_lock);
27676 				CONN_DEC_REF(connp);
27677 			}
27678 		}
27679 		mutex_exit(&connfp->connf_lock);
27680 		connfp++;
27681 	}
27682 }
27683 
27684 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
27685 static void
27686 conn_report1(conn_t *connp, void *mp)
27687 {
27688 	char	buf1[INET6_ADDRSTRLEN];
27689 	char	buf2[INET6_ADDRSTRLEN];
27690 	uint_t	print_len, buf_len;
27691 
27692 	ASSERT(connp != NULL);
27693 
27694 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
27695 	if (buf_len <= 0)
27696 		return;
27697 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
27698 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
27699 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
27700 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
27701 	    "%5d %s/%05d %s/%05d\n",
27702 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
27703 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
27704 	    buf1, connp->conn_lport,
27705 	    buf2, connp->conn_fport);
27706 	if (print_len < buf_len) {
27707 		((mblk_t *)mp)->b_wptr += print_len;
27708 	} else {
27709 		((mblk_t *)mp)->b_wptr += buf_len;
27710 	}
27711 }
27712 
27713 /*
27714  * Named Dispatch routine to produce a formatted report on all conns
27715  * that are listed in one of the fanout tables.
27716  * This report is accessed by using the ndd utility to "get" ND variable
27717  * "ip_conn_status".
27718  */
27719 /* ARGSUSED */
27720 static int
27721 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
27722 {
27723 	(void) mi_mpprintf(mp,
27724 	    "CONN      " MI_COL_HDRPAD_STR
27725 	    "rfq      " MI_COL_HDRPAD_STR
27726 	    "stq      " MI_COL_HDRPAD_STR
27727 	    " zone local                 remote");
27728 
27729 	/*
27730 	 * Because of the ndd constraint, at most we can have 64K buffer
27731 	 * to put in all conn info.  So to be more efficient, just
27732 	 * allocate a 64K buffer here, assuming we need that large buffer.
27733 	 * This should be OK as only privileged processes can do ndd /dev/ip.
27734 	 */
27735 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
27736 		/* The following may work even if we cannot get a large buf. */
27737 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
27738 		return (0);
27739 	}
27740 
27741 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
27742 	return (0);
27743 }
27744 
27745 /*
27746  * Determine if the ill and multicast aspects of that packets
27747  * "matches" the conn.
27748  */
27749 boolean_t
27750 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
27751     zoneid_t zoneid)
27752 {
27753 	ill_t *in_ill;
27754 	boolean_t found;
27755 	ipif_t *ipif;
27756 	ire_t *ire;
27757 	ipaddr_t dst, src;
27758 
27759 	dst = ipha->ipha_dst;
27760 	src = ipha->ipha_src;
27761 
27762 	/*
27763 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
27764 	 * unicast, broadcast and multicast reception to
27765 	 * conn_incoming_ill. conn_wantpacket itself is called
27766 	 * only for BROADCAST and multicast.
27767 	 *
27768 	 * 1) ip_rput supresses duplicate broadcasts if the ill
27769 	 *    is part of a group. Hence, we should be receiving
27770 	 *    just one copy of broadcast for the whole group.
27771 	 *    Thus, if it is part of the group the packet could
27772 	 *    come on any ill of the group and hence we need a
27773 	 *    match on the group. Otherwise, match on ill should
27774 	 *    be sufficient.
27775 	 *
27776 	 * 2) ip_rput does not suppress duplicate multicast packets.
27777 	 *    If there are two interfaces in a ill group and we have
27778 	 *    2 applications (conns) joined a multicast group G on
27779 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
27780 	 *    will give us two packets because we join G on both the
27781 	 *    interfaces rather than nominating just one interface
27782 	 *    for receiving multicast like broadcast above. So,
27783 	 *    we have to call ilg_lookup_ill to filter out duplicate
27784 	 *    copies, if ill is part of a group.
27785 	 */
27786 	in_ill = connp->conn_incoming_ill;
27787 	if (in_ill != NULL) {
27788 		if (in_ill->ill_group == NULL) {
27789 			if (in_ill != ill)
27790 				return (B_FALSE);
27791 		} else if (in_ill->ill_group != ill->ill_group) {
27792 			return (B_FALSE);
27793 		}
27794 	}
27795 
27796 	if (!CLASSD(dst)) {
27797 		if (IPCL_ZONE_MATCH(connp, zoneid))
27798 			return (B_TRUE);
27799 		/*
27800 		 * The conn is in a different zone; we need to check that this
27801 		 * broadcast address is configured in the application's zone and
27802 		 * on one ill in the group.
27803 		 */
27804 		ipif = ipif_get_next_ipif(NULL, ill);
27805 		if (ipif == NULL)
27806 			return (B_FALSE);
27807 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
27808 		    connp->conn_zoneid, NULL,
27809 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
27810 		ipif_refrele(ipif);
27811 		if (ire != NULL) {
27812 			ire_refrele(ire);
27813 			return (B_TRUE);
27814 		} else {
27815 			return (B_FALSE);
27816 		}
27817 	}
27818 
27819 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
27820 	    connp->conn_zoneid == zoneid) {
27821 		/*
27822 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
27823 		 * disabled, therefore we don't dispatch the multicast packet to
27824 		 * the sending zone.
27825 		 */
27826 		return (B_FALSE);
27827 	}
27828 
27829 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
27830 	    connp->conn_zoneid != zoneid) {
27831 		/*
27832 		 * Multicast packet on the loopback interface: we only match
27833 		 * conns who joined the group in the specified zone.
27834 		 */
27835 		return (B_FALSE);
27836 	}
27837 
27838 	if (connp->conn_multi_router) {
27839 		/* multicast packet and multicast router socket: send up */
27840 		return (B_TRUE);
27841 	}
27842 
27843 	mutex_enter(&connp->conn_lock);
27844 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
27845 	mutex_exit(&connp->conn_lock);
27846 	return (found);
27847 }
27848 
27849 /*
27850  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
27851  */
27852 /* ARGSUSED */
27853 static void
27854 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
27855 {
27856 	ill_t *ill = (ill_t *)q->q_ptr;
27857 	mblk_t	*mp1, *mp2;
27858 	ipif_t  *ipif;
27859 	int err = 0;
27860 	conn_t *connp = NULL;
27861 	ipsq_t	*ipsq;
27862 	arc_t	*arc;
27863 
27864 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
27865 
27866 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
27867 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
27868 
27869 	ASSERT(IAM_WRITER_ILL(ill));
27870 	mp2 = mp->b_cont;
27871 	mp->b_cont = NULL;
27872 
27873 	/*
27874 	 * We have now received the arp bringup completion message
27875 	 * from ARP. Mark the arp bringup as done. Also if the arp
27876 	 * stream has already started closing, send up the AR_ARP_CLOSING
27877 	 * ack now since ARP is waiting in close for this ack.
27878 	 */
27879 	mutex_enter(&ill->ill_lock);
27880 	ill->ill_arp_bringup_pending = 0;
27881 	if (ill->ill_arp_closing) {
27882 		mutex_exit(&ill->ill_lock);
27883 		/* Let's reuse the mp for sending the ack */
27884 		arc = (arc_t *)mp->b_rptr;
27885 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
27886 		arc->arc_cmd = AR_ARP_CLOSING;
27887 		qreply(q, mp);
27888 	} else {
27889 		mutex_exit(&ill->ill_lock);
27890 		freeb(mp);
27891 	}
27892 
27893 	/* We should have an IOCTL waiting on this. */
27894 	ipsq = ill->ill_phyint->phyint_ipsq;
27895 	ipif = ipsq->ipsq_pending_ipif;
27896 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
27897 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
27898 	if (mp1 == NULL) {
27899 		/* bringup was aborted by the user */
27900 		freemsg(mp2);
27901 		return;
27902 	}
27903 	ASSERT(connp != NULL);
27904 	q = CONNP_TO_WQ(connp);
27905 	/*
27906 	 * If the DL_BIND_REQ fails, it is noted
27907 	 * in arc_name_offset.
27908 	 */
27909 	err = *((int *)mp2->b_rptr);
27910 	if (err == 0) {
27911 		if (ipif->ipif_isv6) {
27912 			if ((err = ipif_up_done_v6(ipif)) != 0)
27913 				ip0dbg(("ip_arp_done: init failed\n"));
27914 		} else {
27915 			if ((err = ipif_up_done(ipif)) != 0)
27916 				ip0dbg(("ip_arp_done: init failed\n"));
27917 		}
27918 	} else {
27919 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
27920 	}
27921 
27922 	freemsg(mp2);
27923 
27924 	if ((err == 0) && (ill->ill_up_ipifs)) {
27925 		err = ill_up_ipifs(ill, q, mp1);
27926 		if (err == EINPROGRESS)
27927 			return;
27928 	}
27929 
27930 	if (ill->ill_up_ipifs) {
27931 		ill_group_cleanup(ill);
27932 	}
27933 
27934 	/*
27935 	 * The ioctl must complete now without EINPROGRESS
27936 	 * since ipsq_pending_mp_get has removed the ioctl mblk
27937 	 * from ipsq_pending_mp. Otherwise the ioctl will be
27938 	 * stuck for ever in the ipsq.
27939 	 */
27940 	ASSERT(err != EINPROGRESS);
27941 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
27942 }
27943 
27944 /* Allocate the private structure */
27945 static int
27946 ip_priv_alloc(void **bufp)
27947 {
27948 	void	*buf;
27949 
27950 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
27951 		return (ENOMEM);
27952 
27953 	*bufp = buf;
27954 	return (0);
27955 }
27956 
27957 /* Function to delete the private structure */
27958 void
27959 ip_priv_free(void *buf)
27960 {
27961 	ASSERT(buf != NULL);
27962 	kmem_free(buf, sizeof (ip_priv_t));
27963 }
27964 
27965 /*
27966  * The entry point for IPPF processing.
27967  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
27968  * routine just returns.
27969  *
27970  * When called, ip_process generates an ipp_packet_t structure
27971  * which holds the state information for this packet and invokes the
27972  * the classifier (via ipp_packet_process). The classification, depending on
27973  * configured filters, results in a list of actions for this packet. Invoking
27974  * an action may cause the packet to be dropped, in which case the resulting
27975  * mblk (*mpp) is NULL. proc indicates the callout position for
27976  * this packet and ill_index is the interface this packet on or will leave
27977  * on (inbound and outbound resp.).
27978  */
27979 void
27980 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
27981 {
27982 	mblk_t		*mp;
27983 	ip_priv_t	*priv;
27984 	ipp_action_id_t	aid;
27985 	int		rc = 0;
27986 	ipp_packet_t	*pp;
27987 #define	IP_CLASS	"ip"
27988 
27989 	/* If the classifier is not loaded, return  */
27990 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
27991 		return;
27992 	}
27993 
27994 	mp = *mpp;
27995 	ASSERT(mp != NULL);
27996 
27997 	/* Allocate the packet structure */
27998 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
27999 	if (rc != 0) {
28000 		*mpp = NULL;
28001 		freemsg(mp);
28002 		return;
28003 	}
28004 
28005 	/* Allocate the private structure */
28006 	rc = ip_priv_alloc((void **)&priv);
28007 	if (rc != 0) {
28008 		*mpp = NULL;
28009 		freemsg(mp);
28010 		ipp_packet_free(pp);
28011 		return;
28012 	}
28013 	priv->proc = proc;
28014 	priv->ill_index = ill_index;
28015 	ipp_packet_set_private(pp, priv, ip_priv_free);
28016 	ipp_packet_set_data(pp, mp);
28017 
28018 	/* Invoke the classifier */
28019 	rc = ipp_packet_process(&pp);
28020 	if (pp != NULL) {
28021 		mp = ipp_packet_get_data(pp);
28022 		ipp_packet_free(pp);
28023 		if (rc != 0) {
28024 			freemsg(mp);
28025 			*mpp = NULL;
28026 		}
28027 	} else {
28028 		*mpp = NULL;
28029 	}
28030 #undef	IP_CLASS
28031 }
28032 
28033 /*
28034  * Propagate a multicast group membership operation (add/drop) on
28035  * all the interfaces crossed by the related multirt routes.
28036  * The call is considered successful if the operation succeeds
28037  * on at least one interface.
28038  */
28039 static int
28040 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28041     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28042     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28043     mblk_t *first_mp)
28044 {
28045 	ire_t		*ire_gw;
28046 	irb_t		*irb;
28047 	int		error = 0;
28048 	opt_restart_t	*or;
28049 
28050 	irb = ire->ire_bucket;
28051 	ASSERT(irb != NULL);
28052 
28053 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28054 
28055 	or = (opt_restart_t *)first_mp->b_rptr;
28056 	IRB_REFHOLD(irb);
28057 	for (; ire != NULL; ire = ire->ire_next) {
28058 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28059 			continue;
28060 		if (ire->ire_addr != group)
28061 			continue;
28062 
28063 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28064 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28065 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28066 		/* No resolver exists for the gateway; skip this ire. */
28067 		if (ire_gw == NULL)
28068 			continue;
28069 
28070 		/*
28071 		 * This function can return EINPROGRESS. If so the operation
28072 		 * will be restarted from ip_restart_optmgmt which will
28073 		 * call ip_opt_set and option processing will restart for
28074 		 * this option. So we may end up calling 'fn' more than once.
28075 		 * This requires that 'fn' is idempotent except for the
28076 		 * return value. The operation is considered a success if
28077 		 * it succeeds at least once on any one interface.
28078 		 */
28079 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28080 		    NULL, fmode, src, first_mp);
28081 		if (error == 0)
28082 			or->or_private = CGTP_MCAST_SUCCESS;
28083 
28084 		if (ip_debug > 0) {
28085 			ulong_t	off;
28086 			char	*ksym;
28087 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28088 			ip2dbg(("ip_multirt_apply_membership: "
28089 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28090 			    "error %d [success %u]\n",
28091 			    ksym ? ksym : "?",
28092 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28093 			    error, or->or_private));
28094 		}
28095 
28096 		ire_refrele(ire_gw);
28097 		if (error == EINPROGRESS) {
28098 			IRB_REFRELE(irb);
28099 			return (error);
28100 		}
28101 	}
28102 	IRB_REFRELE(irb);
28103 	/*
28104 	 * Consider the call as successful if we succeeded on at least
28105 	 * one interface. Otherwise, return the last encountered error.
28106 	 */
28107 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28108 }
28109 
28110 
28111 /*
28112  * Issue a warning regarding a route crossing an interface with an
28113  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28114  * amount of time is logged.
28115  */
28116 static void
28117 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28118 {
28119 	hrtime_t	current = gethrtime();
28120 	char		buf[INET_ADDRSTRLEN];
28121 
28122 	/* Convert interval in ms to hrtime in ns */
28123 	if (multirt_bad_mtu_last_time +
28124 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28125 	    current) {
28126 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28127 		    "to %s, incorrect MTU %u (expected %u)\n",
28128 		    ip_dot_addr(ire->ire_addr, buf),
28129 		    ire->ire_max_frag, max_frag);
28130 
28131 		multirt_bad_mtu_last_time = current;
28132 	}
28133 }
28134 
28135 
28136 /*
28137  * Get the CGTP (multirouting) filtering status.
28138  * If 0, the CGTP hooks are transparent.
28139  */
28140 /* ARGSUSED */
28141 static int
28142 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28143 {
28144 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28145 
28146 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28147 	return (0);
28148 }
28149 
28150 
28151 /*
28152  * Set the CGTP (multirouting) filtering status.
28153  * If the status is changed from active to transparent
28154  * or from transparent to active, forward the new status
28155  * to the filtering module (if loaded).
28156  */
28157 /* ARGSUSED */
28158 static int
28159 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28160     cred_t *ioc_cr)
28161 {
28162 	long		new_value;
28163 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28164 
28165 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28166 	    new_value < 0 || new_value > 1) {
28167 		return (EINVAL);
28168 	}
28169 
28170 	/*
28171 	 * Do not enable CGTP filtering - thus preventing the hooks
28172 	 * from being invoked - if the version number of the
28173 	 * filtering module hooks does not match.
28174 	 */
28175 	if ((ip_cgtp_filter_ops != NULL) &&
28176 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
28177 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
28178 		    "(module hooks version %d, expecting %d)\n",
28179 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
28180 		return (ENOTSUP);
28181 	}
28182 
28183 	if ((!*ip_cgtp_filter_value) && new_value) {
28184 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28185 		    ip_cgtp_filter_ops == NULL ?
28186 		    " (module not loaded)" : "");
28187 	}
28188 	if (*ip_cgtp_filter_value && (!new_value)) {
28189 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28190 		    ip_cgtp_filter_ops == NULL ?
28191 		    " (module not loaded)" : "");
28192 	}
28193 
28194 	if (ip_cgtp_filter_ops != NULL) {
28195 		int	res;
28196 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
28197 			return (res);
28198 		}
28199 	}
28200 
28201 	*ip_cgtp_filter_value = (boolean_t)new_value;
28202 
28203 	return (0);
28204 }
28205 
28206 
28207 /*
28208  * Return the expected CGTP hooks version number.
28209  */
28210 int
28211 ip_cgtp_filter_supported(void)
28212 {
28213 	return (ip_cgtp_filter_rev);
28214 }
28215 
28216 
28217 /*
28218  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
28219  * or by invoking this function. In the first case, the version number
28220  * of the registered structure is checked at hooks activation time
28221  * in ip_cgtp_filter_set().
28222  */
28223 int
28224 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
28225 {
28226 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28227 		return (ENOTSUP);
28228 
28229 	ip_cgtp_filter_ops = ops;
28230 	return (0);
28231 }
28232 
28233 static squeue_func_t
28234 ip_squeue_switch(int val)
28235 {
28236 	squeue_func_t rval = squeue_fill;
28237 
28238 	switch (val) {
28239 	case IP_SQUEUE_ENTER_NODRAIN:
28240 		rval = squeue_enter_nodrain;
28241 		break;
28242 	case IP_SQUEUE_ENTER:
28243 		rval = squeue_enter;
28244 		break;
28245 	default:
28246 		break;
28247 	}
28248 	return (rval);
28249 }
28250 
28251 /* ARGSUSED */
28252 static int
28253 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28254     caddr_t addr, cred_t *cr)
28255 {
28256 	int *v = (int *)addr;
28257 	long new_value;
28258 
28259 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28260 		return (EINVAL);
28261 
28262 	ip_input_proc = ip_squeue_switch(new_value);
28263 	*v = new_value;
28264 	return (0);
28265 }
28266 
28267 /* ARGSUSED */
28268 static int
28269 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28270     caddr_t addr, cred_t *cr)
28271 {
28272 	int *v = (int *)addr;
28273 	long new_value;
28274 
28275 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28276 		return (EINVAL);
28277 
28278 	*v = new_value;
28279 	return (0);
28280 }
28281 
28282 static void
28283 ip_kstat_init(void)
28284 {
28285 	ip_named_kstat_t template = {
28286 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
28287 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
28288 		{ "inReceives",		KSTAT_DATA_UINT32, 0 },
28289 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
28290 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
28291 		{ "forwDatagrams",	KSTAT_DATA_UINT32, 0 },
28292 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
28293 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
28294 		{ "inDelivers",		KSTAT_DATA_UINT32, 0 },
28295 		{ "outRequests",	KSTAT_DATA_UINT32, 0 },
28296 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
28297 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
28298 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
28299 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
28300 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
28301 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
28302 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
28303 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
28304 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
28305 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
28306 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
28307 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
28308 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
28309 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
28310 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
28311 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
28312 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
28313 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
28314 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
28315 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
28316 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
28317 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
28318 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
28319 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
28320 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
28321 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
28322 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
28323 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
28324 	};
28325 
28326 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
28327 					NUM_OF_FIELDS(ip_named_kstat_t),
28328 					0);
28329 	if (!ip_mibkp)
28330 		return;
28331 
28332 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
28333 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
28334 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
28335 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
28336 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
28337 
28338 	template.netToMediaEntrySize.value.i32 =
28339 		sizeof (mib2_ipNetToMediaEntry_t);
28340 
28341 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
28342 
28343 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
28344 
28345 	ip_mibkp->ks_update = ip_kstat_update;
28346 
28347 	kstat_install(ip_mibkp);
28348 }
28349 
28350 static void
28351 ip_kstat_fini(void)
28352 {
28353 
28354 	if (ip_mibkp != NULL) {
28355 		kstat_delete(ip_mibkp);
28356 		ip_mibkp = NULL;
28357 	}
28358 }
28359 
28360 static int
28361 ip_kstat_update(kstat_t *kp, int rw)
28362 {
28363 	ip_named_kstat_t *ipkp;
28364 
28365 	if (!kp || !kp->ks_data)
28366 		return (EIO);
28367 
28368 	if (rw == KSTAT_WRITE)
28369 		return (EACCES);
28370 
28371 	ipkp = (ip_named_kstat_t *)kp->ks_data;
28372 
28373 	ipkp->forwarding.value.ui32 =		ip_mib.ipForwarding;
28374 	ipkp->defaultTTL.value.ui32 =		ip_mib.ipDefaultTTL;
28375 	ipkp->inReceives.value.ui32 =		ip_mib.ipInReceives;
28376 	ipkp->inHdrErrors.value.ui32 =		ip_mib.ipInHdrErrors;
28377 	ipkp->inAddrErrors.value.ui32 =		ip_mib.ipInAddrErrors;
28378 	ipkp->forwDatagrams.value.ui32 =	ip_mib.ipForwDatagrams;
28379 	ipkp->inUnknownProtos.value.ui32 =	ip_mib.ipInUnknownProtos;
28380 	ipkp->inDiscards.value.ui32 =		ip_mib.ipInDiscards;
28381 	ipkp->inDelivers.value.ui32 =		ip_mib.ipInDelivers;
28382 	ipkp->outRequests.value.ui32 =		ip_mib.ipOutRequests;
28383 	ipkp->outDiscards.value.ui32 =		ip_mib.ipOutDiscards;
28384 	ipkp->outNoRoutes.value.ui32 =		ip_mib.ipOutNoRoutes;
28385 	ipkp->reasmTimeout.value.ui32 =		ip_mib.ipReasmTimeout;
28386 	ipkp->reasmReqds.value.ui32 =		ip_mib.ipReasmReqds;
28387 	ipkp->reasmOKs.value.ui32 =		ip_mib.ipReasmOKs;
28388 	ipkp->reasmFails.value.ui32 =		ip_mib.ipReasmFails;
28389 	ipkp->fragOKs.value.ui32 =		ip_mib.ipFragOKs;
28390 	ipkp->fragFails.value.ui32 =		ip_mib.ipFragFails;
28391 	ipkp->fragCreates.value.ui32 =		ip_mib.ipFragCreates;
28392 
28393 	ipkp->routingDiscards.value.ui32 =	ip_mib.ipRoutingDiscards;
28394 	ipkp->inErrs.value.ui32 =		ip_mib.tcpInErrs;
28395 	ipkp->noPorts.value.ui32 =		ip_mib.udpNoPorts;
28396 	ipkp->inCksumErrs.value.ui32 =		ip_mib.ipInCksumErrs;
28397 	ipkp->reasmDuplicates.value.ui32 =	ip_mib.ipReasmDuplicates;
28398 	ipkp->reasmPartDups.value.ui32 =	ip_mib.ipReasmPartDups;
28399 	ipkp->forwProhibits.value.ui32 =	ip_mib.ipForwProhibits;
28400 	ipkp->udpInCksumErrs.value.ui32 =	ip_mib.udpInCksumErrs;
28401 	ipkp->udpInOverflows.value.ui32 =	ip_mib.udpInOverflows;
28402 	ipkp->rawipInOverflows.value.ui32 =	ip_mib.rawipInOverflows;
28403 	ipkp->ipsecInSucceeded.value.ui32 =	ip_mib.ipsecInSucceeded;
28404 	ipkp->ipsecInFailed.value.i32 =		ip_mib.ipsecInFailed;
28405 
28406 	ipkp->inIPv6.value.ui32 =		ip_mib.ipInIPv6;
28407 	ipkp->outIPv6.value.ui32 =		ip_mib.ipOutIPv6;
28408 	ipkp->outSwitchIPv6.value.ui32 =	ip_mib.ipOutSwitchIPv6;
28409 
28410 	return (0);
28411 }
28412 
28413 static void
28414 icmp_kstat_init(void)
28415 {
28416 	icmp_named_kstat_t template = {
28417 		{ "inMsgs",		KSTAT_DATA_UINT32 },
28418 		{ "inErrors",		KSTAT_DATA_UINT32 },
28419 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
28420 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
28421 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
28422 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
28423 		{ "inRedirects",	KSTAT_DATA_UINT32 },
28424 		{ "inEchos",		KSTAT_DATA_UINT32 },
28425 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
28426 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
28427 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
28428 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
28429 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
28430 		{ "outMsgs",		KSTAT_DATA_UINT32 },
28431 		{ "outErrors",		KSTAT_DATA_UINT32 },
28432 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
28433 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
28434 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
28435 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
28436 		{ "outRedirects",	KSTAT_DATA_UINT32 },
28437 		{ "outEchos",		KSTAT_DATA_UINT32 },
28438 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
28439 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
28440 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
28441 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
28442 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
28443 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
28444 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
28445 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
28446 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
28447 		{ "outDrops",		KSTAT_DATA_UINT32 },
28448 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
28449 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
28450 	};
28451 
28452 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
28453 					NUM_OF_FIELDS(icmp_named_kstat_t),
28454 					0);
28455 	if (icmp_mibkp == NULL)
28456 		return;
28457 
28458 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
28459 
28460 	icmp_mibkp->ks_update = icmp_kstat_update;
28461 
28462 	kstat_install(icmp_mibkp);
28463 }
28464 
28465 static void
28466 icmp_kstat_fini(void)
28467 {
28468 
28469 	if (icmp_mibkp != NULL) {
28470 		kstat_delete(icmp_mibkp);
28471 		icmp_mibkp = NULL;
28472 	}
28473 }
28474 
28475 static int
28476 icmp_kstat_update(kstat_t *kp, int rw)
28477 {
28478 	icmp_named_kstat_t *icmpkp;
28479 
28480 	if ((kp == NULL) || (kp->ks_data == NULL))
28481 		return (EIO);
28482 
28483 	if (rw == KSTAT_WRITE)
28484 		return (EACCES);
28485 
28486 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
28487 
28488 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
28489 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
28490 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
28491 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
28492 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
28493 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
28494 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
28495 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
28496 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
28497 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
28498 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
28499 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
28500 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
28501 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
28502 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
28503 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
28504 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
28505 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
28506 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
28507 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
28508 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
28509 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
28510 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
28511 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
28512 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
28513 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
28514 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
28515 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
28516 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
28517 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
28518 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
28519 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
28520 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
28521 
28522 	return (0);
28523 }
28524 
28525 /*
28526  * This is the fanout function for raw socket opened for SCTP.  Note
28527  * that it is called after SCTP checks that there is no socket which
28528  * wants a packet.  Then before SCTP handles this out of the blue packet,
28529  * this function is called to see if there is any raw socket for SCTP.
28530  * If there is and it is bound to the correct address, the packet will
28531  * be sent to that socket.  Note that only one raw socket can be bound to
28532  * a port.  This is assured in ipcl_sctp_hash_insert();
28533  */
28534 void
28535 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
28536     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
28537     uint_t ipif_seqid, zoneid_t zoneid)
28538 {
28539 	conn_t		*connp;
28540 	queue_t		*rq;
28541 	mblk_t		*first_mp;
28542 	boolean_t	secure;
28543 	ip6_t		*ip6h;
28544 
28545 	first_mp = mp;
28546 	if (mctl_present) {
28547 		mp = first_mp->b_cont;
28548 		secure = ipsec_in_is_secure(first_mp);
28549 		ASSERT(mp != NULL);
28550 	} else {
28551 		secure = B_FALSE;
28552 	}
28553 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
28554 
28555 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
28556 	if (connp == NULL) {
28557 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
28558 		    mctl_present);
28559 		return;
28560 	}
28561 	rq = connp->conn_rq;
28562 	if (!canputnext(rq)) {
28563 		CONN_DEC_REF(connp);
28564 		BUMP_MIB(&ip_mib, rawipInOverflows);
28565 		freemsg(first_mp);
28566 		return;
28567 	}
28568 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
28569 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
28570 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
28571 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
28572 		if (first_mp == NULL) {
28573 			CONN_DEC_REF(connp);
28574 			return;
28575 		}
28576 	}
28577 	/*
28578 	 * We probably should not send M_CTL message up to
28579 	 * raw socket.
28580 	 */
28581 	if (mctl_present)
28582 		freeb(first_mp);
28583 
28584 	/* Initiate IPPF processing here if needed. */
28585 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
28586 	    (!isv4 && IP6_IN_IPP(flags))) {
28587 		ip_process(IPP_LOCAL_IN, &mp,
28588 		    recv_ill->ill_phyint->phyint_ifindex);
28589 		if (mp == NULL) {
28590 			CONN_DEC_REF(connp);
28591 			return;
28592 		}
28593 	}
28594 
28595 	if (connp->conn_recvif || connp->conn_recvslla ||
28596 	    ((connp->conn_ipv6_recvpktinfo ||
28597 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
28598 	    (flags & IP_FF_IP6INFO))) {
28599 		int in_flags = 0;
28600 
28601 		if (connp->conn_recvif || connp->conn_ipv6_recvpktinfo) {
28602 			in_flags = IPF_RECVIF;
28603 		}
28604 		if (connp->conn_recvslla) {
28605 			in_flags |= IPF_RECVSLLA;
28606 		}
28607 		if (isv4) {
28608 			mp = ip_add_info(mp, recv_ill, in_flags);
28609 		} else {
28610 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
28611 			if (mp == NULL) {
28612 				CONN_DEC_REF(connp);
28613 				return;
28614 			}
28615 		}
28616 	}
28617 
28618 	BUMP_MIB(&ip_mib, ipInDelivers);
28619 	/*
28620 	 * We are sending the IPSEC_IN message also up. Refer
28621 	 * to comments above this function.
28622 	 */
28623 	putnext(rq, mp);
28624 	CONN_DEC_REF(connp);
28625 }
28626 
28627 /*
28628  * This function should be called only if all packet processing
28629  * including fragmentation is complete. Callers of this function
28630  * must set mp->b_prev to one of these values:
28631  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
28632  * prior to handing over the mp as first argument to this function.
28633  *
28634  * If the ire passed by caller is incomplete, this function
28635  * queues the packet and if necessary, sends ARP request and bails.
28636  * If the ire passed is fully resolved, we simply prepend
28637  * the link-layer header to the packet, do ipsec hw acceleration
28638  * work if necessary, and send the packet out on the wire.
28639  *
28640  * NOTE: IPSEC will only call this function with fully resolved
28641  * ires if hw acceleration is involved.
28642  * TODO list :
28643  * 	a Handle M_MULTIDATA so that
28644  *	  tcp_multisend->tcp_multisend_data can
28645  *	  call ip_xmit_v4 directly
28646  *	b Handle post-ARP work for fragments so that
28647  *	  ip_wput_frag can call this function.
28648  */
28649 ipxmit_state_t
28650 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
28651 {
28652 	nce_t		*arpce;
28653 	queue_t		*q;
28654 	int		ill_index;
28655 	mblk_t		*nxt_mp, *first_mp;
28656 	boolean_t	xmit_drop = B_FALSE;
28657 	ip_proc_t	proc;
28658 	ill_t		*out_ill;
28659 
28660 	arpce = ire->ire_nce;
28661 	ASSERT(arpce != NULL);
28662 
28663 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
28664 
28665 	mutex_enter(&arpce->nce_lock);
28666 	switch (arpce->nce_state) {
28667 	case ND_REACHABLE:
28668 		/* If there are other queued packets, queue this packet */
28669 		if (arpce->nce_qd_mp != NULL) {
28670 			if (mp != NULL)
28671 				nce_queue_mp_common(arpce, mp, B_FALSE);
28672 			mp = arpce->nce_qd_mp;
28673 		}
28674 		arpce->nce_qd_mp = NULL;
28675 		mutex_exit(&arpce->nce_lock);
28676 
28677 		/*
28678 		 * Flush the queue.  In the common case, where the
28679 		 * ARP is already resolved,  it will go through the
28680 		 * while loop only once.
28681 		 */
28682 		while (mp != NULL) {
28683 
28684 			nxt_mp = mp->b_next;
28685 			mp->b_next = NULL;
28686 			/*
28687 			 * This info is needed for IPQOS to do COS marking
28688 			 * in ip_wput_attach_llhdr->ip_process.
28689 			 */
28690 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
28691 			mp->b_prev = NULL;
28692 
28693 			/* set up ill index for outbound qos processing */
28694 			out_ill = ire->ire_ipif->ipif_ill;
28695 			ill_index = out_ill->ill_phyint->phyint_ifindex;
28696 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
28697 			    ill_index);
28698 			if (first_mp == NULL) {
28699 				xmit_drop = B_TRUE;
28700 				if (proc == IPP_FWD_OUT) {
28701 					BUMP_MIB(&ip_mib, ipInDiscards);
28702 				} else {
28703 					BUMP_MIB(&ip_mib, ipOutDiscards);
28704 				}
28705 				goto next_mp;
28706 			}
28707 			/* non-ipsec hw accel case */
28708 			if (io == NULL || !io->ipsec_out_accelerated) {
28709 				/* send it */
28710 				q = ire->ire_stq;
28711 				if (proc == IPP_FWD_OUT) {
28712 					UPDATE_IB_PKT_COUNT(ire);
28713 				} else {
28714 					UPDATE_OB_PKT_COUNT(ire);
28715 				}
28716 				ire->ire_last_used_time = lbolt;
28717 
28718 				if (flow_ctl_enabled || canputnext(q))  {
28719 					if (proc == IPP_FWD_OUT) {
28720 						BUMP_MIB(&ip_mib,
28721 						    ipForwDatagrams);
28722 					}
28723 
28724 					if (mp == NULL)
28725 						goto next_mp;
28726 					putnext(q, first_mp);
28727 				} else {
28728 					BUMP_MIB(&ip_mib,
28729 					    ipOutDiscards);
28730 					xmit_drop = B_TRUE;
28731 					freemsg(first_mp);
28732 				}
28733 			} else {
28734 				/*
28735 				 * Safety Pup says: make sure this
28736 				 *  is going to the right interface!
28737 				 */
28738 				ill_t *ill1 =
28739 				    (ill_t *)ire->ire_stq->q_ptr;
28740 				int ifindex =
28741 				    ill1->ill_phyint->phyint_ifindex;
28742 				if (ifindex !=
28743 				    io->ipsec_out_capab_ill_index) {
28744 					xmit_drop = B_TRUE;
28745 					freemsg(mp);
28746 				} else {
28747 					ipsec_hw_putnext(ire->ire_stq,
28748 					    mp);
28749 				}
28750 			}
28751 next_mp:
28752 			mp = nxt_mp;
28753 		} /* while (mp != NULL) */
28754 		if (xmit_drop)
28755 			return (SEND_FAILED);
28756 		else
28757 			return (SEND_PASSED);
28758 
28759 	case ND_INITIAL:
28760 	case ND_INCOMPLETE:
28761 
28762 		/*
28763 		 * While we do send off packets to dests that
28764 		 * use fully-resolved CGTP routes, we do not
28765 		 * handle unresolved CGTP routes.
28766 		 */
28767 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
28768 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
28769 
28770 		if (mp != NULL) {
28771 			/* queue the packet */
28772 			nce_queue_mp_common(arpce, mp, B_FALSE);
28773 		}
28774 
28775 		if (arpce->nce_state == ND_INCOMPLETE) {
28776 			mutex_exit(&arpce->nce_lock);
28777 			DTRACE_PROBE3(ip__xmit__incomplete,
28778 			    (ire_t *), ire, (mblk_t *), mp,
28779 			    (ipsec_out_t *), io);
28780 			return (LOOKUP_IN_PROGRESS);
28781 		}
28782 
28783 		arpce->nce_state = ND_INCOMPLETE;
28784 		mutex_exit(&arpce->nce_lock);
28785 		/*
28786 		 * Note that ire_add() (called from ire_forward())
28787 		 * holds a ref on the ire until ARP is completed.
28788 		 */
28789 
28790 		ire_arpresolve(ire, ire_to_ill(ire));
28791 		return (LOOKUP_IN_PROGRESS);
28792 	default:
28793 		ASSERT(0);
28794 		mutex_exit(&arpce->nce_lock);
28795 		return (LLHDR_RESLV_FAILED);
28796 	}
28797 }
28798 
28799 /*
28800  * Return B_TRUE if the buffers differ in length or content.
28801  * This is used for comparing extension header buffers.
28802  * Note that an extension header would be declared different
28803  * even if all that changed was the next header value in that header i.e.
28804  * what really changed is the next extension header.
28805  */
28806 boolean_t
28807 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
28808     uint_t blen)
28809 {
28810 	if (!b_valid)
28811 		blen = 0;
28812 
28813 	if (alen != blen)
28814 		return (B_TRUE);
28815 	if (alen == 0)
28816 		return (B_FALSE);	/* Both zero length */
28817 	return (bcmp(abuf, bbuf, alen));
28818 }
28819 
28820 /*
28821  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
28822  * Return B_FALSE if memory allocation fails - don't change any state!
28823  */
28824 boolean_t
28825 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28826     const void *src, uint_t srclen)
28827 {
28828 	void *dst;
28829 
28830 	if (!src_valid)
28831 		srclen = 0;
28832 
28833 	ASSERT(*dstlenp == 0);
28834 	if (src != NULL && srclen != 0) {
28835 		dst = mi_alloc(srclen, BPRI_MED);
28836 		if (dst == NULL)
28837 			return (B_FALSE);
28838 	} else {
28839 		dst = NULL;
28840 	}
28841 	if (*dstp != NULL)
28842 		mi_free(*dstp);
28843 	*dstp = dst;
28844 	*dstlenp = dst == NULL ? 0 : srclen;
28845 	return (B_TRUE);
28846 }
28847 
28848 /*
28849  * Replace what is in *dst, *dstlen with the source.
28850  * Assumes ip_allocbuf has already been called.
28851  */
28852 void
28853 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
28854     const void *src, uint_t srclen)
28855 {
28856 	if (!src_valid)
28857 		srclen = 0;
28858 
28859 	ASSERT(*dstlenp == srclen);
28860 	if (src != NULL && srclen != 0)
28861 		bcopy(src, *dstp, srclen);
28862 }
28863 
28864 /*
28865  * Free the storage pointed to by the members of an ip6_pkt_t.
28866  */
28867 void
28868 ip6_pkt_free(ip6_pkt_t *ipp)
28869 {
28870 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
28871 
28872 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
28873 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
28874 		ipp->ipp_hopopts = NULL;
28875 		ipp->ipp_hopoptslen = 0;
28876 	}
28877 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
28878 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
28879 		ipp->ipp_rtdstopts = NULL;
28880 		ipp->ipp_rtdstoptslen = 0;
28881 	}
28882 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
28883 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
28884 		ipp->ipp_dstopts = NULL;
28885 		ipp->ipp_dstoptslen = 0;
28886 	}
28887 	if (ipp->ipp_fields & IPPF_RTHDR) {
28888 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
28889 		ipp->ipp_rthdr = NULL;
28890 		ipp->ipp_rthdrlen = 0;
28891 	}
28892 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
28893 	    IPPF_RTHDR);
28894 }
28895