xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 14ea4bb7)
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 int ip_modclose_ackwait_ms = 3000;
255 
256 /*
257  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
258  */
259 
260 struct listptr_s {
261 	mblk_t	*lp_head;	/* pointer to the head of the list */
262 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
263 };
264 
265 typedef struct listptr_s listptr_t;
266 
267 /*
268  * This is used by ip_snmp_get_mib2_ip_route_media and
269  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
270  */
271 typedef struct iproutedata_s {
272 	uint_t		ird_idx;
273 	listptr_t	ird_route;	/* ipRouteEntryTable */
274 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
275 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
276 } iproutedata_t;
277 
278 /*
279  * Cluster specific hooks. These should be NULL when booted as a non-cluster
280  */
281 
282 /*
283  * Hook functions to enable cluster networking
284  * On non-clustered systems these vectors must always be NULL.
285  *
286  * Hook function to Check ip specified ip address is a shared ip address
287  * in the cluster
288  *
289  */
290 int (*cl_inet_isclusterwide)(uint8_t protocol,
291     sa_family_t addr_family, uint8_t *laddrp) = NULL;
292 
293 /*
294  * Hook function to generate cluster wide ip fragment identifier
295  */
296 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
297     uint8_t *laddrp, uint8_t *faddrp) = NULL;
298 
299 /*
300  * Synchronization notes:
301  *
302  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
303  * MT level protection given by STREAMS. IP uses a combination of its own
304  * internal serialization mechanism and standard Solaris locking techniques.
305  * The internal serialization is per phyint (no IPMP) or per IPMP group.
306  * This is used to serialize plumbing operations, IPMP operations, certain
307  * multicast operations, most set ioctls, igmp/mld timers etc.
308  *
309  * Plumbing is a long sequence of operations involving message
310  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
311  * involved in plumbing operations. A natural model is to serialize these
312  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
313  * parallel without any interference. But various set ioctls on hme0 are best
314  * serialized. However if the system uses IPMP, the operations are easier if
315  * they are serialized on a per IPMP group basis since IPMP operations
316  * happen across ill's of a group. Thus the lowest common denominator is to
317  * serialize most set ioctls, multicast join/leave operations, IPMP operations
318  * igmp/mld timer operations, and processing of DLPI control messages received
319  * from drivers on a per IPMP group basis. If the system does not employ
320  * IPMP the serialization is on a per phyint basis. This serialization is
321  * provided by the ipsq_t and primitives operating on this. Details can
322  * be found in ip_if.c above the core primitives operating on ipsq_t.
323  *
324  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
325  * Simiarly lookup of an ire by a thread also returns a refheld ire.
326  * In addition ipif's and ill's referenced by the ire are also indirectly
327  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
328  * the ipif's address or netmask change as long as an ipif is refheld
329  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
330  * address of an ipif has to go through the ipsq_t. This ensures that only
331  * 1 such exclusive operation proceeds at any time on the ipif. It then
332  * deletes all ires associated with this ipif, and waits for all refcnts
333  * associated with this ipif to come down to zero. The address is changed
334  * only after the ipif has been quiesced. Then the ipif is brought up again.
335  * More details are described above the comment in ip_sioctl_flags.
336  *
337  * Packet processing is based mostly on IREs and are fully multi-threaded
338  * using standard Solaris MT techniques.
339  *
340  * There are explicit locks in IP to handle:
341  * - The ip_g_head list maintained by mi_open_link() and friends.
342  *
343  * - The reassembly data structures (one lock per hash bucket)
344  *
345  * - conn_lock is meant to protect conn_t fields. The fields actually
346  *   protected by conn_lock are documented in the conn_t definition.
347  *
348  * - ire_lock to protect some of the fields of the ire, IRE tables
349  *   (one lock per hash bucket). Refer to ip_ire.c for details.
350  *
351  * - ndp_g_lock and nce_lock for protecting NCEs.
352  *
353  * - ill_lock protects fields of the ill and ipif. Details in ip.h
354  *
355  * - ill_g_lock: This is a global reader/writer lock. Protects the following
356  *	* The AVL tree based global multi list of all ills.
357  *	* The linked list of all ipifs of an ill
358  *	* The <ill-ipsq> mapping
359  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
360  *	* The illgroup list threaded by ill_group_next.
361  *	* <ill-phyint> association
362  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
363  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
364  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
365  *   will all have to hold the ill_g_lock as writer for the actual duration
366  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
367  *   may be found in the IPMP section.
368  *
369  * - ill_lock:  This is a per ill mutex.
370  *   It protects some members of the ill and is documented below.
371  *   It also protects the <ill-ipsq> mapping
372  *   It also protects the illgroup list threaded by ill_group_next.
373  *   It also protects the <ill-phyint> assoc.
374  *   It also protects the list of ipifs hanging off the ill.
375  *
376  * - ipsq_lock: This is a per ipsq_t mutex lock.
377  *   This protects all the other members of the ipsq struct except
378  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
379  *
380  * - illgrp_lock: This is a per ill_group mutex lock.
381  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
382  *   which dictates which is the next ill in an ill_group that is to be chosen
383  *   for sending outgoing packets, through creation of an IRE_CACHE that
384  *   references this ill.
385  *
386  * - phyint_lock: This is a per phyint mutex lock. Protects just the
387  *   phyint_flags
388  *
389  * - ip_g_nd_lock: This is a global reader/writer lock.
390  *   Any call to nd_load to load a new parameter to the ND table must hold the
391  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
392  *   as reader.
393  *
394  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
395  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
396  *   uniqueness check also done atomically.
397  *
398  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
399  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
400  *   as a writer when adding or deleting elements from these lists, and
401  *   as a reader when walking these lists to send a SADB update to the
402  *   IPsec capable ills.
403  *
404  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
405  *   group list linked by ill_usesrc_grp_next. It also protects the
406  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
407  *   group is being added or deleted.  This lock is taken as a reader when
408  *   walking the list/group(eg: to get the number of members in a usesrc group).
409  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
410  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
411  *   example, it is not necessary to take this lock in the initial portion
412  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
413  *   ip_sioctl_flags since the these operations are executed exclusively and
414  *   that ensures that the "usesrc group state" cannot change. The "usesrc
415  *   group state" change can happen only in the latter part of
416  *   ip_sioctl_slifusesrc and in ill_delete.
417  *
418  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
419  *
420  * To change the <ill-phyint> association, the ill_g_lock must be held
421  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
422  * must be held.
423  *
424  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
425  * and the ill_lock of the ill in question must be held.
426  *
427  * To change the <ill-illgroup> association the ill_g_lock must be held as
428  * writer and the ill_lock of the ill in question must be held.
429  *
430  * To add or delete an ipif from the list of ipifs hanging off the ill,
431  * ill_g_lock (writer) and ill_lock must be held and the thread must be
432  * a writer on the associated ipsq,.
433  *
434  * To add or delete an ill to the system, the ill_g_lock must be held as
435  * writer and the thread must be a writer on the associated ipsq.
436  *
437  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
438  * must be a writer on the associated ipsq.
439  *
440  * Lock hierarchy
441  *
442  * Some lock hierarchy scenarios are listed below.
443  *
444  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
445  * ill_g_lock -> illgrp_lock -> ill_lock
446  * ill_g_lock -> ill_lock(s) -> phyint_lock
447  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
448  * ill_g_lock -> ip_addr_avail_lock
449  * conn_lock -> irb_lock -> ill_lock -> ire_lock
450  * ill_g_lock -> ip_g_nd_lock
451  *
452  * When more than 1 ill lock is needed to be held, all ill lock addresses
453  * are sorted on address and locked starting from highest addressed lock
454  * downward.
455  *
456  * Mobile-IP scenarios
457  *
458  * irb_lock -> ill_lock -> ire_mrtun_lock
459  * irb_lock -> ill_lock -> ire_srcif_table_lock
460  *
461  * IPsec scenarios
462  *
463  * ipsa_lock -> ill_g_lock -> ill_lock
464  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
465  * ipsec_capab_ills_lock -> ipsa_lock
466  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
467  *
468  * Trusted Solaris scenarios
469  *
470  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
471  * igsa_lock -> gcdb_lock
472  * gcgrp_rwlock -> ire_lock
473  * gcgrp_rwlock -> gcdb_lock
474  *
475  *
476  * Routing/forwarding table locking notes:
477  *
478  * Lock acquisition order: Radix tree lock, irb_lock.
479  * Requirements:
480  * i.  Walker must not hold any locks during the walker callback.
481  * ii  Walker must not see a truncated tree during the walk because of any node
482  *     deletion.
483  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
484  *     in many places in the code to walk the irb list. Thus even if all the
485  *     ires in a bucket have been deleted, we still can't free the radix node
486  *     until the ires have actually been inactive'd (freed).
487  *
488  * Tree traversal - Need to hold the global tree lock in read mode.
489  * Before dropping the global tree lock, need to either increment the ire_refcnt
490  * to ensure that the radix node can't be deleted.
491  *
492  * Tree add - Need to hold the global tree lock in write mode to add a
493  * radix node. To prevent the node from being deleted, increment the
494  * irb_refcnt, after the node is added to the tree. The ire itself is
495  * added later while holding the irb_lock, but not the tree lock.
496  *
497  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
498  * All associated ires must be inactive (i.e. freed), and irb_refcnt
499  * must be zero.
500  *
501  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
502  * global tree lock (read mode) for traversal.
503  *
504  * IPSEC notes :
505  *
506  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
507  * in front of the actual packet. For outbound datagrams, the M_CTL
508  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
509  * information used by the IPSEC code for applying the right level of
510  * protection. The information initialized by IP in the ipsec_out_t
511  * is determined by the per-socket policy or global policy in the system.
512  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
513  * ipsec_info.h) which starts out with nothing in it. It gets filled
514  * with the right information if it goes through the AH/ESP code, which
515  * happens if the incoming packet is secure. The information initialized
516  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
517  * the policy requirements needed by per-socket policy or global policy
518  * is met or not.
519  *
520  * If there is both per-socket policy (set using setsockopt) and there
521  * is also global policy match for the 5 tuples of the socket,
522  * ipsec_override_policy() makes the decision of which one to use.
523  *
524  * For fully connected sockets i.e dst, src [addr, port] is known,
525  * conn_policy_cached is set indicating that policy has been cached.
526  * conn_in_enforce_policy may or may not be set depending on whether
527  * there is a global policy match or per-socket policy match.
528  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
529  * Once the right policy is set on the conn_t, policy cannot change for
530  * this socket. This makes life simpler for TCP (UDP ?) where
531  * re-transmissions go out with the same policy. For symmetry, policy
532  * is cached for fully connected UDP sockets also. Thus if policy is cached,
533  * it also implies that policy is latched i.e policy cannot change
534  * on these sockets. As we have the right policy on the conn, we don't
535  * have to lookup global policy for every outbound and inbound datagram
536  * and thus serving as an optimization. Note that a global policy change
537  * does not affect fully connected sockets if they have policy. If fully
538  * connected sockets did not have any policy associated with it, global
539  * policy change may affect them.
540  *
541  * IP Flow control notes:
542  *
543  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
544  * cannot be sent down to the driver by IP, because of a canput failure, IP
545  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
546  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
547  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
548  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
549  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
550  * the queued messages, and removes the conn from the drain list, if all
551  * messages were drained. It also qenables the next conn in the drain list to
552  * continue the drain process.
553  *
554  * In reality the drain list is not a single list, but a configurable number
555  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
556  * list. If the ip_wsrv of the next qenabled conn does not run, because the
557  * stream closes, ip_close takes responsibility to qenable the next conn in
558  * the drain list. The directly called ip_wput path always does a putq, if
559  * it cannot putnext. Thus synchronization problems are handled between
560  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
561  * functions that manipulate this drain list. Furthermore conn_drain_insert
562  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
563  * running on a queue at any time. conn_drain_tail can be simultaneously called
564  * from both ip_wsrv and ip_close.
565  *
566  * IPQOS notes:
567  *
568  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
569  * and IPQoS modules. IPPF includes hooks in IP at different control points
570  * (callout positions) which direct packets to IPQoS modules for policy
571  * processing. Policies, if present, are global.
572  *
573  * The callout positions are located in the following paths:
574  *		o local_in (packets destined for this host)
575  *		o local_out (packets orginating from this host )
576  *		o fwd_in  (packets forwarded by this m/c - inbound)
577  *		o fwd_out (packets forwarded by this m/c - outbound)
578  * Hooks at these callout points can be enabled/disabled using the ndd variable
579  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
580  * By default all the callout positions are enabled.
581  *
582  * Outbound (local_out)
583  * Hooks are placed in ip_wput_ire and ipsec_out_process.
584  *
585  * Inbound (local_in)
586  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
587  * TCP and UDP fanout routines.
588  *
589  * Forwarding (in and out)
590  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
591  *
592  * IP Policy Framework processing (IPPF processing)
593  * Policy processing for a packet is initiated by ip_process, which ascertains
594  * that the classifier (ipgpc) is loaded and configured, failing which the
595  * packet resumes normal processing in IP. If the clasifier is present, the
596  * packet is acted upon by one or more IPQoS modules (action instances), per
597  * filters configured in ipgpc and resumes normal IP processing thereafter.
598  * An action instance can drop a packet in course of its processing.
599  *
600  * A boolean variable, ip_policy, is used in all the fanout routines that can
601  * invoke ip_process for a packet. This variable indicates if the packet should
602  * to be sent for policy processing. The variable is set to B_TRUE by default,
603  * i.e. when the routines are invoked in the normal ip procesing path for a
604  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
605  * ip_policy is set to B_FALSE for all the routines called in these two
606  * functions because, in the former case,  we don't process loopback traffic
607  * currently while in the latter, the packets have already been processed in
608  * icmp_inbound.
609  *
610  * Zones notes:
611  *
612  * The partitioning rules for networking are as follows:
613  * 1) Packets coming from a zone must have a source address belonging to that
614  * zone.
615  * 2) Packets coming from a zone can only be sent on a physical interface on
616  * which the zone has an IP address.
617  * 3) Between two zones on the same machine, packet delivery is only allowed if
618  * there's a matching route for the destination and zone in the forwarding
619  * table.
620  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
621  * different zones can bind to the same port with the wildcard address
622  * (INADDR_ANY).
623  *
624  * The granularity of interface partitioning is at the logical interface level.
625  * Therefore, every zone has its own IP addresses, and incoming packets can be
626  * attributed to a zone unambiguously. A logical interface is placed into a zone
627  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
628  * structure. Rule (1) is implemented by modifying the source address selection
629  * algorithm so that the list of eligible addresses is filtered based on the
630  * sending process zone.
631  *
632  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
633  * across all zones, depending on their type. Here is the break-up:
634  *
635  * IRE type				Shared/exclusive
636  * --------				----------------
637  * IRE_BROADCAST			Exclusive
638  * IRE_DEFAULT (default routes)		Shared (*)
639  * IRE_LOCAL				Exclusive (x)
640  * IRE_LOOPBACK				Exclusive
641  * IRE_PREFIX (net routes)		Shared (*)
642  * IRE_CACHE				Exclusive
643  * IRE_IF_NORESOLVER (interface routes)	Exclusive
644  * IRE_IF_RESOLVER (interface routes)	Exclusive
645  * IRE_HOST (host routes)		Shared (*)
646  *
647  * (*) A zone can only use a default or off-subnet route if the gateway is
648  * directly reachable from the zone, that is, if the gateway's address matches
649  * one of the zone's logical interfaces.
650  *
651  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
652  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
653  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
654  * address of the zone itself (the destination). Since IRE_LOCAL is used
655  * for communication between zones, ip_wput_ire has special logic to set
656  * the right source address when sending using an IRE_LOCAL.
657  *
658  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
659  * ire_cache_lookup restricts loopback using an IRE_LOCAL
660  * between zone to the case when L2 would have conceptually looped the packet
661  * back, i.e. the loopback which is required since neither Ethernet drivers
662  * nor Ethernet hardware loops them back. This is the case when the normal
663  * routes (ignoring IREs with different zoneids) would send out the packet on
664  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
665  * associated.
666  *
667  * Multiple zones can share a common broadcast address; typically all zones
668  * share the 255.255.255.255 address. Incoming as well as locally originated
669  * broadcast packets must be dispatched to all the zones on the broadcast
670  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
671  * since some zones may not be on the 10.16.72/24 network. To handle this, each
672  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
673  * sent to every zone that has an IRE_BROADCAST entry for the destination
674  * address on the input ill, see conn_wantpacket().
675  *
676  * Applications in different zones can join the same multicast group address.
677  * For IPv4, group memberships are per-logical interface, so they're already
678  * inherently part of a zone. For IPv6, group memberships are per-physical
679  * interface, so we distinguish IPv6 group memberships based on group address,
680  * interface and zoneid. In both cases, received multicast packets are sent to
681  * every zone for which a group membership entry exists. On IPv6 we need to
682  * check that the target zone still has an address on the receiving physical
683  * interface; it could have been removed since the application issued the
684  * IPV6_JOIN_GROUP.
685  */
686 
687 /*
688  * Squeue Fanout flags:
689  *	0: No fanout.
690  *	1: Fanout across all squeues
691  */
692 boolean_t	ip_squeue_fanout = 0;
693 
694 /*
695  * Maximum dups allowed per packet.
696  */
697 uint_t ip_max_frag_dups = 10;
698 
699 #define	IS_SIMPLE_IPH(ipha)						\
700 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
701 
702 /* RFC1122 Conformance */
703 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
704 
705 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
706 
707 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
708 
709 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
710 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
711 
712 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714     uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t);
723 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
724 		    zoneid_t zoneid);
725 static mblk_t	*icmp_pkt_err_ok(mblk_t *);
726 static void	icmp_redirect(mblk_t *);
727 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t);
728 
729 static void	ip_arp_news(queue_t *, mblk_t *);
730 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *);
731 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
732 char		*ip_dot_addr(ipaddr_t, char *);
733 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
734 int		ip_close(queue_t *, int);
735 static char	*ip_dot_saddr(uchar_t *, char *);
736 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
737 		    boolean_t, boolean_t, ill_t *, zoneid_t);
738 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, zoneid_t);
740 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
741 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
742 static void	ip_lrput(queue_t *, mblk_t *);
743 ipaddr_t	ip_massage_options(ipha_t *);
744 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
747 		    zoneid_t);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(ipparam_t *, size_t, ipndp_t *,
755 			    size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *);
762 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
763 			    ire_t *);
764 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
765 			    mblk_t *, ipha_t **, ipaddr_t *);
766 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *);
767 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
768 		    uint16_t *);
769 int		ip_snmp_get(queue_t *, mblk_t *);
770 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
771 		    mib2_ipIfStatsEntry_t *);
772 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *);
773 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *);
774 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *);
775 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *);
776 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *);
777 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *);
778 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *);
779 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *);
780 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *);
781 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *);
782 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *);
783 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *);
784 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *);
785 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *);
786 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *);
787 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *);
788 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
789 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
790 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
791 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
792 static boolean_t	ip_source_routed(ipha_t *);
793 static boolean_t	ip_source_route_included(ipha_t *);
794 
795 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
796 		    zoneid_t);
797 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int);
798 static void	ip_wput_local_options(ipha_t *);
799 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
800 		    zoneid_t);
801 
802 static void	conn_drain_init(void);
803 static void	conn_drain_fini(void);
804 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
805 
806 static void	conn_walk_drain(void);
807 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
808     zoneid_t);
809 
810 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
811     zoneid_t);
812 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
813     void *dummy_arg);
814 
815 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
816 
817 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
818     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
819     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
820 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
821 
822 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
823 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
824     caddr_t, cred_t *);
825 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
826     caddr_t cp, cred_t *cr);
827 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
828     cred_t *);
829 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
830     caddr_t cp, cred_t *cr);
831 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
832     cred_t *);
833 static squeue_func_t ip_squeue_switch(int);
834 
835 static void	ip_kstat_init(void);
836 static void	ip_kstat_fini(void);
837 static int	ip_kstat_update(kstat_t *kp, int rw);
838 static void	icmp_kstat_init(void);
839 static void	icmp_kstat_fini(void);
840 static int	icmp_kstat_update(kstat_t *kp, int rw);
841 
842 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
843 
844 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
845     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
846 
847 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
848     ipha_t *, ill_t *, boolean_t);
849 
850 timeout_id_t ip_ire_expire_id;	/* IRE expiration timer. */
851 static clock_t ip_ire_arp_time_elapsed; /* Time since IRE cache last flushed */
852 static clock_t ip_ire_rd_time_elapsed;	/* ... redirect IREs last flushed */
853 static clock_t ip_ire_pmtu_time_elapsed; /* Time since path mtu increase */
854 
855 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
856 clock_t icmp_pkt_err_last = 0;	/* Time since last icmp_pkt_err */
857 uint_t	icmp_pkt_err_sent = 0;	/* Number of packets sent in burst */
858 
859 /* How long, in seconds, we allow frags to hang around. */
860 #define	IP_FRAG_TIMEOUT	60
861 
862 time_t	ip_g_frag_timeout = IP_FRAG_TIMEOUT;
863 clock_t	ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
864 
865 /*
866  * Threshold which determines whether MDT should be used when
867  * generating IP fragments; payload size must be greater than
868  * this threshold for MDT to take place.
869  */
870 #define	IP_WPUT_FRAG_MDT_MIN	32768
871 
872 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
873 
874 /* Protected by ip_mi_lock */
875 static void	*ip_g_head;		/* Instance Data List Head */
876 kmutex_t	ip_mi_lock;		/* Lock for list of instances */
877 
878 /* Only modified during _init and _fini thus no locking is needed. */
879 caddr_t		ip_g_nd;		/* Named Dispatch List Head */
880 
881 
882 static long ip_rput_pullups;
883 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
884 
885 vmem_t *ip_minor_arena;
886 
887 /*
888  * MIB-2 stuff for SNMP (both IP and ICMP)
889  */
890 mib2_ipIfStatsEntry_t	ip_mib;
891 mib2_icmp_t		icmp_mib;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 kstat_t		*ip_mibkp;	/* kstat exporting ip_mib data */
898 kstat_t		*icmp_mibkp;	/* kstat exporting icmp_mib data */
899 
900 uint_t	loopback_packets = 0;
901 
902 /*
903  * Multirouting/CGTP stuff
904  */
905 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
906 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
907 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
908 /* Interval (in ms) between consecutive 'bad MTU' warnings */
909 hrtime_t ip_multirt_log_interval = 1000;
910 /* Time since last warning issued. */
911 static hrtime_t	multirt_bad_mtu_last_time = 0;
912 
913 kmutex_t ip_trash_timer_lock;
914 krwlock_t ip_g_nd_lock;
915 
916 /*
917  * XXX following really should only be in a header. Would need more
918  * header and .c clean up first.
919  */
920 extern optdb_obj_t	ip_opt_obj;
921 
922 ulong_t ip_squeue_enter_unbound = 0;
923 
924 /*
925  * Named Dispatch Parameter Table.
926  * All of these are alterable, within the min/max values given, at run time.
927  */
928 static ipparam_t	lcl_param_arr[] = {
929 	/* min	max	value	name */
930 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
931 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
932 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
933 	{  0,	1,	0,	"ip_respond_to_timestamp"},
934 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
935 	{  0,	1,	1,	"ip_send_redirects"},
936 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
937 	{  0,	10,	0,	"ip_debug"},
938 	{  0,	10,	0,	"ip_mrtdebug"},
939 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
940 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
941 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
942 	{  1,	255,	255,	"ip_def_ttl" },
943 	{  0,	1,	0,	"ip_forward_src_routed"},
944 	{  0,	256,	32,	"ip_wroff_extra" },
945 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
946 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
947 	{  0,	1,	1,	"ip_path_mtu_discovery" },
948 	{  0,	240,	30,	"ip_ignore_delete_time" },
949 	{  0,	1,	0,	"ip_ignore_redirect" },
950 	{  0,	1,	1,	"ip_output_queue" },
951 	{  1,	254,	1,	"ip_broadcast_ttl" },
952 	{  0,	99999,	100,	"ip_icmp_err_interval" },
953 	{  1,	99999,	10,	"ip_icmp_err_burst" },
954 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
955 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
956 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
957 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
958 	{  0,	1,	1,	"icmp_accept_clear_messages" },
959 	{  0,	1,	1,	"igmp_accept_clear_messages" },
960 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
961 				"ip_ndp_delay_first_probe_time"},
962 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
963 				"ip_ndp_max_unicast_solicit"},
964 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
965 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
966 	{  0,	1,	0,	"ip6_forward_src_routed"},
967 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
968 	{  0,	1,	1,	"ip6_send_redirects"},
969 	{  0,	1,	0,	"ip6_ignore_redirect" },
970 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
971 
972 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
973 
974 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
975 
976 	{  0,	1,	1,	"pim_accept_clear_messages" },
977 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
978 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
979 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
980 	{  0,	15,	0,	"ip_policy_mask" },
981 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
982 	{  0,	255,	1,	"ip_multirt_ttl" },
983 	{  0,	1,	1,	"ip_multidata_outbound" },
984 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
985 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
986 	{  0,	1000,	1,	"ip_max_temp_defend" },
987 	{  0,	1000,	3,	"ip_max_defend" },
988 	{  0,	999999,	30,	"ip_defend_interval" },
989 	{  0,	3600000, 300000, "ip_dup_recovery" },
990 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
991 	{  0,	1,	1,	"ip_lso_outbound" },
992 #ifdef DEBUG
993 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
994 #endif
995 };
996 
997 ipparam_t	*ip_param_arr = lcl_param_arr;
998 
999 /* Extended NDP table */
1000 static ipndp_t	lcl_ndp_arr[] = {
1001 	/* getf			setf		data			name */
1002 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ip_g_forward,
1003 	    "ip_forwarding" },
1004 	{  ip_param_generic_get,	ip_forward_set,	(caddr_t)&ipv6_forward,
1005 	    "ip6_forwarding" },
1006 	{  ip_ill_report,	NULL,		NULL,
1007 	    "ip_ill_status" },
1008 	{  ip_ipif_report,	NULL,		NULL,
1009 	    "ip_ipif_status" },
1010 	{  ip_ire_report,	NULL,		NULL,
1011 	    "ipv4_ire_status" },
1012 	{  ip_ire_report_mrtun,	NULL,		NULL,
1013 	    "ipv4_mrtun_ire_status" },
1014 	{  ip_ire_report_srcif,	NULL,		NULL,
1015 	    "ipv4_srcif_ire_status" },
1016 	{  ip_ire_report_v6,	NULL,		NULL,
1017 	    "ipv6_ire_status" },
1018 	{  ip_conn_report,	NULL,		NULL,
1019 	    "ip_conn_status" },
1020 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
1021 	    "ip_rput_pullups" },
1022 	{  ndp_report,		NULL,		NULL,
1023 	    "ip_ndp_cache_report" },
1024 	{  ip_srcid_report,	NULL,		NULL,
1025 	    "ip_srcid_status" },
1026 	{ ip_param_generic_get, ip_squeue_profile_set,
1027 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
1028 	{ ip_param_generic_get, ip_squeue_bind_set,
1029 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
1030 	{ ip_param_generic_get, ip_input_proc_set,
1031 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1032 	{ ip_param_generic_get, ip_int_set,
1033 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1034 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, (caddr_t)&ip_cgtp_filter,
1035 	    "ip_cgtp_filter" },
1036 	{ ip_param_generic_get, ip_int_set,
1037 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" }
1038 };
1039 
1040 /*
1041  * ip_g_forward controls IP forwarding.  It takes two values:
1042  *	0: IP_FORWARD_NEVER	Don't forward packets ever.
1043  *	1: IP_FORWARD_ALWAYS	Forward packets for elsewhere.
1044  *
1045  * RFC1122 says there must be a configuration switch to control forwarding,
1046  * but that the default MUST be to not forward packets ever.  Implicit
1047  * control based on configuration of multiple interfaces MUST NOT be
1048  * implemented (Section 3.1).  SunOS 4.1 did provide the "automatic" capability
1049  * and, in fact, it was the default.  That capability is now provided in the
1050  * /etc/rc2.d/S69inet script.
1051  */
1052 int ip_g_forward = IP_FORWARD_DEFAULT;
1053 
1054 /* It also has an IPv6 counterpart. */
1055 
1056 int ipv6_forward = IP_FORWARD_DEFAULT;
1057 
1058 /*
1059  * Table of IP ioctls encoding the various properties of the ioctl and
1060  * indexed based on the last byte of the ioctl command. Occasionally there
1061  * is a clash, and there is more than 1 ioctl with the same last byte.
1062  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1063  * ioctls are encoded in the misc table. An entry in the ndx table is
1064  * retrieved by indexing on the last byte of the ioctl command and comparing
1065  * the ioctl command with the value in the ndx table. In the event of a
1066  * mismatch the misc table is then searched sequentially for the desired
1067  * ioctl command.
1068  *
1069  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1070  */
1071 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1072 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1084 			MISC_CMD, ip_siocaddrt, NULL },
1085 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1086 			MISC_CMD, ip_siocdelrt, NULL },
1087 
1088 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1089 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1090 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1091 			IF_CMD, ip_sioctl_get_addr, NULL },
1092 
1093 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1094 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1095 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1096 			IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
1098 
1099 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1100 			IPI_PRIV | IPI_WR | IPI_REPL,
1101 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1102 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1103 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1104 			IF_CMD, ip_sioctl_get_flags, NULL },
1105 
1106 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 
1109 	/* copyin size cannot be coded for SIOCGIFCONF */
1110 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1111 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1112 
1113 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1114 			IF_CMD, ip_sioctl_mtu, NULL },
1115 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1116 			IF_CMD, ip_sioctl_get_mtu, NULL },
1117 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1118 			IPI_GET_CMD | IPI_REPL,
1119 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1120 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1121 			IF_CMD, ip_sioctl_brdaddr, NULL },
1122 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1123 			IPI_GET_CMD | IPI_REPL,
1124 			IF_CMD, ip_sioctl_get_netmask, NULL },
1125 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1126 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1127 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1128 			IPI_GET_CMD | IPI_REPL,
1129 			IF_CMD, ip_sioctl_get_metric, NULL },
1130 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1131 			IF_CMD, ip_sioctl_metric, NULL },
1132 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 
1134 	/* See 166-168 below for extended SIOC*XARP ioctls */
1135 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1136 			MISC_CMD, ip_sioctl_arp, NULL },
1137 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1138 			MISC_CMD, ip_sioctl_arp, NULL },
1139 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1140 			MISC_CMD, ip_sioctl_arp, NULL },
1141 
1142 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1154 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1155 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1156 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1157 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1158 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1159 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1160 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1161 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1162 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 
1164 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1165 			MISC_CMD, if_unitsel, if_unitsel_restart },
1166 
1167 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1168 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1169 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 
1186 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1187 			IPI_PRIV | IPI_WR | IPI_MODOK,
1188 			IF_CMD, ip_sioctl_sifname, NULL },
1189 
1190 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1191 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1192 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1193 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1194 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1195 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1196 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1197 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1198 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1199 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1200 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1201 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1202 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1203 
1204 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1205 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1206 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1207 			IF_CMD, ip_sioctl_get_muxid, NULL },
1208 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1209 			IPI_PRIV | IPI_WR | IPI_REPL,
1210 			IF_CMD, ip_sioctl_muxid, NULL },
1211 
1212 	/* Both if and lif variants share same func */
1213 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1214 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1215 	/* Both if and lif variants share same func */
1216 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1217 			IPI_PRIV | IPI_WR | IPI_REPL,
1218 			IF_CMD, ip_sioctl_slifindex, NULL },
1219 
1220 	/* copyin size cannot be coded for SIOCGIFCONF */
1221 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1222 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1223 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1224 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1225 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1226 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1227 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1228 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1229 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1230 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1231 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1232 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1233 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1234 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1235 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1236 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1237 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1238 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 
1241 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1242 			IPI_PRIV | IPI_WR | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_removeif,
1244 			ip_sioctl_removeif_restart },
1245 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1246 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_addif, NULL },
1248 #define	SIOCLIFADDR_NDX 112
1249 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1250 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1251 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1252 			IPI_GET_CMD | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_get_addr, NULL },
1254 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1256 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1259 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1260 			IPI_PRIV | IPI_WR | IPI_REPL,
1261 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1262 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1263 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1264 			LIF_CMD, ip_sioctl_get_flags, NULL },
1265 
1266 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1267 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1268 
1269 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1270 			ip_sioctl_get_lifconf, NULL },
1271 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1272 			LIF_CMD, ip_sioctl_mtu, NULL },
1273 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1274 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1275 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1276 			IPI_GET_CMD | IPI_REPL,
1277 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1278 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1279 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1280 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1281 			IPI_GET_CMD | IPI_REPL,
1282 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1283 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1285 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1286 			IPI_GET_CMD | IPI_REPL,
1287 			LIF_CMD, ip_sioctl_get_metric, NULL },
1288 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_metric, NULL },
1290 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1291 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1292 			LIF_CMD, ip_sioctl_slifname,
1293 			ip_sioctl_slifname_restart },
1294 
1295 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1296 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1297 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1298 			IPI_GET_CMD | IPI_REPL,
1299 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1300 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1301 			IPI_PRIV | IPI_WR | IPI_REPL,
1302 			LIF_CMD, ip_sioctl_muxid, NULL },
1303 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1304 			IPI_GET_CMD | IPI_REPL,
1305 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1306 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1307 			IPI_PRIV | IPI_WR | IPI_REPL,
1308 			LIF_CMD, ip_sioctl_slifindex, 0 },
1309 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1310 			LIF_CMD, ip_sioctl_token, NULL },
1311 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1312 			IPI_GET_CMD | IPI_REPL,
1313 			LIF_CMD, ip_sioctl_get_token, NULL },
1314 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1315 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1316 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1317 			IPI_GET_CMD | IPI_REPL,
1318 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1319 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1320 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1321 
1322 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1323 			IPI_GET_CMD | IPI_REPL,
1324 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1325 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1326 			LIF_CMD, ip_siocdelndp_v6, NULL },
1327 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1328 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1329 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1330 			LIF_CMD, ip_siocsetndp_v6, NULL },
1331 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1332 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1333 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1334 			MISC_CMD, ip_sioctl_tonlink, NULL },
1335 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1336 			MISC_CMD, ip_sioctl_tmysite, NULL },
1337 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1338 			TUN_CMD, ip_sioctl_tunparam, NULL },
1339 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1340 			IPI_PRIV | IPI_WR,
1341 			TUN_CMD, ip_sioctl_tunparam, NULL },
1342 
1343 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1344 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1345 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1346 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1347 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1348 
1349 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1350 			IPI_PRIV | IPI_WR | IPI_REPL,
1351 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1352 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1353 			IPI_PRIV | IPI_WR | IPI_REPL,
1354 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1355 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1356 			IPI_PRIV | IPI_WR,
1357 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1358 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1359 			IPI_GET_CMD | IPI_REPL,
1360 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1361 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1362 			IPI_GET_CMD | IPI_REPL,
1363 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1364 
1365 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1366 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1367 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1368 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1369 
1370 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1371 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1372 
1373 	/* These are handled in ip_sioctl_copyin_setup itself */
1374 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1375 			MISC_CMD, NULL, NULL },
1376 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1377 			MISC_CMD, NULL, NULL },
1378 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1379 
1380 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1381 			ip_sioctl_get_lifconf, NULL },
1382 
1383 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1384 			MISC_CMD, ip_sioctl_xarp, NULL },
1385 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1386 			MISC_CMD, ip_sioctl_xarp, NULL },
1387 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1388 			MISC_CMD, ip_sioctl_xarp, NULL },
1389 
1390 	/* SIOCPOPSOCKFS is not handled by IP */
1391 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1392 
1393 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1394 			IPI_GET_CMD | IPI_REPL,
1395 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1396 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1397 			IPI_PRIV | IPI_WR | IPI_REPL,
1398 			LIF_CMD, ip_sioctl_slifzone,
1399 			ip_sioctl_slifzone_restart },
1400 	/* 172-174 are SCTP ioctls and not handled by IP */
1401 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1402 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1403 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1404 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1405 			IPI_GET_CMD, LIF_CMD,
1406 			ip_sioctl_get_lifusesrc, 0 },
1407 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1408 			IPI_PRIV | IPI_WR,
1409 			LIF_CMD, ip_sioctl_slifusesrc,
1410 			NULL },
1411 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1412 			ip_sioctl_get_lifsrcof, NULL },
1413 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1414 			MISC_CMD, ip_sioctl_msfilter, NULL },
1415 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1416 			MISC_CMD, ip_sioctl_msfilter, NULL },
1417 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1418 			MISC_CMD, ip_sioctl_msfilter, NULL },
1419 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1420 			MISC_CMD, ip_sioctl_msfilter, NULL },
1421 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1422 			ip_sioctl_set_ipmpfailback, NULL }
1423 };
1424 
1425 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1426 
1427 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1428 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1429 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1430 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1431 		TUN_CMD, ip_sioctl_tunparam, NULL },
1432 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1433 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1434 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1435 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1436 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1437 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1438 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1439 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1440 		MISC_CMD, mrt_ioctl},
1441 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1442 		MISC_CMD, mrt_ioctl},
1443 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1444 		MISC_CMD, mrt_ioctl}
1445 };
1446 
1447 int ip_misc_ioctl_count =
1448     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1449 
1450 static  idl_t *conn_drain_list;		/* The array of conn drain lists */
1451 static  uint_t conn_drain_list_cnt;	/* Total count of conn_drain_list */
1452 static  int    conn_drain_list_index;	/* Next drain_list to be used */
1453 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1454 					/* Settable in /etc/system */
1455 uint_t	ip_redirect_cnt;		/* Num of redirect routes in ftable */
1456 
1457 /* Defined in ip_ire.c */
1458 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1459 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1460 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1461 
1462 static nv_t	ire_nv_arr[] = {
1463 	{ IRE_BROADCAST, "BROADCAST" },
1464 	{ IRE_LOCAL, "LOCAL" },
1465 	{ IRE_LOOPBACK, "LOOPBACK" },
1466 	{ IRE_CACHE, "CACHE" },
1467 	{ IRE_DEFAULT, "DEFAULT" },
1468 	{ IRE_PREFIX, "PREFIX" },
1469 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1470 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1471 	{ IRE_HOST, "HOST" },
1472 	{ 0 }
1473 };
1474 
1475 nv_t	*ire_nv_tbl = ire_nv_arr;
1476 
1477 /* Defined in ip_if.c, protect the list of IPsec capable ills */
1478 extern krwlock_t ipsec_capab_ills_lock;
1479 
1480 /* Defined in ip_netinfo.c */
1481 extern ddi_taskq_t	*eventq_queue_nic;
1482 
1483 /* Packet dropper for IP IPsec processing failures */
1484 ipdropper_t ip_dropper;
1485 
1486 /* Simple ICMP IP Header Template */
1487 static ipha_t icmp_ipha = {
1488 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1489 };
1490 
1491 struct module_info ip_mod_info = {
1492 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1493 };
1494 
1495 /*
1496  * Duplicate static symbols within a module confuses mdb; so we avoid the
1497  * problem by making the symbols here distinct from those in udp.c.
1498  */
1499 
1500 static struct qinit iprinit = {
1501 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1502 	&ip_mod_info
1503 };
1504 
1505 static struct qinit ipwinit = {
1506 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1507 	&ip_mod_info
1508 };
1509 
1510 static struct qinit iplrinit = {
1511 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1512 	&ip_mod_info
1513 };
1514 
1515 static struct qinit iplwinit = {
1516 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1517 	&ip_mod_info
1518 };
1519 
1520 struct streamtab ipinfo = {
1521 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1522 };
1523 
1524 #ifdef	DEBUG
1525 static boolean_t skip_sctp_cksum = B_FALSE;
1526 #endif
1527 
1528 /*
1529  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1530  * ip_rput_v6(), ip_output(), etc.  If the message
1531  * block already has a M_CTL at the front of it, then simply set the zoneid
1532  * appropriately.
1533  */
1534 mblk_t *
1535 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid)
1536 {
1537 	mblk_t		*first_mp;
1538 	ipsec_out_t	*io;
1539 
1540 	ASSERT(zoneid != ALL_ZONES);
1541 	if (mp->b_datap->db_type == M_CTL) {
1542 		io = (ipsec_out_t *)mp->b_rptr;
1543 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1544 		io->ipsec_out_zoneid = zoneid;
1545 		return (mp);
1546 	}
1547 
1548 	first_mp = ipsec_alloc_ipsec_out();
1549 	if (first_mp == NULL)
1550 		return (NULL);
1551 	io = (ipsec_out_t *)first_mp->b_rptr;
1552 	/* This is not a secure packet */
1553 	io->ipsec_out_secure = B_FALSE;
1554 	io->ipsec_out_zoneid = zoneid;
1555 	first_mp->b_cont = mp;
1556 	return (first_mp);
1557 }
1558 
1559 /*
1560  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1561  */
1562 mblk_t *
1563 ip_copymsg(mblk_t *mp)
1564 {
1565 	mblk_t *nmp;
1566 	ipsec_info_t *in;
1567 
1568 	if (mp->b_datap->db_type != M_CTL)
1569 		return (copymsg(mp));
1570 
1571 	in = (ipsec_info_t *)mp->b_rptr;
1572 
1573 	/*
1574 	 * Note that M_CTL is also used for delivering ICMP error messages
1575 	 * upstream to transport layers.
1576 	 */
1577 	if (in->ipsec_info_type != IPSEC_OUT &&
1578 	    in->ipsec_info_type != IPSEC_IN)
1579 		return (copymsg(mp));
1580 
1581 	nmp = copymsg(mp->b_cont);
1582 
1583 	if (in->ipsec_info_type == IPSEC_OUT)
1584 		return (ipsec_out_tag(mp, nmp));
1585 	else
1586 		return (ipsec_in_tag(mp, nmp));
1587 }
1588 
1589 /* Generate an ICMP fragmentation needed message. */
1590 static void
1591 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid)
1592 {
1593 	icmph_t	icmph;
1594 	mblk_t *first_mp;
1595 	boolean_t mctl_present;
1596 
1597 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1598 
1599 	if (!(mp = icmp_pkt_err_ok(mp))) {
1600 		if (mctl_present)
1601 			freeb(first_mp);
1602 		return;
1603 	}
1604 
1605 	bzero(&icmph, sizeof (icmph_t));
1606 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1607 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1608 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1609 	BUMP_MIB(&icmp_mib, icmpOutFragNeeded);
1610 	BUMP_MIB(&icmp_mib, icmpOutDestUnreachs);
1611 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid);
1612 }
1613 
1614 /*
1615  * icmp_inbound deals with ICMP messages in the following ways.
1616  *
1617  * 1) It needs to send a reply back and possibly delivering it
1618  *    to the "interested" upper clients.
1619  * 2) It needs to send it to the upper clients only.
1620  * 3) It needs to change some values in IP only.
1621  * 4) It needs to change some values in IP and upper layers e.g TCP.
1622  *
1623  * We need to accomodate icmp messages coming in clear until we get
1624  * everything secure from the wire. If icmp_accept_clear_messages
1625  * is zero we check with the global policy and act accordingly. If
1626  * it is non-zero, we accept the message without any checks. But
1627  * *this does not mean* that this will be delivered to the upper
1628  * clients. By accepting we might send replies back, change our MTU
1629  * value etc. but delivery to the ULP/clients depends on their policy
1630  * dispositions.
1631  *
1632  * We handle the above 4 cases in the context of IPSEC in the
1633  * following way :
1634  *
1635  * 1) Send the reply back in the same way as the request came in.
1636  *    If it came in encrypted, it goes out encrypted. If it came in
1637  *    clear, it goes out in clear. Thus, this will prevent chosen
1638  *    plain text attack.
1639  * 2) The client may or may not expect things to come in secure.
1640  *    If it comes in secure, the policy constraints are checked
1641  *    before delivering it to the upper layers. If it comes in
1642  *    clear, ipsec_inbound_accept_clear will decide whether to
1643  *    accept this in clear or not. In both the cases, if the returned
1644  *    message (IP header + 8 bytes) that caused the icmp message has
1645  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1646  *    sending up. If there are only 8 bytes of returned message, then
1647  *    upper client will not be notified.
1648  * 3) Check with global policy to see whether it matches the constaints.
1649  *    But this will be done only if icmp_accept_messages_in_clear is
1650  *    zero.
1651  * 4) If we need to change both in IP and ULP, then the decision taken
1652  *    while affecting the values in IP and while delivering up to TCP
1653  *    should be the same.
1654  *
1655  * 	There are two cases.
1656  *
1657  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1658  *	   failed), we will not deliver it to the ULP, even though they
1659  *	   are *willing* to accept in *clear*. This is fine as our global
1660  *	   disposition to icmp messages asks us reject the datagram.
1661  *
1662  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1663  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1664  *	   to deliver it to ULP (policy failed), it can lead to
1665  *	   consistency problems. The cases known at this time are
1666  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1667  *	   values :
1668  *
1669  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1670  *	     and Upper layer rejects. Then the communication will
1671  *	     come to a stop. This is solved by making similar decisions
1672  *	     at both levels. Currently, when we are unable to deliver
1673  *	     to the Upper Layer (due to policy failures) while IP has
1674  *	     adjusted ire_max_frag, the next outbound datagram would
1675  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1676  *	     will be with the right level of protection. Thus the right
1677  *	     value will be communicated even if we are not able to
1678  *	     communicate when we get from the wire initially. But this
1679  *	     assumes there would be at least one outbound datagram after
1680  *	     IP has adjusted its ire_max_frag value. To make things
1681  *	     simpler, we accept in clear after the validation of
1682  *	     AH/ESP headers.
1683  *
1684  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1685  *	     upper layer depending on the level of protection the upper
1686  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1687  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1688  *	     should be accepted in clear when the Upper layer expects secure.
1689  *	     Thus the communication may get aborted by some bad ICMP
1690  *	     packets.
1691  *
1692  * IPQoS Notes:
1693  * The only instance when a packet is sent for processing is when there
1694  * isn't an ICMP client and if we are interested in it.
1695  * If there is a client, IPPF processing will take place in the
1696  * ip_fanout_proto routine.
1697  *
1698  * Zones notes:
1699  * The packet is only processed in the context of the specified zone: typically
1700  * only this zone will reply to an echo request, and only interested clients in
1701  * this zone will receive a copy of the packet. This means that the caller must
1702  * call icmp_inbound() for each relevant zone.
1703  */
1704 static void
1705 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1706     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1707     ill_t *recv_ill, zoneid_t zoneid)
1708 {
1709 	icmph_t	*icmph;
1710 	ipha_t	*ipha;
1711 	int	iph_hdr_length;
1712 	int	hdr_length;
1713 	boolean_t	interested;
1714 	uint32_t	ts;
1715 	uchar_t	*wptr;
1716 	ipif_t	*ipif;
1717 	mblk_t *first_mp;
1718 	ipsec_in_t *ii;
1719 	ire_t *src_ire;
1720 	boolean_t onlink;
1721 	timestruc_t now;
1722 	uint32_t ill_index;
1723 
1724 	ASSERT(ill != NULL);
1725 
1726 	first_mp = mp;
1727 	if (mctl_present) {
1728 		mp = first_mp->b_cont;
1729 		ASSERT(mp != NULL);
1730 	}
1731 
1732 	ipha = (ipha_t *)mp->b_rptr;
1733 	if (icmp_accept_clear_messages == 0) {
1734 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1735 		    ipha, NULL, mctl_present);
1736 		if (first_mp == NULL)
1737 			return;
1738 	}
1739 
1740 	/*
1741 	 * On a labeled system, we have to check whether the zone itself is
1742 	 * permitted to receive raw traffic.
1743 	 */
1744 	if (is_system_labeled()) {
1745 		if (zoneid == ALL_ZONES)
1746 			zoneid = tsol_packet_to_zoneid(mp);
1747 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1748 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1749 			    zoneid));
1750 			BUMP_MIB(&icmp_mib, icmpInErrors);
1751 			freemsg(first_mp);
1752 			return;
1753 		}
1754 	}
1755 
1756 	/*
1757 	 * We have accepted the ICMP message. It means that we will
1758 	 * respond to the packet if needed. It may not be delivered
1759 	 * to the upper client depending on the policy constraints
1760 	 * and the disposition in ipsec_inbound_accept_clear.
1761 	 */
1762 
1763 	ASSERT(ill != NULL);
1764 
1765 	BUMP_MIB(&icmp_mib, icmpInMsgs);
1766 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1767 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1768 		/* Last chance to get real. */
1769 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1770 			BUMP_MIB(&icmp_mib, icmpInErrors);
1771 			freemsg(first_mp);
1772 			return;
1773 		}
1774 		/* Refresh iph following the pullup. */
1775 		ipha = (ipha_t *)mp->b_rptr;
1776 	}
1777 	/* ICMP header checksum, including checksum field, should be zero. */
1778 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1779 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1780 		BUMP_MIB(&icmp_mib, icmpInCksumErrs);
1781 		freemsg(first_mp);
1782 		return;
1783 	}
1784 	/* The IP header will always be a multiple of four bytes */
1785 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1786 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1787 	    icmph->icmph_code));
1788 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1789 	/* We will set "interested" to "true" if we want a copy */
1790 	interested = B_FALSE;
1791 	switch (icmph->icmph_type) {
1792 	case ICMP_ECHO_REPLY:
1793 		BUMP_MIB(&icmp_mib, icmpInEchoReps);
1794 		break;
1795 	case ICMP_DEST_UNREACHABLE:
1796 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1797 			BUMP_MIB(&icmp_mib, icmpInFragNeeded);
1798 		interested = B_TRUE;	/* Pass up to transport */
1799 		BUMP_MIB(&icmp_mib, icmpInDestUnreachs);
1800 		break;
1801 	case ICMP_SOURCE_QUENCH:
1802 		interested = B_TRUE;	/* Pass up to transport */
1803 		BUMP_MIB(&icmp_mib, icmpInSrcQuenchs);
1804 		break;
1805 	case ICMP_REDIRECT:
1806 		if (!ip_ignore_redirect)
1807 			interested = B_TRUE;
1808 		BUMP_MIB(&icmp_mib, icmpInRedirects);
1809 		break;
1810 	case ICMP_ECHO_REQUEST:
1811 		/*
1812 		 * Whether to respond to echo requests that come in as IP
1813 		 * broadcasts or as IP multicast is subject to debate
1814 		 * (what isn't?).  We aim to please, you pick it.
1815 		 * Default is do it.
1816 		 */
1817 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1818 			/* unicast: always respond */
1819 			interested = B_TRUE;
1820 		} else if (CLASSD(ipha->ipha_dst)) {
1821 			/* multicast: respond based on tunable */
1822 			interested = ip_g_resp_to_echo_mcast;
1823 		} else if (broadcast) {
1824 			/* broadcast: respond based on tunable */
1825 			interested = ip_g_resp_to_echo_bcast;
1826 		}
1827 		BUMP_MIB(&icmp_mib, icmpInEchos);
1828 		break;
1829 	case ICMP_ROUTER_ADVERTISEMENT:
1830 	case ICMP_ROUTER_SOLICITATION:
1831 		break;
1832 	case ICMP_TIME_EXCEEDED:
1833 		interested = B_TRUE;	/* Pass up to transport */
1834 		BUMP_MIB(&icmp_mib, icmpInTimeExcds);
1835 		break;
1836 	case ICMP_PARAM_PROBLEM:
1837 		interested = B_TRUE;	/* Pass up to transport */
1838 		BUMP_MIB(&icmp_mib, icmpInParmProbs);
1839 		break;
1840 	case ICMP_TIME_STAMP_REQUEST:
1841 		/* Response to Time Stamp Requests is local policy. */
1842 		if (ip_g_resp_to_timestamp &&
1843 		    /* So is whether to respond if it was an IP broadcast. */
1844 		    (!broadcast || ip_g_resp_to_timestamp_bcast)) {
1845 			int tstamp_len = 3 * sizeof (uint32_t);
1846 
1847 			if (wptr +  tstamp_len > mp->b_wptr) {
1848 				if (!pullupmsg(mp, wptr + tstamp_len -
1849 				    mp->b_rptr)) {
1850 					BUMP_MIB(ill->ill_ip_mib,
1851 					    ipIfStatsInDiscards);
1852 					freemsg(first_mp);
1853 					return;
1854 				}
1855 				/* Refresh ipha following the pullup. */
1856 				ipha = (ipha_t *)mp->b_rptr;
1857 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1858 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1859 			}
1860 			interested = B_TRUE;
1861 		}
1862 		BUMP_MIB(&icmp_mib, icmpInTimestamps);
1863 		break;
1864 	case ICMP_TIME_STAMP_REPLY:
1865 		BUMP_MIB(&icmp_mib, icmpInTimestampReps);
1866 		break;
1867 	case ICMP_INFO_REQUEST:
1868 		/* Per RFC 1122 3.2.2.7, ignore this. */
1869 	case ICMP_INFO_REPLY:
1870 		break;
1871 	case ICMP_ADDRESS_MASK_REQUEST:
1872 		if ((ip_respond_to_address_mask_broadcast || !broadcast) &&
1873 		    /* TODO m_pullup of complete header? */
1874 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1875 			interested = B_TRUE;
1876 		BUMP_MIB(&icmp_mib, icmpInAddrMasks);
1877 		break;
1878 	case ICMP_ADDRESS_MASK_REPLY:
1879 		BUMP_MIB(&icmp_mib, icmpInAddrMaskReps);
1880 		break;
1881 	default:
1882 		interested = B_TRUE;	/* Pass up to transport */
1883 		BUMP_MIB(&icmp_mib, icmpInUnknowns);
1884 		break;
1885 	}
1886 	/* See if there is an ICMP client. */
1887 	if (ipcl_proto_search(IPPROTO_ICMP) != NULL) {
1888 		/* If there is an ICMP client and we want one too, copy it. */
1889 		mblk_t *first_mp1;
1890 
1891 		if (!interested) {
1892 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1893 			    ip_policy, recv_ill, zoneid);
1894 			return;
1895 		}
1896 		first_mp1 = ip_copymsg(first_mp);
1897 		if (first_mp1 != NULL) {
1898 			ip_fanout_proto(q, first_mp1, ill, ipha,
1899 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1900 		}
1901 	} else if (!interested) {
1902 		freemsg(first_mp);
1903 		return;
1904 	} else {
1905 		/*
1906 		 * Initiate policy processing for this packet if ip_policy
1907 		 * is true.
1908 		 */
1909 		if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
1910 			ill_index = ill->ill_phyint->phyint_ifindex;
1911 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1912 			if (mp == NULL) {
1913 				if (mctl_present) {
1914 					freeb(first_mp);
1915 				}
1916 				BUMP_MIB(&icmp_mib, icmpInErrors);
1917 				return;
1918 			}
1919 		}
1920 	}
1921 	/* We want to do something with it. */
1922 	/* Check db_ref to make sure we can modify the packet. */
1923 	if (mp->b_datap->db_ref > 1) {
1924 		mblk_t	*first_mp1;
1925 
1926 		first_mp1 = ip_copymsg(first_mp);
1927 		freemsg(first_mp);
1928 		if (!first_mp1) {
1929 			BUMP_MIB(&icmp_mib, icmpOutDrops);
1930 			return;
1931 		}
1932 		first_mp = first_mp1;
1933 		if (mctl_present) {
1934 			mp = first_mp->b_cont;
1935 			ASSERT(mp != NULL);
1936 		} else {
1937 			mp = first_mp;
1938 		}
1939 		ipha = (ipha_t *)mp->b_rptr;
1940 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1941 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1942 	}
1943 	switch (icmph->icmph_type) {
1944 	case ICMP_ADDRESS_MASK_REQUEST:
1945 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1946 		if (ipif == NULL) {
1947 			freemsg(first_mp);
1948 			return;
1949 		}
1950 		/*
1951 		 * outging interface must be IPv4
1952 		 */
1953 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1954 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1955 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1956 		ipif_refrele(ipif);
1957 		BUMP_MIB(&icmp_mib, icmpOutAddrMaskReps);
1958 		break;
1959 	case ICMP_ECHO_REQUEST:
1960 		icmph->icmph_type = ICMP_ECHO_REPLY;
1961 		BUMP_MIB(&icmp_mib, icmpOutEchoReps);
1962 		break;
1963 	case ICMP_TIME_STAMP_REQUEST: {
1964 		uint32_t *tsp;
1965 
1966 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1967 		tsp = (uint32_t *)wptr;
1968 		tsp++;		/* Skip past 'originate time' */
1969 		/* Compute # of milliseconds since midnight */
1970 		gethrestime(&now);
1971 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1972 		    now.tv_nsec / (NANOSEC / MILLISEC);
1973 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1974 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1975 		BUMP_MIB(&icmp_mib, icmpOutTimestampReps);
1976 		break;
1977 	}
1978 	default:
1979 		ipha = (ipha_t *)&icmph[1];
1980 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1981 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1982 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1983 				freemsg(first_mp);
1984 				return;
1985 			}
1986 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1987 			ipha = (ipha_t *)&icmph[1];
1988 		}
1989 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1990 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1991 			freemsg(first_mp);
1992 			return;
1993 		}
1994 		hdr_length = IPH_HDR_LENGTH(ipha);
1995 		if (hdr_length < sizeof (ipha_t)) {
1996 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1997 			freemsg(first_mp);
1998 			return;
1999 		}
2000 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
2001 			if (!pullupmsg(mp,
2002 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
2003 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2004 				freemsg(first_mp);
2005 				return;
2006 			}
2007 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2008 			ipha = (ipha_t *)&icmph[1];
2009 		}
2010 		switch (icmph->icmph_type) {
2011 		case ICMP_REDIRECT:
2012 			/*
2013 			 * As there is no upper client to deliver, we don't
2014 			 * need the first_mp any more.
2015 			 */
2016 			if (mctl_present) {
2017 				freeb(first_mp);
2018 			}
2019 			icmp_redirect(mp);
2020 			return;
2021 		case ICMP_DEST_UNREACHABLE:
2022 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
2023 				if (!icmp_inbound_too_big(icmph, ipha, ill,
2024 				    zoneid, mp, iph_hdr_length)) {
2025 					freemsg(first_mp);
2026 					return;
2027 				}
2028 				/*
2029 				 * icmp_inbound_too_big() may alter mp.
2030 				 * Resynch ipha and icmph accordingly.
2031 				 */
2032 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2033 				ipha = (ipha_t *)&icmph[1];
2034 			}
2035 			/* FALLTHRU */
2036 		default :
2037 			/*
2038 			 * IPQoS notes: Since we have already done IPQoS
2039 			 * processing we don't want to do it again in
2040 			 * the fanout routines called by
2041 			 * icmp_inbound_error_fanout, hence the last
2042 			 * argument, ip_policy, is B_FALSE.
2043 			 */
2044 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
2045 			    ipha, iph_hdr_length, hdr_length, mctl_present,
2046 			    B_FALSE, recv_ill, zoneid);
2047 		}
2048 		return;
2049 	}
2050 	/* Send out an ICMP packet */
2051 	icmph->icmph_checksum = 0;
2052 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
2053 	if (icmph->icmph_checksum == 0)
2054 		icmph->icmph_checksum = 0xFFFF;
2055 	if (broadcast || CLASSD(ipha->ipha_dst)) {
2056 		ipif_t	*ipif_chosen;
2057 		/*
2058 		 * Make it look like it was directed to us, so we don't look
2059 		 * like a fool with a broadcast or multicast source address.
2060 		 */
2061 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2062 		/*
2063 		 * Make sure that we haven't grabbed an interface that's DOWN.
2064 		 */
2065 		if (ipif != NULL) {
2066 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2067 			    ipha->ipha_src, zoneid);
2068 			if (ipif_chosen != NULL) {
2069 				ipif_refrele(ipif);
2070 				ipif = ipif_chosen;
2071 			}
2072 		}
2073 		if (ipif == NULL) {
2074 			ip0dbg(("icmp_inbound: "
2075 			    "No source for broadcast/multicast:\n"
2076 			    "\tsrc 0x%x dst 0x%x ill %p "
2077 			    "ipif_lcl_addr 0x%x\n",
2078 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2079 			    (void *)ill,
2080 			    ill->ill_ipif->ipif_lcl_addr));
2081 			freemsg(first_mp);
2082 			return;
2083 		}
2084 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2085 		ipha->ipha_dst = ipif->ipif_src_addr;
2086 		ipif_refrele(ipif);
2087 	}
2088 	/* Reset time to live. */
2089 	ipha->ipha_ttl = ip_def_ttl;
2090 	{
2091 		/* Swap source and destination addresses */
2092 		ipaddr_t tmp;
2093 
2094 		tmp = ipha->ipha_src;
2095 		ipha->ipha_src = ipha->ipha_dst;
2096 		ipha->ipha_dst = tmp;
2097 	}
2098 	ipha->ipha_ident = 0;
2099 	if (!IS_SIMPLE_IPH(ipha))
2100 		icmp_options_update(ipha);
2101 
2102 	/*
2103 	 * ICMP echo replies should go out on the same interface
2104 	 * the request came on as probes used by in.mpathd for detecting
2105 	 * NIC failures are ECHO packets. We turn-off load spreading
2106 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2107 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2108 	 * function. This is in turn handled by ip_wput and ip_newroute
2109 	 * to make sure that the packet goes out on the interface it came
2110 	 * in on. If we don't turnoff load spreading, the packets might get
2111 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2112 	 * to go out and in.mpathd would wrongly detect a failure or
2113 	 * mis-detect a NIC failure for link failure. As load spreading
2114 	 * can happen only if ill_group is not NULL, we do only for
2115 	 * that case and this does not affect the normal case.
2116 	 *
2117 	 * We turn off load spreading only on echo packets that came from
2118 	 * on-link hosts. If the interface route has been deleted, this will
2119 	 * not be enforced as we can't do much. For off-link hosts, as the
2120 	 * default routes in IPv4 does not typically have an ire_ipif
2121 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2122 	 * Moreover, expecting a default route through this interface may
2123 	 * not be correct. We use ipha_dst because of the swap above.
2124 	 */
2125 	onlink = B_FALSE;
2126 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2127 		/*
2128 		 * First, we need to make sure that it is not one of our
2129 		 * local addresses. If we set onlink when it is one of
2130 		 * our local addresses, we will end up creating IRE_CACHES
2131 		 * for one of our local addresses. Then, we will never
2132 		 * accept packets for them afterwards.
2133 		 */
2134 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2135 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2136 		if (src_ire == NULL) {
2137 			ipif = ipif_get_next_ipif(NULL, ill);
2138 			if (ipif == NULL) {
2139 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2140 				freemsg(mp);
2141 				return;
2142 			}
2143 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2144 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2145 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE);
2146 			ipif_refrele(ipif);
2147 			if (src_ire != NULL) {
2148 				onlink = B_TRUE;
2149 				ire_refrele(src_ire);
2150 			}
2151 		} else {
2152 			ire_refrele(src_ire);
2153 		}
2154 	}
2155 	if (!mctl_present) {
2156 		/*
2157 		 * This packet should go out the same way as it
2158 		 * came in i.e in clear. To make sure that global
2159 		 * policy will not be applied to this in ip_wput_ire,
2160 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2161 		 */
2162 		ASSERT(first_mp == mp);
2163 		if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
2164 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2165 			freemsg(mp);
2166 			return;
2167 		}
2168 		ii = (ipsec_in_t *)first_mp->b_rptr;
2169 
2170 		/* This is not a secure packet */
2171 		ii->ipsec_in_secure = B_FALSE;
2172 		if (onlink) {
2173 			ii->ipsec_in_attach_if = B_TRUE;
2174 			ii->ipsec_in_ill_index =
2175 			    ill->ill_phyint->phyint_ifindex;
2176 			ii->ipsec_in_rill_index =
2177 			    recv_ill->ill_phyint->phyint_ifindex;
2178 		}
2179 		first_mp->b_cont = mp;
2180 	} else if (onlink) {
2181 		ii = (ipsec_in_t *)first_mp->b_rptr;
2182 		ii->ipsec_in_attach_if = B_TRUE;
2183 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2184 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2185 	} else {
2186 		ii = (ipsec_in_t *)first_mp->b_rptr;
2187 	}
2188 	ii->ipsec_in_zoneid = zoneid;
2189 	ASSERT(zoneid != ALL_ZONES);
2190 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2191 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2192 		return;
2193 	}
2194 	BUMP_MIB(&icmp_mib, icmpOutMsgs);
2195 	put(WR(q), first_mp);
2196 }
2197 
2198 static ipaddr_t
2199 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2200 {
2201 	conn_t *connp;
2202 	connf_t *connfp;
2203 	ipaddr_t nexthop_addr = INADDR_ANY;
2204 	int hdr_length = IPH_HDR_LENGTH(ipha);
2205 	uint16_t *up;
2206 	uint32_t ports;
2207 
2208 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2209 	switch (ipha->ipha_protocol) {
2210 		case IPPROTO_TCP:
2211 		{
2212 			tcph_t *tcph;
2213 
2214 			/* do a reverse lookup */
2215 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2216 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2217 			    TCPS_LISTEN);
2218 			break;
2219 		}
2220 		case IPPROTO_UDP:
2221 		{
2222 			uint32_t dstport, srcport;
2223 
2224 			((uint16_t *)&ports)[0] = up[1];
2225 			((uint16_t *)&ports)[1] = up[0];
2226 
2227 			/* Extract ports in net byte order */
2228 			dstport = htons(ntohl(ports) & 0xFFFF);
2229 			srcport = htons(ntohl(ports) >> 16);
2230 
2231 			connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
2232 			mutex_enter(&connfp->connf_lock);
2233 			connp = connfp->connf_head;
2234 
2235 			/* do a reverse lookup */
2236 			while ((connp != NULL) &&
2237 			    (!IPCL_UDP_MATCH(connp, dstport,
2238 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2239 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2240 				connp = connp->conn_next;
2241 			}
2242 			if (connp != NULL)
2243 				CONN_INC_REF(connp);
2244 			mutex_exit(&connfp->connf_lock);
2245 			break;
2246 		}
2247 		case IPPROTO_SCTP:
2248 		{
2249 			in6_addr_t map_src, map_dst;
2250 
2251 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2252 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2253 			((uint16_t *)&ports)[0] = up[1];
2254 			((uint16_t *)&ports)[1] = up[0];
2255 
2256 			if ((connp = sctp_find_conn(&map_src, &map_dst, ports,
2257 			    0, zoneid)) == NULL) {
2258 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2259 				    zoneid, ports, ipha);
2260 			} else {
2261 				CONN_INC_REF(connp);
2262 				SCTP_REFRELE(CONN2SCTP(connp));
2263 			}
2264 			break;
2265 		}
2266 		default:
2267 		{
2268 			ipha_t ripha;
2269 
2270 			ripha.ipha_src = ipha->ipha_dst;
2271 			ripha.ipha_dst = ipha->ipha_src;
2272 			ripha.ipha_protocol = ipha->ipha_protocol;
2273 
2274 			connfp = &ipcl_proto_fanout[ipha->ipha_protocol];
2275 			mutex_enter(&connfp->connf_lock);
2276 			connp = connfp->connf_head;
2277 			for (connp = connfp->connf_head; connp != NULL;
2278 			    connp = connp->conn_next) {
2279 				if (IPCL_PROTO_MATCH(connp,
2280 				    ipha->ipha_protocol, &ripha, ill,
2281 				    0, zoneid)) {
2282 					CONN_INC_REF(connp);
2283 					break;
2284 				}
2285 			}
2286 			mutex_exit(&connfp->connf_lock);
2287 		}
2288 	}
2289 	if (connp != NULL) {
2290 		if (connp->conn_nexthop_set)
2291 			nexthop_addr = connp->conn_nexthop_v4;
2292 		CONN_DEC_REF(connp);
2293 	}
2294 	return (nexthop_addr);
2295 }
2296 
2297 /* Table from RFC 1191 */
2298 static int icmp_frag_size_table[] =
2299 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2300 
2301 /*
2302  * Process received ICMP Packet too big.
2303  * After updating any IRE it does the fanout to any matching transport streams.
2304  * Assumes the message has been pulled up till the IP header that caused
2305  * the error.
2306  *
2307  * Returns B_FALSE on failure and B_TRUE on success.
2308  */
2309 static boolean_t
2310 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2311     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length)
2312 {
2313 	ire_t	*ire, *first_ire;
2314 	int	mtu;
2315 	int	hdr_length;
2316 	ipaddr_t nexthop_addr;
2317 
2318 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2319 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2320 	ASSERT(ill != NULL);
2321 
2322 	hdr_length = IPH_HDR_LENGTH(ipha);
2323 
2324 	/* Drop if the original packet contained a source route */
2325 	if (ip_source_route_included(ipha)) {
2326 		return (B_FALSE);
2327 	}
2328 	/*
2329 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2330 	 * header.
2331 	 */
2332 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2333 	    mp->b_wptr) {
2334 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2335 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2336 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2337 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2338 			return (B_FALSE);
2339 		}
2340 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2341 		ipha = (ipha_t *)&icmph[1];
2342 	}
2343 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2344 	if (nexthop_addr != INADDR_ANY) {
2345 		/* nexthop set */
2346 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2347 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2348 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW);
2349 	} else {
2350 		/* nexthop not set */
2351 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2352 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
2353 	}
2354 
2355 	if (!first_ire) {
2356 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2357 		    ntohl(ipha->ipha_dst)));
2358 		return (B_FALSE);
2359 	}
2360 	/* Check for MTU discovery advice as described in RFC 1191 */
2361 	mtu = ntohs(icmph->icmph_du_mtu);
2362 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2363 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2364 	    ire = ire->ire_next) {
2365 		/*
2366 		 * Look for the connection to which this ICMP message is
2367 		 * directed. If it has the IP_NEXTHOP option set, then the
2368 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2369 		 * option. Else the search is limited to regular IREs.
2370 		 */
2371 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2372 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2373 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2374 		    (nexthop_addr != INADDR_ANY)))
2375 			continue;
2376 
2377 		mutex_enter(&ire->ire_lock);
2378 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2379 			/* Reduce the IRE max frag value as advised. */
2380 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2381 			    mtu, ire->ire_max_frag));
2382 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2383 		} else {
2384 			uint32_t length;
2385 			int	i;
2386 
2387 			/*
2388 			 * Use the table from RFC 1191 to figure out
2389 			 * the next "plateau" based on the length in
2390 			 * the original IP packet.
2391 			 */
2392 			length = ntohs(ipha->ipha_length);
2393 			if (ire->ire_max_frag <= length &&
2394 			    ire->ire_max_frag >= length - hdr_length) {
2395 				/*
2396 				 * Handle broken BSD 4.2 systems that
2397 				 * return the wrong iph_length in ICMP
2398 				 * errors.
2399 				 */
2400 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2401 				    length, ire->ire_max_frag));
2402 				length -= hdr_length;
2403 			}
2404 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2405 				if (length > icmp_frag_size_table[i])
2406 					break;
2407 			}
2408 			if (i == A_CNT(icmp_frag_size_table)) {
2409 				/* Smaller than 68! */
2410 				ip1dbg(("Too big for packet size %d\n",
2411 				    length));
2412 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2413 				ire->ire_frag_flag = 0;
2414 			} else {
2415 				mtu = icmp_frag_size_table[i];
2416 				ip1dbg(("Calculated mtu %d, packet size %d, "
2417 				    "before %d", mtu, length,
2418 				    ire->ire_max_frag));
2419 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2420 				ip1dbg((", after %d\n", ire->ire_max_frag));
2421 			}
2422 			/* Record the new max frag size for the ULP. */
2423 			icmph->icmph_du_zero = 0;
2424 			icmph->icmph_du_mtu =
2425 			    htons((uint16_t)ire->ire_max_frag);
2426 		}
2427 		mutex_exit(&ire->ire_lock);
2428 	}
2429 	rw_exit(&first_ire->ire_bucket->irb_lock);
2430 	ire_refrele(first_ire);
2431 	return (B_TRUE);
2432 }
2433 
2434 /*
2435  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2436  * calls this function.
2437  */
2438 static mblk_t *
2439 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2440 {
2441 	ipha_t *ipha;
2442 	icmph_t *icmph;
2443 	ipha_t *in_ipha;
2444 	int length;
2445 
2446 	ASSERT(mp->b_datap->db_type == M_DATA);
2447 
2448 	/*
2449 	 * For Self-encapsulated packets, we added an extra IP header
2450 	 * without the options. Inner IP header is the one from which
2451 	 * the outer IP header was formed. Thus, we need to remove the
2452 	 * outer IP header. To do this, we pullup the whole message
2453 	 * and overlay whatever follows the outer IP header over the
2454 	 * outer IP header.
2455 	 */
2456 
2457 	if (!pullupmsg(mp, -1))
2458 		return (NULL);
2459 
2460 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2461 	ipha = (ipha_t *)&icmph[1];
2462 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2463 
2464 	/*
2465 	 * The length that we want to overlay is following the inner
2466 	 * IP header. Subtracting the IP header + icmp header + outer
2467 	 * IP header's length should give us the length that we want to
2468 	 * overlay.
2469 	 */
2470 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2471 	    hdr_length;
2472 	/*
2473 	 * Overlay whatever follows the inner header over the
2474 	 * outer header.
2475 	 */
2476 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2477 
2478 	/* Set the wptr to account for the outer header */
2479 	mp->b_wptr -= hdr_length;
2480 	return (mp);
2481 }
2482 
2483 /*
2484  * Try to pass the ICMP message upstream in case the ULP cares.
2485  *
2486  * If the packet that caused the ICMP error is secure, we send
2487  * it to AH/ESP to make sure that the attached packet has a
2488  * valid association. ipha in the code below points to the
2489  * IP header of the packet that caused the error.
2490  *
2491  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2492  * in the context of IPSEC. Normally we tell the upper layer
2493  * whenever we send the ire (including ip_bind), the IPSEC header
2494  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2495  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2496  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2497  * same thing. As TCP has the IPSEC options size that needs to be
2498  * adjusted, we just pass the MTU unchanged.
2499  *
2500  * IFN could have been generated locally or by some router.
2501  *
2502  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2503  *	    This happens because IP adjusted its value of MTU on an
2504  *	    earlier IFN message and could not tell the upper layer,
2505  *	    the new adjusted value of MTU e.g. Packet was encrypted
2506  *	    or there was not enough information to fanout to upper
2507  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2508  *	    generates the IFN, where IPSEC processing has *not* been
2509  *	    done.
2510  *
2511  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2512  *	    could have generated this. This happens because ire_max_frag
2513  *	    value in IP was set to a new value, while the IPSEC processing
2514  *	    was being done and after we made the fragmentation check in
2515  *	    ip_wput_ire. Thus on return from IPSEC processing,
2516  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2517  *	    and generates the IFN. As IPSEC processing is over, we fanout
2518  *	    to AH/ESP to remove the header.
2519  *
2520  *	    In both these cases, ipsec_in_loopback will be set indicating
2521  *	    that IFN was generated locally.
2522  *
2523  * ROUTER : IFN could be secure or non-secure.
2524  *
2525  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2526  *	      packet in error has AH/ESP headers to validate the AH/ESP
2527  *	      headers. AH/ESP will verify whether there is a valid SA or
2528  *	      not and send it back. We will fanout again if we have more
2529  *	      data in the packet.
2530  *
2531  *	      If the packet in error does not have AH/ESP, we handle it
2532  *	      like any other case.
2533  *
2534  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2535  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2536  *	      for validation. AH/ESP will verify whether there is a
2537  *	      valid SA or not and send it back. We will fanout again if
2538  *	      we have more data in the packet.
2539  *
2540  *	      If the packet in error does not have AH/ESP, we handle it
2541  *	      like any other case.
2542  */
2543 static void
2544 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2545     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2546     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2547     zoneid_t zoneid)
2548 {
2549 	uint16_t *up;	/* Pointer to ports in ULP header */
2550 	uint32_t ports;	/* reversed ports for fanout */
2551 	ipha_t ripha;	/* With reversed addresses */
2552 	mblk_t *first_mp;
2553 	ipsec_in_t *ii;
2554 	tcph_t	*tcph;
2555 	conn_t	*connp;
2556 
2557 	ASSERT(ill != NULL);
2558 
2559 	first_mp = mp;
2560 	if (mctl_present) {
2561 		mp = first_mp->b_cont;
2562 		ASSERT(mp != NULL);
2563 
2564 		ii = (ipsec_in_t *)first_mp->b_rptr;
2565 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2566 	} else {
2567 		ii = NULL;
2568 	}
2569 
2570 	switch (ipha->ipha_protocol) {
2571 	case IPPROTO_UDP:
2572 		/*
2573 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2574 		 * transport header.
2575 		 */
2576 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2577 		    mp->b_wptr) {
2578 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2579 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2580 				goto discard_pkt;
2581 			}
2582 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2583 			ipha = (ipha_t *)&icmph[1];
2584 		}
2585 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2586 
2587 		/*
2588 		 * Attempt to find a client stream based on port.
2589 		 * Note that we do a reverse lookup since the header is
2590 		 * in the form we sent it out.
2591 		 * The ripha header is only used for the IP_UDP_MATCH and we
2592 		 * only set the src and dst addresses and protocol.
2593 		 */
2594 		ripha.ipha_src = ipha->ipha_dst;
2595 		ripha.ipha_dst = ipha->ipha_src;
2596 		ripha.ipha_protocol = ipha->ipha_protocol;
2597 		((uint16_t *)&ports)[0] = up[1];
2598 		((uint16_t *)&ports)[1] = up[0];
2599 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2600 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2601 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2602 		    icmph->icmph_type, icmph->icmph_code));
2603 
2604 		/* Have to change db_type after any pullupmsg */
2605 		DB_TYPE(mp) = M_CTL;
2606 
2607 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2608 		    mctl_present, ip_policy, recv_ill, zoneid);
2609 		return;
2610 
2611 	case IPPROTO_TCP:
2612 		/*
2613 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2614 		 * transport header.
2615 		 */
2616 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2617 		    mp->b_wptr) {
2618 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2619 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2620 				goto discard_pkt;
2621 			}
2622 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2623 			ipha = (ipha_t *)&icmph[1];
2624 		}
2625 		/*
2626 		 * Find a TCP client stream for this packet.
2627 		 * Note that we do a reverse lookup since the header is
2628 		 * in the form we sent it out.
2629 		 */
2630 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2631 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN);
2632 		if (connp == NULL)
2633 			goto discard_pkt;
2634 
2635 		/* Have to change db_type after any pullupmsg */
2636 		DB_TYPE(mp) = M_CTL;
2637 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2638 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2639 		return;
2640 
2641 	case IPPROTO_SCTP:
2642 		/*
2643 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2644 		 * transport header.
2645 		 */
2646 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2647 		    mp->b_wptr) {
2648 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2649 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2650 				goto discard_pkt;
2651 			}
2652 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2653 			ipha = (ipha_t *)&icmph[1];
2654 		}
2655 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2656 		/*
2657 		 * Find a SCTP client stream for this packet.
2658 		 * Note that we do a reverse lookup since the header is
2659 		 * in the form we sent it out.
2660 		 * The ripha header is only used for the matching and we
2661 		 * only set the src and dst addresses, protocol, and version.
2662 		 */
2663 		ripha.ipha_src = ipha->ipha_dst;
2664 		ripha.ipha_dst = ipha->ipha_src;
2665 		ripha.ipha_protocol = ipha->ipha_protocol;
2666 		ripha.ipha_version_and_hdr_length =
2667 		    ipha->ipha_version_and_hdr_length;
2668 		((uint16_t *)&ports)[0] = up[1];
2669 		((uint16_t *)&ports)[1] = up[0];
2670 
2671 		/* Have to change db_type after any pullupmsg */
2672 		DB_TYPE(mp) = M_CTL;
2673 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2674 		    mctl_present, ip_policy, 0, zoneid);
2675 		return;
2676 
2677 	case IPPROTO_ESP:
2678 	case IPPROTO_AH: {
2679 		int ipsec_rc;
2680 
2681 		/*
2682 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2683 		 * We will re-use the IPSEC_IN if it is already present as
2684 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2685 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2686 		 * one and attach it in the front.
2687 		 */
2688 		if (ii != NULL) {
2689 			/*
2690 			 * ip_fanout_proto_again converts the ICMP errors
2691 			 * that come back from AH/ESP to M_DATA so that
2692 			 * if it is non-AH/ESP and we do a pullupmsg in
2693 			 * this function, it would work. Convert it back
2694 			 * to M_CTL before we send up as this is a ICMP
2695 			 * error. This could have been generated locally or
2696 			 * by some router. Validate the inner IPSEC
2697 			 * headers.
2698 			 *
2699 			 * NOTE : ill_index is used by ip_fanout_proto_again
2700 			 * to locate the ill.
2701 			 */
2702 			ASSERT(ill != NULL);
2703 			ii->ipsec_in_ill_index =
2704 			    ill->ill_phyint->phyint_ifindex;
2705 			ii->ipsec_in_rill_index =
2706 			    recv_ill->ill_phyint->phyint_ifindex;
2707 			DB_TYPE(first_mp->b_cont) = M_CTL;
2708 		} else {
2709 			/*
2710 			 * IPSEC_IN is not present. We attach a ipsec_in
2711 			 * message and send up to IPSEC for validating
2712 			 * and removing the IPSEC headers. Clear
2713 			 * ipsec_in_secure so that when we return
2714 			 * from IPSEC, we don't mistakenly think that this
2715 			 * is a secure packet came from the network.
2716 			 *
2717 			 * NOTE : ill_index is used by ip_fanout_proto_again
2718 			 * to locate the ill.
2719 			 */
2720 			ASSERT(first_mp == mp);
2721 			first_mp = ipsec_in_alloc(B_TRUE);
2722 			if (first_mp == NULL) {
2723 				freemsg(mp);
2724 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2725 				return;
2726 			}
2727 			ii = (ipsec_in_t *)first_mp->b_rptr;
2728 
2729 			/* This is not a secure packet */
2730 			ii->ipsec_in_secure = B_FALSE;
2731 			first_mp->b_cont = mp;
2732 			DB_TYPE(mp) = M_CTL;
2733 			ASSERT(ill != NULL);
2734 			ii->ipsec_in_ill_index =
2735 			    ill->ill_phyint->phyint_ifindex;
2736 			ii->ipsec_in_rill_index =
2737 			    recv_ill->ill_phyint->phyint_ifindex;
2738 		}
2739 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2740 
2741 		if (!ipsec_loaded()) {
2742 			ip_proto_not_sup(q, first_mp, 0, zoneid);
2743 			return;
2744 		}
2745 
2746 		if (ipha->ipha_protocol == IPPROTO_ESP)
2747 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2748 		else
2749 			ipsec_rc = ipsecah_icmp_error(first_mp);
2750 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2751 			return;
2752 
2753 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2754 		return;
2755 	}
2756 	default:
2757 		/*
2758 		 * The ripha header is only used for the lookup and we
2759 		 * only set the src and dst addresses and protocol.
2760 		 */
2761 		ripha.ipha_src = ipha->ipha_dst;
2762 		ripha.ipha_dst = ipha->ipha_src;
2763 		ripha.ipha_protocol = ipha->ipha_protocol;
2764 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2765 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2766 		    ntohl(ipha->ipha_dst),
2767 		    icmph->icmph_type, icmph->icmph_code));
2768 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2769 			ipha_t *in_ipha;
2770 
2771 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2772 			    mp->b_wptr) {
2773 				if (!pullupmsg(mp, (uchar_t *)ipha +
2774 				    hdr_length + sizeof (ipha_t) -
2775 				    mp->b_rptr)) {
2776 					goto discard_pkt;
2777 				}
2778 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2779 				ipha = (ipha_t *)&icmph[1];
2780 			}
2781 			/*
2782 			 * Caller has verified that length has to be
2783 			 * at least the size of IP header.
2784 			 */
2785 			ASSERT(hdr_length >= sizeof (ipha_t));
2786 			/*
2787 			 * Check the sanity of the inner IP header like
2788 			 * we did for the outer header.
2789 			 */
2790 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2791 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2792 				goto discard_pkt;
2793 			}
2794 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2795 				goto discard_pkt;
2796 			}
2797 			/* Check for Self-encapsulated tunnels */
2798 			if (in_ipha->ipha_src == ipha->ipha_src &&
2799 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2800 
2801 				mp = icmp_inbound_self_encap_error(mp,
2802 				    iph_hdr_length, hdr_length);
2803 				if (mp == NULL)
2804 					goto discard_pkt;
2805 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2806 				ipha = (ipha_t *)&icmph[1];
2807 				hdr_length = IPH_HDR_LENGTH(ipha);
2808 				/*
2809 				 * The packet in error is self-encapsualted.
2810 				 * And we are finding it further encapsulated
2811 				 * which we could not have possibly generated.
2812 				 */
2813 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2814 					goto discard_pkt;
2815 				}
2816 				icmp_inbound_error_fanout(q, ill, first_mp,
2817 				    icmph, ipha, iph_hdr_length, hdr_length,
2818 				    mctl_present, ip_policy, recv_ill, zoneid);
2819 				return;
2820 			}
2821 		}
2822 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2823 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2824 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2825 		    ii != NULL &&
2826 		    ii->ipsec_in_loopback &&
2827 		    ii->ipsec_in_secure) {
2828 			/*
2829 			 * For IP tunnels that get a looped-back
2830 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2831 			 * reported new MTU to take into account the IPsec
2832 			 * headers protecting this configured tunnel.
2833 			 *
2834 			 * This allows the tunnel module (tun.c) to blindly
2835 			 * accept the MTU reported in an ICMP "too big"
2836 			 * message.
2837 			 *
2838 			 * Non-looped back ICMP messages will just be
2839 			 * handled by the security protocols (if needed),
2840 			 * and the first subsequent packet will hit this
2841 			 * path.
2842 			 */
2843 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2844 			    ipsec_in_extra_length(first_mp));
2845 		}
2846 		/* Have to change db_type after any pullupmsg */
2847 		DB_TYPE(mp) = M_CTL;
2848 
2849 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2850 		    ip_policy, recv_ill, zoneid);
2851 		return;
2852 	}
2853 	/* NOTREACHED */
2854 discard_pkt:
2855 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
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, ipIfStatsOutDiscards);
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, ipIfStatsOutDiscards);
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, ipIfStatsOutDiscards);
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, ipIfStatsOutNoRoutes);
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, ipIfStatsOutNoRoutes);
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, ipIfStatsOutNoRoutes);
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, ipIfStatsInCksumErrs);
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 	/*
3821 	 * No lock needed for moving or condemned check, as this is just an
3822 	 * optimization.
3823 	 */
3824 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3825 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3826 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3827 		/* No reason to try to bring this address back. */
3828 		return;
3829 	}
3830 
3831 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3832 		goto alloc_fail;
3833 
3834 	if (ipif->ipif_arp_del_mp == NULL) {
3835 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3836 			goto alloc_fail;
3837 		ipif->ipif_arp_del_mp = arp_del_mp;
3838 	}
3839 
3840 	/* Setting the 'unverified' flag restarts DAD */
3841 	area = (area_t *)arp_add_mp->b_rptr;
3842 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3843 	    ACE_F_UNVERIFIED;
3844 	putnext(ill->ill_rq, arp_add_mp);
3845 	return;
3846 
3847 alloc_fail:
3848 	/*
3849 	 * On allocation failure, just restart the timer.  Note that the ipif
3850 	 * is down here, so no other thread could be trying to start a recovery
3851 	 * timer.  The ill_lock protects the condemned flag and the recovery
3852 	 * timer ID.
3853 	 */
3854 	freemsg(arp_add_mp);
3855 	mutex_enter(&ill->ill_lock);
3856 	if (ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3857 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3858 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3859 		    MSEC_TO_TICK(ip_dup_recovery));
3860 	}
3861 	mutex_exit(&ill->ill_lock);
3862 }
3863 
3864 /*
3865  * This is for exclusive changes due to ARP.  Either tear down an interface due
3866  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3867  */
3868 /* ARGSUSED */
3869 static void
3870 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3871 {
3872 	ill_t	*ill = rq->q_ptr;
3873 	arh_t *arh;
3874 	ipaddr_t src;
3875 	ipif_t	*ipif;
3876 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3877 	char hbuf[MAC_STR_LEN];
3878 	char sbuf[INET_ADDRSTRLEN];
3879 	const char *failtype;
3880 	boolean_t bring_up;
3881 
3882 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3883 	case AR_CN_READY:
3884 		failtype = NULL;
3885 		bring_up = B_TRUE;
3886 		break;
3887 	case AR_CN_FAILED:
3888 		failtype = "in use";
3889 		bring_up = B_FALSE;
3890 		break;
3891 	default:
3892 		failtype = "claimed";
3893 		bring_up = B_FALSE;
3894 		break;
3895 	}
3896 
3897 	arh = (arh_t *)mp->b_cont->b_rptr;
3898 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3899 
3900 	/* Handle failures due to probes */
3901 	if (src == 0) {
3902 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3903 		    IP_ADDR_LEN);
3904 	}
3905 
3906 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3907 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3908 	    sizeof (hbuf));
3909 	(void) ip_dot_addr(src, sbuf);
3910 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3911 
3912 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3913 		    ipif->ipif_lcl_addr != src) {
3914 			continue;
3915 		}
3916 
3917 		/*
3918 		 * If we failed on a recovery probe, then restart the timer to
3919 		 * try again later.
3920 		 */
3921 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3922 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3923 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3924 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3925 		    ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0) {
3926 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3927 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3928 			continue;
3929 		}
3930 
3931 		/*
3932 		 * If what we're trying to do has already been done, then do
3933 		 * nothing.
3934 		 */
3935 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3936 			continue;
3937 
3938 		if (ipif->ipif_id != 0) {
3939 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3940 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3941 			    ipif->ipif_id);
3942 		}
3943 		if (failtype == NULL) {
3944 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3945 			    ibuf);
3946 		} else {
3947 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3948 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3949 		}
3950 
3951 		if (bring_up) {
3952 			ASSERT(ill->ill_dl_up);
3953 			/*
3954 			 * Free up the ARP delete message so we can allocate
3955 			 * a fresh one through the normal path.
3956 			 */
3957 			freemsg(ipif->ipif_arp_del_mp);
3958 			ipif->ipif_arp_del_mp = NULL;
3959 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3960 			    EINPROGRESS) {
3961 				ipif->ipif_addr_ready = 1;
3962 				(void) ipif_up_done(ipif);
3963 			}
3964 			continue;
3965 		}
3966 
3967 		mutex_enter(&ill->ill_lock);
3968 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3969 		ipif->ipif_flags |= IPIF_DUPLICATE;
3970 		ill->ill_ipif_dup_count++;
3971 		mutex_exit(&ill->ill_lock);
3972 		/*
3973 		 * Already exclusive on the ill; no need to handle deferred
3974 		 * processing here.
3975 		 */
3976 		(void) ipif_down(ipif, NULL, NULL);
3977 		ipif_down_tail(ipif);
3978 		mutex_enter(&ill->ill_lock);
3979 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3980 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3981 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3982 		    ip_dup_recovery > 0) {
3983 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3984 			    ipif, MSEC_TO_TICK(ip_dup_recovery));
3985 		}
3986 		mutex_exit(&ill->ill_lock);
3987 	}
3988 	freemsg(mp);
3989 }
3990 
3991 /* ARGSUSED */
3992 static void
3993 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3994 {
3995 	ill_t	*ill = rq->q_ptr;
3996 	arh_t *arh;
3997 	ipaddr_t src;
3998 	ipif_t	*ipif;
3999 
4000 	arh = (arh_t *)mp->b_cont->b_rptr;
4001 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
4002 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
4003 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
4004 			(void) ipif_resolver_up(ipif, Res_act_defend);
4005 	}
4006 	freemsg(mp);
4007 }
4008 
4009 /*
4010  * News from ARP.  ARP sends notification of interesting events down
4011  * to its clients using M_CTL messages with the interesting ARP packet
4012  * attached via b_cont.
4013  * The interesting event from a device comes up the corresponding ARP-IP-DEV
4014  * queue as opposed to ARP sending the message to all the clients, i.e. all
4015  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
4016  * table if a cache IRE is found to delete all the entries for the address in
4017  * the packet.
4018  */
4019 static void
4020 ip_arp_news(queue_t *q, mblk_t *mp)
4021 {
4022 	arcn_t		*arcn;
4023 	arh_t		*arh;
4024 	ire_t		*ire = NULL;
4025 	char		hbuf[MAC_STR_LEN];
4026 	char		sbuf[INET_ADDRSTRLEN];
4027 	ipaddr_t	src;
4028 	in6_addr_t	v6src;
4029 	boolean_t	isv6 = B_FALSE;
4030 	ipif_t		*ipif;
4031 	ill_t		*ill;
4032 
4033 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
4034 		if (q->q_next) {
4035 			putnext(q, mp);
4036 		} else
4037 			freemsg(mp);
4038 		return;
4039 	}
4040 	arh = (arh_t *)mp->b_cont->b_rptr;
4041 	/* Is it one we are interested in? */
4042 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
4043 		isv6 = B_TRUE;
4044 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
4045 		    IPV6_ADDR_LEN);
4046 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
4047 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
4048 		    IP_ADDR_LEN);
4049 	} else {
4050 		freemsg(mp);
4051 		return;
4052 	}
4053 
4054 	ill = q->q_ptr;
4055 
4056 	arcn = (arcn_t *)mp->b_rptr;
4057 	switch (arcn->arcn_code) {
4058 	case AR_CN_BOGON:
4059 		/*
4060 		 * Someone is sending ARP packets with a source protocol
4061 		 * address that we have published and for which we believe our
4062 		 * entry is authoritative and (when ill_arp_extend is set)
4063 		 * verified to be unique on the network.
4064 		 *
4065 		 * The ARP module internally handles the cases where the sender
4066 		 * is just probing (for DAD) and where the hardware address of
4067 		 * a non-authoritative entry has changed.  Thus, these are the
4068 		 * real conflicts, and we have to do resolution.
4069 		 *
4070 		 * We back away quickly from the address if it's from DHCP or
4071 		 * otherwise temporary and hasn't been used recently (or at
4072 		 * all).  We'd like to include "deprecated" addresses here as
4073 		 * well (as there's no real reason to defend something we're
4074 		 * discarding), but IPMP "reuses" this flag to mean something
4075 		 * other than the standard meaning.
4076 		 *
4077 		 * If the ARP module above is not extended (meaning that it
4078 		 * doesn't know how to defend the address), then we just log
4079 		 * the problem as we always did and continue on.  It's not
4080 		 * right, but there's little else we can do, and those old ATM
4081 		 * users are going away anyway.
4082 		 */
4083 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4084 		    hbuf, sizeof (hbuf));
4085 		(void) ip_dot_addr(src, sbuf);
4086 		if (isv6)
4087 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL);
4088 		else
4089 			ire = ire_cache_lookup(src, ALL_ZONES, NULL);
4090 
4091 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4092 			uint32_t now;
4093 			uint32_t maxage;
4094 			clock_t lused;
4095 			uint_t maxdefense;
4096 			uint_t defs;
4097 
4098 			/*
4099 			 * First, figure out if this address hasn't been used
4100 			 * in a while.  If it hasn't, then it's a better
4101 			 * candidate for abandoning.
4102 			 */
4103 			ipif = ire->ire_ipif;
4104 			ASSERT(ipif != NULL);
4105 			now = gethrestime_sec();
4106 			maxage = now - ire->ire_create_time;
4107 			if (maxage > ip_max_temp_idle)
4108 				maxage = ip_max_temp_idle;
4109 			lused = drv_hztousec(ddi_get_lbolt() -
4110 			    ire->ire_last_used_time) / MICROSEC + 1;
4111 			if (lused >= maxage && (ipif->ipif_flags &
4112 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4113 				maxdefense = ip_max_temp_defend;
4114 			else
4115 				maxdefense = ip_max_defend;
4116 
4117 			/*
4118 			 * Now figure out how many times we've defended
4119 			 * ourselves.  Ignore defenses that happened long in
4120 			 * the past.
4121 			 */
4122 			mutex_enter(&ire->ire_lock);
4123 			if ((defs = ire->ire_defense_count) > 0 &&
4124 			    now - ire->ire_defense_time > ip_defend_interval) {
4125 				ire->ire_defense_count = defs = 0;
4126 			}
4127 			ire->ire_defense_count++;
4128 			ire->ire_defense_time = now;
4129 			mutex_exit(&ire->ire_lock);
4130 			ill_refhold(ill);
4131 			ire_refrele(ire);
4132 
4133 			/*
4134 			 * If we've defended ourselves too many times already,
4135 			 * then give up and tear down the interface(s) using
4136 			 * this address.  Otherwise, defend by sending out a
4137 			 * gratuitous ARP.
4138 			 */
4139 			if (defs >= maxdefense && ill->ill_arp_extend) {
4140 				(void) qwriter_ip(NULL, ill, q, mp,
4141 				    ip_arp_excl, CUR_OP, B_FALSE);
4142 			} else {
4143 				cmn_err(CE_WARN,
4144 				    "node %s is using our IP address %s on %s",
4145 				    hbuf, sbuf, ill->ill_name);
4146 				/*
4147 				 * If this is an old (ATM) ARP module, then
4148 				 * don't try to defend the address.  Remain
4149 				 * compatible with the old behavior.  Defend
4150 				 * only with new ARP.
4151 				 */
4152 				if (ill->ill_arp_extend) {
4153 					(void) qwriter_ip(NULL, ill, q, mp,
4154 					    ip_arp_defend, CUR_OP, B_FALSE);
4155 				} else {
4156 					ill_refrele(ill);
4157 				}
4158 			}
4159 			return;
4160 		}
4161 		cmn_err(CE_WARN,
4162 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4163 		    hbuf, sbuf, ill->ill_name);
4164 		if (ire != NULL)
4165 			ire_refrele(ire);
4166 		break;
4167 	case AR_CN_ANNOUNCE:
4168 		if (isv6) {
4169 			/*
4170 			 * For XRESOLV interfaces.
4171 			 * Delete the IRE cache entry and NCE for this
4172 			 * v6 address
4173 			 */
4174 			ip_ire_clookup_and_delete_v6(&v6src);
4175 			/*
4176 			 * If v6src is a non-zero, it's a router address
4177 			 * as below. Do the same sort of thing to clean
4178 			 * out off-net IRE_CACHE entries that go through
4179 			 * the router.
4180 			 */
4181 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4182 				ire_walk_v6(ire_delete_cache_gw_v6,
4183 				    (char *)&v6src, ALL_ZONES);
4184 			}
4185 		} else {
4186 			nce_hw_map_t hwm;
4187 
4188 			/*
4189 			 * ARP gives us a copy of any packet where it thinks
4190 			 * the address has changed, so that we can update our
4191 			 * caches.  We're responsible for caching known answers
4192 			 * in the current design.  We check whether the
4193 			 * hardware address really has changed in all of our
4194 			 * entries that have cached this mapping, and if so, we
4195 			 * blow them away.  This way we will immediately pick
4196 			 * up the rare case of a host changing hardware
4197 			 * address.
4198 			 */
4199 			if (src == 0)
4200 				break;
4201 			hwm.hwm_addr = src;
4202 			hwm.hwm_hwlen = arh->arh_hlen;
4203 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4204 			ndp_walk_common(&ndp4, NULL,
4205 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4206 		}
4207 		break;
4208 	case AR_CN_READY:
4209 		/* No external v6 resolver has a contract to use this */
4210 		if (isv6)
4211 			break;
4212 		/* If the link is down, we'll retry this later */
4213 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4214 			break;
4215 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4216 		    NULL, NULL);
4217 		if (ipif != NULL) {
4218 			/*
4219 			 * If this is a duplicate recovery, then we now need to
4220 			 * go exclusive to bring this thing back up.
4221 			 */
4222 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4223 			    IPIF_DUPLICATE) {
4224 				ipif_refrele(ipif);
4225 				ill_refhold(ill);
4226 				(void) qwriter_ip(NULL, ill, q, mp,
4227 				    ip_arp_excl, CUR_OP, B_FALSE);
4228 				return;
4229 			}
4230 			/*
4231 			 * If this is the first notice that this address is
4232 			 * ready, then let the user know now.
4233 			 */
4234 			if ((ipif->ipif_flags & IPIF_UP) &&
4235 			    !ipif->ipif_addr_ready) {
4236 				ipif_mask_reply(ipif);
4237 				ip_rts_ifmsg(ipif);
4238 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4239 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4240 			}
4241 			ipif->ipif_addr_ready = 1;
4242 			ipif_refrele(ipif);
4243 		}
4244 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp));
4245 		if (ire != NULL) {
4246 			ire->ire_defense_count = 0;
4247 			ire_refrele(ire);
4248 		}
4249 		break;
4250 	case AR_CN_FAILED:
4251 		/* No external v6 resolver has a contract to use this */
4252 		if (isv6)
4253 			break;
4254 		ill_refhold(ill);
4255 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4256 		    B_FALSE);
4257 		return;
4258 	}
4259 	freemsg(mp);
4260 }
4261 
4262 /*
4263  * Create a mblk suitable for carrying the interface index and/or source link
4264  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4265  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4266  * application.
4267  */
4268 mblk_t *
4269 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid)
4270 {
4271 	mblk_t		*mp;
4272 	ip_pktinfo_t	*pinfo;
4273 	ipha_t *ipha;
4274 	struct ether_header *pether;
4275 
4276 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4277 	if (mp == NULL) {
4278 		ip1dbg(("ip_add_info: allocation failure.\n"));
4279 		return (data_mp);
4280 	}
4281 
4282 	ipha	= (ipha_t *)data_mp->b_rptr;
4283 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4284 	bzero(pinfo, sizeof (ip_pktinfo_t));
4285 	pinfo->ip_pkt_flags = (uchar_t)flags;
4286 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4287 
4288 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4289 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4290 	if (flags & IPF_RECVADDR) {
4291 		ipif_t	*ipif;
4292 		ire_t	*ire;
4293 
4294 		/*
4295 		 * Only valid for V4
4296 		 */
4297 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4298 		    (IPV4_VERSION << 4));
4299 
4300 		ipif = ipif_get_next_ipif(NULL, ill);
4301 		if (ipif != NULL) {
4302 			/*
4303 			 * Since a decision has already been made to deliver the
4304 			 * packet, there is no need to test for SECATTR and
4305 			 * ZONEONLY.
4306 			 */
4307 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4308 			    zoneid, NULL, MATCH_IRE_ILL_GROUP);
4309 			if (ire == NULL) {
4310 				/*
4311 				 * packet must have come on a different
4312 				 * interface.
4313 				 * Since a decision has already been made to
4314 				 * deliver the packet, there is no need to test
4315 				 * for SECATTR and ZONEONLY.
4316 				 */
4317 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4318 				    ipif, zoneid, NULL, NULL);
4319 			}
4320 
4321 			if (ire == NULL) {
4322 				/*
4323 				 * This is either a multicast packet or
4324 				 * the address has been removed since
4325 				 * the packet was received.
4326 				 * Return INADDR_ANY so that normal source
4327 				 * selection occurs for the response.
4328 				 */
4329 
4330 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4331 			} else {
4332 				ASSERT(ire->ire_type != IRE_CACHE);
4333 				pinfo->ip_pkt_match_addr.s_addr =
4334 				    ire->ire_src_addr;
4335 				ire_refrele(ire);
4336 			}
4337 			ipif_refrele(ipif);
4338 		} else {
4339 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4340 		}
4341 	}
4342 
4343 	pether = (struct ether_header *)((char *)ipha
4344 	    - sizeof (struct ether_header));
4345 	/*
4346 	 * Make sure the interface is an ethernet type, since this option
4347 	 * is currently supported only on this type of interface. Also make
4348 	 * sure we are pointing correctly above db_base.
4349 	 */
4350 
4351 	if ((flags & IPF_RECVSLLA) &&
4352 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4353 	    (ill->ill_type == IFT_ETHER) &&
4354 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4355 
4356 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4357 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4358 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4359 	} else {
4360 		/*
4361 		 * Clear the bit. Indicate to upper layer that IP is not
4362 		 * sending this ancillary info.
4363 		 */
4364 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4365 	}
4366 
4367 	mp->b_datap->db_type = M_CTL;
4368 	mp->b_wptr += sizeof (ip_pktinfo_t);
4369 	mp->b_cont = data_mp;
4370 
4371 	return (mp);
4372 }
4373 
4374 /*
4375  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4376  * part of the bind request.
4377  */
4378 
4379 boolean_t
4380 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4381 {
4382 	ipsec_in_t *ii;
4383 
4384 	ASSERT(policy_mp != NULL);
4385 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4386 
4387 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4388 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4389 
4390 	connp->conn_policy = ii->ipsec_in_policy;
4391 	ii->ipsec_in_policy = NULL;
4392 
4393 	if (ii->ipsec_in_action != NULL) {
4394 		if (connp->conn_latch == NULL) {
4395 			connp->conn_latch = iplatch_create();
4396 			if (connp->conn_latch == NULL)
4397 				return (B_FALSE);
4398 		}
4399 		ipsec_latch_inbound(connp->conn_latch, ii);
4400 	}
4401 	return (B_TRUE);
4402 }
4403 
4404 /*
4405  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4406  * and to arrange for power-fanout assist.  The ULP is identified by
4407  * adding a single byte at the end of the original bind message.
4408  * A ULP other than UDP or TCP that wishes to be recognized passes
4409  * down a bind with a zero length address.
4410  *
4411  * The binding works as follows:
4412  * - A zero byte address means just bind to the protocol.
4413  * - A four byte address is treated as a request to validate
4414  *   that the address is a valid local address, appropriate for
4415  *   an application to bind to. This does not affect any fanout
4416  *   information in IP.
4417  * - A sizeof sin_t byte address is used to bind to only the local address
4418  *   and port.
4419  * - A sizeof ipa_conn_t byte address contains complete fanout information
4420  *   consisting of local and remote addresses and ports.  In
4421  *   this case, the addresses are both validated as appropriate
4422  *   for this operation, and, if so, the information is retained
4423  *   for use in the inbound fanout.
4424  *
4425  * The ULP (except in the zero-length bind) can append an
4426  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4427  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4428  * a copy of the source or destination IRE (source for local bind;
4429  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4430  * policy information contained should be copied on to the conn.
4431  *
4432  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4433  */
4434 mblk_t *
4435 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4436 {
4437 	ssize_t		len;
4438 	struct T_bind_req	*tbr;
4439 	sin_t		*sin;
4440 	ipa_conn_t	*ac;
4441 	uchar_t		*ucp;
4442 	mblk_t		*mp1;
4443 	boolean_t	ire_requested;
4444 	boolean_t	ipsec_policy_set = B_FALSE;
4445 	int		error = 0;
4446 	int		protocol;
4447 	ipa_conn_x_t	*acx;
4448 
4449 	ASSERT(!connp->conn_af_isv6);
4450 	connp->conn_pkt_isv6 = B_FALSE;
4451 
4452 	len = MBLKL(mp);
4453 	if (len < (sizeof (*tbr) + 1)) {
4454 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4455 		    "ip_bind: bogus msg, len %ld", len);
4456 		/* XXX: Need to return something better */
4457 		goto bad_addr;
4458 	}
4459 	/* Back up and extract the protocol identifier. */
4460 	mp->b_wptr--;
4461 	protocol = *mp->b_wptr & 0xFF;
4462 	tbr = (struct T_bind_req *)mp->b_rptr;
4463 	/* Reset the message type in preparation for shipping it back. */
4464 	DB_TYPE(mp) = M_PCPROTO;
4465 
4466 	connp->conn_ulp = (uint8_t)protocol;
4467 
4468 	/*
4469 	 * Check for a zero length address.  This is from a protocol that
4470 	 * wants to register to receive all packets of its type.
4471 	 */
4472 	if (tbr->ADDR_length == 0) {
4473 		/*
4474 		 * These protocols are now intercepted in ip_bind_v6().
4475 		 * Reject protocol-level binds here for now.
4476 		 *
4477 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4478 		 * so that the protocol type cannot be SCTP.
4479 		 */
4480 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4481 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4482 			goto bad_addr;
4483 		}
4484 
4485 		/*
4486 		 *
4487 		 * The udp module never sends down a zero-length address,
4488 		 * and allowing this on a labeled system will break MLP
4489 		 * functionality.
4490 		 */
4491 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4492 			goto bad_addr;
4493 
4494 		if (connp->conn_mac_exempt)
4495 			goto bad_addr;
4496 
4497 		/* No hash here really.  The table is big enough. */
4498 		connp->conn_srcv6 = ipv6_all_zeros;
4499 
4500 		ipcl_proto_insert(connp, protocol);
4501 
4502 		tbr->PRIM_type = T_BIND_ACK;
4503 		return (mp);
4504 	}
4505 
4506 	/* Extract the address pointer from the message. */
4507 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4508 	    tbr->ADDR_length);
4509 	if (ucp == NULL) {
4510 		ip1dbg(("ip_bind: no address\n"));
4511 		goto bad_addr;
4512 	}
4513 	if (!OK_32PTR(ucp)) {
4514 		ip1dbg(("ip_bind: unaligned address\n"));
4515 		goto bad_addr;
4516 	}
4517 	/*
4518 	 * Check for trailing mps.
4519 	 */
4520 
4521 	mp1 = mp->b_cont;
4522 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4523 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4524 
4525 	switch (tbr->ADDR_length) {
4526 	default:
4527 		ip1dbg(("ip_bind: bad address length %d\n",
4528 		    (int)tbr->ADDR_length));
4529 		goto bad_addr;
4530 
4531 	case IP_ADDR_LEN:
4532 		/* Verification of local address only */
4533 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4534 		    ire_requested, ipsec_policy_set, B_FALSE);
4535 		break;
4536 
4537 	case sizeof (sin_t):
4538 		sin = (sin_t *)ucp;
4539 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4540 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4541 		break;
4542 
4543 	case sizeof (ipa_conn_t):
4544 		ac = (ipa_conn_t *)ucp;
4545 		/* For raw socket, the local port is not set. */
4546 		if (ac->ac_lport == 0)
4547 			ac->ac_lport = connp->conn_lport;
4548 		/* Always verify destination reachability. */
4549 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4550 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4551 		    ipsec_policy_set, B_TRUE, B_TRUE);
4552 		break;
4553 
4554 	case sizeof (ipa_conn_x_t):
4555 		acx = (ipa_conn_x_t *)ucp;
4556 		/*
4557 		 * Whether or not to verify destination reachability depends
4558 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4559 		 */
4560 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4561 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4562 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4563 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4564 		break;
4565 	}
4566 	if (error == EINPROGRESS)
4567 		return (NULL);
4568 	else if (error != 0)
4569 		goto bad_addr;
4570 	/*
4571 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4572 	 * We can't do this in ip_bind_insert_ire because the policy
4573 	 * may not have been inherited at that point in time and hence
4574 	 * conn_out_enforce_policy may not be set.
4575 	 */
4576 	mp1 = mp->b_cont;
4577 	if (ire_requested && connp->conn_out_enforce_policy &&
4578 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4579 		ire_t *ire = (ire_t *)mp1->b_rptr;
4580 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4581 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4582 	}
4583 
4584 	/* Send it home. */
4585 	mp->b_datap->db_type = M_PCPROTO;
4586 	tbr->PRIM_type = T_BIND_ACK;
4587 	return (mp);
4588 
4589 bad_addr:
4590 	/*
4591 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4592 	 * a unix errno.
4593 	 */
4594 	if (error > 0)
4595 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4596 	else
4597 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4598 	return (mp);
4599 }
4600 
4601 /*
4602  * Here address is verified to be a valid local address.
4603  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4604  * address is also considered a valid local address.
4605  * In the case of a broadcast/multicast address, however, the
4606  * upper protocol is expected to reset the src address
4607  * to 0 if it sees a IRE_BROADCAST type returned so that
4608  * no packets are emitted with broadcast/multicast address as
4609  * source address (that violates hosts requirements RFC1122)
4610  * The addresses valid for bind are:
4611  *	(1) - INADDR_ANY (0)
4612  *	(2) - IP address of an UP interface
4613  *	(3) - IP address of a DOWN interface
4614  *	(4) - valid local IP broadcast addresses. In this case
4615  *	the conn will only receive packets destined to
4616  *	the specified broadcast address.
4617  *	(5) - a multicast address. In this case
4618  *	the conn will only receive packets destined to
4619  *	the specified multicast address. Note: the
4620  *	application still has to issue an
4621  *	IP_ADD_MEMBERSHIP socket option.
4622  *
4623  * On error, return -1 for TBADADDR otherwise pass the
4624  * errno with TSYSERR reply.
4625  *
4626  * In all the above cases, the bound address must be valid in the current zone.
4627  * When the address is loopback, multicast or broadcast, there might be many
4628  * matching IREs so bind has to look up based on the zone.
4629  *
4630  * Note: lport is in network byte order.
4631  */
4632 int
4633 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4634     boolean_t ire_requested, boolean_t ipsec_policy_set,
4635     boolean_t fanout_insert)
4636 {
4637 	int		error = 0;
4638 	ire_t		*src_ire;
4639 	mblk_t		*policy_mp;
4640 	ipif_t		*ipif;
4641 	zoneid_t	zoneid;
4642 
4643 	if (ipsec_policy_set) {
4644 		policy_mp = mp->b_cont;
4645 	}
4646 
4647 	/*
4648 	 * If it was previously connected, conn_fully_bound would have
4649 	 * been set.
4650 	 */
4651 	connp->conn_fully_bound = B_FALSE;
4652 
4653 	src_ire = NULL;
4654 	ipif = NULL;
4655 
4656 	zoneid = IPCL_ZONEID(connp);
4657 
4658 	if (src_addr) {
4659 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4660 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
4661 		/*
4662 		 * If an address other than 0.0.0.0 is requested,
4663 		 * we verify that it is a valid address for bind
4664 		 * Note: Following code is in if-else-if form for
4665 		 * readability compared to a condition check.
4666 		 */
4667 		/* LINTED - statement has no consequent */
4668 		if (IRE_IS_LOCAL(src_ire)) {
4669 			/*
4670 			 * (2) Bind to address of local UP interface
4671 			 */
4672 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4673 			/*
4674 			 * (4) Bind to broadcast address
4675 			 * Note: permitted only from transports that
4676 			 * request IRE
4677 			 */
4678 			if (!ire_requested)
4679 				error = EADDRNOTAVAIL;
4680 		} else {
4681 			/*
4682 			 * (3) Bind to address of local DOWN interface
4683 			 * (ipif_lookup_addr() looks up all interfaces
4684 			 * but we do not get here for UP interfaces
4685 			 * - case (2) above)
4686 			 * We put the protocol byte back into the mblk
4687 			 * since we may come back via ip_wput_nondata()
4688 			 * later with this mblk if ipif_lookup_addr chooses
4689 			 * to defer processing.
4690 			 */
4691 			*mp->b_wptr++ = (char)connp->conn_ulp;
4692 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4693 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4694 			    &error)) != NULL) {
4695 				ipif_refrele(ipif);
4696 			} else if (error == EINPROGRESS) {
4697 				if (src_ire != NULL)
4698 					ire_refrele(src_ire);
4699 				return (EINPROGRESS);
4700 			} else if (CLASSD(src_addr)) {
4701 				error = 0;
4702 				if (src_ire != NULL)
4703 					ire_refrele(src_ire);
4704 				/*
4705 				 * (5) bind to multicast address.
4706 				 * Fake out the IRE returned to upper
4707 				 * layer to be a broadcast IRE.
4708 				 */
4709 				src_ire = ire_ctable_lookup(
4710 				    INADDR_BROADCAST, INADDR_ANY,
4711 				    IRE_BROADCAST, NULL, zoneid, NULL,
4712 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY));
4713 				if (src_ire == NULL || !ire_requested)
4714 					error = EADDRNOTAVAIL;
4715 			} else {
4716 				/*
4717 				 * Not a valid address for bind
4718 				 */
4719 				error = EADDRNOTAVAIL;
4720 			}
4721 			/*
4722 			 * Just to keep it consistent with the processing in
4723 			 * ip_bind_v4()
4724 			 */
4725 			mp->b_wptr--;
4726 		}
4727 		if (error) {
4728 			/* Red Alert!  Attempting to be a bogon! */
4729 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4730 			    ntohl(src_addr)));
4731 			goto bad_addr;
4732 		}
4733 	}
4734 
4735 	/*
4736 	 * Allow setting new policies. For example, disconnects come
4737 	 * down as ipa_t bind. As we would have set conn_policy_cached
4738 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4739 	 * can change after the disconnect.
4740 	 */
4741 	connp->conn_policy_cached = B_FALSE;
4742 
4743 	/*
4744 	 * If not fanout_insert this was just an address verification
4745 	 */
4746 	if (fanout_insert) {
4747 		/*
4748 		 * The addresses have been verified. Time to insert in
4749 		 * the correct fanout list.
4750 		 */
4751 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4752 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4753 		connp->conn_lport = lport;
4754 		connp->conn_fport = 0;
4755 		/*
4756 		 * Do we need to add a check to reject Multicast packets
4757 		 *
4758 		 * We need to make sure that the conn_recv is set to a non-null
4759 		 * value before we insert the conn into the classifier table.
4760 		 * This is to avoid a race with an incoming packet which does an
4761 		 * ipcl_classify().
4762 		 */
4763 		if (*mp->b_wptr == IPPROTO_TCP)
4764 			connp->conn_recv = tcp_conn_request;
4765 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4766 	}
4767 
4768 	if (error == 0) {
4769 		if (ire_requested) {
4770 			if (!ip_bind_insert_ire(mp, src_ire, NULL)) {
4771 				error = -1;
4772 				/* Falls through to bad_addr */
4773 			}
4774 		} else if (ipsec_policy_set) {
4775 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4776 				error = -1;
4777 				/* Falls through to bad_addr */
4778 			}
4779 		}
4780 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4781 		connp->conn_recv = tcp_input;
4782 	}
4783 bad_addr:
4784 	if (error != 0) {
4785 		if (connp->conn_anon_port) {
4786 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4787 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4788 			    B_FALSE);
4789 		}
4790 		connp->conn_mlp_type = mlptSingle;
4791 	}
4792 	if (src_ire != NULL)
4793 		IRE_REFRELE(src_ire);
4794 	if (ipsec_policy_set) {
4795 		ASSERT(policy_mp == mp->b_cont);
4796 		ASSERT(policy_mp != NULL);
4797 		freeb(policy_mp);
4798 		/*
4799 		 * As of now assume that nothing else accompanies
4800 		 * IPSEC_POLICY_SET.
4801 		 */
4802 		mp->b_cont = NULL;
4803 	}
4804 	return (error);
4805 }
4806 
4807 /*
4808  * Verify that both the source and destination addresses
4809  * are valid.  If verify_dst is false, then the destination address may be
4810  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4811  * destination reachability, while tunnels do not.
4812  * Note that we allow connect to broadcast and multicast
4813  * addresses when ire_requested is set. Thus the ULP
4814  * has to check for IRE_BROADCAST and multicast.
4815  *
4816  * Returns zero if ok.
4817  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4818  * (for use with TSYSERR reply).
4819  *
4820  * Note: lport and fport are in network byte order.
4821  */
4822 int
4823 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4824     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4825     boolean_t ire_requested, boolean_t ipsec_policy_set,
4826     boolean_t fanout_insert, boolean_t verify_dst)
4827 {
4828 	ire_t		*src_ire;
4829 	ire_t		*dst_ire;
4830 	int		error = 0;
4831 	int 		protocol;
4832 	mblk_t		*policy_mp;
4833 	ire_t		*sire = NULL;
4834 	ire_t		*md_dst_ire = NULL;
4835 	ire_t		*lso_dst_ire = NULL;
4836 	ill_t		*ill = NULL;
4837 	zoneid_t	zoneid;
4838 	ipaddr_t	src_addr = *src_addrp;
4839 
4840 	src_ire = dst_ire = NULL;
4841 	protocol = *mp->b_wptr & 0xFF;
4842 
4843 	/*
4844 	 * If we never got a disconnect before, clear it now.
4845 	 */
4846 	connp->conn_fully_bound = B_FALSE;
4847 
4848 	if (ipsec_policy_set) {
4849 		policy_mp = mp->b_cont;
4850 	}
4851 
4852 	zoneid = IPCL_ZONEID(connp);
4853 
4854 	if (CLASSD(dst_addr)) {
4855 		/* Pick up an IRE_BROADCAST */
4856 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4857 		    NULL, zoneid, MBLK_GETLABEL(mp),
4858 		    (MATCH_IRE_RECURSIVE |
4859 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4860 		    MATCH_IRE_SECATTR));
4861 	} else {
4862 		/*
4863 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4864 		 * and onlink ipif is not found set ENETUNREACH error.
4865 		 */
4866 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4867 			ipif_t *ipif;
4868 
4869 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4870 			    dst_addr : connp->conn_nexthop_v4,
4871 			    connp->conn_zoneid);
4872 			if (ipif == NULL) {
4873 				error = ENETUNREACH;
4874 				goto bad_addr;
4875 			}
4876 			ipif_refrele(ipif);
4877 		}
4878 
4879 		if (connp->conn_nexthop_set) {
4880 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4881 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4882 			    MATCH_IRE_SECATTR);
4883 		} else {
4884 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4885 			    &sire, zoneid, MBLK_GETLABEL(mp),
4886 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4887 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4888 			    MATCH_IRE_SECATTR));
4889 		}
4890 	}
4891 	/*
4892 	 * dst_ire can't be a broadcast when not ire_requested.
4893 	 * We also prevent ire's with src address INADDR_ANY to
4894 	 * be used, which are created temporarily for
4895 	 * sending out packets from endpoints that have
4896 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4897 	 * reachable.  If verify_dst is false, the destination needn't be
4898 	 * reachable.
4899 	 *
4900 	 * If we match on a reject or black hole, then we've got a
4901 	 * local failure.  May as well fail out the connect() attempt,
4902 	 * since it's never going to succeed.
4903 	 */
4904 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4905 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4906 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4907 		/*
4908 		 * If we're verifying destination reachability, we always want
4909 		 * to complain here.
4910 		 *
4911 		 * If we're not verifying destination reachability but the
4912 		 * destination has a route, we still want to fail on the
4913 		 * temporary address and broadcast address tests.
4914 		 */
4915 		if (verify_dst || (dst_ire != NULL)) {
4916 			if (ip_debug > 2) {
4917 				pr_addr_dbg("ip_bind_connected: bad connected "
4918 				    "dst %s\n", AF_INET, &dst_addr);
4919 			}
4920 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4921 				error = ENETUNREACH;
4922 			else
4923 				error = EHOSTUNREACH;
4924 			goto bad_addr;
4925 		}
4926 	}
4927 
4928 	/*
4929 	 * We now know that routing will allow us to reach the destination.
4930 	 * Check whether Trusted Solaris policy allows communication with this
4931 	 * host, and pretend that the destination is unreachable if not.
4932 	 *
4933 	 * This is never a problem for TCP, since that transport is known to
4934 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4935 	 * handling.  If the remote is unreachable, it will be detected at that
4936 	 * point, so there's no reason to check it here.
4937 	 *
4938 	 * Note that for sendto (and other datagram-oriented friends), this
4939 	 * check is done as part of the data path label computation instead.
4940 	 * The check here is just to make non-TCP connect() report the right
4941 	 * error.
4942 	 */
4943 	if (dst_ire != NULL && is_system_labeled() &&
4944 	    !IPCL_IS_TCP(connp) &&
4945 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4946 	    connp->conn_mac_exempt) != 0) {
4947 		error = EHOSTUNREACH;
4948 		if (ip_debug > 2) {
4949 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4950 			    AF_INET, &dst_addr);
4951 		}
4952 		goto bad_addr;
4953 	}
4954 
4955 	/*
4956 	 * If the app does a connect(), it means that it will most likely
4957 	 * send more than 1 packet to the destination.  It makes sense
4958 	 * to clear the temporary flag.
4959 	 */
4960 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4961 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4962 		irb_t *irb = dst_ire->ire_bucket;
4963 
4964 		rw_enter(&irb->irb_lock, RW_WRITER);
4965 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4966 		irb->irb_tmp_ire_cnt--;
4967 		rw_exit(&irb->irb_lock);
4968 	}
4969 
4970 	/*
4971 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4972 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4973 	 * eligibility tests for passive connects are handled separately
4974 	 * through tcp_adapt_ire().  We do this before the source address
4975 	 * selection, because dst_ire may change after a call to
4976 	 * ipif_select_source().  This is a best-effort check, as the
4977 	 * packet for this connection may not actually go through
4978 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4979 	 * calling ip_newroute().  This is why we further check on the
4980 	 * IRE during LSO/Multidata packet transmission in
4981 	 * tcp_lsosend()/tcp_multisend().
4982 	 */
4983 	if (!ipsec_policy_set && dst_ire != NULL &&
4984 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4985 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4986 		if (ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4987 			lso_dst_ire = dst_ire;
4988 			IRE_REFHOLD(lso_dst_ire);
4989 		} else if (ip_multidata_outbound && ILL_MDT_CAPABLE(ill)) {
4990 			md_dst_ire = dst_ire;
4991 			IRE_REFHOLD(md_dst_ire);
4992 		}
4993 	}
4994 
4995 	if (dst_ire != NULL &&
4996 	    dst_ire->ire_type == IRE_LOCAL &&
4997 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4998 		/*
4999 		 * If the IRE belongs to a different zone, look for a matching
5000 		 * route in the forwarding table and use the source address from
5001 		 * that route.
5002 		 */
5003 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
5004 		    zoneid, 0, NULL,
5005 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
5006 		    MATCH_IRE_RJ_BHOLE);
5007 		if (src_ire == NULL) {
5008 			error = EHOSTUNREACH;
5009 			goto bad_addr;
5010 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5011 			if (!(src_ire->ire_type & IRE_HOST))
5012 				error = ENETUNREACH;
5013 			else
5014 				error = EHOSTUNREACH;
5015 			goto bad_addr;
5016 		}
5017 		if (src_addr == INADDR_ANY)
5018 			src_addr = src_ire->ire_src_addr;
5019 		ire_refrele(src_ire);
5020 		src_ire = NULL;
5021 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5022 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5023 			src_addr = sire->ire_src_addr;
5024 			ire_refrele(dst_ire);
5025 			dst_ire = sire;
5026 			sire = NULL;
5027 		} else {
5028 			/*
5029 			 * Pick a source address so that a proper inbound
5030 			 * load spreading would happen.
5031 			 */
5032 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
5033 			ipif_t *src_ipif = NULL;
5034 			ire_t *ipif_ire;
5035 
5036 			/*
5037 			 * Supply a local source address such that inbound
5038 			 * load spreading happens.
5039 			 *
5040 			 * Determine the best source address on this ill for
5041 			 * the destination.
5042 			 *
5043 			 * 1) For broadcast, we should return a broadcast ire
5044 			 *    found above so that upper layers know that the
5045 			 *    destination address is a broadcast address.
5046 			 *
5047 			 * 2) If this is part of a group, select a better
5048 			 *    source address so that better inbound load
5049 			 *    balancing happens. Do the same if the ipif
5050 			 *    is DEPRECATED.
5051 			 *
5052 			 * 3) If the outgoing interface is part of a usesrc
5053 			 *    group, then try selecting a source address from
5054 			 *    the usesrc ILL.
5055 			 */
5056 			if ((dst_ire->ire_zoneid != zoneid &&
5057 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5058 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5059 			    ((dst_ill->ill_group != NULL) ||
5060 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5061 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
5062 				/*
5063 				 * If the destination is reachable via a
5064 				 * given gateway, the selected source address
5065 				 * should be in the same subnet as the gateway.
5066 				 * Otherwise, the destination is not reachable.
5067 				 *
5068 				 * If there are no interfaces on the same subnet
5069 				 * as the destination, ipif_select_source gives
5070 				 * first non-deprecated interface which might be
5071 				 * on a different subnet than the gateway.
5072 				 * This is not desirable. Hence pass the dst_ire
5073 				 * source address to ipif_select_source.
5074 				 * It is sure that the destination is reachable
5075 				 * with the dst_ire source address subnet.
5076 				 * So passing dst_ire source address to
5077 				 * ipif_select_source will make sure that the
5078 				 * selected source will be on the same subnet
5079 				 * as dst_ire source address.
5080 				 */
5081 				ipaddr_t saddr =
5082 				    dst_ire->ire_ipif->ipif_src_addr;
5083 				src_ipif = ipif_select_source(dst_ill,
5084 				    saddr, zoneid);
5085 				if (src_ipif != NULL) {
5086 					if (IS_VNI(src_ipif->ipif_ill)) {
5087 						/*
5088 						 * For VNI there is no
5089 						 * interface route
5090 						 */
5091 						src_addr =
5092 						    src_ipif->ipif_src_addr;
5093 					} else {
5094 						ipif_ire =
5095 						    ipif_to_ire(src_ipif);
5096 						if (ipif_ire != NULL) {
5097 							IRE_REFRELE(dst_ire);
5098 							dst_ire = ipif_ire;
5099 						}
5100 						src_addr =
5101 						    dst_ire->ire_src_addr;
5102 					}
5103 					ipif_refrele(src_ipif);
5104 				} else {
5105 					src_addr = dst_ire->ire_src_addr;
5106 				}
5107 			} else {
5108 				src_addr = dst_ire->ire_src_addr;
5109 			}
5110 		}
5111 	}
5112 
5113 	/*
5114 	 * We do ire_route_lookup() here (and not
5115 	 * interface lookup as we assert that
5116 	 * src_addr should only come from an
5117 	 * UP interface for hard binding.
5118 	 */
5119 	ASSERT(src_ire == NULL);
5120 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5121 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY);
5122 	/* src_ire must be a local|loopback */
5123 	if (!IRE_IS_LOCAL(src_ire)) {
5124 		if (ip_debug > 2) {
5125 			pr_addr_dbg("ip_bind_connected: bad connected "
5126 			    "src %s\n", AF_INET, &src_addr);
5127 		}
5128 		error = EADDRNOTAVAIL;
5129 		goto bad_addr;
5130 	}
5131 
5132 	/*
5133 	 * If the source address is a loopback address, the
5134 	 * destination had best be local or multicast.
5135 	 * The transports that can't handle multicast will reject
5136 	 * those addresses.
5137 	 */
5138 	if (src_ire->ire_type == IRE_LOOPBACK &&
5139 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5140 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5141 		error = -1;
5142 		goto bad_addr;
5143 	}
5144 
5145 	/*
5146 	 * Allow setting new policies. For example, disconnects come
5147 	 * down as ipa_t bind. As we would have set conn_policy_cached
5148 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5149 	 * can change after the disconnect.
5150 	 */
5151 	connp->conn_policy_cached = B_FALSE;
5152 
5153 	/*
5154 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5155 	 * can handle their passed-in conn's.
5156 	 */
5157 
5158 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5159 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5160 	connp->conn_lport = lport;
5161 	connp->conn_fport = fport;
5162 	*src_addrp = src_addr;
5163 
5164 	ASSERT(!(ipsec_policy_set && ire_requested));
5165 	if (ire_requested) {
5166 		iulp_t *ulp_info = NULL;
5167 
5168 		/*
5169 		 * Note that sire will not be NULL if this is an off-link
5170 		 * connection and there is not cache for that dest yet.
5171 		 *
5172 		 * XXX Because of an existing bug, if there are multiple
5173 		 * default routes, the IRE returned now may not be the actual
5174 		 * default route used (default routes are chosen in a
5175 		 * round robin fashion).  So if the metrics for different
5176 		 * default routes are different, we may return the wrong
5177 		 * metrics.  This will not be a problem if the existing
5178 		 * bug is fixed.
5179 		 */
5180 		if (sire != NULL) {
5181 			ulp_info = &(sire->ire_uinfo);
5182 		}
5183 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info)) {
5184 			error = -1;
5185 			goto bad_addr;
5186 		}
5187 	} else if (ipsec_policy_set) {
5188 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5189 			error = -1;
5190 			goto bad_addr;
5191 		}
5192 	}
5193 
5194 	/*
5195 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5196 	 * we'll cache that.  If we don't, we'll inherit global policy.
5197 	 *
5198 	 * We can't insert until the conn reflects the policy. Note that
5199 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5200 	 * connections where we don't have a policy. This is to prevent
5201 	 * global policy lookups in the inbound path.
5202 	 *
5203 	 * If we insert before we set conn_policy_cached,
5204 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5205 	 * because global policy cound be non-empty. We normally call
5206 	 * ipsec_check_policy() for conn_policy_cached connections only if
5207 	 * ipc_in_enforce_policy is set. But in this case,
5208 	 * conn_policy_cached can get set anytime since we made the
5209 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5210 	 * called, which will make the above assumption false.  Thus, we
5211 	 * need to insert after we set conn_policy_cached.
5212 	 */
5213 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5214 		goto bad_addr;
5215 
5216 	if (fanout_insert) {
5217 		/*
5218 		 * The addresses have been verified. Time to insert in
5219 		 * the correct fanout list.
5220 		 * We need to make sure that the conn_recv is set to a non-null
5221 		 * value before we insert into the classifier table to avoid a
5222 		 * race with an incoming packet which does an ipcl_classify().
5223 		 */
5224 		if (protocol == IPPROTO_TCP)
5225 			connp->conn_recv = tcp_input;
5226 		error = ipcl_conn_insert(connp, protocol, src_addr,
5227 		    dst_addr, connp->conn_ports);
5228 	}
5229 
5230 	if (error == 0) {
5231 		connp->conn_fully_bound = B_TRUE;
5232 		/*
5233 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5234 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5235 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5236 		 * ip_xxinfo_return(), which performs further checks
5237 		 * against them and upon success, returns the LSO/MDT info
5238 		 * mblk which we will attach to the bind acknowledgment.
5239 		 */
5240 		if (lso_dst_ire != NULL) {
5241 			mblk_t *lsoinfo_mp;
5242 
5243 			ASSERT(ill->ill_lso_capab != NULL);
5244 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5245 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5246 				linkb(mp, lsoinfo_mp);
5247 		} else if (md_dst_ire != NULL) {
5248 			mblk_t *mdinfo_mp;
5249 
5250 			ASSERT(ill->ill_mdt_capab != NULL);
5251 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5252 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5253 				linkb(mp, mdinfo_mp);
5254 		}
5255 	}
5256 bad_addr:
5257 	if (ipsec_policy_set) {
5258 		ASSERT(policy_mp == mp->b_cont);
5259 		ASSERT(policy_mp != NULL);
5260 		freeb(policy_mp);
5261 		/*
5262 		 * As of now assume that nothing else accompanies
5263 		 * IPSEC_POLICY_SET.
5264 		 */
5265 		mp->b_cont = NULL;
5266 	}
5267 	if (src_ire != NULL)
5268 		IRE_REFRELE(src_ire);
5269 	if (dst_ire != NULL)
5270 		IRE_REFRELE(dst_ire);
5271 	if (sire != NULL)
5272 		IRE_REFRELE(sire);
5273 	if (md_dst_ire != NULL)
5274 		IRE_REFRELE(md_dst_ire);
5275 	if (lso_dst_ire != NULL)
5276 		IRE_REFRELE(lso_dst_ire);
5277 	return (error);
5278 }
5279 
5280 /*
5281  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5282  * Prefers dst_ire over src_ire.
5283  */
5284 static boolean_t
5285 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info)
5286 {
5287 	mblk_t	*mp1;
5288 	ire_t *ret_ire = NULL;
5289 
5290 	mp1 = mp->b_cont;
5291 	ASSERT(mp1 != NULL);
5292 
5293 	if (ire != NULL) {
5294 		/*
5295 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5296 		 * appended mblk. Its <upper protocol>'s
5297 		 * job to make sure there is room.
5298 		 */
5299 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5300 			return (0);
5301 
5302 		mp1->b_datap->db_type = IRE_DB_TYPE;
5303 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5304 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5305 		ret_ire = (ire_t *)mp1->b_rptr;
5306 		/*
5307 		 * Pass the latest setting of the ip_path_mtu_discovery and
5308 		 * copy the ulp info if any.
5309 		 */
5310 		ret_ire->ire_frag_flag |= (ip_path_mtu_discovery) ?
5311 		    IPH_DF : 0;
5312 		if (ulp_info != NULL) {
5313 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5314 			    sizeof (iulp_t));
5315 		}
5316 		ret_ire->ire_mp = mp1;
5317 	} else {
5318 		/*
5319 		 * No IRE was found. Remove IRE mblk.
5320 		 */
5321 		mp->b_cont = mp1->b_cont;
5322 		freeb(mp1);
5323 	}
5324 
5325 	return (1);
5326 }
5327 
5328 /*
5329  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5330  * the final piece where we don't.  Return a pointer to the first mblk in the
5331  * result, and update the pointer to the next mblk to chew on.  If anything
5332  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5333  * NULL pointer.
5334  */
5335 mblk_t *
5336 ip_carve_mp(mblk_t **mpp, ssize_t len)
5337 {
5338 	mblk_t	*mp0;
5339 	mblk_t	*mp1;
5340 	mblk_t	*mp2;
5341 
5342 	if (!len || !mpp || !(mp0 = *mpp))
5343 		return (NULL);
5344 	/* If we aren't going to consume the first mblk, we need a dup. */
5345 	if (mp0->b_wptr - mp0->b_rptr > len) {
5346 		mp1 = dupb(mp0);
5347 		if (mp1) {
5348 			/* Partition the data between the two mblks. */
5349 			mp1->b_wptr = mp1->b_rptr + len;
5350 			mp0->b_rptr = mp1->b_wptr;
5351 			/*
5352 			 * after adjustments if mblk not consumed is now
5353 			 * unaligned, try to align it. If this fails free
5354 			 * all messages and let upper layer recover.
5355 			 */
5356 			if (!OK_32PTR(mp0->b_rptr)) {
5357 				if (!pullupmsg(mp0, -1)) {
5358 					freemsg(mp0);
5359 					freemsg(mp1);
5360 					*mpp = NULL;
5361 					return (NULL);
5362 				}
5363 			}
5364 		}
5365 		return (mp1);
5366 	}
5367 	/* Eat through as many mblks as we need to get len bytes. */
5368 	len -= mp0->b_wptr - mp0->b_rptr;
5369 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5370 		if (mp2->b_wptr - mp2->b_rptr > len) {
5371 			/*
5372 			 * We won't consume the entire last mblk.  Like
5373 			 * above, dup and partition it.
5374 			 */
5375 			mp1->b_cont = dupb(mp2);
5376 			mp1 = mp1->b_cont;
5377 			if (!mp1) {
5378 				/*
5379 				 * Trouble.  Rather than go to a lot of
5380 				 * trouble to clean up, we free the messages.
5381 				 * This won't be any worse than losing it on
5382 				 * the wire.
5383 				 */
5384 				freemsg(mp0);
5385 				freemsg(mp2);
5386 				*mpp = NULL;
5387 				return (NULL);
5388 			}
5389 			mp1->b_wptr = mp1->b_rptr + len;
5390 			mp2->b_rptr = mp1->b_wptr;
5391 			/*
5392 			 * after adjustments if mblk not consumed is now
5393 			 * unaligned, try to align it. If this fails free
5394 			 * all messages and let upper layer recover.
5395 			 */
5396 			if (!OK_32PTR(mp2->b_rptr)) {
5397 				if (!pullupmsg(mp2, -1)) {
5398 					freemsg(mp0);
5399 					freemsg(mp2);
5400 					*mpp = NULL;
5401 					return (NULL);
5402 				}
5403 			}
5404 			*mpp = mp2;
5405 			return (mp0);
5406 		}
5407 		/* Decrement len by the amount we just got. */
5408 		len -= mp2->b_wptr - mp2->b_rptr;
5409 	}
5410 	/*
5411 	 * len should be reduced to zero now.  If not our caller has
5412 	 * screwed up.
5413 	 */
5414 	if (len) {
5415 		/* Shouldn't happen! */
5416 		freemsg(mp0);
5417 		*mpp = NULL;
5418 		return (NULL);
5419 	}
5420 	/*
5421 	 * We consumed up to exactly the end of an mblk.  Detach the part
5422 	 * we are returning from the rest of the chain.
5423 	 */
5424 	mp1->b_cont = NULL;
5425 	*mpp = mp2;
5426 	return (mp0);
5427 }
5428 
5429 /* The ill stream is being unplumbed. Called from ip_close */
5430 int
5431 ip_modclose(ill_t *ill)
5432 {
5433 
5434 	boolean_t success;
5435 	ipsq_t	*ipsq;
5436 	ipif_t	*ipif;
5437 	queue_t	*q = ill->ill_rq;
5438 	hook_nic_event_t *info;
5439 	clock_t timeout;
5440 
5441 	/*
5442 	 * Wait for the ACKs of all deferred control messages to be processed.
5443 	 * In particular, we wait for a potential capability reset initiated
5444 	 * in ip_sioctl_plink() to complete before proceeding.
5445 	 *
5446 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5447 	 * in case the driver never replies.
5448 	 */
5449 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5450 	mutex_enter(&ill->ill_lock);
5451 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5452 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5453 			/* Timeout */
5454 			break;
5455 		}
5456 	}
5457 	mutex_exit(&ill->ill_lock);
5458 
5459 	/*
5460 	 * Forcibly enter the ipsq after some delay. This is to take
5461 	 * care of the case when some ioctl does not complete because
5462 	 * we sent a control message to the driver and it did not
5463 	 * send us a reply. We want to be able to at least unplumb
5464 	 * and replumb rather than force the user to reboot the system.
5465 	 */
5466 	success = ipsq_enter(ill, B_FALSE);
5467 
5468 	/*
5469 	 * Open/close/push/pop is guaranteed to be single threaded
5470 	 * per stream by STREAMS. FS guarantees that all references
5471 	 * from top are gone before close is called. So there can't
5472 	 * be another close thread that has set CONDEMNED on this ill.
5473 	 * and cause ipsq_enter to return failure.
5474 	 */
5475 	ASSERT(success);
5476 	ipsq = ill->ill_phyint->phyint_ipsq;
5477 
5478 	/*
5479 	 * Mark it condemned. No new reference will be made to this ill.
5480 	 * Lookup functions will return an error. Threads that try to
5481 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5482 	 * that the refcnt will drop down to zero.
5483 	 */
5484 	mutex_enter(&ill->ill_lock);
5485 	ill->ill_state_flags |= ILL_CONDEMNED;
5486 	for (ipif = ill->ill_ipif; ipif != NULL;
5487 	    ipif = ipif->ipif_next) {
5488 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5489 	}
5490 	/*
5491 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5492 	 * returns  error if ILL_CONDEMNED is set
5493 	 */
5494 	cv_broadcast(&ill->ill_cv);
5495 	mutex_exit(&ill->ill_lock);
5496 
5497 	/*
5498 	 * Send all the deferred control messages downstream which came in
5499 	 * during the small window right before ipsq_enter(). We do this
5500 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5501 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5502 	 */
5503 	ill_send_all_deferred_mp(ill);
5504 
5505 	/*
5506 	 * Shut down fragmentation reassembly.
5507 	 * ill_frag_timer won't start a timer again.
5508 	 * Now cancel any existing timer
5509 	 */
5510 	(void) untimeout(ill->ill_frag_timer_id);
5511 	(void) ill_frag_timeout(ill, 0);
5512 
5513 	/*
5514 	 * If MOVE was in progress, clear the
5515 	 * move_in_progress fields also.
5516 	 */
5517 	if (ill->ill_move_in_progress) {
5518 		ILL_CLEAR_MOVE(ill);
5519 	}
5520 
5521 	/*
5522 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5523 	 * this ill. Then wait for the refcnts to drop to zero.
5524 	 * ill_is_quiescent checks whether the ill is really quiescent.
5525 	 * Then make sure that threads that are waiting to enter the
5526 	 * ipsq have seen the error returned by ipsq_enter and have
5527 	 * gone away. Then we call ill_delete_tail which does the
5528 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5529 	 */
5530 	ill_delete(ill);
5531 	mutex_enter(&ill->ill_lock);
5532 	while (!ill_is_quiescent(ill))
5533 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5534 	while (ill->ill_waiters)
5535 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5536 
5537 	mutex_exit(&ill->ill_lock);
5538 
5539 	/* qprocsoff is called in ill_delete_tail */
5540 	ill_delete_tail(ill);
5541 
5542 	/*
5543 	 * Walk through all upper (conn) streams and qenable
5544 	 * those that have queued data.
5545 	 * close synchronization needs this to
5546 	 * be done to ensure that all upper layers blocked
5547 	 * due to flow control to the closing device
5548 	 * get unblocked.
5549 	 */
5550 	ip1dbg(("ip_wsrv: walking\n"));
5551 	conn_walk_drain();
5552 
5553 	mutex_enter(&ip_mi_lock);
5554 	mi_close_unlink(&ip_g_head, (IDP)ill);
5555 	mutex_exit(&ip_mi_lock);
5556 
5557 	/*
5558 	 * credp could be null if the open didn't succeed and ip_modopen
5559 	 * itself calls ip_close.
5560 	 */
5561 	if (ill->ill_credp != NULL)
5562 		crfree(ill->ill_credp);
5563 
5564 	/*
5565 	 * Unhook the nic event message from the ill and enqueue it into the nic
5566 	 * event taskq.
5567 	 */
5568 	if ((info = ill->ill_nic_event_info) != NULL) {
5569 		if (ddi_taskq_dispatch(eventq_queue_nic, ip_ne_queue_func,
5570 		    (void *)info, DDI_SLEEP) == DDI_FAILURE) {
5571 			ip2dbg(("ip_ioctl_finish:ddi_taskq_dispatch failed\n"));
5572 			if (info->hne_data != NULL)
5573 				kmem_free(info->hne_data, info->hne_datalen);
5574 			kmem_free(info, sizeof (hook_nic_event_t));
5575 		}
5576 		ill->ill_nic_event_info = NULL;
5577 	}
5578 
5579 	mi_close_free((IDP)ill);
5580 	q->q_ptr = WR(q)->q_ptr = NULL;
5581 
5582 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5583 
5584 	return (0);
5585 }
5586 
5587 /*
5588  * This is called as part of close() for both IP and UDP
5589  * in order to quiesce the conn.
5590  */
5591 void
5592 ip_quiesce_conn(conn_t *connp)
5593 {
5594 	boolean_t	drain_cleanup_reqd = B_FALSE;
5595 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5596 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5597 
5598 	ASSERT(!IPCL_IS_TCP(connp));
5599 
5600 	/*
5601 	 * Mark the conn as closing, and this conn must not be
5602 	 * inserted in future into any list. Eg. conn_drain_insert(),
5603 	 * won't insert this conn into the conn_drain_list.
5604 	 * Similarly ill_pending_mp_add() will not add any mp to
5605 	 * the pending mp list, after this conn has started closing.
5606 	 *
5607 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5608 	 * cannot get set henceforth.
5609 	 */
5610 	mutex_enter(&connp->conn_lock);
5611 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5612 	connp->conn_state_flags |= CONN_CLOSING;
5613 	if (connp->conn_idl != NULL)
5614 		drain_cleanup_reqd = B_TRUE;
5615 	if (connp->conn_oper_pending_ill != NULL)
5616 		conn_ioctl_cleanup_reqd = B_TRUE;
5617 	if (connp->conn_ilg_inuse != 0)
5618 		ilg_cleanup_reqd = B_TRUE;
5619 	mutex_exit(&connp->conn_lock);
5620 
5621 	if (IPCL_IS_UDP(connp))
5622 		udp_quiesce_conn(connp);
5623 
5624 	if (conn_ioctl_cleanup_reqd)
5625 		conn_ioctl_cleanup(connp);
5626 
5627 	if (is_system_labeled() && connp->conn_anon_port) {
5628 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5629 		    connp->conn_mlp_type, connp->conn_ulp,
5630 		    ntohs(connp->conn_lport), B_FALSE);
5631 		connp->conn_anon_port = 0;
5632 	}
5633 	connp->conn_mlp_type = mlptSingle;
5634 
5635 	/*
5636 	 * Remove this conn from any fanout list it is on.
5637 	 * and then wait for any threads currently operating
5638 	 * on this endpoint to finish
5639 	 */
5640 	ipcl_hash_remove(connp);
5641 
5642 	/*
5643 	 * Remove this conn from the drain list, and do
5644 	 * any other cleanup that may be required.
5645 	 * (Only non-tcp streams may have a non-null conn_idl.
5646 	 * TCP streams are never flow controlled, and
5647 	 * conn_idl will be null)
5648 	 */
5649 	if (drain_cleanup_reqd)
5650 		conn_drain_tail(connp, B_TRUE);
5651 
5652 	if (connp->conn_rq == ip_g_mrouter || connp->conn_wq == ip_g_mrouter)
5653 		(void) ip_mrouter_done(NULL);
5654 
5655 	if (ilg_cleanup_reqd)
5656 		ilg_delete_all(connp);
5657 
5658 	conn_delete_ire(connp, NULL);
5659 
5660 	/*
5661 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5662 	 * callers from write side can't be there now because close
5663 	 * is in progress. The only other caller is ipcl_walk
5664 	 * which checks for the condemned flag.
5665 	 */
5666 	mutex_enter(&connp->conn_lock);
5667 	connp->conn_state_flags |= CONN_CONDEMNED;
5668 	while (connp->conn_ref != 1)
5669 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5670 	connp->conn_state_flags |= CONN_QUIESCED;
5671 	mutex_exit(&connp->conn_lock);
5672 }
5673 
5674 /* ARGSUSED */
5675 int
5676 ip_close(queue_t *q, int flags)
5677 {
5678 	conn_t		*connp;
5679 
5680 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5681 
5682 	/*
5683 	 * Call the appropriate delete routine depending on whether this is
5684 	 * a module or device.
5685 	 */
5686 	if (WR(q)->q_next != NULL) {
5687 		/* This is a module close */
5688 		return (ip_modclose((ill_t *)q->q_ptr));
5689 	}
5690 
5691 	connp = q->q_ptr;
5692 	ip_quiesce_conn(connp);
5693 
5694 	qprocsoff(q);
5695 
5696 	/*
5697 	 * Now we are truly single threaded on this stream, and can
5698 	 * delete the things hanging off the connp, and finally the connp.
5699 	 * We removed this connp from the fanout list, it cannot be
5700 	 * accessed thru the fanouts, and we already waited for the
5701 	 * conn_ref to drop to 0. We are already in close, so
5702 	 * there cannot be any other thread from the top. qprocsoff
5703 	 * has completed, and service has completed or won't run in
5704 	 * future.
5705 	 */
5706 	ASSERT(connp->conn_ref == 1);
5707 
5708 	/*
5709 	 * A conn which was previously marked as IPCL_UDP cannot
5710 	 * retain the flag because it would have been cleared by
5711 	 * udp_close().
5712 	 */
5713 	ASSERT(!IPCL_IS_UDP(connp));
5714 
5715 	if (connp->conn_latch != NULL) {
5716 		IPLATCH_REFRELE(connp->conn_latch);
5717 		connp->conn_latch = NULL;
5718 	}
5719 	if (connp->conn_policy != NULL) {
5720 		IPPH_REFRELE(connp->conn_policy);
5721 		connp->conn_policy = NULL;
5722 	}
5723 	if (connp->conn_ipsec_opt_mp != NULL) {
5724 		freemsg(connp->conn_ipsec_opt_mp);
5725 		connp->conn_ipsec_opt_mp = NULL;
5726 	}
5727 
5728 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5729 
5730 	connp->conn_ref--;
5731 	ipcl_conn_destroy(connp);
5732 
5733 	q->q_ptr = WR(q)->q_ptr = NULL;
5734 	return (0);
5735 }
5736 
5737 int
5738 ip_snmpmod_close(queue_t *q)
5739 {
5740 	conn_t *connp = Q_TO_CONN(q);
5741 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5742 
5743 	qprocsoff(q);
5744 
5745 	if (connp->conn_flags & IPCL_UDPMOD)
5746 		udp_close_free(connp);
5747 
5748 	if (connp->conn_cred != NULL) {
5749 		crfree(connp->conn_cred);
5750 		connp->conn_cred = NULL;
5751 	}
5752 	CONN_DEC_REF(connp);
5753 	q->q_ptr = WR(q)->q_ptr = NULL;
5754 	return (0);
5755 }
5756 
5757 /*
5758  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5759  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5760  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5761  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5762  * queues as we never enqueue messages there and we don't handle any ioctls.
5763  * Everything else is freed.
5764  */
5765 void
5766 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5767 {
5768 	conn_t	*connp = q->q_ptr;
5769 	pfi_t	setfn;
5770 	pfi_t	getfn;
5771 
5772 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5773 
5774 	switch (DB_TYPE(mp)) {
5775 	case M_PROTO:
5776 	case M_PCPROTO:
5777 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5778 		    ((((union T_primitives *)mp->b_rptr)->type ==
5779 			T_SVR4_OPTMGMT_REQ) ||
5780 		    (((union T_primitives *)mp->b_rptr)->type ==
5781 			T_OPTMGMT_REQ))) {
5782 			/*
5783 			 * This is the only TPI primitive supported. Its
5784 			 * handling does not require tcp_t, but it does require
5785 			 * conn_t to check permissions.
5786 			 */
5787 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5788 
5789 			if (connp->conn_flags & IPCL_TCPMOD) {
5790 				setfn = tcp_snmp_set;
5791 				getfn = tcp_snmp_get;
5792 			} else {
5793 				setfn = udp_snmp_set;
5794 				getfn = udp_snmp_get;
5795 			}
5796 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5797 				freemsg(mp);
5798 				return;
5799 			}
5800 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5801 		    != NULL)
5802 			qreply(q, mp);
5803 		break;
5804 	case M_FLUSH:
5805 	case M_IOCTL:
5806 		putnext(q, mp);
5807 		break;
5808 	default:
5809 		freemsg(mp);
5810 		break;
5811 	}
5812 }
5813 
5814 /* Return the IP checksum for the IP header at "iph". */
5815 uint16_t
5816 ip_csum_hdr(ipha_t *ipha)
5817 {
5818 	uint16_t	*uph;
5819 	uint32_t	sum;
5820 	int		opt_len;
5821 
5822 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5823 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5824 	uph = (uint16_t *)ipha;
5825 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5826 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5827 	if (opt_len > 0) {
5828 		do {
5829 			sum += uph[10];
5830 			sum += uph[11];
5831 			uph += 2;
5832 		} while (--opt_len);
5833 	}
5834 	sum = (sum & 0xFFFF) + (sum >> 16);
5835 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5836 	if (sum == 0xffff)
5837 		sum = 0;
5838 	return ((uint16_t)sum);
5839 }
5840 
5841 void
5842 ip_ddi_destroy(void)
5843 {
5844 	ipv4_hook_destroy();
5845 	ipv6_hook_destroy();
5846 	ip_net_destroy();
5847 
5848 	tnet_fini();
5849 	tcp_ddi_destroy();
5850 	sctp_ddi_destroy();
5851 	ipsec_loader_destroy();
5852 	ipsec_policy_destroy();
5853 	ipsec_kstat_destroy();
5854 	nd_free(&ip_g_nd);
5855 	mutex_destroy(&igmp_timer_lock);
5856 	mutex_destroy(&mld_timer_lock);
5857 	mutex_destroy(&igmp_slowtimeout_lock);
5858 	mutex_destroy(&mld_slowtimeout_lock);
5859 	mutex_destroy(&ip_mi_lock);
5860 	mutex_destroy(&rts_clients.connf_lock);
5861 	ip_ire_fini();
5862 	ip6_asp_free();
5863 	conn_drain_fini();
5864 	ipcl_destroy();
5865 	inet_minor_destroy(ip_minor_arena);
5866 	icmp_kstat_fini();
5867 	ip_kstat_fini();
5868 	rw_destroy(&ipsec_capab_ills_lock);
5869 	rw_destroy(&ill_g_usesrc_lock);
5870 	ip_drop_unregister(&ip_dropper);
5871 }
5872 
5873 
5874 void
5875 ip_ddi_init(void)
5876 {
5877 	TCP6_MAJ = ddi_name_to_major(TCP6);
5878 	TCP_MAJ	= ddi_name_to_major(TCP);
5879 	SCTP_MAJ = ddi_name_to_major(SCTP);
5880 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5881 
5882 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5883 
5884 	/* IP's IPsec code calls the packet dropper */
5885 	ip_drop_register(&ip_dropper, "IP IPsec processing");
5886 
5887 	if (!ip_g_nd) {
5888 		if (!ip_param_register(lcl_param_arr, A_CNT(lcl_param_arr),
5889 		    lcl_ndp_arr, A_CNT(lcl_ndp_arr))) {
5890 			nd_free(&ip_g_nd);
5891 		}
5892 	}
5893 
5894 	ipsec_loader_init();
5895 	ipsec_policy_init();
5896 	ipsec_kstat_init();
5897 	rw_init(&ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5898 	mutex_init(&igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5899 	mutex_init(&mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5900 	mutex_init(&igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5901 	mutex_init(&mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5902 	mutex_init(&ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5903 	mutex_init(&ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5904 	rw_init(&ill_g_lock, NULL, RW_DEFAULT, NULL);
5905 	rw_init(&ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5906 	rw_init(&ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5907 
5908 	/*
5909 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5910 	 * initial devices: ip, ip6, tcp, tcp6.
5911 	 */
5912 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5913 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5914 		cmn_err(CE_PANIC,
5915 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5916 	}
5917 
5918 	ipcl_init();
5919 	mutex_init(&rts_clients.connf_lock, NULL, MUTEX_DEFAULT, NULL);
5920 	ip_ire_init();
5921 	ip6_asp_init();
5922 	ipif_init();
5923 	conn_drain_init();
5924 	tcp_ddi_init();
5925 	sctp_ddi_init();
5926 
5927 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5928 
5929 	if ((ip_kstat = kstat_create("ip", 0, "ipstat",
5930 		"net", KSTAT_TYPE_NAMED,
5931 		sizeof (ip_statistics) / sizeof (kstat_named_t),
5932 		KSTAT_FLAG_VIRTUAL)) != NULL) {
5933 		ip_kstat->ks_data = &ip_statistics;
5934 		kstat_install(ip_kstat);
5935 	}
5936 	ip_kstat_init();
5937 	ip6_kstat_init();
5938 	icmp_kstat_init();
5939 	ipsec_loader_start();
5940 	tnet_init();
5941 
5942 	ip_net_init();
5943 	ipv4_hook_init();
5944 	ipv6_hook_init();
5945 }
5946 
5947 /*
5948  * Allocate and initialize a DLPI template of the specified length.  (May be
5949  * called as writer.)
5950  */
5951 mblk_t *
5952 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5953 {
5954 	mblk_t	*mp;
5955 
5956 	mp = allocb(len, BPRI_MED);
5957 	if (!mp)
5958 		return (NULL);
5959 
5960 	/*
5961 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5962 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5963 	 * that other DLPI are M_PROTO.
5964 	 */
5965 	if (prim == DL_INFO_REQ) {
5966 		mp->b_datap->db_type = M_PCPROTO;
5967 	} else {
5968 		mp->b_datap->db_type = M_PROTO;
5969 	}
5970 
5971 	mp->b_wptr = mp->b_rptr + len;
5972 	bzero(mp->b_rptr, len);
5973 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
5974 	return (mp);
5975 }
5976 
5977 const char *
5978 dlpi_prim_str(int prim)
5979 {
5980 	switch (prim) {
5981 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
5982 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
5983 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
5984 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
5985 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
5986 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
5987 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
5988 	case DL_OK_ACK:		return ("DL_OK_ACK");
5989 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
5990 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
5991 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
5992 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
5993 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
5994 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
5995 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
5996 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
5997 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
5998 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
5999 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6000 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6001 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6002 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6003 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6004 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6005 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6006 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6007 	default:		return ("<unknown primitive>");
6008 	}
6009 }
6010 
6011 const char *
6012 dlpi_err_str(int err)
6013 {
6014 	switch (err) {
6015 	case DL_ACCESS:		return ("DL_ACCESS");
6016 	case DL_BADADDR:	return ("DL_BADADDR");
6017 	case DL_BADCORR:	return ("DL_BADCORR");
6018 	case DL_BADDATA:	return ("DL_BADDATA");
6019 	case DL_BADPPA:		return ("DL_BADPPA");
6020 	case DL_BADPRIM:	return ("DL_BADPRIM");
6021 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6022 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6023 	case DL_BADSAP:		return ("DL_BADSAP");
6024 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6025 	case DL_BOUND:		return ("DL_BOUND");
6026 	case DL_INITFAILED:	return ("DL_INITFAILED");
6027 	case DL_NOADDR:		return ("DL_NOADDR");
6028 	case DL_NOTINIT:	return ("DL_NOTINIT");
6029 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6030 	case DL_SYSERR:		return ("DL_SYSERR");
6031 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6032 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6033 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6034 	case DL_TOOMANY:	return ("DL_TOOMANY");
6035 	case DL_NOTENAB:	return ("DL_NOTENAB");
6036 	case DL_BUSY:		return ("DL_BUSY");
6037 	case DL_NOAUTO:		return ("DL_NOAUTO");
6038 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6039 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6040 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6041 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6042 	case DL_PENDING:	return ("DL_PENDING");
6043 	default:		return ("<unknown error>");
6044 	}
6045 }
6046 
6047 /*
6048  * Debug formatting routine.  Returns a character string representation of the
6049  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6050  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6051  *
6052  * Once the ndd table-printing interfaces are removed, this can be changed to
6053  * standard dotted-decimal form.
6054  */
6055 char *
6056 ip_dot_addr(ipaddr_t addr, char *buf)
6057 {
6058 	uint8_t *ap = (uint8_t *)&addr;
6059 
6060 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6061 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6062 	return (buf);
6063 }
6064 
6065 /*
6066  * Write the given MAC address as a printable string in the usual colon-
6067  * separated format.
6068  */
6069 const char *
6070 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6071 {
6072 	char *bp;
6073 
6074 	if (alen == 0 || buflen < 4)
6075 		return ("?");
6076 	bp = buf;
6077 	for (;;) {
6078 		/*
6079 		 * If there are more MAC address bytes available, but we won't
6080 		 * have any room to print them, then add "..." to the string
6081 		 * instead.  See below for the 'magic number' explanation.
6082 		 */
6083 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6084 			(void) strcpy(bp, "...");
6085 			break;
6086 		}
6087 		(void) sprintf(bp, "%02x", *addr++);
6088 		bp += 2;
6089 		if (--alen == 0)
6090 			break;
6091 		*bp++ = ':';
6092 		buflen -= 3;
6093 		/*
6094 		 * At this point, based on the first 'if' statement above,
6095 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6096 		 * buflen >= 4.  The first case leaves room for the final "xx"
6097 		 * number and trailing NUL byte.  The second leaves room for at
6098 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6099 		 * that statement.
6100 		 */
6101 	}
6102 	return (buf);
6103 }
6104 
6105 /*
6106  * Send an ICMP error after patching up the packet appropriately.  Returns
6107  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6108  */
6109 static boolean_t
6110 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6111     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present, zoneid_t zoneid)
6112 {
6113 	ipha_t *ipha;
6114 	mblk_t *first_mp;
6115 	boolean_t secure;
6116 	unsigned char db_type;
6117 
6118 	first_mp = mp;
6119 	if (mctl_present) {
6120 		mp = mp->b_cont;
6121 		secure = ipsec_in_is_secure(first_mp);
6122 		ASSERT(mp != NULL);
6123 	} else {
6124 		/*
6125 		 * If this is an ICMP error being reported - which goes
6126 		 * up as M_CTLs, we need to convert them to M_DATA till
6127 		 * we finish checking with global policy because
6128 		 * ipsec_check_global_policy() assumes M_DATA as clear
6129 		 * and M_CTL as secure.
6130 		 */
6131 		db_type = DB_TYPE(mp);
6132 		DB_TYPE(mp) = M_DATA;
6133 		secure = B_FALSE;
6134 	}
6135 	/*
6136 	 * We are generating an icmp error for some inbound packet.
6137 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6138 	 * Before we generate an error, check with global policy
6139 	 * to see whether this is allowed to enter the system. As
6140 	 * there is no "conn", we are checking with global policy.
6141 	 */
6142 	ipha = (ipha_t *)mp->b_rptr;
6143 	if (secure || ipsec_inbound_v4_policy_present) {
6144 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6145 		    ipha, NULL, mctl_present);
6146 		if (first_mp == NULL)
6147 			return (B_FALSE);
6148 	}
6149 
6150 	if (!mctl_present)
6151 		DB_TYPE(mp) = db_type;
6152 
6153 	if (flags & IP_FF_SEND_ICMP) {
6154 		if (flags & IP_FF_HDR_COMPLETE) {
6155 			if (ip_hdr_complete(ipha, zoneid)) {
6156 				freemsg(first_mp);
6157 				return (B_TRUE);
6158 			}
6159 		}
6160 		if (flags & IP_FF_CKSUM) {
6161 			/*
6162 			 * Have to correct checksum since
6163 			 * the packet might have been
6164 			 * fragmented and the reassembly code in ip_rput
6165 			 * does not restore the IP checksum.
6166 			 */
6167 			ipha->ipha_hdr_checksum = 0;
6168 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6169 		}
6170 		switch (icmp_type) {
6171 		case ICMP_DEST_UNREACHABLE:
6172 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid);
6173 			break;
6174 		default:
6175 			freemsg(first_mp);
6176 			break;
6177 		}
6178 	} else {
6179 		freemsg(first_mp);
6180 		return (B_FALSE);
6181 	}
6182 
6183 	return (B_TRUE);
6184 }
6185 
6186 /*
6187  * Used to send an ICMP error message when a packet is received for
6188  * a protocol that is not supported. The mblk passed as argument
6189  * is consumed by this function.
6190  */
6191 void
6192 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid)
6193 {
6194 	mblk_t *mp;
6195 	ipha_t *ipha;
6196 	ill_t *ill;
6197 	ipsec_in_t *ii;
6198 
6199 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6200 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6201 
6202 	mp = ipsec_mp->b_cont;
6203 	ipsec_mp->b_cont = NULL;
6204 	ipha = (ipha_t *)mp->b_rptr;
6205 	/* Get ill from index in ipsec_in_t. */
6206 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6207 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL);
6208 	if (ill != NULL) {
6209 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6210 			if (ip_fanout_send_icmp(q, mp, flags,
6211 			    ICMP_DEST_UNREACHABLE,
6212 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid)) {
6213 				BUMP_MIB(ill->ill_ip_mib,
6214 				    ipIfStatsInUnknownProtos);
6215 			}
6216 		} else {
6217 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6218 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6219 			    0, B_FALSE, zoneid)) {
6220 				BUMP_MIB(ill->ill_ip_mib,
6221 				    ipIfStatsInUnknownProtos);
6222 			}
6223 		}
6224 		ill_refrele(ill);
6225 	} else { /* re-link for the freemsg() below. */
6226 		ipsec_mp->b_cont = mp;
6227 	}
6228 
6229 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6230 	freemsg(ipsec_mp);
6231 }
6232 
6233 /*
6234  * See if the inbound datagram has had IPsec processing applied to it.
6235  */
6236 boolean_t
6237 ipsec_in_is_secure(mblk_t *ipsec_mp)
6238 {
6239 	ipsec_in_t *ii;
6240 
6241 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6242 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6243 
6244 	if (ii->ipsec_in_loopback) {
6245 		return (ii->ipsec_in_secure);
6246 	} else {
6247 		return (ii->ipsec_in_ah_sa != NULL ||
6248 		    ii->ipsec_in_esp_sa != NULL ||
6249 		    ii->ipsec_in_decaps);
6250 	}
6251 }
6252 
6253 /*
6254  * Handle protocols with which IP is less intimate.  There
6255  * can be more than one stream bound to a particular
6256  * protocol.  When this is the case, normally each one gets a copy
6257  * of any incoming packets.
6258  *
6259  * IPSEC NOTE :
6260  *
6261  * Don't allow a secure packet going up a non-secure connection.
6262  * We don't allow this because
6263  *
6264  * 1) Reply might go out in clear which will be dropped at
6265  *    the sending side.
6266  * 2) If the reply goes out in clear it will give the
6267  *    adversary enough information for getting the key in
6268  *    most of the cases.
6269  *
6270  * Moreover getting a secure packet when we expect clear
6271  * implies that SA's were added without checking for
6272  * policy on both ends. This should not happen once ISAKMP
6273  * is used to negotiate SAs as SAs will be added only after
6274  * verifying the policy.
6275  *
6276  * NOTE : If the packet was tunneled and not multicast we only send
6277  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6278  * back to delivering packets to AF_INET6 raw sockets.
6279  *
6280  * IPQoS Notes:
6281  * Once we have determined the client, invoke IPPF processing.
6282  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6283  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6284  * ip_policy will be false.
6285  *
6286  * Zones notes:
6287  * Currently only applications in the global zone can create raw sockets for
6288  * protocols other than ICMP. So unlike the broadcast / multicast case of
6289  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6290  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6291  */
6292 static void
6293 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6294     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6295     zoneid_t zoneid)
6296 {
6297 	queue_t	*rq;
6298 	mblk_t	*mp1, *first_mp1;
6299 	uint_t	protocol = ipha->ipha_protocol;
6300 	ipaddr_t dst;
6301 	boolean_t one_only;
6302 	mblk_t *first_mp = mp;
6303 	boolean_t secure;
6304 	uint32_t ill_index;
6305 	conn_t	*connp, *first_connp, *next_connp;
6306 	connf_t	*connfp;
6307 	boolean_t shared_addr;
6308 	mib2_ipIfStatsEntry_t *mibptr;
6309 
6310 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ip_mib;
6311 	if (mctl_present) {
6312 		mp = first_mp->b_cont;
6313 		secure = ipsec_in_is_secure(first_mp);
6314 		ASSERT(mp != NULL);
6315 	} else {
6316 		secure = B_FALSE;
6317 	}
6318 	dst = ipha->ipha_dst;
6319 	/*
6320 	 * If the packet was tunneled and not multicast we only send to it
6321 	 * the first match.
6322 	 */
6323 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6324 	    !CLASSD(dst));
6325 
6326 	shared_addr = (zoneid == ALL_ZONES);
6327 	if (shared_addr) {
6328 		/*
6329 		 * We don't allow multilevel ports for raw IP, so no need to
6330 		 * check for that here.
6331 		 */
6332 		zoneid = tsol_packet_to_zoneid(mp);
6333 	}
6334 
6335 	connfp = &ipcl_proto_fanout[protocol];
6336 	mutex_enter(&connfp->connf_lock);
6337 	connp = connfp->connf_head;
6338 	for (connp = connfp->connf_head; connp != NULL;
6339 		connp = connp->conn_next) {
6340 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6341 		    zoneid) &&
6342 		    (!is_system_labeled() ||
6343 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6344 		    connp)))
6345 			break;
6346 	}
6347 
6348 	if (connp == NULL || connp->conn_upq == NULL) {
6349 		/*
6350 		 * No one bound to these addresses.  Is
6351 		 * there a client that wants all
6352 		 * unclaimed datagrams?
6353 		 */
6354 		mutex_exit(&connfp->connf_lock);
6355 		/*
6356 		 * Check for IPPROTO_ENCAP...
6357 		 */
6358 		if (protocol == IPPROTO_ENCAP && ip_g_mrouter) {
6359 			/*
6360 			 * If an IPsec mblk is here on a multicast
6361 			 * tunnel (using ip_mroute stuff), check policy here,
6362 			 * THEN ship off to ip_mroute_decap().
6363 			 *
6364 			 * BTW,  If I match a configured IP-in-IP
6365 			 * tunnel, this path will not be reached, and
6366 			 * ip_mroute_decap will never be called.
6367 			 */
6368 			first_mp = ipsec_check_global_policy(first_mp, connp,
6369 			    ipha, NULL, mctl_present);
6370 			if (first_mp != NULL) {
6371 				if (mctl_present)
6372 					freeb(first_mp);
6373 				ip_mroute_decap(q, mp);
6374 			} /* Else we already freed everything! */
6375 		} else {
6376 			/*
6377 			 * Otherwise send an ICMP protocol unreachable.
6378 			 */
6379 			if (ip_fanout_send_icmp(q, first_mp, flags,
6380 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6381 			    mctl_present, zoneid)) {
6382 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6383 			}
6384 		}
6385 		return;
6386 	}
6387 	CONN_INC_REF(connp);
6388 	first_connp = connp;
6389 
6390 	/*
6391 	 * Only send message to one tunnel driver by immediately
6392 	 * terminating the loop.
6393 	 */
6394 	connp = one_only ? NULL : connp->conn_next;
6395 
6396 	for (;;) {
6397 		while (connp != NULL) {
6398 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6399 			    flags, zoneid) &&
6400 			    (!is_system_labeled() ||
6401 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6402 			    shared_addr, connp)))
6403 				break;
6404 			connp = connp->conn_next;
6405 		}
6406 
6407 		/*
6408 		 * Copy the packet.
6409 		 */
6410 		if (connp == NULL || connp->conn_upq == NULL ||
6411 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6412 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6413 			/*
6414 			 * No more interested clients or memory
6415 			 * allocation failed
6416 			 */
6417 			connp = first_connp;
6418 			break;
6419 		}
6420 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6421 		CONN_INC_REF(connp);
6422 		mutex_exit(&connfp->connf_lock);
6423 		rq = connp->conn_rq;
6424 		if (!canputnext(rq)) {
6425 			if (flags & IP_FF_RAWIP) {
6426 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6427 			} else {
6428 				BUMP_MIB(&icmp_mib, icmpInOverflows);
6429 			}
6430 
6431 			freemsg(first_mp1);
6432 		} else {
6433 			/*
6434 			 * Don't enforce here if we're an actual tunnel -
6435 			 * let "tun" do it instead.
6436 			 */
6437 			if (!IPCL_IS_IPTUN(connp) &&
6438 			    (CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6439 				first_mp1 = ipsec_check_inbound_policy
6440 				    (first_mp1, connp, ipha, NULL,
6441 				    mctl_present);
6442 			}
6443 			if (first_mp1 != NULL) {
6444 				int in_flags = 0;
6445 				/*
6446 				 * ip_fanout_proto also gets called from
6447 				 * icmp_inbound_error_fanout, in which case
6448 				 * the msg type is M_CTL.  Don't add info
6449 				 * in this case for the time being. In future
6450 				 * when there is a need for knowing the
6451 				 * inbound iface index for ICMP error msgs,
6452 				 * then this can be changed.
6453 				 */
6454 				if (connp->conn_recvif)
6455 					in_flags = IPF_RECVIF;
6456 				/*
6457 				 * The ULP may support IP_RECVPKTINFO for both
6458 				 * IP v4 and v6 so pass the appropriate argument
6459 				 * based on conn IP version.
6460 				 */
6461 				if (connp->conn_ip_recvpktinfo) {
6462 					if (connp->conn_af_isv6) {
6463 						/*
6464 						 * V6 only needs index
6465 						 */
6466 						in_flags |= IPF_RECVIF;
6467 					} else {
6468 						/*
6469 						 * V4 needs index +
6470 						 * matching address.
6471 						 */
6472 						in_flags |= IPF_RECVADDR;
6473 					}
6474 				}
6475 				if ((in_flags != 0) &&
6476 				    (mp->b_datap->db_type != M_CTL)) {
6477 					/*
6478 					 * the actual data will be
6479 					 * contained in b_cont upon
6480 					 * successful return of the
6481 					 * following call else
6482 					 * original mblk is returned
6483 					 */
6484 					ASSERT(recv_ill != NULL);
6485 					mp1 = ip_add_info(mp1, recv_ill,
6486 					    in_flags, IPCL_ZONEID(connp));
6487 				}
6488 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6489 				if (mctl_present)
6490 					freeb(first_mp1);
6491 				putnext(rq, mp1);
6492 			}
6493 		}
6494 		mutex_enter(&connfp->connf_lock);
6495 		/* Follow the next pointer before releasing the conn. */
6496 		next_connp = connp->conn_next;
6497 		CONN_DEC_REF(connp);
6498 		connp = next_connp;
6499 	}
6500 
6501 	/* Last one.  Send it upstream. */
6502 	mutex_exit(&connfp->connf_lock);
6503 
6504 	/*
6505 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6506 	 * will be set to false.
6507 	 */
6508 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6509 		ill_index = ill->ill_phyint->phyint_ifindex;
6510 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6511 		if (mp == NULL) {
6512 			CONN_DEC_REF(connp);
6513 			if (mctl_present) {
6514 				freeb(first_mp);
6515 			}
6516 			return;
6517 		}
6518 	}
6519 
6520 	rq = connp->conn_rq;
6521 	if (!canputnext(rq)) {
6522 		if (flags & IP_FF_RAWIP) {
6523 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6524 		} else {
6525 			BUMP_MIB(&icmp_mib, icmpInOverflows);
6526 		}
6527 
6528 		freemsg(first_mp);
6529 	} else {
6530 		if (IPCL_IS_IPTUN(connp)) {
6531 			/*
6532 			 * Tunneled packet.  We enforce policy in the tunnel
6533 			 * module itself.
6534 			 *
6535 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6536 			 * a policy check.
6537 			 */
6538 			putnext(rq, first_mp);
6539 			CONN_DEC_REF(connp);
6540 			return;
6541 		}
6542 
6543 		if ((CONN_INBOUND_POLICY_PRESENT(connp) || secure)) {
6544 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6545 			    ipha, NULL, mctl_present);
6546 		}
6547 
6548 		if (first_mp != NULL) {
6549 			int in_flags = 0;
6550 
6551 			/*
6552 			 * ip_fanout_proto also gets called
6553 			 * from icmp_inbound_error_fanout, in
6554 			 * which case the msg type is M_CTL.
6555 			 * Don't add info in this case for time
6556 			 * being. In future when there is a
6557 			 * need for knowing the inbound iface
6558 			 * index for ICMP error msgs, then this
6559 			 * can be changed
6560 			 */
6561 			if (connp->conn_recvif)
6562 				in_flags = IPF_RECVIF;
6563 			if (connp->conn_ip_recvpktinfo) {
6564 				if (connp->conn_af_isv6) {
6565 					/*
6566 					 * V6 only needs index
6567 					 */
6568 					in_flags |= IPF_RECVIF;
6569 				} else {
6570 					/*
6571 					 * V4 needs index +
6572 					 * matching address.
6573 					 */
6574 					in_flags |= IPF_RECVADDR;
6575 				}
6576 			}
6577 			if ((in_flags != 0) &&
6578 			    (mp->b_datap->db_type != M_CTL)) {
6579 
6580 				/*
6581 				 * the actual data will be contained in
6582 				 * b_cont upon successful return
6583 				 * of the following call else original
6584 				 * mblk is returned
6585 				 */
6586 				ASSERT(recv_ill != NULL);
6587 				mp = ip_add_info(mp, recv_ill,
6588 				    in_flags, IPCL_ZONEID(connp));
6589 			}
6590 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6591 			putnext(rq, mp);
6592 			if (mctl_present)
6593 				freeb(first_mp);
6594 		}
6595 	}
6596 	CONN_DEC_REF(connp);
6597 }
6598 
6599 /*
6600  * Fanout for TCP packets
6601  * The caller puts <fport, lport> in the ports parameter.
6602  *
6603  * IPQoS Notes
6604  * Before sending it to the client, invoke IPPF processing.
6605  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6606  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6607  * ip_policy is false.
6608  */
6609 static void
6610 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6611     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6612 {
6613 	mblk_t  *first_mp;
6614 	boolean_t secure;
6615 	uint32_t ill_index;
6616 	int	ip_hdr_len;
6617 	tcph_t	*tcph;
6618 	boolean_t syn_present = B_FALSE;
6619 	conn_t	*connp;
6620 
6621 	ASSERT(recv_ill != NULL);
6622 
6623 	first_mp = mp;
6624 	if (mctl_present) {
6625 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6626 		mp = first_mp->b_cont;
6627 		secure = ipsec_in_is_secure(first_mp);
6628 		ASSERT(mp != NULL);
6629 	} else {
6630 		secure = B_FALSE;
6631 	}
6632 
6633 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6634 
6635 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
6636 	    NULL) {
6637 		/*
6638 		 * No connected connection or listener. Send a
6639 		 * TH_RST via tcp_xmit_listeners_reset.
6640 		 */
6641 
6642 		/* Initiate IPPf processing, if needed. */
6643 		if (IPP_ENABLED(IPP_LOCAL_IN)) {
6644 			uint32_t ill_index;
6645 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6646 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6647 			if (first_mp == NULL)
6648 				return;
6649 		}
6650 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6651 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6652 		    zoneid));
6653 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6654 		return;
6655 	}
6656 
6657 	/*
6658 	 * Allocate the SYN for the TCP connection here itself
6659 	 */
6660 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6661 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6662 		if (IPCL_IS_TCP(connp)) {
6663 			squeue_t *sqp;
6664 
6665 			/*
6666 			 * For fused tcp loopback, assign the eager's
6667 			 * squeue to be that of the active connect's.
6668 			 * Note that we don't check for IP_FF_LOOPBACK
6669 			 * here since this routine gets called only
6670 			 * for loopback (unlike the IPv6 counterpart).
6671 			 */
6672 			ASSERT(Q_TO_CONN(q) != NULL);
6673 			if (do_tcp_fusion &&
6674 			    !CONN_INBOUND_POLICY_PRESENT(connp) && !secure &&
6675 			    !IPP_ENABLED(IPP_LOCAL_IN) && !ip_policy &&
6676 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6677 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6678 				sqp = Q_TO_CONN(q)->conn_sqp;
6679 			} else {
6680 				sqp = IP_SQUEUE_GET(lbolt);
6681 			}
6682 
6683 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6684 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6685 			syn_present = B_TRUE;
6686 		}
6687 	}
6688 
6689 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6690 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6691 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6692 		if ((flags & TH_RST) || (flags & TH_URG)) {
6693 			CONN_DEC_REF(connp);
6694 			freemsg(first_mp);
6695 			return;
6696 		}
6697 		if (flags & TH_ACK) {
6698 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
6699 			CONN_DEC_REF(connp);
6700 			return;
6701 		}
6702 
6703 		CONN_DEC_REF(connp);
6704 		freemsg(first_mp);
6705 		return;
6706 	}
6707 
6708 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6709 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6710 		    NULL, mctl_present);
6711 		if (first_mp == NULL) {
6712 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6713 			CONN_DEC_REF(connp);
6714 			return;
6715 		}
6716 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6717 			ASSERT(syn_present);
6718 			if (mctl_present) {
6719 				ASSERT(first_mp != mp);
6720 				first_mp->b_datap->db_struioflag |=
6721 				    STRUIO_POLICY;
6722 			} else {
6723 				ASSERT(first_mp == mp);
6724 				mp->b_datap->db_struioflag &=
6725 				    ~STRUIO_EAGER;
6726 				mp->b_datap->db_struioflag |=
6727 				    STRUIO_POLICY;
6728 			}
6729 		} else {
6730 			/*
6731 			 * Discard first_mp early since we're dealing with a
6732 			 * fully-connected conn_t and tcp doesn't do policy in
6733 			 * this case.
6734 			 */
6735 			if (mctl_present) {
6736 				freeb(first_mp);
6737 				mctl_present = B_FALSE;
6738 			}
6739 			first_mp = mp;
6740 		}
6741 	}
6742 
6743 	/*
6744 	 * Initiate policy processing here if needed. If we get here from
6745 	 * icmp_inbound_error_fanout, ip_policy is false.
6746 	 */
6747 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6748 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6749 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6750 		if (mp == NULL) {
6751 			CONN_DEC_REF(connp);
6752 			if (mctl_present)
6753 				freeb(first_mp);
6754 			return;
6755 		} else if (mctl_present) {
6756 			ASSERT(first_mp != mp);
6757 			first_mp->b_cont = mp;
6758 		} else {
6759 			first_mp = mp;
6760 		}
6761 	}
6762 
6763 
6764 
6765 	/* Handle socket options. */
6766 	if (!syn_present &&
6767 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6768 		/* Add header */
6769 		ASSERT(recv_ill != NULL);
6770 		/*
6771 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6772 		 * IPF_RECVIF.
6773 		 */
6774 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp));
6775 		if (mp == NULL) {
6776 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6777 			CONN_DEC_REF(connp);
6778 			if (mctl_present)
6779 				freeb(first_mp);
6780 			return;
6781 		} else if (mctl_present) {
6782 			/*
6783 			 * ip_add_info might return a new mp.
6784 			 */
6785 			ASSERT(first_mp != mp);
6786 			first_mp->b_cont = mp;
6787 		} else {
6788 			first_mp = mp;
6789 		}
6790 	}
6791 
6792 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6793 	if (IPCL_IS_TCP(connp)) {
6794 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6795 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6796 	} else {
6797 		putnext(connp->conn_rq, first_mp);
6798 		CONN_DEC_REF(connp);
6799 	}
6800 }
6801 
6802 /*
6803  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6804  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6805  * Caller is responsible for dropping references to the conn, and freeing
6806  * first_mp.
6807  *
6808  * IPQoS Notes
6809  * Before sending it to the client, invoke IPPF processing. Policy processing
6810  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6811  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6812  * ip_wput_local, ip_policy is false.
6813  */
6814 static void
6815 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6816     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6817     boolean_t ip_policy)
6818 {
6819 	boolean_t	mctl_present = (first_mp != NULL);
6820 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6821 	uint32_t	ill_index;
6822 
6823 	ASSERT(ill != NULL);
6824 
6825 	if (mctl_present)
6826 		first_mp->b_cont = mp;
6827 	else
6828 		first_mp = mp;
6829 
6830 	if (CONN_UDP_FLOWCTLD(connp)) {
6831 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6832 		freemsg(first_mp);
6833 		return;
6834 	}
6835 
6836 	if (CONN_INBOUND_POLICY_PRESENT(connp) || secure) {
6837 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6838 		    NULL, mctl_present);
6839 		if (first_mp == NULL) {
6840 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6841 			return;	/* Freed by ipsec_check_inbound_policy(). */
6842 		}
6843 	}
6844 	if (mctl_present)
6845 		freeb(first_mp);
6846 
6847 	/* Handle options. */
6848 	if (connp->conn_recvif)
6849 		in_flags = IPF_RECVIF;
6850 	/*
6851 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6852 	 * passed to ip_add_info is based on IP version of connp.
6853 	 */
6854 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6855 		if (connp->conn_af_isv6) {
6856 			/*
6857 			 * V6 only needs index
6858 			 */
6859 			in_flags |= IPF_RECVIF;
6860 		} else {
6861 			/*
6862 			 * V4 needs index + matching address.
6863 			 */
6864 			in_flags |= IPF_RECVADDR;
6865 		}
6866 	}
6867 
6868 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6869 		in_flags |= IPF_RECVSLLA;
6870 
6871 	/*
6872 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6873 	 * freed if the packet is dropped. The caller will do so.
6874 	 */
6875 	if (IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) {
6876 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6877 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6878 		if (mp == NULL) {
6879 			return;
6880 		}
6881 	}
6882 	if ((in_flags != 0) &&
6883 	    (mp->b_datap->db_type != M_CTL)) {
6884 		/*
6885 		 * The actual data will be contained in b_cont
6886 		 * upon successful return of the following call
6887 		 * else original mblk is returned
6888 		 */
6889 		ASSERT(recv_ill != NULL);
6890 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp));
6891 	}
6892 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
6893 	/* Send it upstream */
6894 	CONN_UDP_RECV(connp, mp);
6895 }
6896 
6897 /*
6898  * Fanout for UDP packets.
6899  * The caller puts <fport, lport> in the ports parameter.
6900  *
6901  * If SO_REUSEADDR is set all multicast and broadcast packets
6902  * will be delivered to all streams bound to the same port.
6903  *
6904  * Zones notes:
6905  * Multicast and broadcast packets will be distributed to streams in all zones.
6906  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
6907  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
6908  * packets. To maintain this behavior with multiple zones, the conns are grouped
6909  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
6910  * each zone. If unset, all the following conns in the same zone are skipped.
6911  */
6912 static void
6913 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
6914     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
6915     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
6916 {
6917 	uint32_t	dstport, srcport;
6918 	ipaddr_t	dst;
6919 	mblk_t		*first_mp;
6920 	boolean_t	secure;
6921 	in6_addr_t	v6src;
6922 	conn_t		*connp;
6923 	connf_t		*connfp;
6924 	conn_t		*first_connp;
6925 	conn_t		*next_connp;
6926 	mblk_t		*mp1, *first_mp1;
6927 	ipaddr_t	src;
6928 	zoneid_t	last_zoneid;
6929 	boolean_t	reuseaddr;
6930 	boolean_t	shared_addr;
6931 
6932 	first_mp = mp;
6933 	if (mctl_present) {
6934 		mp = first_mp->b_cont;
6935 		first_mp->b_cont = NULL;
6936 		secure = ipsec_in_is_secure(first_mp);
6937 		ASSERT(mp != NULL);
6938 	} else {
6939 		first_mp = NULL;
6940 		secure = B_FALSE;
6941 	}
6942 
6943 	/* Extract ports in net byte order */
6944 	dstport = htons(ntohl(ports) & 0xFFFF);
6945 	srcport = htons(ntohl(ports) >> 16);
6946 	dst = ipha->ipha_dst;
6947 	src = ipha->ipha_src;
6948 
6949 	shared_addr = (zoneid == ALL_ZONES);
6950 	if (shared_addr) {
6951 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
6952 		if (zoneid == ALL_ZONES)
6953 			zoneid = tsol_packet_to_zoneid(mp);
6954 	}
6955 
6956 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
6957 	mutex_enter(&connfp->connf_lock);
6958 	connp = connfp->connf_head;
6959 	if (!broadcast && !CLASSD(dst)) {
6960 		/*
6961 		 * Not broadcast or multicast. Send to the one (first)
6962 		 * client we find. No need to check conn_wantpacket()
6963 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
6964 		 * IPv4 unicast packets.
6965 		 */
6966 		while ((connp != NULL) &&
6967 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
6968 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
6969 			connp = connp->conn_next;
6970 		}
6971 
6972 		if (connp == NULL || connp->conn_upq == NULL)
6973 			goto notfound;
6974 
6975 		if (is_system_labeled() &&
6976 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6977 		    connp))
6978 			goto notfound;
6979 
6980 		CONN_INC_REF(connp);
6981 		mutex_exit(&connfp->connf_lock);
6982 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
6983 		    flags, recv_ill, ip_policy);
6984 		IP_STAT(ip_udp_fannorm);
6985 		CONN_DEC_REF(connp);
6986 		return;
6987 	}
6988 
6989 	/*
6990 	 * Broadcast and multicast case
6991 	 *
6992 	 * Need to check conn_wantpacket().
6993 	 * If SO_REUSEADDR has been set on the first we send the
6994 	 * packet to all clients that have joined the group and
6995 	 * match the port.
6996 	 */
6997 
6998 	while (connp != NULL) {
6999 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7000 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7001 		    (!is_system_labeled() ||
7002 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7003 		    connp)))
7004 			break;
7005 		connp = connp->conn_next;
7006 	}
7007 
7008 	if (connp == NULL || connp->conn_upq == NULL)
7009 		goto notfound;
7010 
7011 	first_connp = connp;
7012 	/*
7013 	 * When SO_REUSEADDR is not set, send the packet only to the first
7014 	 * matching connection in its zone by keeping track of the zoneid.
7015 	 */
7016 	reuseaddr = first_connp->conn_reuseaddr;
7017 	last_zoneid = first_connp->conn_zoneid;
7018 
7019 	CONN_INC_REF(connp);
7020 	connp = connp->conn_next;
7021 	for (;;) {
7022 		while (connp != NULL) {
7023 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7024 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7025 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7026 			    (!is_system_labeled() ||
7027 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7028 			    shared_addr, connp)))
7029 				break;
7030 			connp = connp->conn_next;
7031 		}
7032 		/*
7033 		 * Just copy the data part alone. The mctl part is
7034 		 * needed just for verifying policy and it is never
7035 		 * sent up.
7036 		 */
7037 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7038 		    ((mp1 = copymsg(mp)) == NULL))) {
7039 			/*
7040 			 * No more interested clients or memory
7041 			 * allocation failed
7042 			 */
7043 			connp = first_connp;
7044 			break;
7045 		}
7046 		if (connp->conn_zoneid != last_zoneid) {
7047 			/*
7048 			 * Update the zoneid so that the packet isn't sent to
7049 			 * any more conns in the same zone unless SO_REUSEADDR
7050 			 * is set.
7051 			 */
7052 			reuseaddr = connp->conn_reuseaddr;
7053 			last_zoneid = connp->conn_zoneid;
7054 		}
7055 		if (first_mp != NULL) {
7056 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7057 			    ipsec_info_type == IPSEC_IN);
7058 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7059 			if (first_mp1 == NULL) {
7060 				freemsg(mp1);
7061 				connp = first_connp;
7062 				break;
7063 			}
7064 		} else {
7065 			first_mp1 = NULL;
7066 		}
7067 		CONN_INC_REF(connp);
7068 		mutex_exit(&connfp->connf_lock);
7069 		/*
7070 		 * IPQoS notes: We don't send the packet for policy
7071 		 * processing here, will do it for the last one (below).
7072 		 * i.e. we do it per-packet now, but if we do policy
7073 		 * processing per-conn, then we would need to do it
7074 		 * here too.
7075 		 */
7076 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7077 		    ipha, flags, recv_ill, B_FALSE);
7078 		mutex_enter(&connfp->connf_lock);
7079 		/* Follow the next pointer before releasing the conn. */
7080 		next_connp = connp->conn_next;
7081 		IP_STAT(ip_udp_fanmb);
7082 		CONN_DEC_REF(connp);
7083 		connp = next_connp;
7084 	}
7085 
7086 	/* Last one.  Send it upstream. */
7087 	mutex_exit(&connfp->connf_lock);
7088 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7089 	    recv_ill, ip_policy);
7090 	IP_STAT(ip_udp_fanmb);
7091 	CONN_DEC_REF(connp);
7092 	return;
7093 
7094 notfound:
7095 
7096 	mutex_exit(&connfp->connf_lock);
7097 	IP_STAT(ip_udp_fanothers);
7098 	/*
7099 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7100 	 * have already been matched above, since they live in the IPv4
7101 	 * fanout tables. This implies we only need to
7102 	 * check for IPv6 in6addr_any endpoints here.
7103 	 * Thus we compare using ipv6_all_zeros instead of the destination
7104 	 * address, except for the multicast group membership lookup which
7105 	 * uses the IPv4 destination.
7106 	 */
7107 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7108 	connfp = &ipcl_udp_fanout[IPCL_UDP_HASH(dstport)];
7109 	mutex_enter(&connfp->connf_lock);
7110 	connp = connfp->connf_head;
7111 	if (!broadcast && !CLASSD(dst)) {
7112 		while (connp != NULL) {
7113 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7114 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7115 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7116 			    !connp->conn_ipv6_v6only)
7117 				break;
7118 			connp = connp->conn_next;
7119 		}
7120 
7121 		if (connp != NULL && is_system_labeled() &&
7122 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7123 		    connp))
7124 			connp = NULL;
7125 
7126 		if (connp == NULL || connp->conn_upq == NULL) {
7127 			/*
7128 			 * No one bound to this port.  Is
7129 			 * there a client that wants all
7130 			 * unclaimed datagrams?
7131 			 */
7132 			mutex_exit(&connfp->connf_lock);
7133 
7134 			if (mctl_present)
7135 				first_mp->b_cont = mp;
7136 			else
7137 				first_mp = mp;
7138 			if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7139 				ip_fanout_proto(q, first_mp, ill, ipha,
7140 				    flags | IP_FF_RAWIP, mctl_present,
7141 				    ip_policy, recv_ill, zoneid);
7142 			} else {
7143 				if (ip_fanout_send_icmp(q, first_mp, flags,
7144 				    ICMP_DEST_UNREACHABLE,
7145 				    ICMP_PORT_UNREACHABLE,
7146 				    mctl_present, zoneid)) {
7147 					BUMP_MIB(ill->ill_ip_mib,
7148 					    udpIfStatsNoPorts);
7149 				}
7150 			}
7151 			return;
7152 		}
7153 
7154 		CONN_INC_REF(connp);
7155 		mutex_exit(&connfp->connf_lock);
7156 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7157 		    flags, recv_ill, ip_policy);
7158 		CONN_DEC_REF(connp);
7159 		return;
7160 	}
7161 	/*
7162 	 * IPv4 multicast packet being delivered to an AF_INET6
7163 	 * in6addr_any endpoint.
7164 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7165 	 * and not conn_wantpacket_v6() since any multicast membership is
7166 	 * for an IPv4-mapped multicast address.
7167 	 * The packet is sent to all clients in all zones that have joined the
7168 	 * group and match the port.
7169 	 */
7170 	while (connp != NULL) {
7171 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7172 		    srcport, v6src) &&
7173 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7174 		    (!is_system_labeled() ||
7175 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7176 		    connp)))
7177 			break;
7178 		connp = connp->conn_next;
7179 	}
7180 
7181 	if (connp == NULL || connp->conn_upq == NULL) {
7182 		/*
7183 		 * No one bound to this port.  Is
7184 		 * there a client that wants all
7185 		 * unclaimed datagrams?
7186 		 */
7187 		mutex_exit(&connfp->connf_lock);
7188 
7189 		if (mctl_present)
7190 			first_mp->b_cont = mp;
7191 		else
7192 			first_mp = mp;
7193 		if (ipcl_proto_search(IPPROTO_UDP) != NULL) {
7194 			ip_fanout_proto(q, first_mp, ill, ipha,
7195 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7196 			    recv_ill, zoneid);
7197 		} else {
7198 			/*
7199 			 * We used to attempt to send an icmp error here, but
7200 			 * since this is known to be a multicast packet
7201 			 * and we don't send icmp errors in response to
7202 			 * multicast, just drop the packet and give up sooner.
7203 			 */
7204 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7205 			freemsg(first_mp);
7206 		}
7207 		return;
7208 	}
7209 
7210 	first_connp = connp;
7211 
7212 	CONN_INC_REF(connp);
7213 	connp = connp->conn_next;
7214 	for (;;) {
7215 		while (connp != NULL) {
7216 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7217 			    ipv6_all_zeros, srcport, v6src) &&
7218 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7219 			    (!is_system_labeled() ||
7220 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7221 			    shared_addr, connp)))
7222 				break;
7223 			connp = connp->conn_next;
7224 		}
7225 		/*
7226 		 * Just copy the data part alone. The mctl part is
7227 		 * needed just for verifying policy and it is never
7228 		 * sent up.
7229 		 */
7230 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7231 		    ((mp1 = copymsg(mp)) == NULL))) {
7232 			/*
7233 			 * No more intested clients or memory
7234 			 * allocation failed
7235 			 */
7236 			connp = first_connp;
7237 			break;
7238 		}
7239 		if (first_mp != NULL) {
7240 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7241 			    ipsec_info_type == IPSEC_IN);
7242 			first_mp1 = ipsec_in_tag(first_mp, NULL);
7243 			if (first_mp1 == NULL) {
7244 				freemsg(mp1);
7245 				connp = first_connp;
7246 				break;
7247 			}
7248 		} else {
7249 			first_mp1 = NULL;
7250 		}
7251 		CONN_INC_REF(connp);
7252 		mutex_exit(&connfp->connf_lock);
7253 		/*
7254 		 * IPQoS notes: We don't send the packet for policy
7255 		 * processing here, will do it for the last one (below).
7256 		 * i.e. we do it per-packet now, but if we do policy
7257 		 * processing per-conn, then we would need to do it
7258 		 * here too.
7259 		 */
7260 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7261 		    ipha, flags, recv_ill, B_FALSE);
7262 		mutex_enter(&connfp->connf_lock);
7263 		/* Follow the next pointer before releasing the conn. */
7264 		next_connp = connp->conn_next;
7265 		CONN_DEC_REF(connp);
7266 		connp = next_connp;
7267 	}
7268 
7269 	/* Last one.  Send it upstream. */
7270 	mutex_exit(&connfp->connf_lock);
7271 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7272 	    recv_ill, ip_policy);
7273 	CONN_DEC_REF(connp);
7274 }
7275 
7276 /*
7277  * Complete the ip_wput header so that it
7278  * is possible to generate ICMP
7279  * errors.
7280  */
7281 int
7282 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid)
7283 {
7284 	ire_t *ire;
7285 
7286 	if (ipha->ipha_src == INADDR_ANY) {
7287 		ire = ire_lookup_local(zoneid);
7288 		if (ire == NULL) {
7289 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7290 			return (1);
7291 		}
7292 		ipha->ipha_src = ire->ire_addr;
7293 		ire_refrele(ire);
7294 	}
7295 	ipha->ipha_ttl = ip_def_ttl;
7296 	ipha->ipha_hdr_checksum = 0;
7297 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7298 	return (0);
7299 }
7300 
7301 /*
7302  * Nobody should be sending
7303  * packets up this stream
7304  */
7305 static void
7306 ip_lrput(queue_t *q, mblk_t *mp)
7307 {
7308 	mblk_t *mp1;
7309 
7310 	switch (mp->b_datap->db_type) {
7311 	case M_FLUSH:
7312 		/* Turn around */
7313 		if (*mp->b_rptr & FLUSHW) {
7314 			*mp->b_rptr &= ~FLUSHR;
7315 			qreply(q, mp);
7316 			return;
7317 		}
7318 		break;
7319 	}
7320 	/* Could receive messages that passed through ar_rput */
7321 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7322 		mp1->b_prev = mp1->b_next = NULL;
7323 	freemsg(mp);
7324 }
7325 
7326 /* Nobody should be sending packets down this stream */
7327 /* ARGSUSED */
7328 void
7329 ip_lwput(queue_t *q, mblk_t *mp)
7330 {
7331 	freemsg(mp);
7332 }
7333 
7334 /*
7335  * Move the first hop in any source route to ipha_dst and remove that part of
7336  * the source route.  Called by other protocols.  Errors in option formatting
7337  * are ignored - will be handled by ip_wput_options Return the final
7338  * destination (either ipha_dst or the last entry in a source route.)
7339  */
7340 ipaddr_t
7341 ip_massage_options(ipha_t *ipha)
7342 {
7343 	ipoptp_t	opts;
7344 	uchar_t		*opt;
7345 	uint8_t		optval;
7346 	uint8_t		optlen;
7347 	ipaddr_t	dst;
7348 	int		i;
7349 	ire_t		*ire;
7350 
7351 	ip2dbg(("ip_massage_options\n"));
7352 	dst = ipha->ipha_dst;
7353 	for (optval = ipoptp_first(&opts, ipha);
7354 	    optval != IPOPT_EOL;
7355 	    optval = ipoptp_next(&opts)) {
7356 		opt = opts.ipoptp_cur;
7357 		switch (optval) {
7358 			uint8_t off;
7359 		case IPOPT_SSRR:
7360 		case IPOPT_LSRR:
7361 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7362 				ip1dbg(("ip_massage_options: bad src route\n"));
7363 				break;
7364 			}
7365 			optlen = opts.ipoptp_len;
7366 			off = opt[IPOPT_OFFSET];
7367 			off--;
7368 		redo_srr:
7369 			if (optlen < IP_ADDR_LEN ||
7370 			    off > optlen - IP_ADDR_LEN) {
7371 				/* End of source route */
7372 				ip1dbg(("ip_massage_options: end of SR\n"));
7373 				break;
7374 			}
7375 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7376 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7377 			    ntohl(dst)));
7378 			/*
7379 			 * Check if our address is present more than
7380 			 * once as consecutive hops in source route.
7381 			 * XXX verify per-interface ip_forwarding
7382 			 * for source route?
7383 			 */
7384 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7385 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
7386 			if (ire != NULL) {
7387 				ire_refrele(ire);
7388 				off += IP_ADDR_LEN;
7389 				goto redo_srr;
7390 			}
7391 			if (dst == htonl(INADDR_LOOPBACK)) {
7392 				ip1dbg(("ip_massage_options: loopback addr in "
7393 				    "source route!\n"));
7394 				break;
7395 			}
7396 			/*
7397 			 * Update ipha_dst to be the first hop and remove the
7398 			 * first hop from the source route (by overwriting
7399 			 * part of the option with NOP options).
7400 			 */
7401 			ipha->ipha_dst = dst;
7402 			/* Put the last entry in dst */
7403 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7404 			    3;
7405 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7406 
7407 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7408 			    ntohl(dst)));
7409 			/* Move down and overwrite */
7410 			opt[IP_ADDR_LEN] = opt[0];
7411 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7412 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7413 			for (i = 0; i < IP_ADDR_LEN; i++)
7414 				opt[i] = IPOPT_NOP;
7415 			break;
7416 		}
7417 	}
7418 	return (dst);
7419 }
7420 
7421 /*
7422  * This function's job is to forward data to the reverse tunnel (FA->HA)
7423  * after doing a few checks. It is assumed that the incoming interface
7424  * of the packet is always different than the outgoing interface and the
7425  * ire_type of the found ire has to be a non-resolver type.
7426  *
7427  * IPQoS notes
7428  * IP policy is invoked twice for a forwarded packet, once on the read side
7429  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7430  * enabled.
7431  */
7432 static void
7433 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7434 {
7435 	ipha_t		*ipha;
7436 	queue_t		*q;
7437 	uint32_t 	pkt_len;
7438 #define	rptr    ((uchar_t *)ipha)
7439 	uint32_t 	sum;
7440 	uint32_t 	max_frag;
7441 	mblk_t		*first_mp;
7442 	uint32_t	ill_index;
7443 	ipxmit_state_t	pktxmit_state;
7444 	ill_t		*out_ill;
7445 
7446 	ASSERT(ire != NULL);
7447 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7448 	ASSERT(ire->ire_stq != NULL);
7449 
7450 	/* Initiate read side IPPF processing */
7451 	if (IPP_ENABLED(IPP_FWD_IN)) {
7452 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7453 		ip_process(IPP_FWD_IN, &mp, ill_index);
7454 		if (mp == NULL) {
7455 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7456 			    "dropped during IPPF processing\n"));
7457 			return;
7458 		}
7459 	}
7460 
7461 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7462 		ILLF_ROUTER) == 0) ||
7463 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7464 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7465 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7466 		    "forwarding is not turned on\n"));
7467 		goto drop_pkt;
7468 	}
7469 
7470 	/*
7471 	 * Don't forward if the interface is down
7472 	 */
7473 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7474 		goto discard_pkt;
7475 	}
7476 
7477 	ipha = (ipha_t *)mp->b_rptr;
7478 	pkt_len = ntohs(ipha->ipha_length);
7479 	/* Adjust the checksum to reflect the ttl decrement. */
7480 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7481 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7482 	if (ipha->ipha_ttl-- <= 1) {
7483 		if (ip_csum_hdr(ipha)) {
7484 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7485 			goto drop_pkt;
7486 		}
7487 		q = ire->ire_stq;
7488 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7489 		    BPRI_HI)) == NULL) {
7490 			goto discard_pkt;
7491 		}
7492 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7493 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7494 		/* Sent by forwarding path, and router is global zone */
7495 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7496 		    GLOBAL_ZONEID);
7497 		return;
7498 	}
7499 
7500 	/* Get the ill_index of the ILL */
7501 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7502 
7503 	/*
7504 	 * This location is chosen for the placement of the forwarding hook
7505 	 * because at this point we know that we have a path out for the
7506 	 * packet but haven't yet applied any logic (such as fragmenting)
7507 	 * that happen as part of transmitting the packet out.
7508 	 */
7509 	out_ill = ire->ire_ipif->ipif_ill;
7510 
7511 	DTRACE_PROBE4(ip4__forwarding__start,
7512 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7513 
7514 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
7515 	    in_ill, out_ill, ipha, mp, mp);
7516 
7517 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7518 
7519 	if (mp == NULL)
7520 		return;
7521 	pkt_len = ntohs(ipha->ipha_length);
7522 
7523 	/*
7524 	 * ip_mrtun_forward is only used by foreign agent to reverse
7525 	 * tunnel the incoming packet. So it does not do any option
7526 	 * processing for source routing.
7527 	 */
7528 	max_frag = ire->ire_max_frag;
7529 	if (pkt_len > max_frag) {
7530 		/*
7531 		 * It needs fragging on its way out.  We haven't
7532 		 * verified the header checksum yet.  Since we
7533 		 * are going to put a surely good checksum in the
7534 		 * outgoing header, we have to make sure that it
7535 		 * was good coming in.
7536 		 */
7537 		if (ip_csum_hdr(ipha)) {
7538 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7539 			goto drop_pkt;
7540 		}
7541 
7542 		/* Initiate write side IPPF processing */
7543 		if (IPP_ENABLED(IPP_FWD_OUT)) {
7544 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7545 			if (mp == NULL) {
7546 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7547 				    "dropped/deferred during ip policy "\
7548 				    "processing\n"));
7549 				return;
7550 			}
7551 		}
7552 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7553 		    BPRI_HI)) == NULL) {
7554 			goto discard_pkt;
7555 		}
7556 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7557 		mp = first_mp;
7558 
7559 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
7560 		return;
7561 	}
7562 
7563 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7564 
7565 	ASSERT(ire->ire_ipif != NULL);
7566 
7567 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7568 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7569 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
7570 	    NULL, out_ill, ipha, mp, mp);
7571 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7572 	if (mp == NULL)
7573 		return;
7574 
7575 	/* Now send the packet to the tunnel interface */
7576 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7577 	q = ire->ire_stq;
7578 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7579 	if ((pktxmit_state == SEND_FAILED) ||
7580 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7581 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7582 		    q->q_ptr));
7583 	}
7584 
7585 	return;
7586 discard_pkt:
7587 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7588 drop_pkt:;
7589 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7590 	freemsg(mp);
7591 #undef	rptr
7592 }
7593 
7594 /*
7595  * Fills the ipsec_out_t data structure with appropriate fields and
7596  * prepends it to mp which contains the IP hdr + data that was meant
7597  * to be forwarded. Please note that ipsec_out_info data structure
7598  * is used here to communicate the outgoing ill path at ip_wput()
7599  * for the ICMP error packet. This has nothing to do with ipsec IP
7600  * security. ipsec_out_t is really used to pass the info to the module
7601  * IP where this information cannot be extracted from conn.
7602  * This functions is called by ip_mrtun_forward().
7603  */
7604 void
7605 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7606 {
7607 	ipsec_out_t	*io;
7608 
7609 	ASSERT(xmit_ill != NULL);
7610 	first_mp->b_datap->db_type = M_CTL;
7611 	first_mp->b_wptr += sizeof (ipsec_info_t);
7612 	/*
7613 	 * This is to pass info to ip_wput in absence of conn.
7614 	 * ipsec_out_secure will be B_FALSE because of this.
7615 	 * Thus ipsec_out_secure being B_FALSE indicates that
7616 	 * this is not IPSEC security related information.
7617 	 */
7618 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7619 	io = (ipsec_out_t *)first_mp->b_rptr;
7620 	io->ipsec_out_type = IPSEC_OUT;
7621 	io->ipsec_out_len = sizeof (ipsec_out_t);
7622 	first_mp->b_cont = mp;
7623 	io->ipsec_out_ill_index =
7624 	    xmit_ill->ill_phyint->phyint_ifindex;
7625 	io->ipsec_out_xmit_if = B_TRUE;
7626 }
7627 
7628 /*
7629  * Return the network mask
7630  * associated with the specified address.
7631  */
7632 ipaddr_t
7633 ip_net_mask(ipaddr_t addr)
7634 {
7635 	uchar_t	*up = (uchar_t *)&addr;
7636 	ipaddr_t mask = 0;
7637 	uchar_t	*maskp = (uchar_t *)&mask;
7638 
7639 #if defined(__i386) || defined(__amd64)
7640 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7641 #endif
7642 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7643 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7644 #endif
7645 	if (CLASSD(addr)) {
7646 		maskp[0] = 0xF0;
7647 		return (mask);
7648 	}
7649 	if (addr == 0)
7650 		return (0);
7651 	maskp[0] = 0xFF;
7652 	if ((up[0] & 0x80) == 0)
7653 		return (mask);
7654 
7655 	maskp[1] = 0xFF;
7656 	if ((up[0] & 0xC0) == 0x80)
7657 		return (mask);
7658 
7659 	maskp[2] = 0xFF;
7660 	if ((up[0] & 0xE0) == 0xC0)
7661 		return (mask);
7662 
7663 	/* Must be experimental or multicast, indicate as much */
7664 	return ((ipaddr_t)0);
7665 }
7666 
7667 /*
7668  * Select an ill for the packet by considering load spreading across
7669  * a different ill in the group if dst_ill is part of some group.
7670  */
7671 ill_t *
7672 ip_newroute_get_dst_ill(ill_t *dst_ill)
7673 {
7674 	ill_t *ill;
7675 
7676 	/*
7677 	 * We schedule irrespective of whether the source address is
7678 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7679 	 */
7680 	ill = illgrp_scheduler(dst_ill);
7681 	if (ill == NULL)
7682 		return (NULL);
7683 
7684 	/*
7685 	 * For groups with names ip_sioctl_groupname ensures that all
7686 	 * ills are of same type. For groups without names, ifgrp_insert
7687 	 * ensures this.
7688 	 */
7689 	ASSERT(dst_ill->ill_type == ill->ill_type);
7690 
7691 	return (ill);
7692 }
7693 
7694 /*
7695  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7696  */
7697 ill_t *
7698 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6)
7699 {
7700 	ill_t *ret_ill;
7701 
7702 	ASSERT(ifindex != 0);
7703 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL);
7704 	if (ret_ill == NULL ||
7705 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7706 		if (isv6) {
7707 			if (ill != NULL) {
7708 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7709 			} else {
7710 				BUMP_MIB(&ip6_mib, ipIfStatsOutDiscards);
7711 			}
7712 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7713 			    "bad ifindex %d.\n", ifindex));
7714 		} else {
7715 			if (ill != NULL) {
7716 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7717 			} else {
7718 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
7719 			}
7720 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7721 			    "bad ifindex %d.\n", ifindex));
7722 		}
7723 		if (ret_ill != NULL)
7724 			ill_refrele(ret_ill);
7725 		freemsg(first_mp);
7726 		return (NULL);
7727 	}
7728 
7729 	return (ret_ill);
7730 }
7731 
7732 /*
7733  * IPv4 -
7734  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7735  * out a packet to a destination address for which we do not have specific
7736  * (or sufficient) routing information.
7737  *
7738  * NOTE : These are the scopes of some of the variables that point at IRE,
7739  *	  which needs to be followed while making any future modifications
7740  *	  to avoid memory leaks.
7741  *
7742  *	- ire and sire are the entries looked up initially by
7743  *	  ire_ftable_lookup.
7744  *	- ipif_ire is used to hold the interface ire associated with
7745  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7746  *	  it before branching out to error paths.
7747  *	- save_ire is initialized before ire_create, so that ire returned
7748  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7749  *	  before breaking out of the switch.
7750  *
7751  *	Thus on failures, we have to REFRELE only ire and sire, if they
7752  *	are not NULL.
7753  */
7754 void
7755 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7756     zoneid_t zoneid)
7757 {
7758 	areq_t	*areq;
7759 	ipaddr_t gw = 0;
7760 	ire_t	*ire = NULL;
7761 	mblk_t	*res_mp;
7762 	ipaddr_t *addrp;
7763 	ipaddr_t nexthop_addr;
7764 	ipif_t  *src_ipif = NULL;
7765 	ill_t	*dst_ill = NULL;
7766 	ipha_t  *ipha;
7767 	ire_t	*sire = NULL;
7768 	mblk_t	*first_mp;
7769 	ire_t	*save_ire;
7770 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7771 	ushort_t ire_marks = 0;
7772 	boolean_t mctl_present;
7773 	ipsec_out_t *io;
7774 	mblk_t	*saved_mp;
7775 	ire_t	*first_sire = NULL;
7776 	mblk_t	*copy_mp = NULL;
7777 	mblk_t	*xmit_mp = NULL;
7778 	ipaddr_t save_dst;
7779 	uint32_t multirt_flags =
7780 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7781 	boolean_t multirt_is_resolvable;
7782 	boolean_t multirt_resolve_next;
7783 	boolean_t do_attach_ill = B_FALSE;
7784 	boolean_t ip_nexthop = B_FALSE;
7785 	tsol_ire_gw_secattr_t *attrp = NULL;
7786 	tsol_gcgrp_t *gcgrp = NULL;
7787 	tsol_gcgrp_addr_t ga;
7788 
7789 	if (ip_debug > 2) {
7790 		/* ip1dbg */
7791 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7792 	}
7793 
7794 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7795 	if (mctl_present) {
7796 		io = (ipsec_out_t *)first_mp->b_rptr;
7797 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7798 		ASSERT(zoneid == io->ipsec_out_zoneid);
7799 		ASSERT(zoneid != ALL_ZONES);
7800 	}
7801 
7802 	ipha = (ipha_t *)mp->b_rptr;
7803 
7804 	/* All multicast lookups come through ip_newroute_ipif() */
7805 	if (CLASSD(dst)) {
7806 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7807 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7808 		freemsg(first_mp);
7809 		return;
7810 	}
7811 
7812 	if (mctl_present && io->ipsec_out_attach_if) {
7813 		/* ip_grab_attach_ill returns a held ill */
7814 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7815 		    io->ipsec_out_ill_index, B_FALSE);
7816 
7817 		/* Failure case frees things for us. */
7818 		if (attach_ill == NULL)
7819 			return;
7820 
7821 		/*
7822 		 * Check if we need an ire that will not be
7823 		 * looked up by anybody else i.e. HIDDEN.
7824 		 */
7825 		if (ill_is_probeonly(attach_ill))
7826 			ire_marks = IRE_MARK_HIDDEN;
7827 	}
7828 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7829 		ip_nexthop = B_TRUE;
7830 		nexthop_addr = io->ipsec_out_nexthop_addr;
7831 	}
7832 	/*
7833 	 * If this IRE is created for forwarding or it is not for
7834 	 * traffic for congestion controlled protocols, mark it as temporary.
7835 	 */
7836 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7837 		ire_marks |= IRE_MARK_TEMPORARY;
7838 
7839 	/*
7840 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7841 	 * chain until it gets the most specific information available.
7842 	 * For example, we know that there is no IRE_CACHE for this dest,
7843 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7844 	 * ire_ftable_lookup will look up the gateway, etc.
7845 	 * Check if in_ill != NULL. If it is true, the packet must be
7846 	 * from an incoming interface where RTA_SRCIFP is set.
7847 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7848 	 * to the destination, of equal netmask length in the forward table,
7849 	 * will be recursively explored. If no information is available
7850 	 * for the final gateway of that route, we force the returned ire
7851 	 * to be equal to sire using MATCH_IRE_PARENT.
7852 	 * At least, in this case we have a starting point (in the buckets)
7853 	 * to look for other routes to the destination in the forward table.
7854 	 * This is actually used only for multirouting, where a list
7855 	 * of routes has to be processed in sequence.
7856 	 *
7857 	 * In the process of coming up with the most specific information,
7858 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7859 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7860 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7861 	 * Two caveats when handling incomplete ire's in ip_newroute:
7862 	 * - we should be careful when accessing its ire_nce (specifically
7863 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7864 	 * - not all legacy code path callers are prepared to handle
7865 	 *   incomplete ire's, so we should not create/add incomplete
7866 	 *   ire_cache entries here. (See discussion about temporary solution
7867 	 *   further below).
7868 	 *
7869 	 * In order to minimize packet dropping, and to preserve existing
7870 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7871 	 * gateway, and instead use the IF_RESOLVER ire to send out
7872 	 * another request to ARP (this is achieved by passing the
7873 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7874 	 * arp response comes back in ip_wput_nondata, we will create
7875 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7876 	 *
7877 	 * Note that this is a temporary solution; the correct solution is
7878 	 * to create an incomplete  per-dst ire_cache entry, and send the
7879 	 * packet out when the gw's nce is resolved. In order to achieve this,
7880 	 * all packet processing must have been completed prior to calling
7881 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7882 	 * to be modified to accomodate this solution.
7883 	 */
7884 	if (in_ill != NULL) {
7885 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
7886 		    in_ill, MATCH_IRE_TYPE);
7887 	} else if (ip_nexthop) {
7888 		/*
7889 		 * The first time we come here, we look for an IRE_INTERFACE
7890 		 * entry for the specified nexthop, set the dst to be the
7891 		 * nexthop address and create an IRE_CACHE entry for the
7892 		 * nexthop. The next time around, we are able to find an
7893 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7894 		 * nexthop address and create an IRE_CACHE entry for the
7895 		 * destination address via the specified nexthop.
7896 		 */
7897 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7898 		    MBLK_GETLABEL(mp));
7899 		if (ire != NULL) {
7900 			gw = nexthop_addr;
7901 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7902 		} else {
7903 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7904 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7905 			    MBLK_GETLABEL(mp),
7906 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
7907 			if (ire != NULL) {
7908 				dst = nexthop_addr;
7909 			}
7910 		}
7911 	} else if (attach_ill == NULL) {
7912 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7913 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7914 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7915 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7916 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE);
7917 	} else {
7918 		/*
7919 		 * attach_ill is set only for communicating with
7920 		 * on-link hosts. So, don't look for DEFAULT.
7921 		 */
7922 		ipif_t	*attach_ipif;
7923 
7924 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7925 		if (attach_ipif == NULL) {
7926 			ill_refrele(attach_ill);
7927 			goto icmp_err_ret;
7928 		}
7929 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7930 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7931 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7932 		    MATCH_IRE_SECATTR);
7933 		ipif_refrele(attach_ipif);
7934 	}
7935 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7936 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7937 
7938 	/*
7939 	 * This loop is run only once in most cases.
7940 	 * We loop to resolve further routes only when the destination
7941 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7942 	 */
7943 	do {
7944 		/* Clear the previous iteration's values */
7945 		if (src_ipif != NULL) {
7946 			ipif_refrele(src_ipif);
7947 			src_ipif = NULL;
7948 		}
7949 		if (dst_ill != NULL) {
7950 			ill_refrele(dst_ill);
7951 			dst_ill = NULL;
7952 		}
7953 
7954 		multirt_resolve_next = B_FALSE;
7955 		/*
7956 		 * We check if packets have to be multirouted.
7957 		 * In this case, given the current <ire, sire> couple,
7958 		 * we look for the next suitable <ire, sire>.
7959 		 * This check is done in ire_multirt_lookup(),
7960 		 * which applies various criteria to find the next route
7961 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7962 		 * unchanged if it detects it has not been tried yet.
7963 		 */
7964 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7965 			ip3dbg(("ip_newroute: starting next_resolution "
7966 			    "with first_mp %p, tag %d\n",
7967 			    (void *)first_mp,
7968 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7969 
7970 			ASSERT(sire != NULL);
7971 			multirt_is_resolvable =
7972 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7973 				MBLK_GETLABEL(mp));
7974 
7975 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7976 			    "ire %p, sire %p\n",
7977 			    multirt_is_resolvable,
7978 			    (void *)ire, (void *)sire));
7979 
7980 			if (!multirt_is_resolvable) {
7981 				/*
7982 				 * No more multirt route to resolve; give up
7983 				 * (all routes resolved or no more
7984 				 * resolvable routes).
7985 				 */
7986 				if (ire != NULL) {
7987 					ire_refrele(ire);
7988 					ire = NULL;
7989 				}
7990 			} else {
7991 				ASSERT(sire != NULL);
7992 				ASSERT(ire != NULL);
7993 				/*
7994 				 * We simply use first_sire as a flag that
7995 				 * indicates if a resolvable multirt route
7996 				 * has already been found.
7997 				 * If it is not the case, we may have to send
7998 				 * an ICMP error to report that the
7999 				 * destination is unreachable.
8000 				 * We do not IRE_REFHOLD first_sire.
8001 				 */
8002 				if (first_sire == NULL) {
8003 					first_sire = sire;
8004 				}
8005 			}
8006 		}
8007 		if (ire == NULL) {
8008 			if (ip_debug > 3) {
8009 				/* ip2dbg */
8010 				pr_addr_dbg("ip_newroute: "
8011 				    "can't resolve %s\n", AF_INET, &dst);
8012 			}
8013 			ip3dbg(("ip_newroute: "
8014 			    "ire %p, sire %p, first_sire %p\n",
8015 			    (void *)ire, (void *)sire, (void *)first_sire));
8016 
8017 			if (sire != NULL) {
8018 				ire_refrele(sire);
8019 				sire = NULL;
8020 			}
8021 
8022 			if (first_sire != NULL) {
8023 				/*
8024 				 * At least one multirt route has been found
8025 				 * in the same call to ip_newroute();
8026 				 * there is no need to report an ICMP error.
8027 				 * first_sire was not IRE_REFHOLDed.
8028 				 */
8029 				MULTIRT_DEBUG_UNTAG(first_mp);
8030 				freemsg(first_mp);
8031 				return;
8032 			}
8033 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8034 			    RTA_DST);
8035 			if (attach_ill != NULL)
8036 				ill_refrele(attach_ill);
8037 			goto icmp_err_ret;
8038 		}
8039 
8040 		/*
8041 		 * When RTA_SRCIFP is used to add a route, then an interface
8042 		 * route is added in the source interface's routing table.
8043 		 * If the outgoing interface of this route is of type
8044 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8045 		 * ire_nce->nce_res_mp is set to NULL.
8046 		 * Later, when this route is first used for forwarding
8047 		 * a packet, ip_newroute() is called
8048 		 * to resolve the hardware address of the outgoing ipif.
8049 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8050 		 * source interface based table. We only come here if the
8051 		 * outgoing interface is a resolver interface and we don't
8052 		 * have the ire_nce->nce_res_mp information yet.
8053 		 * If in_ill is not null that means it is called from
8054 		 * ip_rput.
8055 		 */
8056 
8057 		ASSERT(ire->ire_in_ill == NULL ||
8058 		    (ire->ire_type == IRE_IF_RESOLVER &&
8059 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8060 
8061 		/*
8062 		 * Verify that the returned IRE does not have either
8063 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8064 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8065 		 */
8066 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8067 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8068 			if (attach_ill != NULL)
8069 				ill_refrele(attach_ill);
8070 			goto icmp_err_ret;
8071 		}
8072 		/*
8073 		 * Increment the ire_ob_pkt_count field for ire if it is an
8074 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8075 		 * increment the same for the parent IRE, sire, if it is some
8076 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
8077 		 * and HOST_REDIRECT).
8078 		 */
8079 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8080 			UPDATE_OB_PKT_COUNT(ire);
8081 			ire->ire_last_used_time = lbolt;
8082 		}
8083 
8084 		if (sire != NULL) {
8085 			gw = sire->ire_gateway_addr;
8086 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8087 			    IRE_INTERFACE)) == 0);
8088 			UPDATE_OB_PKT_COUNT(sire);
8089 			sire->ire_last_used_time = lbolt;
8090 		}
8091 		/*
8092 		 * We have a route to reach the destination.
8093 		 *
8094 		 * 1) If the interface is part of ill group, try to get a new
8095 		 *    ill taking load spreading into account.
8096 		 *
8097 		 * 2) After selecting the ill, get a source address that
8098 		 *    might create good inbound load spreading.
8099 		 *    ipif_select_source does this for us.
8100 		 *
8101 		 * If the application specified the ill (ifindex), we still
8102 		 * load spread. Only if the packets needs to go out
8103 		 * specifically on a given ill e.g. binding to
8104 		 * IPIF_NOFAILOVER address, then we don't try to use a
8105 		 * different ill for load spreading.
8106 		 */
8107 		if (attach_ill == NULL) {
8108 			/*
8109 			 * Don't perform outbound load spreading in the
8110 			 * case of an RTF_MULTIRT route, as we actually
8111 			 * typically want to replicate outgoing packets
8112 			 * through particular interfaces.
8113 			 */
8114 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8115 				dst_ill = ire->ire_ipif->ipif_ill;
8116 				/* for uniformity */
8117 				ill_refhold(dst_ill);
8118 			} else {
8119 				/*
8120 				 * If we are here trying to create an IRE_CACHE
8121 				 * for an offlink destination and have the
8122 				 * IRE_CACHE for the next hop and the latter is
8123 				 * using virtual IP source address selection i.e
8124 				 * it's ire->ire_ipif is pointing to a virtual
8125 				 * network interface (vni) then
8126 				 * ip_newroute_get_dst_ll() will return the vni
8127 				 * interface as the dst_ill. Since the vni is
8128 				 * virtual i.e not associated with any physical
8129 				 * interface, it cannot be the dst_ill, hence
8130 				 * in such a case call ip_newroute_get_dst_ll()
8131 				 * with the stq_ill instead of the ire_ipif ILL.
8132 				 * The function returns a refheld ill.
8133 				 */
8134 				if ((ire->ire_type == IRE_CACHE) &&
8135 				    IS_VNI(ire->ire_ipif->ipif_ill))
8136 					dst_ill = ip_newroute_get_dst_ill(
8137 						ire->ire_stq->q_ptr);
8138 				else
8139 					dst_ill = ip_newroute_get_dst_ill(
8140 						ire->ire_ipif->ipif_ill);
8141 			}
8142 			if (dst_ill == NULL) {
8143 				if (ip_debug > 2) {
8144 					pr_addr_dbg("ip_newroute: "
8145 					    "no dst ill for dst"
8146 					    " %s\n", AF_INET, &dst);
8147 				}
8148 				goto icmp_err_ret;
8149 			}
8150 		} else {
8151 			dst_ill = ire->ire_ipif->ipif_ill;
8152 			/* for uniformity */
8153 			ill_refhold(dst_ill);
8154 			/*
8155 			 * We should have found a route matching ill as we
8156 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8157 			 * Rather than asserting, when there is a mismatch,
8158 			 * we just drop the packet.
8159 			 */
8160 			if (dst_ill != attach_ill) {
8161 				ip0dbg(("ip_newroute: Packet dropped as "
8162 				    "IPIF_NOFAILOVER ill is %s, "
8163 				    "ire->ire_ipif->ipif_ill is %s\n",
8164 				    attach_ill->ill_name,
8165 				    dst_ill->ill_name));
8166 				ill_refrele(attach_ill);
8167 				goto icmp_err_ret;
8168 			}
8169 		}
8170 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8171 		if (attach_ill != NULL) {
8172 			ill_refrele(attach_ill);
8173 			attach_ill = NULL;
8174 			do_attach_ill = B_TRUE;
8175 		}
8176 		ASSERT(dst_ill != NULL);
8177 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8178 
8179 		/*
8180 		 * Pick the best source address from dst_ill.
8181 		 *
8182 		 * 1) If it is part of a multipathing group, we would
8183 		 *    like to spread the inbound packets across different
8184 		 *    interfaces. ipif_select_source picks a random source
8185 		 *    across the different ills in the group.
8186 		 *
8187 		 * 2) If it is not part of a multipathing group, we try
8188 		 *    to pick the source address from the destination
8189 		 *    route. Clustering assumes that when we have multiple
8190 		 *    prefixes hosted on an interface, the prefix of the
8191 		 *    source address matches the prefix of the destination
8192 		 *    route. We do this only if the address is not
8193 		 *    DEPRECATED.
8194 		 *
8195 		 * 3) If the conn is in a different zone than the ire, we
8196 		 *    need to pick a source address from the right zone.
8197 		 *
8198 		 * NOTE : If we hit case (1) above, the prefix of the source
8199 		 *	  address picked may not match the prefix of the
8200 		 *	  destination routes prefix as ipif_select_source
8201 		 *	  does not look at "dst" while picking a source
8202 		 *	  address.
8203 		 *	  If we want the same behavior as (2), we will need
8204 		 *	  to change the behavior of ipif_select_source.
8205 		 */
8206 		ASSERT(src_ipif == NULL);
8207 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8208 			/*
8209 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8210 			 * Check that the ipif matching the requested source
8211 			 * address still exists.
8212 			 */
8213 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8214 			    zoneid, NULL, NULL, NULL, NULL);
8215 		}
8216 		if (src_ipif == NULL) {
8217 			ire_marks |= IRE_MARK_USESRC_CHECK;
8218 			if ((dst_ill->ill_group != NULL) ||
8219 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8220 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8221 			    ire->ire_zoneid != ALL_ZONES) ||
8222 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8223 				/*
8224 				 * If the destination is reachable via a
8225 				 * given gateway, the selected source address
8226 				 * should be in the same subnet as the gateway.
8227 				 * Otherwise, the destination is not reachable.
8228 				 *
8229 				 * If there are no interfaces on the same subnet
8230 				 * as the destination, ipif_select_source gives
8231 				 * first non-deprecated interface which might be
8232 				 * on a different subnet than the gateway.
8233 				 * This is not desirable. Hence pass the dst_ire
8234 				 * source address to ipif_select_source.
8235 				 * It is sure that the destination is reachable
8236 				 * with the dst_ire source address subnet.
8237 				 * So passing dst_ire source address to
8238 				 * ipif_select_source will make sure that the
8239 				 * selected source will be on the same subnet
8240 				 * as dst_ire source address.
8241 				 */
8242 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8243 				src_ipif = ipif_select_source(dst_ill, saddr,
8244 				    zoneid);
8245 				if (src_ipif == NULL) {
8246 					if (ip_debug > 2) {
8247 						pr_addr_dbg("ip_newroute: "
8248 						    "no src for dst %s ",
8249 						    AF_INET, &dst);
8250 						printf("through interface %s\n",
8251 						    dst_ill->ill_name);
8252 					}
8253 					goto icmp_err_ret;
8254 				}
8255 			} else {
8256 				src_ipif = ire->ire_ipif;
8257 				ASSERT(src_ipif != NULL);
8258 				/* hold src_ipif for uniformity */
8259 				ipif_refhold(src_ipif);
8260 			}
8261 		}
8262 
8263 		/*
8264 		 * Assign a source address while we have the conn.
8265 		 * We can't have ip_wput_ire pick a source address when the
8266 		 * packet returns from arp since we need to look at
8267 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8268 		 * going through arp.
8269 		 *
8270 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8271 		 *	  it uses ip6i to store this information.
8272 		 */
8273 		if (ipha->ipha_src == INADDR_ANY &&
8274 		    (connp == NULL || !connp->conn_unspec_src)) {
8275 			ipha->ipha_src = src_ipif->ipif_src_addr;
8276 		}
8277 		if (ip_debug > 3) {
8278 			/* ip2dbg */
8279 			pr_addr_dbg("ip_newroute: first hop %s\n",
8280 			    AF_INET, &gw);
8281 		}
8282 		ip2dbg(("\tire type %s (%d)\n",
8283 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8284 
8285 		/*
8286 		 * The TTL of multirouted packets is bounded by the
8287 		 * ip_multirt_ttl ndd variable.
8288 		 */
8289 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8290 			/* Force TTL of multirouted packets */
8291 			if ((ip_multirt_ttl > 0) &&
8292 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
8293 				ip2dbg(("ip_newroute: forcing multirt TTL "
8294 				    "to %d (was %d), dst 0x%08x\n",
8295 				    ip_multirt_ttl, ipha->ipha_ttl,
8296 				    ntohl(sire->ire_addr)));
8297 				ipha->ipha_ttl = ip_multirt_ttl;
8298 			}
8299 		}
8300 		/*
8301 		 * At this point in ip_newroute(), ire is either the
8302 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8303 		 * destination or an IRE_INTERFACE type that should be used
8304 		 * to resolve an on-subnet destination or an on-subnet
8305 		 * next-hop gateway.
8306 		 *
8307 		 * In the IRE_CACHE case, we have the following :
8308 		 *
8309 		 * 1) src_ipif - used for getting a source address.
8310 		 *
8311 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8312 		 *    means packets using this IRE_CACHE will go out on
8313 		 *    dst_ill.
8314 		 *
8315 		 * 3) The IRE sire will point to the prefix that is the
8316 		 *    longest  matching route for the destination. These
8317 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8318 		 *
8319 		 *    The newly created IRE_CACHE entry for the off-subnet
8320 		 *    destination is tied to both the prefix route and the
8321 		 *    interface route used to resolve the next-hop gateway
8322 		 *    via the ire_phandle and ire_ihandle fields,
8323 		 *    respectively.
8324 		 *
8325 		 * In the IRE_INTERFACE case, we have the following :
8326 		 *
8327 		 * 1) src_ipif - used for getting a source address.
8328 		 *
8329 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8330 		 *    means packets using the IRE_CACHE that we will build
8331 		 *    here will go out on dst_ill.
8332 		 *
8333 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8334 		 *    to be created will only be tied to the IRE_INTERFACE
8335 		 *    that was derived from the ire_ihandle field.
8336 		 *
8337 		 *    If sire is non-NULL, it means the destination is
8338 		 *    off-link and we will first create the IRE_CACHE for the
8339 		 *    gateway. Next time through ip_newroute, we will create
8340 		 *    the IRE_CACHE for the final destination as described
8341 		 *    above.
8342 		 *
8343 		 * In both cases, after the current resolution has been
8344 		 * completed (or possibly initialised, in the IRE_INTERFACE
8345 		 * case), the loop may be re-entered to attempt the resolution
8346 		 * of another RTF_MULTIRT route.
8347 		 *
8348 		 * When an IRE_CACHE entry for the off-subnet destination is
8349 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8350 		 * for further processing in emission loops.
8351 		 */
8352 		save_ire = ire;
8353 		switch (ire->ire_type) {
8354 		case IRE_CACHE: {
8355 			ire_t	*ipif_ire;
8356 			mblk_t	*ire_fp_mp;
8357 
8358 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8359 			if (gw == 0)
8360 				gw = ire->ire_gateway_addr;
8361 			/*
8362 			 * We need 3 ire's to create a new cache ire for an
8363 			 * off-link destination from the cache ire of the
8364 			 * gateway.
8365 			 *
8366 			 *	1. The prefix ire 'sire' (Note that this does
8367 			 *	   not apply to the conn_nexthop_set case)
8368 			 *	2. The cache ire of the gateway 'ire'
8369 			 *	3. The interface ire 'ipif_ire'
8370 			 *
8371 			 * We have (1) and (2). We lookup (3) below.
8372 			 *
8373 			 * If there is no interface route to the gateway,
8374 			 * it is a race condition, where we found the cache
8375 			 * but the interface route has been deleted.
8376 			 */
8377 			if (ip_nexthop) {
8378 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8379 			} else {
8380 				ipif_ire =
8381 				    ire_ihandle_lookup_offlink(ire, sire);
8382 			}
8383 			if (ipif_ire == NULL) {
8384 				ip1dbg(("ip_newroute: "
8385 				    "ire_ihandle_lookup_offlink failed\n"));
8386 				goto icmp_err_ret;
8387 			}
8388 			/*
8389 			 * XXX We are using the same res_mp
8390 			 * (DL_UNITDATA_REQ) though the save_ire is not
8391 			 * pointing at the same ill.
8392 			 * This is incorrect. We need to send it up to the
8393 			 * resolver to get the right res_mp. For ethernets
8394 			 * this may be okay (ill_type == DL_ETHER).
8395 			 */
8396 			res_mp = save_ire->ire_nce->nce_res_mp;
8397 			ire_fp_mp = NULL;
8398 			/*
8399 			 * save_ire's nce_fp_mp can't change since it is
8400 			 * not an IRE_MIPRTUN or IRE_BROADCAST
8401 			 * LOCK_IRE_FP_MP does not do any useful work in
8402 			 * the case of IRE_CACHE. So we don't use it below.
8403 			 */
8404 			if (save_ire->ire_stq == dst_ill->ill_wq)
8405 				ire_fp_mp = save_ire->ire_nce->nce_fp_mp;
8406 
8407 			/*
8408 			 * Check cached gateway IRE for any security
8409 			 * attributes; if found, associate the gateway
8410 			 * credentials group to the destination IRE.
8411 			 */
8412 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8413 				mutex_enter(&attrp->igsa_lock);
8414 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8415 					GCGRP_REFHOLD(gcgrp);
8416 				mutex_exit(&attrp->igsa_lock);
8417 			}
8418 
8419 			ire = ire_create(
8420 			    (uchar_t *)&dst,		/* dest address */
8421 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8422 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8423 			    (uchar_t *)&gw,		/* gateway address */
8424 			    NULL,
8425 			    &save_ire->ire_max_frag,
8426 			    ire_fp_mp,			/* Fast Path header */
8427 			    dst_ill->ill_rq,		/* recv-from queue */
8428 			    dst_ill->ill_wq,		/* send-to queue */
8429 			    IRE_CACHE,			/* IRE type */
8430 			    res_mp,
8431 			    src_ipif,
8432 			    in_ill,			/* incoming ill */
8433 			    (sire != NULL) ?
8434 				sire->ire_mask : 0, 	/* Parent mask */
8435 			    (sire != NULL) ?
8436 				sire->ire_phandle : 0,  /* Parent handle */
8437 			    ipif_ire->ire_ihandle,	/* Interface handle */
8438 			    (sire != NULL) ? (sire->ire_flags &
8439 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8440 			    (sire != NULL) ?
8441 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8442 			    NULL,
8443 			    gcgrp);
8444 
8445 			if (ire == NULL) {
8446 				if (gcgrp != NULL) {
8447 					GCGRP_REFRELE(gcgrp);
8448 					gcgrp = NULL;
8449 				}
8450 				ire_refrele(ipif_ire);
8451 				ire_refrele(save_ire);
8452 				break;
8453 			}
8454 
8455 			/* reference now held by IRE */
8456 			gcgrp = NULL;
8457 
8458 			ire->ire_marks |= ire_marks;
8459 
8460 			/*
8461 			 * Prevent sire and ipif_ire from getting deleted.
8462 			 * The newly created ire is tied to both of them via
8463 			 * the phandle and ihandle respectively.
8464 			 */
8465 			if (sire != NULL) {
8466 				IRB_REFHOLD(sire->ire_bucket);
8467 				/* Has it been removed already ? */
8468 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8469 					IRB_REFRELE(sire->ire_bucket);
8470 					ire_refrele(ipif_ire);
8471 					ire_refrele(save_ire);
8472 					break;
8473 				}
8474 			}
8475 
8476 			IRB_REFHOLD(ipif_ire->ire_bucket);
8477 			/* Has it been removed already ? */
8478 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8479 				IRB_REFRELE(ipif_ire->ire_bucket);
8480 				if (sire != NULL)
8481 					IRB_REFRELE(sire->ire_bucket);
8482 				ire_refrele(ipif_ire);
8483 				ire_refrele(save_ire);
8484 				break;
8485 			}
8486 
8487 			xmit_mp = first_mp;
8488 			/*
8489 			 * In the case of multirouting, a copy
8490 			 * of the packet is done before its sending.
8491 			 * The copy is used to attempt another
8492 			 * route resolution, in a next loop.
8493 			 */
8494 			if (ire->ire_flags & RTF_MULTIRT) {
8495 				copy_mp = copymsg(first_mp);
8496 				if (copy_mp != NULL) {
8497 					xmit_mp = copy_mp;
8498 					MULTIRT_DEBUG_TAG(first_mp);
8499 				}
8500 			}
8501 			ire_add_then_send(q, ire, xmit_mp);
8502 			ire_refrele(save_ire);
8503 
8504 			/* Assert that sire is not deleted yet. */
8505 			if (sire != NULL) {
8506 				ASSERT(sire->ire_ptpn != NULL);
8507 				IRB_REFRELE(sire->ire_bucket);
8508 			}
8509 
8510 			/* Assert that ipif_ire is not deleted yet. */
8511 			ASSERT(ipif_ire->ire_ptpn != NULL);
8512 			IRB_REFRELE(ipif_ire->ire_bucket);
8513 			ire_refrele(ipif_ire);
8514 
8515 			/*
8516 			 * If copy_mp is not NULL, multirouting was
8517 			 * requested. We loop to initiate a next
8518 			 * route resolution attempt, starting from sire.
8519 			 */
8520 			if (copy_mp != NULL) {
8521 				/*
8522 				 * Search for the next unresolved
8523 				 * multirt route.
8524 				 */
8525 				copy_mp = NULL;
8526 				ipif_ire = NULL;
8527 				ire = NULL;
8528 				multirt_resolve_next = B_TRUE;
8529 				continue;
8530 			}
8531 			if (sire != NULL)
8532 				ire_refrele(sire);
8533 			ipif_refrele(src_ipif);
8534 			ill_refrele(dst_ill);
8535 			return;
8536 		}
8537 		case IRE_IF_NORESOLVER: {
8538 			/*
8539 			 * We have what we need to build an IRE_CACHE.
8540 			 *
8541 			 * Create a new res_mp with the IP gateway address
8542 			 * in destination address in the DLPI hdr if the
8543 			 * physical length is exactly 4 bytes.
8544 			 */
8545 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8546 				uchar_t *addr;
8547 
8548 				if (gw)
8549 					addr = (uchar_t *)&gw;
8550 				else
8551 					addr = (uchar_t *)&dst;
8552 
8553 				res_mp = ill_dlur_gen(addr,
8554 				    dst_ill->ill_phys_addr_length,
8555 				    dst_ill->ill_sap,
8556 				    dst_ill->ill_sap_length);
8557 
8558 				if (res_mp == NULL) {
8559 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8560 					break;
8561 				}
8562 			} else if (dst_ill->ill_resolver_mp == NULL) {
8563 				ip1dbg(("ip_newroute: dst_ill %p "
8564 				    "for IF_NORESOLV ire %p has "
8565 				    "no ill_resolver_mp\n",
8566 				    (void *)dst_ill, (void *)ire));
8567 				break;
8568 			} else {
8569 				res_mp = NULL;
8570 			}
8571 
8572 			/*
8573 			 * TSol note: We are creating the ire cache for the
8574 			 * destination 'dst'. If 'dst' is offlink, going
8575 			 * through the first hop 'gw', the security attributes
8576 			 * of 'dst' must be set to point to the gateway
8577 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8578 			 * is possible that 'dst' is a potential gateway that is
8579 			 * referenced by some route that has some security
8580 			 * attributes. Thus in the former case, we need to do a
8581 			 * gcgrp_lookup of 'gw' while in the latter case we
8582 			 * need to do gcgrp_lookup of 'dst' itself.
8583 			 */
8584 			ga.ga_af = AF_INET;
8585 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8586 			    &ga.ga_addr);
8587 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8588 
8589 			ire = ire_create(
8590 			    (uchar_t *)&dst,		/* dest address */
8591 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8592 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8593 			    (uchar_t *)&gw,		/* gateway address */
8594 			    NULL,
8595 			    &save_ire->ire_max_frag,
8596 			    NULL,			/* Fast Path header */
8597 			    dst_ill->ill_rq,		/* recv-from queue */
8598 			    dst_ill->ill_wq,		/* send-to queue */
8599 			    IRE_CACHE,
8600 			    res_mp,
8601 			    src_ipif,
8602 			    in_ill,			/* Incoming ill */
8603 			    save_ire->ire_mask,		/* Parent mask */
8604 			    (sire != NULL) ?		/* Parent handle */
8605 				sire->ire_phandle : 0,
8606 			    save_ire->ire_ihandle,	/* Interface handle */
8607 			    (sire != NULL) ? sire->ire_flags &
8608 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8609 			    &(save_ire->ire_uinfo),
8610 			    NULL,
8611 			    gcgrp);
8612 
8613 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8614 				freeb(res_mp);
8615 
8616 			if (ire == NULL) {
8617 				if (gcgrp != NULL) {
8618 					GCGRP_REFRELE(gcgrp);
8619 					gcgrp = NULL;
8620 				}
8621 				ire_refrele(save_ire);
8622 				break;
8623 			}
8624 
8625 			/* reference now held by IRE */
8626 			gcgrp = NULL;
8627 
8628 			ire->ire_marks |= ire_marks;
8629 
8630 			/* Prevent save_ire from getting deleted */
8631 			IRB_REFHOLD(save_ire->ire_bucket);
8632 			/* Has it been removed already ? */
8633 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8634 				IRB_REFRELE(save_ire->ire_bucket);
8635 				ire_refrele(save_ire);
8636 				break;
8637 			}
8638 
8639 			/*
8640 			 * In the case of multirouting, a copy
8641 			 * of the packet is made before it is sent.
8642 			 * The copy is used in the next
8643 			 * loop to attempt another resolution.
8644 			 */
8645 			xmit_mp = first_mp;
8646 			if ((sire != NULL) &&
8647 			    (sire->ire_flags & RTF_MULTIRT)) {
8648 				copy_mp = copymsg(first_mp);
8649 				if (copy_mp != NULL) {
8650 					xmit_mp = copy_mp;
8651 					MULTIRT_DEBUG_TAG(first_mp);
8652 				}
8653 			}
8654 			ire_add_then_send(q, ire, xmit_mp);
8655 
8656 			/* Assert that it is not deleted yet. */
8657 			ASSERT(save_ire->ire_ptpn != NULL);
8658 			IRB_REFRELE(save_ire->ire_bucket);
8659 			ire_refrele(save_ire);
8660 
8661 			if (copy_mp != NULL) {
8662 				/*
8663 				 * If we found a (no)resolver, we ignore any
8664 				 * trailing top priority IRE_CACHE in further
8665 				 * loops. This ensures that we do not omit any
8666 				 * (no)resolver.
8667 				 * This IRE_CACHE, if any, will be processed
8668 				 * by another thread entering ip_newroute().
8669 				 * IRE_CACHE entries, if any, will be processed
8670 				 * by another thread entering ip_newroute(),
8671 				 * (upon resolver response, for instance).
8672 				 * This aims to force parallel multirt
8673 				 * resolutions as soon as a packet must be sent.
8674 				 * In the best case, after the tx of only one
8675 				 * packet, all reachable routes are resolved.
8676 				 * Otherwise, the resolution of all RTF_MULTIRT
8677 				 * routes would require several emissions.
8678 				 */
8679 				multirt_flags &= ~MULTIRT_CACHEGW;
8680 
8681 				/*
8682 				 * Search for the next unresolved multirt
8683 				 * route.
8684 				 */
8685 				copy_mp = NULL;
8686 				save_ire = NULL;
8687 				ire = NULL;
8688 				multirt_resolve_next = B_TRUE;
8689 				continue;
8690 			}
8691 
8692 			/*
8693 			 * Don't need sire anymore
8694 			 */
8695 			if (sire != NULL)
8696 				ire_refrele(sire);
8697 
8698 			ipif_refrele(src_ipif);
8699 			ill_refrele(dst_ill);
8700 			return;
8701 		}
8702 		case IRE_IF_RESOLVER:
8703 			/*
8704 			 * We can't build an IRE_CACHE yet, but at least we
8705 			 * found a resolver that can help.
8706 			 */
8707 			res_mp = dst_ill->ill_resolver_mp;
8708 			if (!OK_RESOLVER_MP(res_mp))
8709 				break;
8710 
8711 			/*
8712 			 * To be at this point in the code with a non-zero gw
8713 			 * means that dst is reachable through a gateway that
8714 			 * we have never resolved.  By changing dst to the gw
8715 			 * addr we resolve the gateway first.
8716 			 * When ire_add_then_send() tries to put the IP dg
8717 			 * to dst, it will reenter ip_newroute() at which
8718 			 * time we will find the IRE_CACHE for the gw and
8719 			 * create another IRE_CACHE in case IRE_CACHE above.
8720 			 */
8721 			if (gw != INADDR_ANY) {
8722 				/*
8723 				 * The source ipif that was determined above was
8724 				 * relative to the destination address, not the
8725 				 * gateway's. If src_ipif was not taken out of
8726 				 * the IRE_IF_RESOLVER entry, we'll need to call
8727 				 * ipif_select_source() again.
8728 				 */
8729 				if (src_ipif != ire->ire_ipif) {
8730 					ipif_refrele(src_ipif);
8731 					src_ipif = ipif_select_source(dst_ill,
8732 					    gw, zoneid);
8733 					if (src_ipif == NULL) {
8734 						if (ip_debug > 2) {
8735 							pr_addr_dbg(
8736 							    "ip_newroute: no "
8737 							    "src for gw %s ",
8738 							    AF_INET, &gw);
8739 							printf("through "
8740 							    "interface %s\n",
8741 							    dst_ill->ill_name);
8742 						}
8743 						goto icmp_err_ret;
8744 					}
8745 				}
8746 				save_dst = dst;
8747 				dst = gw;
8748 				gw = INADDR_ANY;
8749 			}
8750 
8751 			/*
8752 			 * We obtain a partial IRE_CACHE which we will pass
8753 			 * along with the resolver query.  When the response
8754 			 * comes back it will be there ready for us to add.
8755 			 * The ire_max_frag is atomically set under the
8756 			 * irebucket lock in ire_add_v[46].
8757 			 */
8758 
8759 			ire = ire_create_mp(
8760 			    (uchar_t *)&dst,		/* dest address */
8761 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8762 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8763 			    (uchar_t *)&gw,		/* gateway address */
8764 			    NULL,			/* no in_src_addr */
8765 			    NULL,			/* ire_max_frag */
8766 			    NULL,			/* Fast Path header */
8767 			    dst_ill->ill_rq,		/* recv-from queue */
8768 			    dst_ill->ill_wq,		/* send-to queue */
8769 			    IRE_CACHE,
8770 			    NULL,
8771 			    src_ipif,			/* Interface ipif */
8772 			    in_ill,			/* Incoming ILL */
8773 			    save_ire->ire_mask,		/* Parent mask */
8774 			    0,
8775 			    save_ire->ire_ihandle,	/* Interface handle */
8776 			    0,				/* flags if any */
8777 			    &(save_ire->ire_uinfo),
8778 			    NULL,
8779 			    NULL);
8780 
8781 			if (ire == NULL) {
8782 				ire_refrele(save_ire);
8783 				break;
8784 			}
8785 
8786 			if ((sire != NULL) &&
8787 			    (sire->ire_flags & RTF_MULTIRT)) {
8788 				copy_mp = copymsg(first_mp);
8789 				if (copy_mp != NULL)
8790 					MULTIRT_DEBUG_TAG(copy_mp);
8791 			}
8792 
8793 			ire->ire_marks |= ire_marks;
8794 
8795 			/*
8796 			 * Construct message chain for the resolver
8797 			 * of the form:
8798 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8799 			 * Packet could contain a IPSEC_OUT mp.
8800 			 *
8801 			 * NOTE : ire will be added later when the response
8802 			 * comes back from ARP. If the response does not
8803 			 * come back, ARP frees the packet. For this reason,
8804 			 * we can't REFHOLD the bucket of save_ire to prevent
8805 			 * deletions. We may not be able to REFRELE the bucket
8806 			 * if the response never comes back. Thus, before
8807 			 * adding the ire, ire_add_v4 will make sure that the
8808 			 * interface route does not get deleted. This is the
8809 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8810 			 * where we can always prevent deletions because of
8811 			 * the synchronous nature of adding IRES i.e
8812 			 * ire_add_then_send is called after creating the IRE.
8813 			 */
8814 			ASSERT(ire->ire_mp != NULL);
8815 			ire->ire_mp->b_cont = first_mp;
8816 			/* Have saved_mp handy, for cleanup if canput fails */
8817 			saved_mp = mp;
8818 			mp = copyb(res_mp);
8819 			if (mp == NULL) {
8820 				/* Prepare for cleanup */
8821 				mp = saved_mp; /* pkt */
8822 				ire_delete(ire); /* ire_mp */
8823 				ire = NULL;
8824 				ire_refrele(save_ire);
8825 				if (copy_mp != NULL) {
8826 					MULTIRT_DEBUG_UNTAG(copy_mp);
8827 					freemsg(copy_mp);
8828 					copy_mp = NULL;
8829 				}
8830 				break;
8831 			}
8832 			linkb(mp, ire->ire_mp);
8833 
8834 			/*
8835 			 * Fill in the source and dest addrs for the resolver.
8836 			 * NOTE: this depends on memory layouts imposed by
8837 			 * ill_init().
8838 			 */
8839 			areq = (areq_t *)mp->b_rptr;
8840 			addrp = (ipaddr_t *)((char *)areq +
8841 			    areq->areq_sender_addr_offset);
8842 			if (do_attach_ill) {
8843 				/*
8844 				 * This is bind to no failover case.
8845 				 * arp packet also must go out on attach_ill.
8846 				 */
8847 				ASSERT(ipha->ipha_src != NULL);
8848 				*addrp = ipha->ipha_src;
8849 			} else {
8850 				*addrp = save_ire->ire_src_addr;
8851 			}
8852 
8853 			ire_refrele(save_ire);
8854 			addrp = (ipaddr_t *)((char *)areq +
8855 			    areq->areq_target_addr_offset);
8856 			*addrp = dst;
8857 			/* Up to the resolver. */
8858 			if (canputnext(dst_ill->ill_rq) &&
8859 			    !(dst_ill->ill_arp_closing)) {
8860 				putnext(dst_ill->ill_rq, mp);
8861 				ire = NULL;
8862 				if (copy_mp != NULL) {
8863 					/*
8864 					 * If we found a resolver, we ignore
8865 					 * any trailing top priority IRE_CACHE
8866 					 * in the further loops. This ensures
8867 					 * that we do not omit any resolver.
8868 					 * IRE_CACHE entries, if any, will be
8869 					 * processed next time we enter
8870 					 * ip_newroute().
8871 					 */
8872 					multirt_flags &= ~MULTIRT_CACHEGW;
8873 					/*
8874 					 * Search for the next unresolved
8875 					 * multirt route.
8876 					 */
8877 					first_mp = copy_mp;
8878 					copy_mp = NULL;
8879 					/* Prepare the next resolution loop. */
8880 					mp = first_mp;
8881 					EXTRACT_PKT_MP(mp, first_mp,
8882 					    mctl_present);
8883 					if (mctl_present)
8884 						io = (ipsec_out_t *)
8885 						    first_mp->b_rptr;
8886 					ipha = (ipha_t *)mp->b_rptr;
8887 
8888 					ASSERT(sire != NULL);
8889 
8890 					dst = save_dst;
8891 					multirt_resolve_next = B_TRUE;
8892 					continue;
8893 				}
8894 
8895 				if (sire != NULL)
8896 					ire_refrele(sire);
8897 
8898 				/*
8899 				 * The response will come back in ip_wput
8900 				 * with db_type IRE_DB_TYPE.
8901 				 */
8902 				ipif_refrele(src_ipif);
8903 				ill_refrele(dst_ill);
8904 				return;
8905 			} else {
8906 				/* Prepare for cleanup */
8907 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8908 				    mp);
8909 				mp->b_cont = NULL;
8910 				freeb(mp); /* areq */
8911 				/*
8912 				 * this is an ire that is not added to the
8913 				 * cache. ire_freemblk will handle the release
8914 				 * of any resources associated with the ire.
8915 				 */
8916 				ire_delete(ire); /* ire_mp */
8917 				mp = saved_mp; /* pkt */
8918 				ire = NULL;
8919 				if (copy_mp != NULL) {
8920 					MULTIRT_DEBUG_UNTAG(copy_mp);
8921 					freemsg(copy_mp);
8922 					copy_mp = NULL;
8923 				}
8924 				break;
8925 			}
8926 		default:
8927 			break;
8928 		}
8929 	} while (multirt_resolve_next);
8930 
8931 	ip1dbg(("ip_newroute: dropped\n"));
8932 	/* Did this packet originate externally? */
8933 	if (mp->b_prev) {
8934 		mp->b_next = NULL;
8935 		mp->b_prev = NULL;
8936 		if (in_ill != NULL) {
8937 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
8938 		} else {
8939 			BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
8940 		}
8941 	} else {
8942 		if (dst_ill != NULL) {
8943 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8944 		} else {
8945 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
8946 		}
8947 	}
8948 	ASSERT(copy_mp == NULL);
8949 	MULTIRT_DEBUG_UNTAG(first_mp);
8950 	freemsg(first_mp);
8951 	if (ire != NULL)
8952 		ire_refrele(ire);
8953 	if (sire != NULL)
8954 		ire_refrele(sire);
8955 	if (src_ipif != NULL)
8956 		ipif_refrele(src_ipif);
8957 	if (dst_ill != NULL)
8958 		ill_refrele(dst_ill);
8959 	return;
8960 
8961 icmp_err_ret:
8962 	ip1dbg(("ip_newroute: no route\n"));
8963 	if (src_ipif != NULL)
8964 		ipif_refrele(src_ipif);
8965 	if (dst_ill != NULL)
8966 		ill_refrele(dst_ill);
8967 	if (sire != NULL)
8968 		ire_refrele(sire);
8969 	/* Did this packet originate externally? */
8970 	if (mp->b_prev) {
8971 		mp->b_next = NULL;
8972 		mp->b_prev = NULL;
8973 		if (in_ill != NULL) {
8974 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
8975 		} else {
8976 			BUMP_MIB(&ip_mib, ipIfStatsInNoRoutes);
8977 		}
8978 		q = WR(q);
8979 	} else {
8980 		/*
8981 		 * There is no outgoing ill, so just increment the
8982 		 * system MIB.
8983 		 */
8984 		BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
8985 		/*
8986 		 * Since ip_wput() isn't close to finished, we fill
8987 		 * in enough of the header for credible error reporting.
8988 		 */
8989 		if (ip_hdr_complete(ipha, zoneid)) {
8990 			/* Failed */
8991 			MULTIRT_DEBUG_UNTAG(first_mp);
8992 			freemsg(first_mp);
8993 			if (ire != NULL)
8994 				ire_refrele(ire);
8995 			return;
8996 		}
8997 	}
8998 
8999 	/*
9000 	 * At this point we will have ire only if RTF_BLACKHOLE
9001 	 * or RTF_REJECT flags are set on the IRE. It will not
9002 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9003 	 */
9004 	if (ire != NULL) {
9005 		if (ire->ire_flags & RTF_BLACKHOLE) {
9006 			ire_refrele(ire);
9007 			MULTIRT_DEBUG_UNTAG(first_mp);
9008 			freemsg(first_mp);
9009 			return;
9010 		}
9011 		ire_refrele(ire);
9012 	}
9013 	if (ip_source_routed(ipha)) {
9014 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9015 		    zoneid);
9016 		return;
9017 	}
9018 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9019 }
9020 
9021 ip_opt_info_t zero_info;
9022 
9023 /*
9024  * IPv4 -
9025  * ip_newroute_ipif is called by ip_wput_multicast and
9026  * ip_rput_forward_multicast whenever we need to send
9027  * out a packet to a destination address for which we do not have specific
9028  * routing information. It is used when the packet will be sent out
9029  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9030  * socket option is set or icmp error message wants to go out on a particular
9031  * interface for a unicast packet.
9032  *
9033  * In most cases, the destination address is resolved thanks to the ipif
9034  * intrinsic resolver. However, there are some cases where the call to
9035  * ip_newroute_ipif must take into account the potential presence of
9036  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9037  * that uses the interface. This is specified through flags,
9038  * which can be a combination of:
9039  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9040  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9041  *   and flags. Additionally, the packet source address has to be set to
9042  *   the specified address. The caller is thus expected to set this flag
9043  *   if the packet has no specific source address yet.
9044  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9045  *   flag, the resulting ire will inherit the flag. All unresolved routes
9046  *   to the destination must be explored in the same call to
9047  *   ip_newroute_ipif().
9048  */
9049 static void
9050 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9051     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9052 {
9053 	areq_t	*areq;
9054 	ire_t	*ire = NULL;
9055 	mblk_t	*res_mp;
9056 	ipaddr_t *addrp;
9057 	mblk_t *first_mp;
9058 	ire_t	*save_ire = NULL;
9059 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9060 	ipif_t	*src_ipif = NULL;
9061 	ushort_t ire_marks = 0;
9062 	ill_t	*dst_ill = NULL;
9063 	boolean_t mctl_present;
9064 	ipsec_out_t *io;
9065 	ipha_t *ipha;
9066 	int	ihandle = 0;
9067 	mblk_t	*saved_mp;
9068 	ire_t   *fire = NULL;
9069 	mblk_t  *copy_mp = NULL;
9070 	boolean_t multirt_resolve_next;
9071 	ipaddr_t ipha_dst;
9072 
9073 	/*
9074 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9075 	 * here for uniformity
9076 	 */
9077 	ipif_refhold(ipif);
9078 
9079 	/*
9080 	 * This loop is run only once in most cases.
9081 	 * We loop to resolve further routes only when the destination
9082 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9083 	 */
9084 	do {
9085 		if (dst_ill != NULL) {
9086 			ill_refrele(dst_ill);
9087 			dst_ill = NULL;
9088 		}
9089 		if (src_ipif != NULL) {
9090 			ipif_refrele(src_ipif);
9091 			src_ipif = NULL;
9092 		}
9093 		multirt_resolve_next = B_FALSE;
9094 
9095 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9096 		    ipif->ipif_ill->ill_name));
9097 
9098 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9099 		if (mctl_present)
9100 			io = (ipsec_out_t *)first_mp->b_rptr;
9101 
9102 		ipha = (ipha_t *)mp->b_rptr;
9103 
9104 		/*
9105 		 * Save the packet destination address, we may need it after
9106 		 * the packet has been consumed.
9107 		 */
9108 		ipha_dst = ipha->ipha_dst;
9109 
9110 		/*
9111 		 * If the interface is a pt-pt interface we look for an
9112 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9113 		 * local_address and the pt-pt destination address. Otherwise
9114 		 * we just match the local address.
9115 		 * NOTE: dst could be different than ipha->ipha_dst in case
9116 		 * of sending igmp multicast packets over a point-to-point
9117 		 * connection.
9118 		 * Thus we must be careful enough to check ipha_dst to be a
9119 		 * multicast address, otherwise it will take xmit_if path for
9120 		 * multicast packets resulting into kernel stack overflow by
9121 		 * repeated calls to ip_newroute_ipif from ire_send().
9122 		 */
9123 		if (CLASSD(ipha_dst) &&
9124 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9125 			goto err_ret;
9126 		}
9127 
9128 		/*
9129 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9130 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9131 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9132 		 * propagate its flags to the new ire.
9133 		 */
9134 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9135 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9136 			ip2dbg(("ip_newroute_ipif: "
9137 			    "ipif_lookup_multi_ire("
9138 			    "ipif %p, dst %08x) = fire %p\n",
9139 			    (void *)ipif, ntohl(dst), (void *)fire));
9140 		}
9141 
9142 		if (mctl_present && io->ipsec_out_attach_if) {
9143 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9144 			    io->ipsec_out_ill_index, B_FALSE);
9145 
9146 			/* Failure case frees things for us. */
9147 			if (attach_ill == NULL) {
9148 				ipif_refrele(ipif);
9149 				if (fire != NULL)
9150 					ire_refrele(fire);
9151 				return;
9152 			}
9153 
9154 			/*
9155 			 * Check if we need an ire that will not be
9156 			 * looked up by anybody else i.e. HIDDEN.
9157 			 */
9158 			if (ill_is_probeonly(attach_ill)) {
9159 				ire_marks = IRE_MARK_HIDDEN;
9160 			}
9161 			/*
9162 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9163 			 * case.
9164 			 */
9165 			dst_ill = ipif->ipif_ill;
9166 			/* attach_ill has been refheld by ip_grab_attach_ill */
9167 			ASSERT(dst_ill == attach_ill);
9168 		} else {
9169 			/*
9170 			 * If this is set by IP_XMIT_IF, then make sure that
9171 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9172 			 * specified ill.
9173 			 */
9174 			ASSERT((connp == NULL) ||
9175 			    (connp->conn_xmit_if_ill == NULL) ||
9176 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9177 			/*
9178 			 * If the interface belongs to an interface group,
9179 			 * make sure the next possible interface in the group
9180 			 * is used.  This encourages load spreading among
9181 			 * peers in an interface group.
9182 			 * Note: load spreading is disabled for RTF_MULTIRT
9183 			 * routes.
9184 			 */
9185 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9186 			    (fire->ire_flags & RTF_MULTIRT)) {
9187 				/*
9188 				 * Don't perform outbound load spreading
9189 				 * in the case of an RTF_MULTIRT issued route,
9190 				 * we actually typically want to replicate
9191 				 * outgoing packets through particular
9192 				 * interfaces.
9193 				 */
9194 				dst_ill = ipif->ipif_ill;
9195 				ill_refhold(dst_ill);
9196 			} else {
9197 				dst_ill = ip_newroute_get_dst_ill(
9198 				    ipif->ipif_ill);
9199 			}
9200 			if (dst_ill == NULL) {
9201 				if (ip_debug > 2) {
9202 					pr_addr_dbg("ip_newroute_ipif: "
9203 					    "no dst ill for dst %s\n",
9204 					    AF_INET, &dst);
9205 				}
9206 				goto err_ret;
9207 			}
9208 		}
9209 
9210 		/*
9211 		 * Pick a source address preferring non-deprecated ones.
9212 		 * Unlike ip_newroute, we don't do any source address
9213 		 * selection here since for multicast it really does not help
9214 		 * in inbound load spreading as in the unicast case.
9215 		 */
9216 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9217 		    (fire->ire_flags & RTF_SETSRC)) {
9218 			/*
9219 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9220 			 * on that interface. This ire has RTF_SETSRC flag, so
9221 			 * the source address of the packet must be changed.
9222 			 * Check that the ipif matching the requested source
9223 			 * address still exists.
9224 			 */
9225 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9226 			    zoneid, NULL, NULL, NULL, NULL);
9227 		}
9228 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9229 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9230 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9231 		    (src_ipif == NULL)) {
9232 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9233 			if (src_ipif == NULL) {
9234 				if (ip_debug > 2) {
9235 					/* ip1dbg */
9236 					pr_addr_dbg("ip_newroute_ipif: "
9237 					    "no src for dst %s",
9238 					    AF_INET, &dst);
9239 				}
9240 				ip1dbg((" through interface %s\n",
9241 				    dst_ill->ill_name));
9242 				goto err_ret;
9243 			}
9244 			ipif_refrele(ipif);
9245 			ipif = src_ipif;
9246 			ipif_refhold(ipif);
9247 		}
9248 		if (src_ipif == NULL) {
9249 			src_ipif = ipif;
9250 			ipif_refhold(src_ipif);
9251 		}
9252 
9253 		/*
9254 		 * Assign a source address while we have the conn.
9255 		 * We can't have ip_wput_ire pick a source address when the
9256 		 * packet returns from arp since conn_unspec_src might be set
9257 		 * and we loose the conn when going through arp.
9258 		 */
9259 		if (ipha->ipha_src == INADDR_ANY &&
9260 		    (connp == NULL || !connp->conn_unspec_src)) {
9261 			ipha->ipha_src = src_ipif->ipif_src_addr;
9262 		}
9263 
9264 		/*
9265 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9266 		 * interface does not have an interface ire.
9267 		 * Example: Thousands of mobileip PPP interfaces to mobile
9268 		 * nodes. We don't want to create interface ires because
9269 		 * packets from other mobile nodes must not take the route
9270 		 * via interface ires to the visiting mobile node without
9271 		 * going through the home agent, in absence of mobileip
9272 		 * route optimization.
9273 		 */
9274 		if (CLASSD(ipha_dst) && (connp == NULL ||
9275 		    connp->conn_xmit_if_ill == NULL) &&
9276 		    infop->ip_opt_ill_index == 0) {
9277 			/* ipif_to_ire returns an held ire */
9278 			ire = ipif_to_ire(ipif);
9279 			if (ire == NULL)
9280 				goto err_ret;
9281 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9282 				goto err_ret;
9283 			/*
9284 			 * ihandle is needed when the ire is added to
9285 			 * cache table.
9286 			 */
9287 			save_ire = ire;
9288 			ihandle = save_ire->ire_ihandle;
9289 
9290 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9291 			    "flags %04x\n",
9292 			    (void *)ire, (void *)ipif, flags));
9293 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9294 			    (fire->ire_flags & RTF_MULTIRT)) {
9295 				/*
9296 				 * As requested by flags, an IRE_OFFSUBNET was
9297 				 * looked up on that interface. This ire has
9298 				 * RTF_MULTIRT flag, so the resolution loop will
9299 				 * be re-entered to resolve additional routes on
9300 				 * other interfaces. For that purpose, a copy of
9301 				 * the packet is performed at this point.
9302 				 */
9303 				fire->ire_last_used_time = lbolt;
9304 				copy_mp = copymsg(first_mp);
9305 				if (copy_mp) {
9306 					MULTIRT_DEBUG_TAG(copy_mp);
9307 				}
9308 			}
9309 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9310 			    (fire->ire_flags & RTF_SETSRC)) {
9311 				/*
9312 				 * As requested by flags, an IRE_OFFSUBET was
9313 				 * looked up on that interface. This ire has
9314 				 * RTF_SETSRC flag, so the source address of the
9315 				 * packet must be changed.
9316 				 */
9317 				ipha->ipha_src = fire->ire_src_addr;
9318 			}
9319 		} else {
9320 			ASSERT((connp == NULL) ||
9321 			    (connp->conn_xmit_if_ill != NULL) ||
9322 			    (connp->conn_dontroute) ||
9323 			    infop->ip_opt_ill_index != 0);
9324 			/*
9325 			 * The only ways we can come here are:
9326 			 * 1) IP_XMIT_IF socket option is set
9327 			 * 2) ICMP error message generated from
9328 			 *    ip_mrtun_forward() routine and it needs
9329 			 *    to go through the specified ill.
9330 			 * 3) SO_DONTROUTE socket option is set
9331 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9332 			 * In all cases, the new ire will not be added
9333 			 * into cache table.
9334 			 */
9335 			ire_marks |= IRE_MARK_NOADD;
9336 		}
9337 
9338 		switch (ipif->ipif_net_type) {
9339 		case IRE_IF_NORESOLVER: {
9340 			/* We have what we need to build an IRE_CACHE. */
9341 			mblk_t	*res_mp;
9342 
9343 			/*
9344 			 * Create a new res_mp with the
9345 			 * IP gateway address as destination address in the
9346 			 * DLPI hdr if the physical length is exactly 4 bytes.
9347 			 */
9348 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9349 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9350 				    dst_ill->ill_phys_addr_length,
9351 				    dst_ill->ill_sap,
9352 				    dst_ill->ill_sap_length);
9353 			} else if (dst_ill->ill_resolver_mp == NULL) {
9354 				ip1dbg(("ip_newroute: dst_ill %p "
9355 				    "for IF_NORESOLV ire %p has "
9356 				    "no ill_resolver_mp\n",
9357 				    (void *)dst_ill, (void *)ire));
9358 				break;
9359 			} else {
9360 				/* use the value set in ip_ll_subnet_defaults */
9361 				res_mp = ill_dlur_gen(NULL,
9362 				    dst_ill->ill_phys_addr_length,
9363 				    dst_ill->ill_sap,
9364 				    dst_ill->ill_sap_length);
9365 			}
9366 
9367 			if (res_mp == NULL)
9368 				break;
9369 			/*
9370 			 * The new ire inherits the IRE_OFFSUBNET flags
9371 			 * and source address, if this was requested.
9372 			 */
9373 			ire = ire_create(
9374 			    (uchar_t *)&dst,		/* dest address */
9375 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9376 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9377 			    NULL,			/* gateway address */
9378 			    NULL,
9379 			    &ipif->ipif_mtu,
9380 			    NULL,			/* Fast Path header */
9381 			    dst_ill->ill_rq,		/* recv-from queue */
9382 			    dst_ill->ill_wq,		/* send-to queue */
9383 			    IRE_CACHE,
9384 			    res_mp,
9385 			    src_ipif,
9386 			    NULL,
9387 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9388 			    (fire != NULL) ?		/* Parent handle */
9389 				fire->ire_phandle : 0,
9390 			    ihandle,			/* Interface handle */
9391 			    (fire != NULL) ?
9392 				(fire->ire_flags &
9393 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9394 			    (save_ire == NULL ? &ire_uinfo_null :
9395 				&save_ire->ire_uinfo),
9396 			    NULL,
9397 			    NULL);
9398 
9399 			freeb(res_mp);
9400 
9401 			if (ire == NULL) {
9402 				if (save_ire != NULL)
9403 					ire_refrele(save_ire);
9404 				break;
9405 			}
9406 
9407 			ire->ire_marks |= ire_marks;
9408 
9409 			/*
9410 			 * If IRE_MARK_NOADD is set then we need to convert
9411 			 * the max_fragp to a useable value now. This is
9412 			 * normally done in ire_add_v[46]. We also need to
9413 			 * associate the ire with an nce (normally would be
9414 			 * done in ip_wput_nondata()).
9415 			 *
9416 			 * Note that IRE_MARK_NOADD packets created here
9417 			 * do not have a non-null ire_mp pointer. The null
9418 			 * value of ire_bucket indicates that they were
9419 			 * never added.
9420 			 */
9421 			if (ire->ire_marks & IRE_MARK_NOADD) {
9422 				uint_t  max_frag;
9423 
9424 				max_frag = *ire->ire_max_fragp;
9425 				ire->ire_max_fragp = NULL;
9426 				ire->ire_max_frag = max_frag;
9427 
9428 				if ((ire->ire_nce = ndp_lookup_v4(
9429 				    ire_to_ill(ire),
9430 				    (ire->ire_gateway_addr != INADDR_ANY ?
9431 				    &ire->ire_gateway_addr : &ire->ire_addr),
9432 				    B_FALSE)) == NULL) {
9433 					if (save_ire != NULL)
9434 						ire_refrele(save_ire);
9435 					break;
9436 				}
9437 				ASSERT(ire->ire_nce->nce_state ==
9438 				    ND_REACHABLE);
9439 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9440 			}
9441 
9442 			/* Prevent save_ire from getting deleted */
9443 			if (save_ire != NULL) {
9444 				IRB_REFHOLD(save_ire->ire_bucket);
9445 				/* Has it been removed already ? */
9446 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9447 					IRB_REFRELE(save_ire->ire_bucket);
9448 					ire_refrele(save_ire);
9449 					break;
9450 				}
9451 			}
9452 
9453 			ire_add_then_send(q, ire, first_mp);
9454 
9455 			/* Assert that save_ire is not deleted yet. */
9456 			if (save_ire != NULL) {
9457 				ASSERT(save_ire->ire_ptpn != NULL);
9458 				IRB_REFRELE(save_ire->ire_bucket);
9459 				ire_refrele(save_ire);
9460 				save_ire = NULL;
9461 			}
9462 			if (fire != NULL) {
9463 				ire_refrele(fire);
9464 				fire = NULL;
9465 			}
9466 
9467 			/*
9468 			 * the resolution loop is re-entered if this
9469 			 * was requested through flags and if we
9470 			 * actually are in a multirouting case.
9471 			 */
9472 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9473 				boolean_t need_resolve =
9474 				    ire_multirt_need_resolve(ipha_dst,
9475 					MBLK_GETLABEL(copy_mp));
9476 				if (!need_resolve) {
9477 					MULTIRT_DEBUG_UNTAG(copy_mp);
9478 					freemsg(copy_mp);
9479 					copy_mp = NULL;
9480 				} else {
9481 					/*
9482 					 * ipif_lookup_group() calls
9483 					 * ire_lookup_multi() that uses
9484 					 * ire_ftable_lookup() to find
9485 					 * an IRE_INTERFACE for the group.
9486 					 * In the multirt case,
9487 					 * ire_lookup_multi() then invokes
9488 					 * ire_multirt_lookup() to find
9489 					 * the next resolvable ire.
9490 					 * As a result, we obtain an new
9491 					 * interface, derived from the
9492 					 * next ire.
9493 					 */
9494 					ipif_refrele(ipif);
9495 					ipif = ipif_lookup_group(ipha_dst,
9496 					    zoneid);
9497 					ip2dbg(("ip_newroute_ipif: "
9498 					    "multirt dst %08x, ipif %p\n",
9499 					    htonl(dst), (void *)ipif));
9500 					if (ipif != NULL) {
9501 						mp = copy_mp;
9502 						copy_mp = NULL;
9503 						multirt_resolve_next = B_TRUE;
9504 						continue;
9505 					} else {
9506 						freemsg(copy_mp);
9507 					}
9508 				}
9509 			}
9510 			if (ipif != NULL)
9511 				ipif_refrele(ipif);
9512 			ill_refrele(dst_ill);
9513 			ipif_refrele(src_ipif);
9514 			return;
9515 		}
9516 		case IRE_IF_RESOLVER:
9517 			/*
9518 			 * We can't build an IRE_CACHE yet, but at least
9519 			 * we found a resolver that can help.
9520 			 */
9521 			res_mp = dst_ill->ill_resolver_mp;
9522 			if (!OK_RESOLVER_MP(res_mp))
9523 				break;
9524 
9525 			/*
9526 			 * We obtain a partial IRE_CACHE which we will pass
9527 			 * along with the resolver query.  When the response
9528 			 * comes back it will be there ready for us to add.
9529 			 * The new ire inherits the IRE_OFFSUBNET flags
9530 			 * and source address, if this was requested.
9531 			 * The ire_max_frag is atomically set under the
9532 			 * irebucket lock in ire_add_v[46]. Only in the
9533 			 * case of IRE_MARK_NOADD, we set it here itself.
9534 			 */
9535 			ire = ire_create_mp(
9536 			    (uchar_t *)&dst,		/* dest address */
9537 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9538 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9539 			    NULL,			/* gateway address */
9540 			    NULL,			/* no in_src_addr */
9541 			    (ire_marks & IRE_MARK_NOADD) ?
9542 				ipif->ipif_mtu : 0,	/* max_frag */
9543 			    NULL,			/* Fast path header */
9544 			    dst_ill->ill_rq,		/* recv-from queue */
9545 			    dst_ill->ill_wq,		/* send-to queue */
9546 			    IRE_CACHE,
9547 			    NULL,	/* let ire_nce_init figure res_mp out */
9548 			    src_ipif,
9549 			    NULL,
9550 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9551 			    (fire != NULL) ?		/* Parent handle */
9552 				fire->ire_phandle : 0,
9553 			    ihandle,			/* Interface handle */
9554 			    (fire != NULL) ?		/* flags if any */
9555 				(fire->ire_flags &
9556 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9557 			    (save_ire == NULL ? &ire_uinfo_null :
9558 				&save_ire->ire_uinfo),
9559 			    NULL,
9560 			    NULL);
9561 
9562 			if (save_ire != NULL) {
9563 				ire_refrele(save_ire);
9564 				save_ire = NULL;
9565 			}
9566 			if (ire == NULL)
9567 				break;
9568 
9569 			ire->ire_marks |= ire_marks;
9570 			/*
9571 			 * Construct message chain for the resolver of the
9572 			 * form:
9573 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9574 			 *
9575 			 * NOTE : ire will be added later when the response
9576 			 * comes back from ARP. If the response does not
9577 			 * come back, ARP frees the packet. For this reason,
9578 			 * we can't REFHOLD the bucket of save_ire to prevent
9579 			 * deletions. We may not be able to REFRELE the
9580 			 * bucket if the response never comes back.
9581 			 * Thus, before adding the ire, ire_add_v4 will make
9582 			 * sure that the interface route does not get deleted.
9583 			 * This is the only case unlike ip_newroute_v6,
9584 			 * ip_newroute_ipif_v6 where we can always prevent
9585 			 * deletions because ire_add_then_send is called after
9586 			 * creating the IRE.
9587 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9588 			 * does not add this IRE into the IRE CACHE.
9589 			 */
9590 			ASSERT(ire->ire_mp != NULL);
9591 			ire->ire_mp->b_cont = first_mp;
9592 			/* Have saved_mp handy, for cleanup if canput fails */
9593 			saved_mp = mp;
9594 			mp = copyb(res_mp);
9595 			if (mp == NULL) {
9596 				/* Prepare for cleanup */
9597 				mp = saved_mp; /* pkt */
9598 				ire_delete(ire); /* ire_mp */
9599 				ire = NULL;
9600 				if (copy_mp != NULL) {
9601 					MULTIRT_DEBUG_UNTAG(copy_mp);
9602 					freemsg(copy_mp);
9603 					copy_mp = NULL;
9604 				}
9605 				break;
9606 			}
9607 			linkb(mp, ire->ire_mp);
9608 
9609 			/*
9610 			 * Fill in the source and dest addrs for the resolver.
9611 			 * NOTE: this depends on memory layouts imposed by
9612 			 * ill_init().
9613 			 */
9614 			areq = (areq_t *)mp->b_rptr;
9615 			addrp = (ipaddr_t *)((char *)areq +
9616 			    areq->areq_sender_addr_offset);
9617 			*addrp = ire->ire_src_addr;
9618 			addrp = (ipaddr_t *)((char *)areq +
9619 			    areq->areq_target_addr_offset);
9620 			*addrp = dst;
9621 			/* Up to the resolver. */
9622 			if (canputnext(dst_ill->ill_rq) &&
9623 			    !(dst_ill->ill_arp_closing)) {
9624 				putnext(dst_ill->ill_rq, mp);
9625 				/*
9626 				 * The response will come back in ip_wput
9627 				 * with db_type IRE_DB_TYPE.
9628 				 */
9629 			} else {
9630 				mp->b_cont = NULL;
9631 				freeb(mp); /* areq */
9632 				ire_delete(ire); /* ire_mp */
9633 				saved_mp->b_next = NULL;
9634 				saved_mp->b_prev = NULL;
9635 				freemsg(first_mp); /* pkt */
9636 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9637 			}
9638 
9639 			if (fire != NULL) {
9640 				ire_refrele(fire);
9641 				fire = NULL;
9642 			}
9643 
9644 
9645 			/*
9646 			 * The resolution loop is re-entered if this was
9647 			 * requested through flags and we actually are
9648 			 * in a multirouting case.
9649 			 */
9650 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9651 				boolean_t need_resolve =
9652 				    ire_multirt_need_resolve(ipha_dst,
9653 					MBLK_GETLABEL(copy_mp));
9654 				if (!need_resolve) {
9655 					MULTIRT_DEBUG_UNTAG(copy_mp);
9656 					freemsg(copy_mp);
9657 					copy_mp = NULL;
9658 				} else {
9659 					/*
9660 					 * ipif_lookup_group() calls
9661 					 * ire_lookup_multi() that uses
9662 					 * ire_ftable_lookup() to find
9663 					 * an IRE_INTERFACE for the group.
9664 					 * In the multirt case,
9665 					 * ire_lookup_multi() then invokes
9666 					 * ire_multirt_lookup() to find
9667 					 * the next resolvable ire.
9668 					 * As a result, we obtain an new
9669 					 * interface, derived from the
9670 					 * next ire.
9671 					 */
9672 					ipif_refrele(ipif);
9673 					ipif = ipif_lookup_group(ipha_dst,
9674 					    zoneid);
9675 					if (ipif != NULL) {
9676 						mp = copy_mp;
9677 						copy_mp = NULL;
9678 						multirt_resolve_next = B_TRUE;
9679 						continue;
9680 					} else {
9681 						freemsg(copy_mp);
9682 					}
9683 				}
9684 			}
9685 			if (ipif != NULL)
9686 				ipif_refrele(ipif);
9687 			ill_refrele(dst_ill);
9688 			ipif_refrele(src_ipif);
9689 			return;
9690 		default:
9691 			break;
9692 		}
9693 	} while (multirt_resolve_next);
9694 
9695 err_ret:
9696 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9697 	if (fire != NULL)
9698 		ire_refrele(fire);
9699 	ipif_refrele(ipif);
9700 	/* Did this packet originate externally? */
9701 	if (dst_ill != NULL)
9702 		ill_refrele(dst_ill);
9703 	if (src_ipif != NULL)
9704 		ipif_refrele(src_ipif);
9705 	if (mp->b_prev || mp->b_next) {
9706 		mp->b_next = NULL;
9707 		mp->b_prev = NULL;
9708 	} else {
9709 		/*
9710 		 * Since ip_wput() isn't close to finished, we fill
9711 		 * in enough of the header for credible error reporting.
9712 		 */
9713 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
9714 			/* Failed */
9715 			freemsg(first_mp);
9716 			if (ire != NULL)
9717 				ire_refrele(ire);
9718 			return;
9719 		}
9720 	}
9721 	/*
9722 	 * At this point we will have ire only if RTF_BLACKHOLE
9723 	 * or RTF_REJECT flags are set on the IRE. It will not
9724 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9725 	 */
9726 	if (ire != NULL) {
9727 		if (ire->ire_flags & RTF_BLACKHOLE) {
9728 			ire_refrele(ire);
9729 			freemsg(first_mp);
9730 			return;
9731 		}
9732 		ire_refrele(ire);
9733 	}
9734 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid);
9735 }
9736 
9737 /* Name/Value Table Lookup Routine */
9738 char *
9739 ip_nv_lookup(nv_t *nv, int value)
9740 {
9741 	if (!nv)
9742 		return (NULL);
9743 	for (; nv->nv_name; nv++) {
9744 		if (nv->nv_value == value)
9745 			return (nv->nv_name);
9746 	}
9747 	return ("unknown");
9748 }
9749 
9750 /*
9751  * one day it can be patched to 1 from /etc/system for machines that have few
9752  * fast network interfaces feeding multiple cpus.
9753  */
9754 int ill_stream_putlocks = 0;
9755 
9756 /*
9757  * This is a module open, i.e. this is a control stream for access
9758  * to a DLPI device.  We allocate an ill_t as the instance data in
9759  * this case.
9760  */
9761 int
9762 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9763 {
9764 	uint32_t mem_cnt;
9765 	uint32_t cpu_cnt;
9766 	uint32_t min_cnt;
9767 	pgcnt_t mem_avail;
9768 	ill_t	*ill;
9769 	int	err;
9770 
9771 	/*
9772 	 * Prevent unprivileged processes from pushing IP so that
9773 	 * they can't send raw IP.
9774 	 */
9775 	if (secpolicy_net_rawaccess(credp) != 0)
9776 		return (EPERM);
9777 
9778 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9779 	q->q_ptr = WR(q)->q_ptr = ill;
9780 
9781 	/*
9782 	 * ill_init initializes the ill fields and then sends down
9783 	 * down a DL_INFO_REQ after calling qprocson.
9784 	 */
9785 	err = ill_init(q, ill);
9786 	if (err != 0) {
9787 		mi_free(ill);
9788 		q->q_ptr = NULL;
9789 		WR(q)->q_ptr = NULL;
9790 		return (err);
9791 	}
9792 
9793 	/* ill_init initializes the ipsq marking this thread as writer */
9794 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9795 	/* Wait for the DL_INFO_ACK */
9796 	mutex_enter(&ill->ill_lock);
9797 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9798 		/*
9799 		 * Return value of 0 indicates a pending signal.
9800 		 */
9801 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9802 		if (err == 0) {
9803 			mutex_exit(&ill->ill_lock);
9804 			(void) ip_close(q, 0);
9805 			return (EINTR);
9806 		}
9807 	}
9808 	mutex_exit(&ill->ill_lock);
9809 
9810 	/*
9811 	 * ip_rput_other could have set an error  in ill_error on
9812 	 * receipt of M_ERROR.
9813 	 */
9814 
9815 	err = ill->ill_error;
9816 	if (err != 0) {
9817 		(void) ip_close(q, 0);
9818 		return (err);
9819 	}
9820 
9821 	/*
9822 	 * ip_ire_max_bucket_cnt is sized below based on the memory
9823 	 * size and the cpu speed of the machine. This is upper
9824 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
9825 	 * and is lower bounded by the compile time value of
9826 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
9827 	 * ip6_ire_max_bucket_cnt.
9828 	 */
9829 	mem_avail = kmem_avail();
9830 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9831 	    ip_cache_table_size / sizeof (ire_t);
9832 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
9833 
9834 	min_cnt = MIN(cpu_cnt, mem_cnt);
9835 	if (min_cnt < ip_ire_min_bucket_cnt)
9836 		min_cnt = ip_ire_min_bucket_cnt;
9837 	if (ip_ire_max_bucket_cnt > min_cnt) {
9838 		ip_ire_max_bucket_cnt = min_cnt;
9839 	}
9840 
9841 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
9842 	    ip6_cache_table_size / sizeof (ire_t);
9843 	min_cnt = MIN(cpu_cnt, mem_cnt);
9844 	if (min_cnt < ip6_ire_min_bucket_cnt)
9845 		min_cnt = ip6_ire_min_bucket_cnt;
9846 	if (ip6_ire_max_bucket_cnt > min_cnt) {
9847 		ip6_ire_max_bucket_cnt = min_cnt;
9848 	}
9849 
9850 	ill->ill_credp = credp;
9851 	crhold(credp);
9852 
9853 	mutex_enter(&ip_mi_lock);
9854 	err = mi_open_link(&ip_g_head, (IDP)ill, devp, flag, sflag, credp);
9855 	mutex_exit(&ip_mi_lock);
9856 	if (err) {
9857 		(void) ip_close(q, 0);
9858 		return (err);
9859 	}
9860 	return (0);
9861 }
9862 
9863 /* IP open routine. */
9864 int
9865 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9866 {
9867 	conn_t 		*connp;
9868 	major_t		maj;
9869 
9870 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9871 
9872 	/* Allow reopen. */
9873 	if (q->q_ptr != NULL)
9874 		return (0);
9875 
9876 	if (sflag & MODOPEN) {
9877 		/* This is a module open */
9878 		return (ip_modopen(q, devp, flag, sflag, credp));
9879 	}
9880 
9881 	/*
9882 	 * We are opening as a device. This is an IP client stream, and we
9883 	 * allocate an conn_t as the instance data.
9884 	 */
9885 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP);
9886 	connp->conn_upq = q;
9887 	q->q_ptr = WR(q)->q_ptr = connp;
9888 
9889 	if (flag & SO_SOCKSTR)
9890 		connp->conn_flags |= IPCL_SOCKET;
9891 
9892 	/* Minor tells us which /dev entry was opened */
9893 	if (geteminor(*devp) == IPV6_MINOR) {
9894 		connp->conn_flags |= IPCL_ISV6;
9895 		connp->conn_af_isv6 = B_TRUE;
9896 		ip_setqinfo(q, geteminor(*devp), B_FALSE);
9897 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9898 	} else {
9899 		connp->conn_af_isv6 = B_FALSE;
9900 		connp->conn_pkt_isv6 = B_FALSE;
9901 	}
9902 
9903 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9904 		q->q_ptr = WR(q)->q_ptr = NULL;
9905 		CONN_DEC_REF(connp);
9906 		return (EBUSY);
9907 	}
9908 
9909 	maj = getemajor(*devp);
9910 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9911 
9912 	/*
9913 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9914 	 */
9915 	connp->conn_cred = credp;
9916 	crhold(connp->conn_cred);
9917 
9918 	/*
9919 	 * If the caller has the process-wide flag set, then default to MAC
9920 	 * exempt mode.  This allows read-down to unlabeled hosts.
9921 	 */
9922 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9923 		connp->conn_mac_exempt = B_TRUE;
9924 
9925 	connp->conn_zoneid = getzoneid();
9926 
9927 	/*
9928 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9929 	 * administrative ops.  In these cases, we just need a normal conn_t
9930 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9931 	 * an error will be returned.
9932 	 */
9933 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9934 		connp->conn_rq = q;
9935 		connp->conn_wq = WR(q);
9936 	} else {
9937 		connp->conn_ulp = IPPROTO_SCTP;
9938 		connp->conn_rq = connp->conn_wq = NULL;
9939 	}
9940 	/* Non-zero default values */
9941 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9942 
9943 	/*
9944 	 * Make the conn globally visible to walkers
9945 	 */
9946 	mutex_enter(&connp->conn_lock);
9947 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9948 	mutex_exit(&connp->conn_lock);
9949 	ASSERT(connp->conn_ref == 1);
9950 
9951 	qprocson(q);
9952 
9953 	return (0);
9954 }
9955 
9956 /*
9957  * Change q_qinfo based on the value of isv6.
9958  * This can not called on an ill queue.
9959  * Note that there is no race since either q_qinfo works for conn queues - it
9960  * is just an optimization to enter the best wput routine directly.
9961  */
9962 void
9963 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib)
9964 {
9965 	ASSERT(q->q_flag & QREADR);
9966 	ASSERT(WR(q)->q_next == NULL);
9967 	ASSERT(q->q_ptr != NULL);
9968 
9969 	if (minor == IPV6_MINOR)  {
9970 		if (bump_mib)
9971 			BUMP_MIB(&ip6_mib, ipIfStatsOutSwitchIPVersion);
9972 		q->q_qinfo = &rinit_ipv6;
9973 		WR(q)->q_qinfo = &winit_ipv6;
9974 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9975 	} else {
9976 		if (bump_mib)
9977 			BUMP_MIB(&ip_mib, ipIfStatsOutSwitchIPVersion);
9978 		q->q_qinfo = &iprinit;
9979 		WR(q)->q_qinfo = &ipwinit;
9980 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9981 	}
9982 
9983 }
9984 
9985 /*
9986  * See if IPsec needs loading because of the options in mp.
9987  */
9988 static boolean_t
9989 ipsec_opt_present(mblk_t *mp)
9990 {
9991 	uint8_t *optcp, *next_optcp, *opt_endcp;
9992 	struct opthdr *opt;
9993 	struct T_opthdr *topt;
9994 	int opthdr_len;
9995 	t_uscalar_t optname, optlevel;
9996 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9997 	ipsec_req_t *ipsr;
9998 
9999 	/*
10000 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10001 	 * return TRUE.
10002 	 */
10003 
10004 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10005 	opt_endcp = optcp + tor->OPT_length;
10006 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10007 		opthdr_len = sizeof (struct T_opthdr);
10008 	} else {		/* O_OPTMGMT_REQ */
10009 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10010 		opthdr_len = sizeof (struct opthdr);
10011 	}
10012 	for (; optcp < opt_endcp; optcp = next_optcp) {
10013 		if (optcp + opthdr_len > opt_endcp)
10014 			return (B_FALSE);	/* Not enough option header. */
10015 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10016 			topt = (struct T_opthdr *)optcp;
10017 			optlevel = topt->level;
10018 			optname = topt->name;
10019 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10020 		} else {
10021 			opt = (struct opthdr *)optcp;
10022 			optlevel = opt->level;
10023 			optname = opt->name;
10024 			next_optcp = optcp + opthdr_len +
10025 			    _TPI_ALIGN_OPT(opt->len);
10026 		}
10027 		if ((next_optcp < optcp) || /* wraparound pointer space */
10028 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10029 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10030 			return (B_FALSE); /* bad option buffer */
10031 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10032 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10033 			/*
10034 			 * Check to see if it's an all-bypass or all-zeroes
10035 			 * IPsec request.  Don't bother loading IPsec if
10036 			 * the socket doesn't want to use it.  (A good example
10037 			 * is a bypass request.)
10038 			 *
10039 			 * Basically, if any of the non-NEVER bits are set,
10040 			 * load IPsec.
10041 			 */
10042 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10043 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10044 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10045 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10046 			    != 0)
10047 				return (B_TRUE);
10048 		}
10049 	}
10050 	return (B_FALSE);
10051 }
10052 
10053 /*
10054  * If conn is is waiting for ipsec to finish loading, kick it.
10055  */
10056 /* ARGSUSED */
10057 static void
10058 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10059 {
10060 	t_scalar_t	optreq_prim;
10061 	mblk_t		*mp;
10062 	cred_t		*cr;
10063 	int		err = 0;
10064 
10065 	/*
10066 	 * This function is called, after ipsec loading is complete.
10067 	 * Since IP checks exclusively and atomically (i.e it prevents
10068 	 * ipsec load from completing until ip_optcom_req completes)
10069 	 * whether ipsec load is complete, there cannot be a race with IP
10070 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10071 	 */
10072 	mutex_enter(&connp->conn_lock);
10073 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10074 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10075 		mp = connp->conn_ipsec_opt_mp;
10076 		connp->conn_ipsec_opt_mp = NULL;
10077 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10078 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10079 		mutex_exit(&connp->conn_lock);
10080 
10081 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10082 
10083 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10084 		if (optreq_prim == T_OPTMGMT_REQ) {
10085 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10086 			    &ip_opt_obj);
10087 		} else {
10088 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10089 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10090 			    &ip_opt_obj);
10091 		}
10092 		if (err != EINPROGRESS)
10093 			CONN_OPER_PENDING_DONE(connp);
10094 		return;
10095 	}
10096 	mutex_exit(&connp->conn_lock);
10097 }
10098 
10099 /*
10100  * Called from the ipsec_loader thread, outside any perimeter, to tell
10101  * ip qenable any of the queues waiting for the ipsec loader to
10102  * complete.
10103  *
10104  * Use ip_mi_lock to be safe here: all modifications of the mi lists
10105  * are done with this lock held, so it's guaranteed that none of the
10106  * links will change along the way.
10107  */
10108 void
10109 ip_ipsec_load_complete()
10110 {
10111 	ipcl_walk(conn_restart_ipsec_waiter, NULL);
10112 }
10113 
10114 /*
10115  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10116  * determines the grp on which it has to become exclusive, queues the mp
10117  * and sq draining restarts the optmgmt
10118  */
10119 static boolean_t
10120 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10121 {
10122 	conn_t *connp;
10123 
10124 	/*
10125 	 * Take IPsec requests and treat them special.
10126 	 */
10127 	if (ipsec_opt_present(mp)) {
10128 		/* First check if IPsec is loaded. */
10129 		mutex_enter(&ipsec_loader_lock);
10130 		if (ipsec_loader_state != IPSEC_LOADER_WAIT) {
10131 			mutex_exit(&ipsec_loader_lock);
10132 			return (B_FALSE);
10133 		}
10134 		connp = Q_TO_CONN(q);
10135 		mutex_enter(&connp->conn_lock);
10136 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10137 
10138 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10139 		connp->conn_ipsec_opt_mp = mp;
10140 		mutex_exit(&connp->conn_lock);
10141 		mutex_exit(&ipsec_loader_lock);
10142 
10143 		ipsec_loader_loadnow();
10144 		return (B_TRUE);
10145 	}
10146 	return (B_FALSE);
10147 }
10148 
10149 /*
10150  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10151  * all of them are copied to the conn_t. If the req is "zero", the policy is
10152  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10153  * fields.
10154  * We keep only the latest setting of the policy and thus policy setting
10155  * is not incremental/cumulative.
10156  *
10157  * Requests to set policies with multiple alternative actions will
10158  * go through a different API.
10159  */
10160 int
10161 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10162 {
10163 	uint_t ah_req = 0;
10164 	uint_t esp_req = 0;
10165 	uint_t se_req = 0;
10166 	ipsec_selkey_t sel;
10167 	ipsec_act_t *actp = NULL;
10168 	uint_t nact;
10169 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10170 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10171 	ipsec_policy_root_t *pr;
10172 	ipsec_policy_head_t *ph;
10173 	int fam;
10174 	boolean_t is_pol_reset;
10175 	int error = 0;
10176 
10177 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10178 
10179 	/*
10180 	 * The IP_SEC_OPT option does not allow variable length parameters,
10181 	 * hence a request cannot be NULL.
10182 	 */
10183 	if (req == NULL)
10184 		return (EINVAL);
10185 
10186 	ah_req = req->ipsr_ah_req;
10187 	esp_req = req->ipsr_esp_req;
10188 	se_req = req->ipsr_self_encap_req;
10189 
10190 	/*
10191 	 * Are we dealing with a request to reset the policy (i.e.
10192 	 * zero requests).
10193 	 */
10194 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10195 	    (esp_req & REQ_MASK) == 0 &&
10196 	    (se_req & REQ_MASK) == 0);
10197 
10198 	if (!is_pol_reset) {
10199 		/*
10200 		 * If we couldn't load IPsec, fail with "protocol
10201 		 * not supported".
10202 		 * IPsec may not have been loaded for a request with zero
10203 		 * policies, so we don't fail in this case.
10204 		 */
10205 		mutex_enter(&ipsec_loader_lock);
10206 		if (ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10207 			mutex_exit(&ipsec_loader_lock);
10208 			return (EPROTONOSUPPORT);
10209 		}
10210 		mutex_exit(&ipsec_loader_lock);
10211 
10212 		/*
10213 		 * Test for valid requests. Invalid algorithms
10214 		 * need to be tested by IPSEC code because new
10215 		 * algorithms can be added dynamically.
10216 		 */
10217 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10218 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10219 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10220 			return (EINVAL);
10221 		}
10222 
10223 		/*
10224 		 * Only privileged users can issue these
10225 		 * requests.
10226 		 */
10227 		if (((ah_req & IPSEC_PREF_NEVER) ||
10228 		    (esp_req & IPSEC_PREF_NEVER) ||
10229 		    (se_req & IPSEC_PREF_NEVER)) &&
10230 		    secpolicy_net_config(cr, B_FALSE) != 0) {
10231 			return (EPERM);
10232 		}
10233 
10234 		/*
10235 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10236 		 * are mutually exclusive.
10237 		 */
10238 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10239 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10240 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10241 			/* Both of them are set */
10242 			return (EINVAL);
10243 		}
10244 	}
10245 
10246 	mutex_enter(&connp->conn_lock);
10247 
10248 	/*
10249 	 * If we have already cached policies in ip_bind_connected*(), don't
10250 	 * let them change now. We cache policies for connections
10251 	 * whose src,dst [addr, port] is known.
10252 	 */
10253 	if (connp->conn_policy_cached) {
10254 		mutex_exit(&connp->conn_lock);
10255 		return (EINVAL);
10256 	}
10257 
10258 	/*
10259 	 * We have a zero policies, reset the connection policy if already
10260 	 * set. This will cause the connection to inherit the
10261 	 * global policy, if any.
10262 	 */
10263 	if (is_pol_reset) {
10264 		if (connp->conn_policy != NULL) {
10265 			IPPH_REFRELE(connp->conn_policy);
10266 			connp->conn_policy = NULL;
10267 		}
10268 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10269 		connp->conn_in_enforce_policy = B_FALSE;
10270 		connp->conn_out_enforce_policy = B_FALSE;
10271 		mutex_exit(&connp->conn_lock);
10272 		return (0);
10273 	}
10274 
10275 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy);
10276 	if (ph == NULL)
10277 		goto enomem;
10278 
10279 	ipsec_actvec_from_req(req, &actp, &nact);
10280 	if (actp == NULL)
10281 		goto enomem;
10282 
10283 	/*
10284 	 * Always allocate IPv4 policy entries, since they can also
10285 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10286 	 */
10287 	bzero(&sel, sizeof (sel));
10288 	sel.ipsl_valid = IPSL_IPV4;
10289 
10290 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10291 	if (pin4 == NULL)
10292 		goto enomem;
10293 
10294 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL);
10295 	if (pout4 == NULL)
10296 		goto enomem;
10297 
10298 	if (connp->conn_pkt_isv6) {
10299 		/*
10300 		 * We're looking at a v6 socket, also allocate the
10301 		 * v6-specific entries...
10302 		 */
10303 		sel.ipsl_valid = IPSL_IPV6;
10304 		pin6 = ipsec_policy_create(&sel, actp, nact,
10305 		    IPSEC_PRIO_SOCKET, NULL);
10306 		if (pin6 == NULL)
10307 			goto enomem;
10308 
10309 		pout6 = ipsec_policy_create(&sel, actp, nact,
10310 		    IPSEC_PRIO_SOCKET, NULL);
10311 		if (pout6 == NULL)
10312 			goto enomem;
10313 
10314 		/*
10315 		 * .. and file them away in the right place.
10316 		 */
10317 		fam = IPSEC_AF_V6;
10318 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10319 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10320 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10321 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10322 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10323 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10324 	}
10325 
10326 	ipsec_actvec_free(actp, nact);
10327 
10328 	/*
10329 	 * File the v4 policies.
10330 	 */
10331 	fam = IPSEC_AF_V4;
10332 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10333 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10334 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10335 
10336 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10337 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10338 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10339 
10340 	/*
10341 	 * If the requests need security, set enforce_policy.
10342 	 * If the requests are IPSEC_PREF_NEVER, one should
10343 	 * still set conn_out_enforce_policy so that an ipsec_out
10344 	 * gets attached in ip_wput. This is needed so that
10345 	 * for connections that we don't cache policy in ip_bind,
10346 	 * if global policy matches in ip_wput_attach_policy, we
10347 	 * don't wrongly inherit global policy. Similarly, we need
10348 	 * to set conn_in_enforce_policy also so that we don't verify
10349 	 * policy wrongly.
10350 	 */
10351 	if ((ah_req & REQ_MASK) != 0 ||
10352 	    (esp_req & REQ_MASK) != 0 ||
10353 	    (se_req & REQ_MASK) != 0) {
10354 		connp->conn_in_enforce_policy = B_TRUE;
10355 		connp->conn_out_enforce_policy = B_TRUE;
10356 		connp->conn_flags |= IPCL_CHECK_POLICY;
10357 	}
10358 
10359 	mutex_exit(&connp->conn_lock);
10360 	return (error);
10361 #undef REQ_MASK
10362 
10363 	/*
10364 	 * Common memory-allocation-failure exit path.
10365 	 */
10366 enomem:
10367 	mutex_exit(&connp->conn_lock);
10368 	if (actp != NULL)
10369 		ipsec_actvec_free(actp, nact);
10370 	if (pin4 != NULL)
10371 		IPPOL_REFRELE(pin4);
10372 	if (pout4 != NULL)
10373 		IPPOL_REFRELE(pout4);
10374 	if (pin6 != NULL)
10375 		IPPOL_REFRELE(pin6);
10376 	if (pout6 != NULL)
10377 		IPPOL_REFRELE(pout6);
10378 	return (ENOMEM);
10379 }
10380 
10381 /*
10382  * Only for options that pass in an IP addr. Currently only V4 options
10383  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10384  * So this function assumes level is IPPROTO_IP
10385  */
10386 int
10387 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10388     mblk_t *first_mp)
10389 {
10390 	ipif_t *ipif = NULL;
10391 	int error;
10392 	ill_t *ill;
10393 	int zoneid;
10394 
10395 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10396 
10397 	if (addr != INADDR_ANY || checkonly) {
10398 		ASSERT(connp != NULL);
10399 		zoneid = IPCL_ZONEID(connp);
10400 		if (option == IP_NEXTHOP) {
10401 			ipif = ipif_lookup_onlink_addr(addr,
10402 			    connp->conn_zoneid);
10403 		} else {
10404 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10405 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10406 			    &error);
10407 		}
10408 		if (ipif == NULL) {
10409 			if (error == EINPROGRESS)
10410 				return (error);
10411 			else if ((option == IP_MULTICAST_IF) ||
10412 			    (option == IP_NEXTHOP))
10413 				return (EHOSTUNREACH);
10414 			else
10415 				return (EINVAL);
10416 		} else if (checkonly) {
10417 			if (option == IP_MULTICAST_IF) {
10418 				ill = ipif->ipif_ill;
10419 				/* not supported by the virtual network iface */
10420 				if (IS_VNI(ill)) {
10421 					ipif_refrele(ipif);
10422 					return (EINVAL);
10423 				}
10424 			}
10425 			ipif_refrele(ipif);
10426 			return (0);
10427 		}
10428 		ill = ipif->ipif_ill;
10429 		mutex_enter(&connp->conn_lock);
10430 		mutex_enter(&ill->ill_lock);
10431 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10432 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10433 			mutex_exit(&ill->ill_lock);
10434 			mutex_exit(&connp->conn_lock);
10435 			ipif_refrele(ipif);
10436 			return (option == IP_MULTICAST_IF ?
10437 			    EHOSTUNREACH : EINVAL);
10438 		}
10439 	} else {
10440 		mutex_enter(&connp->conn_lock);
10441 	}
10442 
10443 	/* None of the options below are supported on the VNI */
10444 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10445 		mutex_exit(&ill->ill_lock);
10446 		mutex_exit(&connp->conn_lock);
10447 		ipif_refrele(ipif);
10448 		return (EINVAL);
10449 	}
10450 
10451 	switch (option) {
10452 	case IP_DONTFAILOVER_IF:
10453 		/*
10454 		 * This option is used by in.mpathd to ensure
10455 		 * that IPMP probe packets only go out on the
10456 		 * test interfaces. in.mpathd sets this option
10457 		 * on the non-failover interfaces.
10458 		 * For backward compatibility, this option
10459 		 * implicitly sets IP_MULTICAST_IF, as used
10460 		 * be done in bind(), so that ip_wput gets
10461 		 * this ipif to send mcast packets.
10462 		 */
10463 		if (ipif != NULL) {
10464 			ASSERT(addr != INADDR_ANY);
10465 			connp->conn_nofailover_ill = ipif->ipif_ill;
10466 			connp->conn_multicast_ipif = ipif;
10467 		} else {
10468 			ASSERT(addr == INADDR_ANY);
10469 			connp->conn_nofailover_ill = NULL;
10470 			connp->conn_multicast_ipif = NULL;
10471 		}
10472 		break;
10473 
10474 	case IP_MULTICAST_IF:
10475 		connp->conn_multicast_ipif = ipif;
10476 		break;
10477 	case IP_NEXTHOP:
10478 		connp->conn_nexthop_v4 = addr;
10479 		connp->conn_nexthop_set = B_TRUE;
10480 		break;
10481 	}
10482 
10483 	if (ipif != NULL) {
10484 		mutex_exit(&ill->ill_lock);
10485 		mutex_exit(&connp->conn_lock);
10486 		ipif_refrele(ipif);
10487 		return (0);
10488 	}
10489 	mutex_exit(&connp->conn_lock);
10490 	/* We succeded in cleared the option */
10491 	return (0);
10492 }
10493 
10494 /*
10495  * For options that pass in an ifindex specifying the ill. V6 options always
10496  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10497  */
10498 int
10499 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10500     int level, int option, mblk_t *first_mp)
10501 {
10502 	ill_t *ill = NULL;
10503 	int error = 0;
10504 
10505 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10506 	if (ifindex != 0) {
10507 		ASSERT(connp != NULL);
10508 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10509 		    first_mp, ip_restart_optmgmt, &error);
10510 		if (ill != NULL) {
10511 			if (checkonly) {
10512 				/* not supported by the virtual network iface */
10513 				if (IS_VNI(ill)) {
10514 					ill_refrele(ill);
10515 					return (EINVAL);
10516 				}
10517 				ill_refrele(ill);
10518 				return (0);
10519 			}
10520 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10521 			    0, NULL)) {
10522 				ill_refrele(ill);
10523 				ill = NULL;
10524 				mutex_enter(&connp->conn_lock);
10525 				goto setit;
10526 			}
10527 			mutex_enter(&connp->conn_lock);
10528 			mutex_enter(&ill->ill_lock);
10529 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10530 				mutex_exit(&ill->ill_lock);
10531 				mutex_exit(&connp->conn_lock);
10532 				ill_refrele(ill);
10533 				ill = NULL;
10534 				mutex_enter(&connp->conn_lock);
10535 			}
10536 			goto setit;
10537 		} else if (error == EINPROGRESS) {
10538 			return (error);
10539 		} else {
10540 			error = 0;
10541 		}
10542 	}
10543 	mutex_enter(&connp->conn_lock);
10544 setit:
10545 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10546 
10547 	/*
10548 	 * The options below assume that the ILL (if any) transmits and/or
10549 	 * receives traffic. Neither of which is true for the virtual network
10550 	 * interface, so fail setting these on a VNI.
10551 	 */
10552 	if (IS_VNI(ill)) {
10553 		ASSERT(ill != NULL);
10554 		mutex_exit(&ill->ill_lock);
10555 		mutex_exit(&connp->conn_lock);
10556 		ill_refrele(ill);
10557 		return (EINVAL);
10558 	}
10559 
10560 	if (level == IPPROTO_IP) {
10561 		switch (option) {
10562 		case IP_BOUND_IF:
10563 			connp->conn_incoming_ill = ill;
10564 			connp->conn_outgoing_ill = ill;
10565 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10566 			    0 : ifindex;
10567 			break;
10568 
10569 		case IP_XMIT_IF:
10570 			/*
10571 			 * Similar to IP_BOUND_IF, but this only
10572 			 * determines the outgoing interface for
10573 			 * unicast packets. Also no IRE_CACHE entry
10574 			 * is added for the destination of the
10575 			 * outgoing packets. This feature is needed
10576 			 * for mobile IP.
10577 			 */
10578 			connp->conn_xmit_if_ill = ill;
10579 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10580 			    0 : ifindex;
10581 			break;
10582 
10583 		case IP_MULTICAST_IF:
10584 			/*
10585 			 * This option is an internal special. The socket
10586 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10587 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10588 			 * specifies an ifindex and we try first on V6 ill's.
10589 			 * If we don't find one, we they try using on v4 ill's
10590 			 * intenally and we come here.
10591 			 */
10592 			if (!checkonly && ill != NULL) {
10593 				ipif_t	*ipif;
10594 				ipif = ill->ill_ipif;
10595 
10596 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10597 					mutex_exit(&ill->ill_lock);
10598 					mutex_exit(&connp->conn_lock);
10599 					ill_refrele(ill);
10600 					ill = NULL;
10601 					mutex_enter(&connp->conn_lock);
10602 				} else {
10603 					connp->conn_multicast_ipif = ipif;
10604 				}
10605 			}
10606 			break;
10607 		}
10608 	} else {
10609 		switch (option) {
10610 		case IPV6_BOUND_IF:
10611 			connp->conn_incoming_ill = ill;
10612 			connp->conn_outgoing_ill = ill;
10613 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10614 			    0 : ifindex;
10615 			break;
10616 
10617 		case IPV6_BOUND_PIF:
10618 			/*
10619 			 * Limit all transmit to this ill.
10620 			 * Unlike IPV6_BOUND_IF, using this option
10621 			 * prevents load spreading and failover from
10622 			 * happening when the interface is part of the
10623 			 * group. That's why we don't need to remember
10624 			 * the ifindex in orig_bound_ifindex as in
10625 			 * IPV6_BOUND_IF.
10626 			 */
10627 			connp->conn_outgoing_pill = ill;
10628 			break;
10629 
10630 		case IPV6_DONTFAILOVER_IF:
10631 			/*
10632 			 * This option is used by in.mpathd to ensure
10633 			 * that IPMP probe packets only go out on the
10634 			 * test interfaces. in.mpathd sets this option
10635 			 * on the non-failover interfaces.
10636 			 */
10637 			connp->conn_nofailover_ill = ill;
10638 			/*
10639 			 * For backward compatibility, this option
10640 			 * implicitly sets ip_multicast_ill as used in
10641 			 * IP_MULTICAST_IF so that ip_wput gets
10642 			 * this ipif to send mcast packets.
10643 			 */
10644 			connp->conn_multicast_ill = ill;
10645 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10646 			    0 : ifindex;
10647 			break;
10648 
10649 		case IPV6_MULTICAST_IF:
10650 			/*
10651 			 * Set conn_multicast_ill to be the IPv6 ill.
10652 			 * Set conn_multicast_ipif to be an IPv4 ipif
10653 			 * for ifindex to make IPv4 mapped addresses
10654 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10655 			 * Even if no IPv6 ill exists for the ifindex
10656 			 * we need to check for an IPv4 ifindex in order
10657 			 * for this to work with mapped addresses. In that
10658 			 * case only set conn_multicast_ipif.
10659 			 */
10660 			if (!checkonly) {
10661 				if (ifindex == 0) {
10662 					connp->conn_multicast_ill = NULL;
10663 					connp->conn_orig_multicast_ifindex = 0;
10664 					connp->conn_multicast_ipif = NULL;
10665 				} else if (ill != NULL) {
10666 					connp->conn_multicast_ill = ill;
10667 					connp->conn_orig_multicast_ifindex =
10668 					    ifindex;
10669 				}
10670 			}
10671 			break;
10672 		}
10673 	}
10674 
10675 	if (ill != NULL) {
10676 		mutex_exit(&ill->ill_lock);
10677 		mutex_exit(&connp->conn_lock);
10678 		ill_refrele(ill);
10679 		return (0);
10680 	}
10681 	mutex_exit(&connp->conn_lock);
10682 	/*
10683 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10684 	 * locate the ill and could not set the option (ifindex != 0)
10685 	 */
10686 	return (ifindex == 0 ? 0 : EINVAL);
10687 }
10688 
10689 /* This routine sets socket options. */
10690 /* ARGSUSED */
10691 int
10692 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10693     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10694     void *dummy, cred_t *cr, mblk_t *first_mp)
10695 {
10696 	int		*i1 = (int *)invalp;
10697 	conn_t		*connp = Q_TO_CONN(q);
10698 	int		error = 0;
10699 	boolean_t	checkonly;
10700 	ire_t		*ire;
10701 	boolean_t	found;
10702 
10703 	switch (optset_context) {
10704 
10705 	case SETFN_OPTCOM_CHECKONLY:
10706 		checkonly = B_TRUE;
10707 		/*
10708 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10709 		 * inlen != 0 implies value supplied and
10710 		 * 	we have to "pretend" to set it.
10711 		 * inlen == 0 implies that there is no
10712 		 * 	value part in T_CHECK request and just validation
10713 		 * done elsewhere should be enough, we just return here.
10714 		 */
10715 		if (inlen == 0) {
10716 			*outlenp = 0;
10717 			return (0);
10718 		}
10719 		break;
10720 	case SETFN_OPTCOM_NEGOTIATE:
10721 	case SETFN_UD_NEGOTIATE:
10722 	case SETFN_CONN_NEGOTIATE:
10723 		checkonly = B_FALSE;
10724 		break;
10725 	default:
10726 		/*
10727 		 * We should never get here
10728 		 */
10729 		*outlenp = 0;
10730 		return (EINVAL);
10731 	}
10732 
10733 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10734 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10735 
10736 	/*
10737 	 * For fixed length options, no sanity check
10738 	 * of passed in length is done. It is assumed *_optcom_req()
10739 	 * routines do the right thing.
10740 	 */
10741 
10742 	switch (level) {
10743 	case SOL_SOCKET:
10744 		/*
10745 		 * conn_lock protects the bitfields, and is used to
10746 		 * set the fields atomically.
10747 		 */
10748 		switch (name) {
10749 		case SO_BROADCAST:
10750 			if (!checkonly) {
10751 				/* TODO: use value someplace? */
10752 				mutex_enter(&connp->conn_lock);
10753 				connp->conn_broadcast = *i1 ? 1 : 0;
10754 				mutex_exit(&connp->conn_lock);
10755 			}
10756 			break;	/* goto sizeof (int) option return */
10757 		case SO_USELOOPBACK:
10758 			if (!checkonly) {
10759 				/* TODO: use value someplace? */
10760 				mutex_enter(&connp->conn_lock);
10761 				connp->conn_loopback = *i1 ? 1 : 0;
10762 				mutex_exit(&connp->conn_lock);
10763 			}
10764 			break;	/* goto sizeof (int) option return */
10765 		case SO_DONTROUTE:
10766 			if (!checkonly) {
10767 				mutex_enter(&connp->conn_lock);
10768 				connp->conn_dontroute = *i1 ? 1 : 0;
10769 				mutex_exit(&connp->conn_lock);
10770 			}
10771 			break;	/* goto sizeof (int) option return */
10772 		case SO_REUSEADDR:
10773 			if (!checkonly) {
10774 				mutex_enter(&connp->conn_lock);
10775 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10776 				mutex_exit(&connp->conn_lock);
10777 			}
10778 			break;	/* goto sizeof (int) option return */
10779 		case SO_PROTOTYPE:
10780 			if (!checkonly) {
10781 				mutex_enter(&connp->conn_lock);
10782 				connp->conn_proto = *i1;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		case SO_ALLZONES:
10787 			if (!checkonly) {
10788 				mutex_enter(&connp->conn_lock);
10789 				if (IPCL_IS_BOUND(connp)) {
10790 					mutex_exit(&connp->conn_lock);
10791 					return (EINVAL);
10792 				}
10793 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10794 				mutex_exit(&connp->conn_lock);
10795 			}
10796 			break;	/* goto sizeof (int) option return */
10797 		case SO_ANON_MLP:
10798 			if (!checkonly) {
10799 				mutex_enter(&connp->conn_lock);
10800 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10801 				mutex_exit(&connp->conn_lock);
10802 			}
10803 			break;	/* goto sizeof (int) option return */
10804 		case SO_MAC_EXEMPT:
10805 			if (secpolicy_net_mac_aware(cr) != 0 ||
10806 			    IPCL_IS_BOUND(connp))
10807 				return (EACCES);
10808 			if (!checkonly) {
10809 				mutex_enter(&connp->conn_lock);
10810 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10811 				mutex_exit(&connp->conn_lock);
10812 			}
10813 			break;	/* goto sizeof (int) option return */
10814 		default:
10815 			/*
10816 			 * "soft" error (negative)
10817 			 * option not handled at this level
10818 			 * Note: Do not modify *outlenp
10819 			 */
10820 			return (-EINVAL);
10821 		}
10822 		break;
10823 	case IPPROTO_IP:
10824 		switch (name) {
10825 		case IP_NEXTHOP:
10826 			if (secpolicy_net_config(cr, B_FALSE) != 0)
10827 				return (EPERM);
10828 			/* FALLTHRU */
10829 		case IP_MULTICAST_IF:
10830 		case IP_DONTFAILOVER_IF: {
10831 			ipaddr_t addr = *i1;
10832 
10833 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10834 			    first_mp);
10835 			if (error != 0)
10836 				return (error);
10837 			break;	/* goto sizeof (int) option return */
10838 		}
10839 
10840 		case IP_MULTICAST_TTL:
10841 			/* Recorded in transport above IP */
10842 			*outvalp = *invalp;
10843 			*outlenp = sizeof (uchar_t);
10844 			return (0);
10845 		case IP_MULTICAST_LOOP:
10846 			if (!checkonly) {
10847 				mutex_enter(&connp->conn_lock);
10848 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10849 				mutex_exit(&connp->conn_lock);
10850 			}
10851 			*outvalp = *invalp;
10852 			*outlenp = sizeof (uchar_t);
10853 			return (0);
10854 		case IP_ADD_MEMBERSHIP:
10855 		case MCAST_JOIN_GROUP:
10856 		case IP_DROP_MEMBERSHIP:
10857 		case MCAST_LEAVE_GROUP: {
10858 			struct ip_mreq *mreqp;
10859 			struct group_req *greqp;
10860 			ire_t *ire;
10861 			boolean_t done = B_FALSE;
10862 			ipaddr_t group, ifaddr;
10863 			struct sockaddr_in *sin;
10864 			uint32_t *ifindexp;
10865 			boolean_t mcast_opt = B_TRUE;
10866 			mcast_record_t fmode;
10867 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10868 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10869 
10870 			switch (name) {
10871 			case IP_ADD_MEMBERSHIP:
10872 				mcast_opt = B_FALSE;
10873 				/* FALLTHRU */
10874 			case MCAST_JOIN_GROUP:
10875 				fmode = MODE_IS_EXCLUDE;
10876 				optfn = ip_opt_add_group;
10877 				break;
10878 
10879 			case IP_DROP_MEMBERSHIP:
10880 				mcast_opt = B_FALSE;
10881 				/* FALLTHRU */
10882 			case MCAST_LEAVE_GROUP:
10883 				fmode = MODE_IS_INCLUDE;
10884 				optfn = ip_opt_delete_group;
10885 				break;
10886 			}
10887 
10888 			if (mcast_opt) {
10889 				greqp = (struct group_req *)i1;
10890 				sin = (struct sockaddr_in *)&greqp->gr_group;
10891 				if (sin->sin_family != AF_INET) {
10892 					*outlenp = 0;
10893 					return (ENOPROTOOPT);
10894 				}
10895 				group = (ipaddr_t)sin->sin_addr.s_addr;
10896 				ifaddr = INADDR_ANY;
10897 				ifindexp = &greqp->gr_interface;
10898 			} else {
10899 				mreqp = (struct ip_mreq *)i1;
10900 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10901 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10902 				ifindexp = NULL;
10903 			}
10904 
10905 			/*
10906 			 * In the multirouting case, we need to replicate
10907 			 * the request on all interfaces that will take part
10908 			 * in replication.  We do so because multirouting is
10909 			 * reflective, thus we will probably receive multi-
10910 			 * casts on those interfaces.
10911 			 * The ip_multirt_apply_membership() succeeds if the
10912 			 * operation succeeds on at least one interface.
10913 			 */
10914 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10915 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10916 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
10917 			if (ire != NULL) {
10918 				if (ire->ire_flags & RTF_MULTIRT) {
10919 					error = ip_multirt_apply_membership(
10920 					    optfn, ire, connp, checkonly, group,
10921 					    fmode, INADDR_ANY, first_mp);
10922 					done = B_TRUE;
10923 				}
10924 				ire_refrele(ire);
10925 			}
10926 			if (!done) {
10927 				error = optfn(connp, checkonly, group, ifaddr,
10928 				    ifindexp, fmode, INADDR_ANY, first_mp);
10929 			}
10930 			if (error) {
10931 				/*
10932 				 * EINPROGRESS is a soft error, needs retry
10933 				 * so don't make *outlenp zero.
10934 				 */
10935 				if (error != EINPROGRESS)
10936 					*outlenp = 0;
10937 				return (error);
10938 			}
10939 			/* OK return - copy input buffer into output buffer */
10940 			if (invalp != outvalp) {
10941 				/* don't trust bcopy for identical src/dst */
10942 				bcopy(invalp, outvalp, inlen);
10943 			}
10944 			*outlenp = inlen;
10945 			return (0);
10946 		}
10947 		case IP_BLOCK_SOURCE:
10948 		case IP_UNBLOCK_SOURCE:
10949 		case IP_ADD_SOURCE_MEMBERSHIP:
10950 		case IP_DROP_SOURCE_MEMBERSHIP:
10951 		case MCAST_BLOCK_SOURCE:
10952 		case MCAST_UNBLOCK_SOURCE:
10953 		case MCAST_JOIN_SOURCE_GROUP:
10954 		case MCAST_LEAVE_SOURCE_GROUP: {
10955 			struct ip_mreq_source *imreqp;
10956 			struct group_source_req *gsreqp;
10957 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10958 			uint32_t ifindex = 0;
10959 			mcast_record_t fmode;
10960 			struct sockaddr_in *sin;
10961 			ire_t *ire;
10962 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10963 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10964 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10965 
10966 			switch (name) {
10967 			case IP_BLOCK_SOURCE:
10968 				mcast_opt = B_FALSE;
10969 				/* FALLTHRU */
10970 			case MCAST_BLOCK_SOURCE:
10971 				fmode = MODE_IS_EXCLUDE;
10972 				optfn = ip_opt_add_group;
10973 				break;
10974 
10975 			case IP_UNBLOCK_SOURCE:
10976 				mcast_opt = B_FALSE;
10977 				/* FALLTHRU */
10978 			case MCAST_UNBLOCK_SOURCE:
10979 				fmode = MODE_IS_EXCLUDE;
10980 				optfn = ip_opt_delete_group;
10981 				break;
10982 
10983 			case IP_ADD_SOURCE_MEMBERSHIP:
10984 				mcast_opt = B_FALSE;
10985 				/* FALLTHRU */
10986 			case MCAST_JOIN_SOURCE_GROUP:
10987 				fmode = MODE_IS_INCLUDE;
10988 				optfn = ip_opt_add_group;
10989 				break;
10990 
10991 			case IP_DROP_SOURCE_MEMBERSHIP:
10992 				mcast_opt = B_FALSE;
10993 				/* FALLTHRU */
10994 			case MCAST_LEAVE_SOURCE_GROUP:
10995 				fmode = MODE_IS_INCLUDE;
10996 				optfn = ip_opt_delete_group;
10997 				break;
10998 			}
10999 
11000 			if (mcast_opt) {
11001 				gsreqp = (struct group_source_req *)i1;
11002 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11003 					*outlenp = 0;
11004 					return (ENOPROTOOPT);
11005 				}
11006 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11007 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11008 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11009 				src = (ipaddr_t)sin->sin_addr.s_addr;
11010 				ifindex = gsreqp->gsr_interface;
11011 			} else {
11012 				imreqp = (struct ip_mreq_source *)i1;
11013 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11014 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11015 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11016 			}
11017 
11018 			/*
11019 			 * In the multirouting case, we need to replicate
11020 			 * the request as noted in the mcast cases above.
11021 			 */
11022 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11023 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11024 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11025 			if (ire != NULL) {
11026 				if (ire->ire_flags & RTF_MULTIRT) {
11027 					error = ip_multirt_apply_membership(
11028 					    optfn, ire, connp, checkonly, grp,
11029 					    fmode, src, first_mp);
11030 					done = B_TRUE;
11031 				}
11032 				ire_refrele(ire);
11033 			}
11034 			if (!done) {
11035 				error = optfn(connp, checkonly, grp, ifaddr,
11036 				    &ifindex, fmode, src, first_mp);
11037 			}
11038 			if (error != 0) {
11039 				/*
11040 				 * EINPROGRESS is a soft error, needs retry
11041 				 * so don't make *outlenp zero.
11042 				 */
11043 				if (error != EINPROGRESS)
11044 					*outlenp = 0;
11045 				return (error);
11046 			}
11047 			/* OK return - copy input buffer into output buffer */
11048 			if (invalp != outvalp) {
11049 				bcopy(invalp, outvalp, inlen);
11050 			}
11051 			*outlenp = inlen;
11052 			return (0);
11053 		}
11054 		case IP_SEC_OPT:
11055 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11056 			if (error != 0) {
11057 				*outlenp = 0;
11058 				return (error);
11059 			}
11060 			break;
11061 		case IP_HDRINCL:
11062 		case IP_OPTIONS:
11063 		case T_IP_OPTIONS:
11064 		case IP_TOS:
11065 		case T_IP_TOS:
11066 		case IP_TTL:
11067 		case IP_RECVDSTADDR:
11068 		case IP_RECVOPTS:
11069 			/* OK return - copy input buffer into output buffer */
11070 			if (invalp != outvalp) {
11071 				/* don't trust bcopy for identical src/dst */
11072 				bcopy(invalp, outvalp, inlen);
11073 			}
11074 			*outlenp = inlen;
11075 			return (0);
11076 		case IP_RECVIF:
11077 			/* Retrieve the inbound interface index */
11078 			if (!checkonly) {
11079 				mutex_enter(&connp->conn_lock);
11080 				connp->conn_recvif = *i1 ? 1 : 0;
11081 				mutex_exit(&connp->conn_lock);
11082 			}
11083 			break;	/* goto sizeof (int) option return */
11084 		case IP_RECVPKTINFO:
11085 			if (!checkonly) {
11086 				mutex_enter(&connp->conn_lock);
11087 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11088 				mutex_exit(&connp->conn_lock);
11089 			}
11090 			break;	/* goto sizeof (int) option return */
11091 		case IP_RECVSLLA:
11092 			/* Retrieve the source link layer address */
11093 			if (!checkonly) {
11094 				mutex_enter(&connp->conn_lock);
11095 				connp->conn_recvslla = *i1 ? 1 : 0;
11096 				mutex_exit(&connp->conn_lock);
11097 			}
11098 			break;	/* goto sizeof (int) option return */
11099 		case MRT_INIT:
11100 		case MRT_DONE:
11101 		case MRT_ADD_VIF:
11102 		case MRT_DEL_VIF:
11103 		case MRT_ADD_MFC:
11104 		case MRT_DEL_MFC:
11105 		case MRT_ASSERT:
11106 			if ((error = secpolicy_net_config(cr, B_FALSE)) != 0) {
11107 				*outlenp = 0;
11108 				return (error);
11109 			}
11110 			error = ip_mrouter_set((int)name, q, checkonly,
11111 			    (uchar_t *)invalp, inlen, first_mp);
11112 			if (error) {
11113 				*outlenp = 0;
11114 				return (error);
11115 			}
11116 			/* OK return - copy input buffer into output buffer */
11117 			if (invalp != outvalp) {
11118 				/* don't trust bcopy for identical src/dst */
11119 				bcopy(invalp, outvalp, inlen);
11120 			}
11121 			*outlenp = inlen;
11122 			return (0);
11123 		case IP_BOUND_IF:
11124 		case IP_XMIT_IF:
11125 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11126 			    level, name, first_mp);
11127 			if (error != 0)
11128 				return (error);
11129 			break; 		/* goto sizeof (int) option return */
11130 
11131 		case IP_UNSPEC_SRC:
11132 			/* Allow sending with a zero source address */
11133 			if (!checkonly) {
11134 				mutex_enter(&connp->conn_lock);
11135 				connp->conn_unspec_src = *i1 ? 1 : 0;
11136 				mutex_exit(&connp->conn_lock);
11137 			}
11138 			break;	/* goto sizeof (int) option return */
11139 		default:
11140 			/*
11141 			 * "soft" error (negative)
11142 			 * option not handled at this level
11143 			 * Note: Do not modify *outlenp
11144 			 */
11145 			return (-EINVAL);
11146 		}
11147 		break;
11148 	case IPPROTO_IPV6:
11149 		switch (name) {
11150 		case IPV6_BOUND_IF:
11151 		case IPV6_BOUND_PIF:
11152 		case IPV6_DONTFAILOVER_IF:
11153 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11154 			    level, name, first_mp);
11155 			if (error != 0)
11156 				return (error);
11157 			break; 		/* goto sizeof (int) option return */
11158 
11159 		case IPV6_MULTICAST_IF:
11160 			/*
11161 			 * The only possible errors are EINPROGRESS and
11162 			 * EINVAL. EINPROGRESS will be restarted and is not
11163 			 * a hard error. We call this option on both V4 and V6
11164 			 * If both return EINVAL, then this call returns
11165 			 * EINVAL. If at least one of them succeeds we
11166 			 * return success.
11167 			 */
11168 			found = B_FALSE;
11169 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11170 			    level, name, first_mp);
11171 			if (error == EINPROGRESS)
11172 				return (error);
11173 			if (error == 0)
11174 				found = B_TRUE;
11175 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11176 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11177 			if (error == 0)
11178 				found = B_TRUE;
11179 			if (!found)
11180 				return (error);
11181 			break; 		/* goto sizeof (int) option return */
11182 
11183 		case IPV6_MULTICAST_HOPS:
11184 			/* Recorded in transport above IP */
11185 			break;	/* goto sizeof (int) option return */
11186 		case IPV6_MULTICAST_LOOP:
11187 			if (!checkonly) {
11188 				mutex_enter(&connp->conn_lock);
11189 				connp->conn_multicast_loop = *i1;
11190 				mutex_exit(&connp->conn_lock);
11191 			}
11192 			break;	/* goto sizeof (int) option return */
11193 		case IPV6_JOIN_GROUP:
11194 		case MCAST_JOIN_GROUP:
11195 		case IPV6_LEAVE_GROUP:
11196 		case MCAST_LEAVE_GROUP: {
11197 			struct ipv6_mreq *ip_mreqp;
11198 			struct group_req *greqp;
11199 			ire_t *ire;
11200 			boolean_t done = B_FALSE;
11201 			in6_addr_t groupv6;
11202 			uint32_t ifindex;
11203 			boolean_t mcast_opt = B_TRUE;
11204 			mcast_record_t fmode;
11205 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11206 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11207 
11208 			switch (name) {
11209 			case IPV6_JOIN_GROUP:
11210 				mcast_opt = B_FALSE;
11211 				/* FALLTHRU */
11212 			case MCAST_JOIN_GROUP:
11213 				fmode = MODE_IS_EXCLUDE;
11214 				optfn = ip_opt_add_group_v6;
11215 				break;
11216 
11217 			case IPV6_LEAVE_GROUP:
11218 				mcast_opt = B_FALSE;
11219 				/* FALLTHRU */
11220 			case MCAST_LEAVE_GROUP:
11221 				fmode = MODE_IS_INCLUDE;
11222 				optfn = ip_opt_delete_group_v6;
11223 				break;
11224 			}
11225 
11226 			if (mcast_opt) {
11227 				struct sockaddr_in *sin;
11228 				struct sockaddr_in6 *sin6;
11229 				greqp = (struct group_req *)i1;
11230 				if (greqp->gr_group.ss_family == AF_INET) {
11231 					sin = (struct sockaddr_in *)
11232 					    &(greqp->gr_group);
11233 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11234 					    &groupv6);
11235 				} else {
11236 					sin6 = (struct sockaddr_in6 *)
11237 					    &(greqp->gr_group);
11238 					groupv6 = sin6->sin6_addr;
11239 				}
11240 				ifindex = greqp->gr_interface;
11241 			} else {
11242 				ip_mreqp = (struct ipv6_mreq *)i1;
11243 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11244 				ifindex = ip_mreqp->ipv6mr_interface;
11245 			}
11246 			/*
11247 			 * In the multirouting case, we need to replicate
11248 			 * the request on all interfaces that will take part
11249 			 * in replication.  We do so because multirouting is
11250 			 * reflective, thus we will probably receive multi-
11251 			 * casts on those interfaces.
11252 			 * The ip_multirt_apply_membership_v6() succeeds if
11253 			 * the operation succeeds on at least one interface.
11254 			 */
11255 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11256 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11257 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11258 			if (ire != NULL) {
11259 				if (ire->ire_flags & RTF_MULTIRT) {
11260 					error = ip_multirt_apply_membership_v6(
11261 					    optfn, ire, connp, checkonly,
11262 					    &groupv6, fmode, &ipv6_all_zeros,
11263 					    first_mp);
11264 					done = B_TRUE;
11265 				}
11266 				ire_refrele(ire);
11267 			}
11268 			if (!done) {
11269 				error = optfn(connp, checkonly, &groupv6,
11270 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11271 			}
11272 			if (error) {
11273 				/*
11274 				 * EINPROGRESS is a soft error, needs retry
11275 				 * so don't make *outlenp zero.
11276 				 */
11277 				if (error != EINPROGRESS)
11278 					*outlenp = 0;
11279 				return (error);
11280 			}
11281 			/* OK return - copy input buffer into output buffer */
11282 			if (invalp != outvalp) {
11283 				/* don't trust bcopy for identical src/dst */
11284 				bcopy(invalp, outvalp, inlen);
11285 			}
11286 			*outlenp = inlen;
11287 			return (0);
11288 		}
11289 		case MCAST_BLOCK_SOURCE:
11290 		case MCAST_UNBLOCK_SOURCE:
11291 		case MCAST_JOIN_SOURCE_GROUP:
11292 		case MCAST_LEAVE_SOURCE_GROUP: {
11293 			struct group_source_req *gsreqp;
11294 			in6_addr_t v6grp, v6src;
11295 			uint32_t ifindex;
11296 			mcast_record_t fmode;
11297 			ire_t *ire;
11298 			boolean_t done = B_FALSE;
11299 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11300 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11301 
11302 			switch (name) {
11303 			case MCAST_BLOCK_SOURCE:
11304 				fmode = MODE_IS_EXCLUDE;
11305 				optfn = ip_opt_add_group_v6;
11306 				break;
11307 			case MCAST_UNBLOCK_SOURCE:
11308 				fmode = MODE_IS_EXCLUDE;
11309 				optfn = ip_opt_delete_group_v6;
11310 				break;
11311 			case MCAST_JOIN_SOURCE_GROUP:
11312 				fmode = MODE_IS_INCLUDE;
11313 				optfn = ip_opt_add_group_v6;
11314 				break;
11315 			case MCAST_LEAVE_SOURCE_GROUP:
11316 				fmode = MODE_IS_INCLUDE;
11317 				optfn = ip_opt_delete_group_v6;
11318 				break;
11319 			}
11320 
11321 			gsreqp = (struct group_source_req *)i1;
11322 			ifindex = gsreqp->gsr_interface;
11323 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11324 				struct sockaddr_in *s;
11325 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11326 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11327 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11328 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11329 			} else {
11330 				struct sockaddr_in6 *s6;
11331 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11332 				v6grp = s6->sin6_addr;
11333 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11334 				v6src = s6->sin6_addr;
11335 			}
11336 
11337 			/*
11338 			 * In the multirouting case, we need to replicate
11339 			 * the request as noted in the mcast cases above.
11340 			 */
11341 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11342 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11343 			    MATCH_IRE_MASK | MATCH_IRE_TYPE);
11344 			if (ire != NULL) {
11345 				if (ire->ire_flags & RTF_MULTIRT) {
11346 					error = ip_multirt_apply_membership_v6(
11347 					    optfn, ire, connp, checkonly,
11348 					    &v6grp, fmode, &v6src, first_mp);
11349 					done = B_TRUE;
11350 				}
11351 				ire_refrele(ire);
11352 			}
11353 			if (!done) {
11354 				error = optfn(connp, checkonly, &v6grp,
11355 				    ifindex, fmode, &v6src, first_mp);
11356 			}
11357 			if (error != 0) {
11358 				/*
11359 				 * EINPROGRESS is a soft error, needs retry
11360 				 * so don't make *outlenp zero.
11361 				 */
11362 				if (error != EINPROGRESS)
11363 					*outlenp = 0;
11364 				return (error);
11365 			}
11366 			/* OK return - copy input buffer into output buffer */
11367 			if (invalp != outvalp) {
11368 				bcopy(invalp, outvalp, inlen);
11369 			}
11370 			*outlenp = inlen;
11371 			return (0);
11372 		}
11373 		case IPV6_UNICAST_HOPS:
11374 			/* Recorded in transport above IP */
11375 			break;	/* goto sizeof (int) option return */
11376 		case IPV6_UNSPEC_SRC:
11377 			/* Allow sending with a zero source address */
11378 			if (!checkonly) {
11379 				mutex_enter(&connp->conn_lock);
11380 				connp->conn_unspec_src = *i1 ? 1 : 0;
11381 				mutex_exit(&connp->conn_lock);
11382 			}
11383 			break;	/* goto sizeof (int) option return */
11384 		case IPV6_RECVPKTINFO:
11385 			if (!checkonly) {
11386 				mutex_enter(&connp->conn_lock);
11387 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11388 				mutex_exit(&connp->conn_lock);
11389 			}
11390 			break;	/* goto sizeof (int) option return */
11391 		case IPV6_RECVTCLASS:
11392 			if (!checkonly) {
11393 				if (*i1 < 0 || *i1 > 1) {
11394 					return (EINVAL);
11395 				}
11396 				mutex_enter(&connp->conn_lock);
11397 				connp->conn_ipv6_recvtclass = *i1;
11398 				mutex_exit(&connp->conn_lock);
11399 			}
11400 			break;
11401 		case IPV6_RECVPATHMTU:
11402 			if (!checkonly) {
11403 				if (*i1 < 0 || *i1 > 1) {
11404 					return (EINVAL);
11405 				}
11406 				mutex_enter(&connp->conn_lock);
11407 				connp->conn_ipv6_recvpathmtu = *i1;
11408 				mutex_exit(&connp->conn_lock);
11409 			}
11410 			break;
11411 		case IPV6_RECVHOPLIMIT:
11412 			if (!checkonly) {
11413 				mutex_enter(&connp->conn_lock);
11414 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11415 				mutex_exit(&connp->conn_lock);
11416 			}
11417 			break;	/* goto sizeof (int) option return */
11418 		case IPV6_RECVHOPOPTS:
11419 			if (!checkonly) {
11420 				mutex_enter(&connp->conn_lock);
11421 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11422 				mutex_exit(&connp->conn_lock);
11423 			}
11424 			break;	/* goto sizeof (int) option return */
11425 		case IPV6_RECVDSTOPTS:
11426 			if (!checkonly) {
11427 				mutex_enter(&connp->conn_lock);
11428 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11429 				mutex_exit(&connp->conn_lock);
11430 			}
11431 			break;	/* goto sizeof (int) option return */
11432 		case IPV6_RECVRTHDR:
11433 			if (!checkonly) {
11434 				mutex_enter(&connp->conn_lock);
11435 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11436 				mutex_exit(&connp->conn_lock);
11437 			}
11438 			break;	/* goto sizeof (int) option return */
11439 		case IPV6_RECVRTHDRDSTOPTS:
11440 			if (!checkonly) {
11441 				mutex_enter(&connp->conn_lock);
11442 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11443 				mutex_exit(&connp->conn_lock);
11444 			}
11445 			break;	/* goto sizeof (int) option return */
11446 		case IPV6_PKTINFO:
11447 			if (inlen == 0)
11448 				return (-EINVAL);	/* clearing option */
11449 			error = ip6_set_pktinfo(cr, connp,
11450 			    (struct in6_pktinfo *)invalp, first_mp);
11451 			if (error != 0)
11452 				*outlenp = 0;
11453 			else
11454 				*outlenp = inlen;
11455 			return (error);
11456 		case IPV6_NEXTHOP: {
11457 			struct sockaddr_in6 *sin6;
11458 
11459 			/* Verify that the nexthop is reachable */
11460 			if (inlen == 0)
11461 				return (-EINVAL);	/* clearing option */
11462 
11463 			sin6 = (struct sockaddr_in6 *)invalp;
11464 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11465 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11466 			    NULL, MATCH_IRE_DEFAULT);
11467 
11468 			if (ire == NULL) {
11469 				*outlenp = 0;
11470 				return (EHOSTUNREACH);
11471 			}
11472 			ire_refrele(ire);
11473 			return (-EINVAL);
11474 		}
11475 		case IPV6_SEC_OPT:
11476 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11477 			if (error != 0) {
11478 				*outlenp = 0;
11479 				return (error);
11480 			}
11481 			break;
11482 		case IPV6_SRC_PREFERENCES: {
11483 			/*
11484 			 * This is implemented strictly in the ip module
11485 			 * (here and in tcp_opt_*() to accomodate tcp
11486 			 * sockets).  Modules above ip pass this option
11487 			 * down here since ip is the only one that needs to
11488 			 * be aware of source address preferences.
11489 			 *
11490 			 * This socket option only affects connected
11491 			 * sockets that haven't already bound to a specific
11492 			 * IPv6 address.  In other words, sockets that
11493 			 * don't call bind() with an address other than the
11494 			 * unspecified address and that call connect().
11495 			 * ip_bind_connected_v6() passes these preferences
11496 			 * to the ipif_select_source_v6() function.
11497 			 */
11498 			if (inlen != sizeof (uint32_t))
11499 				return (EINVAL);
11500 			error = ip6_set_src_preferences(connp,
11501 			    *(uint32_t *)invalp);
11502 			if (error != 0) {
11503 				*outlenp = 0;
11504 				return (error);
11505 			} else {
11506 				*outlenp = sizeof (uint32_t);
11507 			}
11508 			break;
11509 		}
11510 		case IPV6_V6ONLY:
11511 			if (*i1 < 0 || *i1 > 1) {
11512 				return (EINVAL);
11513 			}
11514 			mutex_enter(&connp->conn_lock);
11515 			connp->conn_ipv6_v6only = *i1;
11516 			mutex_exit(&connp->conn_lock);
11517 			break;
11518 		default:
11519 			return (-EINVAL);
11520 		}
11521 		break;
11522 	default:
11523 		/*
11524 		 * "soft" error (negative)
11525 		 * option not handled at this level
11526 		 * Note: Do not modify *outlenp
11527 		 */
11528 		return (-EINVAL);
11529 	}
11530 	/*
11531 	 * Common case of return from an option that is sizeof (int)
11532 	 */
11533 	*(int *)outvalp = *i1;
11534 	*outlenp = sizeof (int);
11535 	return (0);
11536 }
11537 
11538 /*
11539  * This routine gets default values of certain options whose default
11540  * values are maintained by protocol specific code
11541  */
11542 /* ARGSUSED */
11543 int
11544 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11545 {
11546 	int *i1 = (int *)ptr;
11547 
11548 	switch (level) {
11549 	case IPPROTO_IP:
11550 		switch (name) {
11551 		case IP_MULTICAST_TTL:
11552 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11553 			return (sizeof (uchar_t));
11554 		case IP_MULTICAST_LOOP:
11555 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11556 			return (sizeof (uchar_t));
11557 		default:
11558 			return (-1);
11559 		}
11560 	case IPPROTO_IPV6:
11561 		switch (name) {
11562 		case IPV6_UNICAST_HOPS:
11563 			*i1 = ipv6_def_hops;
11564 			return (sizeof (int));
11565 		case IPV6_MULTICAST_HOPS:
11566 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11567 			return (sizeof (int));
11568 		case IPV6_MULTICAST_LOOP:
11569 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11570 			return (sizeof (int));
11571 		case IPV6_V6ONLY:
11572 			*i1 = 1;
11573 			return (sizeof (int));
11574 		default:
11575 			return (-1);
11576 		}
11577 	default:
11578 		return (-1);
11579 	}
11580 	/* NOTREACHED */
11581 }
11582 
11583 /*
11584  * Given a destination address and a pointer to where to put the information
11585  * this routine fills in the mtuinfo.
11586  */
11587 int
11588 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11589     struct ip6_mtuinfo *mtuinfo)
11590 {
11591 	ire_t *ire;
11592 
11593 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11594 		return (-1);
11595 
11596 	bzero(mtuinfo, sizeof (*mtuinfo));
11597 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11598 	mtuinfo->ip6m_addr.sin6_port = port;
11599 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11600 
11601 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL);
11602 	if (ire != NULL) {
11603 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11604 		ire_refrele(ire);
11605 	} else {
11606 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11607 	}
11608 	return (sizeof (struct ip6_mtuinfo));
11609 }
11610 
11611 /*
11612  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11613  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11614  * isn't.  This doesn't matter as the error checking is done properly for the
11615  * other MRT options coming in through ip_opt_set.
11616  */
11617 int
11618 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11619 {
11620 	conn_t		*connp = Q_TO_CONN(q);
11621 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11622 
11623 	switch (level) {
11624 	case IPPROTO_IP:
11625 		switch (name) {
11626 		case MRT_VERSION:
11627 		case MRT_ASSERT:
11628 			(void) ip_mrouter_get(name, q, ptr);
11629 			return (sizeof (int));
11630 		case IP_SEC_OPT:
11631 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11632 		case IP_NEXTHOP:
11633 			if (connp->conn_nexthop_set) {
11634 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11635 				return (sizeof (ipaddr_t));
11636 			} else
11637 				return (0);
11638 		case IP_RECVPKTINFO:
11639 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11640 			return (sizeof (int));
11641 		default:
11642 			break;
11643 		}
11644 		break;
11645 	case IPPROTO_IPV6:
11646 		switch (name) {
11647 		case IPV6_SEC_OPT:
11648 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11649 		case IPV6_SRC_PREFERENCES: {
11650 			return (ip6_get_src_preferences(connp,
11651 			    (uint32_t *)ptr));
11652 		}
11653 		case IPV6_V6ONLY:
11654 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11655 			return (sizeof (int));
11656 		case IPV6_PATHMTU:
11657 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11658 				(struct ip6_mtuinfo *)ptr));
11659 		default:
11660 			break;
11661 		}
11662 		break;
11663 	default:
11664 		break;
11665 	}
11666 	return (-1);
11667 }
11668 
11669 /* Named Dispatch routine to get a current value out of our parameter table. */
11670 /* ARGSUSED */
11671 static int
11672 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11673 {
11674 	ipparam_t *ippa = (ipparam_t *)cp;
11675 
11676 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11677 	return (0);
11678 }
11679 
11680 /* ARGSUSED */
11681 static int
11682 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11683 {
11684 
11685 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11686 	return (0);
11687 }
11688 
11689 /*
11690  * Set ip{,6}_forwarding values.  This means walking through all of the
11691  * ill's and toggling their forwarding values.
11692  */
11693 /* ARGSUSED */
11694 static int
11695 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11696 {
11697 	long new_value;
11698 	int *forwarding_value = (int *)cp;
11699 	ill_t *walker;
11700 	boolean_t isv6 = (forwarding_value == &ipv6_forward);
11701 	ill_walk_context_t ctx;
11702 
11703 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11704 	    new_value < 0 || new_value > 1) {
11705 		return (EINVAL);
11706 	}
11707 
11708 	*forwarding_value = new_value;
11709 
11710 	/*
11711 	 * Regardless of the current value of ip_forwarding, set all per-ill
11712 	 * values of ip_forwarding to the value being set.
11713 	 *
11714 	 * Bring all the ill's up to date with the new global value.
11715 	 */
11716 	rw_enter(&ill_g_lock, RW_READER);
11717 
11718 	if (isv6)
11719 		walker = ILL_START_WALK_V6(&ctx);
11720 	else
11721 		walker = ILL_START_WALK_V4(&ctx);
11722 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11723 		(void) ill_forward_set(q, mp, (new_value != 0),
11724 		    (caddr_t)walker);
11725 	}
11726 	rw_exit(&ill_g_lock);
11727 
11728 	return (0);
11729 }
11730 
11731 /*
11732  * Walk through the param array specified registering each element with the
11733  * Named Dispatch handler. This is called only during init. So it is ok
11734  * not to acquire any locks
11735  */
11736 static boolean_t
11737 ip_param_register(ipparam_t *ippa, size_t ippa_cnt,
11738     ipndp_t *ipnd, size_t ipnd_cnt)
11739 {
11740 	for (; ippa_cnt-- > 0; ippa++) {
11741 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11742 			if (!nd_load(&ip_g_nd, ippa->ip_param_name,
11743 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11744 				nd_free(&ip_g_nd);
11745 				return (B_FALSE);
11746 			}
11747 		}
11748 	}
11749 
11750 	for (; ipnd_cnt-- > 0; ipnd++) {
11751 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11752 			if (!nd_load(&ip_g_nd, ipnd->ip_ndp_name,
11753 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11754 			    ipnd->ip_ndp_data)) {
11755 				nd_free(&ip_g_nd);
11756 				return (B_FALSE);
11757 			}
11758 		}
11759 	}
11760 
11761 	return (B_TRUE);
11762 }
11763 
11764 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11765 /* ARGSUSED */
11766 static int
11767 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11768 {
11769 	long		new_value;
11770 	ipparam_t	*ippa = (ipparam_t *)cp;
11771 
11772 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11773 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11774 		return (EINVAL);
11775 	}
11776 	ippa->ip_param_value = new_value;
11777 	return (0);
11778 }
11779 
11780 /*
11781  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11782  * When an ipf is passed here for the first time, if
11783  * we already have in-order fragments on the queue, we convert from the fast-
11784  * path reassembly scheme to the hard-case scheme.  From then on, additional
11785  * fragments are reassembled here.  We keep track of the start and end offsets
11786  * of each piece, and the number of holes in the chain.  When the hole count
11787  * goes to zero, we are done!
11788  *
11789  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11790  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11791  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11792  * after the call to ip_reassemble().
11793  */
11794 int
11795 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11796     size_t msg_len)
11797 {
11798 	uint_t	end;
11799 	mblk_t	*next_mp;
11800 	mblk_t	*mp1;
11801 	uint_t	offset;
11802 	boolean_t incr_dups = B_TRUE;
11803 	boolean_t offset_zero_seen = B_FALSE;
11804 	boolean_t pkt_boundary_checked = B_FALSE;
11805 
11806 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11807 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11808 
11809 	/* Add in byte count */
11810 	ipf->ipf_count += msg_len;
11811 	if (ipf->ipf_end) {
11812 		/*
11813 		 * We were part way through in-order reassembly, but now there
11814 		 * is a hole.  We walk through messages already queued, and
11815 		 * mark them for hard case reassembly.  We know that up till
11816 		 * now they were in order starting from offset zero.
11817 		 */
11818 		offset = 0;
11819 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11820 			IP_REASS_SET_START(mp1, offset);
11821 			if (offset == 0) {
11822 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11823 				offset = -ipf->ipf_nf_hdr_len;
11824 			}
11825 			offset += mp1->b_wptr - mp1->b_rptr;
11826 			IP_REASS_SET_END(mp1, offset);
11827 		}
11828 		/* One hole at the end. */
11829 		ipf->ipf_hole_cnt = 1;
11830 		/* Brand it as a hard case, forever. */
11831 		ipf->ipf_end = 0;
11832 	}
11833 	/* Walk through all the new pieces. */
11834 	do {
11835 		end = start + (mp->b_wptr - mp->b_rptr);
11836 		/*
11837 		 * If start is 0, decrease 'end' only for the first mblk of
11838 		 * the fragment. Otherwise 'end' can get wrong value in the
11839 		 * second pass of the loop if first mblk is exactly the
11840 		 * size of ipf_nf_hdr_len.
11841 		 */
11842 		if (start == 0 && !offset_zero_seen) {
11843 			/* First segment */
11844 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11845 			end -= ipf->ipf_nf_hdr_len;
11846 			offset_zero_seen = B_TRUE;
11847 		}
11848 		next_mp = mp->b_cont;
11849 		/*
11850 		 * We are checking to see if there is any interesing data
11851 		 * to process.  If there isn't and the mblk isn't the
11852 		 * one which carries the unfragmentable header then we
11853 		 * drop it.  It's possible to have just the unfragmentable
11854 		 * header come through without any data.  That needs to be
11855 		 * saved.
11856 		 *
11857 		 * If the assert at the top of this function holds then the
11858 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11859 		 * is infrequently traveled enough that the test is left in
11860 		 * to protect against future code changes which break that
11861 		 * invariant.
11862 		 */
11863 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11864 			/* Empty.  Blast it. */
11865 			IP_REASS_SET_START(mp, 0);
11866 			IP_REASS_SET_END(mp, 0);
11867 			/*
11868 			 * If the ipf points to the mblk we are about to free,
11869 			 * update ipf to point to the next mblk (or NULL
11870 			 * if none).
11871 			 */
11872 			if (ipf->ipf_mp->b_cont == mp)
11873 				ipf->ipf_mp->b_cont = next_mp;
11874 			freeb(mp);
11875 			continue;
11876 		}
11877 		mp->b_cont = NULL;
11878 		IP_REASS_SET_START(mp, start);
11879 		IP_REASS_SET_END(mp, end);
11880 		if (!ipf->ipf_tail_mp) {
11881 			ipf->ipf_tail_mp = mp;
11882 			ipf->ipf_mp->b_cont = mp;
11883 			if (start == 0 || !more) {
11884 				ipf->ipf_hole_cnt = 1;
11885 				/*
11886 				 * if the first fragment comes in more than one
11887 				 * mblk, this loop will be executed for each
11888 				 * mblk. Need to adjust hole count so exiting
11889 				 * this routine will leave hole count at 1.
11890 				 */
11891 				if (next_mp)
11892 					ipf->ipf_hole_cnt++;
11893 			} else
11894 				ipf->ipf_hole_cnt = 2;
11895 			continue;
11896 		} else if (ipf->ipf_last_frag_seen && !more &&
11897 			    !pkt_boundary_checked) {
11898 			/*
11899 			 * We check datagram boundary only if this fragment
11900 			 * claims to be the last fragment and we have seen a
11901 			 * last fragment in the past too. We do this only
11902 			 * once for a given fragment.
11903 			 *
11904 			 * start cannot be 0 here as fragments with start=0
11905 			 * and MF=0 gets handled as a complete packet. These
11906 			 * fragments should not reach here.
11907 			 */
11908 
11909 			if (start + msgdsize(mp) !=
11910 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11911 				/*
11912 				 * We have two fragments both of which claim
11913 				 * to be the last fragment but gives conflicting
11914 				 * information about the whole datagram size.
11915 				 * Something fishy is going on. Drop the
11916 				 * fragment and free up the reassembly list.
11917 				 */
11918 				return (IP_REASS_FAILED);
11919 			}
11920 
11921 			/*
11922 			 * We shouldn't come to this code block again for this
11923 			 * particular fragment.
11924 			 */
11925 			pkt_boundary_checked = B_TRUE;
11926 		}
11927 
11928 		/* New stuff at or beyond tail? */
11929 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11930 		if (start >= offset) {
11931 			if (ipf->ipf_last_frag_seen) {
11932 				/* current fragment is beyond last fragment */
11933 				return (IP_REASS_FAILED);
11934 			}
11935 			/* Link it on end. */
11936 			ipf->ipf_tail_mp->b_cont = mp;
11937 			ipf->ipf_tail_mp = mp;
11938 			if (more) {
11939 				if (start != offset)
11940 					ipf->ipf_hole_cnt++;
11941 			} else if (start == offset && next_mp == NULL)
11942 					ipf->ipf_hole_cnt--;
11943 			continue;
11944 		}
11945 		mp1 = ipf->ipf_mp->b_cont;
11946 		offset = IP_REASS_START(mp1);
11947 		/* New stuff at the front? */
11948 		if (start < offset) {
11949 			if (start == 0) {
11950 				if (end >= offset) {
11951 					/* Nailed the hole at the begining. */
11952 					ipf->ipf_hole_cnt--;
11953 				}
11954 			} else if (end < offset) {
11955 				/*
11956 				 * A hole, stuff, and a hole where there used
11957 				 * to be just a hole.
11958 				 */
11959 				ipf->ipf_hole_cnt++;
11960 			}
11961 			mp->b_cont = mp1;
11962 			/* Check for overlap. */
11963 			while (end > offset) {
11964 				if (end < IP_REASS_END(mp1)) {
11965 					mp->b_wptr -= end - offset;
11966 					IP_REASS_SET_END(mp, offset);
11967 					BUMP_MIB(ill->ill_ip_mib,
11968 					    ipIfStatsReasmPartDups);
11969 					break;
11970 				}
11971 				/* Did we cover another hole? */
11972 				if ((mp1->b_cont &&
11973 				    IP_REASS_END(mp1) !=
11974 				    IP_REASS_START(mp1->b_cont) &&
11975 				    end >= IP_REASS_START(mp1->b_cont)) ||
11976 				    (!ipf->ipf_last_frag_seen && !more)) {
11977 					ipf->ipf_hole_cnt--;
11978 				}
11979 				/* Clip out mp1. */
11980 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11981 					/*
11982 					 * After clipping out mp1, this guy
11983 					 * is now hanging off the end.
11984 					 */
11985 					ipf->ipf_tail_mp = mp;
11986 				}
11987 				IP_REASS_SET_START(mp1, 0);
11988 				IP_REASS_SET_END(mp1, 0);
11989 				/* Subtract byte count */
11990 				ipf->ipf_count -= mp1->b_datap->db_lim -
11991 				    mp1->b_datap->db_base;
11992 				freeb(mp1);
11993 				BUMP_MIB(ill->ill_ip_mib,
11994 				    ipIfStatsReasmPartDups);
11995 				mp1 = mp->b_cont;
11996 				if (!mp1)
11997 					break;
11998 				offset = IP_REASS_START(mp1);
11999 			}
12000 			ipf->ipf_mp->b_cont = mp;
12001 			continue;
12002 		}
12003 		/*
12004 		 * The new piece starts somewhere between the start of the head
12005 		 * and before the end of the tail.
12006 		 */
12007 		for (; mp1; mp1 = mp1->b_cont) {
12008 			offset = IP_REASS_END(mp1);
12009 			if (start < offset) {
12010 				if (end <= offset) {
12011 					/* Nothing new. */
12012 					IP_REASS_SET_START(mp, 0);
12013 					IP_REASS_SET_END(mp, 0);
12014 					/* Subtract byte count */
12015 					ipf->ipf_count -= mp->b_datap->db_lim -
12016 					    mp->b_datap->db_base;
12017 					if (incr_dups) {
12018 						ipf->ipf_num_dups++;
12019 						incr_dups = B_FALSE;
12020 					}
12021 					freeb(mp);
12022 					BUMP_MIB(ill->ill_ip_mib,
12023 					    ipIfStatsReasmDuplicates);
12024 					break;
12025 				}
12026 				/*
12027 				 * Trim redundant stuff off beginning of new
12028 				 * piece.
12029 				 */
12030 				IP_REASS_SET_START(mp, offset);
12031 				mp->b_rptr += offset - start;
12032 				BUMP_MIB(ill->ill_ip_mib,
12033 				    ipIfStatsReasmPartDups);
12034 				start = offset;
12035 				if (!mp1->b_cont) {
12036 					/*
12037 					 * After trimming, this guy is now
12038 					 * hanging off the end.
12039 					 */
12040 					mp1->b_cont = mp;
12041 					ipf->ipf_tail_mp = mp;
12042 					if (!more) {
12043 						ipf->ipf_hole_cnt--;
12044 					}
12045 					break;
12046 				}
12047 			}
12048 			if (start >= IP_REASS_START(mp1->b_cont))
12049 				continue;
12050 			/* Fill a hole */
12051 			if (start > offset)
12052 				ipf->ipf_hole_cnt++;
12053 			mp->b_cont = mp1->b_cont;
12054 			mp1->b_cont = mp;
12055 			mp1 = mp->b_cont;
12056 			offset = IP_REASS_START(mp1);
12057 			if (end >= offset) {
12058 				ipf->ipf_hole_cnt--;
12059 				/* Check for overlap. */
12060 				while (end > offset) {
12061 					if (end < IP_REASS_END(mp1)) {
12062 						mp->b_wptr -= end - offset;
12063 						IP_REASS_SET_END(mp, offset);
12064 						/*
12065 						 * TODO we might bump
12066 						 * this up twice if there is
12067 						 * overlap at both ends.
12068 						 */
12069 						BUMP_MIB(ill->ill_ip_mib,
12070 						    ipIfStatsReasmPartDups);
12071 						break;
12072 					}
12073 					/* Did we cover another hole? */
12074 					if ((mp1->b_cont &&
12075 					    IP_REASS_END(mp1)
12076 					    != IP_REASS_START(mp1->b_cont) &&
12077 					    end >=
12078 					    IP_REASS_START(mp1->b_cont)) ||
12079 					    (!ipf->ipf_last_frag_seen &&
12080 					    !more)) {
12081 						ipf->ipf_hole_cnt--;
12082 					}
12083 					/* Clip out mp1. */
12084 					if ((mp->b_cont = mp1->b_cont) ==
12085 					    NULL) {
12086 						/*
12087 						 * After clipping out mp1,
12088 						 * this guy is now hanging
12089 						 * off the end.
12090 						 */
12091 						ipf->ipf_tail_mp = mp;
12092 					}
12093 					IP_REASS_SET_START(mp1, 0);
12094 					IP_REASS_SET_END(mp1, 0);
12095 					/* Subtract byte count */
12096 					ipf->ipf_count -=
12097 					    mp1->b_datap->db_lim -
12098 					    mp1->b_datap->db_base;
12099 					freeb(mp1);
12100 					BUMP_MIB(ill->ill_ip_mib,
12101 					    ipIfStatsReasmPartDups);
12102 					mp1 = mp->b_cont;
12103 					if (!mp1)
12104 						break;
12105 					offset = IP_REASS_START(mp1);
12106 				}
12107 			}
12108 			break;
12109 		}
12110 	} while (start = end, mp = next_mp);
12111 
12112 	/* Fragment just processed could be the last one. Remember this fact */
12113 	if (!more)
12114 		ipf->ipf_last_frag_seen = B_TRUE;
12115 
12116 	/* Still got holes? */
12117 	if (ipf->ipf_hole_cnt)
12118 		return (IP_REASS_PARTIAL);
12119 	/* Clean up overloaded fields to avoid upstream disasters. */
12120 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12121 		IP_REASS_SET_START(mp1, 0);
12122 		IP_REASS_SET_END(mp1, 0);
12123 	}
12124 	return (IP_REASS_COMPLETE);
12125 }
12126 
12127 /*
12128  * ipsec processing for the fast path, used for input UDP Packets
12129  */
12130 static boolean_t
12131 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12132     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12133 {
12134 	uint32_t	ill_index;
12135 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12136 
12137 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12138 	/* The ill_index of the incoming ILL */
12139 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12140 
12141 	/* pass packet up to the transport */
12142 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
12143 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12144 		    NULL, mctl_present);
12145 		if (*first_mpp == NULL) {
12146 			return (B_FALSE);
12147 		}
12148 	}
12149 
12150 	/* Initiate IPPF processing for fastpath UDP */
12151 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
12152 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12153 		if (*mpp == NULL) {
12154 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12155 			    "deferred/dropped during IPPF processing\n"));
12156 			return (B_FALSE);
12157 		}
12158 	}
12159 	/*
12160 	 * We make the checks as below since we are in the fast path
12161 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12162 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12163 	 */
12164 	if (connp->conn_recvif || connp->conn_recvslla ||
12165 	    connp->conn_ip_recvpktinfo) {
12166 		if (connp->conn_recvif) {
12167 			in_flags = IPF_RECVIF;
12168 		}
12169 		/*
12170 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12171 		 * so the flag passed to ip_add_info is based on IP version
12172 		 * of connp.
12173 		 */
12174 		if (connp->conn_ip_recvpktinfo) {
12175 			if (connp->conn_af_isv6) {
12176 				/*
12177 				 * V6 only needs index
12178 				 */
12179 				in_flags |= IPF_RECVIF;
12180 			} else {
12181 				/*
12182 				 * V4 needs index + matching address.
12183 				 */
12184 				in_flags |= IPF_RECVADDR;
12185 			}
12186 		}
12187 		if (connp->conn_recvslla) {
12188 			in_flags |= IPF_RECVSLLA;
12189 		}
12190 		/*
12191 		 * since in_flags are being set ill will be
12192 		 * referenced in ip_add_info, so it better not
12193 		 * be NULL.
12194 		 */
12195 		/*
12196 		 * the actual data will be contained in b_cont
12197 		 * upon successful return of the following call.
12198 		 * If the call fails then the original mblk is
12199 		 * returned.
12200 		 */
12201 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp));
12202 	}
12203 
12204 	return (B_TRUE);
12205 }
12206 
12207 /*
12208  * Fragmentation reassembly.  Each ILL has a hash table for
12209  * queuing packets undergoing reassembly for all IPIFs
12210  * associated with the ILL.  The hash is based on the packet
12211  * IP ident field.  The ILL frag hash table was allocated
12212  * as a timer block at the time the ILL was created.  Whenever
12213  * there is anything on the reassembly queue, the timer will
12214  * be running.  Returns B_TRUE if successful else B_FALSE;
12215  * frees mp on failure.
12216  */
12217 static boolean_t
12218 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12219     uint32_t *cksum_val, uint16_t *cksum_flags)
12220 {
12221 	uint32_t	frag_offset_flags;
12222 	ill_t		*ill = (ill_t *)q->q_ptr;
12223 	mblk_t		*mp = *mpp;
12224 	mblk_t		*t_mp;
12225 	ipaddr_t	dst;
12226 	uint8_t		proto = ipha->ipha_protocol;
12227 	uint32_t	sum_val;
12228 	uint16_t	sum_flags;
12229 	ipf_t		*ipf;
12230 	ipf_t		**ipfp;
12231 	ipfb_t		*ipfb;
12232 	uint16_t	ident;
12233 	uint32_t	offset;
12234 	ipaddr_t	src;
12235 	uint_t		hdr_length;
12236 	uint32_t	end;
12237 	mblk_t		*mp1;
12238 	mblk_t		*tail_mp;
12239 	size_t		count;
12240 	size_t		msg_len;
12241 	uint8_t		ecn_info = 0;
12242 	uint32_t	packet_size;
12243 	boolean_t	pruned = B_FALSE;
12244 
12245 	if (cksum_val != NULL)
12246 		*cksum_val = 0;
12247 	if (cksum_flags != NULL)
12248 		*cksum_flags = 0;
12249 
12250 	/*
12251 	 * Drop the fragmented as early as possible, if
12252 	 * we don't have resource(s) to re-assemble.
12253 	 */
12254 	if (ip_reass_queue_bytes == 0) {
12255 		freemsg(mp);
12256 		return (B_FALSE);
12257 	}
12258 
12259 	/* Check for fragmentation offset; return if there's none */
12260 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12261 	    (IPH_MF | IPH_OFFSET)) == 0)
12262 		return (B_TRUE);
12263 
12264 	/*
12265 	 * We utilize hardware computed checksum info only for UDP since
12266 	 * IP fragmentation is a normal occurence for the protocol.  In
12267 	 * addition, checksum offload support for IP fragments carrying
12268 	 * UDP payload is commonly implemented across network adapters.
12269 	 */
12270 	ASSERT(ill != NULL);
12271 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12272 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12273 		mblk_t *mp1 = mp->b_cont;
12274 		int32_t len;
12275 
12276 		/* Record checksum information from the packet */
12277 		sum_val = (uint32_t)DB_CKSUM16(mp);
12278 		sum_flags = DB_CKSUMFLAGS(mp);
12279 
12280 		/* IP payload offset from beginning of mblk */
12281 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12282 
12283 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12284 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12285 		    offset >= DB_CKSUMSTART(mp) &&
12286 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12287 			uint32_t adj;
12288 			/*
12289 			 * Partial checksum has been calculated by hardware
12290 			 * and attached to the packet; in addition, any
12291 			 * prepended extraneous data is even byte aligned.
12292 			 * If any such data exists, we adjust the checksum;
12293 			 * this would also handle any postpended data.
12294 			 */
12295 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12296 			    mp, mp1, len, adj);
12297 
12298 			/* One's complement subtract extraneous checksum */
12299 			if (adj >= sum_val)
12300 				sum_val = ~(adj - sum_val) & 0xFFFF;
12301 			else
12302 				sum_val -= adj;
12303 		}
12304 	} else {
12305 		sum_val = 0;
12306 		sum_flags = 0;
12307 	}
12308 
12309 	/* Clear hardware checksumming flag */
12310 	DB_CKSUMFLAGS(mp) = 0;
12311 
12312 	ident = ipha->ipha_ident;
12313 	offset = (frag_offset_flags << 3) & 0xFFFF;
12314 	src = ipha->ipha_src;
12315 	dst = ipha->ipha_dst;
12316 	hdr_length = IPH_HDR_LENGTH(ipha);
12317 	end = ntohs(ipha->ipha_length) - hdr_length;
12318 
12319 	/* If end == 0 then we have a packet with no data, so just free it */
12320 	if (end == 0) {
12321 		freemsg(mp);
12322 		return (B_FALSE);
12323 	}
12324 
12325 	/* Record the ECN field info. */
12326 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12327 	if (offset != 0) {
12328 		/*
12329 		 * If this isn't the first piece, strip the header, and
12330 		 * add the offset to the end value.
12331 		 */
12332 		mp->b_rptr += hdr_length;
12333 		end += offset;
12334 	}
12335 
12336 	msg_len = MBLKSIZE(mp);
12337 	tail_mp = mp;
12338 	while (tail_mp->b_cont != NULL) {
12339 		tail_mp = tail_mp->b_cont;
12340 		msg_len += MBLKSIZE(tail_mp);
12341 	}
12342 
12343 	/* If the reassembly list for this ILL will get too big, prune it */
12344 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12345 	    ip_reass_queue_bytes) {
12346 		ill_frag_prune(ill,
12347 		    (ip_reass_queue_bytes < msg_len) ? 0 :
12348 		    (ip_reass_queue_bytes - msg_len));
12349 		pruned = B_TRUE;
12350 	}
12351 
12352 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12353 	mutex_enter(&ipfb->ipfb_lock);
12354 
12355 	ipfp = &ipfb->ipfb_ipf;
12356 	/* Try to find an existing fragment queue for this packet. */
12357 	for (;;) {
12358 		ipf = ipfp[0];
12359 		if (ipf != NULL) {
12360 			/*
12361 			 * It has to match on ident and src/dst address.
12362 			 */
12363 			if (ipf->ipf_ident == ident &&
12364 			    ipf->ipf_src == src &&
12365 			    ipf->ipf_dst == dst &&
12366 			    ipf->ipf_protocol == proto) {
12367 				/*
12368 				 * If we have received too many
12369 				 * duplicate fragments for this packet
12370 				 * free it.
12371 				 */
12372 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12373 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12374 					freemsg(mp);
12375 					mutex_exit(&ipfb->ipfb_lock);
12376 					return (B_FALSE);
12377 				}
12378 				/* Found it. */
12379 				break;
12380 			}
12381 			ipfp = &ipf->ipf_hash_next;
12382 			continue;
12383 		}
12384 
12385 		/*
12386 		 * If we pruned the list, do we want to store this new
12387 		 * fragment?. We apply an optimization here based on the
12388 		 * fact that most fragments will be received in order.
12389 		 * So if the offset of this incoming fragment is zero,
12390 		 * it is the first fragment of a new packet. We will
12391 		 * keep it.  Otherwise drop the fragment, as we have
12392 		 * probably pruned the packet already (since the
12393 		 * packet cannot be found).
12394 		 */
12395 		if (pruned && offset != 0) {
12396 			mutex_exit(&ipfb->ipfb_lock);
12397 			freemsg(mp);
12398 			return (B_FALSE);
12399 		}
12400 
12401 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS)  {
12402 			/*
12403 			 * Too many fragmented packets in this hash
12404 			 * bucket. Free the oldest.
12405 			 */
12406 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12407 		}
12408 
12409 		/* New guy.  Allocate a frag message. */
12410 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12411 		if (mp1 == NULL) {
12412 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12413 			freemsg(mp);
12414 reass_done:
12415 			mutex_exit(&ipfb->ipfb_lock);
12416 			return (B_FALSE);
12417 		}
12418 
12419 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12420 		mp1->b_cont = mp;
12421 
12422 		/* Initialize the fragment header. */
12423 		ipf = (ipf_t *)mp1->b_rptr;
12424 		ipf->ipf_mp = mp1;
12425 		ipf->ipf_ptphn = ipfp;
12426 		ipfp[0] = ipf;
12427 		ipf->ipf_hash_next = NULL;
12428 		ipf->ipf_ident = ident;
12429 		ipf->ipf_protocol = proto;
12430 		ipf->ipf_src = src;
12431 		ipf->ipf_dst = dst;
12432 		ipf->ipf_nf_hdr_len = 0;
12433 		/* Record reassembly start time. */
12434 		ipf->ipf_timestamp = gethrestime_sec();
12435 		/* Record ipf generation and account for frag header */
12436 		ipf->ipf_gen = ill->ill_ipf_gen++;
12437 		ipf->ipf_count = MBLKSIZE(mp1);
12438 		ipf->ipf_last_frag_seen = B_FALSE;
12439 		ipf->ipf_ecn = ecn_info;
12440 		ipf->ipf_num_dups = 0;
12441 		ipfb->ipfb_frag_pkts++;
12442 		ipf->ipf_checksum = 0;
12443 		ipf->ipf_checksum_flags = 0;
12444 
12445 		/* Store checksum value in fragment header */
12446 		if (sum_flags != 0) {
12447 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12448 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12449 			ipf->ipf_checksum = sum_val;
12450 			ipf->ipf_checksum_flags = sum_flags;
12451 		}
12452 
12453 		/*
12454 		 * We handle reassembly two ways.  In the easy case,
12455 		 * where all the fragments show up in order, we do
12456 		 * minimal bookkeeping, and just clip new pieces on
12457 		 * the end.  If we ever see a hole, then we go off
12458 		 * to ip_reassemble which has to mark the pieces and
12459 		 * keep track of the number of holes, etc.  Obviously,
12460 		 * the point of having both mechanisms is so we can
12461 		 * handle the easy case as efficiently as possible.
12462 		 */
12463 		if (offset == 0) {
12464 			/* Easy case, in-order reassembly so far. */
12465 			ipf->ipf_count += msg_len;
12466 			ipf->ipf_tail_mp = tail_mp;
12467 			/*
12468 			 * Keep track of next expected offset in
12469 			 * ipf_end.
12470 			 */
12471 			ipf->ipf_end = end;
12472 			ipf->ipf_nf_hdr_len = hdr_length;
12473 		} else {
12474 			/* Hard case, hole at the beginning. */
12475 			ipf->ipf_tail_mp = NULL;
12476 			/*
12477 			 * ipf_end == 0 means that we have given up
12478 			 * on easy reassembly.
12479 			 */
12480 			ipf->ipf_end = 0;
12481 
12482 			/* Forget checksum offload from now on */
12483 			ipf->ipf_checksum_flags = 0;
12484 
12485 			/*
12486 			 * ipf_hole_cnt is set by ip_reassemble.
12487 			 * ipf_count is updated by ip_reassemble.
12488 			 * No need to check for return value here
12489 			 * as we don't expect reassembly to complete
12490 			 * or fail for the first fragment itself.
12491 			 */
12492 			(void) ip_reassemble(mp, ipf,
12493 			    (frag_offset_flags & IPH_OFFSET) << 3,
12494 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12495 		}
12496 		/* Update per ipfb and ill byte counts */
12497 		ipfb->ipfb_count += ipf->ipf_count;
12498 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12499 		ill->ill_frag_count += ipf->ipf_count;
12500 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12501 		/* If the frag timer wasn't already going, start it. */
12502 		mutex_enter(&ill->ill_lock);
12503 		ill_frag_timer_start(ill);
12504 		mutex_exit(&ill->ill_lock);
12505 		goto reass_done;
12506 	}
12507 
12508 	/*
12509 	 * If the packet's flag has changed (it could be coming up
12510 	 * from an interface different than the previous, therefore
12511 	 * possibly different checksum capability), then forget about
12512 	 * any stored checksum states.  Otherwise add the value to
12513 	 * the existing one stored in the fragment header.
12514 	 */
12515 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12516 		sum_val += ipf->ipf_checksum;
12517 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12518 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12519 		ipf->ipf_checksum = sum_val;
12520 	} else if (ipf->ipf_checksum_flags != 0) {
12521 		/* Forget checksum offload from now on */
12522 		ipf->ipf_checksum_flags = 0;
12523 	}
12524 
12525 	/*
12526 	 * We have a new piece of a datagram which is already being
12527 	 * reassembled.  Update the ECN info if all IP fragments
12528 	 * are ECN capable.  If there is one which is not, clear
12529 	 * all the info.  If there is at least one which has CE
12530 	 * code point, IP needs to report that up to transport.
12531 	 */
12532 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12533 		if (ecn_info == IPH_ECN_CE)
12534 			ipf->ipf_ecn = IPH_ECN_CE;
12535 	} else {
12536 		ipf->ipf_ecn = IPH_ECN_NECT;
12537 	}
12538 	if (offset && ipf->ipf_end == offset) {
12539 		/* The new fragment fits at the end */
12540 		ipf->ipf_tail_mp->b_cont = mp;
12541 		/* Update the byte count */
12542 		ipf->ipf_count += msg_len;
12543 		/* Update per ipfb and ill byte counts */
12544 		ipfb->ipfb_count += msg_len;
12545 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12546 		ill->ill_frag_count += msg_len;
12547 		ASSERT(ill->ill_frag_count > 0); /* Wraparound */
12548 		if (frag_offset_flags & IPH_MF) {
12549 			/* More to come. */
12550 			ipf->ipf_end = end;
12551 			ipf->ipf_tail_mp = tail_mp;
12552 			goto reass_done;
12553 		}
12554 	} else {
12555 		/* Go do the hard cases. */
12556 		int ret;
12557 
12558 		if (offset == 0)
12559 			ipf->ipf_nf_hdr_len = hdr_length;
12560 
12561 		/* Save current byte count */
12562 		count = ipf->ipf_count;
12563 		ret = ip_reassemble(mp, ipf,
12564 		    (frag_offset_flags & IPH_OFFSET) << 3,
12565 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12566 		/* Count of bytes added and subtracted (freeb()ed) */
12567 		count = ipf->ipf_count - count;
12568 		if (count) {
12569 			/* Update per ipfb and ill byte counts */
12570 			ipfb->ipfb_count += count;
12571 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12572 			ill->ill_frag_count += count;
12573 			ASSERT(ill->ill_frag_count > 0);
12574 		}
12575 		if (ret == IP_REASS_PARTIAL) {
12576 			goto reass_done;
12577 		} else if (ret == IP_REASS_FAILED) {
12578 			/* Reassembly failed. Free up all resources */
12579 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12580 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12581 				IP_REASS_SET_START(t_mp, 0);
12582 				IP_REASS_SET_END(t_mp, 0);
12583 			}
12584 			freemsg(mp);
12585 			goto reass_done;
12586 		}
12587 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12588 	}
12589 	/*
12590 	 * We have completed reassembly.  Unhook the frag header from
12591 	 * the reassembly list.
12592 	 *
12593 	 * Before we free the frag header, record the ECN info
12594 	 * to report back to the transport.
12595 	 */
12596 	ecn_info = ipf->ipf_ecn;
12597 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12598 	ipfp = ipf->ipf_ptphn;
12599 
12600 	/* We need to supply these to caller */
12601 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12602 		sum_val = ipf->ipf_checksum;
12603 	else
12604 		sum_val = 0;
12605 
12606 	mp1 = ipf->ipf_mp;
12607 	count = ipf->ipf_count;
12608 	ipf = ipf->ipf_hash_next;
12609 	if (ipf != NULL)
12610 		ipf->ipf_ptphn = ipfp;
12611 	ipfp[0] = ipf;
12612 	ill->ill_frag_count -= count;
12613 	ASSERT(ipfb->ipfb_count >= count);
12614 	ipfb->ipfb_count -= count;
12615 	ipfb->ipfb_frag_pkts--;
12616 	mutex_exit(&ipfb->ipfb_lock);
12617 	/* Ditch the frag header. */
12618 	mp = mp1->b_cont;
12619 
12620 	freeb(mp1);
12621 
12622 	/* Restore original IP length in header. */
12623 	packet_size = (uint32_t)msgdsize(mp);
12624 	if (packet_size > IP_MAXPACKET) {
12625 		freemsg(mp);
12626 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12627 		return (B_FALSE);
12628 	}
12629 
12630 	if (DB_REF(mp) > 1) {
12631 		mblk_t *mp2 = copymsg(mp);
12632 
12633 		freemsg(mp);
12634 		if (mp2 == NULL) {
12635 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12636 			return (B_FALSE);
12637 		}
12638 		mp = mp2;
12639 	}
12640 	ipha = (ipha_t *)mp->b_rptr;
12641 
12642 	ipha->ipha_length = htons((uint16_t)packet_size);
12643 	/* We're now complete, zip the frag state */
12644 	ipha->ipha_fragment_offset_and_flags = 0;
12645 	/* Record the ECN info. */
12646 	ipha->ipha_type_of_service &= 0xFC;
12647 	ipha->ipha_type_of_service |= ecn_info;
12648 	*mpp = mp;
12649 
12650 	/* Reassembly is successful; return checksum information if needed */
12651 	if (cksum_val != NULL)
12652 		*cksum_val = sum_val;
12653 	if (cksum_flags != NULL)
12654 		*cksum_flags = sum_flags;
12655 
12656 	return (B_TRUE);
12657 }
12658 
12659 /*
12660  * Perform ip header check sum update local options.
12661  * return B_TRUE if all is well, else return B_FALSE and release
12662  * the mp. caller is responsible for decrementing ire ref cnt.
12663  */
12664 static boolean_t
12665 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire)
12666 {
12667 	mblk_t		*first_mp;
12668 	boolean_t	mctl_present;
12669 	uint16_t	sum;
12670 
12671 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12672 	/*
12673 	 * Don't do the checksum if it has gone through AH/ESP
12674 	 * processing.
12675 	 */
12676 	if (!mctl_present) {
12677 		sum = ip_csum_hdr(ipha);
12678 		if (sum != 0) {
12679 			if (ill != NULL) {
12680 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12681 			} else {
12682 				BUMP_MIB(&ip_mib, ipIfStatsInCksumErrs);
12683 			}
12684 			freemsg(first_mp);
12685 			return (B_FALSE);
12686 		}
12687 	}
12688 
12689 	if (!ip_rput_local_options(q, mp, ipha, ire)) {
12690 		if (mctl_present)
12691 			freeb(first_mp);
12692 		return (B_FALSE);
12693 	}
12694 
12695 	return (B_TRUE);
12696 }
12697 
12698 /*
12699  * All udp packet are delivered to the local host via this routine.
12700  */
12701 void
12702 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12703     ill_t *recv_ill)
12704 {
12705 	uint32_t	sum;
12706 	uint32_t	u1;
12707 	boolean_t	mctl_present;
12708 	conn_t		*connp;
12709 	mblk_t		*first_mp;
12710 	uint16_t	*up;
12711 	ill_t		*ill = (ill_t *)q->q_ptr;
12712 	uint16_t	reass_hck_flags = 0;
12713 
12714 #define	rptr    ((uchar_t *)ipha)
12715 
12716 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12717 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12718 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12719 	ASSERT(ill != NULL);
12720 
12721 	/*
12722 	 * FAST PATH for udp packets
12723 	 */
12724 
12725 	/* u1 is # words of IP options */
12726 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12727 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12728 
12729 	/* IP options present */
12730 	if (u1 != 0)
12731 		goto ipoptions;
12732 
12733 	/* Check the IP header checksum.  */
12734 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12735 		/* Clear the IP header h/w cksum flag */
12736 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12737 	} else {
12738 #define	uph	((uint16_t *)ipha)
12739 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12740 		    uph[6] + uph[7] + uph[8] + uph[9];
12741 #undef	uph
12742 		/* finish doing IP checksum */
12743 		sum = (sum & 0xFFFF) + (sum >> 16);
12744 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12745 		/*
12746 		 * Don't verify header checksum if this packet is coming
12747 		 * back from AH/ESP as we already did it.
12748 		 */
12749 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12750 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12751 			freemsg(first_mp);
12752 			return;
12753 		}
12754 	}
12755 
12756 	/*
12757 	 * Count for SNMP of inbound packets for ire.
12758 	 * if mctl is present this might be a secure packet and
12759 	 * has already been counted for in ip_proto_input().
12760 	 */
12761 	if (!mctl_present) {
12762 		UPDATE_IB_PKT_COUNT(ire);
12763 		ire->ire_last_used_time = lbolt;
12764 	}
12765 
12766 	/* packet part of fragmented IP packet? */
12767 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12768 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12769 		goto fragmented;
12770 	}
12771 
12772 	/* u1 = IP header length (20 bytes) */
12773 	u1 = IP_SIMPLE_HDR_LENGTH;
12774 
12775 	/* packet does not contain complete IP & UDP headers */
12776 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12777 		goto udppullup;
12778 
12779 	/* up points to UDP header */
12780 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12781 #define	iphs    ((uint16_t *)ipha)
12782 
12783 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12784 	if (up[3] != 0) {
12785 		mblk_t *mp1 = mp->b_cont;
12786 		boolean_t cksum_err;
12787 		uint16_t hck_flags = 0;
12788 
12789 		/* Pseudo-header checksum */
12790 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12791 		    iphs[9] + up[2];
12792 
12793 		/*
12794 		 * Revert to software checksum calculation if the interface
12795 		 * isn't capable of checksum offload or if IPsec is present.
12796 		 */
12797 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12798 			hck_flags = DB_CKSUMFLAGS(mp);
12799 
12800 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12801 			IP_STAT(ip_in_sw_cksum);
12802 
12803 		IP_CKSUM_RECV(hck_flags, u1,
12804 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12805 		    (int32_t)((uchar_t *)up - rptr),
12806 		    mp, mp1, cksum_err);
12807 
12808 		if (cksum_err) {
12809 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12810 			if (hck_flags & HCK_FULLCKSUM)
12811 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12812 			else if (hck_flags & HCK_PARTIALCKSUM)
12813 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12814 			else
12815 				IP_STAT(ip_udp_in_sw_cksum_err);
12816 
12817 			freemsg(first_mp);
12818 			return;
12819 		}
12820 	}
12821 
12822 	/* Non-fragmented broadcast or multicast packet? */
12823 	if (ire->ire_type == IRE_BROADCAST)
12824 		goto udpslowpath;
12825 
12826 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12827 	    ire->ire_zoneid)) != NULL) {
12828 		ASSERT(connp->conn_upq != NULL);
12829 		IP_STAT(ip_udp_fast_path);
12830 
12831 		if (CONN_UDP_FLOWCTLD(connp)) {
12832 			freemsg(mp);
12833 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12834 		} else {
12835 			if (!mctl_present) {
12836 				BUMP_MIB(ill->ill_ip_mib,
12837 				    ipIfStatsHCInDelivers);
12838 			}
12839 			/*
12840 			 * mp and first_mp can change.
12841 			 */
12842 			if (ip_udp_check(q, connp, recv_ill,
12843 			    ipha, &mp, &first_mp, mctl_present)) {
12844 				/* Send it upstream */
12845 				CONN_UDP_RECV(connp, mp);
12846 			}
12847 		}
12848 		/*
12849 		 * freeb() cannot deal with null mblk being passed
12850 		 * in and first_mp can be set to null in the call
12851 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12852 		 */
12853 		if (mctl_present && first_mp != NULL) {
12854 			freeb(first_mp);
12855 		}
12856 		CONN_DEC_REF(connp);
12857 		return;
12858 	}
12859 
12860 	/*
12861 	 * if we got here we know the packet is not fragmented and
12862 	 * has no options. The classifier could not find a conn_t and
12863 	 * most likely its an icmp packet so send it through slow path.
12864 	 */
12865 
12866 	goto udpslowpath;
12867 
12868 ipoptions:
12869 	if (!ip_options_cksum(q, ill, mp, ipha, ire)) {
12870 		goto slow_done;
12871 	}
12872 
12873 	UPDATE_IB_PKT_COUNT(ire);
12874 	ire->ire_last_used_time = lbolt;
12875 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12876 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12877 fragmented:
12878 		/*
12879 		 * "sum" and "reass_hck_flags" are non-zero if the
12880 		 * reassembled packet has a valid hardware computed
12881 		 * checksum information associated with it.
12882 		 */
12883 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12884 			goto slow_done;
12885 		/*
12886 		 * Make sure that first_mp points back to mp as
12887 		 * the mp we came in with could have changed in
12888 		 * ip_rput_fragment().
12889 		 */
12890 		ASSERT(!mctl_present);
12891 		ipha = (ipha_t *)mp->b_rptr;
12892 		first_mp = mp;
12893 	}
12894 
12895 	/* Now we have a complete datagram, destined for this machine. */
12896 	u1 = IPH_HDR_LENGTH(ipha);
12897 	/* Pull up the UDP header, if necessary. */
12898 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12899 udppullup:
12900 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12901 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12902 			freemsg(first_mp);
12903 			goto slow_done;
12904 		}
12905 		ipha = (ipha_t *)mp->b_rptr;
12906 	}
12907 
12908 	/*
12909 	 * Validate the checksum for the reassembled packet; for the
12910 	 * pullup case we calculate the payload checksum in software.
12911 	 */
12912 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12913 	if (up[3] != 0) {
12914 		boolean_t cksum_err;
12915 
12916 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12917 			IP_STAT(ip_in_sw_cksum);
12918 
12919 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12920 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12921 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12922 		    iphs[9] + up[2], sum, cksum_err);
12923 
12924 		if (cksum_err) {
12925 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12926 
12927 			if (reass_hck_flags & HCK_FULLCKSUM)
12928 				IP_STAT(ip_udp_in_full_hw_cksum_err);
12929 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12930 				IP_STAT(ip_udp_in_part_hw_cksum_err);
12931 			else
12932 				IP_STAT(ip_udp_in_sw_cksum_err);
12933 
12934 			freemsg(first_mp);
12935 			goto slow_done;
12936 		}
12937 	}
12938 udpslowpath:
12939 
12940 	/* Clear hardware checksum flag to be safe */
12941 	DB_CKSUMFLAGS(mp) = 0;
12942 
12943 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12944 	    (ire->ire_type == IRE_BROADCAST),
12945 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12946 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12947 
12948 slow_done:
12949 	IP_STAT(ip_udp_slow_path);
12950 	return;
12951 
12952 #undef  iphs
12953 #undef  rptr
12954 }
12955 
12956 /* ARGSUSED */
12957 static mblk_t *
12958 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12959     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12960     ill_rx_ring_t *ill_ring)
12961 {
12962 	conn_t		*connp;
12963 	uint32_t	sum;
12964 	uint32_t	u1;
12965 	uint16_t	*up;
12966 	int		offset;
12967 	ssize_t		len;
12968 	mblk_t		*mp1;
12969 	boolean_t	syn_present = B_FALSE;
12970 	tcph_t		*tcph;
12971 	uint_t		ip_hdr_len;
12972 	ill_t		*ill = (ill_t *)q->q_ptr;
12973 	zoneid_t	zoneid = ire->ire_zoneid;
12974 	boolean_t	cksum_err;
12975 	uint16_t	hck_flags = 0;
12976 
12977 #define	rptr	((uchar_t *)ipha)
12978 
12979 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12980 	ASSERT(ill != NULL);
12981 
12982 	/*
12983 	 * FAST PATH for tcp packets
12984 	 */
12985 
12986 	/* u1 is # words of IP options */
12987 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12988 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12989 
12990 	/* IP options present */
12991 	if (u1) {
12992 		goto ipoptions;
12993 	} else {
12994 		/* Check the IP header checksum.  */
12995 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12996 			/* Clear the IP header h/w cksum flag */
12997 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12998 		} else {
12999 #define	uph	((uint16_t *)ipha)
13000 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13001 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13002 #undef	uph
13003 			/* finish doing IP checksum */
13004 			sum = (sum & 0xFFFF) + (sum >> 16);
13005 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13006 			/*
13007 			 * Don't verify header checksum if this packet
13008 			 * is coming back from AH/ESP as we already did it.
13009 			 */
13010 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13011 				BUMP_MIB(ill->ill_ip_mib,
13012 				    ipIfStatsInCksumErrs);
13013 				goto error;
13014 			}
13015 		}
13016 	}
13017 
13018 	if (!mctl_present) {
13019 		UPDATE_IB_PKT_COUNT(ire);
13020 		ire->ire_last_used_time = lbolt;
13021 	}
13022 
13023 	/* packet part of fragmented IP packet? */
13024 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13025 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13026 		goto fragmented;
13027 	}
13028 
13029 	/* u1 = IP header length (20 bytes) */
13030 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13031 
13032 	/* does packet contain IP+TCP headers? */
13033 	len = mp->b_wptr - rptr;
13034 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13035 		IP_STAT(ip_tcppullup);
13036 		goto tcppullup;
13037 	}
13038 
13039 	/* TCP options present? */
13040 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13041 
13042 	/*
13043 	 * If options need to be pulled up, then goto tcpoptions.
13044 	 * otherwise we are still in the fast path
13045 	 */
13046 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13047 		IP_STAT(ip_tcpoptions);
13048 		goto tcpoptions;
13049 	}
13050 
13051 	/* multiple mblks of tcp data? */
13052 	if ((mp1 = mp->b_cont) != NULL) {
13053 		/* more then two? */
13054 		if (mp1->b_cont != NULL) {
13055 			IP_STAT(ip_multipkttcp);
13056 			goto multipkttcp;
13057 		}
13058 		len += mp1->b_wptr - mp1->b_rptr;
13059 	}
13060 
13061 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13062 
13063 	/* part of pseudo checksum */
13064 
13065 	/* TCP datagram length */
13066 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13067 
13068 #define	iphs    ((uint16_t *)ipha)
13069 
13070 #ifdef	_BIG_ENDIAN
13071 	u1 += IPPROTO_TCP;
13072 #else
13073 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13074 #endif
13075 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13076 
13077 	/*
13078 	 * Revert to software checksum calculation if the interface
13079 	 * isn't capable of checksum offload or if IPsec is present.
13080 	 */
13081 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13082 		hck_flags = DB_CKSUMFLAGS(mp);
13083 
13084 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13085 		IP_STAT(ip_in_sw_cksum);
13086 
13087 	IP_CKSUM_RECV(hck_flags, u1,
13088 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13089 	    (int32_t)((uchar_t *)up - rptr),
13090 	    mp, mp1, cksum_err);
13091 
13092 	if (cksum_err) {
13093 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13094 
13095 		if (hck_flags & HCK_FULLCKSUM)
13096 			IP_STAT(ip_tcp_in_full_hw_cksum_err);
13097 		else if (hck_flags & HCK_PARTIALCKSUM)
13098 			IP_STAT(ip_tcp_in_part_hw_cksum_err);
13099 		else
13100 			IP_STAT(ip_tcp_in_sw_cksum_err);
13101 
13102 		goto error;
13103 	}
13104 
13105 try_again:
13106 
13107 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len, zoneid)) ==
13108 	    NULL) {
13109 		/* Send the TH_RST */
13110 		goto no_conn;
13111 	}
13112 
13113 	/*
13114 	 * TCP FAST PATH for AF_INET socket.
13115 	 *
13116 	 * TCP fast path to avoid extra work. An AF_INET socket type
13117 	 * does not have facility to receive extra information via
13118 	 * ip_process or ip_add_info. Also, when the connection was
13119 	 * established, we made a check if this connection is impacted
13120 	 * by any global IPSec policy or per connection policy (a
13121 	 * policy that comes in effect later will not apply to this
13122 	 * connection). Since all this can be determined at the
13123 	 * connection establishment time, a quick check of flags
13124 	 * can avoid extra work.
13125 	 */
13126 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13127 	    !IPP_ENABLED(IPP_LOCAL_IN)) {
13128 		ASSERT(first_mp == mp);
13129 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13130 		SET_SQUEUE(mp, tcp_rput_data, connp);
13131 		return (mp);
13132 	}
13133 
13134 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13135 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13136 		if (IPCL_IS_TCP(connp)) {
13137 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13138 			DB_CKSUMSTART(mp) =
13139 			    (intptr_t)ip_squeue_get(ill_ring);
13140 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13141 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
13142 				BUMP_MIB(ill->ill_ip_mib,
13143 				    ipIfStatsHCInDelivers);
13144 				SET_SQUEUE(mp, connp->conn_recv, connp);
13145 				return (mp);
13146 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13147 			    !CONN_INBOUND_POLICY_PRESENT(connp)) {
13148 				BUMP_MIB(ill->ill_ip_mib,
13149 				    ipIfStatsHCInDelivers);
13150 				ip_squeue_enter_unbound++;
13151 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13152 				    connp);
13153 				return (mp);
13154 			}
13155 			syn_present = B_TRUE;
13156 		}
13157 
13158 	}
13159 
13160 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13161 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13162 
13163 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13164 		/* No need to send this packet to TCP */
13165 		if ((flags & TH_RST) || (flags & TH_URG)) {
13166 			CONN_DEC_REF(connp);
13167 			freemsg(first_mp);
13168 			return (NULL);
13169 		}
13170 		if (flags & TH_ACK) {
13171 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid);
13172 			CONN_DEC_REF(connp);
13173 			return (NULL);
13174 		}
13175 
13176 		CONN_DEC_REF(connp);
13177 		freemsg(first_mp);
13178 		return (NULL);
13179 	}
13180 
13181 	if (CONN_INBOUND_POLICY_PRESENT(connp) || mctl_present) {
13182 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13183 		    ipha, NULL, mctl_present);
13184 		if (first_mp == NULL) {
13185 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13186 			CONN_DEC_REF(connp);
13187 			return (NULL);
13188 		}
13189 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13190 			ASSERT(syn_present);
13191 			if (mctl_present) {
13192 				ASSERT(first_mp != mp);
13193 				first_mp->b_datap->db_struioflag |=
13194 				    STRUIO_POLICY;
13195 			} else {
13196 				ASSERT(first_mp == mp);
13197 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13198 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13199 			}
13200 		} else {
13201 			/*
13202 			 * Discard first_mp early since we're dealing with a
13203 			 * fully-connected conn_t and tcp doesn't do policy in
13204 			 * this case.
13205 			 */
13206 			if (mctl_present) {
13207 				freeb(first_mp);
13208 				mctl_present = B_FALSE;
13209 			}
13210 			first_mp = mp;
13211 		}
13212 	}
13213 
13214 	/* Initiate IPPF processing for fastpath */
13215 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13216 		uint32_t	ill_index;
13217 
13218 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13219 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13220 		if (mp == NULL) {
13221 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13222 			    "deferred/dropped during IPPF processing\n"));
13223 			CONN_DEC_REF(connp);
13224 			if (mctl_present)
13225 				freeb(first_mp);
13226 			return (NULL);
13227 		} else if (mctl_present) {
13228 			/*
13229 			 * ip_process might return a new mp.
13230 			 */
13231 			ASSERT(first_mp != mp);
13232 			first_mp->b_cont = mp;
13233 		} else {
13234 			first_mp = mp;
13235 		}
13236 
13237 	}
13238 
13239 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13240 		/*
13241 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13242 		 * make sure IPF_RECVIF is passed to ip_add_info.
13243 		 */
13244 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13245 		    IPCL_ZONEID(connp));
13246 		if (mp == NULL) {
13247 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13248 			CONN_DEC_REF(connp);
13249 			if (mctl_present)
13250 				freeb(first_mp);
13251 			return (NULL);
13252 		} else if (mctl_present) {
13253 			/*
13254 			 * ip_add_info might return a new mp.
13255 			 */
13256 			ASSERT(first_mp != mp);
13257 			first_mp->b_cont = mp;
13258 		} else {
13259 			first_mp = mp;
13260 		}
13261 	}
13262 
13263 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13264 	if (IPCL_IS_TCP(connp)) {
13265 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13266 		return (first_mp);
13267 	} else {
13268 		putnext(connp->conn_rq, first_mp);
13269 		CONN_DEC_REF(connp);
13270 		return (NULL);
13271 	}
13272 
13273 no_conn:
13274 	/* Initiate IPPf processing, if needed. */
13275 	if (IPP_ENABLED(IPP_LOCAL_IN)) {
13276 		uint32_t ill_index;
13277 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13278 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13279 		if (first_mp == NULL) {
13280 			return (NULL);
13281 		}
13282 	}
13283 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13284 
13285 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid);
13286 	return (NULL);
13287 ipoptions:
13288 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire)) {
13289 		goto slow_done;
13290 	}
13291 
13292 	UPDATE_IB_PKT_COUNT(ire);
13293 	ire->ire_last_used_time = lbolt;
13294 
13295 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13296 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13297 fragmented:
13298 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13299 			if (mctl_present)
13300 				freeb(first_mp);
13301 			goto slow_done;
13302 		}
13303 		/*
13304 		 * Make sure that first_mp points back to mp as
13305 		 * the mp we came in with could have changed in
13306 		 * ip_rput_fragment().
13307 		 */
13308 		ASSERT(!mctl_present);
13309 		ipha = (ipha_t *)mp->b_rptr;
13310 		first_mp = mp;
13311 	}
13312 
13313 	/* Now we have a complete datagram, destined for this machine. */
13314 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13315 
13316 	len = mp->b_wptr - mp->b_rptr;
13317 	/* Pull up a minimal TCP header, if necessary. */
13318 	if (len < (u1 + 20)) {
13319 tcppullup:
13320 		if (!pullupmsg(mp, u1 + 20)) {
13321 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13322 			goto error;
13323 		}
13324 		ipha = (ipha_t *)mp->b_rptr;
13325 		len = mp->b_wptr - mp->b_rptr;
13326 	}
13327 
13328 	/*
13329 	 * Extract the offset field from the TCP header.  As usual, we
13330 	 * try to help the compiler more than the reader.
13331 	 */
13332 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13333 	if (offset != 5) {
13334 tcpoptions:
13335 		if (offset < 5) {
13336 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13337 			goto error;
13338 		}
13339 		/*
13340 		 * There must be TCP options.
13341 		 * Make sure we can grab them.
13342 		 */
13343 		offset <<= 2;
13344 		offset += u1;
13345 		if (len < offset) {
13346 			if (!pullupmsg(mp, offset)) {
13347 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13348 				goto error;
13349 			}
13350 			ipha = (ipha_t *)mp->b_rptr;
13351 			len = mp->b_wptr - rptr;
13352 		}
13353 	}
13354 
13355 	/* Get the total packet length in len, including headers. */
13356 	if (mp->b_cont) {
13357 multipkttcp:
13358 		len = msgdsize(mp);
13359 	}
13360 
13361 	/*
13362 	 * Check the TCP checksum by pulling together the pseudo-
13363 	 * header checksum, and passing it to ip_csum to be added in
13364 	 * with the TCP datagram.
13365 	 *
13366 	 * Since we are not using the hwcksum if available we must
13367 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13368 	 * If either of these fails along the way the mblk is freed.
13369 	 * If this logic ever changes and mblk is reused to say send
13370 	 * ICMP's back, then this flag may need to be cleared in
13371 	 * other places as well.
13372 	 */
13373 	DB_CKSUMFLAGS(mp) = 0;
13374 
13375 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13376 
13377 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13378 #ifdef	_BIG_ENDIAN
13379 	u1 += IPPROTO_TCP;
13380 #else
13381 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13382 #endif
13383 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13384 	/*
13385 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13386 	 */
13387 	IP_STAT(ip_in_sw_cksum);
13388 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13389 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13390 		goto error;
13391 	}
13392 
13393 	IP_STAT(ip_tcp_slow_path);
13394 	goto try_again;
13395 #undef  iphs
13396 #undef  rptr
13397 
13398 error:
13399 	freemsg(first_mp);
13400 slow_done:
13401 	return (NULL);
13402 }
13403 
13404 /* ARGSUSED */
13405 static void
13406 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13407     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13408 {
13409 	conn_t		*connp;
13410 	uint32_t	sum;
13411 	uint32_t	u1;
13412 	ssize_t		len;
13413 	sctp_hdr_t	*sctph;
13414 	zoneid_t	zoneid = ire->ire_zoneid;
13415 	uint32_t	pktsum;
13416 	uint32_t	calcsum;
13417 	uint32_t	ports;
13418 	uint_t		ipif_seqid;
13419 	in6_addr_t	map_src, map_dst;
13420 	ill_t		*ill = (ill_t *)q->q_ptr;
13421 
13422 #define	rptr	((uchar_t *)ipha)
13423 
13424 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13425 	ASSERT(ill != NULL);
13426 
13427 	/* u1 is # words of IP options */
13428 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13429 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13430 
13431 	/* IP options present */
13432 	if (u1 > 0) {
13433 		goto ipoptions;
13434 	} else {
13435 		/* Check the IP header checksum.  */
13436 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13437 #define	uph	((uint16_t *)ipha)
13438 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13439 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13440 #undef	uph
13441 			/* finish doing IP checksum */
13442 			sum = (sum & 0xFFFF) + (sum >> 16);
13443 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13444 			/*
13445 			 * Don't verify header checksum if this packet
13446 			 * is coming back from AH/ESP as we already did it.
13447 			 */
13448 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13449 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13450 				goto error;
13451 			}
13452 		}
13453 		/*
13454 		 * Since there is no SCTP h/w cksum support yet, just
13455 		 * clear the flag.
13456 		 */
13457 		DB_CKSUMFLAGS(mp) = 0;
13458 	}
13459 
13460 	/*
13461 	 * Don't verify header checksum if this packet is coming
13462 	 * back from AH/ESP as we already did it.
13463 	 */
13464 	if (!mctl_present) {
13465 		UPDATE_IB_PKT_COUNT(ire);
13466 		ire->ire_last_used_time = lbolt;
13467 	}
13468 
13469 	/* packet part of fragmented IP packet? */
13470 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13471 	if (u1 & (IPH_MF | IPH_OFFSET))
13472 		goto fragmented;
13473 
13474 	/* u1 = IP header length (20 bytes) */
13475 	u1 = IP_SIMPLE_HDR_LENGTH;
13476 
13477 find_sctp_client:
13478 	/* Pullup if we don't have the sctp common header. */
13479 	len = MBLKL(mp);
13480 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13481 		if (mp->b_cont == NULL ||
13482 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13483 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13484 			goto error;
13485 		}
13486 		ipha = (ipha_t *)mp->b_rptr;
13487 		len = MBLKL(mp);
13488 	}
13489 
13490 	sctph = (sctp_hdr_t *)(rptr + u1);
13491 #ifdef	DEBUG
13492 	if (!skip_sctp_cksum) {
13493 #endif
13494 		pktsum = sctph->sh_chksum;
13495 		sctph->sh_chksum = 0;
13496 		calcsum = sctp_cksum(mp, u1);
13497 		if (calcsum != pktsum) {
13498 			BUMP_MIB(&sctp_mib, sctpChecksumError);
13499 			goto error;
13500 		}
13501 		sctph->sh_chksum = pktsum;
13502 #ifdef	DEBUG	/* skip_sctp_cksum */
13503 	}
13504 #endif
13505 	/* get the ports */
13506 	ports = *(uint32_t *)&sctph->sh_sport;
13507 
13508 	ipif_seqid = ire->ire_ipif->ipif_seqid;
13509 	IRE_REFRELE(ire);
13510 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13511 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13512 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, ipif_seqid, zoneid,
13513 	    mp)) == NULL) {
13514 		/* Check for raw socket or OOTB handling */
13515 		goto no_conn;
13516 	}
13517 
13518 	/* Found a client; up it goes */
13519 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13520 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13521 	return;
13522 
13523 no_conn:
13524 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13525 	    ports, mctl_present, flags, B_TRUE, ipif_seqid, zoneid);
13526 	return;
13527 
13528 ipoptions:
13529 	DB_CKSUMFLAGS(mp) = 0;
13530 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire))
13531 		goto slow_done;
13532 
13533 	UPDATE_IB_PKT_COUNT(ire);
13534 	ire->ire_last_used_time = lbolt;
13535 
13536 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13537 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13538 fragmented:
13539 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13540 			goto slow_done;
13541 		/*
13542 		 * Make sure that first_mp points back to mp as
13543 		 * the mp we came in with could have changed in
13544 		 * ip_rput_fragment().
13545 		 */
13546 		ASSERT(!mctl_present);
13547 		ipha = (ipha_t *)mp->b_rptr;
13548 		first_mp = mp;
13549 	}
13550 
13551 	/* Now we have a complete datagram, destined for this machine. */
13552 	u1 = IPH_HDR_LENGTH(ipha);
13553 	goto find_sctp_client;
13554 #undef  iphs
13555 #undef  rptr
13556 
13557 error:
13558 	freemsg(first_mp);
13559 slow_done:
13560 	IRE_REFRELE(ire);
13561 }
13562 
13563 #define	VER_BITS	0xF0
13564 #define	VERSION_6	0x60
13565 
13566 static boolean_t
13567 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13568     ipaddr_t *dstp)
13569 {
13570 	uint_t	opt_len;
13571 	ipha_t *ipha;
13572 	ssize_t len;
13573 	uint_t	pkt_len;
13574 
13575 	ASSERT(ill != NULL);
13576 	IP_STAT(ip_ipoptions);
13577 	ipha = *iphapp;
13578 
13579 #define	rptr    ((uchar_t *)ipha)
13580 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13581 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13582 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13583 		freemsg(mp);
13584 		return (B_FALSE);
13585 	}
13586 
13587 	/* multiple mblk or too short */
13588 	pkt_len = ntohs(ipha->ipha_length);
13589 
13590 	/* Get the number of words of IP options in the IP header. */
13591 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13592 	if (opt_len) {
13593 		/* IP Options present!  Validate and process. */
13594 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13595 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13596 			goto done;
13597 		}
13598 		/*
13599 		 * Recompute complete header length and make sure we
13600 		 * have access to all of it.
13601 		 */
13602 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13603 		if (len > (mp->b_wptr - rptr)) {
13604 			if (len > pkt_len) {
13605 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13606 				goto done;
13607 			}
13608 			if (!pullupmsg(mp, len)) {
13609 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13610 				goto done;
13611 			}
13612 			ipha = (ipha_t *)mp->b_rptr;
13613 		}
13614 		/*
13615 		 * Go off to ip_rput_options which returns the next hop
13616 		 * destination address, which may have been affected
13617 		 * by source routing.
13618 		 */
13619 		IP_STAT(ip_opt);
13620 		if (ip_rput_options(q, mp, ipha, dstp) == -1) {
13621 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13622 			return (B_FALSE);
13623 		}
13624 	}
13625 	*iphapp = ipha;
13626 	return (B_TRUE);
13627 done:
13628 	/* clear b_prev - used by ip_mroute_decap */
13629 	mp->b_prev = NULL;
13630 	freemsg(mp);
13631 	return (B_FALSE);
13632 #undef  rptr
13633 }
13634 
13635 /*
13636  * Deal with the fact that there is no ire for the destination.
13637  * The incoming ill (in_ill) is passed in to ip_newroute only
13638  * in the case of packets coming from mobile ip forward tunnel.
13639  * It must be null otherwise.
13640  */
13641 static ire_t *
13642 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13643     ipaddr_t dst)
13644 {
13645 	ipha_t	*ipha;
13646 	ill_t	*ill;
13647 	ire_t	*ire;
13648 	boolean_t	check_multirt = B_FALSE;
13649 
13650 	ipha = (ipha_t *)mp->b_rptr;
13651 	ill = (ill_t *)q->q_ptr;
13652 
13653 	ASSERT(ill != NULL);
13654 	/*
13655 	 * No IRE for this destination, so it can't be for us.
13656 	 * Unless we are forwarding, drop the packet.
13657 	 * We have to let source routed packets through
13658 	 * since we don't yet know if they are 'ping -l'
13659 	 * packets i.e. if they will go out over the
13660 	 * same interface as they came in on.
13661 	 */
13662 	if (ll_multicast) {
13663 		freemsg(mp);
13664 		return (NULL);
13665 	}
13666 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha)) {
13667 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13668 		freemsg(mp);
13669 		return (NULL);
13670 	}
13671 
13672 	/*
13673 	 * Mark this packet as having originated externally.
13674 	 *
13675 	 * For non-forwarding code path, ire_send later double
13676 	 * checks this interface to see if it is still exists
13677 	 * post-ARP resolution.
13678 	 *
13679 	 * Also, IPQOS uses this to differentiate between
13680 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13681 	 * QOS packet processing in ip_wput_attach_llhdr().
13682 	 * The QoS module can mark the b_band for a fastpath message
13683 	 * or the dl_priority field in a unitdata_req header for
13684 	 * CoS marking. This info can only be found in
13685 	 * ip_wput_attach_llhdr().
13686 	 */
13687 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13688 	/*
13689 	 * Clear the indication that this may have a hardware checksum
13690 	 * as we are not using it
13691 	 */
13692 	DB_CKSUMFLAGS(mp) = 0;
13693 
13694 	if (in_ill != NULL) {
13695 		/*
13696 		 * Now hand the packet to ip_newroute.
13697 		 */
13698 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13699 		return (NULL);
13700 	}
13701 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13702 	    MBLK_GETLABEL(mp));
13703 
13704 	if (ire == NULL && check_multirt) {
13705 		/* Let ip_newroute handle CGTP  */
13706 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID);
13707 		return (NULL);
13708 	}
13709 
13710 	if (ire != NULL)
13711 		return (ire);
13712 
13713 	mp->b_prev = mp->b_next = 0;
13714 	/* send icmp unreachable */
13715 	q = WR(q);
13716 	/* Sent by forwarding path, and router is global zone */
13717 	if (ip_source_routed(ipha)) {
13718 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13719 		    GLOBAL_ZONEID);
13720 	} else {
13721 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13722 	}
13723 
13724 	return (NULL);
13725 
13726 }
13727 
13728 /*
13729  * check ip header length and align it.
13730  */
13731 static boolean_t
13732 ip_check_and_align_header(queue_t *q, mblk_t *mp)
13733 {
13734 	ssize_t len;
13735 	ill_t *ill;
13736 	ipha_t	*ipha;
13737 
13738 	len = MBLKL(mp);
13739 
13740 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13741 		ill = (ill_t *)q->q_ptr;
13742 
13743 		if (!OK_32PTR(mp->b_rptr))
13744 			IP_STAT(ip_notaligned1);
13745 		else
13746 			IP_STAT(ip_notaligned2);
13747 		/* Guard against bogus device drivers */
13748 		if (len < 0) {
13749 			/* clear b_prev - used by ip_mroute_decap */
13750 			mp->b_prev = NULL;
13751 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13752 			freemsg(mp);
13753 			return (B_FALSE);
13754 		}
13755 
13756 		if (ip_rput_pullups++ == 0) {
13757 			ipha = (ipha_t *)mp->b_rptr;
13758 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13759 			    "ip_check_and_align_header: %s forced us to "
13760 			    " pullup pkt, hdr len %ld, hdr addr %p",
13761 			    ill->ill_name, len, ipha);
13762 		}
13763 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13764 			/* clear b_prev - used by ip_mroute_decap */
13765 			mp->b_prev = NULL;
13766 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13767 			freemsg(mp);
13768 			return (B_FALSE);
13769 		}
13770 	}
13771 	return (B_TRUE);
13772 }
13773 
13774 static boolean_t
13775 ip_rput_notforus(queue_t **qp, mblk_t *mp, ire_t *ire, ill_t *ill)
13776 {
13777 	ill_group_t	*ill_group;
13778 	ill_group_t	*ire_group;
13779 	queue_t 	*q;
13780 	ill_t		*ire_ill;
13781 	uint_t		ill_ifindex;
13782 
13783 	q = *qp;
13784 	/*
13785 	 * We need to check to make sure the packet came in
13786 	 * on the queue associated with the destination IRE.
13787 	 * Note that for multicast packets and broadcast packets sent to
13788 	 * a broadcast address which is shared between multiple interfaces
13789 	 * we should not do this since we just got a random broadcast ire.
13790 	 */
13791 	if (ire->ire_rfq && ire->ire_type != IRE_BROADCAST) {
13792 		boolean_t check_multi = B_TRUE;
13793 
13794 		/*
13795 		 * This packet came in on an interface other than the
13796 		 * one associated with the destination address.
13797 		 * "Gateway" it to the appropriate interface here.
13798 		 * As long as the ills belong to the same group,
13799 		 * we don't consider them to arriving on the wrong
13800 		 * interface. Thus, when the switch is doing inbound
13801 		 * load spreading, we won't drop packets when we
13802 		 * are doing strict multihoming checks. Note, the
13803 		 * same holds true for 'usesrc groups' where the
13804 		 * destination address may belong to another interface
13805 		 * to allow multipathing to happen
13806 		 */
13807 		ill_group = ill->ill_group;
13808 		ire_ill = (ill_t *)(ire->ire_rfq)->q_ptr;
13809 		ill_ifindex = ill->ill_usesrc_ifindex;
13810 		ire_group = ire_ill->ill_group;
13811 
13812 		/*
13813 		 * If it's part of the same IPMP group, or if it's a legal
13814 		 * address on the 'usesrc' interface, then bypass strict
13815 		 * checks.
13816 		 */
13817 		if (ill_group != NULL && ill_group == ire_group) {
13818 			check_multi = B_FALSE;
13819 		} else if (ill_ifindex != 0 &&
13820 		    ill_ifindex == ire_ill->ill_phyint->phyint_ifindex) {
13821 			check_multi = B_FALSE;
13822 		}
13823 
13824 		if (check_multi &&
13825 		    ip_strict_dst_multihoming &&
13826 		    ((ill->ill_flags &
13827 		    ire->ire_ipif->ipif_ill->ill_flags &
13828 		    ILLF_ROUTER) == 0)) {
13829 			/* Drop packet */
13830 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13831 			freemsg(mp);
13832 			return (B_TRUE);
13833 		}
13834 
13835 		/*
13836 		 * Change the queue (for non-virtual destination network
13837 		 * interfaces) and ip_rput_local will be called with the right
13838 		 * queue
13839 		 */
13840 		q = ire->ire_rfq;
13841 	}
13842 	/* Must be broadcast.  We'll take it. */
13843 	*qp = q;
13844 	return (B_FALSE);
13845 }
13846 
13847 ire_t *
13848 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13849 {
13850 	ipha_t	*ipha;
13851 	ipaddr_t ip_dst, ip_src;
13852 	ire_t	*src_ire = NULL;
13853 	ill_t	*stq_ill;
13854 	uint_t	hlen;
13855 	uint_t	pkt_len;
13856 	uint32_t sum;
13857 	queue_t	*dev_q;
13858 	boolean_t check_multirt = B_FALSE;
13859 
13860 
13861 	ipha = (ipha_t *)mp->b_rptr;
13862 
13863 	/*
13864 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13865 	 * The loopback address check for both src and dst has already
13866 	 * been checked in ip_input
13867 	 */
13868 	ip_dst = ntohl(dst);
13869 	ip_src = ntohl(ipha->ipha_src);
13870 
13871 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13872 	    IN_CLASSD(ip_src)) {
13873 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13874 		goto drop;
13875 	}
13876 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13877 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
13878 
13879 	if (src_ire != NULL) {
13880 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13881 		goto drop;
13882 	}
13883 
13884 
13885 	/* No ire cache of nexthop. So first create one  */
13886 	if (ire == NULL) {
13887 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL);
13888 		/*
13889 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13890 		 * is not set. So upon return from ire_forward
13891 		 * check_multirt should remain as false.
13892 		 */
13893 		ASSERT(!check_multirt);
13894 		if (ire == NULL) {
13895 			/* An attempt was made to forward the packet */
13896 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13897 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13898 			mp->b_prev = mp->b_next = 0;
13899 			/* send icmp unreachable */
13900 			/* Sent by forwarding path, and router is global zone */
13901 			if (ip_source_routed(ipha)) {
13902 				icmp_unreachable(ill->ill_wq, mp,
13903 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
13904 			} else {
13905 				icmp_unreachable(ill->ill_wq, mp,
13906 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID);
13907 			}
13908 			return (ire);
13909 		}
13910 	}
13911 
13912 	/*
13913 	 * Forwarding fastpath exception case:
13914 	 * If either of the follwoing case is true, we take
13915 	 * the slowpath
13916 	 *	o forwarding is not enabled
13917 	 *	o incoming and outgoing interface are the same, or the same
13918 	 *	  IPMP group
13919 	 *	o corresponding ire is in incomplete state
13920 	 *	o packet needs fragmentation
13921 	 *
13922 	 * The codeflow from here on is thus:
13923 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13924 	 */
13925 	pkt_len = ntohs(ipha->ipha_length);
13926 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13927 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13928 	    !(ill->ill_flags & ILLF_ROUTER) ||
13929 	    (ill == stq_ill) ||
13930 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13931 	    (ire->ire_nce == NULL) ||
13932 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13933 	    (pkt_len > ire->ire_max_frag) ||
13934 	    ipha->ipha_ttl <= 1) {
13935 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13936 		    ipha, ill, B_FALSE);
13937 		return (ire);
13938 	}
13939 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13940 
13941 	DTRACE_PROBE4(ip4__forwarding__start,
13942 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13943 
13944 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
13945 	    ill, stq_ill, ipha, mp, mp);
13946 
13947 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13948 
13949 	if (mp == NULL)
13950 		goto drop;
13951 
13952 	mp->b_datap->db_struioun.cksum.flags = 0;
13953 	/* Adjust the checksum to reflect the ttl decrement. */
13954 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13955 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13956 	ipha->ipha_ttl--;
13957 
13958 	dev_q = ire->ire_stq->q_next;
13959 	if ((dev_q->q_next != NULL ||
13960 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13961 		goto indiscard;
13962 	}
13963 
13964 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13965 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13966 
13967 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13968 		mblk_t *mpip = mp;
13969 
13970 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13971 		if (mp != NULL) {
13972 			DTRACE_PROBE4(ip4__physical__out__start,
13973 			    ill_t *, NULL, ill_t *, stq_ill,
13974 			    ipha_t *, ipha, mblk_t *, mp);
13975 			FW_HOOKS(ip4_physical_out_event,
13976 			    ipv4firewall_physical_out,
13977 			    NULL, stq_ill, ipha, mp, mpip);
13978 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13979 			    mp);
13980 			if (mp == NULL)
13981 				goto drop;
13982 
13983 			UPDATE_IB_PKT_COUNT(ire);
13984 			ire->ire_last_used_time = lbolt;
13985 			BUMP_MIB(stq_ill->ill_ip_mib,
13986 			    ipIfStatsHCOutForwDatagrams);
13987 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13988 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
13989 			    pkt_len);
13990 			putnext(ire->ire_stq, mp);
13991 			return (ire);
13992 		}
13993 	}
13994 
13995 indiscard:
13996 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13997 drop:
13998 	if (mp != NULL)
13999 		freemsg(mp);
14000 	if (src_ire != NULL)
14001 		ire_refrele(src_ire);
14002 	return (ire);
14003 
14004 }
14005 
14006 /*
14007  * This function is called in the forwarding slowpath, when
14008  * either the ire lacks the link-layer address, or the packet needs
14009  * further processing(eg. fragmentation), before transmission.
14010  */
14011 
14012 static void
14013 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14014     ill_t *ill, boolean_t ll_multicast)
14015 {
14016 	ill_group_t	*ill_group;
14017 	ill_group_t	*ire_group;
14018 	queue_t		*dev_q;
14019 	ire_t		*src_ire;
14020 
14021 	ASSERT(ire->ire_stq != NULL);
14022 
14023 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14024 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14025 
14026 	if (ll_multicast != 0) {
14027 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14028 		goto drop_pkt;
14029 	}
14030 
14031 	/*
14032 	 * check if ipha_src is a broadcast address. Note that this
14033 	 * check is redundant when we get here from ip_fast_forward()
14034 	 * which has already done this check. However, since we can
14035 	 * also get here from ip_rput_process_broadcast() or, for
14036 	 * for the slow path through ip_fast_forward(), we perform
14037 	 * the check again for code-reusability
14038 	 */
14039 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14040 	    ALL_ZONES, NULL, MATCH_IRE_TYPE);
14041 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14042 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14043 		if (src_ire != NULL)
14044 			ire_refrele(src_ire);
14045 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14046 		ip2dbg(("ip_rput_process_forward: Received packet with"
14047 		    " bad src/dst address on %s\n", ill->ill_name));
14048 		goto drop_pkt;
14049 	}
14050 
14051 	ill_group = ill->ill_group;
14052 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14053 	/*
14054 	 * Check if we want to forward this one at this time.
14055 	 * We allow source routed packets on a host provided that
14056 	 * they go out the same interface or same interface group
14057 	 * as they came in on.
14058 	 *
14059 	 * XXX To be quicker, we may wish to not chase pointers to
14060 	 * get the ILLF_ROUTER flag and instead store the
14061 	 * forwarding policy in the ire.  An unfortunate
14062 	 * side-effect of that would be requiring an ire flush
14063 	 * whenever the ILLF_ROUTER flag changes.
14064 	 */
14065 	if (((ill->ill_flags &
14066 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14067 	    ILLF_ROUTER) == 0) &&
14068 	    !(ip_source_routed(ipha) && (ire->ire_rfq == q ||
14069 	    (ill_group != NULL && ill_group == ire_group)))) {
14070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14071 		if (ip_source_routed(ipha)) {
14072 			q = WR(q);
14073 			/*
14074 			 * Clear the indication that this may have
14075 			 * hardware checksum as we are not using it.
14076 			 */
14077 			DB_CKSUMFLAGS(mp) = 0;
14078 			/* Sent by forwarding path, and router is global zone */
14079 			icmp_unreachable(q, mp,
14080 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID);
14081 			return;
14082 		}
14083 		goto drop_pkt;
14084 	}
14085 
14086 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14087 
14088 	/* Packet is being forwarded. Turning off hwcksum flag. */
14089 	DB_CKSUMFLAGS(mp) = 0;
14090 	if (ip_g_send_redirects) {
14091 		/*
14092 		 * Check whether the incoming interface and outgoing
14093 		 * interface is part of the same group. If so,
14094 		 * send redirects.
14095 		 *
14096 		 * Check the source address to see if it originated
14097 		 * on the same logical subnet it is going back out on.
14098 		 * If so, we should be able to send it a redirect.
14099 		 * Avoid sending a redirect if the destination
14100 		 * is directly connected (i.e., ipha_dst is the same
14101 		 * as ire_gateway_addr or the ire_addr of the
14102 		 * nexthop IRE_CACHE ), or if the packet was source
14103 		 * routed out this interface.
14104 		 */
14105 		ipaddr_t src, nhop;
14106 		mblk_t	*mp1;
14107 		ire_t	*nhop_ire = NULL;
14108 
14109 		/*
14110 		 * Check whether ire_rfq and q are from the same ill
14111 		 * or if they are not same, they at least belong
14112 		 * to the same group. If so, send redirects.
14113 		 */
14114 		if ((ire->ire_rfq == q ||
14115 		    (ill_group != NULL && ill_group == ire_group)) &&
14116 		    !ip_source_routed(ipha)) {
14117 
14118 			nhop = (ire->ire_gateway_addr != 0 ?
14119 			    ire->ire_gateway_addr : ire->ire_addr);
14120 
14121 			if (ipha->ipha_dst == nhop) {
14122 				/*
14123 				 * We avoid sending a redirect if the
14124 				 * destination is directly connected
14125 				 * because it is possible that multiple
14126 				 * IP subnets may have been configured on
14127 				 * the link, and the source may not
14128 				 * be on the same subnet as ip destination,
14129 				 * even though they are on the same
14130 				 * physical link.
14131 				 */
14132 				goto sendit;
14133 			}
14134 
14135 			src = ipha->ipha_src;
14136 
14137 			/*
14138 			 * We look up the interface ire for the nexthop,
14139 			 * to see if ipha_src is in the same subnet
14140 			 * as the nexthop.
14141 			 *
14142 			 * Note that, if, in the future, IRE_CACHE entries
14143 			 * are obsoleted,  this lookup will not be needed,
14144 			 * as the ire passed to this function will be the
14145 			 * same as the nhop_ire computed below.
14146 			 */
14147 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14148 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14149 			    0, NULL, MATCH_IRE_TYPE);
14150 
14151 			if (nhop_ire != NULL) {
14152 				if ((src & nhop_ire->ire_mask) ==
14153 				    (nhop & nhop_ire->ire_mask)) {
14154 					/*
14155 					 * The source is directly connected.
14156 					 * Just copy the ip header (which is
14157 					 * in the first mblk)
14158 					 */
14159 					mp1 = copyb(mp);
14160 					if (mp1 != NULL) {
14161 						icmp_send_redirect(WR(q), mp1,
14162 						    nhop);
14163 					}
14164 				}
14165 				ire_refrele(nhop_ire);
14166 			}
14167 		}
14168 	}
14169 sendit:
14170 	dev_q = ire->ire_stq->q_next;
14171 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14172 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14173 		freemsg(mp);
14174 		return;
14175 	}
14176 
14177 	ip_rput_forward(ire, ipha, mp, ill);
14178 	return;
14179 
14180 drop_pkt:
14181 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14182 	freemsg(mp);
14183 }
14184 
14185 ire_t *
14186 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14187     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14188 {
14189 	queue_t		*q;
14190 	uint16_t	hcksumflags;
14191 
14192 	q = *qp;
14193 
14194 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14195 
14196 	/*
14197 	 * Clear the indication that this may have hardware
14198 	 * checksum as we are not using it for forwarding.
14199 	 */
14200 	hcksumflags = DB_CKSUMFLAGS(mp);
14201 	DB_CKSUMFLAGS(mp) = 0;
14202 
14203 	/*
14204 	 * Directed broadcast forwarding: if the packet came in over a
14205 	 * different interface then it is routed out over we can forward it.
14206 	 */
14207 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14208 		ire_refrele(ire);
14209 		freemsg(mp);
14210 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14211 		return (NULL);
14212 	}
14213 	/*
14214 	 * For multicast we have set dst to be INADDR_BROADCAST
14215 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14216 	 * only for broadcast packets.
14217 	 */
14218 	if (!CLASSD(ipha->ipha_dst)) {
14219 		ire_t *new_ire;
14220 		ipif_t *ipif;
14221 		/*
14222 		 * For ill groups, as the switch duplicates broadcasts
14223 		 * across all the ports, we need to filter out and
14224 		 * send up only one copy. There is one copy for every
14225 		 * broadcast address on each ill. Thus, we look for a
14226 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14227 		 * later to see whether this ill is eligible to receive
14228 		 * them or not. ill_nominate_bcast_rcv() nominates only
14229 		 * one set of IREs for receiving.
14230 		 */
14231 
14232 		ipif = ipif_get_next_ipif(NULL, ill);
14233 		if (ipif == NULL) {
14234 			ire_refrele(ire);
14235 			freemsg(mp);
14236 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14237 			return (NULL);
14238 		}
14239 		new_ire = ire_ctable_lookup(dst, 0, 0,
14240 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL);
14241 		ipif_refrele(ipif);
14242 
14243 		if (new_ire != NULL) {
14244 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14245 				ire_refrele(ire);
14246 				ire_refrele(new_ire);
14247 				freemsg(mp);
14248 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14249 				return (NULL);
14250 			}
14251 			/*
14252 			 * In the special case of multirouted broadcast
14253 			 * packets, we unconditionally need to "gateway"
14254 			 * them to the appropriate interface here.
14255 			 * In the normal case, this cannot happen, because
14256 			 * there is no broadcast IRE tagged with the
14257 			 * RTF_MULTIRT flag.
14258 			 */
14259 			if (new_ire->ire_flags & RTF_MULTIRT) {
14260 				ire_refrele(new_ire);
14261 				if (ire->ire_rfq != NULL) {
14262 					q = ire->ire_rfq;
14263 					*qp = q;
14264 				}
14265 			} else {
14266 				ire_refrele(ire);
14267 				ire = new_ire;
14268 			}
14269 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14270 			if (!ip_g_forward_directed_bcast) {
14271 				/*
14272 				 * Free the message if
14273 				 * ip_g_forward_directed_bcast is turned
14274 				 * off for non-local broadcast.
14275 				 */
14276 				ire_refrele(ire);
14277 				freemsg(mp);
14278 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14279 				return (NULL);
14280 			}
14281 		} else {
14282 			/*
14283 			 * This CGTP packet successfully passed the
14284 			 * CGTP filter, but the related CGTP
14285 			 * broadcast IRE has not been found,
14286 			 * meaning that the redundant ipif is
14287 			 * probably down. However, if we discarded
14288 			 * this packet, its duplicate would be
14289 			 * filtered out by the CGTP filter so none
14290 			 * of them would get through. So we keep
14291 			 * going with this one.
14292 			 */
14293 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14294 			if (ire->ire_rfq != NULL) {
14295 				q = ire->ire_rfq;
14296 				*qp = q;
14297 			}
14298 		}
14299 	}
14300 	if (ip_g_forward_directed_bcast && ll_multicast == 0) {
14301 		/*
14302 		 * Verify that there are not more then one
14303 		 * IRE_BROADCAST with this broadcast address which
14304 		 * has ire_stq set.
14305 		 * TODO: simplify, loop over all IRE's
14306 		 */
14307 		ire_t	*ire1;
14308 		int	num_stq = 0;
14309 		mblk_t	*mp1;
14310 
14311 		/* Find the first one with ire_stq set */
14312 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14313 		for (ire1 = ire; ire1 &&
14314 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14315 		    ire1 = ire1->ire_next)
14316 			;
14317 		if (ire1) {
14318 			ire_refrele(ire);
14319 			ire = ire1;
14320 			IRE_REFHOLD(ire);
14321 		}
14322 
14323 		/* Check if there are additional ones with stq set */
14324 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14325 			if (ire->ire_addr != ire1->ire_addr)
14326 				break;
14327 			if (ire1->ire_stq) {
14328 				num_stq++;
14329 				break;
14330 			}
14331 		}
14332 		rw_exit(&ire->ire_bucket->irb_lock);
14333 		if (num_stq == 1 && ire->ire_stq != NULL) {
14334 			ip1dbg(("ip_rput_process_broadcast: directed "
14335 			    "broadcast to 0x%x\n",
14336 			    ntohl(ire->ire_addr)));
14337 			mp1 = copymsg(mp);
14338 			if (mp1) {
14339 				switch (ipha->ipha_protocol) {
14340 				case IPPROTO_UDP:
14341 					ip_udp_input(q, mp1, ipha, ire, ill);
14342 					break;
14343 				default:
14344 					ip_proto_input(q, mp1, ipha, ire, ill);
14345 					break;
14346 				}
14347 			}
14348 			/*
14349 			 * Adjust ttl to 2 (1+1 - the forward engine
14350 			 * will decrement it by one.
14351 			 */
14352 			if (ip_csum_hdr(ipha)) {
14353 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14354 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14355 				freemsg(mp);
14356 				ire_refrele(ire);
14357 				return (NULL);
14358 			}
14359 			ipha->ipha_ttl = ip_broadcast_ttl + 1;
14360 			ipha->ipha_hdr_checksum = 0;
14361 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14362 			ip_rput_process_forward(q, mp, ire, ipha,
14363 			    ill, ll_multicast);
14364 			ire_refrele(ire);
14365 			return (NULL);
14366 		}
14367 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14368 		    ntohl(ire->ire_addr)));
14369 	}
14370 
14371 
14372 	/* Restore any hardware checksum flags */
14373 	DB_CKSUMFLAGS(mp) = hcksumflags;
14374 	return (ire);
14375 }
14376 
14377 /* ARGSUSED */
14378 static boolean_t
14379 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14380     int *ll_multicast, ipaddr_t *dstp)
14381 {
14382 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14383 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14384 	    ntohs(ipha->ipha_length));
14385 
14386 	/*
14387 	 * Forward packets only if we have joined the allmulti
14388 	 * group on this interface.
14389 	 */
14390 	if (ip_g_mrouter && ill->ill_join_allmulti) {
14391 		int retval;
14392 
14393 		/*
14394 		 * Clear the indication that this may have hardware
14395 		 * checksum as we are not using it.
14396 		 */
14397 		DB_CKSUMFLAGS(mp) = 0;
14398 		retval = ip_mforward(ill, ipha, mp);
14399 		/* ip_mforward updates mib variables if needed */
14400 		/* clear b_prev - used by ip_mroute_decap */
14401 		mp->b_prev = NULL;
14402 
14403 		switch (retval) {
14404 		case 0:
14405 			/*
14406 			 * pkt is okay and arrived on phyint.
14407 			 *
14408 			 * If we are running as a multicast router
14409 			 * we need to see all IGMP and/or PIM packets.
14410 			 */
14411 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14412 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14413 				goto done;
14414 			}
14415 			break;
14416 		case -1:
14417 			/* pkt is mal-formed, toss it */
14418 			goto drop_pkt;
14419 		case 1:
14420 			/* pkt is okay and arrived on a tunnel */
14421 			/*
14422 			 * If we are running a multicast router
14423 			 *  we need to see all igmp packets.
14424 			 */
14425 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14426 				*dstp = INADDR_BROADCAST;
14427 				*ll_multicast = 1;
14428 				return (B_FALSE);
14429 			}
14430 
14431 			goto drop_pkt;
14432 		}
14433 	}
14434 
14435 	ILM_WALKER_HOLD(ill);
14436 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14437 		/*
14438 		 * This might just be caused by the fact that
14439 		 * multiple IP Multicast addresses map to the same
14440 		 * link layer multicast - no need to increment counter!
14441 		 */
14442 		ILM_WALKER_RELE(ill);
14443 		freemsg(mp);
14444 		return (B_TRUE);
14445 	}
14446 	ILM_WALKER_RELE(ill);
14447 done:
14448 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14449 	/*
14450 	 * This assumes the we deliver to all streams for multicast
14451 	 * and broadcast packets.
14452 	 */
14453 	*dstp = INADDR_BROADCAST;
14454 	*ll_multicast = 1;
14455 	return (B_FALSE);
14456 drop_pkt:
14457 	ip2dbg(("ip_rput: drop pkt\n"));
14458 	freemsg(mp);
14459 	return (B_TRUE);
14460 }
14461 
14462 static boolean_t
14463 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14464     int *ll_multicast, mblk_t **mpp)
14465 {
14466 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14467 	boolean_t must_copy = B_FALSE;
14468 	struct iocblk   *iocp;
14469 	ipha_t		*ipha;
14470 
14471 #define	rptr    ((uchar_t *)ipha)
14472 
14473 	first_mp = *first_mpp;
14474 	mp = *mpp;
14475 
14476 	ASSERT(first_mp == mp);
14477 
14478 	/*
14479 	 * if db_ref > 1 then copymsg and free original. Packet may be
14480 	 * changed and do not want other entity who has a reference to this
14481 	 * message to trip over the changes. This is a blind change because
14482 	 * trying to catch all places that might change packet is too
14483 	 * difficult (since it may be a module above this one)
14484 	 *
14485 	 * This corresponds to the non-fast path case. We walk down the full
14486 	 * chain in this case, and check the db_ref count of all the dblks,
14487 	 * and do a copymsg if required. It is possible that the db_ref counts
14488 	 * of the data blocks in the mblk chain can be different.
14489 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14490 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14491 	 * 'snoop' is running.
14492 	 */
14493 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14494 		if (mp1->b_datap->db_ref > 1) {
14495 			must_copy = B_TRUE;
14496 			break;
14497 		}
14498 	}
14499 
14500 	if (must_copy) {
14501 		mp1 = copymsg(mp);
14502 		if (mp1 == NULL) {
14503 			for (mp1 = mp; mp1 != NULL;
14504 			    mp1 = mp1->b_cont) {
14505 				mp1->b_next = NULL;
14506 				mp1->b_prev = NULL;
14507 			}
14508 			freemsg(mp);
14509 			if (ill != NULL) {
14510 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14511 			} else {
14512 				BUMP_MIB(&ip_mib, ipIfStatsInDiscards);
14513 			}
14514 			return (B_TRUE);
14515 		}
14516 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14517 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14518 			/* Copy b_prev - used by ip_mroute_decap */
14519 			to_mp->b_prev = from_mp->b_prev;
14520 			from_mp->b_prev = NULL;
14521 		}
14522 		*first_mpp = first_mp = mp1;
14523 		freemsg(mp);
14524 		mp = mp1;
14525 		*mpp = mp1;
14526 	}
14527 
14528 	ipha = (ipha_t *)mp->b_rptr;
14529 
14530 	/*
14531 	 * previous code has a case for M_DATA.
14532 	 * We want to check how that happens.
14533 	 */
14534 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14535 	switch (first_mp->b_datap->db_type) {
14536 	case M_PROTO:
14537 	case M_PCPROTO:
14538 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14539 		    DL_UNITDATA_IND) {
14540 			/* Go handle anything other than data elsewhere. */
14541 			ip_rput_dlpi(q, mp);
14542 			return (B_TRUE);
14543 		}
14544 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14545 		/* Ditch the DLPI header. */
14546 		mp1 = mp->b_cont;
14547 		ASSERT(first_mp == mp);
14548 		*first_mpp = mp1;
14549 		freeb(mp);
14550 		*mpp = mp1;
14551 		return (B_FALSE);
14552 	case M_IOCACK:
14553 		ip1dbg(("got iocack "));
14554 		iocp = (struct iocblk *)mp->b_rptr;
14555 		switch (iocp->ioc_cmd) {
14556 		case DL_IOC_HDR_INFO:
14557 			ill = (ill_t *)q->q_ptr;
14558 			ill_fastpath_ack(ill, mp);
14559 			return (B_TRUE);
14560 		case SIOCSTUNPARAM:
14561 		case OSIOCSTUNPARAM:
14562 			/* Go through qwriter_ip */
14563 			break;
14564 		case SIOCGTUNPARAM:
14565 		case OSIOCGTUNPARAM:
14566 			ip_rput_other(NULL, q, mp, NULL);
14567 			return (B_TRUE);
14568 		default:
14569 			putnext(q, mp);
14570 			return (B_TRUE);
14571 		}
14572 		/* FALLTHRU */
14573 	case M_ERROR:
14574 	case M_HANGUP:
14575 		/*
14576 		 * Since this is on the ill stream we unconditionally
14577 		 * bump up the refcount
14578 		 */
14579 		ill_refhold(ill);
14580 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14581 		    B_FALSE);
14582 		return (B_TRUE);
14583 	case M_CTL:
14584 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14585 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14586 			IPHADA_M_CTL)) {
14587 			/*
14588 			 * It's an IPsec accelerated packet.
14589 			 * Make sure that the ill from which we received the
14590 			 * packet has enabled IPsec hardware acceleration.
14591 			 */
14592 			if (!(ill->ill_capabilities &
14593 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14594 				/* IPsec kstats: bean counter */
14595 				freemsg(mp);
14596 				return (B_TRUE);
14597 			}
14598 
14599 			/*
14600 			 * Make mp point to the mblk following the M_CTL,
14601 			 * then process according to type of mp.
14602 			 * After this processing, first_mp will point to
14603 			 * the data-attributes and mp to the pkt following
14604 			 * the M_CTL.
14605 			 */
14606 			mp = first_mp->b_cont;
14607 			if (mp == NULL) {
14608 				freemsg(first_mp);
14609 				return (B_TRUE);
14610 			}
14611 			/*
14612 			 * A Hardware Accelerated packet can only be M_DATA
14613 			 * ESP or AH packet.
14614 			 */
14615 			if (mp->b_datap->db_type != M_DATA) {
14616 				/* non-M_DATA IPsec accelerated packet */
14617 				IPSECHW_DEBUG(IPSECHW_PKT,
14618 				    ("non-M_DATA IPsec accelerated pkt\n"));
14619 				freemsg(first_mp);
14620 				return (B_TRUE);
14621 			}
14622 			ipha = (ipha_t *)mp->b_rptr;
14623 			if (ipha->ipha_protocol != IPPROTO_AH &&
14624 			    ipha->ipha_protocol != IPPROTO_ESP) {
14625 				IPSECHW_DEBUG(IPSECHW_PKT,
14626 				    ("non-M_DATA IPsec accelerated pkt\n"));
14627 				freemsg(first_mp);
14628 				return (B_TRUE);
14629 			}
14630 			*mpp = mp;
14631 			return (B_FALSE);
14632 		}
14633 		putnext(q, mp);
14634 		return (B_TRUE);
14635 	case M_FLUSH:
14636 		if (*mp->b_rptr & FLUSHW) {
14637 			*mp->b_rptr &= ~FLUSHR;
14638 			qreply(q, mp);
14639 			return (B_TRUE);
14640 		}
14641 		freemsg(mp);
14642 		return (B_TRUE);
14643 	case M_IOCNAK:
14644 		ip1dbg(("got iocnak "));
14645 		iocp = (struct iocblk *)mp->b_rptr;
14646 		switch (iocp->ioc_cmd) {
14647 		case DL_IOC_HDR_INFO:
14648 		case SIOCSTUNPARAM:
14649 		case OSIOCSTUNPARAM:
14650 			/*
14651 			 * Since this is on the ill stream we unconditionally
14652 			 * bump up the refcount
14653 			 */
14654 			ill_refhold(ill);
14655 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14656 			    CUR_OP, B_FALSE);
14657 			return (B_TRUE);
14658 		case SIOCGTUNPARAM:
14659 		case OSIOCGTUNPARAM:
14660 			ip_rput_other(NULL, q, mp, NULL);
14661 			return (B_TRUE);
14662 		default:
14663 			break;
14664 		}
14665 		/* FALLTHRU */
14666 	default:
14667 		putnext(q, mp);
14668 		return (B_TRUE);
14669 	}
14670 }
14671 
14672 /* Read side put procedure.  Packets coming from the wire arrive here. */
14673 void
14674 ip_rput(queue_t *q, mblk_t *mp)
14675 {
14676 	ill_t	*ill;
14677 	mblk_t	 *dmp = NULL;
14678 
14679 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14680 
14681 	ill = (ill_t *)q->q_ptr;
14682 
14683 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14684 		union DL_primitives *dl;
14685 
14686 		/*
14687 		 * Things are opening or closing. Only accept DLPI control
14688 		 * messages. In the open case, the ill->ill_ipif has not yet
14689 		 * been created. In the close case, things hanging off the
14690 		 * ill could have been freed already. In either case it
14691 		 * may not be safe to proceed further.
14692 		 */
14693 
14694 		dl = (union DL_primitives *)mp->b_rptr;
14695 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14696 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14697 			/*
14698 			 * Also SIOC[GS]TUN* ioctls can come here.
14699 			 */
14700 			inet_freemsg(mp);
14701 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14702 			    "ip_input_end: q %p (%S)", q, "uninit");
14703 			return;
14704 		}
14705 	}
14706 
14707 	/*
14708 	 * if db_ref > 1 then copymsg and free original. Packet may be
14709 	 * changed and we do not want the other entity who has a reference to
14710 	 * this message to trip over the changes. This is a blind change because
14711 	 * trying to catch all places that might change the packet is too
14712 	 * difficult.
14713 	 *
14714 	 * This corresponds to the fast path case, where we have a chain of
14715 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14716 	 * in the mblk chain. There doesn't seem to be a reason why a device
14717 	 * driver would send up data with varying db_ref counts in the mblk
14718 	 * chain. In any case the Fast path is a private interface, and our
14719 	 * drivers don't do such a thing. Given the above assumption, there is
14720 	 * no need to walk down the entire mblk chain (which could have a
14721 	 * potential performance problem)
14722 	 */
14723 	if (mp->b_datap->db_ref > 1) {
14724 		mblk_t  *mp1;
14725 		boolean_t adjusted = B_FALSE;
14726 		IP_STAT(ip_db_ref);
14727 
14728 		/*
14729 		 * The IP_RECVSLLA option depends on having the link layer
14730 		 * header. First check that:
14731 		 * a> the underlying device is of type ether, since this
14732 		 * option is currently supported only over ethernet.
14733 		 * b> there is enough room to copy over the link layer header.
14734 		 *
14735 		 * Once the checks are done, adjust rptr so that the link layer
14736 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14737 		 * be returned by some non-ethernet drivers but in this case the
14738 		 * second check will fail.
14739 		 */
14740 		if (ill->ill_type == IFT_ETHER &&
14741 		    (mp->b_rptr - mp->b_datap->db_base) >=
14742 		    sizeof (struct ether_header)) {
14743 			mp->b_rptr -= sizeof (struct ether_header);
14744 			adjusted = B_TRUE;
14745 		}
14746 		mp1 = copymsg(mp);
14747 		if (mp1 == NULL) {
14748 			mp->b_next = NULL;
14749 			/* clear b_prev - used by ip_mroute_decap */
14750 			mp->b_prev = NULL;
14751 			freemsg(mp);
14752 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14753 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14754 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14755 			return;
14756 		}
14757 		if (adjusted) {
14758 			/*
14759 			 * Copy is done. Restore the pointer in the _new_ mblk
14760 			 */
14761 			mp1->b_rptr += sizeof (struct ether_header);
14762 		}
14763 		/* Copy b_prev - used by ip_mroute_decap */
14764 		mp1->b_prev = mp->b_prev;
14765 		mp->b_prev = NULL;
14766 		freemsg(mp);
14767 		mp = mp1;
14768 	}
14769 	if (DB_TYPE(mp) == M_DATA) {
14770 		dmp = mp;
14771 	} else if (DB_TYPE(mp) == M_PROTO &&
14772 	    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14773 		dmp = mp->b_cont;
14774 	}
14775 	if (dmp != NULL) {
14776 		/*
14777 		 * IP header ptr not aligned?
14778 		 * OR IP header not complete in first mblk
14779 		 */
14780 		if (!OK_32PTR(dmp->b_rptr) ||
14781 		    (dmp->b_wptr - dmp->b_rptr) < IP_SIMPLE_HDR_LENGTH) {
14782 			if (!ip_check_and_align_header(q, dmp))
14783 				return;
14784 		}
14785 	}
14786 
14787 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14788 	    "ip_rput_end: q %p (%S)", q, "end");
14789 
14790 	ip_input(ill, NULL, mp, NULL);
14791 }
14792 
14793 /*
14794  * Direct read side procedure capable of dealing with chains. GLDv3 based
14795  * drivers call this function directly with mblk chains while STREAMS
14796  * read side procedure ip_rput() calls this for single packet with ip_ring
14797  * set to NULL to process one packet at a time.
14798  *
14799  * The ill will always be valid if this function is called directly from
14800  * the driver.
14801  *
14802  * If ip_input() is called from GLDv3:
14803  *
14804  *   - This must be a non-VLAN IP stream.
14805  *   - 'mp' is either an untagged or a special priority-tagged packet.
14806  *   - Any VLAN tag that was in the MAC header has been stripped.
14807  *
14808  * Thus, there is no need to adjust b_rptr in this function.
14809  */
14810 /* ARGSUSED */
14811 void
14812 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14813     struct mac_header_info_s *mhip)
14814 {
14815 	ipaddr_t		dst = NULL;
14816 	ipaddr_t		prev_dst;
14817 	ire_t			*ire = NULL;
14818 	ipha_t			*ipha;
14819 	uint_t			pkt_len;
14820 	ssize_t			len;
14821 	uint_t			opt_len;
14822 	int			ll_multicast;
14823 	int			cgtp_flt_pkt;
14824 	queue_t			*q = ill->ill_rq;
14825 	squeue_t		*curr_sqp = NULL;
14826 	mblk_t 			*head = NULL;
14827 	mblk_t			*tail = NULL;
14828 	mblk_t			*first_mp;
14829 	mblk_t 			*mp;
14830 	int			cnt = 0;
14831 
14832 	ASSERT(mp_chain != NULL);
14833 	ASSERT(ill != NULL);
14834 
14835 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14836 
14837 #define	rptr	((uchar_t *)ipha)
14838 
14839 	while (mp_chain != NULL) {
14840 		first_mp = mp = mp_chain;
14841 		mp_chain = mp_chain->b_next;
14842 		mp->b_next = NULL;
14843 		ll_multicast = 0;
14844 
14845 		/*
14846 		 * We do ire caching from one iteration to
14847 		 * another. In the event the packet chain contains
14848 		 * all packets from the same dst, this caching saves
14849 		 * an ire_cache_lookup for each of the succeeding
14850 		 * packets in a packet chain.
14851 		 */
14852 		prev_dst = dst;
14853 
14854 		/*
14855 		 * ip_input fast path
14856 		 */
14857 
14858 		/* mblk type is not M_DATA */
14859 		if (mp->b_datap->db_type != M_DATA) {
14860 			if (ip_rput_process_notdata(q, &first_mp, ill,
14861 			    &ll_multicast, &mp))
14862 				continue;
14863 		}
14864 
14865 		/* Make sure its an M_DATA and that its aligned */
14866 		ASSERT(mp->b_datap->db_type == M_DATA);
14867 		ASSERT(mp->b_datap->db_ref == 1 && OK_32PTR(mp->b_rptr));
14868 
14869 		ipha = (ipha_t *)mp->b_rptr;
14870 		len = mp->b_wptr - rptr;
14871 		pkt_len = ntohs(ipha->ipha_length);
14872 
14873 		/*
14874 		 * We must count all incoming packets, even if they end
14875 		 * up being dropped later on.
14876 		 */
14877 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14878 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14879 
14880 		/* multiple mblk or too short */
14881 		len -= pkt_len;
14882 		if (len != 0) {
14883 			/*
14884 			 * Make sure we have data length consistent
14885 			 * with the IP header.
14886 			 */
14887 			if (mp->b_cont == NULL) {
14888 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14889 					BUMP_MIB(ill->ill_ip_mib,
14890 					    ipIfStatsInHdrErrors);
14891 					ip2dbg(("ip_input: drop pkt\n"));
14892 					freemsg(mp);
14893 					continue;
14894 				}
14895 				mp->b_wptr = rptr + pkt_len;
14896 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14897 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14898 					BUMP_MIB(ill->ill_ip_mib,
14899 					    ipIfStatsInHdrErrors);
14900 					ip2dbg(("ip_input: drop pkt\n"));
14901 					freemsg(mp);
14902 					continue;
14903 				}
14904 				(void) adjmsg(mp, -len);
14905 				IP_STAT(ip_multimblk3);
14906 			}
14907 		}
14908 
14909 		/* Obtain the dst of the current packet */
14910 		dst = ipha->ipha_dst;
14911 
14912 		if (IP_LOOPBACK_ADDR(dst) ||
14913 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14914 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14915 			cmn_err(CE_CONT, "dst %X src %X\n",
14916 			    dst, ipha->ipha_src);
14917 			freemsg(mp);
14918 			continue;
14919 		}
14920 
14921 		/*
14922 		 * The event for packets being received from a 'physical'
14923 		 * interface is placed after validation of the source and/or
14924 		 * destination address as being local so that packets can be
14925 		 * redirected to loopback addresses using ipnat.
14926 		 */
14927 		DTRACE_PROBE4(ip4__physical__in__start,
14928 		    ill_t *, ill, ill_t *, NULL,
14929 		    ipha_t *, ipha, mblk_t *, first_mp);
14930 
14931 		FW_HOOKS(ip4_physical_in_event, ipv4firewall_physical_in,
14932 		    ill, NULL, ipha, first_mp, mp);
14933 
14934 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14935 
14936 		if (first_mp == NULL) {
14937 			continue;
14938 		}
14939 		dst = ipha->ipha_dst;
14940 
14941 		/*
14942 		 * Attach any necessary label information to
14943 		 * this packet
14944 		 */
14945 		if (is_system_labeled() &&
14946 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14947 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14948 			freemsg(mp);
14949 			continue;
14950 		}
14951 
14952 		/*
14953 		 * Reuse the cached ire only if the ipha_dst of the previous
14954 		 * packet is the same as the current packet AND it is not
14955 		 * INADDR_ANY.
14956 		 */
14957 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14958 		    (ire != NULL)) {
14959 			ire_refrele(ire);
14960 			ire = NULL;
14961 		}
14962 		opt_len = ipha->ipha_version_and_hdr_length -
14963 		    IP_SIMPLE_HDR_VERSION;
14964 
14965 		/*
14966 		 * Check to see if we can take the fastpath.
14967 		 * That is possible if the following conditions are met
14968 		 *	o Tsol disabled
14969 		 *	o CGTP disabled
14970 		 *	o ipp_action_count is 0
14971 		 *	o Mobile IP not running
14972 		 *	o no options in the packet
14973 		 *	o not a RSVP packet
14974 		 * 	o not a multicast packet
14975 		 */
14976 		if (!is_system_labeled() &&
14977 		    !ip_cgtp_filter && ipp_action_count == 0 &&
14978 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
14979 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14980 		    !ll_multicast && !CLASSD(dst)) {
14981 			if (ire == NULL)
14982 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL);
14983 
14984 			/* incoming packet is for forwarding */
14985 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14986 				ire = ip_fast_forward(ire, dst, ill, mp);
14987 				continue;
14988 			}
14989 			/* incoming packet is for local consumption */
14990 			if (ire->ire_type & IRE_LOCAL)
14991 				goto local;
14992 		}
14993 
14994 		/*
14995 		 * Disable ire caching for anything more complex
14996 		 * than the simple fast path case we checked for above.
14997 		 */
14998 		if (ire != NULL) {
14999 			ire_refrele(ire);
15000 			ire = NULL;
15001 		}
15002 
15003 		/* Full-blown slow path */
15004 		if (opt_len != 0) {
15005 			if (len != 0)
15006 				IP_STAT(ip_multimblk4);
15007 			else
15008 				IP_STAT(ip_ipoptions);
15009 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15010 			    &dst))
15011 				continue;
15012 		}
15013 
15014 		/*
15015 		 * Invoke the CGTP (multirouting) filtering module to process
15016 		 * the incoming packet. Packets identified as duplicates
15017 		 * must be discarded. Filtering is active only if the
15018 		 * the ip_cgtp_filter ndd variable is non-zero.
15019 		 */
15020 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15021 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL)) {
15022 			cgtp_flt_pkt =
15023 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15024 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15025 				freemsg(first_mp);
15026 				continue;
15027 			}
15028 		}
15029 
15030 		/*
15031 		 * If rsvpd is running, let RSVP daemon handle its processing
15032 		 * and forwarding of RSVP multicast/unicast packets.
15033 		 * If rsvpd is not running but mrouted is running, RSVP
15034 		 * multicast packets are forwarded as multicast traffic
15035 		 * and RSVP unicast packets are forwarded by unicast router.
15036 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15037 		 * packets are not forwarded, but the unicast packets are
15038 		 * forwarded like unicast traffic.
15039 		 */
15040 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15041 		    ipcl_proto_search(IPPROTO_RSVP) != NULL) {
15042 			/* RSVP packet and rsvpd running. Treat as ours */
15043 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15044 			/*
15045 			 * This assumes that we deliver to all streams for
15046 			 * multicast and broadcast packets.
15047 			 * We have to force ll_multicast to 1 to handle the
15048 			 * M_DATA messages passed in from ip_mroute_decap.
15049 			 */
15050 			dst = INADDR_BROADCAST;
15051 			ll_multicast = 1;
15052 		} else if (CLASSD(dst)) {
15053 			/* packet is multicast */
15054 			mp->b_next = NULL;
15055 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15056 			    &ll_multicast, &dst))
15057 				continue;
15058 		}
15059 
15060 
15061 		/*
15062 		 * Check if the packet is coming from the Mobile IP
15063 		 * forward tunnel interface
15064 		 */
15065 		if (ill->ill_srcif_refcnt > 0) {
15066 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15067 			    NULL, ill, MATCH_IRE_TYPE);
15068 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15069 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15070 
15071 				/* We need to resolve the link layer info */
15072 				ire_refrele(ire);
15073 				ire = NULL;
15074 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15075 				    ll_multicast, dst);
15076 				continue;
15077 			}
15078 		}
15079 
15080 		if (ire == NULL) {
15081 			ire = ire_cache_lookup(dst, ALL_ZONES,
15082 			    MBLK_GETLABEL(mp));
15083 		}
15084 
15085 		/*
15086 		 * If mipagent is running and reverse tunnel is created as per
15087 		 * mobile node request, then any packet coming through the
15088 		 * incoming interface from the mobile-node, should be reverse
15089 		 * tunneled to it's home agent except those that are destined
15090 		 * to foreign agent only.
15091 		 * This needs source address based ire lookup. The routing
15092 		 * entries for source address based lookup are only created by
15093 		 * mipagent program only when a reverse tunnel is created.
15094 		 * Reference : RFC2002, RFC2344
15095 		 */
15096 		if (ill->ill_mrtun_refcnt > 0) {
15097 			ipaddr_t	srcaddr;
15098 			ire_t		*tmp_ire;
15099 
15100 			tmp_ire = ire;	/* Save, we might need it later */
15101 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15102 			    ire->ire_type != IRE_BROADCAST)) {
15103 				srcaddr = ipha->ipha_src;
15104 				ire = ire_mrtun_lookup(srcaddr, ill);
15105 				if (ire != NULL) {
15106 					/*
15107 					 * Should not be getting iphada packet
15108 					 * here. we should only get those for
15109 					 * IRE_LOCAL traffic, excluded above.
15110 					 * Fail-safe (drop packet) in the event
15111 					 * hardware is misbehaving.
15112 					 */
15113 					if (first_mp != mp) {
15114 						/* IPsec KSTATS: beancount me */
15115 						freemsg(first_mp);
15116 					} else {
15117 						/*
15118 						 * This packet must be forwarded
15119 						 * to Reverse Tunnel
15120 						 */
15121 						ip_mrtun_forward(ire, ill, mp);
15122 					}
15123 					ire_refrele(ire);
15124 					ire = NULL;
15125 					if (tmp_ire != NULL) {
15126 						ire_refrele(tmp_ire);
15127 						tmp_ire = NULL;
15128 					}
15129 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15130 					    "ip_input_end: q %p (%S)",
15131 					    q, "uninit");
15132 					continue;
15133 				}
15134 			}
15135 			/*
15136 			 * If this packet is from a non-mobilenode  or a
15137 			 * mobile-node which does not request reverse
15138 			 * tunnel service
15139 			 */
15140 			ire = tmp_ire;
15141 		}
15142 
15143 
15144 		/*
15145 		 * If we reach here that means the incoming packet satisfies
15146 		 * one of the following conditions:
15147 		 *   - packet is from a mobile node which does not request
15148 		 *	reverse tunnel
15149 		 *   - packet is from a non-mobile node, which is the most
15150 		 *	common case
15151 		 *   - packet is from a reverse tunnel enabled mobile node
15152 		 *	and destined to foreign agent only
15153 		 */
15154 
15155 		if (ire == NULL) {
15156 			/*
15157 			 * No IRE for this destination, so it can't be for us.
15158 			 * Unless we are forwarding, drop the packet.
15159 			 * We have to let source routed packets through
15160 			 * since we don't yet know if they are 'ping -l'
15161 			 * packets i.e. if they will go out over the
15162 			 * same interface as they came in on.
15163 			 */
15164 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15165 			if (ire == NULL)
15166 				continue;
15167 		}
15168 
15169 		/*
15170 		 * Broadcast IRE may indicate either broadcast or
15171 		 * multicast packet
15172 		 */
15173 		if (ire->ire_type == IRE_BROADCAST) {
15174 			/*
15175 			 * Skip broadcast checks if packet is UDP multicast;
15176 			 * we'd rather not enter ip_rput_process_broadcast()
15177 			 * unless the packet is broadcast for real, since
15178 			 * that routine is a no-op for multicast.
15179 			 */
15180 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15181 			    !CLASSD(ipha->ipha_dst)) {
15182 				ire = ip_rput_process_broadcast(&q, mp,
15183 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15184 				    ll_multicast);
15185 				if (ire == NULL)
15186 					continue;
15187 			}
15188 		} else if (ire->ire_stq != NULL) {
15189 			/* fowarding? */
15190 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15191 			    ll_multicast);
15192 			/* ip_rput_process_forward consumed the packet */
15193 			continue;
15194 		}
15195 
15196 local:
15197 		/* packet not for us */
15198 		if (ire->ire_rfq != q) {
15199 			if (ip_rput_notforus(&q, mp, ire, ill))
15200 				continue;
15201 		}
15202 
15203 		switch (ipha->ipha_protocol) {
15204 		case IPPROTO_TCP:
15205 			ASSERT(first_mp == mp);
15206 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15207 				mp, 0, q, ip_ring)) != NULL) {
15208 				if (curr_sqp == NULL) {
15209 					curr_sqp = GET_SQUEUE(mp);
15210 					ASSERT(cnt == 0);
15211 					cnt++;
15212 					head = tail = mp;
15213 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15214 					ASSERT(tail != NULL);
15215 					cnt++;
15216 					tail->b_next = mp;
15217 					tail = mp;
15218 				} else {
15219 					/*
15220 					 * A different squeue. Send the
15221 					 * chain for the previous squeue on
15222 					 * its way. This shouldn't happen
15223 					 * often unless interrupt binding
15224 					 * changes.
15225 					 */
15226 					IP_STAT(ip_input_multi_squeue);
15227 					squeue_enter_chain(curr_sqp, head,
15228 					    tail, cnt, SQTAG_IP_INPUT);
15229 					curr_sqp = GET_SQUEUE(mp);
15230 					head = mp;
15231 					tail = mp;
15232 					cnt = 1;
15233 				}
15234 			}
15235 			continue;
15236 		case IPPROTO_UDP:
15237 			ASSERT(first_mp == mp);
15238 			ip_udp_input(q, mp, ipha, ire, ill);
15239 			continue;
15240 		case IPPROTO_SCTP:
15241 			ASSERT(first_mp == mp);
15242 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15243 			    q, dst);
15244 			/* ire has been released by ip_sctp_input */
15245 			ire = NULL;
15246 			continue;
15247 		default:
15248 			ip_proto_input(q, first_mp, ipha, ire, ill);
15249 			continue;
15250 		}
15251 	}
15252 
15253 	if (ire != NULL)
15254 		ire_refrele(ire);
15255 
15256 	if (head != NULL)
15257 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15258 
15259 	/*
15260 	 * This code is there just to make netperf/ttcp look good.
15261 	 *
15262 	 * Its possible that after being in polling mode (and having cleared
15263 	 * the backlog), squeues have turned the interrupt frequency higher
15264 	 * to improve latency at the expense of more CPU utilization (less
15265 	 * packets per interrupts or more number of interrupts). Workloads
15266 	 * like ttcp/netperf do manage to tickle polling once in a while
15267 	 * but for the remaining time, stay in higher interrupt mode since
15268 	 * their packet arrival rate is pretty uniform and this shows up
15269 	 * as higher CPU utilization. Since people care about CPU utilization
15270 	 * while running netperf/ttcp, turn the interrupt frequency back to
15271 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15272 	 */
15273 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15274 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15275 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15276 			ip_ring->rr_blank(ip_ring->rr_handle,
15277 			    ip_ring->rr_normal_blank_time,
15278 			    ip_ring->rr_normal_pkt_cnt);
15279 		}
15280 	}
15281 
15282 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15283 	    "ip_input_end: q %p (%S)", q, "end");
15284 #undef	rptr
15285 }
15286 
15287 static void
15288 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15289     t_uscalar_t err)
15290 {
15291 	if (dl_err == DL_SYSERR) {
15292 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15293 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15294 		    ill->ill_name, dlpi_prim_str(prim), err);
15295 		return;
15296 	}
15297 
15298 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15299 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15300 	    dlpi_err_str(dl_err));
15301 }
15302 
15303 /*
15304  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15305  * than DL_UNITDATA_IND messages. If we need to process this message
15306  * exclusively, we call qwriter_ip, in which case we also need to call
15307  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15308  */
15309 void
15310 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15311 {
15312 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15313 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15314 	ill_t		*ill;
15315 
15316 	ip1dbg(("ip_rput_dlpi"));
15317 	ill = (ill_t *)q->q_ptr;
15318 	switch (dloa->dl_primitive) {
15319 	case DL_ERROR_ACK:
15320 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15321 		    "%s (0x%x), unix %u\n", ill->ill_name,
15322 		    dlpi_prim_str(dlea->dl_error_primitive),
15323 		    dlea->dl_error_primitive,
15324 		    dlpi_err_str(dlea->dl_errno),
15325 		    dlea->dl_errno,
15326 		    dlea->dl_unix_errno));
15327 		switch (dlea->dl_error_primitive) {
15328 		case DL_UNBIND_REQ:
15329 			mutex_enter(&ill->ill_lock);
15330 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15331 			cv_signal(&ill->ill_cv);
15332 			mutex_exit(&ill->ill_lock);
15333 			/* FALLTHRU */
15334 		case DL_NOTIFY_REQ:
15335 		case DL_ATTACH_REQ:
15336 		case DL_DETACH_REQ:
15337 		case DL_INFO_REQ:
15338 		case DL_BIND_REQ:
15339 		case DL_ENABMULTI_REQ:
15340 		case DL_PHYS_ADDR_REQ:
15341 		case DL_CAPABILITY_REQ:
15342 		case DL_CONTROL_REQ:
15343 			/*
15344 			 * Refhold the ill to match qwriter_ip which does a
15345 			 * refrele. Since this is on the ill stream we
15346 			 * unconditionally bump up the refcount without
15347 			 * checking for ILL_CAN_LOOKUP
15348 			 */
15349 			ill_refhold(ill);
15350 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15351 			    CUR_OP, B_FALSE);
15352 			return;
15353 		case DL_DISABMULTI_REQ:
15354 			freemsg(mp);	/* Don't want to pass this up */
15355 			return;
15356 		default:
15357 			break;
15358 		}
15359 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15360 		    dlea->dl_errno, dlea->dl_unix_errno);
15361 		freemsg(mp);
15362 		return;
15363 	case DL_INFO_ACK:
15364 	case DL_BIND_ACK:
15365 	case DL_PHYS_ADDR_ACK:
15366 	case DL_NOTIFY_ACK:
15367 	case DL_CAPABILITY_ACK:
15368 	case DL_CONTROL_ACK:
15369 		/*
15370 		 * Refhold the ill to match qwriter_ip which does a refrele
15371 		 * Since this is on the ill stream we unconditionally
15372 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15373 		 */
15374 		ill_refhold(ill);
15375 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15376 		    CUR_OP, B_FALSE);
15377 		return;
15378 	case DL_NOTIFY_IND:
15379 		ill_refhold(ill);
15380 		/*
15381 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15382 		 * relation to the current ioctl in progress (if any). Hence we
15383 		 * pass in NEW_OP in this case.
15384 		 */
15385 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15386 		    NEW_OP, B_FALSE);
15387 		return;
15388 	case DL_OK_ACK:
15389 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15390 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15391 		switch (dloa->dl_correct_primitive) {
15392 		case DL_UNBIND_REQ:
15393 			mutex_enter(&ill->ill_lock);
15394 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15395 			cv_signal(&ill->ill_cv);
15396 			mutex_exit(&ill->ill_lock);
15397 			/* FALLTHRU */
15398 		case DL_ATTACH_REQ:
15399 		case DL_DETACH_REQ:
15400 			/*
15401 			 * Refhold the ill to match qwriter_ip which does a
15402 			 * refrele. Since this is on the ill stream we
15403 			 * unconditionally bump up the refcount
15404 			 */
15405 			ill_refhold(ill);
15406 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15407 			    CUR_OP, B_FALSE);
15408 			return;
15409 		case DL_ENABMULTI_REQ:
15410 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15411 				ill->ill_dlpi_multicast_state = IDS_OK;
15412 			break;
15413 
15414 		}
15415 		break;
15416 	default:
15417 		break;
15418 	}
15419 	freemsg(mp);
15420 }
15421 
15422 /*
15423  * Handling of DLPI messages that require exclusive access to the ipsq.
15424  *
15425  * Need to do ill_pending_mp_release on ioctl completion, which could
15426  * happen here. (along with mi_copy_done)
15427  */
15428 /* ARGSUSED */
15429 static void
15430 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15431 {
15432 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15433 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15434 	int		err = 0;
15435 	ill_t		*ill;
15436 	ipif_t		*ipif = NULL;
15437 	mblk_t		*mp1 = NULL;
15438 	conn_t		*connp = NULL;
15439 	t_uscalar_t	physaddr_req;
15440 	mblk_t		*mp_hw;
15441 	union DL_primitives *dlp;
15442 	boolean_t	success;
15443 	boolean_t	ioctl_aborted = B_FALSE;
15444 	boolean_t	log = B_TRUE;
15445 	hook_nic_event_t	*info;
15446 
15447 	ip1dbg(("ip_rput_dlpi_writer .."));
15448 	ill = (ill_t *)q->q_ptr;
15449 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15450 
15451 	ASSERT(IAM_WRITER_ILL(ill));
15452 
15453 	/*
15454 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15455 	 * both are null or non-null. However we can assert that only
15456 	 * after grabbing the ipsq_lock. So we don't make any assertion
15457 	 * here and in other places in the code.
15458 	 */
15459 	ipif = ipsq->ipsq_pending_ipif;
15460 	/*
15461 	 * The current ioctl could have been aborted by the user and a new
15462 	 * ioctl to bring up another ill could have started. We could still
15463 	 * get a response from the driver later.
15464 	 */
15465 	if (ipif != NULL && ipif->ipif_ill != ill)
15466 		ioctl_aborted = B_TRUE;
15467 
15468 	switch (dloa->dl_primitive) {
15469 	case DL_ERROR_ACK:
15470 		switch (dlea->dl_error_primitive) {
15471 		case DL_UNBIND_REQ:
15472 		case DL_ATTACH_REQ:
15473 		case DL_DETACH_REQ:
15474 		case DL_INFO_REQ:
15475 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15476 			break;
15477 		case DL_NOTIFY_REQ:
15478 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15479 			log = B_FALSE;
15480 			break;
15481 		case DL_PHYS_ADDR_REQ:
15482 			/*
15483 			 * For IPv6 only, there are two additional
15484 			 * phys_addr_req's sent to the driver to get the
15485 			 * IPv6 token and lla. This allows IP to acquire
15486 			 * the hardware address format for a given interface
15487 			 * without having built in knowledge of the hardware
15488 			 * address. ill_phys_addr_pend keeps track of the last
15489 			 * DL_PAR sent so we know which response we are
15490 			 * dealing with. ill_dlpi_done will update
15491 			 * ill_phys_addr_pend when it sends the next req.
15492 			 * We don't complete the IOCTL until all three DL_PARs
15493 			 * have been attempted, so set *_len to 0 and break.
15494 			 */
15495 			physaddr_req = ill->ill_phys_addr_pend;
15496 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15497 			if (physaddr_req == DL_IPV6_TOKEN) {
15498 				ill->ill_token_length = 0;
15499 				log = B_FALSE;
15500 				break;
15501 			} else if (physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
15502 				ill->ill_nd_lla_len = 0;
15503 				log = B_FALSE;
15504 				break;
15505 			}
15506 			/*
15507 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15508 			 * We presumably have an IOCTL hanging out waiting
15509 			 * for completion. Find it and complete the IOCTL
15510 			 * with the error noted.
15511 			 * However, ill_dl_phys was called on an ill queue
15512 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15513 			 * set. But the ioctl is known to be pending on ill_wq.
15514 			 */
15515 			if (!ill->ill_ifname_pending)
15516 				break;
15517 			ill->ill_ifname_pending = 0;
15518 			if (!ioctl_aborted)
15519 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15520 			if (mp1 != NULL) {
15521 				/*
15522 				 * This operation (SIOCSLIFNAME) must have
15523 				 * happened on the ill. Assert there is no conn
15524 				 */
15525 				ASSERT(connp == NULL);
15526 				q = ill->ill_wq;
15527 			}
15528 			break;
15529 		case DL_BIND_REQ:
15530 			ill_dlpi_done(ill, DL_BIND_REQ);
15531 			if (ill->ill_ifname_pending)
15532 				break;
15533 			/*
15534 			 * Something went wrong with the bind.  We presumably
15535 			 * have an IOCTL hanging out waiting for completion.
15536 			 * Find it, take down the interface that was coming
15537 			 * up, and complete the IOCTL with the error noted.
15538 			 */
15539 			if (!ioctl_aborted)
15540 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15541 			if (mp1 != NULL) {
15542 				/*
15543 				 * This operation (SIOCSLIFFLAGS) must have
15544 				 * happened from a conn.
15545 				 */
15546 				ASSERT(connp != NULL);
15547 				q = CONNP_TO_WQ(connp);
15548 				if (ill->ill_move_in_progress) {
15549 					ILL_CLEAR_MOVE(ill);
15550 				}
15551 				(void) ipif_down(ipif, NULL, NULL);
15552 				/* error is set below the switch */
15553 			}
15554 			break;
15555 		case DL_ENABMULTI_REQ:
15556 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15557 
15558 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15559 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15560 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15561 				ipif_t *ipif;
15562 
15563 				log = B_FALSE;
15564 				printf("ip: joining multicasts failed (%d)"
15565 				    " on %s - will use link layer "
15566 				    "broadcasts for multicast\n",
15567 				    dlea->dl_errno, ill->ill_name);
15568 
15569 				/*
15570 				 * Set up the multicast mapping alone.
15571 				 * writer, so ok to access ill->ill_ipif
15572 				 * without any lock.
15573 				 */
15574 				ipif = ill->ill_ipif;
15575 				mutex_enter(&ill->ill_phyint->phyint_lock);
15576 				ill->ill_phyint->phyint_flags |=
15577 				    PHYI_MULTI_BCAST;
15578 				mutex_exit(&ill->ill_phyint->phyint_lock);
15579 
15580 				if (!ill->ill_isv6) {
15581 					(void) ipif_arp_setup_multicast(ipif,
15582 					    NULL);
15583 				} else {
15584 					(void) ipif_ndp_setup_multicast(ipif,
15585 					    NULL);
15586 				}
15587 			}
15588 			freemsg(mp);	/* Don't want to pass this up */
15589 			return;
15590 		case DL_CAPABILITY_REQ:
15591 		case DL_CONTROL_REQ:
15592 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15593 			    "DL_CAPABILITY/CONTROL REQ\n"));
15594 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15595 			ill->ill_dlpi_capab_state = IDS_FAILED;
15596 			freemsg(mp);
15597 			return;
15598 		}
15599 		/*
15600 		 * Note the error for IOCTL completion (mp1 is set when
15601 		 * ready to complete ioctl). If ill_ifname_pending_err is
15602 		 * set, an error occured during plumbing (ill_ifname_pending),
15603 		 * so we want to report that error.
15604 		 *
15605 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15606 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15607 		 * expected to get errack'd if the driver doesn't support
15608 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15609 		 * if these error conditions are encountered.
15610 		 */
15611 		if (mp1 != NULL) {
15612 			if (ill->ill_ifname_pending_err != 0)  {
15613 				err = ill->ill_ifname_pending_err;
15614 				ill->ill_ifname_pending_err = 0;
15615 			} else {
15616 				err = dlea->dl_unix_errno ?
15617 				    dlea->dl_unix_errno : ENXIO;
15618 			}
15619 		/*
15620 		 * If we're plumbing an interface and an error hasn't already
15621 		 * been saved, set ill_ifname_pending_err to the error passed
15622 		 * up. Ignore the error if log is B_FALSE (see comment above).
15623 		 */
15624 		} else if (log && ill->ill_ifname_pending &&
15625 		    ill->ill_ifname_pending_err == 0) {
15626 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15627 			dlea->dl_unix_errno : ENXIO;
15628 		}
15629 
15630 		if (log)
15631 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15632 			    dlea->dl_errno, dlea->dl_unix_errno);
15633 		break;
15634 	case DL_CAPABILITY_ACK: {
15635 		boolean_t reneg_flag = B_FALSE;
15636 		/* Call a routine to handle this one. */
15637 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15638 		/*
15639 		 * Check if the ACK is due to renegotiation case since we
15640 		 * will need to send a new CAPABILITY_REQ later.
15641 		 */
15642 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15643 			/* This is the ack for a renogiation case */
15644 			reneg_flag = B_TRUE;
15645 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15646 		}
15647 		ill_capability_ack(ill, mp);
15648 		if (reneg_flag)
15649 			ill_capability_probe(ill);
15650 		break;
15651 	}
15652 	case DL_CONTROL_ACK:
15653 		/* We treat all of these as "fire and forget" */
15654 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15655 		break;
15656 	case DL_INFO_ACK:
15657 		/* Call a routine to handle this one. */
15658 		ill_dlpi_done(ill, DL_INFO_REQ);
15659 		ip_ll_subnet_defaults(ill, mp);
15660 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15661 		return;
15662 	case DL_BIND_ACK:
15663 		/*
15664 		 * We should have an IOCTL waiting on this unless
15665 		 * sent by ill_dl_phys, in which case just return
15666 		 */
15667 		ill_dlpi_done(ill, DL_BIND_REQ);
15668 		if (ill->ill_ifname_pending)
15669 			break;
15670 
15671 		if (!ioctl_aborted)
15672 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15673 		if (mp1 == NULL)
15674 			break;
15675 		ASSERT(connp != NULL);
15676 		q = CONNP_TO_WQ(connp);
15677 
15678 		/*
15679 		 * We are exclusive. So nothing can change even after
15680 		 * we get the pending mp. If need be we can put it back
15681 		 * and restart, as in calling ipif_arp_up()  below.
15682 		 */
15683 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15684 
15685 		mutex_enter(&ill->ill_lock);
15686 
15687 		ill->ill_dl_up = 1;
15688 
15689 		if ((info = ill->ill_nic_event_info) != NULL) {
15690 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15691 			    "attached for %s\n", info->hne_event,
15692 			    ill->ill_name));
15693 			if (info->hne_data != NULL)
15694 				kmem_free(info->hne_data, info->hne_datalen);
15695 			kmem_free(info, sizeof (hook_nic_event_t));
15696 		}
15697 
15698 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15699 		if (info != NULL) {
15700 			info->hne_nic = ill->ill_phyint->phyint_ifindex;
15701 			info->hne_lif = 0;
15702 			info->hne_event = NE_UP;
15703 			info->hne_data = NULL;
15704 			info->hne_datalen = 0;
15705 			info->hne_family = ill->ill_isv6 ? ipv6 : ipv4;
15706 		} else
15707 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15708 			    "event information for %s (ENOMEM)\n",
15709 			    ill->ill_name));
15710 
15711 		ill->ill_nic_event_info = info;
15712 
15713 		mutex_exit(&ill->ill_lock);
15714 
15715 		/*
15716 		 * Now bring up the resolver; when that is complete, we'll
15717 		 * create IREs.  Note that we intentionally mirror what
15718 		 * ipif_up() would have done, because we got here by way of
15719 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15720 		 */
15721 		if (ill->ill_isv6) {
15722 			/*
15723 			 * v6 interfaces.
15724 			 * Unlike ARP which has to do another bind
15725 			 * and attach, once we get here we are
15726 			 * done with NDP. Except in the case of
15727 			 * ILLF_XRESOLV, in which case we send an
15728 			 * AR_INTERFACE_UP to the external resolver.
15729 			 * If all goes well, the ioctl will complete
15730 			 * in ip_rput(). If there's an error, we
15731 			 * complete it here.
15732 			 */
15733 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr,
15734 			    B_FALSE);
15735 			if (err == 0) {
15736 				if (ill->ill_flags & ILLF_XRESOLV) {
15737 					mutex_enter(&connp->conn_lock);
15738 					mutex_enter(&ill->ill_lock);
15739 					success = ipsq_pending_mp_add(
15740 					    connp, ipif, q, mp1, 0);
15741 					mutex_exit(&ill->ill_lock);
15742 					mutex_exit(&connp->conn_lock);
15743 					if (success) {
15744 						err = ipif_resolver_up(ipif,
15745 						    Res_act_initial);
15746 						if (err == EINPROGRESS) {
15747 							freemsg(mp);
15748 							return;
15749 						}
15750 						ASSERT(err != 0);
15751 						mp1 = ipsq_pending_mp_get(ipsq,
15752 						    &connp);
15753 						ASSERT(mp1 != NULL);
15754 					} else {
15755 						/* conn has started closing */
15756 						err = EINTR;
15757 					}
15758 				} else { /* Non XRESOLV interface */
15759 					(void) ipif_resolver_up(ipif,
15760 					    Res_act_initial);
15761 					err = ipif_up_done_v6(ipif);
15762 				}
15763 			}
15764 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15765 			/*
15766 			 * ARP and other v4 external resolvers.
15767 			 * Leave the pending mblk intact so that
15768 			 * the ioctl completes in ip_rput().
15769 			 */
15770 			mutex_enter(&connp->conn_lock);
15771 			mutex_enter(&ill->ill_lock);
15772 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15773 			mutex_exit(&ill->ill_lock);
15774 			mutex_exit(&connp->conn_lock);
15775 			if (success) {
15776 				err = ipif_resolver_up(ipif, Res_act_initial);
15777 				if (err == EINPROGRESS) {
15778 					freemsg(mp);
15779 					return;
15780 				}
15781 				ASSERT(err != 0);
15782 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15783 			} else {
15784 				/* The conn has started closing */
15785 				err = EINTR;
15786 			}
15787 		} else {
15788 			/*
15789 			 * This one is complete. Reply to pending ioctl.
15790 			 */
15791 			(void) ipif_resolver_up(ipif, Res_act_initial);
15792 			err = ipif_up_done(ipif);
15793 		}
15794 
15795 		if ((err == 0) && (ill->ill_up_ipifs)) {
15796 			err = ill_up_ipifs(ill, q, mp1);
15797 			if (err == EINPROGRESS) {
15798 				freemsg(mp);
15799 				return;
15800 			}
15801 		}
15802 
15803 		if (ill->ill_up_ipifs) {
15804 			ill_group_cleanup(ill);
15805 		}
15806 
15807 		break;
15808 	case DL_NOTIFY_IND: {
15809 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15810 		ire_t *ire;
15811 		boolean_t need_ire_walk_v4 = B_FALSE;
15812 		boolean_t need_ire_walk_v6 = B_FALSE;
15813 
15814 		/*
15815 		 * Change the address everywhere we need to.
15816 		 * What we're getting here is a link-level addr or phys addr.
15817 		 * The new addr is at notify + notify->dl_addr_offset
15818 		 * The address length is notify->dl_addr_length;
15819 		 */
15820 		switch (notify->dl_notification) {
15821 		case DL_NOTE_PHYS_ADDR:
15822 			mp_hw = copyb(mp);
15823 			if (mp_hw == NULL) {
15824 				err = ENOMEM;
15825 				break;
15826 			}
15827 			dlp = (union DL_primitives *)mp_hw->b_rptr;
15828 			/*
15829 			 * We currently don't support changing
15830 			 * the token via DL_NOTIFY_IND.
15831 			 * When we do support it, we have to consider
15832 			 * what the implications are with respect to
15833 			 * the token and the link local address.
15834 			 */
15835 			mutex_enter(&ill->ill_lock);
15836 			if (dlp->notify_ind.dl_data ==
15837 			    DL_IPV6_LINK_LAYER_ADDR) {
15838 				if (ill->ill_nd_lla_mp != NULL)
15839 					freemsg(ill->ill_nd_lla_mp);
15840 				ill->ill_nd_lla_mp = mp_hw;
15841 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
15842 				    dlp->notify_ind.dl_addr_offset;
15843 				ill->ill_nd_lla_len =
15844 				    dlp->notify_ind.dl_addr_length -
15845 				    ABS(ill->ill_sap_length);
15846 				mutex_exit(&ill->ill_lock);
15847 				break;
15848 			} else if (dlp->notify_ind.dl_data ==
15849 			    DL_CURR_PHYS_ADDR) {
15850 				if (ill->ill_phys_addr_mp != NULL)
15851 					freemsg(ill->ill_phys_addr_mp);
15852 				ill->ill_phys_addr_mp = mp_hw;
15853 				ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
15854 				    dlp->notify_ind.dl_addr_offset;
15855 				ill->ill_phys_addr_length =
15856 				    dlp->notify_ind.dl_addr_length -
15857 				    ABS(ill->ill_sap_length);
15858 				if (ill->ill_isv6 &&
15859 				    !(ill->ill_flags & ILLF_XRESOLV)) {
15860 					if (ill->ill_nd_lla_mp != NULL)
15861 						freemsg(ill->ill_nd_lla_mp);
15862 					ill->ill_nd_lla_mp = copyb(mp_hw);
15863 					ill->ill_nd_lla = (uchar_t *)
15864 					    ill->ill_nd_lla_mp->b_rptr +
15865 					    dlp->notify_ind.dl_addr_offset;
15866 					ill->ill_nd_lla_len =
15867 					    ill->ill_phys_addr_length;
15868 				}
15869 			}
15870 			mutex_exit(&ill->ill_lock);
15871 			/*
15872 			 * Send out gratuitous arp request for our new
15873 			 * hardware address.
15874 			 */
15875 			for (ipif = ill->ill_ipif; ipif != NULL;
15876 			    ipif = ipif->ipif_next) {
15877 				if (!(ipif->ipif_flags & IPIF_UP))
15878 					continue;
15879 				if (ill->ill_isv6) {
15880 					ipif_ndp_down(ipif);
15881 					/*
15882 					 * Set B_TRUE to enable
15883 					 * ipif_ndp_up() to send out
15884 					 * unsolicited advertisements.
15885 					 */
15886 					err = ipif_ndp_up(ipif,
15887 					    &ipif->ipif_v6lcl_addr,
15888 					    B_TRUE);
15889 					if (err) {
15890 						ip1dbg((
15891 						    "ip_rput_dlpi_writer: "
15892 						    "Failed to update ndp "
15893 						    "err %d\n", err));
15894 					}
15895 				} else {
15896 					/*
15897 					 * IPv4 ARP case
15898 					 *
15899 					 * Set Res_act_move, as we only want
15900 					 * ipif_resolver_up to send an
15901 					 * AR_ENTRY_ADD request up to
15902 					 * ARP.
15903 					 */
15904 					err = ipif_resolver_up(ipif,
15905 					    Res_act_move);
15906 					if (err) {
15907 						ip1dbg((
15908 						    "ip_rput_dlpi_writer: "
15909 						    "Failed to update arp "
15910 						    "err %d\n", err));
15911 					}
15912 				}
15913 			}
15914 			/*
15915 			 * Allow "fall through" to the DL_NOTE_FASTPATH_FLUSH
15916 			 * case so that all old fastpath information can be
15917 			 * purged from IRE caches.
15918 			 */
15919 		/* FALLTHRU */
15920 		case DL_NOTE_FASTPATH_FLUSH:
15921 			/*
15922 			 * Any fastpath probe sent henceforth will get the
15923 			 * new fp mp. So we first delete any ires that are
15924 			 * waiting for the fastpath. Then walk all ires and
15925 			 * delete the ire or delete the fp mp. In the case of
15926 			 * IRE_MIPRTUN and IRE_BROADCAST it is difficult to
15927 			 * recreate the ire's without going through a complex
15928 			 * ipif up/down dance. So we don't delete the ire
15929 			 * itself, but just the nce_fp_mp for these 2 ire's
15930 			 * In the case of the other ire's we delete the ire's
15931 			 * themselves. Access to nce_fp_mp is completely
15932 			 * protected by ire_lock for IRE_MIPRTUN and
15933 			 * IRE_BROADCAST. Deleting the ire is preferable in the
15934 			 * other cases for performance.
15935 			 */
15936 			if (ill->ill_isv6) {
15937 				nce_fastpath_list_dispatch(ill, NULL, NULL);
15938 				ndp_walk(ill, (pfi_t)ndp_fastpath_flush,
15939 				    NULL);
15940 			} else {
15941 				ire_fastpath_list_dispatch(ill, NULL, NULL);
15942 				ire_walk_ill_v4(MATCH_IRE_WQ | MATCH_IRE_TYPE,
15943 				    IRE_CACHE | IRE_BROADCAST,
15944 				    ire_fastpath_flush, NULL, ill);
15945 				mutex_enter(&ire_mrtun_lock);
15946 				if (ire_mrtun_count != 0) {
15947 					mutex_exit(&ire_mrtun_lock);
15948 					ire_walk_ill_mrtun(MATCH_IRE_WQ,
15949 					    IRE_MIPRTUN, ire_fastpath_flush,
15950 					    NULL, ill);
15951 				} else {
15952 					mutex_exit(&ire_mrtun_lock);
15953 				}
15954 			}
15955 			break;
15956 		case DL_NOTE_SDU_SIZE:
15957 			/*
15958 			 * Change the MTU size of the interface, of all
15959 			 * attached ipif's, and of all relevant ire's.  The
15960 			 * new value's a uint32_t at notify->dl_data.
15961 			 * Mtu change Vs. new ire creation - protocol below.
15962 			 *
15963 			 * a Mark the ipif as IPIF_CHANGING.
15964 			 * b Set the new mtu in the ipif.
15965 			 * c Change the ire_max_frag on all affected ires
15966 			 * d Unmark the IPIF_CHANGING
15967 			 *
15968 			 * To see how the protocol works, assume an interface
15969 			 * route is also being added simultaneously by
15970 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15971 			 * the ire. If the ire is created before step a,
15972 			 * it will be cleaned up by step c. If the ire is
15973 			 * created after step d, it will see the new value of
15974 			 * ipif_mtu. Any attempt to create the ire between
15975 			 * steps a to d will fail because of the IPIF_CHANGING
15976 			 * flag. Note that ire_create() is passed a pointer to
15977 			 * the ipif_mtu, and not the value. During ire_add
15978 			 * under the bucket lock, the ire_max_frag of the
15979 			 * new ire being created is set from the ipif/ire from
15980 			 * which it is being derived.
15981 			 */
15982 			mutex_enter(&ill->ill_lock);
15983 			ill->ill_max_frag = (uint_t)notify->dl_data;
15984 
15985 			/*
15986 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15987 			 * leave it alone
15988 			 */
15989 			if (ill->ill_mtu_userspecified) {
15990 				mutex_exit(&ill->ill_lock);
15991 				break;
15992 			}
15993 			ill->ill_max_mtu = ill->ill_max_frag;
15994 			if (ill->ill_isv6) {
15995 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15996 					ill->ill_max_mtu = IPV6_MIN_MTU;
15997 			} else {
15998 				if (ill->ill_max_mtu < IP_MIN_MTU)
15999 					ill->ill_max_mtu = IP_MIN_MTU;
16000 			}
16001 			for (ipif = ill->ill_ipif; ipif != NULL;
16002 			    ipif = ipif->ipif_next) {
16003 				/*
16004 				 * Don't override the mtu if the user
16005 				 * has explicitly set it.
16006 				 */
16007 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16008 					continue;
16009 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16010 				if (ipif->ipif_isv6)
16011 					ire = ipif_to_ire_v6(ipif);
16012 				else
16013 					ire = ipif_to_ire(ipif);
16014 				if (ire != NULL) {
16015 					ire->ire_max_frag = ipif->ipif_mtu;
16016 					ire_refrele(ire);
16017 				}
16018 				if (ipif->ipif_flags & IPIF_UP) {
16019 					if (ill->ill_isv6)
16020 						need_ire_walk_v6 = B_TRUE;
16021 					else
16022 						need_ire_walk_v4 = B_TRUE;
16023 				}
16024 			}
16025 			mutex_exit(&ill->ill_lock);
16026 			if (need_ire_walk_v4)
16027 				ire_walk_v4(ill_mtu_change, (char *)ill,
16028 				    ALL_ZONES);
16029 			if (need_ire_walk_v6)
16030 				ire_walk_v6(ill_mtu_change, (char *)ill,
16031 				    ALL_ZONES);
16032 			break;
16033 		case DL_NOTE_LINK_UP:
16034 		case DL_NOTE_LINK_DOWN: {
16035 			/*
16036 			 * We are writer. ill / phyint / ipsq assocs stable.
16037 			 * The RUNNING flag reflects the state of the link.
16038 			 */
16039 			phyint_t *phyint = ill->ill_phyint;
16040 			uint64_t new_phyint_flags;
16041 			boolean_t changed = B_FALSE;
16042 			boolean_t went_up;
16043 
16044 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16045 			mutex_enter(&phyint->phyint_lock);
16046 			new_phyint_flags = went_up ?
16047 			    phyint->phyint_flags | PHYI_RUNNING :
16048 			    phyint->phyint_flags & ~PHYI_RUNNING;
16049 			if (new_phyint_flags != phyint->phyint_flags) {
16050 				phyint->phyint_flags = new_phyint_flags;
16051 				changed = B_TRUE;
16052 			}
16053 			mutex_exit(&phyint->phyint_lock);
16054 			/*
16055 			 * ill_restart_dad handles the DAD restart and routing
16056 			 * socket notification logic.
16057 			 */
16058 			if (changed) {
16059 				ill_restart_dad(phyint->phyint_illv4, went_up);
16060 				ill_restart_dad(phyint->phyint_illv6, went_up);
16061 			}
16062 			break;
16063 		}
16064 		case DL_NOTE_PROMISC_ON_PHYS:
16065 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16066 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16067 			mutex_enter(&ill->ill_lock);
16068 			ill->ill_promisc_on_phys = B_TRUE;
16069 			mutex_exit(&ill->ill_lock);
16070 			break;
16071 		case DL_NOTE_PROMISC_OFF_PHYS:
16072 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16073 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16074 			mutex_enter(&ill->ill_lock);
16075 			ill->ill_promisc_on_phys = B_FALSE;
16076 			mutex_exit(&ill->ill_lock);
16077 			break;
16078 		case DL_NOTE_CAPAB_RENEG:
16079 			/*
16080 			 * Something changed on the driver side.
16081 			 * It wants us to renegotiate the capabilities
16082 			 * on this ill. The most likely cause is the
16083 			 * aggregation interface under us where a
16084 			 * port got added or went away.
16085 			 *
16086 			 * We reset the capabilities and set the
16087 			 * state to IDS_RENG so that when the ack
16088 			 * comes back, we can start the
16089 			 * renegotiation process.
16090 			 */
16091 			ill_capability_reset(ill);
16092 			ill->ill_dlpi_capab_state = IDS_RENEG;
16093 			break;
16094 		default:
16095 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16096 			    "type 0x%x for DL_NOTIFY_IND\n",
16097 			    notify->dl_notification));
16098 			break;
16099 		}
16100 
16101 		/*
16102 		 * As this is an asynchronous operation, we
16103 		 * should not call ill_dlpi_done
16104 		 */
16105 		break;
16106 	}
16107 	case DL_NOTIFY_ACK: {
16108 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16109 
16110 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16111 			ill->ill_note_link = 1;
16112 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16113 		break;
16114 	}
16115 	case DL_PHYS_ADDR_ACK: {
16116 		/*
16117 		 * We should have an IOCTL waiting on this when request
16118 		 * sent by ill_dl_phys.
16119 		 * However, ill_dl_phys was called on an ill queue (from
16120 		 * SIOCSLIFNAME), thus conn_pending_ill is not set. But the
16121 		 * ioctl is known to be pending on ill_wq.
16122 		 * There are two additional phys_addr_req's sent to the
16123 		 * driver to get the token and lla. ill_phys_addr_pend
16124 		 * keeps track of the last one sent so we know which
16125 		 * response we are dealing with. ill_dlpi_done will
16126 		 * update ill_phys_addr_pend when it sends the next req.
16127 		 * We don't complete the IOCTL until all three DL_PARs
16128 		 * have been attempted.
16129 		 *
16130 		 * We don't need any lock to update ill_nd_lla* fields,
16131 		 * since the ill is not yet up, We grab the lock just
16132 		 * for uniformity with other code that accesses ill_nd_lla.
16133 		 */
16134 		physaddr_req = ill->ill_phys_addr_pend;
16135 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16136 		if (physaddr_req == DL_IPV6_TOKEN ||
16137 		    physaddr_req == DL_IPV6_LINK_LAYER_ADDR) {
16138 			if (physaddr_req == DL_IPV6_TOKEN) {
16139 				/*
16140 				 * bcopy to low-order bits of ill_token
16141 				 *
16142 				 * XXX Temporary hack - currently,
16143 				 * all known tokens are 64 bits,
16144 				 * so I'll cheat for the moment.
16145 				 */
16146 				dlp = (union DL_primitives *)mp->b_rptr;
16147 
16148 				mutex_enter(&ill->ill_lock);
16149 				bcopy((uchar_t *)(mp->b_rptr +
16150 				dlp->physaddr_ack.dl_addr_offset),
16151 				(void *)&ill->ill_token.s6_addr32[2],
16152 				dlp->physaddr_ack.dl_addr_length);
16153 				ill->ill_token_length =
16154 					dlp->physaddr_ack.dl_addr_length;
16155 				mutex_exit(&ill->ill_lock);
16156 			} else {
16157 				ASSERT(ill->ill_nd_lla_mp == NULL);
16158 				mp_hw = copyb(mp);
16159 				if (mp_hw == NULL) {
16160 					err = ENOMEM;
16161 					break;
16162 				}
16163 				dlp = (union DL_primitives *)mp_hw->b_rptr;
16164 				mutex_enter(&ill->ill_lock);
16165 				ill->ill_nd_lla_mp = mp_hw;
16166 				ill->ill_nd_lla = (uchar_t *)mp_hw->b_rptr +
16167 				dlp->physaddr_ack.dl_addr_offset;
16168 				ill->ill_nd_lla_len =
16169 					dlp->physaddr_ack.dl_addr_length;
16170 				mutex_exit(&ill->ill_lock);
16171 			}
16172 			break;
16173 		}
16174 		ASSERT(physaddr_req == DL_CURR_PHYS_ADDR);
16175 		ASSERT(ill->ill_phys_addr_mp == NULL);
16176 		if (!ill->ill_ifname_pending)
16177 			break;
16178 		ill->ill_ifname_pending = 0;
16179 		if (!ioctl_aborted)
16180 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16181 		if (mp1 != NULL) {
16182 			ASSERT(connp == NULL);
16183 			q = ill->ill_wq;
16184 		}
16185 		/*
16186 		 * If any error acks received during the plumbing sequence,
16187 		 * ill_ifname_pending_err will be set. Break out and send up
16188 		 * the error to the pending ioctl.
16189 		 */
16190 		if (ill->ill_ifname_pending_err != 0) {
16191 			err = ill->ill_ifname_pending_err;
16192 			ill->ill_ifname_pending_err = 0;
16193 			break;
16194 		}
16195 		/*
16196 		 * Get the interface token.  If the zeroth interface
16197 		 * address is zero then set the address to the link local
16198 		 * address
16199 		 */
16200 		mp_hw = copyb(mp);
16201 		if (mp_hw == NULL) {
16202 			err = ENOMEM;
16203 			break;
16204 		}
16205 		dlp = (union DL_primitives *)mp_hw->b_rptr;
16206 		ill->ill_phys_addr_mp = mp_hw;
16207 		ill->ill_phys_addr = (uchar_t *)mp_hw->b_rptr +
16208 				dlp->physaddr_ack.dl_addr_offset;
16209 		if (dlp->physaddr_ack.dl_addr_length == 0 ||
16210 		    ill->ill_phys_addr_length == 0 ||
16211 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16212 			/*
16213 			 * Compatibility: atun driver returns a length of 0.
16214 			 * ipdptp has an ill_phys_addr_length of zero(from
16215 			 * DL_BIND_ACK) but a non-zero length here.
16216 			 * ipd has an ill_phys_addr_length of 4(from
16217 			 * DL_BIND_ACK) but a non-zero length here.
16218 			 */
16219 			ill->ill_phys_addr = NULL;
16220 		} else if (dlp->physaddr_ack.dl_addr_length !=
16221 		    ill->ill_phys_addr_length) {
16222 			ip0dbg(("DL_PHYS_ADDR_ACK: "
16223 			    "Address length mismatch %d %d\n",
16224 			    dlp->physaddr_ack.dl_addr_length,
16225 			    ill->ill_phys_addr_length));
16226 			err = EINVAL;
16227 			break;
16228 		}
16229 		mutex_enter(&ill->ill_lock);
16230 		if (ill->ill_nd_lla_mp == NULL) {
16231 			ill->ill_nd_lla_mp = copyb(mp_hw);
16232 			if (ill->ill_nd_lla_mp == NULL) {
16233 				err = ENOMEM;
16234 				mutex_exit(&ill->ill_lock);
16235 				break;
16236 			}
16237 			ill->ill_nd_lla =
16238 			    (uchar_t *)ill->ill_nd_lla_mp->b_rptr +
16239 			    dlp->physaddr_ack.dl_addr_offset;
16240 			ill->ill_nd_lla_len = ill->ill_phys_addr_length;
16241 		}
16242 		mutex_exit(&ill->ill_lock);
16243 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16244 			(void) ill_setdefaulttoken(ill);
16245 
16246 		/*
16247 		 * If the ill zero interface has a zero address assign
16248 		 * it the proper link local address.
16249 		 */
16250 		ASSERT(ill->ill_ipif->ipif_id == 0);
16251 		if (ipif != NULL &&
16252 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
16253 			(void) ipif_setlinklocal(ipif);
16254 		break;
16255 	}
16256 	case DL_OK_ACK:
16257 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16258 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16259 		    dloa->dl_correct_primitive));
16260 		switch (dloa->dl_correct_primitive) {
16261 		case DL_UNBIND_REQ:
16262 		case DL_ATTACH_REQ:
16263 		case DL_DETACH_REQ:
16264 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16265 			break;
16266 		}
16267 		break;
16268 	default:
16269 		break;
16270 	}
16271 
16272 	freemsg(mp);
16273 	if (mp1) {
16274 		struct iocblk *iocp;
16275 		int mode;
16276 
16277 		/*
16278 		 * Complete the waiting IOCTL. For SIOCLIFADDIF or
16279 		 * SIOCSLIFNAME do a copyout.
16280 		 */
16281 		iocp = (struct iocblk *)mp1->b_rptr;
16282 
16283 		if (iocp->ioc_cmd == SIOCLIFADDIF ||
16284 		    iocp->ioc_cmd == SIOCSLIFNAME)
16285 			mode = COPYOUT;
16286 		else
16287 			mode = NO_COPYOUT;
16288 		/*
16289 		 * The ioctl must complete now without EINPROGRESS
16290 		 * since ipsq_pending_mp_get has removed the ioctl mblk
16291 		 * from ipsq_pending_mp. Otherwise the ioctl will be
16292 		 * stuck for ever in the ipsq.
16293 		 */
16294 		ASSERT(err != EINPROGRESS);
16295 		ip_ioctl_finish(q, mp1, err, mode, ipif, ipsq);
16296 
16297 	}
16298 }
16299 
16300 /*
16301  * ip_rput_other is called by ip_rput to handle messages modifying the global
16302  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16303  */
16304 /* ARGSUSED */
16305 void
16306 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16307 {
16308 	ill_t		*ill;
16309 	struct iocblk	*iocp;
16310 	mblk_t		*mp1;
16311 	conn_t		*connp = NULL;
16312 
16313 	ip1dbg(("ip_rput_other "));
16314 	ill = (ill_t *)q->q_ptr;
16315 	/*
16316 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16317 	 * in which case ipsq is NULL.
16318 	 */
16319 	if (ipsq != NULL) {
16320 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16321 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16322 	}
16323 
16324 	switch (mp->b_datap->db_type) {
16325 	case M_ERROR:
16326 	case M_HANGUP:
16327 		/*
16328 		 * The device has a problem.  We force the ILL down.  It can
16329 		 * be brought up again manually using SIOCSIFFLAGS (via
16330 		 * ifconfig or equivalent).
16331 		 */
16332 		ASSERT(ipsq != NULL);
16333 		if (mp->b_rptr < mp->b_wptr)
16334 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16335 		if (ill->ill_error == 0)
16336 			ill->ill_error = ENXIO;
16337 		if (!ill_down_start(q, mp))
16338 			return;
16339 		ipif_all_down_tail(ipsq, q, mp, NULL);
16340 		break;
16341 	case M_IOCACK:
16342 		iocp = (struct iocblk *)mp->b_rptr;
16343 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16344 		switch (iocp->ioc_cmd) {
16345 		case SIOCSTUNPARAM:
16346 		case OSIOCSTUNPARAM:
16347 			ASSERT(ipsq != NULL);
16348 			/*
16349 			 * Finish socket ioctl passed through to tun.
16350 			 * We should have an IOCTL waiting on this.
16351 			 */
16352 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16353 			if (ill->ill_isv6) {
16354 				struct iftun_req *ta;
16355 
16356 				/*
16357 				 * if a source or destination is
16358 				 * being set, try and set the link
16359 				 * local address for the tunnel
16360 				 */
16361 				ta = (struct iftun_req *)mp->b_cont->
16362 				    b_cont->b_rptr;
16363 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16364 					ipif_set_tun_llink(ill, ta);
16365 				}
16366 
16367 			}
16368 			if (mp1 != NULL) {
16369 				/*
16370 				 * Now copy back the b_next/b_prev used by
16371 				 * mi code for the mi_copy* functions.
16372 				 * See ip_sioctl_tunparam() for the reason.
16373 				 * Also protect against missing b_cont.
16374 				 */
16375 				if (mp->b_cont != NULL) {
16376 					mp->b_cont->b_next =
16377 					    mp1->b_cont->b_next;
16378 					mp->b_cont->b_prev =
16379 					    mp1->b_cont->b_prev;
16380 				}
16381 				inet_freemsg(mp1);
16382 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16383 				ASSERT(connp != NULL);
16384 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16385 				    iocp->ioc_error, NO_COPYOUT,
16386 				    ipsq->ipsq_current_ipif, ipsq);
16387 			} else {
16388 				ASSERT(connp == NULL);
16389 				putnext(q, mp);
16390 			}
16391 			break;
16392 		case SIOCGTUNPARAM:
16393 		case OSIOCGTUNPARAM:
16394 			/*
16395 			 * This is really M_IOCDATA from the tunnel driver.
16396 			 * convert back and complete the ioctl.
16397 			 * We should have an IOCTL waiting on this.
16398 			 */
16399 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16400 			if (mp1) {
16401 				/*
16402 				 * Now copy back the b_next/b_prev used by
16403 				 * mi code for the mi_copy* functions.
16404 				 * See ip_sioctl_tunparam() for the reason.
16405 				 * Also protect against missing b_cont.
16406 				 */
16407 				if (mp->b_cont != NULL) {
16408 					mp->b_cont->b_next =
16409 					    mp1->b_cont->b_next;
16410 					mp->b_cont->b_prev =
16411 					    mp1->b_cont->b_prev;
16412 				}
16413 				inet_freemsg(mp1);
16414 				if (iocp->ioc_error == 0)
16415 					mp->b_datap->db_type = M_IOCDATA;
16416 				ASSERT(connp != NULL);
16417 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16418 				    iocp->ioc_error, COPYOUT, NULL, NULL);
16419 			} else {
16420 				ASSERT(connp == NULL);
16421 				putnext(q, mp);
16422 			}
16423 			break;
16424 		default:
16425 			break;
16426 		}
16427 		break;
16428 	case M_IOCNAK:
16429 		iocp = (struct iocblk *)mp->b_rptr;
16430 
16431 		switch (iocp->ioc_cmd) {
16432 		int mode;
16433 		ipif_t	*ipif;
16434 
16435 		case DL_IOC_HDR_INFO:
16436 			/*
16437 			 * If this was the first attempt turn of the
16438 			 * fastpath probing.
16439 			 */
16440 			mutex_enter(&ill->ill_lock);
16441 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16442 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16443 				mutex_exit(&ill->ill_lock);
16444 				ill_fastpath_nack(ill);
16445 				ip1dbg(("ip_rput: DLPI fastpath off on "
16446 				    "interface %s\n",
16447 				    ill->ill_name));
16448 			} else {
16449 				mutex_exit(&ill->ill_lock);
16450 			}
16451 			freemsg(mp);
16452 			break;
16453 		case SIOCSTUNPARAM:
16454 		case OSIOCSTUNPARAM:
16455 			ASSERT(ipsq != NULL);
16456 			/*
16457 			 * Finish socket ioctl passed through to tun
16458 			 * We should have an IOCTL waiting on this.
16459 			 */
16460 			/* FALLTHRU */
16461 		case SIOCGTUNPARAM:
16462 		case OSIOCGTUNPARAM:
16463 			/*
16464 			 * This is really M_IOCDATA from the tunnel driver.
16465 			 * convert back and complete the ioctl.
16466 			 * We should have an IOCTL waiting on this.
16467 			 */
16468 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16469 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16470 				mp1 = ill_pending_mp_get(ill, &connp,
16471 				    iocp->ioc_id);
16472 				mode = COPYOUT;
16473 				ipsq = NULL;
16474 				ipif = NULL;
16475 			} else {
16476 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16477 				mode = NO_COPYOUT;
16478 				ASSERT(ipsq->ipsq_current_ipif != NULL);
16479 				ipif = ipsq->ipsq_current_ipif;
16480 			}
16481 			if (mp1 != NULL) {
16482 				/*
16483 				 * Now copy back the b_next/b_prev used by
16484 				 * mi code for the mi_copy* functions.
16485 				 * See ip_sioctl_tunparam() for the reason.
16486 				 * Also protect against missing b_cont.
16487 				 */
16488 				if (mp->b_cont != NULL) {
16489 					mp->b_cont->b_next =
16490 					    mp1->b_cont->b_next;
16491 					mp->b_cont->b_prev =
16492 					    mp1->b_cont->b_prev;
16493 				}
16494 				inet_freemsg(mp1);
16495 				if (iocp->ioc_error == 0)
16496 					iocp->ioc_error = EINVAL;
16497 				ASSERT(connp != NULL);
16498 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16499 				    iocp->ioc_error, mode, ipif, ipsq);
16500 			} else {
16501 				ASSERT(connp == NULL);
16502 				putnext(q, mp);
16503 			}
16504 			break;
16505 		default:
16506 			break;
16507 		}
16508 	default:
16509 		break;
16510 	}
16511 }
16512 
16513 /*
16514  * NOTE : This function does not ire_refrele the ire argument passed in.
16515  *
16516  * IPQoS notes
16517  * IP policy is invoked twice for a forwarded packet, once on the read side
16518  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16519  * enabled. An additional parameter, in_ill, has been added for this purpose.
16520  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16521  * because ip_mroute drops this information.
16522  *
16523  */
16524 void
16525 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16526 {
16527 	uint32_t	pkt_len;
16528 	queue_t	*q;
16529 	uint32_t	sum;
16530 #define	rptr	((uchar_t *)ipha)
16531 	uint32_t	max_frag;
16532 	uint32_t	ill_index;
16533 	ill_t		*out_ill;
16534 	mib2_ipIfStatsEntry_t *mibptr;
16535 
16536 	/* Get the ill_index of the incoming ILL */
16537 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16538 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ip_mib;
16539 
16540 	/* Initiate Read side IPPF processing */
16541 	if (IPP_ENABLED(IPP_FWD_IN)) {
16542 		ip_process(IPP_FWD_IN, &mp, ill_index);
16543 		if (mp == NULL) {
16544 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16545 			    "during IPPF processing\n"));
16546 			return;
16547 		}
16548 	}
16549 
16550 	pkt_len = ntohs(ipha->ipha_length);
16551 
16552 	/* Adjust the checksum to reflect the ttl decrement. */
16553 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16554 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16555 
16556 	if (ipha->ipha_ttl-- <= 1) {
16557 		if (ip_csum_hdr(ipha)) {
16558 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16559 			goto drop_pkt;
16560 		}
16561 		/*
16562 		 * Note: ire_stq this will be NULL for multicast
16563 		 * datagrams using the long path through arp (the IRE
16564 		 * is not an IRE_CACHE). This should not cause
16565 		 * problems since we don't generate ICMP errors for
16566 		 * multicast packets.
16567 		 */
16568 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16569 		q = ire->ire_stq;
16570 		if (q != NULL) {
16571 			/* Sent by forwarding path, and router is global zone */
16572 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16573 			    GLOBAL_ZONEID);
16574 		} else
16575 			freemsg(mp);
16576 		return;
16577 	}
16578 
16579 	/*
16580 	 * Don't forward if the interface is down
16581 	 */
16582 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16583 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16584 		ip2dbg(("ip_rput_forward:interface is down\n"));
16585 		goto drop_pkt;
16586 	}
16587 
16588 	/* Get the ill_index of the outgoing ILL */
16589 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16590 
16591 	out_ill = ire->ire_ipif->ipif_ill;
16592 
16593 	DTRACE_PROBE4(ip4__forwarding__start,
16594 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16595 
16596 	FW_HOOKS(ip4_forwarding_event, ipv4firewall_forwarding,
16597 	    in_ill, out_ill, ipha, mp, mp);
16598 
16599 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16600 
16601 	if (mp == NULL)
16602 		return;
16603 	pkt_len = ntohs(ipha->ipha_length);
16604 
16605 	if (is_system_labeled()) {
16606 		mblk_t *mp1;
16607 
16608 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16609 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16610 			goto drop_pkt;
16611 		}
16612 		/* Size may have changed */
16613 		mp = mp1;
16614 		ipha = (ipha_t *)mp->b_rptr;
16615 		pkt_len = ntohs(ipha->ipha_length);
16616 	}
16617 
16618 	/* Check if there are options to update */
16619 	if (!IS_SIMPLE_IPH(ipha)) {
16620 		if (ip_csum_hdr(ipha)) {
16621 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16622 			goto drop_pkt;
16623 		}
16624 		if (ip_rput_forward_options(mp, ipha, ire)) {
16625 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16626 			return;
16627 		}
16628 
16629 		ipha->ipha_hdr_checksum = 0;
16630 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16631 	}
16632 	max_frag = ire->ire_max_frag;
16633 	if (pkt_len > max_frag) {
16634 		/*
16635 		 * It needs fragging on its way out.  We haven't
16636 		 * verified the header checksum yet.  Since we
16637 		 * are going to put a surely good checksum in the
16638 		 * outgoing header, we have to make sure that it
16639 		 * was good coming in.
16640 		 */
16641 		if (ip_csum_hdr(ipha)) {
16642 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16643 			goto drop_pkt;
16644 		}
16645 		/* Initiate Write side IPPF processing */
16646 		if (IPP_ENABLED(IPP_FWD_OUT)) {
16647 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16648 			if (mp == NULL) {
16649 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16650 				    " during IPPF processing\n"));
16651 				return;
16652 			}
16653 		}
16654 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID);
16655 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16656 		return;
16657 	}
16658 
16659 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16660 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16661 	FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
16662 	    NULL, out_ill, ipha, mp, mp);
16663 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16664 	if (mp == NULL)
16665 		return;
16666 
16667 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16668 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16669 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16670 	/* ip_xmit_v4 always consumes the packet */
16671 	return;
16672 
16673 drop_pkt:;
16674 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16675 	freemsg(mp);
16676 #undef	rptr
16677 }
16678 
16679 void
16680 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16681 {
16682 	ire_t	*ire;
16683 
16684 	ASSERT(!ipif->ipif_isv6);
16685 	/*
16686 	 * Find an IRE which matches the destination and the outgoing
16687 	 * queue in the cache table. All we need is an IRE_CACHE which
16688 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16689 	 * then it is enough to have some IRE_CACHE in the group.
16690 	 */
16691 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16692 		dst = ipif->ipif_pp_dst_addr;
16693 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16694 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR);
16695 	if (ire == NULL) {
16696 		/*
16697 		 * Mark this packet to make it be delivered to
16698 		 * ip_rput_forward after the new ire has been
16699 		 * created.
16700 		 */
16701 		mp->b_prev = NULL;
16702 		mp->b_next = mp;
16703 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16704 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16705 	} else {
16706 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16707 		IRE_REFRELE(ire);
16708 	}
16709 }
16710 
16711 /* Update any source route, record route or timestamp options */
16712 static int
16713 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire)
16714 {
16715 	ipoptp_t	opts;
16716 	uchar_t		*opt;
16717 	uint8_t		optval;
16718 	uint8_t		optlen;
16719 	ipaddr_t	dst;
16720 	uint32_t	ts;
16721 	ire_t		*dst_ire = NULL;
16722 	ire_t		*tmp_ire = NULL;
16723 	timestruc_t	now;
16724 
16725 	ip2dbg(("ip_rput_forward_options\n"));
16726 	dst = ipha->ipha_dst;
16727 	for (optval = ipoptp_first(&opts, ipha);
16728 	    optval != IPOPT_EOL;
16729 	    optval = ipoptp_next(&opts)) {
16730 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16731 		opt = opts.ipoptp_cur;
16732 		optlen = opts.ipoptp_len;
16733 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16734 		    optval, opts.ipoptp_len));
16735 		switch (optval) {
16736 			uint32_t off;
16737 		case IPOPT_SSRR:
16738 		case IPOPT_LSRR:
16739 			/* Check if adminstratively disabled */
16740 			if (!ip_forward_src_routed) {
16741 				if (ire->ire_stq != NULL) {
16742 					/*
16743 					 * Sent by forwarding path, and router
16744 					 * is global zone
16745 					 */
16746 					icmp_unreachable(ire->ire_stq, mp,
16747 					    ICMP_SOURCE_ROUTE_FAILED,
16748 					    GLOBAL_ZONEID);
16749 				} else {
16750 					ip0dbg(("ip_rput_forward_options: "
16751 					    "unable to send unreach\n"));
16752 					freemsg(mp);
16753 				}
16754 				return (-1);
16755 			}
16756 
16757 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16758 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16759 			if (dst_ire == NULL) {
16760 				/*
16761 				 * Must be partial since ip_rput_options
16762 				 * checked for strict.
16763 				 */
16764 				break;
16765 			}
16766 			off = opt[IPOPT_OFFSET];
16767 			off--;
16768 		redo_srr:
16769 			if (optlen < IP_ADDR_LEN ||
16770 			    off > optlen - IP_ADDR_LEN) {
16771 				/* End of source route */
16772 				ip1dbg((
16773 				    "ip_rput_forward_options: end of SR\n"));
16774 				ire_refrele(dst_ire);
16775 				break;
16776 			}
16777 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16778 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16779 			    IP_ADDR_LEN);
16780 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16781 			    ntohl(dst)));
16782 
16783 			/*
16784 			 * Check if our address is present more than
16785 			 * once as consecutive hops in source route.
16786 			 */
16787 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16788 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
16789 			if (tmp_ire != NULL) {
16790 				ire_refrele(tmp_ire);
16791 				off += IP_ADDR_LEN;
16792 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16793 				goto redo_srr;
16794 			}
16795 			ipha->ipha_dst = dst;
16796 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16797 			ire_refrele(dst_ire);
16798 			break;
16799 		case IPOPT_RR:
16800 			off = opt[IPOPT_OFFSET];
16801 			off--;
16802 			if (optlen < IP_ADDR_LEN ||
16803 			    off > optlen - IP_ADDR_LEN) {
16804 				/* No more room - ignore */
16805 				ip1dbg((
16806 				    "ip_rput_forward_options: end of RR\n"));
16807 				break;
16808 			}
16809 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16810 			    IP_ADDR_LEN);
16811 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16812 			break;
16813 		case IPOPT_TS:
16814 			/* Insert timestamp if there is room */
16815 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16816 			case IPOPT_TS_TSONLY:
16817 				off = IPOPT_TS_TIMELEN;
16818 				break;
16819 			case IPOPT_TS_PRESPEC:
16820 			case IPOPT_TS_PRESPEC_RFC791:
16821 				/* Verify that the address matched */
16822 				off = opt[IPOPT_OFFSET] - 1;
16823 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16824 				dst_ire = ire_ctable_lookup(dst, 0,
16825 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16826 				    MATCH_IRE_TYPE);
16827 
16828 				if (dst_ire == NULL) {
16829 					/* Not for us */
16830 					break;
16831 				}
16832 				ire_refrele(dst_ire);
16833 				/* FALLTHRU */
16834 			case IPOPT_TS_TSANDADDR:
16835 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16836 				break;
16837 			default:
16838 				/*
16839 				 * ip_*put_options should have already
16840 				 * dropped this packet.
16841 				 */
16842 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16843 				    "unknown IT - bug in ip_rput_options?\n");
16844 				return (0);	/* Keep "lint" happy */
16845 			}
16846 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16847 				/* Increase overflow counter */
16848 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16849 				opt[IPOPT_POS_OV_FLG] =
16850 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16851 				    (off << 4));
16852 				break;
16853 			}
16854 			off = opt[IPOPT_OFFSET] - 1;
16855 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16856 			case IPOPT_TS_PRESPEC:
16857 			case IPOPT_TS_PRESPEC_RFC791:
16858 			case IPOPT_TS_TSANDADDR:
16859 				bcopy(&ire->ire_src_addr,
16860 				    (char *)opt + off, IP_ADDR_LEN);
16861 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16862 				/* FALLTHRU */
16863 			case IPOPT_TS_TSONLY:
16864 				off = opt[IPOPT_OFFSET] - 1;
16865 				/* Compute # of milliseconds since midnight */
16866 				gethrestime(&now);
16867 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16868 				    now.tv_nsec / (NANOSEC / MILLISEC);
16869 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16870 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16871 				break;
16872 			}
16873 			break;
16874 		}
16875 	}
16876 	return (0);
16877 }
16878 
16879 /*
16880  * This is called after processing at least one of AH/ESP headers.
16881  *
16882  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16883  * the actual, physical interface on which the packet was received,
16884  * but, when ip_strict_dst_multihoming is set to 1, could be the
16885  * interface which had the ipha_dst configured when the packet went
16886  * through ip_rput. The ill_index corresponding to the recv_ill
16887  * is saved in ipsec_in_rill_index
16888  */
16889 void
16890 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16891 {
16892 	mblk_t *mp;
16893 	ipaddr_t dst;
16894 	in6_addr_t *v6dstp;
16895 	ipha_t *ipha;
16896 	ip6_t *ip6h;
16897 	ipsec_in_t *ii;
16898 	boolean_t ill_need_rele = B_FALSE;
16899 	boolean_t rill_need_rele = B_FALSE;
16900 	boolean_t ire_need_rele = B_FALSE;
16901 
16902 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16903 	ASSERT(ii->ipsec_in_ill_index != 0);
16904 
16905 	mp = ipsec_mp->b_cont;
16906 	ASSERT(mp != NULL);
16907 
16908 
16909 	if (ill == NULL) {
16910 		ASSERT(recv_ill == NULL);
16911 		/*
16912 		 * We need to get the original queue on which ip_rput_local
16913 		 * or ip_rput_data_v6 was called.
16914 		 */
16915 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16916 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL);
16917 		ill_need_rele = B_TRUE;
16918 
16919 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16920 			recv_ill = ill_lookup_on_ifindex(
16921 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16922 			    NULL, NULL, NULL, NULL);
16923 			rill_need_rele = B_TRUE;
16924 		} else {
16925 			recv_ill = ill;
16926 		}
16927 
16928 		if ((ill == NULL) || (recv_ill == NULL)) {
16929 			ip0dbg(("ip_fanout_proto_again: interface "
16930 			    "disappeared\n"));
16931 			if (ill != NULL)
16932 				ill_refrele(ill);
16933 			if (recv_ill != NULL)
16934 				ill_refrele(recv_ill);
16935 			freemsg(ipsec_mp);
16936 			return;
16937 		}
16938 	}
16939 
16940 	ASSERT(ill != NULL && recv_ill != NULL);
16941 
16942 	if (mp->b_datap->db_type == M_CTL) {
16943 		/*
16944 		 * AH/ESP is returning the ICMP message after
16945 		 * removing their headers. Fanout again till
16946 		 * it gets to the right protocol.
16947 		 */
16948 		if (ii->ipsec_in_v4) {
16949 			icmph_t *icmph;
16950 			int iph_hdr_length;
16951 			int hdr_length;
16952 
16953 			ipha = (ipha_t *)mp->b_rptr;
16954 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16955 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16956 			ipha = (ipha_t *)&icmph[1];
16957 			hdr_length = IPH_HDR_LENGTH(ipha);
16958 			/*
16959 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16960 			 * Reset the type to M_DATA.
16961 			 */
16962 			mp->b_datap->db_type = M_DATA;
16963 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16964 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16965 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16966 		} else {
16967 			icmp6_t *icmp6;
16968 			int hdr_length;
16969 
16970 			ip6h = (ip6_t *)mp->b_rptr;
16971 			/* Don't call hdr_length_v6() unless you have to. */
16972 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16973 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16974 			else
16975 				hdr_length = IPV6_HDR_LEN;
16976 
16977 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16978 			/*
16979 			 * icmp_inbound_error_fanout_v6 may need to do
16980 			 * pullupmsg.  Reset the type to M_DATA.
16981 			 */
16982 			mp->b_datap->db_type = M_DATA;
16983 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16984 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16985 		}
16986 		if (ill_need_rele)
16987 			ill_refrele(ill);
16988 		if (rill_need_rele)
16989 			ill_refrele(recv_ill);
16990 		return;
16991 	}
16992 
16993 	if (ii->ipsec_in_v4) {
16994 		ipha = (ipha_t *)mp->b_rptr;
16995 		dst = ipha->ipha_dst;
16996 		if (CLASSD(dst)) {
16997 			/*
16998 			 * Multicast has to be delivered to all streams.
16999 			 */
17000 			dst = INADDR_BROADCAST;
17001 		}
17002 
17003 		if (ire == NULL) {
17004 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17005 			    MBLK_GETLABEL(mp));
17006 			if (ire == NULL) {
17007 				if (ill_need_rele)
17008 					ill_refrele(ill);
17009 				if (rill_need_rele)
17010 					ill_refrele(recv_ill);
17011 				ip1dbg(("ip_fanout_proto_again: "
17012 				    "IRE not found"));
17013 				freemsg(ipsec_mp);
17014 				return;
17015 			}
17016 			ire_need_rele = B_TRUE;
17017 		}
17018 
17019 		switch (ipha->ipha_protocol) {
17020 			case IPPROTO_UDP:
17021 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17022 				    recv_ill);
17023 				if (ire_need_rele)
17024 					ire_refrele(ire);
17025 				break;
17026 			case IPPROTO_TCP:
17027 				if (!ire_need_rele)
17028 					IRE_REFHOLD(ire);
17029 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17030 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17031 				IRE_REFRELE(ire);
17032 				if (mp != NULL)
17033 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17034 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17035 				break;
17036 			case IPPROTO_SCTP:
17037 				if (!ire_need_rele)
17038 					IRE_REFHOLD(ire);
17039 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17040 				    ipsec_mp, 0, ill->ill_rq, dst);
17041 				break;
17042 			default:
17043 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17044 				    recv_ill);
17045 				if (ire_need_rele)
17046 					ire_refrele(ire);
17047 				break;
17048 		}
17049 	} else {
17050 		uint32_t rput_flags = 0;
17051 
17052 		ip6h = (ip6_t *)mp->b_rptr;
17053 		v6dstp = &ip6h->ip6_dst;
17054 		/*
17055 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17056 		 * address.
17057 		 *
17058 		 * Currently, we don't store that state in the IPSEC_IN
17059 		 * message, and we may need to.
17060 		 */
17061 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17062 		    IP6_IN_LLMCAST : 0);
17063 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17064 		    NULL, NULL);
17065 	}
17066 	if (ill_need_rele)
17067 		ill_refrele(ill);
17068 	if (rill_need_rele)
17069 		ill_refrele(recv_ill);
17070 }
17071 
17072 /*
17073  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17074  * returns 'true' if there are still fragments left on the queue, in
17075  * which case we restart the timer.
17076  */
17077 void
17078 ill_frag_timer(void *arg)
17079 {
17080 	ill_t	*ill = (ill_t *)arg;
17081 	boolean_t frag_pending;
17082 
17083 	mutex_enter(&ill->ill_lock);
17084 	ASSERT(!ill->ill_fragtimer_executing);
17085 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17086 		ill->ill_frag_timer_id = 0;
17087 		mutex_exit(&ill->ill_lock);
17088 		return;
17089 	}
17090 	ill->ill_fragtimer_executing = 1;
17091 	mutex_exit(&ill->ill_lock);
17092 
17093 	frag_pending = ill_frag_timeout(ill, ip_g_frag_timeout);
17094 
17095 	/*
17096 	 * Restart the timer, if we have fragments pending or if someone
17097 	 * wanted us to be scheduled again.
17098 	 */
17099 	mutex_enter(&ill->ill_lock);
17100 	ill->ill_fragtimer_executing = 0;
17101 	ill->ill_frag_timer_id = 0;
17102 	if (frag_pending || ill->ill_fragtimer_needrestart)
17103 		ill_frag_timer_start(ill);
17104 	mutex_exit(&ill->ill_lock);
17105 }
17106 
17107 void
17108 ill_frag_timer_start(ill_t *ill)
17109 {
17110 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17111 
17112 	/* If the ill is closing or opening don't proceed */
17113 	if (ill->ill_state_flags & ILL_CONDEMNED)
17114 		return;
17115 
17116 	if (ill->ill_fragtimer_executing) {
17117 		/*
17118 		 * ill_frag_timer is currently executing. Just record the
17119 		 * the fact that we want the timer to be restarted.
17120 		 * ill_frag_timer will post a timeout before it returns,
17121 		 * ensuring it will be called again.
17122 		 */
17123 		ill->ill_fragtimer_needrestart = 1;
17124 		return;
17125 	}
17126 
17127 	if (ill->ill_frag_timer_id == 0) {
17128 		/*
17129 		 * The timer is neither running nor is the timeout handler
17130 		 * executing. Post a timeout so that ill_frag_timer will be
17131 		 * called
17132 		 */
17133 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17134 		    MSEC_TO_TICK(ip_g_frag_timo_ms >> 1));
17135 		ill->ill_fragtimer_needrestart = 0;
17136 	}
17137 }
17138 
17139 /*
17140  * This routine is needed for loopback when forwarding multicasts.
17141  *
17142  * IPQoS Notes:
17143  * IPPF processing is done in fanout routines.
17144  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17145  * processing for IPSec packets is done when it comes back in clear.
17146  * NOTE : The callers of this function need to do the ire_refrele for the
17147  *	  ire that is being passed in.
17148  */
17149 void
17150 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17151     ill_t *recv_ill)
17152 {
17153 	ill_t	*ill = (ill_t *)q->q_ptr;
17154 	uint32_t	sum;
17155 	uint32_t	u1;
17156 	uint32_t	u2;
17157 	int		hdr_length;
17158 	boolean_t	mctl_present;
17159 	mblk_t		*first_mp = mp;
17160 	mblk_t		*hada_mp = NULL;
17161 	ipha_t		*inner_ipha;
17162 
17163 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17164 	    "ip_rput_locl_start: q %p", q);
17165 
17166 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17167 	ASSERT(ill != NULL);
17168 
17169 
17170 #define	rptr	((uchar_t *)ipha)
17171 #define	iphs	((uint16_t *)ipha)
17172 
17173 	/*
17174 	 * no UDP or TCP packet should come here anymore.
17175 	 */
17176 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17177 	    (ipha->ipha_protocol != IPPROTO_UDP));
17178 
17179 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17180 	if (mctl_present &&
17181 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17182 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17183 
17184 		/*
17185 		 * It's an IPsec accelerated packet.
17186 		 * Keep a pointer to the data attributes around until
17187 		 * we allocate the ipsec_info_t.
17188 		 */
17189 		IPSECHW_DEBUG(IPSECHW_PKT,
17190 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17191 		hada_mp = first_mp;
17192 		hada_mp->b_cont = NULL;
17193 		/*
17194 		 * Since it is accelerated, it comes directly from
17195 		 * the ill and the data attributes is followed by
17196 		 * the packet data.
17197 		 */
17198 		ASSERT(mp->b_datap->db_type != M_CTL);
17199 		first_mp = mp;
17200 		mctl_present = B_FALSE;
17201 	}
17202 
17203 	/*
17204 	 * IF M_CTL is not present, then ipsec_in_is_secure
17205 	 * should return B_TRUE. There is a case where loopback
17206 	 * packets has an M_CTL in the front with all the
17207 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17208 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17209 	 * packets never comes here, it is safe to ASSERT the
17210 	 * following.
17211 	 */
17212 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17213 
17214 
17215 	/* u1 is # words of IP options */
17216 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17217 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17218 
17219 	if (u1) {
17220 		if (!ip_options_cksum(q, ill, mp, ipha, ire)) {
17221 			if (hada_mp != NULL)
17222 				freemsg(hada_mp);
17223 			return;
17224 		}
17225 	} else {
17226 		/* Check the IP header checksum.  */
17227 #define	uph	((uint16_t *)ipha)
17228 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17229 		    uph[6] + uph[7] + uph[8] + uph[9];
17230 #undef  uph
17231 		/* finish doing IP checksum */
17232 		sum = (sum & 0xFFFF) + (sum >> 16);
17233 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17234 		/*
17235 		 * Don't verify header checksum if this packet is coming
17236 		 * back from AH/ESP as we already did it.
17237 		 */
17238 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17239 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17240 			goto drop_pkt;
17241 		}
17242 	}
17243 
17244 	/*
17245 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17246 	 * might be called more than once for secure packets, count only
17247 	 * the first time.
17248 	 */
17249 	if (!mctl_present) {
17250 		UPDATE_IB_PKT_COUNT(ire);
17251 		ire->ire_last_used_time = lbolt;
17252 	}
17253 
17254 	/* Check for fragmentation offset. */
17255 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17256 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17257 	if (u1) {
17258 		/*
17259 		 * We re-assemble fragments before we do the AH/ESP
17260 		 * processing. Thus, M_CTL should not be present
17261 		 * while we are re-assembling.
17262 		 */
17263 		ASSERT(!mctl_present);
17264 		ASSERT(first_mp == mp);
17265 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17266 			return;
17267 		}
17268 		/*
17269 		 * Make sure that first_mp points back to mp as
17270 		 * the mp we came in with could have changed in
17271 		 * ip_rput_fragment().
17272 		 */
17273 		ipha = (ipha_t *)mp->b_rptr;
17274 		first_mp = mp;
17275 	}
17276 
17277 	/*
17278 	 * Clear hardware checksumming flag as it is currently only
17279 	 * used by TCP and UDP.
17280 	 */
17281 	DB_CKSUMFLAGS(mp) = 0;
17282 
17283 	/* Now we have a complete datagram, destined for this machine. */
17284 	u1 = IPH_HDR_LENGTH(ipha);
17285 	switch (ipha->ipha_protocol) {
17286 	case IPPROTO_ICMP: {
17287 		ire_t		*ire_zone;
17288 		ilm_t		*ilm;
17289 		mblk_t		*mp1;
17290 		zoneid_t	last_zoneid;
17291 
17292 		if (CLASSD(ipha->ipha_dst) &&
17293 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17294 			ASSERT(ire->ire_type == IRE_BROADCAST);
17295 			/*
17296 			 * In the multicast case, applications may have joined
17297 			 * the group from different zones, so we need to deliver
17298 			 * the packet to each of them. Loop through the
17299 			 * multicast memberships structures (ilm) on the receive
17300 			 * ill and send a copy of the packet up each matching
17301 			 * one. However, we don't do this for multicasts sent on
17302 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17303 			 * they must stay in the sender's zone.
17304 			 *
17305 			 * ilm_add_v6() ensures that ilms in the same zone are
17306 			 * contiguous in the ill_ilm list. We use this property
17307 			 * to avoid sending duplicates needed when two
17308 			 * applications in the same zone join the same group on
17309 			 * different logical interfaces: we ignore the ilm if
17310 			 * its zoneid is the same as the last matching one.
17311 			 * In addition, the sending of the packet for
17312 			 * ire_zoneid is delayed until all of the other ilms
17313 			 * have been exhausted.
17314 			 */
17315 			last_zoneid = -1;
17316 			ILM_WALKER_HOLD(recv_ill);
17317 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17318 			    ilm = ilm->ilm_next) {
17319 				if ((ilm->ilm_flags & ILM_DELETED) ||
17320 				    ipha->ipha_dst != ilm->ilm_addr ||
17321 				    ilm->ilm_zoneid == last_zoneid ||
17322 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17323 				    ilm->ilm_zoneid == ALL_ZONES ||
17324 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17325 					continue;
17326 				mp1 = ip_copymsg(first_mp);
17327 				if (mp1 == NULL)
17328 					continue;
17329 				icmp_inbound(q, mp1, B_TRUE, ill,
17330 				    0, sum, mctl_present, B_TRUE,
17331 				    recv_ill, ilm->ilm_zoneid);
17332 				last_zoneid = ilm->ilm_zoneid;
17333 			}
17334 			ILM_WALKER_RELE(recv_ill);
17335 		} else if (ire->ire_type == IRE_BROADCAST) {
17336 			/*
17337 			 * In the broadcast case, there may be many zones
17338 			 * which need a copy of the packet delivered to them.
17339 			 * There is one IRE_BROADCAST per broadcast address
17340 			 * and per zone; we walk those using a helper function.
17341 			 * In addition, the sending of the packet for ire is
17342 			 * delayed until all of the other ires have been
17343 			 * processed.
17344 			 */
17345 			IRB_REFHOLD(ire->ire_bucket);
17346 			ire_zone = NULL;
17347 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17348 			    ire)) != NULL) {
17349 				mp1 = ip_copymsg(first_mp);
17350 				if (mp1 == NULL)
17351 					continue;
17352 
17353 				UPDATE_IB_PKT_COUNT(ire_zone);
17354 				ire_zone->ire_last_used_time = lbolt;
17355 				icmp_inbound(q, mp1, B_TRUE, ill,
17356 				    0, sum, mctl_present, B_TRUE,
17357 				    recv_ill, ire_zone->ire_zoneid);
17358 			}
17359 			IRB_REFRELE(ire->ire_bucket);
17360 		}
17361 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17362 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17363 		    ire->ire_zoneid);
17364 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17365 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17366 		return;
17367 	}
17368 	case IPPROTO_IGMP:
17369 		/*
17370 		 * If we are not willing to accept IGMP packets in clear,
17371 		 * then check with global policy.
17372 		 */
17373 		if (igmp_accept_clear_messages == 0) {
17374 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17375 			    ipha, NULL, mctl_present);
17376 			if (first_mp == NULL)
17377 				return;
17378 		}
17379 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17380 			freemsg(first_mp);
17381 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17382 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17383 			return;
17384 		}
17385 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17386 			/* Bad packet - discarded by igmp_input */
17387 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17388 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17389 			if (mctl_present)
17390 				freeb(first_mp);
17391 			return;
17392 		}
17393 		/*
17394 		 * igmp_input() may have returned the pulled up message.
17395 		 * So first_mp and ipha need to be reinitialized.
17396 		 */
17397 		ipha = (ipha_t *)mp->b_rptr;
17398 		if (mctl_present)
17399 			first_mp->b_cont = mp;
17400 		else
17401 			first_mp = mp;
17402 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17403 			/* No user-level listener for IGMP packets */
17404 			goto drop_pkt;
17405 		}
17406 		/* deliver to local raw users */
17407 		break;
17408 	case IPPROTO_PIM:
17409 		/*
17410 		 * If we are not willing to accept PIM packets in clear,
17411 		 * then check with global policy.
17412 		 */
17413 		if (pim_accept_clear_messages == 0) {
17414 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17415 			    ipha, NULL, mctl_present);
17416 			if (first_mp == NULL)
17417 				return;
17418 		}
17419 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17420 			freemsg(first_mp);
17421 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17422 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17423 			return;
17424 		}
17425 		if (pim_input(q, mp) != 0) {
17426 			/* Bad packet - discarded by pim_input */
17427 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17428 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17429 			if (mctl_present)
17430 				freeb(first_mp);
17431 			return;
17432 		}
17433 
17434 		/*
17435 		 * pim_input() may have pulled up the message so ipha needs to
17436 		 * be reinitialized.
17437 		 */
17438 		ipha = (ipha_t *)mp->b_rptr;
17439 		if (ipcl_proto_search(ipha->ipha_protocol) == NULL) {
17440 			/* No user-level listener for PIM packets */
17441 			goto drop_pkt;
17442 		}
17443 		/* deliver to local raw users */
17444 		break;
17445 	case IPPROTO_ENCAP:
17446 		/*
17447 		 * Handle self-encapsulated packets (IP-in-IP where
17448 		 * the inner addresses == the outer addresses).
17449 		 */
17450 		hdr_length = IPH_HDR_LENGTH(ipha);
17451 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17452 		    mp->b_wptr) {
17453 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17454 			    sizeof (ipha_t) - mp->b_rptr)) {
17455 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17456 				freemsg(first_mp);
17457 				return;
17458 			}
17459 			ipha = (ipha_t *)mp->b_rptr;
17460 		}
17461 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17462 		/*
17463 		 * Check the sanity of the inner IP header.
17464 		 */
17465 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17466 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17467 			freemsg(first_mp);
17468 			return;
17469 		}
17470 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17471 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17472 			freemsg(first_mp);
17473 			return;
17474 		}
17475 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17476 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17477 			ipsec_in_t *ii;
17478 
17479 			/*
17480 			 * Self-encapsulated tunnel packet. Remove
17481 			 * the outer IP header and fanout again.
17482 			 * We also need to make sure that the inner
17483 			 * header is pulled up until options.
17484 			 */
17485 			mp->b_rptr = (uchar_t *)inner_ipha;
17486 			ipha = inner_ipha;
17487 			hdr_length = IPH_HDR_LENGTH(ipha);
17488 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17489 				if (!pullupmsg(mp, (uchar_t *)ipha +
17490 				    + hdr_length - mp->b_rptr)) {
17491 					freemsg(first_mp);
17492 					return;
17493 				}
17494 				ipha = (ipha_t *)mp->b_rptr;
17495 			}
17496 			if (!mctl_present) {
17497 				ASSERT(first_mp == mp);
17498 				/*
17499 				 * This means that somebody is sending
17500 				 * Self-encapsualted packets without AH/ESP.
17501 				 * If AH/ESP was present, we would have already
17502 				 * allocated the first_mp.
17503 				 */
17504 				if ((first_mp = ipsec_in_alloc(B_TRUE)) ==
17505 				    NULL) {
17506 					ip1dbg(("ip_proto_input: IPSEC_IN "
17507 					    "allocation failure.\n"));
17508 					BUMP_MIB(ill->ill_ip_mib,
17509 					    ipIfStatsInDiscards);
17510 					freemsg(mp);
17511 					return;
17512 				}
17513 				first_mp->b_cont = mp;
17514 			}
17515 			/*
17516 			 * We generally store the ill_index if we need to
17517 			 * do IPSEC processing as we lose the ill queue when
17518 			 * we come back. But in this case, we never should
17519 			 * have to store the ill_index here as it should have
17520 			 * been stored previously when we processed the
17521 			 * AH/ESP header in this routine or for non-ipsec
17522 			 * cases, we still have the queue. But for some bad
17523 			 * packets from the wire, we can get to IPSEC after
17524 			 * this and we better store the index for that case.
17525 			 */
17526 			ill = (ill_t *)q->q_ptr;
17527 			ii = (ipsec_in_t *)first_mp->b_rptr;
17528 			ii->ipsec_in_ill_index =
17529 			    ill->ill_phyint->phyint_ifindex;
17530 			ii->ipsec_in_rill_index =
17531 			    recv_ill->ill_phyint->phyint_ifindex;
17532 			if (ii->ipsec_in_decaps) {
17533 				/*
17534 				 * This packet is self-encapsulated multiple
17535 				 * times. We don't want to recurse infinitely.
17536 				 * To keep it simple, drop the packet.
17537 				 */
17538 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17539 				freemsg(first_mp);
17540 				return;
17541 			}
17542 			ii->ipsec_in_decaps = B_TRUE;
17543 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17544 			    ire);
17545 			return;
17546 		}
17547 		break;
17548 	case IPPROTO_AH:
17549 	case IPPROTO_ESP: {
17550 		/*
17551 		 * Fast path for AH/ESP. If this is the first time
17552 		 * we are sending a datagram to AH/ESP, allocate
17553 		 * a IPSEC_IN message and prepend it. Otherwise,
17554 		 * just fanout.
17555 		 */
17556 
17557 		int ipsec_rc;
17558 		ipsec_in_t *ii;
17559 
17560 		IP_STAT(ipsec_proto_ahesp);
17561 		if (!mctl_present) {
17562 			ASSERT(first_mp == mp);
17563 			if ((first_mp = ipsec_in_alloc(B_TRUE)) == NULL) {
17564 				ip1dbg(("ip_proto_input: IPSEC_IN "
17565 				    "allocation failure.\n"));
17566 				freemsg(hada_mp); /* okay ifnull */
17567 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17568 				freemsg(mp);
17569 				return;
17570 			}
17571 			/*
17572 			 * Store the ill_index so that when we come back
17573 			 * from IPSEC we ride on the same queue.
17574 			 */
17575 			ill = (ill_t *)q->q_ptr;
17576 			ii = (ipsec_in_t *)first_mp->b_rptr;
17577 			ii->ipsec_in_ill_index =
17578 			    ill->ill_phyint->phyint_ifindex;
17579 			ii->ipsec_in_rill_index =
17580 			    recv_ill->ill_phyint->phyint_ifindex;
17581 			first_mp->b_cont = mp;
17582 			/*
17583 			 * Cache hardware acceleration info.
17584 			 */
17585 			if (hada_mp != NULL) {
17586 				IPSECHW_DEBUG(IPSECHW_PKT,
17587 				    ("ip_rput_local: caching data attr.\n"));
17588 				ii->ipsec_in_accelerated = B_TRUE;
17589 				ii->ipsec_in_da = hada_mp;
17590 				hada_mp = NULL;
17591 			}
17592 		} else {
17593 			ii = (ipsec_in_t *)first_mp->b_rptr;
17594 		}
17595 
17596 		if (!ipsec_loaded()) {
17597 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17598 			    ire->ire_zoneid);
17599 			return;
17600 		}
17601 
17602 		/* select inbound SA and have IPsec process the pkt */
17603 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17604 			esph_t *esph = ipsec_inbound_esp_sa(first_mp);
17605 			if (esph == NULL)
17606 				return;
17607 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17608 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17609 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17610 			    first_mp, esph);
17611 		} else {
17612 			ah_t *ah = ipsec_inbound_ah_sa(first_mp);
17613 			if (ah == NULL)
17614 				return;
17615 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17616 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17617 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17618 			    first_mp, ah);
17619 		}
17620 
17621 		switch (ipsec_rc) {
17622 		case IPSEC_STATUS_SUCCESS:
17623 			break;
17624 		case IPSEC_STATUS_FAILED:
17625 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17626 			/* FALLTHRU */
17627 		case IPSEC_STATUS_PENDING:
17628 			return;
17629 		}
17630 		/* we're done with IPsec processing, send it up */
17631 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17632 		return;
17633 	}
17634 	default:
17635 		break;
17636 	}
17637 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17638 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17639 		    ire->ire_zoneid));
17640 		goto drop_pkt;
17641 	}
17642 	/*
17643 	 * Handle protocols with which IP is less intimate.  There
17644 	 * can be more than one stream bound to a particular
17645 	 * protocol.  When this is the case, each one gets a copy
17646 	 * of any incoming packets.
17647 	 */
17648 	ip_fanout_proto(q, first_mp, ill, ipha,
17649 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17650 	    B_TRUE, recv_ill, ire->ire_zoneid);
17651 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17652 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17653 	return;
17654 
17655 drop_pkt:
17656 	freemsg(first_mp);
17657 	if (hada_mp != NULL)
17658 		freeb(hada_mp);
17659 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17660 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17661 #undef	rptr
17662 #undef  iphs
17663 
17664 }
17665 
17666 /*
17667  * Update any source route, record route or timestamp options.
17668  * Check that we are at end of strict source route.
17669  * The options have already been checked for sanity in ip_rput_options().
17670  */
17671 static boolean_t
17672 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire)
17673 {
17674 	ipoptp_t	opts;
17675 	uchar_t		*opt;
17676 	uint8_t		optval;
17677 	uint8_t		optlen;
17678 	ipaddr_t	dst;
17679 	uint32_t	ts;
17680 	ire_t		*dst_ire;
17681 	timestruc_t	now;
17682 	zoneid_t	zoneid;
17683 	ill_t		*ill;
17684 
17685 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17686 
17687 	ip2dbg(("ip_rput_local_options\n"));
17688 
17689 	for (optval = ipoptp_first(&opts, ipha);
17690 	    optval != IPOPT_EOL;
17691 	    optval = ipoptp_next(&opts)) {
17692 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17693 		opt = opts.ipoptp_cur;
17694 		optlen = opts.ipoptp_len;
17695 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17696 		    optval, optlen));
17697 		switch (optval) {
17698 			uint32_t off;
17699 		case IPOPT_SSRR:
17700 		case IPOPT_LSRR:
17701 			off = opt[IPOPT_OFFSET];
17702 			off--;
17703 			if (optlen < IP_ADDR_LEN ||
17704 			    off > optlen - IP_ADDR_LEN) {
17705 				/* End of source route */
17706 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17707 				break;
17708 			}
17709 			/*
17710 			 * This will only happen if two consecutive entries
17711 			 * in the source route contains our address or if
17712 			 * it is a packet with a loose source route which
17713 			 * reaches us before consuming the whole source route
17714 			 */
17715 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17716 			if (optval == IPOPT_SSRR) {
17717 				goto bad_src_route;
17718 			}
17719 			/*
17720 			 * Hack: instead of dropping the packet truncate the
17721 			 * source route to what has been used by filling the
17722 			 * rest with IPOPT_NOP.
17723 			 */
17724 			opt[IPOPT_OLEN] = (uint8_t)off;
17725 			while (off < optlen) {
17726 				opt[off++] = IPOPT_NOP;
17727 			}
17728 			break;
17729 		case IPOPT_RR:
17730 			off = opt[IPOPT_OFFSET];
17731 			off--;
17732 			if (optlen < IP_ADDR_LEN ||
17733 			    off > optlen - IP_ADDR_LEN) {
17734 				/* No more room - ignore */
17735 				ip1dbg((
17736 				    "ip_rput_local_options: end of RR\n"));
17737 				break;
17738 			}
17739 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17740 			    IP_ADDR_LEN);
17741 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17742 			break;
17743 		case IPOPT_TS:
17744 			/* Insert timestamp if there is romm */
17745 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17746 			case IPOPT_TS_TSONLY:
17747 				off = IPOPT_TS_TIMELEN;
17748 				break;
17749 			case IPOPT_TS_PRESPEC:
17750 			case IPOPT_TS_PRESPEC_RFC791:
17751 				/* Verify that the address matched */
17752 				off = opt[IPOPT_OFFSET] - 1;
17753 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17754 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17755 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
17756 				if (dst_ire == NULL) {
17757 					/* Not for us */
17758 					break;
17759 				}
17760 				ire_refrele(dst_ire);
17761 				/* FALLTHRU */
17762 			case IPOPT_TS_TSANDADDR:
17763 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17764 				break;
17765 			default:
17766 				/*
17767 				 * ip_*put_options should have already
17768 				 * dropped this packet.
17769 				 */
17770 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17771 				    "unknown IT - bug in ip_rput_options?\n");
17772 				return (B_TRUE);	/* Keep "lint" happy */
17773 			}
17774 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17775 				/* Increase overflow counter */
17776 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17777 				opt[IPOPT_POS_OV_FLG] =
17778 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17779 				    (off << 4));
17780 				break;
17781 			}
17782 			off = opt[IPOPT_OFFSET] - 1;
17783 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17784 			case IPOPT_TS_PRESPEC:
17785 			case IPOPT_TS_PRESPEC_RFC791:
17786 			case IPOPT_TS_TSANDADDR:
17787 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17788 				    IP_ADDR_LEN);
17789 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17790 				/* FALLTHRU */
17791 			case IPOPT_TS_TSONLY:
17792 				off = opt[IPOPT_OFFSET] - 1;
17793 				/* Compute # of milliseconds since midnight */
17794 				gethrestime(&now);
17795 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17796 				    now.tv_nsec / (NANOSEC / MILLISEC);
17797 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17798 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17799 				break;
17800 			}
17801 			break;
17802 		}
17803 	}
17804 	return (B_TRUE);
17805 
17806 bad_src_route:
17807 	q = WR(q);
17808 	if (q->q_next != NULL)
17809 		ill = q->q_ptr;
17810 	else
17811 		ill = NULL;
17812 
17813 	/* make sure we clear any indication of a hardware checksum */
17814 	DB_CKSUMFLAGS(mp) = 0;
17815 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill);
17816 	if (zoneid == ALL_ZONES)
17817 		freemsg(mp);
17818 	else
17819 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
17820 	return (B_FALSE);
17821 
17822 }
17823 
17824 /*
17825  * Process IP options in an inbound packet.  If an option affects the
17826  * effective destination address, return the next hop address via dstp.
17827  * Returns -1 if something fails in which case an ICMP error has been sent
17828  * and mp freed.
17829  */
17830 static int
17831 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp)
17832 {
17833 	ipoptp_t	opts;
17834 	uchar_t		*opt;
17835 	uint8_t		optval;
17836 	uint8_t		optlen;
17837 	ipaddr_t	dst;
17838 	intptr_t	code = 0;
17839 	ire_t		*ire = NULL;
17840 	zoneid_t	zoneid;
17841 	ill_t		*ill;
17842 
17843 	ip2dbg(("ip_rput_options\n"));
17844 	dst = ipha->ipha_dst;
17845 	for (optval = ipoptp_first(&opts, ipha);
17846 	    optval != IPOPT_EOL;
17847 	    optval = ipoptp_next(&opts)) {
17848 		opt = opts.ipoptp_cur;
17849 		optlen = opts.ipoptp_len;
17850 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17851 		    optval, optlen));
17852 		/*
17853 		 * Note: we need to verify the checksum before we
17854 		 * modify anything thus this routine only extracts the next
17855 		 * hop dst from any source route.
17856 		 */
17857 		switch (optval) {
17858 			uint32_t off;
17859 		case IPOPT_SSRR:
17860 		case IPOPT_LSRR:
17861 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17862 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17863 			if (ire == NULL) {
17864 				if (optval == IPOPT_SSRR) {
17865 					ip1dbg(("ip_rput_options: not next"
17866 					    " strict source route 0x%x\n",
17867 					    ntohl(dst)));
17868 					code = (char *)&ipha->ipha_dst -
17869 					    (char *)ipha;
17870 					goto param_prob; /* RouterReq's */
17871 				}
17872 				ip2dbg(("ip_rput_options: "
17873 				    "not next source route 0x%x\n",
17874 				    ntohl(dst)));
17875 				break;
17876 			}
17877 			ire_refrele(ire);
17878 
17879 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17880 				ip1dbg((
17881 				    "ip_rput_options: bad option offset\n"));
17882 				code = (char *)&opt[IPOPT_OLEN] -
17883 				    (char *)ipha;
17884 				goto param_prob;
17885 			}
17886 			off = opt[IPOPT_OFFSET];
17887 			off--;
17888 		redo_srr:
17889 			if (optlen < IP_ADDR_LEN ||
17890 			    off > optlen - IP_ADDR_LEN) {
17891 				/* End of source route */
17892 				ip1dbg(("ip_rput_options: end of SR\n"));
17893 				break;
17894 			}
17895 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17896 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17897 			    ntohl(dst)));
17898 
17899 			/*
17900 			 * Check if our address is present more than
17901 			 * once as consecutive hops in source route.
17902 			 * XXX verify per-interface ip_forwarding
17903 			 * for source route?
17904 			 */
17905 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17906 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
17907 
17908 			if (ire != NULL) {
17909 				ire_refrele(ire);
17910 				off += IP_ADDR_LEN;
17911 				goto redo_srr;
17912 			}
17913 
17914 			if (dst == htonl(INADDR_LOOPBACK)) {
17915 				ip1dbg(("ip_rput_options: loopback addr in "
17916 				    "source route!\n"));
17917 				goto bad_src_route;
17918 			}
17919 			/*
17920 			 * For strict: verify that dst is directly
17921 			 * reachable.
17922 			 */
17923 			if (optval == IPOPT_SSRR) {
17924 				ire = ire_ftable_lookup(dst, 0, 0,
17925 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17926 				    MBLK_GETLABEL(mp),
17927 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
17928 				if (ire == NULL) {
17929 					ip1dbg(("ip_rput_options: SSRR not "
17930 					    "directly reachable: 0x%x\n",
17931 					    ntohl(dst)));
17932 					goto bad_src_route;
17933 				}
17934 				ire_refrele(ire);
17935 			}
17936 			/*
17937 			 * Defer update of the offset and the record route
17938 			 * until the packet is forwarded.
17939 			 */
17940 			break;
17941 		case IPOPT_RR:
17942 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17943 				ip1dbg((
17944 				    "ip_rput_options: bad option offset\n"));
17945 				code = (char *)&opt[IPOPT_OLEN] -
17946 				    (char *)ipha;
17947 				goto param_prob;
17948 			}
17949 			break;
17950 		case IPOPT_TS:
17951 			/*
17952 			 * Verify that length >= 5 and that there is either
17953 			 * room for another timestamp or that the overflow
17954 			 * counter is not maxed out.
17955 			 */
17956 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17957 			if (optlen < IPOPT_MINLEN_IT) {
17958 				goto param_prob;
17959 			}
17960 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17961 				ip1dbg((
17962 				    "ip_rput_options: bad option offset\n"));
17963 				code = (char *)&opt[IPOPT_OFFSET] -
17964 				    (char *)ipha;
17965 				goto param_prob;
17966 			}
17967 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17968 			case IPOPT_TS_TSONLY:
17969 				off = IPOPT_TS_TIMELEN;
17970 				break;
17971 			case IPOPT_TS_TSANDADDR:
17972 			case IPOPT_TS_PRESPEC:
17973 			case IPOPT_TS_PRESPEC_RFC791:
17974 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17975 				break;
17976 			default:
17977 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17978 				    (char *)ipha;
17979 				goto param_prob;
17980 			}
17981 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17982 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17983 				/*
17984 				 * No room and the overflow counter is 15
17985 				 * already.
17986 				 */
17987 				goto param_prob;
17988 			}
17989 			break;
17990 		}
17991 	}
17992 
17993 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17994 		*dstp = dst;
17995 		return (0);
17996 	}
17997 
17998 	ip1dbg(("ip_rput_options: error processing IP options."));
17999 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18000 
18001 param_prob:
18002 	q = WR(q);
18003 	if (q->q_next != NULL)
18004 		ill = q->q_ptr;
18005 	else
18006 		ill = NULL;
18007 
18008 	/* make sure we clear any indication of a hardware checksum */
18009 	DB_CKSUMFLAGS(mp) = 0;
18010 	/* Don't know whether this is for non-global or global/forwarding */
18011 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
18012 	if (zoneid == ALL_ZONES)
18013 		freemsg(mp);
18014 	else
18015 		icmp_param_problem(q, mp, (uint8_t)code, zoneid);
18016 	return (-1);
18017 
18018 bad_src_route:
18019 	q = WR(q);
18020 	if (q->q_next != NULL)
18021 		ill = q->q_ptr;
18022 	else
18023 		ill = NULL;
18024 
18025 	/* make sure we clear any indication of a hardware checksum */
18026 	DB_CKSUMFLAGS(mp) = 0;
18027 	zoneid = ipif_lookup_addr_zoneid(dst, ill);
18028 	if (zoneid == ALL_ZONES)
18029 		freemsg(mp);
18030 	else
18031 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
18032 	return (-1);
18033 }
18034 
18035 /*
18036  * IP & ICMP info in >=14 msg's ...
18037  *  - ip fixed part (mib2_ip_t)
18038  *  - icmp fixed part (mib2_icmp_t)
18039  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18040  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18041  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18042  *  - ipRouteAttributeTable (ip 102)	labeled routes
18043  *  - ip multicast membership (ip_member_t)
18044  *  - ip multicast source filtering (ip_grpsrc_t)
18045  *  - igmp fixed part (struct igmpstat)
18046  *  - multicast routing stats (struct mrtstat)
18047  *  - multicast routing vifs (array of struct vifctl)
18048  *  - multicast routing routes (array of struct mfcctl)
18049  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18050  *					One per ill plus one generic
18051  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18052  *					One per ill plus one generic
18053  *  - ipv6RouteEntry			all IPv6 IREs
18054  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18055  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18056  *  - ipv6AddrEntry			all IPv6 ipifs
18057  *  - ipv6 multicast membership (ipv6_member_t)
18058  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18059  *
18060  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18061  *
18062  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18063  * already filled in by the caller.
18064  * Return value of 0 indicates that no messages were sent and caller
18065  * should free mpctl.
18066  */
18067 int
18068 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18069 {
18070 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18071 		return (0);
18072 	}
18073 
18074 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl)) == NULL) {
18075 		return (1);
18076 	}
18077 
18078 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl)) == NULL) {
18079 		return (1);
18080 	}
18081 
18082 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl)) == NULL) {
18083 		return (1);
18084 	}
18085 
18086 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl)) == NULL) {
18087 		return (1);
18088 	}
18089 
18090 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl)) == NULL) {
18091 		return (1);
18092 	}
18093 
18094 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl)) == NULL) {
18095 		return (1);
18096 	}
18097 
18098 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl)) == NULL) {
18099 		return (1);
18100 	}
18101 
18102 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl)) == NULL) {
18103 		return (1);
18104 	}
18105 
18106 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl)) == NULL) {
18107 		return (1);
18108 	}
18109 
18110 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl)) == NULL) {
18111 		return (1);
18112 	}
18113 
18114 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl)) == NULL) {
18115 		return (1);
18116 	}
18117 
18118 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl)) == NULL) {
18119 		return (1);
18120 	}
18121 
18122 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl)) == NULL) {
18123 		return (1);
18124 	}
18125 
18126 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl)) == NULL) {
18127 		return (1);
18128 	}
18129 
18130 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl)) == NULL) {
18131 		return (1);
18132 	}
18133 
18134 	if ((mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl)) == NULL) {
18135 		return (1);
18136 	}
18137 
18138 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl)) == NULL) {
18139 		return (1);
18140 	}
18141 	freemsg(mpctl);
18142 	return (1);
18143 }
18144 
18145 
18146 /* Get global (legacy) IPv4 statistics */
18147 static mblk_t *
18148 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib)
18149 {
18150 	mib2_ip_t		old_ip_mib;
18151 	struct opthdr		*optp;
18152 	mblk_t			*mp2ctl;
18153 
18154 	/*
18155 	 * make a copy of the original message
18156 	 */
18157 	mp2ctl = copymsg(mpctl);
18158 
18159 	/* fixed length IP structure... */
18160 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18161 	optp->level = MIB2_IP;
18162 	optp->name = 0;
18163 	SET_MIB(old_ip_mib.ipForwarding,
18164 	    (WE_ARE_FORWARDING ? 1 : 2));
18165 	SET_MIB(old_ip_mib.ipDefaultTTL,
18166 	    (uint32_t)ip_def_ttl);
18167 	SET_MIB(old_ip_mib.ipReasmTimeout,
18168 	    ip_g_frag_timeout);
18169 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18170 	    sizeof (mib2_ipAddrEntry_t));
18171 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18172 	    sizeof (mib2_ipRouteEntry_t));
18173 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18174 	    sizeof (mib2_ipNetToMediaEntry_t));
18175 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18176 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18177 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18178 	    sizeof (mib2_ipAttributeEntry_t));
18179 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18180 
18181 	/*
18182 	 * Grab the statistics from the new IP MIB
18183 	 */
18184 	SET_MIB(old_ip_mib.ipInReceives,
18185 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18186 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18187 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18188 	SET_MIB(old_ip_mib.ipForwDatagrams,
18189 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18190 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18191 	    ipmib->ipIfStatsInUnknownProtos);
18192 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18193 	SET_MIB(old_ip_mib.ipInDelivers,
18194 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18195 	SET_MIB(old_ip_mib.ipOutRequests,
18196 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18197 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18198 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18199 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18200 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18201 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18202 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18203 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18204 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18205 
18206 	/* ipRoutingDiscards is not being used */
18207 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18208 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18209 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18210 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18211 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18212 	    ipmib->ipIfStatsReasmDuplicates);
18213 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18214 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18215 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18216 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18217 	SET_MIB(old_ip_mib.rawipInOverflows,
18218 	    ipmib->rawipIfStatsInOverflows);
18219 
18220 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18221 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18222 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18223 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18224 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18225 	    ipmib->ipIfStatsOutSwitchIPVersion);
18226 
18227 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18228 	    (int)sizeof (old_ip_mib))) {
18229 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18230 		    (uint_t)sizeof (old_ip_mib)));
18231 	}
18232 
18233 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18234 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18235 	    (int)optp->level, (int)optp->name, (int)optp->len));
18236 	qreply(q, mpctl);
18237 	return (mp2ctl);
18238 }
18239 
18240 /* Per interface IPv4 statistics */
18241 static mblk_t *
18242 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl)
18243 {
18244 	struct opthdr		*optp;
18245 	mblk_t			*mp2ctl;
18246 	ill_t			*ill;
18247 	ill_walk_context_t	ctx;
18248 	mblk_t			*mp_tail = NULL;
18249 	mib2_ipIfStatsEntry_t	global_ip_mib;
18250 
18251 	/*
18252 	 * Make a copy of the original message
18253 	 */
18254 	mp2ctl = copymsg(mpctl);
18255 
18256 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18257 	optp->level = MIB2_IP;
18258 	optp->name = MIB2_IP_TRAFFIC_STATS;
18259 	/* Include "unknown interface" ip_mib */
18260 	ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18261 	ip_mib.ipIfStatsIfIndex = MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18262 	SET_MIB(ip_mib.ipIfStatsForwarding, (WE_ARE_FORWARDING ? 1 : 2));
18263 	SET_MIB(ip_mib.ipIfStatsDefaultTTL, (uint32_t)ip_def_ttl);
18264 	SET_MIB(ip_mib.ipIfStatsEntrySize, sizeof (mib2_ipIfStatsEntry_t));
18265 	SET_MIB(ip_mib.ipIfStatsAddrEntrySize, sizeof (mib2_ipAddrEntry_t));
18266 	SET_MIB(ip_mib.ipIfStatsRouteEntrySize, sizeof (mib2_ipRouteEntry_t));
18267 	SET_MIB(ip_mib.ipIfStatsNetToMediaEntrySize,
18268 	    sizeof (mib2_ipNetToMediaEntry_t));
18269 	SET_MIB(ip_mib.ipIfStatsMemberEntrySize, sizeof (ip_member_t));
18270 	SET_MIB(ip_mib.ipIfStatsGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18271 
18272 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip_mib,
18273 	    (int)sizeof (ip_mib))) {
18274 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18275 		    "failed to allocate %u bytes\n",
18276 		    (uint_t)sizeof (ip_mib)));
18277 	}
18278 
18279 	bcopy(&ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18280 
18281 	rw_enter(&ill_g_lock, RW_READER);
18282 	ill = ILL_START_WALK_V4(&ctx);
18283 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18284 		ill->ill_ip_mib->ipIfStatsIfIndex =
18285 		    ill->ill_phyint->phyint_ifindex;
18286 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18287 		    (WE_ARE_FORWARDING ? 1 : 2));
18288 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18289 		    (uint32_t)ip_def_ttl);
18290 
18291 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18292 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18293 		    (char *)ill->ill_ip_mib,
18294 		    (int)sizeof (*ill->ill_ip_mib))) {
18295 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18296 			    "failed to allocate %u bytes\n",
18297 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18298 		}
18299 	}
18300 	rw_exit(&ill_g_lock);
18301 
18302 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18303 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18304 	    "level %d, name %d, len %d\n",
18305 	    (int)optp->level, (int)optp->name, (int)optp->len));
18306 	qreply(q, mpctl);
18307 
18308 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib));
18309 }
18310 
18311 /* Global IPv4 ICMP statistics */
18312 static mblk_t *
18313 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl)
18314 {
18315 	struct opthdr		*optp;
18316 	mblk_t			*mp2ctl;
18317 
18318 	/*
18319 	 * Make a copy of the original message
18320 	 */
18321 	mp2ctl = copymsg(mpctl);
18322 
18323 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18324 	optp->level = MIB2_ICMP;
18325 	optp->name = 0;
18326 	if (!snmp_append_data(mpctl->b_cont, (char *)&icmp_mib,
18327 	    (int)sizeof (icmp_mib))) {
18328 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18329 		    (uint_t)sizeof (icmp_mib)));
18330 	}
18331 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18332 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18333 	    (int)optp->level, (int)optp->name, (int)optp->len));
18334 	qreply(q, mpctl);
18335 	return (mp2ctl);
18336 }
18337 
18338 /* Global IPv4 IGMP statistics */
18339 static mblk_t *
18340 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl)
18341 {
18342 	struct opthdr		*optp;
18343 	mblk_t			*mp2ctl;
18344 
18345 	/*
18346 	 * make a copy of the original message
18347 	 */
18348 	mp2ctl = copymsg(mpctl);
18349 
18350 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18351 	optp->level = EXPER_IGMP;
18352 	optp->name = 0;
18353 	if (!snmp_append_data(mpctl->b_cont, (char *)&igmpstat,
18354 	    (int)sizeof (igmpstat))) {
18355 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18356 		    (uint_t)sizeof (igmpstat)));
18357 	}
18358 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18359 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18360 	    (int)optp->level, (int)optp->name, (int)optp->len));
18361 	qreply(q, mpctl);
18362 	return (mp2ctl);
18363 }
18364 
18365 /* Global IPv4 Multicast Routing statistics */
18366 static mblk_t *
18367 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl)
18368 {
18369 	struct opthdr		*optp;
18370 	mblk_t			*mp2ctl;
18371 
18372 	/*
18373 	 * make a copy of the original message
18374 	 */
18375 	mp2ctl = copymsg(mpctl);
18376 
18377 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18378 	optp->level = EXPER_DVMRP;
18379 	optp->name = 0;
18380 	if (!ip_mroute_stats(mpctl->b_cont)) {
18381 		ip0dbg(("ip_mroute_stats: failed\n"));
18382 	}
18383 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18384 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18385 	    (int)optp->level, (int)optp->name, (int)optp->len));
18386 	qreply(q, mpctl);
18387 	return (mp2ctl);
18388 }
18389 
18390 /* IPv4 address information */
18391 static mblk_t *
18392 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl)
18393 {
18394 	struct opthdr		*optp;
18395 	mblk_t			*mp2ctl;
18396 	mblk_t			*mp_tail = NULL;
18397 	ill_t			*ill;
18398 	ipif_t			*ipif;
18399 	uint_t			bitval;
18400 	mib2_ipAddrEntry_t	mae;
18401 	zoneid_t		zoneid;
18402 	ill_walk_context_t ctx;
18403 
18404 	/*
18405 	 * make a copy of the original message
18406 	 */
18407 	mp2ctl = copymsg(mpctl);
18408 
18409 	/* ipAddrEntryTable */
18410 
18411 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18412 	optp->level = MIB2_IP;
18413 	optp->name = MIB2_IP_ADDR;
18414 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18415 
18416 	rw_enter(&ill_g_lock, RW_READER);
18417 	ill = ILL_START_WALK_V4(&ctx);
18418 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18419 		for (ipif = ill->ill_ipif; ipif != NULL;
18420 		    ipif = ipif->ipif_next) {
18421 			if (ipif->ipif_zoneid != zoneid &&
18422 			    ipif->ipif_zoneid != ALL_ZONES)
18423 				continue;
18424 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18425 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18426 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18427 
18428 			(void) ipif_get_name(ipif,
18429 			    mae.ipAdEntIfIndex.o_bytes,
18430 			    OCTET_LENGTH);
18431 			mae.ipAdEntIfIndex.o_length =
18432 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18433 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18434 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18435 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18436 			mae.ipAdEntInfo.ae_subnet_len =
18437 			    ip_mask_to_plen(ipif->ipif_net_mask);
18438 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18439 			for (bitval = 1;
18440 			    bitval &&
18441 			    !(bitval & ipif->ipif_brd_addr);
18442 			    bitval <<= 1)
18443 				noop;
18444 			mae.ipAdEntBcastAddr = bitval;
18445 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18446 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18447 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18448 			mae.ipAdEntInfo.ae_broadcast_addr =
18449 			    ipif->ipif_brd_addr;
18450 			mae.ipAdEntInfo.ae_pp_dst_addr =
18451 			    ipif->ipif_pp_dst_addr;
18452 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18453 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18454 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18455 
18456 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18457 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18458 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18459 				    "allocate %u bytes\n",
18460 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18461 			}
18462 		}
18463 	}
18464 	rw_exit(&ill_g_lock);
18465 
18466 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18467 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18468 	    (int)optp->level, (int)optp->name, (int)optp->len));
18469 	qreply(q, mpctl);
18470 	return (mp2ctl);
18471 }
18472 
18473 /* IPv6 address information */
18474 static mblk_t *
18475 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl)
18476 {
18477 	struct opthdr		*optp;
18478 	mblk_t			*mp2ctl;
18479 	mblk_t			*mp_tail = NULL;
18480 	ill_t			*ill;
18481 	ipif_t			*ipif;
18482 	mib2_ipv6AddrEntry_t	mae6;
18483 	zoneid_t		zoneid;
18484 	ill_walk_context_t	ctx;
18485 
18486 	/*
18487 	 * make a copy of the original message
18488 	 */
18489 	mp2ctl = copymsg(mpctl);
18490 
18491 	/* ipv6AddrEntryTable */
18492 
18493 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18494 	optp->level = MIB2_IP6;
18495 	optp->name = MIB2_IP6_ADDR;
18496 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18497 
18498 	rw_enter(&ill_g_lock, RW_READER);
18499 	ill = ILL_START_WALK_V6(&ctx);
18500 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18501 		for (ipif = ill->ill_ipif; ipif != NULL;
18502 		    ipif = ipif->ipif_next) {
18503 			if (ipif->ipif_zoneid != zoneid &&
18504 			    ipif->ipif_zoneid != ALL_ZONES)
18505 				continue;
18506 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18507 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18508 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18509 
18510 			(void) ipif_get_name(ipif,
18511 			    mae6.ipv6AddrIfIndex.o_bytes,
18512 			    OCTET_LENGTH);
18513 			mae6.ipv6AddrIfIndex.o_length =
18514 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18515 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18516 			mae6.ipv6AddrPfxLength =
18517 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18518 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18519 			mae6.ipv6AddrInfo.ae_subnet_len =
18520 			    mae6.ipv6AddrPfxLength;
18521 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18522 
18523 			/* Type: stateless(1), stateful(2), unknown(3) */
18524 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18525 				mae6.ipv6AddrType = 1;
18526 			else
18527 				mae6.ipv6AddrType = 2;
18528 			/* Anycast: true(1), false(2) */
18529 			if (ipif->ipif_flags & IPIF_ANYCAST)
18530 				mae6.ipv6AddrAnycastFlag = 1;
18531 			else
18532 				mae6.ipv6AddrAnycastFlag = 2;
18533 
18534 			/*
18535 			 * Address status: preferred(1), deprecated(2),
18536 			 * invalid(3), inaccessible(4), unknown(5)
18537 			 */
18538 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18539 				mae6.ipv6AddrStatus = 3;
18540 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18541 				mae6.ipv6AddrStatus = 2;
18542 			else
18543 				mae6.ipv6AddrStatus = 1;
18544 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18545 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18546 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18547 						ipif->ipif_v6pp_dst_addr;
18548 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18549 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18550 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18551 			mae6.ipv6AddrIdentifier = ill->ill_token;
18552 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18553 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18554 			mae6.ipv6AddrRetransmitTime =
18555 			    ill->ill_reachable_retrans_time;
18556 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18557 				(char *)&mae6,
18558 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18559 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18560 				    "allocate %u bytes\n",
18561 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18562 			}
18563 		}
18564 	}
18565 	rw_exit(&ill_g_lock);
18566 
18567 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18568 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18569 	    (int)optp->level, (int)optp->name, (int)optp->len));
18570 	qreply(q, mpctl);
18571 	return (mp2ctl);
18572 }
18573 
18574 /* IPv4 multicast group membership. */
18575 static mblk_t *
18576 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl)
18577 {
18578 	struct opthdr		*optp;
18579 	mblk_t			*mp2ctl;
18580 	ill_t			*ill;
18581 	ipif_t			*ipif;
18582 	ilm_t			*ilm;
18583 	ip_member_t		ipm;
18584 	mblk_t			*mp_tail = NULL;
18585 	ill_walk_context_t	ctx;
18586 	zoneid_t		zoneid;
18587 
18588 	/*
18589 	 * make a copy of the original message
18590 	 */
18591 	mp2ctl = copymsg(mpctl);
18592 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18593 
18594 	/* ipGroupMember table */
18595 	optp = (struct opthdr *)&mpctl->b_rptr[
18596 	    sizeof (struct T_optmgmt_ack)];
18597 	optp->level = MIB2_IP;
18598 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18599 
18600 	rw_enter(&ill_g_lock, RW_READER);
18601 	ill = ILL_START_WALK_V4(&ctx);
18602 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18603 		ILM_WALKER_HOLD(ill);
18604 		for (ipif = ill->ill_ipif; ipif != NULL;
18605 		    ipif = ipif->ipif_next) {
18606 			if (ipif->ipif_zoneid != zoneid &&
18607 			    ipif->ipif_zoneid != ALL_ZONES)
18608 				continue;	/* not this zone */
18609 			(void) ipif_get_name(ipif,
18610 			    ipm.ipGroupMemberIfIndex.o_bytes,
18611 			    OCTET_LENGTH);
18612 			ipm.ipGroupMemberIfIndex.o_length =
18613 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18614 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18615 				ASSERT(ilm->ilm_ipif != NULL);
18616 				ASSERT(ilm->ilm_ill == NULL);
18617 				if (ilm->ilm_ipif != ipif)
18618 					continue;
18619 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18620 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18621 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18622 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18623 				    (char *)&ipm, (int)sizeof (ipm))) {
18624 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18625 					    "failed to allocate %u bytes\n",
18626 						(uint_t)sizeof (ipm)));
18627 				}
18628 			}
18629 		}
18630 		ILM_WALKER_RELE(ill);
18631 	}
18632 	rw_exit(&ill_g_lock);
18633 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18634 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18635 	    (int)optp->level, (int)optp->name, (int)optp->len));
18636 	qreply(q, mpctl);
18637 	return (mp2ctl);
18638 }
18639 
18640 /* IPv6 multicast group membership. */
18641 static mblk_t *
18642 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl)
18643 {
18644 	struct opthdr		*optp;
18645 	mblk_t			*mp2ctl;
18646 	ill_t			*ill;
18647 	ilm_t			*ilm;
18648 	ipv6_member_t		ipm6;
18649 	mblk_t			*mp_tail = NULL;
18650 	ill_walk_context_t	ctx;
18651 	zoneid_t		zoneid;
18652 
18653 	/*
18654 	 * make a copy of the original message
18655 	 */
18656 	mp2ctl = copymsg(mpctl);
18657 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18658 
18659 	/* ip6GroupMember table */
18660 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18661 	optp->level = MIB2_IP6;
18662 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
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 		ILM_WALKER_HOLD(ill);
18668 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18669 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18670 			ASSERT(ilm->ilm_ipif == NULL);
18671 			ASSERT(ilm->ilm_ill != NULL);
18672 			if (ilm->ilm_zoneid != zoneid)
18673 				continue;	/* not this zone */
18674 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18675 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18676 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18677 			if (!snmp_append_data2(mpctl->b_cont,
18678 			    &mp_tail,
18679 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18680 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18681 				    "failed to allocate %u bytes\n",
18682 				    (uint_t)sizeof (ipm6)));
18683 			}
18684 		}
18685 		ILM_WALKER_RELE(ill);
18686 	}
18687 	rw_exit(&ill_g_lock);
18688 
18689 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18690 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18691 	    (int)optp->level, (int)optp->name, (int)optp->len));
18692 	qreply(q, mpctl);
18693 	return (mp2ctl);
18694 }
18695 
18696 /* IP multicast filtered sources */
18697 static mblk_t *
18698 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl)
18699 {
18700 	struct opthdr		*optp;
18701 	mblk_t			*mp2ctl;
18702 	ill_t			*ill;
18703 	ipif_t			*ipif;
18704 	ilm_t			*ilm;
18705 	ip_grpsrc_t		ips;
18706 	mblk_t			*mp_tail = NULL;
18707 	ill_walk_context_t	ctx;
18708 	zoneid_t		zoneid;
18709 	int			i;
18710 	slist_t			*sl;
18711 
18712 	/*
18713 	 * make a copy of the original message
18714 	 */
18715 	mp2ctl = copymsg(mpctl);
18716 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18717 
18718 	/* ipGroupSource table */
18719 	optp = (struct opthdr *)&mpctl->b_rptr[
18720 	    sizeof (struct T_optmgmt_ack)];
18721 	optp->level = MIB2_IP;
18722 	optp->name = EXPER_IP_GROUP_SOURCES;
18723 
18724 	rw_enter(&ill_g_lock, RW_READER);
18725 	ill = ILL_START_WALK_V4(&ctx);
18726 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18727 		ILM_WALKER_HOLD(ill);
18728 		for (ipif = ill->ill_ipif; ipif != NULL;
18729 		    ipif = ipif->ipif_next) {
18730 			if (ipif->ipif_zoneid != zoneid)
18731 				continue;	/* not this zone */
18732 			(void) ipif_get_name(ipif,
18733 			    ips.ipGroupSourceIfIndex.o_bytes,
18734 			    OCTET_LENGTH);
18735 			ips.ipGroupSourceIfIndex.o_length =
18736 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18737 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18738 				ASSERT(ilm->ilm_ipif != NULL);
18739 				ASSERT(ilm->ilm_ill == NULL);
18740 				sl = ilm->ilm_filter;
18741 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18742 					continue;
18743 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18744 				for (i = 0; i < sl->sl_numsrc; i++) {
18745 					if (!IN6_IS_ADDR_V4MAPPED(
18746 					    &sl->sl_addr[i]))
18747 						continue;
18748 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18749 					    ips.ipGroupSourceAddress);
18750 					if (snmp_append_data2(mpctl->b_cont,
18751 					    &mp_tail, (char *)&ips,
18752 					    (int)sizeof (ips)) == 0) {
18753 						ip1dbg(("ip_snmp_get_mib2_"
18754 						    "ip_group_src: failed to "
18755 						    "allocate %u bytes\n",
18756 						    (uint_t)sizeof (ips)));
18757 					}
18758 				}
18759 			}
18760 		}
18761 		ILM_WALKER_RELE(ill);
18762 	}
18763 	rw_exit(&ill_g_lock);
18764 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18765 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18766 	    (int)optp->level, (int)optp->name, (int)optp->len));
18767 	qreply(q, mpctl);
18768 	return (mp2ctl);
18769 }
18770 
18771 /* IPv6 multicast filtered sources. */
18772 static mblk_t *
18773 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl)
18774 {
18775 	struct opthdr		*optp;
18776 	mblk_t			*mp2ctl;
18777 	ill_t			*ill;
18778 	ilm_t			*ilm;
18779 	ipv6_grpsrc_t		ips6;
18780 	mblk_t			*mp_tail = NULL;
18781 	ill_walk_context_t	ctx;
18782 	zoneid_t		zoneid;
18783 	int			i;
18784 	slist_t			*sl;
18785 
18786 	/*
18787 	 * make a copy of the original message
18788 	 */
18789 	mp2ctl = copymsg(mpctl);
18790 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18791 
18792 	/* ip6GroupMember table */
18793 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18794 	optp->level = MIB2_IP6;
18795 	optp->name = EXPER_IP6_GROUP_SOURCES;
18796 
18797 	rw_enter(&ill_g_lock, RW_READER);
18798 	ill = ILL_START_WALK_V6(&ctx);
18799 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18800 		ILM_WALKER_HOLD(ill);
18801 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18802 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18803 			ASSERT(ilm->ilm_ipif == NULL);
18804 			ASSERT(ilm->ilm_ill != NULL);
18805 			sl = ilm->ilm_filter;
18806 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18807 				continue;
18808 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18809 			for (i = 0; i < sl->sl_numsrc; i++) {
18810 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18811 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18812 				    (char *)&ips6, (int)sizeof (ips6))) {
18813 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18814 					    "group_src: failed to allocate "
18815 					    "%u bytes\n",
18816 					    (uint_t)sizeof (ips6)));
18817 				}
18818 			}
18819 		}
18820 		ILM_WALKER_RELE(ill);
18821 	}
18822 	rw_exit(&ill_g_lock);
18823 
18824 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18825 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18826 	    (int)optp->level, (int)optp->name, (int)optp->len));
18827 	qreply(q, mpctl);
18828 	return (mp2ctl);
18829 }
18830 
18831 /* Multicast routing virtual interface table. */
18832 static mblk_t *
18833 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl)
18834 {
18835 	struct opthdr		*optp;
18836 	mblk_t			*mp2ctl;
18837 
18838 	/*
18839 	 * make a copy of the original message
18840 	 */
18841 	mp2ctl = copymsg(mpctl);
18842 
18843 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18844 	optp->level = EXPER_DVMRP;
18845 	optp->name = EXPER_DVMRP_VIF;
18846 	if (!ip_mroute_vif(mpctl->b_cont)) {
18847 		ip0dbg(("ip_mroute_vif: failed\n"));
18848 	}
18849 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18850 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18851 	    (int)optp->level, (int)optp->name, (int)optp->len));
18852 	qreply(q, mpctl);
18853 	return (mp2ctl);
18854 }
18855 
18856 /* Multicast routing table. */
18857 static mblk_t *
18858 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl)
18859 {
18860 	struct opthdr		*optp;
18861 	mblk_t			*mp2ctl;
18862 
18863 	/*
18864 	 * make a copy of the original message
18865 	 */
18866 	mp2ctl = copymsg(mpctl);
18867 
18868 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18869 	optp->level = EXPER_DVMRP;
18870 	optp->name = EXPER_DVMRP_MRT;
18871 	if (!ip_mroute_mrt(mpctl->b_cont)) {
18872 		ip0dbg(("ip_mroute_mrt: failed\n"));
18873 	}
18874 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18875 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18876 	    (int)optp->level, (int)optp->name, (int)optp->len));
18877 	qreply(q, mpctl);
18878 	return (mp2ctl);
18879 }
18880 
18881 /*
18882  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18883  * in one IRE walk.
18884  */
18885 static mblk_t *
18886 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl)
18887 {
18888 	struct opthdr	*optp;
18889 	mblk_t		*mp2ctl;	/* Returned */
18890 	mblk_t		*mp3ctl;	/* nettomedia */
18891 	mblk_t		*mp4ctl;	/* routeattrs */
18892 	iproutedata_t	ird;
18893 	zoneid_t	zoneid;
18894 
18895 	/*
18896 	 * make copies of the original message
18897 	 *	- mp2ctl is returned unchanged to the caller for his use
18898 	 *	- mpctl is sent upstream as ipRouteEntryTable
18899 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18900 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18901 	 */
18902 	mp2ctl = copymsg(mpctl);
18903 	mp3ctl = copymsg(mpctl);
18904 	mp4ctl = copymsg(mpctl);
18905 	if (mp3ctl == NULL || mp4ctl == NULL) {
18906 		freemsg(mp4ctl);
18907 		freemsg(mp3ctl);
18908 		freemsg(mp2ctl);
18909 		freemsg(mpctl);
18910 		return (NULL);
18911 	}
18912 
18913 	bzero(&ird, sizeof (ird));
18914 
18915 	ird.ird_route.lp_head = mpctl->b_cont;
18916 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18917 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18918 
18919 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18920 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid);
18921 	if (zoneid == GLOBAL_ZONEID) {
18922 		/*
18923 		 * Those IREs are used by Mobile-IP; since mipagent(1M) requires
18924 		 * the sys_net_config privilege, it can only run in the global
18925 		 * zone, so we don't display these IREs in the other zones.
18926 		 */
18927 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird);
18928 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL);
18929 	}
18930 
18931 	/* ipRouteEntryTable in mpctl */
18932 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18933 	optp->level = MIB2_IP;
18934 	optp->name = MIB2_IP_ROUTE;
18935 	optp->len = msgdsize(ird.ird_route.lp_head);
18936 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18937 	    (int)optp->level, (int)optp->name, (int)optp->len));
18938 	qreply(q, mpctl);
18939 
18940 	/* ipNetToMediaEntryTable in mp3ctl */
18941 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18942 	optp->level = MIB2_IP;
18943 	optp->name = MIB2_IP_MEDIA;
18944 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18945 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18946 	    (int)optp->level, (int)optp->name, (int)optp->len));
18947 	qreply(q, mp3ctl);
18948 
18949 	/* ipRouteAttributeTable in mp4ctl */
18950 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18951 	optp->level = MIB2_IP;
18952 	optp->name = EXPER_IP_RTATTR;
18953 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18954 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18955 	    (int)optp->level, (int)optp->name, (int)optp->len));
18956 	if (optp->len == 0)
18957 		freemsg(mp4ctl);
18958 	else
18959 		qreply(q, mp4ctl);
18960 
18961 	return (mp2ctl);
18962 }
18963 
18964 /*
18965  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18966  * ipv6NetToMediaEntryTable in an NDP walk.
18967  */
18968 static mblk_t *
18969 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl)
18970 {
18971 	struct opthdr	*optp;
18972 	mblk_t		*mp2ctl;	/* Returned */
18973 	mblk_t		*mp3ctl;	/* nettomedia */
18974 	mblk_t		*mp4ctl;	/* routeattrs */
18975 	iproutedata_t	ird;
18976 	zoneid_t	zoneid;
18977 
18978 	/*
18979 	 * make copies of the original message
18980 	 *	- mp2ctl is returned unchanged to the caller for his use
18981 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18982 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18983 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18984 	 */
18985 	mp2ctl = copymsg(mpctl);
18986 	mp3ctl = copymsg(mpctl);
18987 	mp4ctl = copymsg(mpctl);
18988 	if (mp3ctl == NULL || mp4ctl == NULL) {
18989 		freemsg(mp4ctl);
18990 		freemsg(mp3ctl);
18991 		freemsg(mp2ctl);
18992 		freemsg(mpctl);
18993 		return (NULL);
18994 	}
18995 
18996 	bzero(&ird, sizeof (ird));
18997 
18998 	ird.ird_route.lp_head = mpctl->b_cont;
18999 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19000 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19001 
19002 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19003 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid);
19004 
19005 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19006 	optp->level = MIB2_IP6;
19007 	optp->name = MIB2_IP6_ROUTE;
19008 	optp->len = msgdsize(ird.ird_route.lp_head);
19009 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19010 	    (int)optp->level, (int)optp->name, (int)optp->len));
19011 	qreply(q, mpctl);
19012 
19013 	/* ipv6NetToMediaEntryTable in mp3ctl */
19014 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird);
19015 
19016 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19017 	optp->level = MIB2_IP6;
19018 	optp->name = MIB2_IP6_MEDIA;
19019 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19020 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19021 	    (int)optp->level, (int)optp->name, (int)optp->len));
19022 	qreply(q, mp3ctl);
19023 
19024 	/* ipv6RouteAttributeTable in mp4ctl */
19025 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19026 	optp->level = MIB2_IP6;
19027 	optp->name = EXPER_IP_RTATTR;
19028 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19029 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19030 	    (int)optp->level, (int)optp->name, (int)optp->len));
19031 	if (optp->len == 0)
19032 		freemsg(mp4ctl);
19033 	else
19034 		qreply(q, mp4ctl);
19035 
19036 	return (mp2ctl);
19037 }
19038 
19039 /*
19040  * IPv6 mib: One per ill
19041  */
19042 static mblk_t *
19043 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl)
19044 {
19045 	struct opthdr		*optp;
19046 	mblk_t			*mp2ctl;
19047 	ill_t			*ill;
19048 	ill_walk_context_t	ctx;
19049 	mblk_t			*mp_tail = NULL;
19050 
19051 	/*
19052 	 * Make a copy of the original message
19053 	 */
19054 	mp2ctl = copymsg(mpctl);
19055 
19056 	/* fixed length IPv6 structure ... */
19057 
19058 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19059 	optp->level = MIB2_IP6;
19060 	optp->name = 0;
19061 	/* Include "unknown interface" ip6_mib */
19062 	ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19063 	ip6_mib.ipIfStatsIfIndex = MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19064 	SET_MIB(ip6_mib.ipIfStatsForwarding, ipv6_forward ? 1 : 2);
19065 	SET_MIB(ip6_mib.ipIfStatsDefaultHopLimit, ipv6_def_hops);
19066 	SET_MIB(ip6_mib.ipIfStatsEntrySize,
19067 	    sizeof (mib2_ipIfStatsEntry_t));
19068 	SET_MIB(ip6_mib.ipIfStatsAddrEntrySize, sizeof (mib2_ipv6AddrEntry_t));
19069 	SET_MIB(ip6_mib.ipIfStatsRouteEntrySize,
19070 	    sizeof (mib2_ipv6RouteEntry_t));
19071 	SET_MIB(ip6_mib.ipIfStatsNetToMediaEntrySize,
19072 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19073 	SET_MIB(ip6_mib.ipIfStatsMemberEntrySize, sizeof (ipv6_member_t));
19074 	SET_MIB(ip6_mib.ipIfStatsGroupSourceEntrySize, sizeof (ipv6_grpsrc_t));
19075 
19076 	/*
19077 	 * Synchronize 64- and 32-bit counters
19078 	 */
19079 	SYNC32_MIB(&ip6_mib, ipIfStatsInReceives, ipIfStatsHCInReceives);
19080 	SYNC32_MIB(&ip6_mib, ipIfStatsInDelivers, ipIfStatsHCInDelivers);
19081 	SYNC32_MIB(&ip6_mib, ipIfStatsOutRequests, ipIfStatsHCOutRequests);
19082 	SYNC32_MIB(&ip6_mib, ipIfStatsOutForwDatagrams,
19083 	    ipIfStatsHCOutForwDatagrams);
19084 	SYNC32_MIB(&ip6_mib, ipIfStatsOutMcastPkts, ipIfStatsHCOutMcastPkts);
19085 	SYNC32_MIB(&ip6_mib, ipIfStatsInMcastPkts, ipIfStatsHCInMcastPkts);
19086 
19087 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&ip6_mib,
19088 	    (int)sizeof (ip6_mib))) {
19089 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19090 		    (uint_t)sizeof (ip6_mib)));
19091 	}
19092 
19093 	rw_enter(&ill_g_lock, RW_READER);
19094 	ill = ILL_START_WALK_V6(&ctx);
19095 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19096 		ill->ill_ip_mib->ipIfStatsIfIndex =
19097 		    ill->ill_phyint->phyint_ifindex;
19098 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19099 		    ipv6_forward ? 1 : 2);
19100 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19101 		    ill->ill_max_hops);
19102 
19103 		/*
19104 		 * Synchronize 64- and 32-bit counters
19105 		 */
19106 		SYNC32_MIB(&ip6_mib, ipIfStatsInReceives,
19107 		    ipIfStatsHCInReceives);
19108 		SYNC32_MIB(&ip6_mib, ipIfStatsInDelivers,
19109 		    ipIfStatsHCInDelivers);
19110 		SYNC32_MIB(&ip6_mib, ipIfStatsOutRequests,
19111 		    ipIfStatsHCOutRequests);
19112 		SYNC32_MIB(&ip6_mib, ipIfStatsOutForwDatagrams,
19113 		    ipIfStatsHCOutForwDatagrams);
19114 		SYNC32_MIB(&ip6_mib, ipIfStatsOutMcastPkts,
19115 		    ipIfStatsHCOutMcastPkts);
19116 		SYNC32_MIB(&ip6_mib, ipIfStatsInMcastPkts,
19117 		    ipIfStatsHCInMcastPkts);
19118 
19119 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19120 		    (char *)ill->ill_ip_mib,
19121 		    (int)sizeof (*ill->ill_ip_mib))) {
19122 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19123 				"%u bytes\n",
19124 				(uint_t)sizeof (*ill->ill_ip_mib)));
19125 		}
19126 	}
19127 	rw_exit(&ill_g_lock);
19128 
19129 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19130 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19131 	    (int)optp->level, (int)optp->name, (int)optp->len));
19132 	qreply(q, mpctl);
19133 	return (mp2ctl);
19134 }
19135 
19136 /*
19137  * ICMPv6 mib: One per ill
19138  */
19139 static mblk_t *
19140 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl)
19141 {
19142 	struct opthdr		*optp;
19143 	mblk_t			*mp2ctl;
19144 	ill_t			*ill;
19145 	ill_walk_context_t	ctx;
19146 	mblk_t			*mp_tail = NULL;
19147 	/*
19148 	 * Make a copy of the original message
19149 	 */
19150 	mp2ctl = copymsg(mpctl);
19151 
19152 	/* fixed length ICMPv6 structure ... */
19153 
19154 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19155 	optp->level = MIB2_ICMP6;
19156 	optp->name = 0;
19157 	/* Include "unknown interface" icmp6_mib */
19158 	icmp6_mib.ipv6IfIcmpIfIndex = MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19159 	icmp6_mib.ipv6IfIcmpEntrySize = sizeof (mib2_ipv6IfIcmpEntry_t);
19160 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail, (char *)&icmp6_mib,
19161 	    (int)sizeof (icmp6_mib))) {
19162 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19163 		    (uint_t)sizeof (icmp6_mib)));
19164 	}
19165 
19166 	rw_enter(&ill_g_lock, RW_READER);
19167 	ill = ILL_START_WALK_V6(&ctx);
19168 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19169 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19170 		    ill->ill_phyint->phyint_ifindex;
19171 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19172 		    (char *)ill->ill_icmp6_mib,
19173 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19174 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19175 			    "%u bytes\n",
19176 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19177 		}
19178 	}
19179 	rw_exit(&ill_g_lock);
19180 
19181 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19182 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19183 	    (int)optp->level, (int)optp->name, (int)optp->len));
19184 	qreply(q, mpctl);
19185 	return (mp2ctl);
19186 }
19187 
19188 /*
19189  * ire_walk routine to create both ipRouteEntryTable and
19190  * ipRouteAttributeTable in one IRE walk
19191  */
19192 static void
19193 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19194 {
19195 	ill_t				*ill;
19196 	ipif_t				*ipif;
19197 	mib2_ipRouteEntry_t		*re;
19198 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19199 	ipaddr_t			gw_addr;
19200 	tsol_ire_gw_secattr_t		*attrp;
19201 	tsol_gc_t			*gc = NULL;
19202 	tsol_gcgrp_t			*gcgrp = NULL;
19203 	uint_t				sacnt = 0;
19204 	int				i;
19205 
19206 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19207 
19208 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19209 		return;
19210 
19211 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19212 		mutex_enter(&attrp->igsa_lock);
19213 		if ((gc = attrp->igsa_gc) != NULL) {
19214 			gcgrp = gc->gc_grp;
19215 			ASSERT(gcgrp != NULL);
19216 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19217 			sacnt = 1;
19218 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19219 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19220 			gc = gcgrp->gcgrp_head;
19221 			sacnt = gcgrp->gcgrp_count;
19222 		}
19223 		mutex_exit(&attrp->igsa_lock);
19224 
19225 		/* do nothing if there's no gc to report */
19226 		if (gc == NULL) {
19227 			ASSERT(sacnt == 0);
19228 			if (gcgrp != NULL) {
19229 				/* we might as well drop the lock now */
19230 				rw_exit(&gcgrp->gcgrp_rwlock);
19231 				gcgrp = NULL;
19232 			}
19233 			attrp = NULL;
19234 		}
19235 
19236 		ASSERT(gc == NULL || (gcgrp != NULL &&
19237 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19238 	}
19239 	ASSERT(sacnt == 0 || gc != NULL);
19240 
19241 	if (sacnt != 0 &&
19242 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19243 		kmem_free(re, sizeof (*re));
19244 		rw_exit(&gcgrp->gcgrp_rwlock);
19245 		return;
19246 	}
19247 
19248 	/*
19249 	 * Return all IRE types for route table... let caller pick and choose
19250 	 */
19251 	re->ipRouteDest = ire->ire_addr;
19252 	ipif = ire->ire_ipif;
19253 	re->ipRouteIfIndex.o_length = 0;
19254 	if (ire->ire_type == IRE_CACHE) {
19255 		ill = (ill_t *)ire->ire_stq->q_ptr;
19256 		re->ipRouteIfIndex.o_length =
19257 		    ill->ill_name_length == 0 ? 0 :
19258 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19259 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19260 		    re->ipRouteIfIndex.o_length);
19261 	} else if (ipif != NULL) {
19262 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19263 		    OCTET_LENGTH);
19264 		re->ipRouteIfIndex.o_length =
19265 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19266 	}
19267 	re->ipRouteMetric1 = -1;
19268 	re->ipRouteMetric2 = -1;
19269 	re->ipRouteMetric3 = -1;
19270 	re->ipRouteMetric4 = -1;
19271 
19272 	gw_addr = ire->ire_gateway_addr;
19273 
19274 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19275 		re->ipRouteNextHop = ire->ire_src_addr;
19276 	else
19277 		re->ipRouteNextHop = gw_addr;
19278 	/* indirect(4), direct(3), or invalid(2) */
19279 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19280 		re->ipRouteType = 2;
19281 	else
19282 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19283 	re->ipRouteProto = -1;
19284 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19285 	re->ipRouteMask = ire->ire_mask;
19286 	re->ipRouteMetric5 = -1;
19287 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19288 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19289 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19290 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19291 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19292 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19293 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19294 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19295 	re->ipRouteInfo.re_in_ill.o_length = 0;
19296 
19297 	if (ire->ire_flags & RTF_DYNAMIC) {
19298 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19299 	} else {
19300 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19301 	}
19302 
19303 	if (ire->ire_in_ill != NULL) {
19304 		re->ipRouteInfo.re_in_ill.o_length =
19305 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19306 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19307 		bcopy(ire->ire_in_ill->ill_name,
19308 		    re->ipRouteInfo.re_in_ill.o_bytes,
19309 		    re->ipRouteInfo.re_in_ill.o_length);
19310 	}
19311 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19312 
19313 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19314 	    (char *)re, (int)sizeof (*re))) {
19315 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19316 		    (uint_t)sizeof (*re)));
19317 	}
19318 
19319 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19320 		iaeptr->iae_routeidx = ird->ird_idx;
19321 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19322 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19323 	}
19324 
19325 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19326 	    (char *)iae, sacnt * sizeof (*iae))) {
19327 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19328 		    (unsigned)(sacnt * sizeof (*iae))));
19329 	}
19330 
19331 	/* bump route index for next pass */
19332 	ird->ird_idx++;
19333 
19334 	kmem_free(re, sizeof (*re));
19335 	if (sacnt != 0)
19336 		kmem_free(iae, sacnt * sizeof (*iae));
19337 
19338 	if (gcgrp != NULL)
19339 		rw_exit(&gcgrp->gcgrp_rwlock);
19340 }
19341 
19342 /*
19343  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19344  */
19345 static void
19346 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19347 {
19348 	ill_t				*ill;
19349 	ipif_t				*ipif;
19350 	mib2_ipv6RouteEntry_t		*re;
19351 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19352 	in6_addr_t			gw_addr_v6;
19353 	tsol_ire_gw_secattr_t		*attrp;
19354 	tsol_gc_t			*gc = NULL;
19355 	tsol_gcgrp_t			*gcgrp = NULL;
19356 	uint_t				sacnt = 0;
19357 	int				i;
19358 
19359 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19360 
19361 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19362 		return;
19363 
19364 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19365 		mutex_enter(&attrp->igsa_lock);
19366 		if ((gc = attrp->igsa_gc) != NULL) {
19367 			gcgrp = gc->gc_grp;
19368 			ASSERT(gcgrp != NULL);
19369 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19370 			sacnt = 1;
19371 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19372 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19373 			gc = gcgrp->gcgrp_head;
19374 			sacnt = gcgrp->gcgrp_count;
19375 		}
19376 		mutex_exit(&attrp->igsa_lock);
19377 
19378 		/* do nothing if there's no gc to report */
19379 		if (gc == NULL) {
19380 			ASSERT(sacnt == 0);
19381 			if (gcgrp != NULL) {
19382 				/* we might as well drop the lock now */
19383 				rw_exit(&gcgrp->gcgrp_rwlock);
19384 				gcgrp = NULL;
19385 			}
19386 			attrp = NULL;
19387 		}
19388 
19389 		ASSERT(gc == NULL || (gcgrp != NULL &&
19390 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19391 	}
19392 	ASSERT(sacnt == 0 || gc != NULL);
19393 
19394 	if (sacnt != 0 &&
19395 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19396 		kmem_free(re, sizeof (*re));
19397 		rw_exit(&gcgrp->gcgrp_rwlock);
19398 		return;
19399 	}
19400 
19401 	/*
19402 	 * Return all IRE types for route table... let caller pick and choose
19403 	 */
19404 	re->ipv6RouteDest = ire->ire_addr_v6;
19405 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19406 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19407 	re->ipv6RouteIfIndex.o_length = 0;
19408 	ipif = ire->ire_ipif;
19409 	if (ire->ire_type == IRE_CACHE) {
19410 		ill = (ill_t *)ire->ire_stq->q_ptr;
19411 		re->ipv6RouteIfIndex.o_length =
19412 		    ill->ill_name_length == 0 ? 0 :
19413 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19414 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19415 		    re->ipv6RouteIfIndex.o_length);
19416 	} else if (ipif != NULL) {
19417 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19418 		    OCTET_LENGTH);
19419 		re->ipv6RouteIfIndex.o_length =
19420 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19421 	}
19422 
19423 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19424 
19425 	mutex_enter(&ire->ire_lock);
19426 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19427 	mutex_exit(&ire->ire_lock);
19428 
19429 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19430 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19431 	else
19432 		re->ipv6RouteNextHop = gw_addr_v6;
19433 
19434 	/* remote(4), local(3), or discard(2) */
19435 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19436 		re->ipv6RouteType = 2;
19437 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19438 		re->ipv6RouteType = 3;
19439 	else
19440 		re->ipv6RouteType = 4;
19441 
19442 	re->ipv6RouteProtocol	= -1;
19443 	re->ipv6RoutePolicy	= 0;
19444 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19445 	re->ipv6RouteNextHopRDI	= 0;
19446 	re->ipv6RouteWeight	= 0;
19447 	re->ipv6RouteMetric	= 0;
19448 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19449 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19450 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19451 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19452 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19453 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19454 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19455 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19456 
19457 	if (ire->ire_flags & RTF_DYNAMIC) {
19458 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19459 	} else {
19460 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19461 	}
19462 
19463 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19464 	    (char *)re, (int)sizeof (*re))) {
19465 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19466 		    (uint_t)sizeof (*re)));
19467 	}
19468 
19469 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19470 		iaeptr->iae_routeidx = ird->ird_idx;
19471 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19472 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19473 	}
19474 
19475 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19476 	    (char *)iae, sacnt * sizeof (*iae))) {
19477 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19478 		    (unsigned)(sacnt * sizeof (*iae))));
19479 	}
19480 
19481 	/* bump route index for next pass */
19482 	ird->ird_idx++;
19483 
19484 	kmem_free(re, sizeof (*re));
19485 	if (sacnt != 0)
19486 		kmem_free(iae, sacnt * sizeof (*iae));
19487 
19488 	if (gcgrp != NULL)
19489 		rw_exit(&gcgrp->gcgrp_rwlock);
19490 }
19491 
19492 /*
19493  * ndp_walk routine to create ipv6NetToMediaEntryTable
19494  */
19495 static int
19496 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19497 {
19498 	ill_t				*ill;
19499 	mib2_ipv6NetToMediaEntry_t	ntme;
19500 	dl_unitdata_req_t		*dl;
19501 
19502 	ill = nce->nce_ill;
19503 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19504 		return (0);
19505 
19506 	/*
19507 	 * Neighbor cache entry attached to IRE with on-link
19508 	 * destination.
19509 	 */
19510 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19511 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19512 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19513 	    (nce->nce_res_mp != NULL)) {
19514 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19515 		ntme.ipv6NetToMediaPhysAddress.o_length =
19516 		    dl->dl_dest_addr_length;
19517 	} else {
19518 		ntme.ipv6NetToMediaPhysAddress.o_length =
19519 		    ill->ill_phys_addr_length;
19520 	}
19521 	if (nce->nce_res_mp != NULL) {
19522 		bcopy((char *)nce->nce_res_mp->b_rptr +
19523 		    NCE_LL_ADDR_OFFSET(ill),
19524 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19525 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19526 	} else {
19527 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19528 		    ill->ill_phys_addr_length);
19529 	}
19530 	/*
19531 	 * Note: Returns ND_* states. Should be:
19532 	 * reachable(1), stale(2), delay(3), probe(4),
19533 	 * invalid(5), unknown(6)
19534 	 */
19535 	ntme.ipv6NetToMediaState = nce->nce_state;
19536 	ntme.ipv6NetToMediaLastUpdated = 0;
19537 
19538 	/* other(1), dynamic(2), static(3), local(4) */
19539 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19540 		ntme.ipv6NetToMediaType = 4;
19541 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19542 		ntme.ipv6NetToMediaType = 1;
19543 	} else {
19544 		ntme.ipv6NetToMediaType = 2;
19545 	}
19546 
19547 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19548 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19549 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19550 		    (uint_t)sizeof (ntme)));
19551 	}
19552 	return (0);
19553 }
19554 
19555 /*
19556  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19557  */
19558 /* ARGSUSED */
19559 int
19560 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19561 {
19562 	switch (level) {
19563 	case MIB2_IP:
19564 	case MIB2_ICMP:
19565 		switch (name) {
19566 		default:
19567 			break;
19568 		}
19569 		return (1);
19570 	default:
19571 		return (1);
19572 	}
19573 }
19574 
19575 /*
19576  * When there exists both a 64- and 32-bit counter of a particular type
19577  * (i.e., InReceives), only the 64-bit counters are added.
19578  */
19579 void
19580 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19581 {
19582 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19583 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19584 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19585 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19586 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19587 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19588 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19589 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19590 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19591 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19592 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19593 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19594 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19595 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19596 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19597 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19598 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19599 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19600 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19601 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19602 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19603 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19604 	    o2->ipIfStatsInWrongIPVersion);
19605 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19606 	    o2->ipIfStatsInWrongIPVersion);
19607 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19608 	    o2->ipIfStatsOutSwitchIPVersion);
19609 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19610 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19611 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19612 	    o2->ipIfStatsHCInForwDatagrams);
19613 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19614 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19615 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19616 	    o2->ipIfStatsHCOutForwDatagrams);
19617 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19618 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19619 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19620 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19621 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19622 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19623 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19624 	    o2->ipIfStatsHCOutMcastOctets);
19625 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19626 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19627 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19628 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19629 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19630 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19631 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19632 }
19633 
19634 void
19635 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19636 {
19637 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19638 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19639 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19640 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19641 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19642 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19643 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19644 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19645 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19646 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19647 	    o2->ipv6IfIcmpInRouterSolicits);
19648 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19649 	    o2->ipv6IfIcmpInRouterAdvertisements);
19650 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19651 	    o2->ipv6IfIcmpInNeighborSolicits);
19652 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19653 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19654 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19655 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19656 	    o2->ipv6IfIcmpInGroupMembQueries);
19657 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19658 	    o2->ipv6IfIcmpInGroupMembResponses);
19659 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19660 	    o2->ipv6IfIcmpInGroupMembReductions);
19661 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19662 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19663 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19664 	    o2->ipv6IfIcmpOutDestUnreachs);
19665 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19666 	    o2->ipv6IfIcmpOutAdminProhibs);
19667 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19668 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19669 	    o2->ipv6IfIcmpOutParmProblems);
19670 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19671 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19672 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19673 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19674 	    o2->ipv6IfIcmpOutRouterSolicits);
19675 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19676 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19677 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19678 	    o2->ipv6IfIcmpOutNeighborSolicits);
19679 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19680 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19681 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19682 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19683 	    o2->ipv6IfIcmpOutGroupMembQueries);
19684 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19685 	    o2->ipv6IfIcmpOutGroupMembResponses);
19686 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19687 	    o2->ipv6IfIcmpOutGroupMembReductions);
19688 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19689 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19690 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19691 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19692 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19693 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19694 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19695 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19696 	    o2->ipv6IfIcmpInGroupMembTotal);
19697 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19698 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19699 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19700 	    o2->ipv6IfIcmpInGroupMembBadReports);
19701 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19702 	    o2->ipv6IfIcmpInGroupMembOurReports);
19703 }
19704 
19705 /*
19706  * Called before the options are updated to check if this packet will
19707  * be source routed from here.
19708  * This routine assumes that the options are well formed i.e. that they
19709  * have already been checked.
19710  */
19711 static boolean_t
19712 ip_source_routed(ipha_t *ipha)
19713 {
19714 	ipoptp_t	opts;
19715 	uchar_t		*opt;
19716 	uint8_t		optval;
19717 	uint8_t		optlen;
19718 	ipaddr_t	dst;
19719 	ire_t		*ire;
19720 
19721 	if (IS_SIMPLE_IPH(ipha)) {
19722 		ip2dbg(("not source routed\n"));
19723 		return (B_FALSE);
19724 	}
19725 	dst = ipha->ipha_dst;
19726 	for (optval = ipoptp_first(&opts, ipha);
19727 	    optval != IPOPT_EOL;
19728 	    optval = ipoptp_next(&opts)) {
19729 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19730 		opt = opts.ipoptp_cur;
19731 		optlen = opts.ipoptp_len;
19732 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19733 		    optval, optlen));
19734 		switch (optval) {
19735 			uint32_t off;
19736 		case IPOPT_SSRR:
19737 		case IPOPT_LSRR:
19738 			/*
19739 			 * If dst is one of our addresses and there are some
19740 			 * entries left in the source route return (true).
19741 			 */
19742 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19743 			    ALL_ZONES, NULL, MATCH_IRE_TYPE);
19744 			if (ire == NULL) {
19745 				ip2dbg(("ip_source_routed: not next"
19746 				    " source route 0x%x\n",
19747 				    ntohl(dst)));
19748 				return (B_FALSE);
19749 			}
19750 			ire_refrele(ire);
19751 			off = opt[IPOPT_OFFSET];
19752 			off--;
19753 			if (optlen < IP_ADDR_LEN ||
19754 			    off > optlen - IP_ADDR_LEN) {
19755 				/* End of source route */
19756 				ip1dbg(("ip_source_routed: end of SR\n"));
19757 				return (B_FALSE);
19758 			}
19759 			return (B_TRUE);
19760 		}
19761 	}
19762 	ip2dbg(("not source routed\n"));
19763 	return (B_FALSE);
19764 }
19765 
19766 /*
19767  * Check if the packet contains any source route.
19768  */
19769 static boolean_t
19770 ip_source_route_included(ipha_t *ipha)
19771 {
19772 	ipoptp_t	opts;
19773 	uint8_t		optval;
19774 
19775 	if (IS_SIMPLE_IPH(ipha))
19776 		return (B_FALSE);
19777 	for (optval = ipoptp_first(&opts, ipha);
19778 	    optval != IPOPT_EOL;
19779 	    optval = ipoptp_next(&opts)) {
19780 		switch (optval) {
19781 		case IPOPT_SSRR:
19782 		case IPOPT_LSRR:
19783 			return (B_TRUE);
19784 		}
19785 	}
19786 	return (B_FALSE);
19787 }
19788 
19789 /*
19790  * Called when the IRE expiration timer fires.
19791  */
19792 /* ARGSUSED */
19793 void
19794 ip_trash_timer_expire(void *args)
19795 {
19796 	int	flush_flag = 0;
19797 
19798 	/*
19799 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19800 	 * This lock makes sure that a new invocation of this function
19801 	 * that occurs due to an almost immediate timer firing will not
19802 	 * progress beyond this point until the current invocation is done
19803 	 */
19804 	mutex_enter(&ip_trash_timer_lock);
19805 	ip_ire_expire_id = 0;
19806 	mutex_exit(&ip_trash_timer_lock);
19807 
19808 	/* Periodic timer */
19809 	if (ip_ire_arp_time_elapsed >= ip_ire_arp_interval) {
19810 		/*
19811 		 * Remove all IRE_CACHE entries since they might
19812 		 * contain arp information.
19813 		 */
19814 		flush_flag |= FLUSH_ARP_TIME;
19815 		ip_ire_arp_time_elapsed = 0;
19816 		IP_STAT(ip_ire_arp_timer_expired);
19817 	}
19818 	if (ip_ire_rd_time_elapsed >= ip_ire_redir_interval) {
19819 		/* Remove all redirects */
19820 		flush_flag |= FLUSH_REDIRECT_TIME;
19821 		ip_ire_rd_time_elapsed = 0;
19822 		IP_STAT(ip_ire_redirect_timer_expired);
19823 	}
19824 	if (ip_ire_pmtu_time_elapsed >= ip_ire_pathmtu_interval) {
19825 		/* Increase path mtu */
19826 		flush_flag |= FLUSH_MTU_TIME;
19827 		ip_ire_pmtu_time_elapsed = 0;
19828 		IP_STAT(ip_ire_pmtu_timer_expired);
19829 	}
19830 
19831 	/*
19832 	 * Optimize for the case when there are no redirects in the
19833 	 * ftable, that is, no need to walk the ftable in that case.
19834 	 */
19835 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19836 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19837 		    (char *)(uintptr_t)flush_flag, IP_MASK_TABLE_SIZE, 0, NULL,
19838 		    ip_cache_table_size, ip_cache_table, NULL, ALL_ZONES);
19839 	}
19840 	if ((flush_flag & FLUSH_REDIRECT_TIME) && ip_redirect_cnt > 0) {
19841 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19842 		    ire_expire, (char *)(uintptr_t)flush_flag,
19843 		    IP_MASK_TABLE_SIZE, 0, NULL, 0, NULL, NULL, ALL_ZONES);
19844 	}
19845 	if (flush_flag & FLUSH_MTU_TIME) {
19846 		/*
19847 		 * Walk all IPv6 IRE's and update them
19848 		 * Note that ARP and redirect timers are not
19849 		 * needed since NUD handles stale entries.
19850 		 */
19851 		flush_flag = FLUSH_MTU_TIME;
19852 		ire_walk_v6(ire_expire, (char *)(uintptr_t)flush_flag,
19853 		    ALL_ZONES);
19854 	}
19855 
19856 	ip_ire_arp_time_elapsed += ip_timer_interval;
19857 	ip_ire_rd_time_elapsed += ip_timer_interval;
19858 	ip_ire_pmtu_time_elapsed += ip_timer_interval;
19859 
19860 	/*
19861 	 * Hold the lock to serialize timeout calls and prevent
19862 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19863 	 * for the timer to fire and a new invocation of this function
19864 	 * to start before the return value of timeout has been stored
19865 	 * in ip_ire_expire_id by the current invocation.
19866 	 */
19867 	mutex_enter(&ip_trash_timer_lock);
19868 	ip_ire_expire_id = timeout(ip_trash_timer_expire, NULL,
19869 	    MSEC_TO_TICK(ip_timer_interval));
19870 	mutex_exit(&ip_trash_timer_lock);
19871 }
19872 
19873 /*
19874  * Called by the memory allocator subsystem directly, when the system
19875  * is running low on memory.
19876  */
19877 /* ARGSUSED */
19878 void
19879 ip_trash_ire_reclaim(void *args)
19880 {
19881 	ire_cache_count_t icc;
19882 	ire_cache_reclaim_t icr;
19883 	ncc_cache_count_t ncc;
19884 	nce_cache_reclaim_t ncr;
19885 	uint_t delete_cnt;
19886 	/*
19887 	 * Memory reclaim call back.
19888 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19889 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19890 	 * entries, determine what fraction to free for
19891 	 * each category of IRE_CACHE entries giving absolute priority
19892 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19893 	 * entry will be freed unless all offlink entries are freed).
19894 	 */
19895 	icc.icc_total = 0;
19896 	icc.icc_unused = 0;
19897 	icc.icc_offlink = 0;
19898 	icc.icc_pmtu = 0;
19899 	icc.icc_onlink = 0;
19900 	ire_walk(ire_cache_count, (char *)&icc);
19901 
19902 	/*
19903 	 * Free NCEs for IPv6 like the onlink ires.
19904 	 */
19905 	ncc.ncc_total = 0;
19906 	ncc.ncc_host = 0;
19907 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc);
19908 
19909 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19910 	    icc.icc_pmtu + icc.icc_onlink);
19911 	delete_cnt = icc.icc_total/ip_ire_reclaim_fraction;
19912 	IP_STAT(ip_trash_ire_reclaim_calls);
19913 	if (delete_cnt == 0)
19914 		return;
19915 	IP_STAT(ip_trash_ire_reclaim_success);
19916 	/* Always delete all unused offlink entries */
19917 	icr.icr_unused = 1;
19918 	if (delete_cnt <= icc.icc_unused) {
19919 		/*
19920 		 * Only need to free unused entries.  In other words,
19921 		 * there are enough unused entries to free to meet our
19922 		 * target number of freed ire cache entries.
19923 		 */
19924 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19925 		ncr.ncr_host = 0;
19926 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19927 		/*
19928 		 * Only need to free unused entries, plus a fraction of offlink
19929 		 * entries.  It follows from the first if statement that
19930 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19931 		 */
19932 		delete_cnt -= icc.icc_unused;
19933 		/* Round up # deleted by truncating fraction */
19934 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19935 		icr.icr_pmtu = icr.icr_onlink = 0;
19936 		ncr.ncr_host = 0;
19937 	} else if (delete_cnt <=
19938 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19939 		/*
19940 		 * Free all unused and offlink entries, plus a fraction of
19941 		 * pmtu entries.  It follows from the previous if statement
19942 		 * that icc_pmtu is non-zero, and that
19943 		 * delete_cnt != icc_unused + icc_offlink.
19944 		 */
19945 		icr.icr_offlink = 1;
19946 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19947 		/* Round up # deleted by truncating fraction */
19948 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19949 		icr.icr_onlink = 0;
19950 		ncr.ncr_host = 0;
19951 	} else {
19952 		/*
19953 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19954 		 * of onlink entries.  If we're here, then we know that
19955 		 * icc_onlink is non-zero, and that
19956 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19957 		 */
19958 		icr.icr_offlink = icr.icr_pmtu = 1;
19959 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19960 		    icc.icc_pmtu;
19961 		/* Round up # deleted by truncating fraction */
19962 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19963 		/* Using the same delete fraction as for onlink IREs */
19964 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19965 	}
19966 #ifdef DEBUG
19967 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19968 	    "fractions %d/%d/%d/%d\n",
19969 	    icc.icc_total/ip_ire_reclaim_fraction, icc.icc_total,
19970 	    icc.icc_unused, icc.icc_offlink,
19971 	    icc.icc_pmtu, icc.icc_onlink,
19972 	    icr.icr_unused, icr.icr_offlink,
19973 	    icr.icr_pmtu, icr.icr_onlink));
19974 #endif
19975 	ire_walk(ire_cache_reclaim, (char *)&icr);
19976 	if (ncr.ncr_host != 0)
19977 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19978 		    (uchar_t *)&ncr);
19979 #ifdef DEBUG
19980 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19981 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19982 	ire_walk(ire_cache_count, (char *)&icc);
19983 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19984 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19985 	    icc.icc_pmtu, icc.icc_onlink));
19986 #endif
19987 }
19988 
19989 /*
19990  * ip_unbind is called when a copy of an unbind request is received from the
19991  * upper level protocol.  We remove this conn from any fanout hash list it is
19992  * on, and zero out the bind information.  No reply is expected up above.
19993  */
19994 mblk_t *
19995 ip_unbind(queue_t *q, mblk_t *mp)
19996 {
19997 	conn_t	*connp = Q_TO_CONN(q);
19998 
19999 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20000 
20001 	if (is_system_labeled() && connp->conn_anon_port) {
20002 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20003 		    connp->conn_mlp_type, connp->conn_ulp,
20004 		    ntohs(connp->conn_lport), B_FALSE);
20005 		connp->conn_anon_port = 0;
20006 	}
20007 	connp->conn_mlp_type = mlptSingle;
20008 
20009 	ipcl_hash_remove(connp);
20010 
20011 	ASSERT(mp->b_cont == NULL);
20012 	/*
20013 	 * Convert mp into a T_OK_ACK
20014 	 */
20015 	mp = mi_tpi_ok_ack_alloc(mp);
20016 
20017 	/*
20018 	 * should not happen in practice... T_OK_ACK is smaller than the
20019 	 * original message.
20020 	 */
20021 	if (mp == NULL)
20022 		return (NULL);
20023 
20024 	/*
20025 	 * Don't bzero the ports if its TCP since TCP still needs the
20026 	 * lport to remove it from its own bind hash. TCP will do the
20027 	 * cleanup.
20028 	 */
20029 	if (!IPCL_IS_TCP(connp))
20030 		bzero(&connp->u_port, sizeof (connp->u_port));
20031 
20032 	return (mp);
20033 }
20034 
20035 /*
20036  * Write side put procedure.  Outbound data, IOCTLs, responses from
20037  * resolvers, etc, come down through here.
20038  *
20039  * arg2 is always a queue_t *.
20040  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20041  * the zoneid.
20042  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20043  */
20044 void
20045 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20046 {
20047 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20048 }
20049 
20050 void
20051 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20052     ip_opt_info_t *infop)
20053 {
20054 	conn_t		*connp = NULL;
20055 	queue_t		*q = (queue_t *)arg2;
20056 	ipha_t		*ipha;
20057 #define	rptr	((uchar_t *)ipha)
20058 	ire_t		*ire = NULL;
20059 	ire_t		*sctp_ire = NULL;
20060 	uint32_t	v_hlen_tos_len;
20061 	ipaddr_t	dst;
20062 	mblk_t		*first_mp = NULL;
20063 	boolean_t	mctl_present;
20064 	ipsec_out_t	*io;
20065 	int		match_flags;
20066 	ill_t		*attach_ill = NULL;
20067 					/* Bind to IPIF_NOFAILOVER ill etc. */
20068 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20069 	ipif_t		*dst_ipif;
20070 	boolean_t	multirt_need_resolve = B_FALSE;
20071 	mblk_t		*copy_mp = NULL;
20072 	int		err;
20073 	zoneid_t	zoneid;
20074 	int	adjust;
20075 	uint16_t iplen;
20076 	boolean_t	need_decref = B_FALSE;
20077 	boolean_t	ignore_dontroute = B_FALSE;
20078 	boolean_t	ignore_nexthop = B_FALSE;
20079 	boolean_t	ip_nexthop = B_FALSE;
20080 	ipaddr_t	nexthop_addr;
20081 
20082 #ifdef	_BIG_ENDIAN
20083 #define	V_HLEN	(v_hlen_tos_len >> 24)
20084 #else
20085 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20086 #endif
20087 
20088 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20089 	    "ip_wput_start: q %p", q);
20090 
20091 	/*
20092 	 * ip_wput fast path
20093 	 */
20094 
20095 	/* is packet from ARP ? */
20096 	if (q->q_next != NULL) {
20097 		zoneid = (zoneid_t)(uintptr_t)arg;
20098 		goto qnext;
20099 	}
20100 
20101 	connp = (conn_t *)arg;
20102 	ASSERT(connp != NULL);
20103 	zoneid = connp->conn_zoneid;
20104 
20105 	/* is queue flow controlled? */
20106 	if ((q->q_first != NULL || connp->conn_draining) &&
20107 	    (caller == IP_WPUT)) {
20108 		ASSERT(!need_decref);
20109 		(void) putq(q, mp);
20110 		return;
20111 	}
20112 
20113 	/* Multidata transmit? */
20114 	if (DB_TYPE(mp) == M_MULTIDATA) {
20115 		/*
20116 		 * We should never get here, since all Multidata messages
20117 		 * originating from tcp should have been directed over to
20118 		 * tcp_multisend() in the first place.
20119 		 */
20120 		BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20121 		freemsg(mp);
20122 		return;
20123 	} else if (DB_TYPE(mp) != M_DATA)
20124 		goto notdata;
20125 
20126 	if (mp->b_flag & MSGHASREF) {
20127 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20128 		mp->b_flag &= ~MSGHASREF;
20129 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20130 		need_decref = B_TRUE;
20131 	}
20132 	ipha = (ipha_t *)mp->b_rptr;
20133 
20134 	/* is IP header non-aligned or mblk smaller than basic IP header */
20135 #ifndef SAFETY_BEFORE_SPEED
20136 	if (!OK_32PTR(rptr) ||
20137 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20138 		goto hdrtoosmall;
20139 #endif
20140 
20141 	ASSERT(OK_32PTR(ipha));
20142 
20143 	/*
20144 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20145 	 * wrong version, we'll catch it again in ip_output_v6.
20146 	 *
20147 	 * Note that this is *only* locally-generated output here, and never
20148 	 * forwarded data, and that we need to deal only with transports that
20149 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20150 	 * label.)
20151 	 */
20152 	if (is_system_labeled() &&
20153 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20154 	    !connp->conn_ulp_labeled) {
20155 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20156 		    connp->conn_mac_exempt);
20157 		ipha = (ipha_t *)mp->b_rptr;
20158 		if (err != 0) {
20159 			first_mp = mp;
20160 			if (err == EINVAL)
20161 				goto icmp_parameter_problem;
20162 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20163 			goto discard_pkt;
20164 		}
20165 		iplen = ntohs(ipha->ipha_length) + adjust;
20166 		ipha->ipha_length = htons(iplen);
20167 	}
20168 
20169 	ASSERT(infop != NULL);
20170 
20171 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20172 		/*
20173 		 * IP_PKTINFO ancillary option is present.
20174 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20175 		 * allows using address of any zone as the source address.
20176 		 */
20177 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20178 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20179 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY);
20180 		if (ire == NULL)
20181 			goto drop_pkt;
20182 		ire_refrele(ire);
20183 		ire = NULL;
20184 	}
20185 
20186 	/*
20187 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20188 	 * ill index passed in IP_PKTINFO.
20189 	 */
20190 	if (infop->ip_opt_ill_index != 0 &&
20191 	    connp->conn_xmit_if_ill == NULL &&
20192 	    connp->conn_nofailover_ill == NULL) {
20193 
20194 		xmit_ill = ill_lookup_on_ifindex(
20195 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL);
20196 
20197 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20198 			goto drop_pkt;
20199 		/*
20200 		 * check that there is an ipif belonging
20201 		 * to our zone. IPCL_ZONEID is not used because
20202 		 * IP_ALLZONES option is valid only when the ill is
20203 		 * accessible from all zones i.e has a valid ipif in
20204 		 * all zones.
20205 		 */
20206 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20207 			goto drop_pkt;
20208 		}
20209 	}
20210 
20211 	/*
20212 	 * If there is a policy, try to attach an ipsec_out in
20213 	 * the front. At the end, first_mp either points to a
20214 	 * M_DATA message or IPSEC_OUT message linked to a
20215 	 * M_DATA message. We have to do it now as we might
20216 	 * lose the "conn" if we go through ip_newroute.
20217 	 */
20218 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20219 		if (((mp = ipsec_attach_ipsec_out(mp, connp, NULL,
20220 		    ipha->ipha_protocol)) == NULL)) {
20221 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20222 			if (need_decref)
20223 				CONN_DEC_REF(connp);
20224 			return;
20225 		} else {
20226 			ASSERT(mp->b_datap->db_type == M_CTL);
20227 			first_mp = mp;
20228 			mp = mp->b_cont;
20229 			mctl_present = B_TRUE;
20230 		}
20231 	} else {
20232 		first_mp = mp;
20233 		mctl_present = B_FALSE;
20234 	}
20235 
20236 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20237 
20238 	/* is wrong version or IP options present */
20239 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20240 		goto version_hdrlen_check;
20241 	dst = ipha->ipha_dst;
20242 
20243 	if (connp->conn_nofailover_ill != NULL) {
20244 		attach_ill = conn_get_held_ill(connp,
20245 		    &connp->conn_nofailover_ill, &err);
20246 		if (err == ILL_LOOKUP_FAILED) {
20247 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20248 			if (need_decref)
20249 				CONN_DEC_REF(connp);
20250 			freemsg(first_mp);
20251 			return;
20252 		}
20253 	}
20254 
20255 
20256 	/* is packet multicast? */
20257 	if (CLASSD(dst))
20258 		goto multicast;
20259 
20260 	/*
20261 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20262 	 * takes precedence over conn_dontroute and conn_nexthop_set
20263 	 */
20264 	if (xmit_ill != NULL) {
20265 		goto send_from_ill;
20266 	}
20267 
20268 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20269 	    (connp->conn_nexthop_set)) {
20270 		/*
20271 		 * If the destination is a broadcast or a loopback
20272 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20273 		 * through the standard path. But in the case of local
20274 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20275 		 * the standard path not IP_XMIT_IF.
20276 		 */
20277 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20278 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20279 		    (ire->ire_type != IRE_LOOPBACK))) {
20280 			if ((connp->conn_dontroute ||
20281 			    connp->conn_nexthop_set) && (ire != NULL) &&
20282 			    (ire->ire_type == IRE_LOCAL))
20283 				goto standard_path;
20284 
20285 			if (ire != NULL) {
20286 				ire_refrele(ire);
20287 				/* No more access to ire */
20288 				ire = NULL;
20289 			}
20290 			/*
20291 			 * bypass routing checks and go directly to
20292 			 * interface.
20293 			 */
20294 			if (connp->conn_dontroute) {
20295 				goto dontroute;
20296 			} else if (connp->conn_nexthop_set) {
20297 				ip_nexthop = B_TRUE;
20298 				nexthop_addr = connp->conn_nexthop_v4;
20299 				goto send_from_ill;
20300 			}
20301 
20302 			/*
20303 			 * If IP_XMIT_IF socket option is set,
20304 			 * then we allow unicast and multicast
20305 			 * packets to go through the ill. It is
20306 			 * quite possible that the destination
20307 			 * is not in the ire cache table and we
20308 			 * do not want to go to ip_newroute()
20309 			 * instead we call ip_newroute_ipif.
20310 			 */
20311 			xmit_ill = conn_get_held_ill(connp,
20312 			    &connp->conn_xmit_if_ill, &err);
20313 			if (err == ILL_LOOKUP_FAILED) {
20314 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20315 				if (attach_ill != NULL)
20316 					ill_refrele(attach_ill);
20317 				if (need_decref)
20318 					CONN_DEC_REF(connp);
20319 				freemsg(first_mp);
20320 				return;
20321 			}
20322 			goto send_from_ill;
20323 		}
20324 standard_path:
20325 		/* Must be a broadcast, a loopback or a local ire */
20326 		if (ire != NULL) {
20327 			ire_refrele(ire);
20328 			/* No more access to ire */
20329 			ire = NULL;
20330 		}
20331 	}
20332 
20333 	if (attach_ill != NULL)
20334 		goto send_from_ill;
20335 
20336 	/*
20337 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20338 	 * this for the tcp global queue and listen end point
20339 	 * as it does not really have a real destination to
20340 	 * talk to.  This is also true for SCTP.
20341 	 */
20342 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20343 	    !connp->conn_fully_bound) {
20344 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20345 		if (ire == NULL)
20346 			goto noirefound;
20347 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20348 		    "ip_wput_end: q %p (%S)", q, "end");
20349 
20350 		/*
20351 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20352 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20353 		 */
20354 		if (ire->ire_flags & RTF_MULTIRT) {
20355 
20356 			/*
20357 			 * Force the TTL of multirouted packets if required.
20358 			 * The TTL of such packets is bounded by the
20359 			 * ip_multirt_ttl ndd variable.
20360 			 */
20361 			if ((ip_multirt_ttl > 0) &&
20362 			    (ipha->ipha_ttl > ip_multirt_ttl)) {
20363 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20364 				    "(was %d), dst 0x%08x\n",
20365 				    ip_multirt_ttl, ipha->ipha_ttl,
20366 				    ntohl(ire->ire_addr)));
20367 				ipha->ipha_ttl = ip_multirt_ttl;
20368 			}
20369 			/*
20370 			 * We look at this point if there are pending
20371 			 * unresolved routes. ire_multirt_resolvable()
20372 			 * checks in O(n) that all IRE_OFFSUBNET ire
20373 			 * entries for the packet's destination and
20374 			 * flagged RTF_MULTIRT are currently resolved.
20375 			 * If some remain unresolved, we make a copy
20376 			 * of the current message. It will be used
20377 			 * to initiate additional route resolutions.
20378 			 */
20379 			multirt_need_resolve =
20380 			    ire_multirt_need_resolve(ire->ire_addr,
20381 			    MBLK_GETLABEL(first_mp));
20382 			ip2dbg(("ip_wput[TCP]: ire %p, "
20383 			    "multirt_need_resolve %d, first_mp %p\n",
20384 			    (void *)ire, multirt_need_resolve,
20385 			    (void *)first_mp));
20386 			if (multirt_need_resolve) {
20387 				copy_mp = copymsg(first_mp);
20388 				if (copy_mp != NULL) {
20389 					MULTIRT_DEBUG_TAG(copy_mp);
20390 				}
20391 			}
20392 		}
20393 
20394 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20395 
20396 		/*
20397 		 * Try to resolve another multiroute if
20398 		 * ire_multirt_need_resolve() deemed it necessary.
20399 		 */
20400 		if (copy_mp != NULL) {
20401 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20402 		}
20403 		if (need_decref)
20404 			CONN_DEC_REF(connp);
20405 		return;
20406 	}
20407 
20408 	/*
20409 	 * Access to conn_ire_cache. (protected by conn_lock)
20410 	 *
20411 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20412 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20413 	 * send a packet or two with the IRE_CACHE that is going away.
20414 	 * Access to the ire requires an ire refhold on the ire prior to
20415 	 * its use since an interface unplumb thread may delete the cached
20416 	 * ire and release the refhold at any time.
20417 	 *
20418 	 * Caching an ire in the conn_ire_cache
20419 	 *
20420 	 * o Caching an ire pointer in the conn requires a strict check for
20421 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20422 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20423 	 * in the conn is done after making sure under the bucket lock that the
20424 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20425 	 * caching an ire after the unplumb thread has cleaned up the conn.
20426 	 * If the conn does not send a packet subsequently the unplumb thread
20427 	 * will be hanging waiting for the ire count to drop to zero.
20428 	 *
20429 	 * o We also need to atomically test for a null conn_ire_cache and
20430 	 * set the conn_ire_cache under the the protection of the conn_lock
20431 	 * to avoid races among concurrent threads trying to simultaneously
20432 	 * cache an ire in the conn_ire_cache.
20433 	 */
20434 	mutex_enter(&connp->conn_lock);
20435 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20436 
20437 	if (ire != NULL && ire->ire_addr == dst &&
20438 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20439 
20440 		IRE_REFHOLD(ire);
20441 		mutex_exit(&connp->conn_lock);
20442 
20443 	} else {
20444 		boolean_t cached = B_FALSE;
20445 		connp->conn_ire_cache = NULL;
20446 		mutex_exit(&connp->conn_lock);
20447 		/* Release the old ire */
20448 		if (ire != NULL && sctp_ire == NULL)
20449 			IRE_REFRELE_NOTR(ire);
20450 
20451 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
20452 		if (ire == NULL)
20453 			goto noirefound;
20454 		IRE_REFHOLD_NOTR(ire);
20455 
20456 		mutex_enter(&connp->conn_lock);
20457 		if (!(connp->conn_state_flags & CONN_CLOSING) &&
20458 		    connp->conn_ire_cache == NULL) {
20459 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20460 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20461 				connp->conn_ire_cache = ire;
20462 				cached = B_TRUE;
20463 			}
20464 			rw_exit(&ire->ire_bucket->irb_lock);
20465 		}
20466 		mutex_exit(&connp->conn_lock);
20467 
20468 		/*
20469 		 * We can continue to use the ire but since it was
20470 		 * not cached, we should drop the extra reference.
20471 		 */
20472 		if (!cached)
20473 			IRE_REFRELE_NOTR(ire);
20474 	}
20475 
20476 
20477 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20478 	    "ip_wput_end: q %p (%S)", q, "end");
20479 
20480 	/*
20481 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20482 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20483 	 */
20484 	if (ire->ire_flags & RTF_MULTIRT) {
20485 
20486 		/*
20487 		 * Force the TTL of multirouted packets if required.
20488 		 * The TTL of such packets is bounded by the
20489 		 * ip_multirt_ttl ndd variable.
20490 		 */
20491 		if ((ip_multirt_ttl > 0) &&
20492 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
20493 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20494 			    "(was %d), dst 0x%08x\n",
20495 			    ip_multirt_ttl, ipha->ipha_ttl,
20496 			    ntohl(ire->ire_addr)));
20497 			ipha->ipha_ttl = ip_multirt_ttl;
20498 		}
20499 
20500 		/*
20501 		 * At this point, we check to see if there are any pending
20502 		 * unresolved routes. ire_multirt_resolvable()
20503 		 * checks in O(n) that all IRE_OFFSUBNET ire
20504 		 * entries for the packet's destination and
20505 		 * flagged RTF_MULTIRT are currently resolved.
20506 		 * If some remain unresolved, we make a copy
20507 		 * of the current message. It will be used
20508 		 * to initiate additional route resolutions.
20509 		 */
20510 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20511 		    MBLK_GETLABEL(first_mp));
20512 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20513 		    "multirt_need_resolve %d, first_mp %p\n",
20514 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20515 		if (multirt_need_resolve) {
20516 			copy_mp = copymsg(first_mp);
20517 			if (copy_mp != NULL) {
20518 				MULTIRT_DEBUG_TAG(copy_mp);
20519 			}
20520 		}
20521 	}
20522 
20523 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20524 
20525 	/*
20526 	 * Try to resolve another multiroute if
20527 	 * ire_multirt_resolvable() deemed it necessary
20528 	 */
20529 	if (copy_mp != NULL) {
20530 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
20531 	}
20532 	if (need_decref)
20533 		CONN_DEC_REF(connp);
20534 	return;
20535 
20536 qnext:
20537 	/*
20538 	 * Upper Level Protocols pass down complete IP datagrams
20539 	 * as M_DATA messages.	Everything else is a sideshow.
20540 	 *
20541 	 * 1) We could be re-entering ip_wput because of ip_neworute
20542 	 *    in which case we could have a IPSEC_OUT message. We
20543 	 *    need to pass through ip_wput like other datagrams and
20544 	 *    hence cannot branch to ip_wput_nondata.
20545 	 *
20546 	 * 2) ARP, AH, ESP, and other clients who are on the module
20547 	 *    instance of IP stream, give us something to deal with.
20548 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20549 	 *
20550 	 * 3) ICMP replies also could come here.
20551 	 */
20552 	if (DB_TYPE(mp) != M_DATA) {
20553 	    notdata:
20554 		if (DB_TYPE(mp) == M_CTL) {
20555 			/*
20556 			 * M_CTL messages are used by ARP, AH and ESP to
20557 			 * communicate with IP. We deal with IPSEC_IN and
20558 			 * IPSEC_OUT here. ip_wput_nondata handles other
20559 			 * cases.
20560 			 */
20561 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20562 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20563 				first_mp = mp->b_cont;
20564 				first_mp->b_flag &= ~MSGHASREF;
20565 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20566 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20567 				CONN_DEC_REF(connp);
20568 				connp = NULL;
20569 			}
20570 			if (ii->ipsec_info_type == IPSEC_IN) {
20571 				/*
20572 				 * Either this message goes back to
20573 				 * IPSEC for further processing or to
20574 				 * ULP after policy checks.
20575 				 */
20576 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20577 				return;
20578 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20579 				io = (ipsec_out_t *)ii;
20580 				if (io->ipsec_out_proc_begin) {
20581 					/*
20582 					 * IPSEC processing has already started.
20583 					 * Complete it.
20584 					 * IPQoS notes: We don't care what is
20585 					 * in ipsec_out_ill_index since this
20586 					 * won't be processed for IPQoS policies
20587 					 * in ipsec_out_process.
20588 					 */
20589 					ipsec_out_process(q, mp, NULL,
20590 					    io->ipsec_out_ill_index);
20591 					return;
20592 				} else {
20593 					connp = (q->q_next != NULL) ?
20594 					    NULL : Q_TO_CONN(q);
20595 					first_mp = mp;
20596 					mp = mp->b_cont;
20597 					mctl_present = B_TRUE;
20598 				}
20599 				zoneid = io->ipsec_out_zoneid;
20600 				ASSERT(zoneid != ALL_ZONES);
20601 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20602 				/*
20603 				 * It's an IPsec control message requesting
20604 				 * an SADB update to be sent to the IPsec
20605 				 * hardware acceleration capable ills.
20606 				 */
20607 				ipsec_ctl_t *ipsec_ctl =
20608 				    (ipsec_ctl_t *)mp->b_rptr;
20609 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20610 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20611 				mblk_t *cmp = mp->b_cont;
20612 
20613 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20614 				ASSERT(cmp != NULL);
20615 
20616 				freeb(mp);
20617 				ill_ipsec_capab_send_all(satype, cmp, sa);
20618 				return;
20619 			} else {
20620 				/*
20621 				 * This must be ARP or special TSOL signaling.
20622 				 */
20623 				ip_wput_nondata(NULL, q, mp, NULL);
20624 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20625 				    "ip_wput_end: q %p (%S)", q, "nondata");
20626 				return;
20627 			}
20628 		} else {
20629 			/*
20630 			 * This must be non-(ARP/AH/ESP) messages.
20631 			 */
20632 			ASSERT(!need_decref);
20633 			ip_wput_nondata(NULL, q, mp, NULL);
20634 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20635 			    "ip_wput_end: q %p (%S)", q, "nondata");
20636 			return;
20637 		}
20638 	} else {
20639 		first_mp = mp;
20640 		mctl_present = B_FALSE;
20641 	}
20642 
20643 	ASSERT(first_mp != NULL);
20644 	/*
20645 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20646 	 * to make sure that this packet goes out on the same interface it
20647 	 * came in. We handle that here.
20648 	 */
20649 	if (mctl_present) {
20650 		uint_t ifindex;
20651 
20652 		io = (ipsec_out_t *)first_mp->b_rptr;
20653 		if (io->ipsec_out_attach_if ||
20654 		    io->ipsec_out_xmit_if ||
20655 		    io->ipsec_out_ip_nexthop) {
20656 			ill_t	*ill;
20657 
20658 			/*
20659 			 * We may have lost the conn context if we are
20660 			 * coming here from ip_newroute(). Copy the
20661 			 * nexthop information.
20662 			 */
20663 			if (io->ipsec_out_ip_nexthop) {
20664 				ip_nexthop = B_TRUE;
20665 				nexthop_addr = io->ipsec_out_nexthop_addr;
20666 
20667 				ipha = (ipha_t *)mp->b_rptr;
20668 				dst = ipha->ipha_dst;
20669 				goto send_from_ill;
20670 			} else {
20671 				ASSERT(io->ipsec_out_ill_index != 0);
20672 				ifindex = io->ipsec_out_ill_index;
20673 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20674 				    NULL, NULL, NULL, NULL);
20675 				/*
20676 				 * ipsec_out_xmit_if bit is used to tell
20677 				 * ip_wput to use the ill to send outgoing data
20678 				 * as we have no conn when data comes from ICMP
20679 				 * error msg routines. Currently this feature is
20680 				 * only used by ip_mrtun_forward routine.
20681 				 */
20682 				if (io->ipsec_out_xmit_if) {
20683 					xmit_ill = ill;
20684 					if (xmit_ill == NULL) {
20685 						ip1dbg(("ip_output:bad ifindex "
20686 						    "for xmit_ill %d\n",
20687 						    ifindex));
20688 						freemsg(first_mp);
20689 						BUMP_MIB(&ip_mib,
20690 						    ipIfStatsOutDiscards);
20691 						ASSERT(!need_decref);
20692 						return;
20693 					}
20694 					/* Free up the ipsec_out_t mblk */
20695 					ASSERT(first_mp->b_cont == mp);
20696 					first_mp->b_cont = NULL;
20697 					freeb(first_mp);
20698 					/* Just send the IP header+ICMP+data */
20699 					first_mp = mp;
20700 					ipha = (ipha_t *)mp->b_rptr;
20701 					dst = ipha->ipha_dst;
20702 					goto send_from_ill;
20703 				} else {
20704 					attach_ill = ill;
20705 				}
20706 
20707 				if (attach_ill == NULL) {
20708 					ASSERT(xmit_ill == NULL);
20709 					ip1dbg(("ip_output: bad ifindex for "
20710 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20711 					    ifindex));
20712 					freemsg(first_mp);
20713 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20714 					ASSERT(!need_decref);
20715 					return;
20716 				}
20717 			}
20718 		}
20719 	}
20720 
20721 	ASSERT(xmit_ill == NULL);
20722 
20723 	/* We have a complete IP datagram heading outbound. */
20724 	ipha = (ipha_t *)mp->b_rptr;
20725 
20726 #ifndef SPEED_BEFORE_SAFETY
20727 	/*
20728 	 * Make sure we have a full-word aligned message and that at least
20729 	 * a simple IP header is accessible in the first message.  If not,
20730 	 * try a pullup.
20731 	 */
20732 	if (!OK_32PTR(rptr) ||
20733 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20734 	    hdrtoosmall:
20735 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20736 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20737 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20738 			if (first_mp == NULL)
20739 				first_mp = mp;
20740 			goto discard_pkt;
20741 		}
20742 
20743 		/* This function assumes that mp points to an IPv4 packet. */
20744 		if (is_system_labeled() && q->q_next == NULL &&
20745 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20746 		    !connp->conn_ulp_labeled) {
20747 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20748 			    &adjust, connp->conn_mac_exempt);
20749 			ipha = (ipha_t *)mp->b_rptr;
20750 			if (first_mp != NULL)
20751 				first_mp->b_cont = mp;
20752 			if (err != 0) {
20753 				if (first_mp == NULL)
20754 					first_mp = mp;
20755 				if (err == EINVAL)
20756 					goto icmp_parameter_problem;
20757 				ip2dbg(("ip_wput: label check failed (%d)\n",
20758 				    err));
20759 				goto discard_pkt;
20760 			}
20761 			iplen = ntohs(ipha->ipha_length) + adjust;
20762 			ipha->ipha_length = htons(iplen);
20763 		}
20764 
20765 		ipha = (ipha_t *)mp->b_rptr;
20766 		if (first_mp == NULL) {
20767 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20768 			/*
20769 			 * If we got here because of "goto hdrtoosmall"
20770 			 * We need to attach a IPSEC_OUT.
20771 			 */
20772 			if (connp->conn_out_enforce_policy) {
20773 				if (((mp = ipsec_attach_ipsec_out(mp, connp,
20774 				    NULL, ipha->ipha_protocol)) == NULL)) {
20775 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20776 					if (need_decref)
20777 						CONN_DEC_REF(connp);
20778 					return;
20779 				} else {
20780 					ASSERT(mp->b_datap->db_type == M_CTL);
20781 					first_mp = mp;
20782 					mp = mp->b_cont;
20783 					mctl_present = B_TRUE;
20784 				}
20785 			} else {
20786 				first_mp = mp;
20787 				mctl_present = B_FALSE;
20788 			}
20789 		}
20790 	}
20791 #endif
20792 
20793 	/* Most of the code below is written for speed, not readability */
20794 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20795 
20796 	/*
20797 	 * If ip_newroute() fails, we're going to need a full
20798 	 * header for the icmp wraparound.
20799 	 */
20800 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20801 		uint_t	v_hlen;
20802 	    version_hdrlen_check:
20803 		ASSERT(first_mp != NULL);
20804 		v_hlen = V_HLEN;
20805 		/*
20806 		 * siphon off IPv6 packets coming down from transport
20807 		 * layer modules here.
20808 		 * Note: high-order bit carries NUD reachability confirmation
20809 		 */
20810 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20811 			/*
20812 			 * XXX implement a IPv4 and IPv6 packet counter per
20813 			 * conn and switch when ratio exceeds e.g. 10:1
20814 			 */
20815 #ifdef notyet
20816 			if (q->q_next == NULL) /* Avoid ill queue */
20817 				ip_setqinfo(RD(q), B_TRUE, B_TRUE);
20818 #endif
20819 			BUMP_MIB(&ip_mib, ipIfStatsOutWrongIPVersion);
20820 			ASSERT(xmit_ill == NULL);
20821 			if (attach_ill != NULL)
20822 				ill_refrele(attach_ill);
20823 			if (need_decref)
20824 				mp->b_flag |= MSGHASREF;
20825 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20826 			return;
20827 		}
20828 
20829 		if ((v_hlen >> 4) != IP_VERSION) {
20830 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20831 			    "ip_wput_end: q %p (%S)", q, "badvers");
20832 			goto discard_pkt;
20833 		}
20834 		/*
20835 		 * Is the header length at least 20 bytes?
20836 		 *
20837 		 * Are there enough bytes accessible in the header?  If
20838 		 * not, try a pullup.
20839 		 */
20840 		v_hlen &= 0xF;
20841 		v_hlen <<= 2;
20842 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20843 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20844 			    "ip_wput_end: q %p (%S)", q, "badlen");
20845 			goto discard_pkt;
20846 		}
20847 		if (v_hlen > (mp->b_wptr - rptr)) {
20848 			if (!pullupmsg(mp, v_hlen)) {
20849 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20850 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20851 				goto discard_pkt;
20852 			}
20853 			ipha = (ipha_t *)mp->b_rptr;
20854 		}
20855 		/*
20856 		 * Move first entry from any source route into ipha_dst and
20857 		 * verify the options
20858 		 */
20859 		if (ip_wput_options(q, first_mp, ipha, mctl_present, zoneid)) {
20860 			ASSERT(xmit_ill == NULL);
20861 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
20862 			if (attach_ill != NULL)
20863 				ill_refrele(attach_ill);
20864 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20865 			    "ip_wput_end: q %p (%S)", q, "badopts");
20866 			if (need_decref)
20867 				CONN_DEC_REF(connp);
20868 			return;
20869 		}
20870 	}
20871 	dst = ipha->ipha_dst;
20872 
20873 	/*
20874 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20875 	 * we have to run the packet through ip_newroute which will take
20876 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20877 	 * a resolver, or assigning a default gateway, etc.
20878 	 */
20879 	if (CLASSD(dst)) {
20880 		ipif_t	*ipif;
20881 		uint32_t setsrc = 0;
20882 
20883 	    multicast:
20884 		ASSERT(first_mp != NULL);
20885 		ip2dbg(("ip_wput: CLASSD\n"));
20886 		if (connp == NULL) {
20887 			/*
20888 			 * Use the first good ipif on the ill.
20889 			 * XXX Should this ever happen? (Appears
20890 			 * to show up with just ppp and no ethernet due
20891 			 * to in.rdisc.)
20892 			 * However, ire_send should be able to
20893 			 * call ip_wput_ire directly.
20894 			 *
20895 			 * XXX Also, this can happen for ICMP and other packets
20896 			 * with multicast source addresses.  Perhaps we should
20897 			 * fix things so that we drop the packet in question,
20898 			 * but for now, just run with it.
20899 			 */
20900 			ill_t *ill = (ill_t *)q->q_ptr;
20901 
20902 			/*
20903 			 * Don't honor attach_if for this case. If ill
20904 			 * is part of the group, ipif could belong to
20905 			 * any ill and we cannot maintain attach_ill
20906 			 * and ipif_ill same anymore and the assert
20907 			 * below would fail.
20908 			 */
20909 			if (mctl_present && io->ipsec_out_attach_if) {
20910 				io->ipsec_out_ill_index = 0;
20911 				io->ipsec_out_attach_if = B_FALSE;
20912 				ASSERT(attach_ill != NULL);
20913 				ill_refrele(attach_ill);
20914 				attach_ill = NULL;
20915 			}
20916 
20917 			ASSERT(attach_ill == NULL);
20918 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20919 			if (ipif == NULL) {
20920 				if (need_decref)
20921 					CONN_DEC_REF(connp);
20922 				freemsg(first_mp);
20923 				return;
20924 			}
20925 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20926 			    ntohl(dst), ill->ill_name));
20927 		} else {
20928 			/*
20929 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20930 			 * and IP_MULTICAST_IF.
20931 			 * Block comment above this function explains the
20932 			 * locking mechanism used here
20933 			 */
20934 			if (xmit_ill == NULL) {
20935 				xmit_ill = conn_get_held_ill(connp,
20936 				    &connp->conn_xmit_if_ill, &err);
20937 				if (err == ILL_LOOKUP_FAILED) {
20938 					ip1dbg(("ip_wput: No ill for "
20939 					    "IP_XMIT_IF\n"));
20940 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20941 					goto drop_pkt;
20942 				}
20943 			}
20944 
20945 			if (xmit_ill == NULL) {
20946 				ipif = conn_get_held_ipif(connp,
20947 				    &connp->conn_multicast_ipif, &err);
20948 				if (err == IPIF_LOOKUP_FAILED) {
20949 					ip1dbg(("ip_wput: No ipif for "
20950 					    "multicast\n"));
20951 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20952 					goto drop_pkt;
20953 				}
20954 			}
20955 			if (xmit_ill != NULL) {
20956 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20957 				if (ipif == NULL) {
20958 					ip1dbg(("ip_wput: No ipif for "
20959 					    "IP_XMIT_IF\n"));
20960 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20961 					goto drop_pkt;
20962 				}
20963 			} else if (ipif == NULL || ipif->ipif_isv6) {
20964 				/*
20965 				 * We must do this ipif determination here
20966 				 * else we could pass through ip_newroute
20967 				 * and come back here without the conn context.
20968 				 *
20969 				 * Note: we do late binding i.e. we bind to
20970 				 * the interface when the first packet is sent.
20971 				 * For performance reasons we do not rebind on
20972 				 * each packet but keep the binding until the
20973 				 * next IP_MULTICAST_IF option.
20974 				 *
20975 				 * conn_multicast_{ipif,ill} are shared between
20976 				 * IPv4 and IPv6 and AF_INET6 sockets can
20977 				 * send both IPv4 and IPv6 packets. Hence
20978 				 * we have to check that "isv6" matches above.
20979 				 */
20980 				if (ipif != NULL)
20981 					ipif_refrele(ipif);
20982 				ipif = ipif_lookup_group(dst, zoneid);
20983 				if (ipif == NULL) {
20984 					ip1dbg(("ip_wput: No ipif for "
20985 					    "multicast\n"));
20986 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20987 					goto drop_pkt;
20988 				}
20989 				err = conn_set_held_ipif(connp,
20990 				    &connp->conn_multicast_ipif, ipif);
20991 				if (err == IPIF_LOOKUP_FAILED) {
20992 					ipif_refrele(ipif);
20993 					ip1dbg(("ip_wput: No ipif for "
20994 					    "multicast\n"));
20995 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
20996 					goto drop_pkt;
20997 				}
20998 			}
20999 		}
21000 		ASSERT(!ipif->ipif_isv6);
21001 		/*
21002 		 * As we may lose the conn by the time we reach ip_wput_ire,
21003 		 * we copy conn_multicast_loop and conn_dontroute on to an
21004 		 * ipsec_out. In case if this datagram goes out secure,
21005 		 * we need the ill_index also. Copy that also into the
21006 		 * ipsec_out.
21007 		 */
21008 		if (mctl_present) {
21009 			io = (ipsec_out_t *)first_mp->b_rptr;
21010 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21011 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21012 		} else {
21013 			ASSERT(mp == first_mp);
21014 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21015 			    BPRI_HI)) == NULL) {
21016 				ipif_refrele(ipif);
21017 				first_mp = mp;
21018 				goto discard_pkt;
21019 			}
21020 			first_mp->b_datap->db_type = M_CTL;
21021 			first_mp->b_wptr += sizeof (ipsec_info_t);
21022 			/* ipsec_out_secure is B_FALSE now */
21023 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21024 			io = (ipsec_out_t *)first_mp->b_rptr;
21025 			io->ipsec_out_type = IPSEC_OUT;
21026 			io->ipsec_out_len = sizeof (ipsec_out_t);
21027 			io->ipsec_out_use_global_policy = B_TRUE;
21028 			first_mp->b_cont = mp;
21029 			mctl_present = B_TRUE;
21030 		}
21031 		if (attach_ill != NULL) {
21032 			ASSERT(attach_ill == ipif->ipif_ill);
21033 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21034 
21035 			/*
21036 			 * Check if we need an ire that will not be
21037 			 * looked up by anybody else i.e. HIDDEN.
21038 			 */
21039 			if (ill_is_probeonly(attach_ill)) {
21040 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21041 			}
21042 			io->ipsec_out_ill_index =
21043 			    attach_ill->ill_phyint->phyint_ifindex;
21044 			io->ipsec_out_attach_if = B_TRUE;
21045 		} else {
21046 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21047 			io->ipsec_out_ill_index =
21048 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21049 		}
21050 		if (connp != NULL) {
21051 			io->ipsec_out_multicast_loop =
21052 			    connp->conn_multicast_loop;
21053 			io->ipsec_out_dontroute = connp->conn_dontroute;
21054 			io->ipsec_out_zoneid = connp->conn_zoneid;
21055 		}
21056 		/*
21057 		 * If the application uses IP_MULTICAST_IF with
21058 		 * different logical addresses of the same ILL, we
21059 		 * need to make sure that the soruce address of
21060 		 * the packet matches the logical IP address used
21061 		 * in the option. We do it by initializing ipha_src
21062 		 * here. This should keep IPSEC also happy as
21063 		 * when we return from IPSEC processing, we don't
21064 		 * have to worry about getting the right address on
21065 		 * the packet. Thus it is sufficient to look for
21066 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21067 		 * MATCH_IRE_IPIF.
21068 		 *
21069 		 * NOTE : We need to do it for non-secure case also as
21070 		 * this might go out secure if there is a global policy
21071 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21072 		 * address, the source should be initialized already and
21073 		 * hence we won't be initializing here.
21074 		 *
21075 		 * As we do not have the ire yet, it is possible that
21076 		 * we set the source address here and then later discover
21077 		 * that the ire implies the source address to be assigned
21078 		 * through the RTF_SETSRC flag.
21079 		 * In that case, the setsrc variable will remind us
21080 		 * that overwritting the source address by the one
21081 		 * of the RTF_SETSRC-flagged ire is allowed.
21082 		 */
21083 		if (ipha->ipha_src == INADDR_ANY &&
21084 		    (connp == NULL || !connp->conn_unspec_src)) {
21085 			ipha->ipha_src = ipif->ipif_src_addr;
21086 			setsrc = RTF_SETSRC;
21087 		}
21088 		/*
21089 		 * Find an IRE which matches the destination and the outgoing
21090 		 * queue (i.e. the outgoing interface.)
21091 		 * For loopback use a unicast IP address for
21092 		 * the ire lookup.
21093 		 */
21094 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
21095 		    PHYI_LOOPBACK) {
21096 			dst = ipif->ipif_lcl_addr;
21097 		}
21098 		/*
21099 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21100 		 * We don't need to lookup ire in ctable as the packet
21101 		 * needs to be sent to the destination through the specified
21102 		 * ill irrespective of ires in the cache table.
21103 		 */
21104 		ire = NULL;
21105 		if (xmit_ill == NULL) {
21106 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21107 			    zoneid, MBLK_GETLABEL(mp), match_flags);
21108 		}
21109 
21110 		/*
21111 		 * refrele attach_ill as its not needed anymore.
21112 		 */
21113 		if (attach_ill != NULL) {
21114 			ill_refrele(attach_ill);
21115 			attach_ill = NULL;
21116 		}
21117 
21118 		if (ire == NULL) {
21119 			/*
21120 			 * Multicast loopback and multicast forwarding is
21121 			 * done in ip_wput_ire.
21122 			 *
21123 			 * Mark this packet to make it be delivered to
21124 			 * ip_wput_ire after the new ire has been
21125 			 * created.
21126 			 *
21127 			 * The call to ip_newroute_ipif takes into account
21128 			 * the setsrc reminder. In any case, we take care
21129 			 * of the RTF_MULTIRT flag.
21130 			 */
21131 			mp->b_prev = mp->b_next = NULL;
21132 			if (xmit_ill == NULL ||
21133 			    xmit_ill->ill_ipif_up_count > 0) {
21134 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21135 				    setsrc | RTF_MULTIRT, zoneid, infop);
21136 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21137 				    "ip_wput_end: q %p (%S)", q, "noire");
21138 			} else {
21139 				freemsg(first_mp);
21140 			}
21141 			ipif_refrele(ipif);
21142 			if (xmit_ill != NULL)
21143 				ill_refrele(xmit_ill);
21144 			if (need_decref)
21145 				CONN_DEC_REF(connp);
21146 			return;
21147 		}
21148 
21149 		ipif_refrele(ipif);
21150 		ipif = NULL;
21151 		ASSERT(xmit_ill == NULL);
21152 
21153 		/*
21154 		 * Honor the RTF_SETSRC flag for multicast packets,
21155 		 * if allowed by the setsrc reminder.
21156 		 */
21157 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21158 			ipha->ipha_src = ire->ire_src_addr;
21159 		}
21160 
21161 		/*
21162 		 * Unconditionally force the TTL to 1 for
21163 		 * multirouted multicast packets:
21164 		 * multirouted multicast should not cross
21165 		 * multicast routers.
21166 		 */
21167 		if (ire->ire_flags & RTF_MULTIRT) {
21168 			if (ipha->ipha_ttl > 1) {
21169 				ip2dbg(("ip_wput: forcing multicast "
21170 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21171 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21172 				ipha->ipha_ttl = 1;
21173 			}
21174 		}
21175 	} else {
21176 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
21177 		if ((ire != NULL) && (ire->ire_type &
21178 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21179 			ignore_dontroute = B_TRUE;
21180 			ignore_nexthop = B_TRUE;
21181 		}
21182 		if (ire != NULL) {
21183 			ire_refrele(ire);
21184 			ire = NULL;
21185 		}
21186 		/*
21187 		 * Guard against coming in from arp in which case conn is NULL.
21188 		 * Also guard against non M_DATA with dontroute set but
21189 		 * destined to local, loopback or broadcast addresses.
21190 		 */
21191 		if (connp != NULL && connp->conn_dontroute &&
21192 		    !ignore_dontroute) {
21193 dontroute:
21194 			/*
21195 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21196 			 * routing protocols from seeing false direct
21197 			 * connectivity.
21198 			 */
21199 			ipha->ipha_ttl = 1;
21200 			/*
21201 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21202 			 * along with SO_DONTROUTE, higher precedence is
21203 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21204 			 */
21205 			if (connp->conn_xmit_if_ill == NULL) {
21206 				/* If suitable ipif not found, drop packet */
21207 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid);
21208 				if (dst_ipif == NULL) {
21209 					ip1dbg(("ip_wput: no route for "
21210 					    "dst using SO_DONTROUTE\n"));
21211 					BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
21212 					mp->b_prev = mp->b_next = NULL;
21213 					if (first_mp == NULL)
21214 						first_mp = mp;
21215 					goto drop_pkt;
21216 				} else {
21217 					/*
21218 					 * If suitable ipif has been found, set
21219 					 * xmit_ill to the corresponding
21220 					 * ipif_ill because we'll be following
21221 					 * the IP_XMIT_IF logic.
21222 					 */
21223 					ASSERT(xmit_ill == NULL);
21224 					xmit_ill = dst_ipif->ipif_ill;
21225 					mutex_enter(&xmit_ill->ill_lock);
21226 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21227 						mutex_exit(&xmit_ill->ill_lock);
21228 						xmit_ill = NULL;
21229 						ipif_refrele(dst_ipif);
21230 						ip1dbg(("ip_wput: no route for"
21231 						    " dst using"
21232 						    " SO_DONTROUTE\n"));
21233 						BUMP_MIB(&ip_mib,
21234 						    ipIfStatsOutNoRoutes);
21235 						mp->b_prev = mp->b_next = NULL;
21236 						if (first_mp == NULL)
21237 							first_mp = mp;
21238 						goto drop_pkt;
21239 					}
21240 					ill_refhold_locked(xmit_ill);
21241 					mutex_exit(&xmit_ill->ill_lock);
21242 					ipif_refrele(dst_ipif);
21243 				}
21244 			}
21245 
21246 		}
21247 		/*
21248 		 * If we are bound to IPIF_NOFAILOVER address, look for
21249 		 * an IRE_CACHE matching the ill.
21250 		 */
21251 send_from_ill:
21252 		if (attach_ill != NULL) {
21253 			ipif_t	*attach_ipif;
21254 
21255 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21256 
21257 			/*
21258 			 * Check if we need an ire that will not be
21259 			 * looked up by anybody else i.e. HIDDEN.
21260 			 */
21261 			if (ill_is_probeonly(attach_ill)) {
21262 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21263 			}
21264 
21265 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21266 			if (attach_ipif == NULL) {
21267 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21268 				goto discard_pkt;
21269 			}
21270 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21271 			    zoneid, MBLK_GETLABEL(mp), match_flags);
21272 			ipif_refrele(attach_ipif);
21273 		} else if (xmit_ill != NULL || (connp != NULL &&
21274 			    connp->conn_xmit_if_ill != NULL)) {
21275 			/*
21276 			 * Mark this packet as originated locally
21277 			 */
21278 			mp->b_prev = mp->b_next = NULL;
21279 			/*
21280 			 * xmit_ill could be NULL if SO_DONTROUTE
21281 			 * is also set.
21282 			 */
21283 			if (xmit_ill == NULL) {
21284 				xmit_ill = conn_get_held_ill(connp,
21285 				    &connp->conn_xmit_if_ill, &err);
21286 				if (err == ILL_LOOKUP_FAILED) {
21287 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
21288 					if (need_decref)
21289 						CONN_DEC_REF(connp);
21290 					freemsg(first_mp);
21291 					return;
21292 				}
21293 				if (xmit_ill == NULL) {
21294 					if (connp->conn_dontroute)
21295 						goto dontroute;
21296 					goto send_from_ill;
21297 				}
21298 			}
21299 			/*
21300 			 * Could be SO_DONTROUTE case also.
21301 			 * check at least one interface is UP as
21302 			 * specified by this ILL
21303 			 */
21304 			if (xmit_ill->ill_ipif_up_count > 0) {
21305 				ipif_t *ipif;
21306 
21307 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21308 				if (ipif == NULL) {
21309 					ip1dbg(("ip_output: "
21310 					    "xmit_ill NULL ipif\n"));
21311 					goto drop_pkt;
21312 				}
21313 				/*
21314 				 * Look for a ire that is part of the group,
21315 				 * if found use it else call ip_newroute_ipif.
21316 				 * IPCL_ZONEID is not used for matching because
21317 				 * IP_ALLZONES option is valid only when the
21318 				 * ill is accessible from all zones i.e has a
21319 				 * valid ipif in all zones.
21320 				 */
21321 				match_flags = MATCH_IRE_ILL_GROUP |
21322 				    MATCH_IRE_SECATTR;
21323 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21324 				    MBLK_GETLABEL(mp), match_flags);
21325 				/*
21326 				 * If an ire exists use it or else create
21327 				 * an ire but don't add it to the cache.
21328 				 * Adding an ire may cause issues with
21329 				 * asymmetric routing.
21330 				 * In case of multiroute always act as if
21331 				 * ire does not exist.
21332 				 */
21333 				if (ire == NULL ||
21334 				    ire->ire_flags & RTF_MULTIRT) {
21335 					if (ire != NULL)
21336 						ire_refrele(ire);
21337 					ip_newroute_ipif(q, first_mp, ipif,
21338 					    dst, connp, 0, zoneid, infop);
21339 					ipif_refrele(ipif);
21340 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21341 					ill_refrele(xmit_ill);
21342 					if (need_decref)
21343 						CONN_DEC_REF(connp);
21344 					return;
21345 				}
21346 				ipif_refrele(ipif);
21347 			} else {
21348 				goto drop_pkt;
21349 			}
21350 		} else if (ip_nexthop || (connp != NULL &&
21351 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21352 			if (!ip_nexthop) {
21353 				ip_nexthop = B_TRUE;
21354 				nexthop_addr = connp->conn_nexthop_v4;
21355 			}
21356 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21357 			    MATCH_IRE_GW;
21358 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21359 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags);
21360 		} else {
21361 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp));
21362 		}
21363 		if (!ire) {
21364 			/*
21365 			 * Make sure we don't load spread if this
21366 			 * is IPIF_NOFAILOVER case.
21367 			 */
21368 			if ((attach_ill != NULL) ||
21369 			    (ip_nexthop && !ignore_nexthop)) {
21370 				if (mctl_present) {
21371 					io = (ipsec_out_t *)first_mp->b_rptr;
21372 					ASSERT(first_mp->b_datap->db_type ==
21373 					    M_CTL);
21374 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21375 				} else {
21376 					ASSERT(mp == first_mp);
21377 					first_mp = allocb(
21378 					    sizeof (ipsec_info_t), BPRI_HI);
21379 					if (first_mp == NULL) {
21380 						first_mp = mp;
21381 						goto discard_pkt;
21382 					}
21383 					first_mp->b_datap->db_type = M_CTL;
21384 					first_mp->b_wptr +=
21385 					    sizeof (ipsec_info_t);
21386 					/* ipsec_out_secure is B_FALSE now */
21387 					bzero(first_mp->b_rptr,
21388 					    sizeof (ipsec_info_t));
21389 					io = (ipsec_out_t *)first_mp->b_rptr;
21390 					io->ipsec_out_type = IPSEC_OUT;
21391 					io->ipsec_out_len =
21392 					    sizeof (ipsec_out_t);
21393 					io->ipsec_out_use_global_policy =
21394 					    B_TRUE;
21395 					first_mp->b_cont = mp;
21396 					mctl_present = B_TRUE;
21397 				}
21398 				if (attach_ill != NULL) {
21399 					io->ipsec_out_ill_index = attach_ill->
21400 					    ill_phyint->phyint_ifindex;
21401 					io->ipsec_out_attach_if = B_TRUE;
21402 				} else {
21403 					io->ipsec_out_ip_nexthop = ip_nexthop;
21404 					io->ipsec_out_nexthop_addr =
21405 					    nexthop_addr;
21406 				}
21407 			}
21408 noirefound:
21409 			/*
21410 			 * Mark this packet as having originated on
21411 			 * this machine.  This will be noted in
21412 			 * ire_add_then_send, which needs to know
21413 			 * whether to run it back through ip_wput or
21414 			 * ip_rput following successful resolution.
21415 			 */
21416 			mp->b_prev = NULL;
21417 			mp->b_next = NULL;
21418 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid);
21419 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21420 			    "ip_wput_end: q %p (%S)", q, "newroute");
21421 			if (attach_ill != NULL)
21422 				ill_refrele(attach_ill);
21423 			if (xmit_ill != NULL)
21424 				ill_refrele(xmit_ill);
21425 			if (need_decref)
21426 				CONN_DEC_REF(connp);
21427 			return;
21428 		}
21429 	}
21430 
21431 	/* We now know where we are going with it. */
21432 
21433 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21434 	    "ip_wput_end: q %p (%S)", q, "end");
21435 
21436 	/*
21437 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21438 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21439 	 */
21440 	if (ire->ire_flags & RTF_MULTIRT) {
21441 		/*
21442 		 * Force the TTL of multirouted packets if required.
21443 		 * The TTL of such packets is bounded by the
21444 		 * ip_multirt_ttl ndd variable.
21445 		 */
21446 		if ((ip_multirt_ttl > 0) &&
21447 		    (ipha->ipha_ttl > ip_multirt_ttl)) {
21448 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21449 			    "(was %d), dst 0x%08x\n",
21450 			    ip_multirt_ttl, ipha->ipha_ttl,
21451 			    ntohl(ire->ire_addr)));
21452 			ipha->ipha_ttl = ip_multirt_ttl;
21453 		}
21454 		/*
21455 		 * At this point, we check to see if there are any pending
21456 		 * unresolved routes. ire_multirt_resolvable()
21457 		 * checks in O(n) that all IRE_OFFSUBNET ire
21458 		 * entries for the packet's destination and
21459 		 * flagged RTF_MULTIRT are currently resolved.
21460 		 * If some remain unresolved, we make a copy
21461 		 * of the current message. It will be used
21462 		 * to initiate additional route resolutions.
21463 		 */
21464 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21465 		    MBLK_GETLABEL(first_mp));
21466 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21467 		    "multirt_need_resolve %d, first_mp %p\n",
21468 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21469 		if (multirt_need_resolve) {
21470 			copy_mp = copymsg(first_mp);
21471 			if (copy_mp != NULL) {
21472 				MULTIRT_DEBUG_TAG(copy_mp);
21473 			}
21474 		}
21475 	}
21476 
21477 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21478 	/*
21479 	 * Try to resolve another multiroute if
21480 	 * ire_multirt_resolvable() deemed it necessary.
21481 	 * At this point, we need to distinguish
21482 	 * multicasts from other packets. For multicasts,
21483 	 * we call ip_newroute_ipif() and request that both
21484 	 * multirouting and setsrc flags are checked.
21485 	 */
21486 	if (copy_mp != NULL) {
21487 		if (CLASSD(dst)) {
21488 			ipif_t *ipif = ipif_lookup_group(dst, zoneid);
21489 			if (ipif) {
21490 				ASSERT(infop->ip_opt_ill_index == 0);
21491 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21492 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21493 				ipif_refrele(ipif);
21494 			} else {
21495 				MULTIRT_DEBUG_UNTAG(copy_mp);
21496 				freemsg(copy_mp);
21497 				copy_mp = NULL;
21498 			}
21499 		} else {
21500 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid);
21501 		}
21502 	}
21503 	if (attach_ill != NULL)
21504 		ill_refrele(attach_ill);
21505 	if (xmit_ill != NULL)
21506 		ill_refrele(xmit_ill);
21507 	if (need_decref)
21508 		CONN_DEC_REF(connp);
21509 	return;
21510 
21511 icmp_parameter_problem:
21512 	/* could not have originated externally */
21513 	ASSERT(mp->b_prev == NULL);
21514 	if (ip_hdr_complete(ipha, zoneid) == 0) {
21515 		BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
21516 		/* it's the IP header length that's in trouble */
21517 		icmp_param_problem(q, first_mp, 0, zoneid);
21518 		first_mp = NULL;
21519 	}
21520 
21521 discard_pkt:
21522 	BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
21523 drop_pkt:
21524 	ip1dbg(("ip_wput: dropped packet\n"));
21525 	if (ire != NULL)
21526 		ire_refrele(ire);
21527 	if (need_decref)
21528 		CONN_DEC_REF(connp);
21529 	freemsg(first_mp);
21530 	if (attach_ill != NULL)
21531 		ill_refrele(attach_ill);
21532 	if (xmit_ill != NULL)
21533 		ill_refrele(xmit_ill);
21534 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21535 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21536 }
21537 
21538 /*
21539  * If this is a conn_t queue, then we pass in the conn. This includes the
21540  * zoneid.
21541  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21542  * in which case we use the global zoneid since those are all part of
21543  * the global zone.
21544  */
21545 void
21546 ip_wput(queue_t *q, mblk_t *mp)
21547 {
21548 	if (CONN_Q(q))
21549 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21550 	else
21551 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21552 }
21553 
21554 /*
21555  *
21556  * The following rules must be observed when accessing any ipif or ill
21557  * that has been cached in the conn. Typically conn_nofailover_ill,
21558  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21559  *
21560  * Access: The ipif or ill pointed to from the conn can be accessed under
21561  * the protection of the conn_lock or after it has been refheld under the
21562  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21563  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21564  * The reason for this is that a concurrent unplumb could actually be
21565  * cleaning up these cached pointers by walking the conns and might have
21566  * finished cleaning up the conn in question. The macros check that an
21567  * unplumb has not yet started on the ipif or ill.
21568  *
21569  * Caching: An ipif or ill pointer may be cached in the conn only after
21570  * making sure that an unplumb has not started. So the caching is done
21571  * while holding both the conn_lock and the ill_lock and after using the
21572  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21573  * flag before starting the cleanup of conns.
21574  *
21575  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21576  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21577  * or a reference to the ipif or a reference to an ire that references the
21578  * ipif. An ipif does not change its ill except for failover/failback. Since
21579  * failover/failback happens only after bringing down the ipif and making sure
21580  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21581  * the above holds.
21582  */
21583 ipif_t *
21584 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21585 {
21586 	ipif_t	*ipif;
21587 	ill_t	*ill;
21588 
21589 	*err = 0;
21590 	rw_enter(&ill_g_lock, RW_READER);
21591 	mutex_enter(&connp->conn_lock);
21592 	ipif = *ipifp;
21593 	if (ipif != NULL) {
21594 		ill = ipif->ipif_ill;
21595 		mutex_enter(&ill->ill_lock);
21596 		if (IPIF_CAN_LOOKUP(ipif)) {
21597 			ipif_refhold_locked(ipif);
21598 			mutex_exit(&ill->ill_lock);
21599 			mutex_exit(&connp->conn_lock);
21600 			rw_exit(&ill_g_lock);
21601 			return (ipif);
21602 		} else {
21603 			*err = IPIF_LOOKUP_FAILED;
21604 		}
21605 		mutex_exit(&ill->ill_lock);
21606 	}
21607 	mutex_exit(&connp->conn_lock);
21608 	rw_exit(&ill_g_lock);
21609 	return (NULL);
21610 }
21611 
21612 ill_t *
21613 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21614 {
21615 	ill_t	*ill;
21616 
21617 	*err = 0;
21618 	mutex_enter(&connp->conn_lock);
21619 	ill = *illp;
21620 	if (ill != NULL) {
21621 		mutex_enter(&ill->ill_lock);
21622 		if (ILL_CAN_LOOKUP(ill)) {
21623 			ill_refhold_locked(ill);
21624 			mutex_exit(&ill->ill_lock);
21625 			mutex_exit(&connp->conn_lock);
21626 			return (ill);
21627 		} else {
21628 			*err = ILL_LOOKUP_FAILED;
21629 		}
21630 		mutex_exit(&ill->ill_lock);
21631 	}
21632 	mutex_exit(&connp->conn_lock);
21633 	return (NULL);
21634 }
21635 
21636 static int
21637 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21638 {
21639 	ill_t	*ill;
21640 
21641 	ill = ipif->ipif_ill;
21642 	mutex_enter(&connp->conn_lock);
21643 	mutex_enter(&ill->ill_lock);
21644 	if (IPIF_CAN_LOOKUP(ipif)) {
21645 		*ipifp = ipif;
21646 		mutex_exit(&ill->ill_lock);
21647 		mutex_exit(&connp->conn_lock);
21648 		return (0);
21649 	}
21650 	mutex_exit(&ill->ill_lock);
21651 	mutex_exit(&connp->conn_lock);
21652 	return (IPIF_LOOKUP_FAILED);
21653 }
21654 
21655 /*
21656  * This is called if the outbound datagram needs fragmentation.
21657  *
21658  * NOTE : This function does not ire_refrele the ire argument passed in.
21659  */
21660 static void
21661 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid)
21662 {
21663 	ipha_t		*ipha;
21664 	mblk_t		*mp;
21665 	uint32_t	v_hlen_tos_len;
21666 	uint32_t	max_frag;
21667 	uint32_t	frag_flag;
21668 	boolean_t	dont_use;
21669 
21670 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21671 		mp = ipsec_mp->b_cont;
21672 	} else {
21673 		mp = ipsec_mp;
21674 	}
21675 
21676 	ipha = (ipha_t *)mp->b_rptr;
21677 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21678 
21679 #ifdef	_BIG_ENDIAN
21680 #define	V_HLEN	(v_hlen_tos_len >> 24)
21681 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21682 #else
21683 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21684 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21685 #endif
21686 
21687 #ifndef SPEED_BEFORE_SAFETY
21688 	/*
21689 	 * Check that ipha_length is consistent with
21690 	 * the mblk length
21691 	 */
21692 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21693 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21694 		    LENGTH, msgdsize(mp)));
21695 		freemsg(ipsec_mp);
21696 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21697 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21698 		    "packet length mismatch");
21699 		return;
21700 	}
21701 #endif
21702 	/*
21703 	 * Don't use frag_flag if pre-built packet or source
21704 	 * routed or if multicast (since multicast packets do not solicit
21705 	 * ICMP "packet too big" messages). Get the values of
21706 	 * max_frag and frag_flag atomically by acquiring the
21707 	 * ire_lock.
21708 	 */
21709 	mutex_enter(&ire->ire_lock);
21710 	max_frag = ire->ire_max_frag;
21711 	frag_flag = ire->ire_frag_flag;
21712 	mutex_exit(&ire->ire_lock);
21713 
21714 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21715 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21716 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21717 
21718 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21719 	    (dont_use ? 0 : frag_flag), zoneid);
21720 }
21721 
21722 /*
21723  * Used for deciding the MSS size for the upper layer. Thus
21724  * we need to check the outbound policy values in the conn.
21725  */
21726 int
21727 conn_ipsec_length(conn_t *connp)
21728 {
21729 	ipsec_latch_t *ipl;
21730 
21731 	ipl = connp->conn_latch;
21732 	if (ipl == NULL)
21733 		return (0);
21734 
21735 	if (ipl->ipl_out_policy == NULL)
21736 		return (0);
21737 
21738 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21739 }
21740 
21741 /*
21742  * Returns an estimate of the IPSEC headers size. This is used if
21743  * we don't want to call into IPSEC to get the exact size.
21744  */
21745 int
21746 ipsec_out_extra_length(mblk_t *ipsec_mp)
21747 {
21748 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21749 	ipsec_action_t *a;
21750 
21751 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21752 	if (!io->ipsec_out_secure)
21753 		return (0);
21754 
21755 	a = io->ipsec_out_act;
21756 
21757 	if (a == NULL) {
21758 		ASSERT(io->ipsec_out_policy != NULL);
21759 		a = io->ipsec_out_policy->ipsp_act;
21760 	}
21761 	ASSERT(a != NULL);
21762 
21763 	return (a->ipa_ovhd);
21764 }
21765 
21766 /*
21767  * Returns an estimate of the IPSEC headers size. This is used if
21768  * we don't want to call into IPSEC to get the exact size.
21769  */
21770 int
21771 ipsec_in_extra_length(mblk_t *ipsec_mp)
21772 {
21773 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21774 	ipsec_action_t *a;
21775 
21776 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21777 
21778 	a = ii->ipsec_in_action;
21779 	return (a == NULL ? 0 : a->ipa_ovhd);
21780 }
21781 
21782 /*
21783  * If there are any source route options, return the true final
21784  * destination. Otherwise, return the destination.
21785  */
21786 ipaddr_t
21787 ip_get_dst(ipha_t *ipha)
21788 {
21789 	ipoptp_t	opts;
21790 	uchar_t		*opt;
21791 	uint8_t		optval;
21792 	uint8_t		optlen;
21793 	ipaddr_t	dst;
21794 	uint32_t off;
21795 
21796 	dst = ipha->ipha_dst;
21797 
21798 	if (IS_SIMPLE_IPH(ipha))
21799 		return (dst);
21800 
21801 	for (optval = ipoptp_first(&opts, ipha);
21802 	    optval != IPOPT_EOL;
21803 	    optval = ipoptp_next(&opts)) {
21804 		opt = opts.ipoptp_cur;
21805 		optlen = opts.ipoptp_len;
21806 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21807 		switch (optval) {
21808 		case IPOPT_SSRR:
21809 		case IPOPT_LSRR:
21810 			off = opt[IPOPT_OFFSET];
21811 			/*
21812 			 * If one of the conditions is true, it means
21813 			 * end of options and dst already has the right
21814 			 * value.
21815 			 */
21816 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21817 				off = optlen - IP_ADDR_LEN;
21818 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21819 			}
21820 			return (dst);
21821 		default:
21822 			break;
21823 		}
21824 	}
21825 
21826 	return (dst);
21827 }
21828 
21829 mblk_t *
21830 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21831     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21832 {
21833 	ipsec_out_t	*io;
21834 	mblk_t		*first_mp;
21835 	boolean_t policy_present;
21836 
21837 	first_mp = mp;
21838 	if (mp->b_datap->db_type == M_CTL) {
21839 		io = (ipsec_out_t *)first_mp->b_rptr;
21840 		/*
21841 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21842 		 *
21843 		 * 1) There is per-socket policy (including cached global
21844 		 *    policy) or a policy on the IP-in-IP tunnel.
21845 		 * 2) There is no per-socket policy, but it is
21846 		 *    a multicast packet that needs to go out
21847 		 *    on a specific interface. This is the case
21848 		 *    where (ip_wput and ip_wput_multicast) attaches
21849 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21850 		 *
21851 		 * In case (2) we check with global policy to
21852 		 * see if there is a match and set the ill_index
21853 		 * appropriately so that we can lookup the ire
21854 		 * properly in ip_wput_ipsec_out.
21855 		 */
21856 
21857 		/*
21858 		 * ipsec_out_use_global_policy is set to B_FALSE
21859 		 * in ipsec_in_to_out(). Refer to that function for
21860 		 * details.
21861 		 */
21862 		if ((io->ipsec_out_latch == NULL) &&
21863 		    (io->ipsec_out_use_global_policy)) {
21864 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21865 				    ire, connp, unspec_src, zoneid));
21866 		}
21867 		if (!io->ipsec_out_secure) {
21868 			/*
21869 			 * If this is not a secure packet, drop
21870 			 * the IPSEC_OUT mp and treat it as a clear
21871 			 * packet. This happens when we are sending
21872 			 * a ICMP reply back to a clear packet. See
21873 			 * ipsec_in_to_out() for details.
21874 			 */
21875 			mp = first_mp->b_cont;
21876 			freeb(first_mp);
21877 		}
21878 		return (mp);
21879 	}
21880 	/*
21881 	 * See whether we need to attach a global policy here. We
21882 	 * don't depend on the conn (as it could be null) for deciding
21883 	 * what policy this datagram should go through because it
21884 	 * should have happened in ip_wput if there was some
21885 	 * policy. This normally happens for connections which are not
21886 	 * fully bound preventing us from caching policies in
21887 	 * ip_bind. Packets coming from the TCP listener/global queue
21888 	 * - which are non-hard_bound - could also be affected by
21889 	 * applying policy here.
21890 	 *
21891 	 * If this packet is coming from tcp global queue or listener,
21892 	 * we will be applying policy here.  This may not be *right*
21893 	 * if these packets are coming from the detached connection as
21894 	 * it could have gone in clear before. This happens only if a
21895 	 * TCP connection started when there is no policy and somebody
21896 	 * added policy before it became detached. Thus packets of the
21897 	 * detached connection could go out secure and the other end
21898 	 * would drop it because it will be expecting in clear. The
21899 	 * converse is not true i.e if somebody starts a TCP
21900 	 * connection and deletes the policy, all the packets will
21901 	 * still go out with the policy that existed before deleting
21902 	 * because ip_unbind sends up policy information which is used
21903 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21904 	 * TCP to attach a dummy IPSEC_OUT and set
21905 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21906 	 * affect performance for normal cases, we are not doing it.
21907 	 * Thus, set policy before starting any TCP connections.
21908 	 *
21909 	 * NOTE - We might apply policy even for a hard bound connection
21910 	 * - for which we cached policy in ip_bind - if somebody added
21911 	 * global policy after we inherited the policy in ip_bind.
21912 	 * This means that the packets that were going out in clear
21913 	 * previously would start going secure and hence get dropped
21914 	 * on the other side. To fix this, TCP attaches a dummy
21915 	 * ipsec_out and make sure that we don't apply global policy.
21916 	 */
21917 	if (ipha != NULL)
21918 		policy_present = ipsec_outbound_v4_policy_present;
21919 	else
21920 		policy_present = ipsec_outbound_v6_policy_present;
21921 	if (!policy_present)
21922 		return (mp);
21923 
21924 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21925 		    zoneid));
21926 }
21927 
21928 ire_t *
21929 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21930 {
21931 	ipaddr_t addr;
21932 	ire_t *save_ire;
21933 	irb_t *irb;
21934 	ill_group_t *illgrp;
21935 	int	err;
21936 
21937 	save_ire = ire;
21938 	addr = ire->ire_addr;
21939 
21940 	ASSERT(ire->ire_type == IRE_BROADCAST);
21941 
21942 	illgrp = connp->conn_outgoing_ill->ill_group;
21943 	if (illgrp == NULL) {
21944 		*conn_outgoing_ill = conn_get_held_ill(connp,
21945 		    &connp->conn_outgoing_ill, &err);
21946 		if (err == ILL_LOOKUP_FAILED) {
21947 			ire_refrele(save_ire);
21948 			return (NULL);
21949 		}
21950 		return (save_ire);
21951 	}
21952 	/*
21953 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21954 	 * If it is part of the group, we need to send on the ire
21955 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21956 	 * to this group. This is okay as IP_BOUND_IF really means
21957 	 * any ill in the group. We depend on the fact that the
21958 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21959 	 * if such an ire exists. This is possible only if you have
21960 	 * at least one ill in the group that has not failed.
21961 	 *
21962 	 * First get to the ire that matches the address and group.
21963 	 *
21964 	 * We don't look for an ire with a matching zoneid because a given zone
21965 	 * won't always have broadcast ires on all ills in the group.
21966 	 */
21967 	irb = ire->ire_bucket;
21968 	rw_enter(&irb->irb_lock, RW_READER);
21969 	if (ire->ire_marks & IRE_MARK_NORECV) {
21970 		/*
21971 		 * If the current zone only has an ire broadcast for this
21972 		 * address marked NORECV, the ire we want is ahead in the
21973 		 * bucket, so we look it up deliberately ignoring the zoneid.
21974 		 */
21975 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21976 			if (ire->ire_addr != addr)
21977 				continue;
21978 			/* skip over deleted ires */
21979 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21980 				continue;
21981 		}
21982 	}
21983 	while (ire != NULL) {
21984 		/*
21985 		 * If a new interface is coming up, we could end up
21986 		 * seeing the loopback ire and the non-loopback ire
21987 		 * may not have been added yet. So check for ire_stq
21988 		 */
21989 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21990 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21991 			break;
21992 		}
21993 		ire = ire->ire_next;
21994 	}
21995 	if (ire != NULL && ire->ire_addr == addr &&
21996 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21997 		IRE_REFHOLD(ire);
21998 		rw_exit(&irb->irb_lock);
21999 		ire_refrele(save_ire);
22000 		*conn_outgoing_ill = ire_to_ill(ire);
22001 		/*
22002 		 * Refhold the ill to make the conn_outgoing_ill
22003 		 * independent of the ire. ip_wput_ire goes in a loop
22004 		 * and may refrele the ire. Since we have an ire at this
22005 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22006 		 */
22007 		ill_refhold(*conn_outgoing_ill);
22008 		return (ire);
22009 	}
22010 	rw_exit(&irb->irb_lock);
22011 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22012 	/*
22013 	 * If we can't find a suitable ire, return the original ire.
22014 	 */
22015 	return (save_ire);
22016 }
22017 
22018 /*
22019  * This function does the ire_refrele of the ire passed in as the
22020  * argument. As this function looks up more ires i.e broadcast ires,
22021  * it needs to REFRELE them. Currently, for simplicity we don't
22022  * differentiate the one passed in and looked up here. We always
22023  * REFRELE.
22024  * IPQoS Notes:
22025  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22026  * IPSec packets are done in ipsec_out_process.
22027  *
22028  */
22029 void
22030 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22031     zoneid_t zoneid)
22032 {
22033 	ipha_t		*ipha;
22034 #define	rptr	((uchar_t *)ipha)
22035 	queue_t		*stq;
22036 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22037 	uint32_t	v_hlen_tos_len;
22038 	uint32_t	ttl_protocol;
22039 	ipaddr_t	src;
22040 	ipaddr_t	dst;
22041 	uint32_t	cksum;
22042 	ipaddr_t	orig_src;
22043 	ire_t		*ire1;
22044 	mblk_t		*next_mp;
22045 	uint_t		hlen;
22046 	uint16_t	*up;
22047 	uint32_t	max_frag = ire->ire_max_frag;
22048 	ill_t		*ill = ire_to_ill(ire);
22049 	int		clusterwide;
22050 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22051 	int		ipsec_len;
22052 	mblk_t		*first_mp;
22053 	ipsec_out_t	*io;
22054 	boolean_t	conn_dontroute;		/* conn value for multicast */
22055 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22056 	boolean_t	multicast_forward;	/* Should we forward ? */
22057 	boolean_t	unspec_src;
22058 	ill_t		*conn_outgoing_ill = NULL;
22059 	ill_t		*ire_ill;
22060 	ill_t		*ire1_ill;
22061 	ill_t		*out_ill;
22062 	uint32_t 	ill_index = 0;
22063 	boolean_t	multirt_send = B_FALSE;
22064 	int		err;
22065 	ipxmit_state_t	pktxmit_state;
22066 
22067 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22068 	    "ip_wput_ire_start: q %p", q);
22069 
22070 	multicast_forward = B_FALSE;
22071 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22072 
22073 	if (ire->ire_flags & RTF_MULTIRT) {
22074 		/*
22075 		 * Multirouting case. The bucket where ire is stored
22076 		 * probably holds other RTF_MULTIRT flagged ire
22077 		 * to the destination. In this call to ip_wput_ire,
22078 		 * we attempt to send the packet through all
22079 		 * those ires. Thus, we first ensure that ire is the
22080 		 * first RTF_MULTIRT ire in the bucket,
22081 		 * before walking the ire list.
22082 		 */
22083 		ire_t *first_ire;
22084 		irb_t *irb = ire->ire_bucket;
22085 		ASSERT(irb != NULL);
22086 
22087 		/* Make sure we do not omit any multiroute ire. */
22088 		IRB_REFHOLD(irb);
22089 		for (first_ire = irb->irb_ire;
22090 		    first_ire != NULL;
22091 		    first_ire = first_ire->ire_next) {
22092 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22093 			    (first_ire->ire_addr == ire->ire_addr) &&
22094 			    !(first_ire->ire_marks &
22095 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22096 				break;
22097 		}
22098 
22099 		if ((first_ire != NULL) && (first_ire != ire)) {
22100 			IRE_REFHOLD(first_ire);
22101 			ire_refrele(ire);
22102 			ire = first_ire;
22103 			ill = ire_to_ill(ire);
22104 		}
22105 		IRB_REFRELE(irb);
22106 	}
22107 
22108 	/*
22109 	 * conn_outgoing_ill is used only in the broadcast loop.
22110 	 * for performance we don't grab the mutexs in the fastpath
22111 	 */
22112 	if ((connp != NULL) &&
22113 	    (connp->conn_xmit_if_ill == NULL) &&
22114 	    (ire->ire_type == IRE_BROADCAST) &&
22115 	    ((connp->conn_nofailover_ill != NULL) ||
22116 	    (connp->conn_outgoing_ill != NULL))) {
22117 		/*
22118 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22119 		 * option. So, see if this endpoint is bound to a
22120 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22121 		 * that if the interface is failed, we will still send
22122 		 * the packet on the same ill which is what we want.
22123 		 */
22124 		conn_outgoing_ill = conn_get_held_ill(connp,
22125 		    &connp->conn_nofailover_ill, &err);
22126 		if (err == ILL_LOOKUP_FAILED) {
22127 			ire_refrele(ire);
22128 			freemsg(mp);
22129 			return;
22130 		}
22131 		if (conn_outgoing_ill == NULL) {
22132 			/*
22133 			 * Choose a good ill in the group to send the
22134 			 * packets on.
22135 			 */
22136 			ire = conn_set_outgoing_ill(connp, ire,
22137 			    &conn_outgoing_ill);
22138 			if (ire == NULL) {
22139 				freemsg(mp);
22140 				return;
22141 			}
22142 		}
22143 	}
22144 
22145 	if (mp->b_datap->db_type != M_CTL) {
22146 		ipha = (ipha_t *)mp->b_rptr;
22147 	} else {
22148 		io = (ipsec_out_t *)mp->b_rptr;
22149 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22150 		ASSERT(zoneid == io->ipsec_out_zoneid);
22151 		ASSERT(zoneid != ALL_ZONES);
22152 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22153 		dst = ipha->ipha_dst;
22154 		/*
22155 		 * For the multicast case, ipsec_out carries conn_dontroute and
22156 		 * conn_multicast_loop as conn may not be available here. We
22157 		 * need this for multicast loopback and forwarding which is done
22158 		 * later in the code.
22159 		 */
22160 		if (CLASSD(dst)) {
22161 			conn_dontroute = io->ipsec_out_dontroute;
22162 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22163 			/*
22164 			 * If conn_dontroute is not set or conn_multicast_loop
22165 			 * is set, we need to do forwarding/loopback. For
22166 			 * datagrams from ip_wput_multicast, conn_dontroute is
22167 			 * set to B_TRUE and conn_multicast_loop is set to
22168 			 * B_FALSE so that we neither do forwarding nor
22169 			 * loopback.
22170 			 */
22171 			if (!conn_dontroute || conn_multicast_loop)
22172 				multicast_forward = B_TRUE;
22173 		}
22174 	}
22175 
22176 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22177 	    ire->ire_zoneid != ALL_ZONES) {
22178 		/*
22179 		 * When a zone sends a packet to another zone, we try to deliver
22180 		 * the packet under the same conditions as if the destination
22181 		 * was a real node on the network. To do so, we look for a
22182 		 * matching route in the forwarding table.
22183 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22184 		 * ip_newroute() does.
22185 		 * Note that IRE_LOCAL are special, since they are used
22186 		 * when the zoneid doesn't match in some cases. This means that
22187 		 * we need to handle ipha_src differently since ire_src_addr
22188 		 * belongs to the receiving zone instead of the sending zone.
22189 		 * When ip_restrict_interzone_loopback is set, then
22190 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22191 		 * for loopback between zones when the logical "Ethernet" would
22192 		 * have looped them back.
22193 		 */
22194 		ire_t *src_ire;
22195 
22196 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22197 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22198 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE));
22199 		if (src_ire != NULL &&
22200 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22201 		    (!ip_restrict_interzone_loopback ||
22202 		    ire_local_same_ill_group(ire, src_ire))) {
22203 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22204 				ipha->ipha_src = src_ire->ire_src_addr;
22205 			ire_refrele(src_ire);
22206 		} else {
22207 			ire_refrele(ire);
22208 			if (conn_outgoing_ill != NULL)
22209 				ill_refrele(conn_outgoing_ill);
22210 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
22211 			if (src_ire != NULL) {
22212 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22213 					ire_refrele(src_ire);
22214 					freemsg(mp);
22215 					return;
22216 				}
22217 				ire_refrele(src_ire);
22218 			}
22219 			if (ip_hdr_complete(ipha, zoneid)) {
22220 				/* Failed */
22221 				freemsg(mp);
22222 				return;
22223 			}
22224 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid);
22225 			return;
22226 		}
22227 	}
22228 
22229 	if (mp->b_datap->db_type == M_CTL ||
22230 	    ipsec_outbound_v4_policy_present) {
22231 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22232 		    unspec_src, zoneid);
22233 		if (mp == NULL) {
22234 			ire_refrele(ire);
22235 			if (conn_outgoing_ill != NULL)
22236 				ill_refrele(conn_outgoing_ill);
22237 			return;
22238 		}
22239 	}
22240 
22241 	first_mp = mp;
22242 	ipsec_len = 0;
22243 
22244 	if (first_mp->b_datap->db_type == M_CTL) {
22245 		io = (ipsec_out_t *)first_mp->b_rptr;
22246 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22247 		mp = first_mp->b_cont;
22248 		ipsec_len = ipsec_out_extra_length(first_mp);
22249 		ASSERT(ipsec_len >= 0);
22250 		/* We already picked up the zoneid from the M_CTL above */
22251 		ASSERT(zoneid == io->ipsec_out_zoneid);
22252 		ASSERT(zoneid != ALL_ZONES);
22253 
22254 		/*
22255 		 * Drop M_CTL here if IPsec processing is not needed.
22256 		 * (Non-IPsec use of M_CTL extracted any information it
22257 		 * needed above).
22258 		 */
22259 		if (ipsec_len == 0) {
22260 			freeb(first_mp);
22261 			first_mp = mp;
22262 		}
22263 	}
22264 
22265 	/*
22266 	 * Fast path for ip_wput_ire
22267 	 */
22268 
22269 	ipha = (ipha_t *)mp->b_rptr;
22270 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22271 	dst = ipha->ipha_dst;
22272 
22273 	/*
22274 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22275 	 * if the socket is a SOCK_RAW type. The transport checksum should
22276 	 * be provided in the pre-built packet, so we don't need to compute it.
22277 	 * Also, other application set flags, like DF, should not be altered.
22278 	 * Other transport MUST pass down zero.
22279 	 */
22280 	ip_hdr_included = ipha->ipha_ident;
22281 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22282 
22283 	if (CLASSD(dst)) {
22284 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22285 		    ntohl(dst),
22286 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22287 		    ntohl(ire->ire_addr)));
22288 	}
22289 
22290 /* Macros to extract header fields from data already in registers */
22291 #ifdef	_BIG_ENDIAN
22292 #define	V_HLEN	(v_hlen_tos_len >> 24)
22293 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22294 #define	PROTO	(ttl_protocol & 0xFF)
22295 #else
22296 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22297 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22298 #define	PROTO	(ttl_protocol >> 8)
22299 #endif
22300 
22301 
22302 	orig_src = src = ipha->ipha_src;
22303 	/* (The loop back to "another" is explained down below.) */
22304 another:;
22305 	/*
22306 	 * Assign an ident value for this packet.  We assign idents on
22307 	 * a per destination basis out of the IRE.  There could be
22308 	 * other threads targeting the same destination, so we have to
22309 	 * arrange for a atomic increment.  Note that we use a 32-bit
22310 	 * atomic add because it has better performance than its
22311 	 * 16-bit sibling.
22312 	 *
22313 	 * If running in cluster mode and if the source address
22314 	 * belongs to a replicated service then vector through
22315 	 * cl_inet_ipident vector to allocate ip identifier
22316 	 * NOTE: This is a contract private interface with the
22317 	 * clustering group.
22318 	 */
22319 	clusterwide = 0;
22320 	if (cl_inet_ipident) {
22321 		ASSERT(cl_inet_isclusterwide);
22322 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22323 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22324 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22325 			    AF_INET, (uint8_t *)(uintptr_t)src,
22326 			    (uint8_t *)(uintptr_t)dst);
22327 			clusterwide = 1;
22328 		}
22329 	}
22330 	if (!clusterwide) {
22331 		ipha->ipha_ident =
22332 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22333 	}
22334 
22335 #ifndef _BIG_ENDIAN
22336 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22337 #endif
22338 
22339 	/*
22340 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22341 	 * This is needed to obey conn_unspec_src when packets go through
22342 	 * ip_newroute + arp.
22343 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22344 	 */
22345 	if (src == INADDR_ANY && !unspec_src) {
22346 		/*
22347 		 * Assign the appropriate source address from the IRE if none
22348 		 * was specified.
22349 		 */
22350 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22351 
22352 		/*
22353 		 * With IP multipathing, broadcast packets are sent on the ire
22354 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22355 		 * the group. However, this ire might not be in the same zone so
22356 		 * we can't always use its source address. We look for a
22357 		 * broadcast ire in the same group and in the right zone.
22358 		 */
22359 		if (ire->ire_type == IRE_BROADCAST &&
22360 		    ire->ire_zoneid != zoneid) {
22361 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22362 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22363 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
22364 			if (src_ire != NULL) {
22365 				src = src_ire->ire_src_addr;
22366 				ire_refrele(src_ire);
22367 			} else {
22368 				ire_refrele(ire);
22369 				if (conn_outgoing_ill != NULL)
22370 					ill_refrele(conn_outgoing_ill);
22371 				freemsg(first_mp);
22372 				if (ill != NULL) {
22373 					BUMP_MIB(ill->ill_ip_mib,
22374 					    ipIfStatsOutDiscards);
22375 				} else {
22376 					BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
22377 				}
22378 				return;
22379 			}
22380 		} else {
22381 			src = ire->ire_src_addr;
22382 		}
22383 
22384 		if (connp == NULL) {
22385 			ip1dbg(("ip_wput_ire: no connp and no src "
22386 			    "address for dst 0x%x, using src 0x%x\n",
22387 			    ntohl(dst),
22388 			    ntohl(src)));
22389 		}
22390 		ipha->ipha_src = src;
22391 	}
22392 	stq = ire->ire_stq;
22393 
22394 	/*
22395 	 * We only allow ire chains for broadcasts since there will
22396 	 * be multiple IRE_CACHE entries for the same multicast
22397 	 * address (one per ipif).
22398 	 */
22399 	next_mp = NULL;
22400 
22401 	/* broadcast packet */
22402 	if (ire->ire_type == IRE_BROADCAST)
22403 		goto broadcast;
22404 
22405 	/* loopback ? */
22406 	if (stq == NULL)
22407 		goto nullstq;
22408 
22409 	/* The ill_index for outbound ILL */
22410 	ill_index = Q_TO_INDEX(stq);
22411 
22412 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22413 	ttl_protocol = ((uint16_t *)ipha)[4];
22414 
22415 	/* pseudo checksum (do it in parts for IP header checksum) */
22416 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22417 
22418 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22419 		queue_t *dev_q = stq->q_next;
22420 
22421 		/* flow controlled */
22422 		if ((dev_q->q_next || dev_q->q_first) &&
22423 		    !canput(dev_q))
22424 			goto blocked;
22425 		if ((PROTO == IPPROTO_UDP) &&
22426 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22427 			hlen = (V_HLEN & 0xF) << 2;
22428 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22429 			if (*up != 0) {
22430 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22431 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22432 				/* Software checksum? */
22433 				if (DB_CKSUMFLAGS(mp) == 0) {
22434 					IP_STAT(ip_out_sw_cksum);
22435 					IP_STAT_UPDATE(
22436 					    ip_udp_out_sw_cksum_bytes,
22437 					    LENGTH - hlen);
22438 				}
22439 			}
22440 		}
22441 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22442 		hlen = (V_HLEN & 0xF) << 2;
22443 		if (PROTO == IPPROTO_TCP) {
22444 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22445 			/*
22446 			 * The packet header is processed once and for all, even
22447 			 * in the multirouting case. We disable hardware
22448 			 * checksum if the packet is multirouted, as it will be
22449 			 * replicated via several interfaces, and not all of
22450 			 * them may have this capability.
22451 			 */
22452 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22453 			    LENGTH, max_frag, ipsec_len, cksum);
22454 			/* Software checksum? */
22455 			if (DB_CKSUMFLAGS(mp) == 0) {
22456 				IP_STAT(ip_out_sw_cksum);
22457 				IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22458 				    LENGTH - hlen);
22459 			}
22460 		} else {
22461 			sctp_hdr_t	*sctph;
22462 
22463 			ASSERT(PROTO == IPPROTO_SCTP);
22464 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22465 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22466 			/*
22467 			 * Zero out the checksum field to ensure proper
22468 			 * checksum calculation.
22469 			 */
22470 			sctph->sh_chksum = 0;
22471 #ifdef	DEBUG
22472 			if (!skip_sctp_cksum)
22473 #endif
22474 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22475 		}
22476 	}
22477 
22478 	/*
22479 	 * If this is a multicast packet and originated from ip_wput
22480 	 * we need to do loopback and forwarding checks. If it comes
22481 	 * from ip_wput_multicast, we SHOULD not do this.
22482 	 */
22483 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22484 
22485 	/* checksum */
22486 	cksum += ttl_protocol;
22487 
22488 	/* fragment the packet */
22489 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22490 		goto fragmentit;
22491 	/*
22492 	 * Don't use frag_flag if packet is pre-built or source
22493 	 * routed or if multicast (since multicast packets do
22494 	 * not solicit ICMP "packet too big" messages).
22495 	 */
22496 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22497 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22498 	    !ip_source_route_included(ipha)) &&
22499 	    !CLASSD(ipha->ipha_dst))
22500 		ipha->ipha_fragment_offset_and_flags |=
22501 		    htons(ire->ire_frag_flag);
22502 
22503 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22504 		/* calculate IP header checksum */
22505 		cksum += ipha->ipha_ident;
22506 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22507 		cksum += ipha->ipha_fragment_offset_and_flags;
22508 
22509 		/* IP options present */
22510 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22511 		if (hlen)
22512 			goto checksumoptions;
22513 
22514 		/* calculate hdr checksum */
22515 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22516 		cksum = ~(cksum + (cksum >> 16));
22517 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22518 	}
22519 	if (ipsec_len != 0) {
22520 		/*
22521 		 * We will do the rest of the processing after
22522 		 * we come back from IPSEC in ip_wput_ipsec_out().
22523 		 */
22524 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22525 
22526 		io = (ipsec_out_t *)first_mp->b_rptr;
22527 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22528 				ill_phyint->phyint_ifindex;
22529 
22530 		ipsec_out_process(q, first_mp, ire, ill_index);
22531 		ire_refrele(ire);
22532 		if (conn_outgoing_ill != NULL)
22533 			ill_refrele(conn_outgoing_ill);
22534 		return;
22535 	}
22536 
22537 	/*
22538 	 * In most cases, the emission loop below is entered only
22539 	 * once. Only in the case where the ire holds the
22540 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22541 	 * flagged ires in the bucket, and send the packet
22542 	 * through all crossed RTF_MULTIRT routes.
22543 	 */
22544 	if (ire->ire_flags & RTF_MULTIRT) {
22545 		multirt_send = B_TRUE;
22546 	}
22547 	do {
22548 		if (multirt_send) {
22549 			irb_t *irb;
22550 			/*
22551 			 * We are in a multiple send case, need to get
22552 			 * the next ire and make a duplicate of the packet.
22553 			 * ire1 holds here the next ire to process in the
22554 			 * bucket. If multirouting is expected,
22555 			 * any non-RTF_MULTIRT ire that has the
22556 			 * right destination address is ignored.
22557 			 */
22558 			irb = ire->ire_bucket;
22559 			ASSERT(irb != NULL);
22560 
22561 			IRB_REFHOLD(irb);
22562 			for (ire1 = ire->ire_next;
22563 			    ire1 != NULL;
22564 			    ire1 = ire1->ire_next) {
22565 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22566 					continue;
22567 				if (ire1->ire_addr != ire->ire_addr)
22568 					continue;
22569 				if (ire1->ire_marks &
22570 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22571 					continue;
22572 
22573 				/* Got one */
22574 				IRE_REFHOLD(ire1);
22575 				break;
22576 			}
22577 			IRB_REFRELE(irb);
22578 
22579 			if (ire1 != NULL) {
22580 				next_mp = copyb(mp);
22581 				if ((next_mp == NULL) ||
22582 				    ((mp->b_cont != NULL) &&
22583 				    ((next_mp->b_cont =
22584 				    dupmsg(mp->b_cont)) == NULL))) {
22585 					freemsg(next_mp);
22586 					next_mp = NULL;
22587 					ire_refrele(ire1);
22588 					ire1 = NULL;
22589 				}
22590 			}
22591 
22592 			/* Last multiroute ire; don't loop anymore. */
22593 			if (ire1 == NULL) {
22594 				multirt_send = B_FALSE;
22595 			}
22596 		}
22597 
22598 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22599 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22600 		    mblk_t *, mp);
22601 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
22602 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp);
22603 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22604 		if (mp == NULL)
22605 			goto release_ire_and_ill;
22606 
22607 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22608 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22609 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22610 		if ((pktxmit_state == SEND_FAILED) ||
22611 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22612 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22613 			    "- packet dropped\n"));
22614 release_ire_and_ill:
22615 			ire_refrele(ire);
22616 			if (next_mp != NULL) {
22617 				freemsg(next_mp);
22618 				ire_refrele(ire1);
22619 			}
22620 			if (conn_outgoing_ill != NULL)
22621 				ill_refrele(conn_outgoing_ill);
22622 			return;
22623 		}
22624 
22625 		if (CLASSD(dst)) {
22626 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22627 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22628 			    ntohs(ipha->ipha_length));
22629 		}
22630 
22631 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22632 		    "ip_wput_ire_end: q %p (%S)",
22633 		    q, "last copy out");
22634 		IRE_REFRELE(ire);
22635 
22636 		if (multirt_send) {
22637 			ASSERT(ire1);
22638 			/*
22639 			 * Proceed with the next RTF_MULTIRT ire,
22640 			 * Also set up the send-to queue accordingly.
22641 			 */
22642 			ire = ire1;
22643 			ire1 = NULL;
22644 			stq = ire->ire_stq;
22645 			mp = next_mp;
22646 			next_mp = NULL;
22647 			ipha = (ipha_t *)mp->b_rptr;
22648 			ill_index = Q_TO_INDEX(stq);
22649 			ill = (ill_t *)stq->q_ptr;
22650 		}
22651 	} while (multirt_send);
22652 	if (conn_outgoing_ill != NULL)
22653 		ill_refrele(conn_outgoing_ill);
22654 	return;
22655 
22656 	/*
22657 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22658 	 */
22659 broadcast:
22660 	{
22661 		/*
22662 		 * Avoid broadcast storms by setting the ttl to 1
22663 		 * for broadcasts. This parameter can be set
22664 		 * via ndd, so make sure that for the SO_DONTROUTE
22665 		 * case that ipha_ttl is always set to 1.
22666 		 * In the event that we are replying to incoming
22667 		 * ICMP packets, conn could be NULL.
22668 		 */
22669 		if ((connp != NULL) && connp->conn_dontroute)
22670 			ipha->ipha_ttl = 1;
22671 		else
22672 			ipha->ipha_ttl = ip_broadcast_ttl;
22673 
22674 		/*
22675 		 * Note that we are not doing a IRB_REFHOLD here.
22676 		 * Actually we don't care if the list changes i.e
22677 		 * if somebody deletes an IRE from the list while
22678 		 * we drop the lock, the next time we come around
22679 		 * ire_next will be NULL and hence we won't send
22680 		 * out multiple copies which is fine.
22681 		 */
22682 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22683 		ire1 = ire->ire_next;
22684 		if (conn_outgoing_ill != NULL) {
22685 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22686 				ASSERT(ire1 == ire->ire_next);
22687 				if (ire1 != NULL && ire1->ire_addr == dst) {
22688 					ire_refrele(ire);
22689 					ire = ire1;
22690 					IRE_REFHOLD(ire);
22691 					ire1 = ire->ire_next;
22692 					continue;
22693 				}
22694 				rw_exit(&ire->ire_bucket->irb_lock);
22695 				/* Did not find a matching ill */
22696 				ip1dbg(("ip_wput_ire: broadcast with no "
22697 				    "matching IP_BOUND_IF ill %s\n",
22698 				    conn_outgoing_ill->ill_name));
22699 				freemsg(first_mp);
22700 				if (ire != NULL)
22701 					ire_refrele(ire);
22702 				ill_refrele(conn_outgoing_ill);
22703 				return;
22704 			}
22705 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22706 			/*
22707 			 * If the next IRE has the same address and is not one
22708 			 * of the two copies that we need to send, try to see
22709 			 * whether this copy should be sent at all. This
22710 			 * assumes that we insert loopbacks first and then
22711 			 * non-loopbacks. This is acheived by inserting the
22712 			 * loopback always before non-loopback.
22713 			 * This is used to send a single copy of a broadcast
22714 			 * packet out all physical interfaces that have an
22715 			 * matching IRE_BROADCAST while also looping
22716 			 * back one copy (to ip_wput_local) for each
22717 			 * matching physical interface. However, we avoid
22718 			 * sending packets out different logical that match by
22719 			 * having ipif_up/ipif_down supress duplicate
22720 			 * IRE_BROADCASTS.
22721 			 *
22722 			 * This feature is currently used to get broadcasts
22723 			 * sent to multiple interfaces, when the broadcast
22724 			 * address being used applies to multiple interfaces.
22725 			 * For example, a whole net broadcast will be
22726 			 * replicated on every connected subnet of
22727 			 * the target net.
22728 			 *
22729 			 * Each zone has its own set of IRE_BROADCASTs, so that
22730 			 * we're able to distribute inbound packets to multiple
22731 			 * zones who share a broadcast address. We avoid looping
22732 			 * back outbound packets in different zones but on the
22733 			 * same ill, as the application would see duplicates.
22734 			 *
22735 			 * If the interfaces are part of the same group,
22736 			 * we would want to send only one copy out for
22737 			 * whole group.
22738 			 *
22739 			 * This logic assumes that ire_add_v4() groups the
22740 			 * IRE_BROADCAST entries so that those with the same
22741 			 * ire_addr and ill_group are kept together.
22742 			 */
22743 			ire_ill = ire->ire_ipif->ipif_ill;
22744 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22745 				if (ire_ill->ill_group != NULL &&
22746 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22747 					/*
22748 					 * If the current zone only has an ire
22749 					 * broadcast for this address marked
22750 					 * NORECV, the ire we want is ahead in
22751 					 * the bucket, so we look it up
22752 					 * deliberately ignoring the zoneid.
22753 					 */
22754 					for (ire1 = ire->ire_bucket->irb_ire;
22755 					    ire1 != NULL;
22756 					    ire1 = ire1->ire_next) {
22757 						ire1_ill =
22758 						    ire1->ire_ipif->ipif_ill;
22759 						if (ire1->ire_addr != dst)
22760 							continue;
22761 						/* skip over the current ire */
22762 						if (ire1 == ire)
22763 							continue;
22764 						/* skip over deleted ires */
22765 						if (ire1->ire_marks &
22766 						    IRE_MARK_CONDEMNED)
22767 							continue;
22768 						/*
22769 						 * non-loopback ire in our
22770 						 * group: use it for the next
22771 						 * pass in the loop
22772 						 */
22773 						if (ire1->ire_stq != NULL &&
22774 						    ire1_ill->ill_group ==
22775 						    ire_ill->ill_group)
22776 							break;
22777 					}
22778 				}
22779 			} else {
22780 				while (ire1 != NULL && ire1->ire_addr == dst) {
22781 					ire1_ill = ire1->ire_ipif->ipif_ill;
22782 					/*
22783 					 * We can have two broadcast ires on the
22784 					 * same ill in different zones; here
22785 					 * we'll send a copy of the packet on
22786 					 * each ill and the fanout code will
22787 					 * call conn_wantpacket() to check that
22788 					 * the zone has the broadcast address
22789 					 * configured on the ill. If the two
22790 					 * ires are in the same group we only
22791 					 * send one copy up.
22792 					 */
22793 					if (ire1_ill != ire_ill &&
22794 					    (ire1_ill->ill_group == NULL ||
22795 					    ire_ill->ill_group == NULL ||
22796 					    ire1_ill->ill_group !=
22797 					    ire_ill->ill_group)) {
22798 						break;
22799 					}
22800 					ire1 = ire1->ire_next;
22801 				}
22802 			}
22803 		}
22804 		ASSERT(multirt_send == B_FALSE);
22805 		if (ire1 != NULL && ire1->ire_addr == dst) {
22806 			if ((ire->ire_flags & RTF_MULTIRT) &&
22807 			    (ire1->ire_flags & RTF_MULTIRT)) {
22808 				/*
22809 				 * We are in the multirouting case.
22810 				 * The message must be sent at least
22811 				 * on both ires. These ires have been
22812 				 * inserted AFTER the standard ones
22813 				 * in ip_rt_add(). There are thus no
22814 				 * other ire entries for the destination
22815 				 * address in the rest of the bucket
22816 				 * that do not have the RTF_MULTIRT
22817 				 * flag. We don't process a copy
22818 				 * of the message here. This will be
22819 				 * done in the final sending loop.
22820 				 */
22821 				multirt_send = B_TRUE;
22822 			} else {
22823 				next_mp = ip_copymsg(first_mp);
22824 				if (next_mp != NULL)
22825 					IRE_REFHOLD(ire1);
22826 			}
22827 		}
22828 		rw_exit(&ire->ire_bucket->irb_lock);
22829 	}
22830 
22831 	if (stq) {
22832 		/*
22833 		 * A non-NULL send-to queue means this packet is going
22834 		 * out of this machine.
22835 		 */
22836 		out_ill = (ill_t *)stq->q_ptr;
22837 
22838 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22839 		ttl_protocol = ((uint16_t *)ipha)[4];
22840 		/*
22841 		 * We accumulate the pseudo header checksum in cksum.
22842 		 * This is pretty hairy code, so watch close.  One
22843 		 * thing to keep in mind is that UDP and TCP have
22844 		 * stored their respective datagram lengths in their
22845 		 * checksum fields.  This lines things up real nice.
22846 		 */
22847 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22848 		    (src >> 16) + (src & 0xFFFF);
22849 		/*
22850 		 * We assume the udp checksum field contains the
22851 		 * length, so to compute the pseudo header checksum,
22852 		 * all we need is the protocol number and src/dst.
22853 		 */
22854 		/* Provide the checksums for UDP and TCP. */
22855 		if ((PROTO == IPPROTO_TCP) &&
22856 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22857 			/* hlen gets the number of uchar_ts in the IP header */
22858 			hlen = (V_HLEN & 0xF) << 2;
22859 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22860 			IP_STAT(ip_out_sw_cksum);
22861 			IP_STAT_UPDATE(ip_tcp_out_sw_cksum_bytes,
22862 			    LENGTH - hlen);
22863 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22864 			if (*up == 0)
22865 				*up = 0xFFFF;
22866 		} else if (PROTO == IPPROTO_SCTP &&
22867 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22868 			sctp_hdr_t	*sctph;
22869 
22870 			hlen = (V_HLEN & 0xF) << 2;
22871 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22872 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22873 			sctph->sh_chksum = 0;
22874 #ifdef	DEBUG
22875 			if (!skip_sctp_cksum)
22876 #endif
22877 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22878 		} else {
22879 			queue_t *dev_q = stq->q_next;
22880 
22881 			if ((dev_q->q_next || dev_q->q_first) &&
22882 			    !canput(dev_q)) {
22883 			    blocked:
22884 				ipha->ipha_ident = ip_hdr_included;
22885 				/*
22886 				 * If we don't have a conn to apply
22887 				 * backpressure, free the message.
22888 				 * In the ire_send path, we don't know
22889 				 * the position to requeue the packet. Rather
22890 				 * than reorder packets, we just drop this
22891 				 * packet.
22892 				 */
22893 				if (ip_output_queue && connp != NULL &&
22894 				    caller != IRE_SEND) {
22895 					if (caller == IP_WSRV) {
22896 						connp->conn_did_putbq = 1;
22897 						(void) putbq(connp->conn_wq,
22898 						    first_mp);
22899 						conn_drain_insert(connp);
22900 						/*
22901 						 * This is the service thread,
22902 						 * and the queue is already
22903 						 * noenabled. The check for
22904 						 * canput and the putbq is not
22905 						 * atomic. So we need to check
22906 						 * again.
22907 						 */
22908 						if (canput(stq->q_next))
22909 							connp->conn_did_putbq
22910 							    = 0;
22911 						IP_STAT(ip_conn_flputbq);
22912 					} else {
22913 						/*
22914 						 * We are not the service proc.
22915 						 * ip_wsrv will be scheduled or
22916 						 * is already running.
22917 						 */
22918 						(void) putq(connp->conn_wq,
22919 						    first_mp);
22920 					}
22921 				} else {
22922 					out_ill = (ill_t *)stq->q_ptr;
22923 					BUMP_MIB(out_ill->ill_ip_mib,
22924 					    ipIfStatsOutDiscards);
22925 					freemsg(first_mp);
22926 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22927 					    "ip_wput_ire_end: q %p (%S)",
22928 					    q, "discard");
22929 				}
22930 				ire_refrele(ire);
22931 				if (next_mp) {
22932 					ire_refrele(ire1);
22933 					freemsg(next_mp);
22934 				}
22935 				if (conn_outgoing_ill != NULL)
22936 					ill_refrele(conn_outgoing_ill);
22937 				return;
22938 			}
22939 			if ((PROTO == IPPROTO_UDP) &&
22940 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22941 				/*
22942 				 * hlen gets the number of uchar_ts in the
22943 				 * IP header
22944 				 */
22945 				hlen = (V_HLEN & 0xF) << 2;
22946 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22947 				max_frag = ire->ire_max_frag;
22948 				if (*up != 0) {
22949 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22950 					    up, PROTO, hlen, LENGTH, max_frag,
22951 					    ipsec_len, cksum);
22952 					/* Software checksum? */
22953 					if (DB_CKSUMFLAGS(mp) == 0) {
22954 						IP_STAT(ip_out_sw_cksum);
22955 						IP_STAT_UPDATE(
22956 						    ip_udp_out_sw_cksum_bytes,
22957 						    LENGTH - hlen);
22958 					}
22959 				}
22960 			}
22961 		}
22962 		/*
22963 		 * Need to do this even when fragmenting. The local
22964 		 * loopback can be done without computing checksums
22965 		 * but forwarding out other interface must be done
22966 		 * after the IP checksum (and ULP checksums) have been
22967 		 * computed.
22968 		 *
22969 		 * NOTE : multicast_forward is set only if this packet
22970 		 * originated from ip_wput. For packets originating from
22971 		 * ip_wput_multicast, it is not set.
22972 		 */
22973 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22974 		    multi_loopback:
22975 			ip2dbg(("ip_wput: multicast, loop %d\n",
22976 			    conn_multicast_loop));
22977 
22978 			/*  Forget header checksum offload */
22979 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22980 
22981 			/*
22982 			 * Local loopback of multicasts?  Check the
22983 			 * ill.
22984 			 *
22985 			 * Note that the loopback function will not come
22986 			 * in through ip_rput - it will only do the
22987 			 * client fanout thus we need to do an mforward
22988 			 * as well.  The is different from the BSD
22989 			 * logic.
22990 			 */
22991 			if (ill != NULL) {
22992 				ilm_t	*ilm;
22993 
22994 				ILM_WALKER_HOLD(ill);
22995 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22996 				    ALL_ZONES);
22997 				ILM_WALKER_RELE(ill);
22998 				if (ilm != NULL) {
22999 					/*
23000 					 * Pass along the virtual output q.
23001 					 * ip_wput_local() will distribute the
23002 					 * packet to all the matching zones,
23003 					 * except the sending zone when
23004 					 * IP_MULTICAST_LOOP is false.
23005 					 */
23006 					ip_multicast_loopback(q, ill, first_mp,
23007 					    conn_multicast_loop ? 0 :
23008 					    IP_FF_NO_MCAST_LOOP, zoneid);
23009 				}
23010 			}
23011 			if (ipha->ipha_ttl == 0) {
23012 				/*
23013 				 * 0 => only to this host i.e. we are
23014 				 * done. We are also done if this was the
23015 				 * loopback interface since it is sufficient
23016 				 * to loopback one copy of a multicast packet.
23017 				 */
23018 				freemsg(first_mp);
23019 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23020 				    "ip_wput_ire_end: q %p (%S)",
23021 				    q, "loopback");
23022 				ire_refrele(ire);
23023 				if (conn_outgoing_ill != NULL)
23024 					ill_refrele(conn_outgoing_ill);
23025 				return;
23026 			}
23027 			/*
23028 			 * ILLF_MULTICAST is checked in ip_newroute
23029 			 * i.e. we don't need to check it here since
23030 			 * all IRE_CACHEs come from ip_newroute.
23031 			 * For multicast traffic, SO_DONTROUTE is interpreted
23032 			 * to mean only send the packet out the interface
23033 			 * (optionally specified with IP_MULTICAST_IF)
23034 			 * and do not forward it out additional interfaces.
23035 			 * RSVP and the rsvp daemon is an example of a
23036 			 * protocol and user level process that
23037 			 * handles it's own routing. Hence, it uses the
23038 			 * SO_DONTROUTE option to accomplish this.
23039 			 */
23040 
23041 			if (ip_g_mrouter && !conn_dontroute && ill != NULL) {
23042 				/* Unconditionally redo the checksum */
23043 				ipha->ipha_hdr_checksum = 0;
23044 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23045 
23046 				/*
23047 				 * If this needs to go out secure, we need
23048 				 * to wait till we finish the IPSEC
23049 				 * processing.
23050 				 */
23051 				if (ipsec_len == 0 &&
23052 				    ip_mforward(ill, ipha, mp)) {
23053 					freemsg(first_mp);
23054 					ip1dbg(("ip_wput: mforward failed\n"));
23055 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23056 					    "ip_wput_ire_end: q %p (%S)",
23057 					    q, "mforward failed");
23058 					ire_refrele(ire);
23059 					if (conn_outgoing_ill != NULL)
23060 						ill_refrele(conn_outgoing_ill);
23061 					return;
23062 				}
23063 			}
23064 		}
23065 		max_frag = ire->ire_max_frag;
23066 		cksum += ttl_protocol;
23067 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23068 			/* No fragmentation required for this one. */
23069 			/*
23070 			 * Don't use frag_flag if packet is pre-built or source
23071 			 * routed or if multicast (since multicast packets do
23072 			 * not solicit ICMP "packet too big" messages).
23073 			 */
23074 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23075 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23076 			    !ip_source_route_included(ipha)) &&
23077 			    !CLASSD(ipha->ipha_dst))
23078 				ipha->ipha_fragment_offset_and_flags |=
23079 				    htons(ire->ire_frag_flag);
23080 
23081 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23082 				/* Complete the IP header checksum. */
23083 				cksum += ipha->ipha_ident;
23084 				cksum += (v_hlen_tos_len >> 16)+
23085 				    (v_hlen_tos_len & 0xFFFF);
23086 				cksum += ipha->ipha_fragment_offset_and_flags;
23087 				hlen = (V_HLEN & 0xF) -
23088 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23089 				if (hlen) {
23090 				    checksumoptions:
23091 					/*
23092 					 * Account for the IP Options in the IP
23093 					 * header checksum.
23094 					 */
23095 					up = (uint16_t *)(rptr+
23096 					    IP_SIMPLE_HDR_LENGTH);
23097 					do {
23098 						cksum += up[0];
23099 						cksum += up[1];
23100 						up += 2;
23101 					} while (--hlen);
23102 				}
23103 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23104 				cksum = ~(cksum + (cksum >> 16));
23105 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23106 			}
23107 			if (ipsec_len != 0) {
23108 				ipsec_out_process(q, first_mp, ire, ill_index);
23109 				if (!next_mp) {
23110 					ire_refrele(ire);
23111 					if (conn_outgoing_ill != NULL)
23112 						ill_refrele(conn_outgoing_ill);
23113 					return;
23114 				}
23115 				goto next;
23116 			}
23117 
23118 			/*
23119 			 * multirt_send has already been handled
23120 			 * for broadcast, but not yet for multicast
23121 			 * or IP options.
23122 			 */
23123 			if (next_mp == NULL) {
23124 				if (ire->ire_flags & RTF_MULTIRT) {
23125 					multirt_send = B_TRUE;
23126 				}
23127 			}
23128 
23129 			/*
23130 			 * In most cases, the emission loop below is
23131 			 * entered only once. Only in the case where
23132 			 * the ire holds the RTF_MULTIRT flag, do we loop
23133 			 * to process all RTF_MULTIRT ires in the bucket,
23134 			 * and send the packet through all crossed
23135 			 * RTF_MULTIRT routes.
23136 			 */
23137 			do {
23138 				if (multirt_send) {
23139 					irb_t *irb;
23140 
23141 					irb = ire->ire_bucket;
23142 					ASSERT(irb != NULL);
23143 					/*
23144 					 * We are in a multiple send case,
23145 					 * need to get the next IRE and make
23146 					 * a duplicate of the packet.
23147 					 */
23148 					IRB_REFHOLD(irb);
23149 					for (ire1 = ire->ire_next;
23150 					    ire1 != NULL;
23151 					    ire1 = ire1->ire_next) {
23152 						if (!(ire1->ire_flags &
23153 						    RTF_MULTIRT))
23154 							continue;
23155 						if (ire1->ire_addr !=
23156 						    ire->ire_addr)
23157 							continue;
23158 						if (ire1->ire_marks &
23159 						    (IRE_MARK_CONDEMNED|
23160 							IRE_MARK_HIDDEN))
23161 							continue;
23162 
23163 						/* Got one */
23164 						IRE_REFHOLD(ire1);
23165 						break;
23166 					}
23167 					IRB_REFRELE(irb);
23168 
23169 					if (ire1 != NULL) {
23170 						next_mp = copyb(mp);
23171 						if ((next_mp == NULL) ||
23172 						    ((mp->b_cont != NULL) &&
23173 						    ((next_mp->b_cont =
23174 						    dupmsg(mp->b_cont))
23175 						    == NULL))) {
23176 							freemsg(next_mp);
23177 							next_mp = NULL;
23178 							ire_refrele(ire1);
23179 							ire1 = NULL;
23180 						}
23181 					}
23182 
23183 					/*
23184 					 * Last multiroute ire; don't loop
23185 					 * anymore. The emission is over
23186 					 * and next_mp is NULL.
23187 					 */
23188 					if (ire1 == NULL) {
23189 						multirt_send = B_FALSE;
23190 					}
23191 				}
23192 
23193 				out_ill = ire->ire_ipif->ipif_ill;
23194 				DTRACE_PROBE4(ip4__physical__out__start,
23195 				    ill_t *, NULL,
23196 				    ill_t *, out_ill,
23197 				    ipha_t *, ipha, mblk_t *, mp);
23198 				FW_HOOKS(ip4_physical_out_event,
23199 				    ipv4firewall_physical_out,
23200 				    NULL, out_ill, ipha, mp, mp);
23201 				DTRACE_PROBE1(ip4__physical__out__end,
23202 				    mblk_t *, mp);
23203 				if (mp == NULL)
23204 					goto release_ire_and_ill_2;
23205 
23206 				ASSERT(ipsec_len == 0);
23207 				mp->b_prev =
23208 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23209 				DTRACE_PROBE2(ip__xmit__2,
23210 				    mblk_t *, mp, ire_t *, ire);
23211 				pktxmit_state = ip_xmit_v4(mp, ire,
23212 				    NULL, B_TRUE);
23213 				if ((pktxmit_state == SEND_FAILED) ||
23214 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23215 release_ire_and_ill_2:
23216 					if (next_mp) {
23217 						freemsg(next_mp);
23218 						ire_refrele(ire1);
23219 					}
23220 					ire_refrele(ire);
23221 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23222 					    "ip_wput_ire_end: q %p (%S)",
23223 					    q, "discard MDATA");
23224 					if (conn_outgoing_ill != NULL)
23225 						ill_refrele(conn_outgoing_ill);
23226 					return;
23227 				}
23228 
23229 				if (CLASSD(dst)) {
23230 					BUMP_MIB(out_ill->ill_ip_mib,
23231 					    ipIfStatsHCOutMcastPkts);
23232 					UPDATE_MIB(out_ill->ill_ip_mib,
23233 					    ipIfStatsHCOutMcastOctets,
23234 					    ntohs(ipha->ipha_length));
23235 				} else if (ire->ire_type == IRE_BROADCAST) {
23236 					BUMP_MIB(out_ill->ill_ip_mib,
23237 					    ipIfStatsHCOutBcastPkts);
23238 				}
23239 
23240 				if (multirt_send) {
23241 					/*
23242 					 * We are in a multiple send case,
23243 					 * need to re-enter the sending loop
23244 					 * using the next ire.
23245 					 */
23246 					ire_refrele(ire);
23247 					ire = ire1;
23248 					stq = ire->ire_stq;
23249 					mp = next_mp;
23250 					next_mp = NULL;
23251 					ipha = (ipha_t *)mp->b_rptr;
23252 					ill_index = Q_TO_INDEX(stq);
23253 				}
23254 			} while (multirt_send);
23255 
23256 			if (!next_mp) {
23257 				/*
23258 				 * Last copy going out (the ultra-common
23259 				 * case).  Note that we intentionally replicate
23260 				 * the putnext rather than calling it before
23261 				 * the next_mp check in hopes of a little
23262 				 * tail-call action out of the compiler.
23263 				 */
23264 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23265 				    "ip_wput_ire_end: q %p (%S)",
23266 				    q, "last copy out(1)");
23267 				ire_refrele(ire);
23268 				if (conn_outgoing_ill != NULL)
23269 					ill_refrele(conn_outgoing_ill);
23270 				return;
23271 			}
23272 			/* More copies going out below. */
23273 		} else {
23274 			int offset;
23275 		    fragmentit:
23276 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23277 			/*
23278 			 * If this would generate a icmp_frag_needed message,
23279 			 * we need to handle it before we do the IPSEC
23280 			 * processing. Otherwise, we need to strip the IPSEC
23281 			 * headers before we send up the message to the ULPs
23282 			 * which becomes messy and difficult.
23283 			 */
23284 			if (ipsec_len != 0) {
23285 				if ((max_frag < (unsigned int)(LENGTH +
23286 				    ipsec_len)) && (offset & IPH_DF)) {
23287 					out_ill = (ill_t *)stq->q_ptr;
23288 					BUMP_MIB(out_ill->ill_ip_mib,
23289 					    ipIfStatsOutFragFails);
23290 					BUMP_MIB(out_ill->ill_ip_mib,
23291 					    ipIfStatsOutFragReqds);
23292 					ipha->ipha_hdr_checksum = 0;
23293 					ipha->ipha_hdr_checksum =
23294 					    (uint16_t)ip_csum_hdr(ipha);
23295 					icmp_frag_needed(ire->ire_stq, first_mp,
23296 					    max_frag, zoneid);
23297 					if (!next_mp) {
23298 						ire_refrele(ire);
23299 						if (conn_outgoing_ill != NULL) {
23300 							ill_refrele(
23301 							    conn_outgoing_ill);
23302 						}
23303 						return;
23304 					}
23305 				} else {
23306 					/*
23307 					 * This won't cause a icmp_frag_needed
23308 					 * message. to be generated. Send it on
23309 					 * the wire. Note that this could still
23310 					 * cause fragmentation and all we
23311 					 * do is the generation of the message
23312 					 * to the ULP if needed before IPSEC.
23313 					 */
23314 					if (!next_mp) {
23315 						ipsec_out_process(q, first_mp,
23316 						    ire, ill_index);
23317 						TRACE_2(TR_FAC_IP,
23318 						    TR_IP_WPUT_IRE_END,
23319 						    "ip_wput_ire_end: q %p "
23320 						    "(%S)", q,
23321 						    "last ipsec_out_process");
23322 						ire_refrele(ire);
23323 						if (conn_outgoing_ill != NULL) {
23324 							ill_refrele(
23325 							    conn_outgoing_ill);
23326 						}
23327 						return;
23328 					}
23329 					ipsec_out_process(q, first_mp,
23330 					    ire, ill_index);
23331 				}
23332 			} else {
23333 				/*
23334 				 * Initiate IPPF processing. For
23335 				 * fragmentable packets we finish
23336 				 * all QOS packet processing before
23337 				 * calling:
23338 				 * ip_wput_ire_fragmentit->ip_wput_frag
23339 				 */
23340 
23341 				if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23342 					ip_process(IPP_LOCAL_OUT, &mp,
23343 					    ill_index);
23344 					if (mp == NULL) {
23345 						out_ill = (ill_t *)stq->q_ptr;
23346 						BUMP_MIB(out_ill->ill_ip_mib,
23347 						    ipIfStatsOutDiscards);
23348 						if (next_mp != NULL) {
23349 							freemsg(next_mp);
23350 							ire_refrele(ire1);
23351 						}
23352 						ire_refrele(ire);
23353 						TRACE_2(TR_FAC_IP,
23354 						    TR_IP_WPUT_IRE_END,
23355 						    "ip_wput_ire: q %p (%S)",
23356 						    q, "discard MDATA");
23357 						if (conn_outgoing_ill != NULL) {
23358 							ill_refrele(
23359 							    conn_outgoing_ill);
23360 						}
23361 						return;
23362 					}
23363 				}
23364 				if (!next_mp) {
23365 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23366 					    "ip_wput_ire_end: q %p (%S)",
23367 					    q, "last fragmentation");
23368 					ip_wput_ire_fragmentit(mp, ire,
23369 					    zoneid);
23370 					ire_refrele(ire);
23371 					if (conn_outgoing_ill != NULL)
23372 						ill_refrele(conn_outgoing_ill);
23373 					return;
23374 				}
23375 				ip_wput_ire_fragmentit(mp, ire, zoneid);
23376 			}
23377 		}
23378 	} else {
23379 	    nullstq:
23380 		/* A NULL stq means the destination address is local. */
23381 		UPDATE_OB_PKT_COUNT(ire);
23382 		ire->ire_last_used_time = lbolt;
23383 		ASSERT(ire->ire_ipif != NULL);
23384 		if (!next_mp) {
23385 			/*
23386 			 * Is there an "in" and "out" for traffic local
23387 			 * to a host (loopback)?  The code in Solaris doesn't
23388 			 * explicitly draw a line in its code for in vs out,
23389 			 * so we've had to draw a line in the sand: ip_wput_ire
23390 			 * is considered to be the "output" side and
23391 			 * ip_wput_local to be the "input" side.
23392 			 */
23393 			out_ill = ire->ire_ipif->ipif_ill;
23394 
23395 			DTRACE_PROBE4(ip4__loopback__out__start,
23396 			    ill_t *, NULL, ill_t *, out_ill,
23397 			    ipha_t *, ipha, mblk_t *, first_mp);
23398 
23399 			FW_HOOKS(ip4_loopback_out_event,
23400 			    ipv4firewall_loopback_out,
23401 			    NULL, out_ill, ipha, first_mp, mp);
23402 
23403 			DTRACE_PROBE1(ip4__loopback__out_end,
23404 			    mblk_t *, first_mp);
23405 
23406 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23407 			    "ip_wput_ire_end: q %p (%S)",
23408 			    q, "local address");
23409 
23410 			if (first_mp != NULL)
23411 				ip_wput_local(q, out_ill, ipha,
23412 				    first_mp, ire, 0, ire->ire_zoneid);
23413 			ire_refrele(ire);
23414 			if (conn_outgoing_ill != NULL)
23415 				ill_refrele(conn_outgoing_ill);
23416 			return;
23417 		}
23418 
23419 		out_ill = ire->ire_ipif->ipif_ill;
23420 
23421 		DTRACE_PROBE4(ip4__loopback__out__start,
23422 		    ill_t *, NULL, ill_t *, out_ill,
23423 		    ipha_t *, ipha, mblk_t *, first_mp);
23424 
23425 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
23426 		    NULL, out_ill, ipha, first_mp, mp);
23427 
23428 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23429 
23430 		if (first_mp != NULL)
23431 			ip_wput_local(q, out_ill, ipha,
23432 			    first_mp, ire, 0, ire->ire_zoneid);
23433 	}
23434 next:
23435 	/*
23436 	 * More copies going out to additional interfaces.
23437 	 * ire1 has already been held. We don't need the
23438 	 * "ire" anymore.
23439 	 */
23440 	ire_refrele(ire);
23441 	ire = ire1;
23442 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23443 	mp = next_mp;
23444 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23445 	ill = ire_to_ill(ire);
23446 	first_mp = mp;
23447 	if (ipsec_len != 0) {
23448 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23449 		mp = mp->b_cont;
23450 	}
23451 	dst = ire->ire_addr;
23452 	ipha = (ipha_t *)mp->b_rptr;
23453 	/*
23454 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23455 	 * Restore ipha_ident "no checksum" flag.
23456 	 */
23457 	src = orig_src;
23458 	ipha->ipha_ident = ip_hdr_included;
23459 	goto another;
23460 
23461 #undef	rptr
23462 #undef	Q_TO_INDEX
23463 }
23464 
23465 /*
23466  * Routine to allocate a message that is used to notify the ULP about MDT.
23467  * The caller may provide a pointer to the link-layer MDT capabilities,
23468  * or NULL if MDT is to be disabled on the stream.
23469  */
23470 mblk_t *
23471 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23472 {
23473 	mblk_t *mp;
23474 	ip_mdt_info_t *mdti;
23475 	ill_mdt_capab_t *idst;
23476 
23477 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23478 		DB_TYPE(mp) = M_CTL;
23479 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23480 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23481 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23482 		idst = &(mdti->mdt_capab);
23483 
23484 		/*
23485 		 * If the caller provides us with the capability, copy
23486 		 * it over into our notification message; otherwise
23487 		 * we zero out the capability portion.
23488 		 */
23489 		if (isrc != NULL)
23490 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23491 		else
23492 			bzero((caddr_t)idst, sizeof (*idst));
23493 	}
23494 	return (mp);
23495 }
23496 
23497 /*
23498  * Routine which determines whether MDT can be enabled on the destination
23499  * IRE and IPC combination, and if so, allocates and returns the MDT
23500  * notification mblk that may be used by ULP.  We also check if we need to
23501  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23502  * MDT usage in the past have been lifted.  This gets called during IP
23503  * and ULP binding.
23504  */
23505 mblk_t *
23506 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23507     ill_mdt_capab_t *mdt_cap)
23508 {
23509 	mblk_t *mp;
23510 	boolean_t rc = B_FALSE;
23511 
23512 	ASSERT(dst_ire != NULL);
23513 	ASSERT(connp != NULL);
23514 	ASSERT(mdt_cap != NULL);
23515 
23516 	/*
23517 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23518 	 * Multidata, which is handled in tcp_multisend().  This
23519 	 * is the reason why we do all these checks here, to ensure
23520 	 * that we don't enable Multidata for the cases which we
23521 	 * can't handle at the moment.
23522 	 */
23523 	do {
23524 		/* Only do TCP at the moment */
23525 		if (connp->conn_ulp != IPPROTO_TCP)
23526 			break;
23527 
23528 		/*
23529 		 * IPSEC outbound policy present?  Note that we get here
23530 		 * after calling ipsec_conn_cache_policy() where the global
23531 		 * policy checking is performed.  conn_latch will be
23532 		 * non-NULL as long as there's a policy defined,
23533 		 * i.e. conn_out_enforce_policy may be NULL in such case
23534 		 * when the connection is non-secure, and hence we check
23535 		 * further if the latch refers to an outbound policy.
23536 		 */
23537 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23538 			break;
23539 
23540 		/* CGTP (multiroute) is enabled? */
23541 		if (dst_ire->ire_flags & RTF_MULTIRT)
23542 			break;
23543 
23544 		/* Outbound IPQoS enabled? */
23545 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23546 			/*
23547 			 * In this case, we disable MDT for this and all
23548 			 * future connections going over the interface.
23549 			 */
23550 			mdt_cap->ill_mdt_on = 0;
23551 			break;
23552 		}
23553 
23554 		/* socket option(s) present? */
23555 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23556 			break;
23557 
23558 		rc = B_TRUE;
23559 	/* CONSTCOND */
23560 	} while (0);
23561 
23562 	/* Remember the result */
23563 	connp->conn_mdt_ok = rc;
23564 
23565 	if (!rc)
23566 		return (NULL);
23567 	else if (!mdt_cap->ill_mdt_on) {
23568 		/*
23569 		 * If MDT has been previously turned off in the past, and we
23570 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23571 		 * then enable it for this interface.
23572 		 */
23573 		mdt_cap->ill_mdt_on = 1;
23574 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23575 		    "interface %s\n", ill_name));
23576 	}
23577 
23578 	/* Allocate the MDT info mblk */
23579 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23580 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23581 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23582 		return (NULL);
23583 	}
23584 	return (mp);
23585 }
23586 
23587 /*
23588  * Routine to allocate a message that is used to notify the ULP about LSO.
23589  * The caller may provide a pointer to the link-layer LSO capabilities,
23590  * or NULL if LSO is to be disabled on the stream.
23591  */
23592 mblk_t *
23593 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23594 {
23595 	mblk_t *mp;
23596 	ip_lso_info_t *lsoi;
23597 	ill_lso_capab_t *idst;
23598 
23599 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23600 		DB_TYPE(mp) = M_CTL;
23601 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23602 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23603 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23604 		idst = &(lsoi->lso_capab);
23605 
23606 		/*
23607 		 * If the caller provides us with the capability, copy
23608 		 * it over into our notification message; otherwise
23609 		 * we zero out the capability portion.
23610 		 */
23611 		if (isrc != NULL)
23612 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23613 		else
23614 			bzero((caddr_t)idst, sizeof (*idst));
23615 	}
23616 	return (mp);
23617 }
23618 
23619 /*
23620  * Routine which determines whether LSO can be enabled on the destination
23621  * IRE and IPC combination, and if so, allocates and returns the LSO
23622  * notification mblk that may be used by ULP.  We also check if we need to
23623  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23624  * LSO usage in the past have been lifted.  This gets called during IP
23625  * and ULP binding.
23626  */
23627 mblk_t *
23628 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23629     ill_lso_capab_t *lso_cap)
23630 {
23631 	mblk_t *mp;
23632 
23633 	ASSERT(dst_ire != NULL);
23634 	ASSERT(connp != NULL);
23635 	ASSERT(lso_cap != NULL);
23636 
23637 	connp->conn_lso_ok = B_TRUE;
23638 
23639 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23640 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23641 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23642 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23643 	    (IPP_ENABLED(IPP_LOCAL_OUT))) {
23644 		connp->conn_lso_ok = B_FALSE;
23645 		if (IPP_ENABLED(IPP_LOCAL_OUT)) {
23646 			/*
23647 			 * Disable LSO for this and all future connections going
23648 			 * over the interface.
23649 			 */
23650 			lso_cap->ill_lso_on = 0;
23651 		}
23652 	}
23653 
23654 	if (!connp->conn_lso_ok)
23655 		return (NULL);
23656 	else if (!lso_cap->ill_lso_on) {
23657 		/*
23658 		 * If LSO has been previously turned off in the past, and we
23659 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23660 		 * then enable it for this interface.
23661 		 */
23662 		lso_cap->ill_lso_on = 1;
23663 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23664 		    ill_name));
23665 	}
23666 
23667 	/* Allocate the LSO info mblk */
23668 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23669 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23670 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23671 
23672 	return (mp);
23673 }
23674 
23675 /*
23676  * Create destination address attribute, and fill it with the physical
23677  * destination address and SAP taken from the template DL_UNITDATA_REQ
23678  * message block.
23679  */
23680 boolean_t
23681 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23682 {
23683 	dl_unitdata_req_t *dlurp;
23684 	pattr_t *pa;
23685 	pattrinfo_t pa_info;
23686 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23687 	uint_t das_len, das_off;
23688 
23689 	ASSERT(dlmp != NULL);
23690 
23691 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23692 	das_len = dlurp->dl_dest_addr_length;
23693 	das_off = dlurp->dl_dest_addr_offset;
23694 
23695 	pa_info.type = PATTR_DSTADDRSAP;
23696 	pa_info.len = sizeof (**das) + das_len - 1;
23697 
23698 	/* create and associate the attribute */
23699 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23700 	if (pa != NULL) {
23701 		ASSERT(*das != NULL);
23702 		(*das)->addr_is_group = 0;
23703 		(*das)->addr_len = (uint8_t)das_len;
23704 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23705 	}
23706 
23707 	return (pa != NULL);
23708 }
23709 
23710 /*
23711  * Create hardware checksum attribute and fill it with the values passed.
23712  */
23713 boolean_t
23714 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23715     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23716 {
23717 	pattr_t *pa;
23718 	pattrinfo_t pa_info;
23719 
23720 	ASSERT(mmd != NULL);
23721 
23722 	pa_info.type = PATTR_HCKSUM;
23723 	pa_info.len = sizeof (pattr_hcksum_t);
23724 
23725 	/* create and associate the attribute */
23726 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23727 	if (pa != NULL) {
23728 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23729 
23730 		hck->hcksum_start_offset = start_offset;
23731 		hck->hcksum_stuff_offset = stuff_offset;
23732 		hck->hcksum_end_offset = end_offset;
23733 		hck->hcksum_flags = flags;
23734 	}
23735 	return (pa != NULL);
23736 }
23737 
23738 /*
23739  * Create zerocopy attribute and fill it with the specified flags
23740  */
23741 boolean_t
23742 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23743 {
23744 	pattr_t *pa;
23745 	pattrinfo_t pa_info;
23746 
23747 	ASSERT(mmd != NULL);
23748 	pa_info.type = PATTR_ZCOPY;
23749 	pa_info.len = sizeof (pattr_zcopy_t);
23750 
23751 	/* create and associate the attribute */
23752 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23753 	if (pa != NULL) {
23754 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23755 
23756 		zcopy->zcopy_flags = flags;
23757 	}
23758 	return (pa != NULL);
23759 }
23760 
23761 /*
23762  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23763  * block chain. We could rewrite to handle arbitrary message block chains but
23764  * that would make the code complicated and slow. Right now there three
23765  * restrictions:
23766  *
23767  *   1. The first message block must contain the complete IP header and
23768  *	at least 1 byte of payload data.
23769  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23770  *	so that we can use a single Multidata message.
23771  *   3. No frag must be distributed over two or more message blocks so
23772  *	that we don't need more than two packet descriptors per frag.
23773  *
23774  * The above restrictions allow us to support userland applications (which
23775  * will send down a single message block) and NFS over UDP (which will
23776  * send down a chain of at most three message blocks).
23777  *
23778  * We also don't use MDT for payloads with less than or equal to
23779  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23780  */
23781 boolean_t
23782 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23783 {
23784 	int	blocks;
23785 	ssize_t	total, missing, size;
23786 
23787 	ASSERT(mp != NULL);
23788 	ASSERT(hdr_len > 0);
23789 
23790 	size = MBLKL(mp) - hdr_len;
23791 	if (size <= 0)
23792 		return (B_FALSE);
23793 
23794 	/* The first mblk contains the header and some payload. */
23795 	blocks = 1;
23796 	total = size;
23797 	size %= len;
23798 	missing = (size == 0) ? 0 : (len - size);
23799 	mp = mp->b_cont;
23800 
23801 	while (mp != NULL) {
23802 		/*
23803 		 * Give up if we encounter a zero length message block.
23804 		 * In practice, this should rarely happen and therefore
23805 		 * not worth the trouble of freeing and re-linking the
23806 		 * mblk from the chain to handle such case.
23807 		 */
23808 		if ((size = MBLKL(mp)) == 0)
23809 			return (B_FALSE);
23810 
23811 		/* Too many payload buffers for a single Multidata message? */
23812 		if (++blocks > MULTIDATA_MAX_PBUFS)
23813 			return (B_FALSE);
23814 
23815 		total += size;
23816 		/* Is a frag distributed over two or more message blocks? */
23817 		if (missing > size)
23818 			return (B_FALSE);
23819 		size -= missing;
23820 
23821 		size %= len;
23822 		missing = (size == 0) ? 0 : (len - size);
23823 
23824 		mp = mp->b_cont;
23825 	}
23826 
23827 	return (total > ip_wput_frag_mdt_min);
23828 }
23829 
23830 /*
23831  * Outbound IPv4 fragmentation routine using MDT.
23832  */
23833 static void
23834 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23835     uint32_t frag_flag, int offset)
23836 {
23837 	ipha_t		*ipha_orig;
23838 	int		i1, ip_data_end;
23839 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23840 	mblk_t		*hdr_mp, *md_mp = NULL;
23841 	unsigned char	*hdr_ptr, *pld_ptr;
23842 	multidata_t	*mmd;
23843 	ip_pdescinfo_t	pdi;
23844 	ill_t		*ill;
23845 
23846 	ASSERT(DB_TYPE(mp) == M_DATA);
23847 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23848 
23849 	ill = ire_to_ill(ire);
23850 	ASSERT(ill != NULL);
23851 
23852 	ipha_orig = (ipha_t *)mp->b_rptr;
23853 	mp->b_rptr += sizeof (ipha_t);
23854 
23855 	/* Calculate how many packets we will send out */
23856 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23857 	pkts = (i1 + len - 1) / len;
23858 	ASSERT(pkts > 1);
23859 
23860 	/* Allocate a message block which will hold all the IP Headers. */
23861 	wroff = ip_wroff_extra;
23862 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23863 
23864 	i1 = pkts * hdr_chunk_len;
23865 	/*
23866 	 * Create the header buffer, Multidata and destination address
23867 	 * and SAP attribute that should be associated with it.
23868 	 */
23869 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23870 	    ((hdr_mp->b_wptr += i1),
23871 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23872 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23873 		freemsg(mp);
23874 		if (md_mp == NULL) {
23875 			freemsg(hdr_mp);
23876 		} else {
23877 free_mmd:		IP_STAT(ip_frag_mdt_discarded);
23878 			freemsg(md_mp);
23879 		}
23880 		IP_STAT(ip_frag_mdt_allocfail);
23881 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23882 		return;
23883 	}
23884 	IP_STAT(ip_frag_mdt_allocd);
23885 
23886 	/*
23887 	 * Add a payload buffer to the Multidata; this operation must not
23888 	 * fail, or otherwise our logic in this routine is broken.  There
23889 	 * is no memory allocation done by the routine, so any returned
23890 	 * failure simply tells us that we've done something wrong.
23891 	 *
23892 	 * A failure tells us that either we're adding the same payload
23893 	 * buffer more than once, or we're trying to add more buffers than
23894 	 * allowed.  None of the above cases should happen, and we panic
23895 	 * because either there's horrible heap corruption, and/or
23896 	 * programming mistake.
23897 	 */
23898 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23899 		goto pbuf_panic;
23900 
23901 	hdr_ptr = hdr_mp->b_rptr;
23902 	pld_ptr = mp->b_rptr;
23903 
23904 	/* Establish the ending byte offset, based on the starting offset. */
23905 	offset <<= 3;
23906 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23907 	    IP_SIMPLE_HDR_LENGTH;
23908 
23909 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23910 
23911 	while (pld_ptr < mp->b_wptr) {
23912 		ipha_t		*ipha;
23913 		uint16_t	offset_and_flags;
23914 		uint16_t	ip_len;
23915 		int		error;
23916 
23917 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23918 		ipha = (ipha_t *)(hdr_ptr + wroff);
23919 		ASSERT(OK_32PTR(ipha));
23920 		*ipha = *ipha_orig;
23921 
23922 		if (ip_data_end - offset > len) {
23923 			offset_and_flags = IPH_MF;
23924 		} else {
23925 			/*
23926 			 * Last frag. Set len to the length of this last piece.
23927 			 */
23928 			len = ip_data_end - offset;
23929 			/* A frag of a frag might have IPH_MF non-zero */
23930 			offset_and_flags =
23931 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23932 			    IPH_MF;
23933 		}
23934 		offset_and_flags |= (uint16_t)(offset >> 3);
23935 		offset_and_flags |= (uint16_t)frag_flag;
23936 		/* Store the offset and flags in the IP header. */
23937 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23938 
23939 		/* Store the length in the IP header. */
23940 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23941 		ipha->ipha_length = htons(ip_len);
23942 
23943 		/*
23944 		 * Set the IP header checksum.  Note that mp is just
23945 		 * the header, so this is easy to pass to ip_csum.
23946 		 */
23947 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23948 
23949 		/*
23950 		 * Record offset and size of header and data of the next packet
23951 		 * in the multidata message.
23952 		 */
23953 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23954 		PDESC_PLD_INIT(&pdi);
23955 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23956 		ASSERT(i1 > 0);
23957 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23958 		if (i1 == len) {
23959 			pld_ptr += len;
23960 		} else {
23961 			i1 = len - i1;
23962 			mp = mp->b_cont;
23963 			ASSERT(mp != NULL);
23964 			ASSERT(MBLKL(mp) >= i1);
23965 			/*
23966 			 * Attach the next payload message block to the
23967 			 * multidata message.
23968 			 */
23969 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23970 				goto pbuf_panic;
23971 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23972 			pld_ptr = mp->b_rptr + i1;
23973 		}
23974 
23975 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23976 		    KM_NOSLEEP)) == NULL) {
23977 			/*
23978 			 * Any failure other than ENOMEM indicates that we
23979 			 * have passed in invalid pdesc info or parameters
23980 			 * to mmd_addpdesc, which must not happen.
23981 			 *
23982 			 * EINVAL is a result of failure on boundary checks
23983 			 * against the pdesc info contents.  It should not
23984 			 * happen, and we panic because either there's
23985 			 * horrible heap corruption, and/or programming
23986 			 * mistake.
23987 			 */
23988 			if (error != ENOMEM) {
23989 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23990 				    "pdesc logic error detected for "
23991 				    "mmd %p pinfo %p (%d)\n",
23992 				    (void *)mmd, (void *)&pdi, error);
23993 				/* NOTREACHED */
23994 			}
23995 			IP_STAT(ip_frag_mdt_addpdescfail);
23996 			/* Free unattached payload message blocks as well */
23997 			md_mp->b_cont = mp->b_cont;
23998 			goto free_mmd;
23999 		}
24000 
24001 		/* Advance fragment offset. */
24002 		offset += len;
24003 
24004 		/* Advance to location for next header in the buffer. */
24005 		hdr_ptr += hdr_chunk_len;
24006 
24007 		/* Did we reach the next payload message block? */
24008 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24009 			mp = mp->b_cont;
24010 			/*
24011 			 * Attach the next message block with payload
24012 			 * data to the multidata message.
24013 			 */
24014 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24015 				goto pbuf_panic;
24016 			pld_ptr = mp->b_rptr;
24017 		}
24018 	}
24019 
24020 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24021 	ASSERT(mp->b_wptr == pld_ptr);
24022 
24023 	/* Update IP statistics */
24024 	IP_STAT_UPDATE(ip_frag_mdt_pkt_out, pkts);
24025 
24026 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24027 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24028 
24029 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24030 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24031 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24032 
24033 	if (pkt_type == OB_PKT) {
24034 		ire->ire_ob_pkt_count += pkts;
24035 		if (ire->ire_ipif != NULL)
24036 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24037 	} else {
24038 		/*
24039 		 * The type is IB_PKT in the forwarding path and in
24040 		 * the mobile IP case when the packet is being reverse-
24041 		 * tunneled to the home agent.
24042 		 */
24043 		ire->ire_ib_pkt_count += pkts;
24044 		ASSERT(!IRE_IS_LOCAL(ire));
24045 		if (ire->ire_type & IRE_BROADCAST) {
24046 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24047 		} else {
24048 			UPDATE_MIB(ill->ill_ip_mib,
24049 			    ipIfStatsHCOutForwDatagrams, pkts);
24050 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24051 		}
24052 	}
24053 	ire->ire_last_used_time = lbolt;
24054 	/* Send it down */
24055 	putnext(ire->ire_stq, md_mp);
24056 	return;
24057 
24058 pbuf_panic:
24059 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24060 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24061 	    pbuf_idx);
24062 	/* NOTREACHED */
24063 }
24064 
24065 /*
24066  * Outbound IP fragmentation routine.
24067  *
24068  * NOTE : This routine does not ire_refrele the ire that is passed in
24069  * as the argument.
24070  */
24071 static void
24072 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24073     uint32_t frag_flag, zoneid_t zoneid)
24074 {
24075 	int		i1;
24076 	mblk_t		*ll_hdr_mp;
24077 	int 		ll_hdr_len;
24078 	int		hdr_len;
24079 	mblk_t		*hdr_mp;
24080 	ipha_t		*ipha;
24081 	int		ip_data_end;
24082 	int		len;
24083 	mblk_t		*mp = mp_orig, *mp1;
24084 	int		offset;
24085 	queue_t		*q;
24086 	uint32_t	v_hlen_tos_len;
24087 	mblk_t		*first_mp;
24088 	boolean_t	mctl_present;
24089 	ill_t		*ill;
24090 	ill_t		*out_ill;
24091 	mblk_t		*xmit_mp;
24092 	mblk_t		*carve_mp;
24093 	ire_t		*ire1 = NULL;
24094 	ire_t		*save_ire = NULL;
24095 	mblk_t  	*next_mp = NULL;
24096 	boolean_t	last_frag = B_FALSE;
24097 	boolean_t	multirt_send = B_FALSE;
24098 	ire_t		*first_ire = NULL;
24099 	irb_t		*irb = NULL;
24100 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24101 
24102 	ill = ire_to_ill(ire);
24103 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ip_mib;
24104 
24105 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24106 
24107 	/*
24108 	 * IPSEC does not allow hw accelerated packets to be fragmented
24109 	 * This check is made in ip_wput_ipsec_out prior to coming here
24110 	 * via ip_wput_ire_fragmentit.
24111 	 *
24112 	 * If at this point we have an ire whose ARP request has not
24113 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24114 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24115 	 * This packet and all fragmentable packets for this ire will
24116 	 * continue to get dropped while ire_nce->nce_state remains in
24117 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24118 	 * ND_REACHABLE, all subsquent large packets for this ire will
24119 	 * get fragemented and sent out by this function.
24120 	 */
24121 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24122 		/* If nce_state is ND_INITIAL, trigger ARP query */
24123 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24124 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24125 		    " -  dropping packet\n"));
24126 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24127 		freemsg(mp);
24128 		return;
24129 	}
24130 
24131 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24132 	    "ip_wput_frag_start:");
24133 
24134 	if (mp->b_datap->db_type == M_CTL) {
24135 		first_mp = mp;
24136 		mp_orig = mp = mp->b_cont;
24137 		mctl_present = B_TRUE;
24138 	} else {
24139 		first_mp = mp;
24140 		mctl_present = B_FALSE;
24141 	}
24142 
24143 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24144 	ipha = (ipha_t *)mp->b_rptr;
24145 
24146 	/*
24147 	 * If the Don't Fragment flag is on, generate an ICMP destination
24148 	 * unreachable, fragmentation needed.
24149 	 */
24150 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24151 	if (offset & IPH_DF) {
24152 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24153 		/*
24154 		 * Need to compute hdr checksum if called from ip_wput_ire.
24155 		 * Note that ip_rput_forward verifies the checksum before
24156 		 * calling this routine so in that case this is a noop.
24157 		 */
24158 		ipha->ipha_hdr_checksum = 0;
24159 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24160 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid);
24161 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24162 		    "ip_wput_frag_end:(%S)",
24163 		    "don't fragment");
24164 		return;
24165 	}
24166 	if (mctl_present)
24167 		freeb(first_mp);
24168 	/*
24169 	 * Establish the starting offset.  May not be zero if we are fragging
24170 	 * a fragment that is being forwarded.
24171 	 */
24172 	offset = offset & IPH_OFFSET;
24173 
24174 	/* TODO why is this test needed? */
24175 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24176 	if (((max_frag - LENGTH) & ~7) < 8) {
24177 		/* TODO: notify ulp somehow */
24178 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24179 		freemsg(mp);
24180 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24181 		    "ip_wput_frag_end:(%S)",
24182 		    "len < 8");
24183 		return;
24184 	}
24185 
24186 	hdr_len = (V_HLEN & 0xF) << 2;
24187 
24188 	ipha->ipha_hdr_checksum = 0;
24189 
24190 	/*
24191 	 * Establish the number of bytes maximum per frag, after putting
24192 	 * in the header.
24193 	 */
24194 	len = (max_frag - hdr_len) & ~7;
24195 
24196 	/* Check if we can use MDT to send out the frags. */
24197 	ASSERT(!IRE_IS_LOCAL(ire));
24198 	if (hdr_len == IP_SIMPLE_HDR_LENGTH && ip_multidata_outbound &&
24199 	    !(ire->ire_flags & RTF_MULTIRT) && !IPP_ENABLED(IPP_LOCAL_OUT) &&
24200 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24201 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24202 		ASSERT(ill->ill_mdt_capab != NULL);
24203 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24204 			/*
24205 			 * If MDT has been previously turned off in the past,
24206 			 * and we currently can do MDT (due to IPQoS policy
24207 			 * removal, etc.) then enable it for this interface.
24208 			 */
24209 			ill->ill_mdt_capab->ill_mdt_on = 1;
24210 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24211 			    ill->ill_name));
24212 		}
24213 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24214 		    offset);
24215 		return;
24216 	}
24217 
24218 	/* Get a copy of the header for the trailing frags */
24219 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset);
24220 	if (!hdr_mp) {
24221 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24222 		freemsg(mp);
24223 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24224 		    "ip_wput_frag_end:(%S)",
24225 		    "couldn't copy hdr");
24226 		return;
24227 	}
24228 	if (DB_CRED(mp) != NULL)
24229 		mblk_setcred(hdr_mp, DB_CRED(mp));
24230 
24231 	/* Store the starting offset, with the MoreFrags flag. */
24232 	i1 = offset | IPH_MF | frag_flag;
24233 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24234 
24235 	/* Establish the ending byte offset, based on the starting offset. */
24236 	offset <<= 3;
24237 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24238 
24239 	/* Store the length of the first fragment in the IP header. */
24240 	i1 = len + hdr_len;
24241 	ASSERT(i1 <= IP_MAXPACKET);
24242 	ipha->ipha_length = htons((uint16_t)i1);
24243 
24244 	/*
24245 	 * Compute the IP header checksum for the first frag.  We have to
24246 	 * watch out that we stop at the end of the header.
24247 	 */
24248 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24249 
24250 	/*
24251 	 * Now carve off the first frag.  Note that this will include the
24252 	 * original IP header.
24253 	 */
24254 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24255 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24256 		freeb(hdr_mp);
24257 		freemsg(mp_orig);
24258 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24259 		    "ip_wput_frag_end:(%S)",
24260 		    "couldn't carve first");
24261 		return;
24262 	}
24263 
24264 	/*
24265 	 * Multirouting case. Each fragment is replicated
24266 	 * via all non-condemned RTF_MULTIRT routes
24267 	 * currently resolved.
24268 	 * We ensure that first_ire is the first RTF_MULTIRT
24269 	 * ire in the bucket.
24270 	 */
24271 	if (ire->ire_flags & RTF_MULTIRT) {
24272 		irb = ire->ire_bucket;
24273 		ASSERT(irb != NULL);
24274 
24275 		multirt_send = B_TRUE;
24276 
24277 		/* Make sure we do not omit any multiroute ire. */
24278 		IRB_REFHOLD(irb);
24279 		for (first_ire = irb->irb_ire;
24280 		    first_ire != NULL;
24281 		    first_ire = first_ire->ire_next) {
24282 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24283 			    (first_ire->ire_addr == ire->ire_addr) &&
24284 			    !(first_ire->ire_marks &
24285 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24286 				break;
24287 		}
24288 
24289 		if (first_ire != NULL) {
24290 			if (first_ire != ire) {
24291 				IRE_REFHOLD(first_ire);
24292 				/*
24293 				 * Do not release the ire passed in
24294 				 * as the argument.
24295 				 */
24296 				ire = first_ire;
24297 			} else {
24298 				first_ire = NULL;
24299 			}
24300 		}
24301 		IRB_REFRELE(irb);
24302 
24303 		/*
24304 		 * Save the first ire; we will need to restore it
24305 		 * for the trailing frags.
24306 		 * We REFHOLD save_ire, as each iterated ire will be
24307 		 * REFRELEd.
24308 		 */
24309 		save_ire = ire;
24310 		IRE_REFHOLD(save_ire);
24311 	}
24312 
24313 	/*
24314 	 * First fragment emission loop.
24315 	 * In most cases, the emission loop below is entered only
24316 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24317 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24318 	 * bucket, and send the fragment through all crossed
24319 	 * RTF_MULTIRT routes.
24320 	 */
24321 	do {
24322 		if (ire->ire_flags & RTF_MULTIRT) {
24323 			/*
24324 			 * We are in a multiple send case, need to get
24325 			 * the next ire and make a copy of the packet.
24326 			 * ire1 holds here the next ire to process in the
24327 			 * bucket. If multirouting is expected,
24328 			 * any non-RTF_MULTIRT ire that has the
24329 			 * right destination address is ignored.
24330 			 *
24331 			 * We have to take into account the MTU of
24332 			 * each walked ire. max_frag is set by the
24333 			 * the caller and generally refers to
24334 			 * the primary ire entry. Here we ensure that
24335 			 * no route with a lower MTU will be used, as
24336 			 * fragments are carved once for all ires,
24337 			 * then replicated.
24338 			 */
24339 			ASSERT(irb != NULL);
24340 			IRB_REFHOLD(irb);
24341 			for (ire1 = ire->ire_next;
24342 			    ire1 != NULL;
24343 			    ire1 = ire1->ire_next) {
24344 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24345 					continue;
24346 				if (ire1->ire_addr != ire->ire_addr)
24347 					continue;
24348 				if (ire1->ire_marks &
24349 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24350 					continue;
24351 				/*
24352 				 * Ensure we do not exceed the MTU
24353 				 * of the next route.
24354 				 */
24355 				if (ire1->ire_max_frag < max_frag) {
24356 					ip_multirt_bad_mtu(ire1, max_frag);
24357 					continue;
24358 				}
24359 
24360 				/* Got one. */
24361 				IRE_REFHOLD(ire1);
24362 				break;
24363 			}
24364 			IRB_REFRELE(irb);
24365 
24366 			if (ire1 != NULL) {
24367 				next_mp = copyb(mp);
24368 				if ((next_mp == NULL) ||
24369 				    ((mp->b_cont != NULL) &&
24370 				    ((next_mp->b_cont =
24371 				    dupmsg(mp->b_cont)) == NULL))) {
24372 					freemsg(next_mp);
24373 					next_mp = NULL;
24374 					ire_refrele(ire1);
24375 					ire1 = NULL;
24376 				}
24377 			}
24378 
24379 			/* Last multiroute ire; don't loop anymore. */
24380 			if (ire1 == NULL) {
24381 				multirt_send = B_FALSE;
24382 			}
24383 		}
24384 
24385 		ll_hdr_len = 0;
24386 		LOCK_IRE_FP_MP(ire);
24387 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24388 		if (ll_hdr_mp != NULL) {
24389 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24390 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24391 		} else {
24392 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24393 		}
24394 
24395 		/* If there is a transmit header, get a copy for this frag. */
24396 		/*
24397 		 * TODO: should check db_ref before calling ip_carve_mp since
24398 		 * it might give us a dup.
24399 		 */
24400 		if (!ll_hdr_mp) {
24401 			/* No xmit header. */
24402 			xmit_mp = mp;
24403 
24404 		/* We have a link-layer header that can fit in our mblk. */
24405 		} else if (mp->b_datap->db_ref == 1 &&
24406 		    ll_hdr_len != 0 &&
24407 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24408 			/* M_DATA fastpath */
24409 			mp->b_rptr -= ll_hdr_len;
24410 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24411 			xmit_mp = mp;
24412 
24413 		/* Corner case if copyb has failed */
24414 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24415 			UNLOCK_IRE_FP_MP(ire);
24416 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24417 			freeb(hdr_mp);
24418 			freemsg(mp);
24419 			freemsg(mp_orig);
24420 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24421 			    "ip_wput_frag_end:(%S)",
24422 			    "discard");
24423 
24424 			if (multirt_send) {
24425 				ASSERT(ire1);
24426 				ASSERT(next_mp);
24427 
24428 				freemsg(next_mp);
24429 				ire_refrele(ire1);
24430 			}
24431 			if (save_ire != NULL)
24432 				IRE_REFRELE(save_ire);
24433 
24434 			if (first_ire != NULL)
24435 				ire_refrele(first_ire);
24436 			return;
24437 
24438 		/*
24439 		 * Case of res_mp OR the fastpath mp can't fit
24440 		 * in the mblk
24441 		 */
24442 		} else {
24443 			xmit_mp->b_cont = mp;
24444 			if (DB_CRED(mp) != NULL)
24445 				mblk_setcred(xmit_mp, DB_CRED(mp));
24446 			/*
24447 			 * Get priority marking, if any.
24448 			 * We propagate the CoS marking from the
24449 			 * original packet that went to QoS processing
24450 			 * in ip_wput_ire to the newly carved mp.
24451 			 */
24452 			if (DB_TYPE(xmit_mp) == M_DATA)
24453 				xmit_mp->b_band = mp->b_band;
24454 		}
24455 		UNLOCK_IRE_FP_MP(ire);
24456 
24457 		q = ire->ire_stq;
24458 		out_ill = (ill_t *)q->q_ptr;
24459 
24460 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24461 
24462 		DTRACE_PROBE4(ip4__physical__out__start,
24463 		    ill_t *, NULL, ill_t *, out_ill,
24464 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24465 
24466 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
24467 		    NULL, out_ill, ipha, xmit_mp, mp);
24468 
24469 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24470 
24471 		if (xmit_mp != NULL) {
24472 			putnext(q, xmit_mp);
24473 
24474 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24475 			UPDATE_MIB(out_ill->ill_ip_mib,
24476 			    ipIfStatsHCOutOctets, i1);
24477 
24478 			if (pkt_type != OB_PKT) {
24479 				/*
24480 				 * Update the packet count and MIB stats
24481 				 * of trailing RTF_MULTIRT ires.
24482 				 */
24483 				UPDATE_OB_PKT_COUNT(ire);
24484 				BUMP_MIB(out_ill->ill_ip_mib,
24485 				    ipIfStatsOutFragReqds);
24486 			}
24487 		}
24488 
24489 		if (multirt_send) {
24490 			/*
24491 			 * We are in a multiple send case; look for
24492 			 * the next ire and re-enter the loop.
24493 			 */
24494 			ASSERT(ire1);
24495 			ASSERT(next_mp);
24496 			/* REFRELE the current ire before looping */
24497 			ire_refrele(ire);
24498 			ire = ire1;
24499 			ire1 = NULL;
24500 			mp = next_mp;
24501 			next_mp = NULL;
24502 		}
24503 	} while (multirt_send);
24504 
24505 	ASSERT(ire1 == NULL);
24506 
24507 	/* Restore the original ire; we need it for the trailing frags */
24508 	if (save_ire != NULL) {
24509 		/* REFRELE the last iterated ire */
24510 		ire_refrele(ire);
24511 		/* save_ire has been REFHOLDed */
24512 		ire = save_ire;
24513 		save_ire = NULL;
24514 		q = ire->ire_stq;
24515 	}
24516 
24517 	if (pkt_type == OB_PKT) {
24518 		UPDATE_OB_PKT_COUNT(ire);
24519 	} else {
24520 		out_ill = (ill_t *)q->q_ptr;
24521 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24522 		UPDATE_IB_PKT_COUNT(ire);
24523 	}
24524 
24525 	/* Advance the offset to the second frag starting point. */
24526 	offset += len;
24527 	/*
24528 	 * Update hdr_len from the copied header - there might be less options
24529 	 * in the later fragments.
24530 	 */
24531 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24532 	/* Loop until done. */
24533 	for (;;) {
24534 		uint16_t	offset_and_flags;
24535 		uint16_t	ip_len;
24536 
24537 		if (ip_data_end - offset > len) {
24538 			/*
24539 			 * Carve off the appropriate amount from the original
24540 			 * datagram.
24541 			 */
24542 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24543 				mp = NULL;
24544 				break;
24545 			}
24546 			/*
24547 			 * More frags after this one.  Get another copy
24548 			 * of the header.
24549 			 */
24550 			if (carve_mp->b_datap->db_ref == 1 &&
24551 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24552 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24553 				/* Inline IP header */
24554 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24555 				    hdr_mp->b_rptr;
24556 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24557 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24558 				mp = carve_mp;
24559 			} else {
24560 				if (!(mp = copyb(hdr_mp))) {
24561 					freemsg(carve_mp);
24562 					break;
24563 				}
24564 				/* Get priority marking, if any. */
24565 				mp->b_band = carve_mp->b_band;
24566 				mp->b_cont = carve_mp;
24567 			}
24568 			ipha = (ipha_t *)mp->b_rptr;
24569 			offset_and_flags = IPH_MF;
24570 		} else {
24571 			/*
24572 			 * Last frag.  Consume the header. Set len to
24573 			 * the length of this last piece.
24574 			 */
24575 			len = ip_data_end - offset;
24576 
24577 			/*
24578 			 * Carve off the appropriate amount from the original
24579 			 * datagram.
24580 			 */
24581 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24582 				mp = NULL;
24583 				break;
24584 			}
24585 			if (carve_mp->b_datap->db_ref == 1 &&
24586 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24587 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24588 				/* Inline IP header */
24589 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24590 				    hdr_mp->b_rptr;
24591 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24592 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24593 				mp = carve_mp;
24594 				freeb(hdr_mp);
24595 				hdr_mp = mp;
24596 			} else {
24597 				mp = hdr_mp;
24598 				/* Get priority marking, if any. */
24599 				mp->b_band = carve_mp->b_band;
24600 				mp->b_cont = carve_mp;
24601 			}
24602 			ipha = (ipha_t *)mp->b_rptr;
24603 			/* A frag of a frag might have IPH_MF non-zero */
24604 			offset_and_flags =
24605 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24606 			    IPH_MF;
24607 		}
24608 		offset_and_flags |= (uint16_t)(offset >> 3);
24609 		offset_and_flags |= (uint16_t)frag_flag;
24610 		/* Store the offset and flags in the IP header. */
24611 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24612 
24613 		/* Store the length in the IP header. */
24614 		ip_len = (uint16_t)(len + hdr_len);
24615 		ipha->ipha_length = htons(ip_len);
24616 
24617 		/*
24618 		 * Set the IP header checksum.	Note that mp is just
24619 		 * the header, so this is easy to pass to ip_csum.
24620 		 */
24621 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24622 
24623 		/* Attach a transmit header, if any, and ship it. */
24624 		if (pkt_type == OB_PKT) {
24625 			UPDATE_OB_PKT_COUNT(ire);
24626 		} else {
24627 			out_ill = (ill_t *)q->q_ptr;
24628 			BUMP_MIB(out_ill->ill_ip_mib,
24629 			    ipIfStatsHCOutForwDatagrams);
24630 			UPDATE_IB_PKT_COUNT(ire);
24631 		}
24632 
24633 		if (ire->ire_flags & RTF_MULTIRT) {
24634 			irb = ire->ire_bucket;
24635 			ASSERT(irb != NULL);
24636 
24637 			multirt_send = B_TRUE;
24638 
24639 			/*
24640 			 * Save the original ire; we will need to restore it
24641 			 * for the tailing frags.
24642 			 */
24643 			save_ire = ire;
24644 			IRE_REFHOLD(save_ire);
24645 		}
24646 		/*
24647 		 * Emission loop for this fragment, similar
24648 		 * to what is done for the first fragment.
24649 		 */
24650 		do {
24651 			if (multirt_send) {
24652 				/*
24653 				 * We are in a multiple send case, need to get
24654 				 * the next ire and make a copy of the packet.
24655 				 */
24656 				ASSERT(irb != NULL);
24657 				IRB_REFHOLD(irb);
24658 				for (ire1 = ire->ire_next;
24659 				    ire1 != NULL;
24660 				    ire1 = ire1->ire_next) {
24661 					if (!(ire1->ire_flags & RTF_MULTIRT))
24662 						continue;
24663 					if (ire1->ire_addr != ire->ire_addr)
24664 						continue;
24665 					if (ire1->ire_marks &
24666 					    (IRE_MARK_CONDEMNED|
24667 						IRE_MARK_HIDDEN))
24668 						continue;
24669 					/*
24670 					 * Ensure we do not exceed the MTU
24671 					 * of the next route.
24672 					 */
24673 					if (ire1->ire_max_frag < max_frag) {
24674 						ip_multirt_bad_mtu(ire1,
24675 						    max_frag);
24676 						continue;
24677 					}
24678 
24679 					/* Got one. */
24680 					IRE_REFHOLD(ire1);
24681 					break;
24682 				}
24683 				IRB_REFRELE(irb);
24684 
24685 				if (ire1 != NULL) {
24686 					next_mp = copyb(mp);
24687 					if ((next_mp == NULL) ||
24688 					    ((mp->b_cont != NULL) &&
24689 					    ((next_mp->b_cont =
24690 					    dupmsg(mp->b_cont)) == NULL))) {
24691 						freemsg(next_mp);
24692 						next_mp = NULL;
24693 						ire_refrele(ire1);
24694 						ire1 = NULL;
24695 					}
24696 				}
24697 
24698 				/* Last multiroute ire; don't loop anymore. */
24699 				if (ire1 == NULL) {
24700 					multirt_send = B_FALSE;
24701 				}
24702 			}
24703 
24704 			/* Update transmit header */
24705 			ll_hdr_len = 0;
24706 			LOCK_IRE_FP_MP(ire);
24707 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24708 			if (ll_hdr_mp != NULL) {
24709 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24710 				ll_hdr_len = MBLKL(ll_hdr_mp);
24711 			} else {
24712 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24713 			}
24714 
24715 			if (!ll_hdr_mp) {
24716 				xmit_mp = mp;
24717 
24718 			/*
24719 			 * We have link-layer header that can fit in
24720 			 * our mblk.
24721 			 */
24722 			} else if (mp->b_datap->db_ref == 1 &&
24723 			    ll_hdr_len != 0 &&
24724 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24725 				/* M_DATA fastpath */
24726 				mp->b_rptr -= ll_hdr_len;
24727 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24728 				    ll_hdr_len);
24729 				xmit_mp = mp;
24730 
24731 			/*
24732 			 * Case of res_mp OR the fastpath mp can't fit
24733 			 * in the mblk
24734 			 */
24735 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24736 				xmit_mp->b_cont = mp;
24737 				if (DB_CRED(mp) != NULL)
24738 					mblk_setcred(xmit_mp, DB_CRED(mp));
24739 				/* Get priority marking, if any. */
24740 				if (DB_TYPE(xmit_mp) == M_DATA)
24741 					xmit_mp->b_band = mp->b_band;
24742 
24743 			/* Corner case if copyb failed */
24744 			} else {
24745 				/*
24746 				 * Exit both the replication and
24747 				 * fragmentation loops.
24748 				 */
24749 				UNLOCK_IRE_FP_MP(ire);
24750 				goto drop_pkt;
24751 			}
24752 			UNLOCK_IRE_FP_MP(ire);
24753 
24754 			mp1 = mp;
24755 			out_ill = (ill_t *)q->q_ptr;
24756 
24757 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24758 
24759 			DTRACE_PROBE4(ip4__physical__out__start,
24760 			    ill_t *, NULL, ill_t *, out_ill,
24761 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24762 
24763 			FW_HOOKS(ip4_physical_out_event,
24764 			    ipv4firewall_physical_out,
24765 			    NULL, out_ill, ipha, xmit_mp, mp);
24766 
24767 			DTRACE_PROBE1(ip4__physical__out__end,
24768 			    mblk_t *, xmit_mp);
24769 
24770 			if (mp != mp1 && hdr_mp == mp1)
24771 				hdr_mp = mp;
24772 			if (mp != mp1 && mp_orig == mp1)
24773 				mp_orig = mp;
24774 
24775 			if (xmit_mp != NULL) {
24776 				putnext(q, xmit_mp);
24777 
24778 				BUMP_MIB(out_ill->ill_ip_mib,
24779 				    ipIfStatsHCOutTransmits);
24780 				UPDATE_MIB(out_ill->ill_ip_mib,
24781 				    ipIfStatsHCOutOctets, ip_len);
24782 
24783 				if (pkt_type != OB_PKT) {
24784 					/*
24785 					 * Update the packet count of trailing
24786 					 * RTF_MULTIRT ires.
24787 					 */
24788 					UPDATE_OB_PKT_COUNT(ire);
24789 				}
24790 			}
24791 
24792 			/* All done if we just consumed the hdr_mp. */
24793 			if (mp == hdr_mp) {
24794 				last_frag = B_TRUE;
24795 				BUMP_MIB(out_ill->ill_ip_mib,
24796 				    ipIfStatsOutFragOKs);
24797 			}
24798 
24799 			if (multirt_send) {
24800 				/*
24801 				 * We are in a multiple send case; look for
24802 				 * the next ire and re-enter the loop.
24803 				 */
24804 				ASSERT(ire1);
24805 				ASSERT(next_mp);
24806 				/* REFRELE the current ire before looping */
24807 				ire_refrele(ire);
24808 				ire = ire1;
24809 				ire1 = NULL;
24810 				q = ire->ire_stq;
24811 				mp = next_mp;
24812 				next_mp = NULL;
24813 			}
24814 		} while (multirt_send);
24815 		/*
24816 		 * Restore the original ire; we need it for the
24817 		 * trailing frags
24818 		 */
24819 		if (save_ire != NULL) {
24820 			ASSERT(ire1 == NULL);
24821 			/* REFRELE the last iterated ire */
24822 			ire_refrele(ire);
24823 			/* save_ire has been REFHOLDed */
24824 			ire = save_ire;
24825 			q = ire->ire_stq;
24826 			save_ire = NULL;
24827 		}
24828 
24829 		if (last_frag) {
24830 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24831 			    "ip_wput_frag_end:(%S)",
24832 			    "consumed hdr_mp");
24833 
24834 			if (first_ire != NULL)
24835 				ire_refrele(first_ire);
24836 			return;
24837 		}
24838 		/* Otherwise, advance and loop. */
24839 		offset += len;
24840 	}
24841 
24842 drop_pkt:
24843 	/* Clean up following allocation failure. */
24844 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24845 	freemsg(mp);
24846 	if (mp != hdr_mp)
24847 		freeb(hdr_mp);
24848 	if (mp != mp_orig)
24849 		freemsg(mp_orig);
24850 
24851 	if (save_ire != NULL)
24852 		IRE_REFRELE(save_ire);
24853 	if (first_ire != NULL)
24854 		ire_refrele(first_ire);
24855 
24856 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24857 	    "ip_wput_frag_end:(%S)",
24858 	    "end--alloc failure");
24859 }
24860 
24861 /*
24862  * Copy the header plus those options which have the copy bit set
24863  */
24864 static mblk_t *
24865 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset)
24866 {
24867 	mblk_t	*mp;
24868 	uchar_t	*up;
24869 
24870 	/*
24871 	 * Quick check if we need to look for options without the copy bit
24872 	 * set
24873 	 */
24874 	mp = allocb(ip_wroff_extra + hdr_len, BPRI_HI);
24875 	if (!mp)
24876 		return (mp);
24877 	mp->b_rptr += ip_wroff_extra;
24878 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24879 		bcopy(rptr, mp->b_rptr, hdr_len);
24880 		mp->b_wptr += hdr_len + ip_wroff_extra;
24881 		return (mp);
24882 	}
24883 	up  = mp->b_rptr;
24884 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24885 	up += IP_SIMPLE_HDR_LENGTH;
24886 	rptr += IP_SIMPLE_HDR_LENGTH;
24887 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24888 	while (hdr_len > 0) {
24889 		uint32_t optval;
24890 		uint32_t optlen;
24891 
24892 		optval = *rptr;
24893 		if (optval == IPOPT_EOL)
24894 			break;
24895 		if (optval == IPOPT_NOP)
24896 			optlen = 1;
24897 		else
24898 			optlen = rptr[1];
24899 		if (optval & IPOPT_COPY) {
24900 			bcopy(rptr, up, optlen);
24901 			up += optlen;
24902 		}
24903 		rptr += optlen;
24904 		hdr_len -= optlen;
24905 	}
24906 	/*
24907 	 * Make sure that we drop an even number of words by filling
24908 	 * with EOL to the next word boundary.
24909 	 */
24910 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24911 	    hdr_len & 0x3; hdr_len++)
24912 		*up++ = IPOPT_EOL;
24913 	mp->b_wptr = up;
24914 	/* Update header length */
24915 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24916 	return (mp);
24917 }
24918 
24919 /*
24920  * Delivery to local recipients including fanout to multiple recipients.
24921  * Does not do checksumming of UDP/TCP.
24922  * Note: q should be the read side queue for either the ill or conn.
24923  * Note: rq should be the read side q for the lower (ill) stream.
24924  * We don't send packets to IPPF processing, thus the last argument
24925  * to all the fanout calls are B_FALSE.
24926  */
24927 void
24928 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24929     int fanout_flags, zoneid_t zoneid)
24930 {
24931 	uint32_t	protocol;
24932 	mblk_t		*first_mp;
24933 	boolean_t	mctl_present;
24934 	int		ire_type;
24935 #define	rptr	((uchar_t *)ipha)
24936 
24937 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24938 	    "ip_wput_local_start: q %p", q);
24939 
24940 	if (ire != NULL) {
24941 		ire_type = ire->ire_type;
24942 	} else {
24943 		/*
24944 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24945 		 * packet is not multicast, we can't tell the ire type.
24946 		 */
24947 		ASSERT(CLASSD(ipha->ipha_dst));
24948 		ire_type = IRE_BROADCAST;
24949 	}
24950 
24951 	first_mp = mp;
24952 	if (first_mp->b_datap->db_type == M_CTL) {
24953 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24954 		if (!io->ipsec_out_secure) {
24955 			/*
24956 			 * This ipsec_out_t was allocated in ip_wput
24957 			 * for multicast packets to store the ill_index.
24958 			 * As this is being delivered locally, we don't
24959 			 * need this anymore.
24960 			 */
24961 			mp = first_mp->b_cont;
24962 			freeb(first_mp);
24963 			first_mp = mp;
24964 			mctl_present = B_FALSE;
24965 		} else {
24966 			/*
24967 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24968 			 * security properties for the looped-back packet.
24969 			 */
24970 			mctl_present = B_TRUE;
24971 			mp = first_mp->b_cont;
24972 			ASSERT(mp != NULL);
24973 			ipsec_out_to_in(first_mp);
24974 		}
24975 	} else {
24976 		mctl_present = B_FALSE;
24977 	}
24978 
24979 	DTRACE_PROBE4(ip4__loopback__in__start,
24980 	    ill_t *, ill, ill_t *, NULL,
24981 	    ipha_t *, ipha, mblk_t *, first_mp);
24982 
24983 	FW_HOOKS(ip4_loopback_in_event, ipv4firewall_loopback_in,
24984 	    ill, NULL, ipha, first_mp, mp);
24985 
24986 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24987 
24988 	if (first_mp == NULL)
24989 		return;
24990 
24991 	loopback_packets++;
24992 
24993 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24994 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24995 	if (!IS_SIMPLE_IPH(ipha)) {
24996 		ip_wput_local_options(ipha);
24997 	}
24998 
24999 	protocol = ipha->ipha_protocol;
25000 	switch (protocol) {
25001 	case IPPROTO_ICMP: {
25002 		ire_t		*ire_zone;
25003 		ilm_t		*ilm;
25004 		mblk_t		*mp1;
25005 		zoneid_t	last_zoneid;
25006 
25007 		if (CLASSD(ipha->ipha_dst) &&
25008 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
25009 			ASSERT(ire_type == IRE_BROADCAST);
25010 			/*
25011 			 * In the multicast case, applications may have joined
25012 			 * the group from different zones, so we need to deliver
25013 			 * the packet to each of them. Loop through the
25014 			 * multicast memberships structures (ilm) on the receive
25015 			 * ill and send a copy of the packet up each matching
25016 			 * one. However, we don't do this for multicasts sent on
25017 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25018 			 * they must stay in the sender's zone.
25019 			 *
25020 			 * ilm_add_v6() ensures that ilms in the same zone are
25021 			 * contiguous in the ill_ilm list. We use this property
25022 			 * to avoid sending duplicates needed when two
25023 			 * applications in the same zone join the same group on
25024 			 * different logical interfaces: we ignore the ilm if
25025 			 * it's zoneid is the same as the last matching one.
25026 			 * In addition, the sending of the packet for
25027 			 * ire_zoneid is delayed until all of the other ilms
25028 			 * have been exhausted.
25029 			 */
25030 			last_zoneid = -1;
25031 			ILM_WALKER_HOLD(ill);
25032 			for (ilm = ill->ill_ilm; ilm != NULL;
25033 			    ilm = ilm->ilm_next) {
25034 				if ((ilm->ilm_flags & ILM_DELETED) ||
25035 				    ipha->ipha_dst != ilm->ilm_addr ||
25036 				    ilm->ilm_zoneid == last_zoneid ||
25037 				    ilm->ilm_zoneid == zoneid ||
25038 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25039 					continue;
25040 				mp1 = ip_copymsg(first_mp);
25041 				if (mp1 == NULL)
25042 					continue;
25043 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25044 				    mctl_present, B_FALSE, ill,
25045 				    ilm->ilm_zoneid);
25046 				last_zoneid = ilm->ilm_zoneid;
25047 			}
25048 			ILM_WALKER_RELE(ill);
25049 			/*
25050 			 * Loopback case: the sending endpoint has
25051 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25052 			 * dispatch the multicast packet to the sending zone.
25053 			 */
25054 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25055 				freemsg(first_mp);
25056 				return;
25057 			}
25058 		} else if (ire_type == IRE_BROADCAST) {
25059 			/*
25060 			 * In the broadcast case, there may be many zones
25061 			 * which need a copy of the packet delivered to them.
25062 			 * There is one IRE_BROADCAST per broadcast address
25063 			 * and per zone; we walk those using a helper function.
25064 			 * In addition, the sending of the packet for zoneid is
25065 			 * delayed until all of the other ires have been
25066 			 * processed.
25067 			 */
25068 			IRB_REFHOLD(ire->ire_bucket);
25069 			ire_zone = NULL;
25070 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25071 			    ire)) != NULL) {
25072 				mp1 = ip_copymsg(first_mp);
25073 				if (mp1 == NULL)
25074 					continue;
25075 
25076 				UPDATE_IB_PKT_COUNT(ire_zone);
25077 				ire_zone->ire_last_used_time = lbolt;
25078 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25079 				    mctl_present, B_FALSE, ill,
25080 				    ire_zone->ire_zoneid);
25081 			}
25082 			IRB_REFRELE(ire->ire_bucket);
25083 		}
25084 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25085 		    0, mctl_present, B_FALSE, ill, zoneid);
25086 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25087 		    "ip_wput_local_end: q %p (%S)",
25088 		    q, "icmp");
25089 		return;
25090 	}
25091 	case IPPROTO_IGMP:
25092 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25093 			/* Bad packet - discarded by igmp_input */
25094 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25095 			    "ip_wput_local_end: q %p (%S)",
25096 			    q, "igmp_input--bad packet");
25097 			if (mctl_present)
25098 				freeb(first_mp);
25099 			return;
25100 		}
25101 		/*
25102 		 * igmp_input() may have returned the pulled up message.
25103 		 * So first_mp and ipha need to be reinitialized.
25104 		 */
25105 		ipha = (ipha_t *)mp->b_rptr;
25106 		if (mctl_present)
25107 			first_mp->b_cont = mp;
25108 		else
25109 			first_mp = mp;
25110 		/* deliver to local raw users */
25111 		break;
25112 	case IPPROTO_ENCAP:
25113 		/*
25114 		 * This case is covered by either ip_fanout_proto, or by
25115 		 * the above security processing for self-tunneled packets.
25116 		 */
25117 		break;
25118 	case IPPROTO_UDP: {
25119 		uint16_t	*up;
25120 		uint32_t	ports;
25121 
25122 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25123 		    UDP_PORTS_OFFSET);
25124 		/* Force a 'valid' checksum. */
25125 		up[3] = 0;
25126 
25127 		ports = *(uint32_t *)up;
25128 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25129 		    (ire_type == IRE_BROADCAST),
25130 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25131 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25132 		    ill, zoneid);
25133 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25134 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25135 		return;
25136 	}
25137 	case IPPROTO_TCP: {
25138 
25139 		/*
25140 		 * For TCP, discard broadcast packets.
25141 		 */
25142 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25143 			freemsg(first_mp);
25144 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25145 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25146 			return;
25147 		}
25148 
25149 		if (mp->b_datap->db_type == M_DATA) {
25150 			/*
25151 			 * M_DATA mblk, so init mblk (chain) for no struio().
25152 			 */
25153 			mblk_t	*mp1 = mp;
25154 
25155 			do
25156 				mp1->b_datap->db_struioflag = 0;
25157 			while ((mp1 = mp1->b_cont) != NULL);
25158 		}
25159 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25160 		    <= mp->b_wptr);
25161 		ip_fanout_tcp(q, first_mp, ill, ipha,
25162 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25163 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25164 		    mctl_present, B_FALSE, zoneid);
25165 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25166 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25167 		return;
25168 	}
25169 	case IPPROTO_SCTP:
25170 	{
25171 		uint32_t	ports;
25172 
25173 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25174 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25175 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25176 		    IP_FF_IPINFO,
25177 		    mctl_present, B_FALSE, 0, zoneid);
25178 		return;
25179 	}
25180 
25181 	default:
25182 		break;
25183 	}
25184 	/*
25185 	 * Find a client for some other protocol.  We give
25186 	 * copies to multiple clients, if more than one is
25187 	 * bound.
25188 	 */
25189 	ip_fanout_proto(q, first_mp, ill, ipha,
25190 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25191 	    mctl_present, B_FALSE, ill, zoneid);
25192 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25193 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25194 #undef	rptr
25195 }
25196 
25197 /*
25198  * Update any source route, record route, or timestamp options.
25199  * Check that we are at end of strict source route.
25200  * The options have been sanity checked by ip_wput_options().
25201  */
25202 static void
25203 ip_wput_local_options(ipha_t *ipha)
25204 {
25205 	ipoptp_t	opts;
25206 	uchar_t		*opt;
25207 	uint8_t		optval;
25208 	uint8_t		optlen;
25209 	ipaddr_t	dst;
25210 	uint32_t	ts;
25211 	ire_t		*ire;
25212 	timestruc_t	now;
25213 
25214 	ip2dbg(("ip_wput_local_options\n"));
25215 	for (optval = ipoptp_first(&opts, ipha);
25216 	    optval != IPOPT_EOL;
25217 	    optval = ipoptp_next(&opts)) {
25218 		opt = opts.ipoptp_cur;
25219 		optlen = opts.ipoptp_len;
25220 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25221 		switch (optval) {
25222 			uint32_t off;
25223 		case IPOPT_SSRR:
25224 		case IPOPT_LSRR:
25225 			off = opt[IPOPT_OFFSET];
25226 			off--;
25227 			if (optlen < IP_ADDR_LEN ||
25228 			    off > optlen - IP_ADDR_LEN) {
25229 				/* End of source route */
25230 				break;
25231 			}
25232 			/*
25233 			 * This will only happen if two consecutive entries
25234 			 * in the source route contains our address or if
25235 			 * it is a packet with a loose source route which
25236 			 * reaches us before consuming the whole source route
25237 			 */
25238 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25239 			if (optval == IPOPT_SSRR) {
25240 				return;
25241 			}
25242 			/*
25243 			 * Hack: instead of dropping the packet truncate the
25244 			 * source route to what has been used by filling the
25245 			 * rest with IPOPT_NOP.
25246 			 */
25247 			opt[IPOPT_OLEN] = (uint8_t)off;
25248 			while (off < optlen) {
25249 				opt[off++] = IPOPT_NOP;
25250 			}
25251 			break;
25252 		case IPOPT_RR:
25253 			off = opt[IPOPT_OFFSET];
25254 			off--;
25255 			if (optlen < IP_ADDR_LEN ||
25256 			    off > optlen - IP_ADDR_LEN) {
25257 				/* No more room - ignore */
25258 				ip1dbg((
25259 				    "ip_wput_forward_options: end of RR\n"));
25260 				break;
25261 			}
25262 			dst = htonl(INADDR_LOOPBACK);
25263 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25264 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25265 			break;
25266 		case IPOPT_TS:
25267 			/* Insert timestamp if there is romm */
25268 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25269 			case IPOPT_TS_TSONLY:
25270 				off = IPOPT_TS_TIMELEN;
25271 				break;
25272 			case IPOPT_TS_PRESPEC:
25273 			case IPOPT_TS_PRESPEC_RFC791:
25274 				/* Verify that the address matched */
25275 				off = opt[IPOPT_OFFSET] - 1;
25276 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25277 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25278 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
25279 				if (ire == NULL) {
25280 					/* Not for us */
25281 					break;
25282 				}
25283 				ire_refrele(ire);
25284 				/* FALLTHRU */
25285 			case IPOPT_TS_TSANDADDR:
25286 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25287 				break;
25288 			default:
25289 				/*
25290 				 * ip_*put_options should have already
25291 				 * dropped this packet.
25292 				 */
25293 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25294 				    "unknown IT - bug in ip_wput_options?\n");
25295 				return;	/* Keep "lint" happy */
25296 			}
25297 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25298 				/* Increase overflow counter */
25299 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25300 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25301 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25302 				    (off << 4);
25303 				break;
25304 			}
25305 			off = opt[IPOPT_OFFSET] - 1;
25306 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25307 			case IPOPT_TS_PRESPEC:
25308 			case IPOPT_TS_PRESPEC_RFC791:
25309 			case IPOPT_TS_TSANDADDR:
25310 				dst = htonl(INADDR_LOOPBACK);
25311 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25312 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25313 				/* FALLTHRU */
25314 			case IPOPT_TS_TSONLY:
25315 				off = opt[IPOPT_OFFSET] - 1;
25316 				/* Compute # of milliseconds since midnight */
25317 				gethrestime(&now);
25318 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25319 				    now.tv_nsec / (NANOSEC / MILLISEC);
25320 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25321 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25322 				break;
25323 			}
25324 			break;
25325 		}
25326 	}
25327 }
25328 
25329 /*
25330  * Send out a multicast packet on interface ipif.
25331  * The sender does not have an conn.
25332  * Caller verifies that this isn't a PHYI_LOOPBACK.
25333  */
25334 void
25335 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25336 {
25337 	ipha_t	*ipha;
25338 	ire_t	*ire;
25339 	ipaddr_t	dst;
25340 	mblk_t		*first_mp;
25341 
25342 	/* igmp_sendpkt always allocates a ipsec_out_t */
25343 	ASSERT(mp->b_datap->db_type == M_CTL);
25344 	ASSERT(!ipif->ipif_isv6);
25345 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25346 
25347 	first_mp = mp;
25348 	mp = first_mp->b_cont;
25349 	ASSERT(mp->b_datap->db_type == M_DATA);
25350 	ipha = (ipha_t *)mp->b_rptr;
25351 
25352 	/*
25353 	 * Find an IRE which matches the destination and the outgoing
25354 	 * queue (i.e. the outgoing interface.)
25355 	 */
25356 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25357 		dst = ipif->ipif_pp_dst_addr;
25358 	else
25359 		dst = ipha->ipha_dst;
25360 	/*
25361 	 * The source address has already been initialized by the
25362 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25363 	 * be sufficient rather than MATCH_IRE_IPIF.
25364 	 *
25365 	 * This function is used for sending IGMP packets. We need
25366 	 * to make sure that we send the packet out of the interface
25367 	 * (ipif->ipif_ill) where we joined the group. This is to
25368 	 * prevent from switches doing IGMP snooping to send us multicast
25369 	 * packets for a given group on the interface we have joined.
25370 	 * If we can't find an ire, igmp_sendpkt has already initialized
25371 	 * ipsec_out_attach_if so that this will not be load spread in
25372 	 * ip_newroute_ipif.
25373 	 */
25374 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25375 	    MATCH_IRE_ILL);
25376 	if (!ire) {
25377 		/*
25378 		 * Mark this packet to make it be delivered to
25379 		 * ip_wput_ire after the new ire has been
25380 		 * created.
25381 		 */
25382 		mp->b_prev = NULL;
25383 		mp->b_next = NULL;
25384 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25385 		    zoneid, &zero_info);
25386 		return;
25387 	}
25388 
25389 	/*
25390 	 * Honor the RTF_SETSRC flag; this is the only case
25391 	 * where we force this addr whatever the current src addr is,
25392 	 * because this address is set by igmp_sendpkt(), and
25393 	 * cannot be specified by any user.
25394 	 */
25395 	if (ire->ire_flags & RTF_SETSRC) {
25396 		ipha->ipha_src = ire->ire_src_addr;
25397 	}
25398 
25399 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25400 }
25401 
25402 /*
25403  * NOTE : This function does not ire_refrele the ire argument passed in.
25404  *
25405  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25406  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25407  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25408  * the ire_lock to access the nce_fp_mp in this case.
25409  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25410  * prepending a fastpath message IPQoS processing must precede it, we also set
25411  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25412  * (IPQoS might have set the b_band for CoS marking).
25413  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25414  * must follow it so that IPQoS can mark the dl_priority field for CoS
25415  * marking, if needed.
25416  */
25417 static mblk_t *
25418 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25419 {
25420 	uint_t	hlen;
25421 	ipha_t *ipha;
25422 	mblk_t *mp1;
25423 	boolean_t qos_done = B_FALSE;
25424 	uchar_t	*ll_hdr;
25425 
25426 #define	rptr	((uchar_t *)ipha)
25427 
25428 	ipha = (ipha_t *)mp->b_rptr;
25429 	hlen = 0;
25430 	LOCK_IRE_FP_MP(ire);
25431 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25432 		ASSERT(DB_TYPE(mp1) == M_DATA);
25433 		/* Initiate IPPF processing */
25434 		if ((proc != 0) && IPP_ENABLED(proc)) {
25435 			UNLOCK_IRE_FP_MP(ire);
25436 			ip_process(proc, &mp, ill_index);
25437 			if (mp == NULL)
25438 				return (NULL);
25439 
25440 			ipha = (ipha_t *)mp->b_rptr;
25441 			LOCK_IRE_FP_MP(ire);
25442 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25443 				qos_done = B_TRUE;
25444 				goto no_fp_mp;
25445 			}
25446 			ASSERT(DB_TYPE(mp1) == M_DATA);
25447 		}
25448 		hlen = MBLKL(mp1);
25449 		/*
25450 		 * Check if we have enough room to prepend fastpath
25451 		 * header
25452 		 */
25453 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25454 			ll_hdr = rptr - hlen;
25455 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25456 			/*
25457 			 * Set the b_rptr to the start of the link layer
25458 			 * header
25459 			 */
25460 			mp->b_rptr = ll_hdr;
25461 			mp1 = mp;
25462 		} else {
25463 			mp1 = copyb(mp1);
25464 			if (mp1 == NULL)
25465 				goto unlock_err;
25466 			mp1->b_band = mp->b_band;
25467 			mp1->b_cont = mp;
25468 			/*
25469 			 * certain system generated traffic may not
25470 			 * have cred/label in ip header block. This
25471 			 * is true even for a labeled system. But for
25472 			 * labeled traffic, inherit the label in the
25473 			 * new header.
25474 			 */
25475 			if (DB_CRED(mp) != NULL)
25476 				mblk_setcred(mp1, DB_CRED(mp));
25477 			/*
25478 			 * XXX disable ICK_VALID and compute checksum
25479 			 * here; can happen if nce_fp_mp changes and
25480 			 * it can't be copied now due to insufficient
25481 			 * space. (unlikely, fp mp can change, but it
25482 			 * does not increase in length)
25483 			 */
25484 		}
25485 		UNLOCK_IRE_FP_MP(ire);
25486 	} else {
25487 no_fp_mp:
25488 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25489 		if (mp1 == NULL) {
25490 unlock_err:
25491 			UNLOCK_IRE_FP_MP(ire);
25492 			freemsg(mp);
25493 			return (NULL);
25494 		}
25495 		UNLOCK_IRE_FP_MP(ire);
25496 		mp1->b_cont = mp;
25497 		/*
25498 		 * certain system generated traffic may not
25499 		 * have cred/label in ip header block. This
25500 		 * is true even for a labeled system. But for
25501 		 * labeled traffic, inherit the label in the
25502 		 * new header.
25503 		 */
25504 		if (DB_CRED(mp) != NULL)
25505 			mblk_setcred(mp1, DB_CRED(mp));
25506 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc)) {
25507 			ip_process(proc, &mp1, ill_index);
25508 			if (mp1 == NULL)
25509 				return (NULL);
25510 		}
25511 	}
25512 	return (mp1);
25513 #undef rptr
25514 }
25515 
25516 /*
25517  * Finish the outbound IPsec processing for an IPv6 packet. This function
25518  * is called from ipsec_out_process() if the IPsec packet was processed
25519  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25520  * asynchronously.
25521  */
25522 void
25523 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25524     ire_t *ire_arg)
25525 {
25526 	in6_addr_t *v6dstp;
25527 	ire_t *ire;
25528 	mblk_t *mp;
25529 	ip6_t *ip6h1;
25530 	uint_t	ill_index;
25531 	ipsec_out_t *io;
25532 	boolean_t attach_if, hwaccel;
25533 	uint32_t flags = IP6_NO_IPPOLICY;
25534 	int match_flags;
25535 	zoneid_t zoneid;
25536 	boolean_t ill_need_rele = B_FALSE;
25537 	boolean_t ire_need_rele = B_FALSE;
25538 
25539 	mp = ipsec_mp->b_cont;
25540 	ip6h1 = (ip6_t *)mp->b_rptr;
25541 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25542 	ill_index = io->ipsec_out_ill_index;
25543 	if (io->ipsec_out_reachable) {
25544 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25545 	}
25546 	attach_if = io->ipsec_out_attach_if;
25547 	hwaccel = io->ipsec_out_accelerated;
25548 	zoneid = io->ipsec_out_zoneid;
25549 	ASSERT(zoneid != ALL_ZONES);
25550 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25551 	/* Multicast addresses should have non-zero ill_index. */
25552 	v6dstp = &ip6h->ip6_dst;
25553 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25554 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25555 	ASSERT(!attach_if || ill_index != 0);
25556 	if (ill_index != 0) {
25557 		if (ill == NULL) {
25558 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25559 			    B_TRUE);
25560 
25561 			/* Failure case frees things for us. */
25562 			if (ill == NULL)
25563 				return;
25564 
25565 			ill_need_rele = B_TRUE;
25566 		}
25567 		/*
25568 		 * If this packet needs to go out on a particular interface
25569 		 * honor it.
25570 		 */
25571 		if (attach_if) {
25572 			match_flags = MATCH_IRE_ILL;
25573 
25574 			/*
25575 			 * Check if we need an ire that will not be
25576 			 * looked up by anybody else i.e. HIDDEN.
25577 			 */
25578 			if (ill_is_probeonly(ill)) {
25579 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25580 			}
25581 		}
25582 	}
25583 	ASSERT(mp != NULL);
25584 
25585 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25586 		boolean_t unspec_src;
25587 		ipif_t	*ipif;
25588 
25589 		/*
25590 		 * Use the ill_index to get the right ill.
25591 		 */
25592 		unspec_src = io->ipsec_out_unspec_src;
25593 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25594 		if (ipif == NULL) {
25595 			if (ill_need_rele)
25596 				ill_refrele(ill);
25597 			freemsg(ipsec_mp);
25598 			return;
25599 		}
25600 
25601 		if (ire_arg != NULL) {
25602 			ire = ire_arg;
25603 		} else {
25604 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25605 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25606 			ire_need_rele = B_TRUE;
25607 		}
25608 		if (ire != NULL) {
25609 			ipif_refrele(ipif);
25610 			/*
25611 			 * XXX Do the multicast forwarding now, as the IPSEC
25612 			 * processing has been done.
25613 			 */
25614 			goto send;
25615 		}
25616 
25617 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25618 		mp->b_prev = NULL;
25619 		mp->b_next = NULL;
25620 
25621 		/*
25622 		 * If the IPsec packet was processed asynchronously,
25623 		 * drop it now.
25624 		 */
25625 		if (q == NULL) {
25626 			if (ill_need_rele)
25627 				ill_refrele(ill);
25628 			freemsg(ipsec_mp);
25629 			return;
25630 		}
25631 
25632 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25633 		    unspec_src, zoneid);
25634 		ipif_refrele(ipif);
25635 	} else {
25636 		if (attach_if) {
25637 			ipif_t	*ipif;
25638 
25639 			ipif = ipif_get_next_ipif(NULL, ill);
25640 			if (ipif == NULL) {
25641 				if (ill_need_rele)
25642 					ill_refrele(ill);
25643 				freemsg(ipsec_mp);
25644 				return;
25645 			}
25646 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25647 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25648 			ire_need_rele = B_TRUE;
25649 			ipif_refrele(ipif);
25650 		} else {
25651 			if (ire_arg != NULL) {
25652 				ire = ire_arg;
25653 			} else {
25654 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL);
25655 				ire_need_rele = B_TRUE;
25656 			}
25657 		}
25658 		if (ire != NULL)
25659 			goto send;
25660 		/*
25661 		 * ire disappeared underneath.
25662 		 *
25663 		 * What we need to do here is the ip_newroute
25664 		 * logic to get the ire without doing the IPSEC
25665 		 * processing. Follow the same old path. But this
25666 		 * time, ip_wput or ire_add_then_send will call us
25667 		 * directly as all the IPSEC operations are done.
25668 		 */
25669 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25670 		mp->b_prev = NULL;
25671 		mp->b_next = NULL;
25672 
25673 		/*
25674 		 * If the IPsec packet was processed asynchronously,
25675 		 * drop it now.
25676 		 */
25677 		if (q == NULL) {
25678 			if (ill_need_rele)
25679 				ill_refrele(ill);
25680 			freemsg(ipsec_mp);
25681 			return;
25682 		}
25683 
25684 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25685 		    zoneid);
25686 	}
25687 	if (ill != NULL && ill_need_rele)
25688 		ill_refrele(ill);
25689 	return;
25690 send:
25691 	if (ill != NULL && ill_need_rele)
25692 		ill_refrele(ill);
25693 
25694 	/* Local delivery */
25695 	if (ire->ire_stq == NULL) {
25696 		ill_t	*out_ill;
25697 		ASSERT(q != NULL);
25698 
25699 		/* PFHooks: LOOPBACK_OUT */
25700 		out_ill = ire->ire_ipif->ipif_ill;
25701 
25702 		DTRACE_PROBE4(ip6__loopback__out__start,
25703 		    ill_t *, NULL, ill_t *, out_ill,
25704 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25705 
25706 		FW_HOOKS6(ip6_loopback_out_event, ipv6firewall_loopback_out,
25707 		    NULL, out_ill, ip6h1, ipsec_mp, mp);
25708 
25709 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25710 
25711 		if (ipsec_mp != NULL)
25712 			ip_wput_local_v6(RD(q), out_ill,
25713 			    ip6h, ipsec_mp, ire, 0);
25714 		if (ire_need_rele)
25715 			ire_refrele(ire);
25716 		return;
25717 	}
25718 	/*
25719 	 * Everything is done. Send it out on the wire.
25720 	 * We force the insertion of a fragment header using the
25721 	 * IPH_FRAG_HDR flag in two cases:
25722 	 * - after reception of an ICMPv6 "packet too big" message
25723 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25724 	 * - for multirouted IPv6 packets, so that the receiver can
25725 	 *   discard duplicates according to their fragment identifier
25726 	 */
25727 	/* XXX fix flow control problems. */
25728 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25729 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25730 		if (hwaccel) {
25731 			/*
25732 			 * hardware acceleration does not handle these
25733 			 * "slow path" cases.
25734 			 */
25735 			/* IPsec KSTATS: should bump bean counter here. */
25736 			if (ire_need_rele)
25737 				ire_refrele(ire);
25738 			freemsg(ipsec_mp);
25739 			return;
25740 		}
25741 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25742 		    (mp->b_cont ? msgdsize(mp) :
25743 		    mp->b_wptr - (uchar_t *)ip6h)) {
25744 			/* IPsec KSTATS: should bump bean counter here. */
25745 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25746 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25747 			    msgdsize(mp)));
25748 			if (ire_need_rele)
25749 				ire_refrele(ire);
25750 			freemsg(ipsec_mp);
25751 			return;
25752 		}
25753 		ASSERT(mp->b_prev == NULL);
25754 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25755 		    ntohs(ip6h->ip6_plen) +
25756 		    IPV6_HDR_LEN, ire->ire_max_frag));
25757 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25758 		    ire->ire_max_frag);
25759 	} else {
25760 		UPDATE_OB_PKT_COUNT(ire);
25761 		ire->ire_last_used_time = lbolt;
25762 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25763 	}
25764 	if (ire_need_rele)
25765 		ire_refrele(ire);
25766 	freeb(ipsec_mp);
25767 }
25768 
25769 void
25770 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25771 {
25772 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25773 	da_ipsec_t *hada;	/* data attributes */
25774 	ill_t *ill = (ill_t *)q->q_ptr;
25775 
25776 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25777 
25778 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25779 		/* IPsec KSTATS: Bump lose counter here! */
25780 		freemsg(mp);
25781 		return;
25782 	}
25783 
25784 	/*
25785 	 * It's an IPsec packet that must be
25786 	 * accelerated by the Provider, and the
25787 	 * outbound ill is IPsec acceleration capable.
25788 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25789 	 * to the ill.
25790 	 * IPsec KSTATS: should bump packet counter here.
25791 	 */
25792 
25793 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25794 	if (hada_mp == NULL) {
25795 		/* IPsec KSTATS: should bump packet counter here. */
25796 		freemsg(mp);
25797 		return;
25798 	}
25799 
25800 	hada_mp->b_datap->db_type = M_CTL;
25801 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25802 	hada_mp->b_cont = mp;
25803 
25804 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25805 	bzero(hada, sizeof (da_ipsec_t));
25806 	hada->da_type = IPHADA_M_CTL;
25807 
25808 	putnext(q, hada_mp);
25809 }
25810 
25811 /*
25812  * Finish the outbound IPsec processing. This function is called from
25813  * ipsec_out_process() if the IPsec packet was processed
25814  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25815  * asynchronously.
25816  */
25817 void
25818 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25819     ire_t *ire_arg)
25820 {
25821 	uint32_t v_hlen_tos_len;
25822 	ipaddr_t	dst;
25823 	ipif_t	*ipif = NULL;
25824 	ire_t *ire;
25825 	ire_t *ire1 = NULL;
25826 	mblk_t *next_mp = NULL;
25827 	uint32_t max_frag;
25828 	boolean_t multirt_send = B_FALSE;
25829 	mblk_t *mp;
25830 	mblk_t *mp1;
25831 	ipha_t *ipha1;
25832 	uint_t	ill_index;
25833 	ipsec_out_t *io;
25834 	boolean_t attach_if;
25835 	int match_flags, offset;
25836 	irb_t *irb = NULL;
25837 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25838 	zoneid_t zoneid;
25839 	uint32_t cksum;
25840 	uint16_t *up;
25841 	ipxmit_state_t	pktxmit_state;
25842 #ifdef	_BIG_ENDIAN
25843 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25844 #else
25845 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25846 #endif
25847 
25848 	mp = ipsec_mp->b_cont;
25849 	ipha1 = (ipha_t *)mp->b_rptr;
25850 	ASSERT(mp != NULL);
25851 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25852 	dst = ipha->ipha_dst;
25853 
25854 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25855 	ill_index = io->ipsec_out_ill_index;
25856 	attach_if = io->ipsec_out_attach_if;
25857 	zoneid = io->ipsec_out_zoneid;
25858 	ASSERT(zoneid != ALL_ZONES);
25859 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25860 	if (ill_index != 0) {
25861 		if (ill == NULL) {
25862 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25863 			    ill_index, B_FALSE);
25864 
25865 			/* Failure case frees things for us. */
25866 			if (ill == NULL)
25867 				return;
25868 
25869 			ill_need_rele = B_TRUE;
25870 		}
25871 		/*
25872 		 * If this packet needs to go out on a particular interface
25873 		 * honor it.
25874 		 */
25875 		if (attach_if) {
25876 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25877 
25878 			/*
25879 			 * Check if we need an ire that will not be
25880 			 * looked up by anybody else i.e. HIDDEN.
25881 			 */
25882 			if (ill_is_probeonly(ill)) {
25883 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25884 			}
25885 		}
25886 	}
25887 
25888 	if (CLASSD(dst)) {
25889 		boolean_t conn_dontroute;
25890 		/*
25891 		 * Use the ill_index to get the right ipif.
25892 		 */
25893 		conn_dontroute = io->ipsec_out_dontroute;
25894 		if (ill_index == 0)
25895 			ipif = ipif_lookup_group(dst, zoneid);
25896 		else
25897 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25898 		if (ipif == NULL) {
25899 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25900 			    " multicast\n"));
25901 			BUMP_MIB(&ip_mib, ipIfStatsOutNoRoutes);
25902 			freemsg(ipsec_mp);
25903 			goto done;
25904 		}
25905 		/*
25906 		 * ipha_src has already been intialized with the
25907 		 * value of the ipif in ip_wput. All we need now is
25908 		 * an ire to send this downstream.
25909 		 */
25910 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25911 		    MBLK_GETLABEL(mp), match_flags);
25912 		if (ire != NULL) {
25913 			ill_t *ill1;
25914 			/*
25915 			 * Do the multicast forwarding now, as the IPSEC
25916 			 * processing has been done.
25917 			 */
25918 			if (ip_g_mrouter && !conn_dontroute &&
25919 			    (ill1 = ire_to_ill(ire))) {
25920 				if (ip_mforward(ill1, ipha, mp)) {
25921 					freemsg(ipsec_mp);
25922 					ip1dbg(("ip_wput_ipsec_out: mforward "
25923 					    "failed\n"));
25924 					ire_refrele(ire);
25925 					goto done;
25926 				}
25927 			}
25928 			goto send;
25929 		}
25930 
25931 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25932 		mp->b_prev = NULL;
25933 		mp->b_next = NULL;
25934 
25935 		/*
25936 		 * If the IPsec packet was processed asynchronously,
25937 		 * drop it now.
25938 		 */
25939 		if (q == NULL) {
25940 			freemsg(ipsec_mp);
25941 			goto done;
25942 		}
25943 
25944 		/*
25945 		 * We may be using a wrong ipif to create the ire.
25946 		 * But it is okay as the source address is assigned
25947 		 * for the packet already. Next outbound packet would
25948 		 * create the IRE with the right IPIF in ip_wput.
25949 		 *
25950 		 * Also handle RTF_MULTIRT routes.
25951 		 */
25952 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25953 		    zoneid, &zero_info);
25954 	} else {
25955 		if (attach_if) {
25956 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25957 			    zoneid, MBLK_GETLABEL(mp), match_flags);
25958 		} else {
25959 			if (ire_arg != NULL) {
25960 				ire = ire_arg;
25961 				ire_need_rele = B_FALSE;
25962 			} else {
25963 				ire = ire_cache_lookup(dst, zoneid,
25964 				    MBLK_GETLABEL(mp));
25965 			}
25966 		}
25967 		if (ire != NULL) {
25968 			goto send;
25969 		}
25970 
25971 		/*
25972 		 * ire disappeared underneath.
25973 		 *
25974 		 * What we need to do here is the ip_newroute
25975 		 * logic to get the ire without doing the IPSEC
25976 		 * processing. Follow the same old path. But this
25977 		 * time, ip_wput or ire_add_then_put will call us
25978 		 * directly as all the IPSEC operations are done.
25979 		 */
25980 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25981 		mp->b_prev = NULL;
25982 		mp->b_next = NULL;
25983 
25984 		/*
25985 		 * If the IPsec packet was processed asynchronously,
25986 		 * drop it now.
25987 		 */
25988 		if (q == NULL) {
25989 			freemsg(ipsec_mp);
25990 			goto done;
25991 		}
25992 
25993 		/*
25994 		 * Since we're going through ip_newroute() again, we
25995 		 * need to make sure we don't:
25996 		 *
25997 		 *	1.) Trigger the ASSERT() with the ipha_ident
25998 		 *	    overloading.
25999 		 *	2.) Redo transport-layer checksumming, since we've
26000 		 *	    already done all that to get this far.
26001 		 *
26002 		 * The easiest way not do either of the above is to set
26003 		 * the ipha_ident field to IP_HDR_INCLUDED.
26004 		 */
26005 		ipha->ipha_ident = IP_HDR_INCLUDED;
26006 		ip_newroute(q, ipsec_mp, dst, NULL,
26007 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid);
26008 	}
26009 	goto done;
26010 send:
26011 	if (ipha->ipha_protocol == IPPROTO_UDP && udp_compute_checksum()) {
26012 		/*
26013 		 * ESP NAT-Traversal packet.
26014 		 *
26015 		 * Just do software checksum for now.
26016 		 */
26017 
26018 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26019 		IP_STAT(ip_out_sw_cksum);
26020 		IP_STAT_UPDATE(ip_udp_out_sw_cksum_bytes,
26021 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26022 #define	iphs	((uint16_t *)ipha)
26023 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26024 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26025 		    IP_SIMPLE_HDR_LENGTH);
26026 #undef iphs
26027 		if ((cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum)) == 0)
26028 			cksum = 0xFFFF;
26029 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26030 			if (mp1->b_wptr - mp1->b_rptr >=
26031 			    offset + sizeof (uint16_t)) {
26032 				up = (uint16_t *)(mp1->b_rptr + offset);
26033 				*up = cksum;
26034 				break;	/* out of for loop */
26035 			} else {
26036 				offset -= (mp->b_wptr - mp->b_rptr);
26037 			}
26038 	} /* Otherwise, just keep the all-zero checksum. */
26039 
26040 	if (ire->ire_stq == NULL) {
26041 		ill_t	*out_ill;
26042 		/*
26043 		 * Loopbacks go through ip_wput_local except for one case.
26044 		 * We come here if we generate a icmp_frag_needed message
26045 		 * after IPSEC processing is over. When this function calls
26046 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26047 		 * icmp_frag_needed. The message generated comes back here
26048 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26049 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26050 		 * source address as it is usually set in ip_wput_ire. As
26051 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26052 		 * and we end up here. We can't enter ip_wput_ire once the
26053 		 * IPSEC processing is over and hence we need to do it here.
26054 		 */
26055 		ASSERT(q != NULL);
26056 		UPDATE_OB_PKT_COUNT(ire);
26057 		ire->ire_last_used_time = lbolt;
26058 		if (ipha->ipha_src == 0)
26059 			ipha->ipha_src = ire->ire_src_addr;
26060 
26061 		/* PFHooks: LOOPBACK_OUT */
26062 		out_ill = ire->ire_ipif->ipif_ill;
26063 
26064 		DTRACE_PROBE4(ip4__loopback__out__start,
26065 		    ill_t *, NULL, ill_t *, out_ill,
26066 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26067 
26068 		FW_HOOKS(ip4_loopback_out_event, ipv4firewall_loopback_out,
26069 		    NULL, out_ill, ipha1, ipsec_mp, mp);
26070 
26071 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26072 
26073 		if (ipsec_mp != NULL)
26074 			ip_wput_local(RD(q), out_ill,
26075 			    ipha, ipsec_mp, ire, 0, zoneid);
26076 		if (ire_need_rele)
26077 			ire_refrele(ire);
26078 		goto done;
26079 	}
26080 
26081 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26082 		/*
26083 		 * We are through with IPSEC processing.
26084 		 * Fragment this and send it on the wire.
26085 		 */
26086 		if (io->ipsec_out_accelerated) {
26087 			/*
26088 			 * The packet has been accelerated but must
26089 			 * be fragmented. This should not happen
26090 			 * since AH and ESP must not accelerate
26091 			 * packets that need fragmentation, however
26092 			 * the configuration could have changed
26093 			 * since the AH or ESP processing.
26094 			 * Drop packet.
26095 			 * IPsec KSTATS: bump bean counter here.
26096 			 */
26097 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26098 			    "fragmented accelerated packet!\n"));
26099 			freemsg(ipsec_mp);
26100 		} else {
26101 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid);
26102 		}
26103 		if (ire_need_rele)
26104 			ire_refrele(ire);
26105 		goto done;
26106 	}
26107 
26108 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26109 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26110 	    (void *)ire->ire_ipif, (void *)ipif));
26111 
26112 	/*
26113 	 * Multiroute the secured packet, unless IPsec really
26114 	 * requires the packet to go out only through a particular
26115 	 * interface.
26116 	 */
26117 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26118 		ire_t *first_ire;
26119 		irb = ire->ire_bucket;
26120 		ASSERT(irb != NULL);
26121 		/*
26122 		 * This ire has been looked up as the one that
26123 		 * goes through the given ipif;
26124 		 * make sure we do not omit any other multiroute ire
26125 		 * that may be present in the bucket before this one.
26126 		 */
26127 		IRB_REFHOLD(irb);
26128 		for (first_ire = irb->irb_ire;
26129 		    first_ire != NULL;
26130 		    first_ire = first_ire->ire_next) {
26131 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26132 			    (first_ire->ire_addr == ire->ire_addr) &&
26133 			    !(first_ire->ire_marks &
26134 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
26135 				break;
26136 		}
26137 
26138 		if ((first_ire != NULL) && (first_ire != ire)) {
26139 			/*
26140 			 * Don't change the ire if the packet must
26141 			 * be fragmented if sent via this new one.
26142 			 */
26143 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26144 				IRE_REFHOLD(first_ire);
26145 				if (ire_need_rele)
26146 					ire_refrele(ire);
26147 				else
26148 					ire_need_rele = B_TRUE;
26149 				ire = first_ire;
26150 			}
26151 		}
26152 		IRB_REFRELE(irb);
26153 
26154 		multirt_send = B_TRUE;
26155 		max_frag = ire->ire_max_frag;
26156 	} else {
26157 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26158 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26159 			    "flag, attach_if %d\n", attach_if));
26160 		}
26161 	}
26162 
26163 	/*
26164 	 * In most cases, the emission loop below is entered only once.
26165 	 * Only in the case where the ire holds the RTF_MULTIRT
26166 	 * flag, we loop to process all RTF_MULTIRT ires in the
26167 	 * bucket, and send the packet through all crossed
26168 	 * RTF_MULTIRT routes.
26169 	 */
26170 	do {
26171 		if (multirt_send) {
26172 			/*
26173 			 * ire1 holds here the next ire to process in the
26174 			 * bucket. If multirouting is expected,
26175 			 * any non-RTF_MULTIRT ire that has the
26176 			 * right destination address is ignored.
26177 			 */
26178 			ASSERT(irb != NULL);
26179 			IRB_REFHOLD(irb);
26180 			for (ire1 = ire->ire_next;
26181 			    ire1 != NULL;
26182 			    ire1 = ire1->ire_next) {
26183 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26184 					continue;
26185 				if (ire1->ire_addr != ire->ire_addr)
26186 					continue;
26187 				if (ire1->ire_marks &
26188 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26189 					continue;
26190 				/* No loopback here */
26191 				if (ire1->ire_stq == NULL)
26192 					continue;
26193 				/*
26194 				 * Ensure we do not exceed the MTU
26195 				 * of the next route.
26196 				 */
26197 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26198 					ip_multirt_bad_mtu(ire1, max_frag);
26199 					continue;
26200 				}
26201 
26202 				IRE_REFHOLD(ire1);
26203 				break;
26204 			}
26205 			IRB_REFRELE(irb);
26206 			if (ire1 != NULL) {
26207 				/*
26208 				 * We are in a multiple send case, need to
26209 				 * make a copy of the packet.
26210 				 */
26211 				next_mp = copymsg(ipsec_mp);
26212 				if (next_mp == NULL) {
26213 					ire_refrele(ire1);
26214 					ire1 = NULL;
26215 				}
26216 			}
26217 		}
26218 		/*
26219 		 * Everything is done. Send it out on the wire
26220 		 *
26221 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26222 		 * either send it on the wire or, in the case of
26223 		 * HW acceleration, call ipsec_hw_putnext.
26224 		 */
26225 		if (ire->ire_nce &&
26226 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26227 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26228 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26229 			/*
26230 			 * If ire's link-layer is unresolved (this
26231 			 * would only happen if the incomplete ire
26232 			 * was added to cachetable via forwarding path)
26233 			 * don't bother going to ip_xmit_v4. Just drop the
26234 			 * packet.
26235 			 * There is a slight risk here, in that, if we
26236 			 * have the forwarding path create an incomplete
26237 			 * IRE, then until the IRE is completed, any
26238 			 * transmitted IPSEC packets will be dropped
26239 			 * instead of being queued waiting for resolution.
26240 			 *
26241 			 * But the likelihood of a forwarding packet and a wput
26242 			 * packet sending to the same dst at the same time
26243 			 * and there not yet be an ARP entry for it is small.
26244 			 * Furthermore, if this actually happens, it might
26245 			 * be likely that wput would generate multiple
26246 			 * packets (and forwarding would also have a train
26247 			 * of packets) for that destination. If this is
26248 			 * the case, some of them would have been dropped
26249 			 * anyway, since ARP only queues a few packets while
26250 			 * waiting for resolution
26251 			 *
26252 			 * NOTE: We should really call ip_xmit_v4,
26253 			 * and let it queue the packet and send the
26254 			 * ARP query and have ARP come back thus:
26255 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26256 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26257 			 * hw accel work. But it's too complex to get
26258 			 * the IPsec hw  acceleration approach to fit
26259 			 * well with ip_xmit_v4 doing ARP without
26260 			 * doing IPSEC simplification. For now, we just
26261 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26262 			 * that we can continue with the send on the next
26263 			 * attempt.
26264 			 *
26265 			 * XXX THis should be revisited, when
26266 			 * the IPsec/IP interaction is cleaned up
26267 			 */
26268 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26269 			    " - dropping packet\n"));
26270 			freemsg(ipsec_mp);
26271 			/*
26272 			 * Call ip_xmit_v4() to trigger ARP query
26273 			 * in case the nce_state is ND_INITIAL
26274 			 */
26275 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26276 			goto drop_pkt;
26277 		}
26278 
26279 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26280 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26281 		    mblk_t *, mp);
26282 		FW_HOOKS(ip4_physical_out_event, ipv4firewall_physical_out,
26283 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp);
26284 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26285 		if (mp == NULL)
26286 			goto drop_pkt;
26287 
26288 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26289 		pktxmit_state = ip_xmit_v4(mp, ire,
26290 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26291 
26292 		if ((pktxmit_state ==  SEND_FAILED) ||
26293 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26294 
26295 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26296 drop_pkt:
26297 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26298 			    ipIfStatsOutDiscards);
26299 			if (ire_need_rele)
26300 				ire_refrele(ire);
26301 			if (ire1 != NULL) {
26302 				ire_refrele(ire1);
26303 				freemsg(next_mp);
26304 			}
26305 			goto done;
26306 		}
26307 
26308 		freeb(ipsec_mp);
26309 		if (ire_need_rele)
26310 			ire_refrele(ire);
26311 
26312 		if (ire1 != NULL) {
26313 			ire = ire1;
26314 			ire_need_rele = B_TRUE;
26315 			ASSERT(next_mp);
26316 			ipsec_mp = next_mp;
26317 			mp = ipsec_mp->b_cont;
26318 			ire1 = NULL;
26319 			next_mp = NULL;
26320 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26321 		} else {
26322 			multirt_send = B_FALSE;
26323 		}
26324 	} while (multirt_send);
26325 done:
26326 	if (ill != NULL && ill_need_rele)
26327 		ill_refrele(ill);
26328 	if (ipif != NULL)
26329 		ipif_refrele(ipif);
26330 }
26331 
26332 /*
26333  * Get the ill corresponding to the specified ire, and compare its
26334  * capabilities with the protocol and algorithms specified by the
26335  * the SA obtained from ipsec_out. If they match, annotate the
26336  * ipsec_out structure to indicate that the packet needs acceleration.
26337  *
26338  *
26339  * A packet is eligible for outbound hardware acceleration if the
26340  * following conditions are satisfied:
26341  *
26342  * 1. the packet will not be fragmented
26343  * 2. the provider supports the algorithm
26344  * 3. there is no pending control message being exchanged
26345  * 4. snoop is not attached
26346  * 5. the destination address is not a broadcast or multicast address.
26347  *
26348  * Rationale:
26349  *	- Hardware drivers do not support fragmentation with
26350  *	  the current interface.
26351  *	- snoop, multicast, and broadcast may result in exposure of
26352  *	  a cleartext datagram.
26353  * We check all five of these conditions here.
26354  *
26355  * XXX would like to nuke "ire_t *" parameter here; problem is that
26356  * IRE is only way to figure out if a v4 address is a broadcast and
26357  * thus ineligible for acceleration...
26358  */
26359 static void
26360 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26361 {
26362 	ipsec_out_t *io;
26363 	mblk_t *data_mp;
26364 	uint_t plen, overhead;
26365 
26366 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26367 		return;
26368 
26369 	if (ill == NULL)
26370 		return;
26371 
26372 	/*
26373 	 * Destination address is a broadcast or multicast.  Punt.
26374 	 */
26375 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26376 	    IRE_LOCAL)))
26377 		return;
26378 
26379 	data_mp = ipsec_mp->b_cont;
26380 
26381 	if (ill->ill_isv6) {
26382 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26383 
26384 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26385 			return;
26386 
26387 		plen = ip6h->ip6_plen;
26388 	} else {
26389 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26390 
26391 		if (CLASSD(ipha->ipha_dst))
26392 			return;
26393 
26394 		plen = ipha->ipha_length;
26395 	}
26396 	/*
26397 	 * Is there a pending DLPI control message being exchanged
26398 	 * between IP/IPsec and the DLS Provider? If there is, it
26399 	 * could be a SADB update, and the state of the DLS Provider
26400 	 * SADB might not be in sync with the SADB maintained by
26401 	 * IPsec. To avoid dropping packets or using the wrong keying
26402 	 * material, we do not accelerate this packet.
26403 	 */
26404 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26405 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26406 		    "ill_dlpi_pending! don't accelerate packet\n"));
26407 		return;
26408 	}
26409 
26410 	/*
26411 	 * Is the Provider in promiscous mode? If it does, we don't
26412 	 * accelerate the packet since it will bounce back up to the
26413 	 * listeners in the clear.
26414 	 */
26415 	if (ill->ill_promisc_on_phys) {
26416 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26417 		    "ill in promiscous mode, don't accelerate packet\n"));
26418 		return;
26419 	}
26420 
26421 	/*
26422 	 * Will the packet require fragmentation?
26423 	 */
26424 
26425 	/*
26426 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26427 	 * as is used elsewhere.
26428 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26429 	 *	+ 2-byte trailer
26430 	 */
26431 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26432 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26433 
26434 	if ((plen + overhead) > ill->ill_max_mtu)
26435 		return;
26436 
26437 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26438 
26439 	/*
26440 	 * Can the ill accelerate this IPsec protocol and algorithm
26441 	 * specified by the SA?
26442 	 */
26443 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26444 	    ill->ill_isv6, sa)) {
26445 		return;
26446 	}
26447 
26448 	/*
26449 	 * Tell AH or ESP that the outbound ill is capable of
26450 	 * accelerating this packet.
26451 	 */
26452 	io->ipsec_out_is_capab_ill = B_TRUE;
26453 }
26454 
26455 /*
26456  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26457  *
26458  * If this function returns B_TRUE, the requested SA's have been filled
26459  * into the ipsec_out_*_sa pointers.
26460  *
26461  * If the function returns B_FALSE, the packet has been "consumed", most
26462  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26463  *
26464  * The SA references created by the protocol-specific "select"
26465  * function will be released when the ipsec_mp is freed, thanks to the
26466  * ipsec_out_free destructor -- see spd.c.
26467  */
26468 static boolean_t
26469 ipsec_out_select_sa(mblk_t *ipsec_mp)
26470 {
26471 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26472 	ipsec_out_t *io;
26473 	ipsec_policy_t *pp;
26474 	ipsec_action_t *ap;
26475 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26476 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26477 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26478 
26479 	if (!io->ipsec_out_secure) {
26480 		/*
26481 		 * We came here by mistake.
26482 		 * Don't bother with ipsec processing
26483 		 * We should "discourage" this path in the future.
26484 		 */
26485 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26486 		return (B_FALSE);
26487 	}
26488 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26489 	ASSERT((io->ipsec_out_policy != NULL) ||
26490 	    (io->ipsec_out_act != NULL));
26491 
26492 	ASSERT(io->ipsec_out_failed == B_FALSE);
26493 
26494 	/*
26495 	 * IPSEC processing has started.
26496 	 */
26497 	io->ipsec_out_proc_begin = B_TRUE;
26498 	ap = io->ipsec_out_act;
26499 	if (ap == NULL) {
26500 		pp = io->ipsec_out_policy;
26501 		ASSERT(pp != NULL);
26502 		ap = pp->ipsp_act;
26503 		ASSERT(ap != NULL);
26504 	}
26505 
26506 	/*
26507 	 * We have an action.  now, let's select SA's.
26508 	 * (In the future, we can cache this in the conn_t..)
26509 	 */
26510 	if (ap->ipa_want_esp) {
26511 		if (io->ipsec_out_esp_sa == NULL) {
26512 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26513 			    IPPROTO_ESP);
26514 		}
26515 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26516 	}
26517 
26518 	if (ap->ipa_want_ah) {
26519 		if (io->ipsec_out_ah_sa == NULL) {
26520 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26521 			    IPPROTO_AH);
26522 		}
26523 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26524 		/*
26525 		 * The ESP and AH processing order needs to be preserved
26526 		 * when both protocols are required (ESP should be applied
26527 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26528 		 * when both ESP and AH are required, and an AH ACQUIRE
26529 		 * is needed.
26530 		 */
26531 		if (ap->ipa_want_esp && need_ah_acquire)
26532 			need_esp_acquire = B_TRUE;
26533 	}
26534 
26535 	/*
26536 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26537 	 * Release SAs that got referenced, but will not be used until we
26538 	 * acquire _all_ of the SAs we need.
26539 	 */
26540 	if (need_ah_acquire || need_esp_acquire) {
26541 		if (io->ipsec_out_ah_sa != NULL) {
26542 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26543 			io->ipsec_out_ah_sa = NULL;
26544 		}
26545 		if (io->ipsec_out_esp_sa != NULL) {
26546 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26547 			io->ipsec_out_esp_sa = NULL;
26548 		}
26549 
26550 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26551 		return (B_FALSE);
26552 	}
26553 
26554 	return (B_TRUE);
26555 }
26556 
26557 /*
26558  * Process an IPSEC_OUT message and see what you can
26559  * do with it.
26560  * IPQoS Notes:
26561  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26562  * IPSec.
26563  * XXX would like to nuke ire_t.
26564  * XXX ill_index better be "real"
26565  */
26566 void
26567 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26568 {
26569 	ipsec_out_t *io;
26570 	ipsec_policy_t *pp;
26571 	ipsec_action_t *ap;
26572 	ipha_t *ipha;
26573 	ip6_t *ip6h;
26574 	mblk_t *mp;
26575 	ill_t *ill;
26576 	zoneid_t zoneid;
26577 	ipsec_status_t ipsec_rc;
26578 	boolean_t ill_need_rele = B_FALSE;
26579 
26580 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26581 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26582 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26583 	mp = ipsec_mp->b_cont;
26584 
26585 	/*
26586 	 * Initiate IPPF processing. We do it here to account for packets
26587 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26588 	 * We can check for ipsec_out_proc_begin even for such packets, as
26589 	 * they will always be false (asserted below).
26590 	 */
26591 	if (IPP_ENABLED(IPP_LOCAL_OUT) && !io->ipsec_out_proc_begin) {
26592 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26593 		    io->ipsec_out_ill_index : ill_index);
26594 		if (mp == NULL) {
26595 			ip2dbg(("ipsec_out_process: packet dropped "\
26596 			    "during IPPF processing\n"));
26597 			freeb(ipsec_mp);
26598 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26599 			return;
26600 		}
26601 	}
26602 
26603 	if (!io->ipsec_out_secure) {
26604 		/*
26605 		 * We came here by mistake.
26606 		 * Don't bother with ipsec processing
26607 		 * Should "discourage" this path in the future.
26608 		 */
26609 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26610 		goto done;
26611 	}
26612 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26613 	ASSERT((io->ipsec_out_policy != NULL) ||
26614 	    (io->ipsec_out_act != NULL));
26615 	ASSERT(io->ipsec_out_failed == B_FALSE);
26616 
26617 	if (!ipsec_loaded()) {
26618 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26619 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26620 			BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26621 		} else {
26622 			BUMP_MIB(&ip6_mib, ipIfStatsOutDiscards);
26623 		}
26624 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26625 		    &ipdrops_ip_ipsec_not_loaded, &ip_dropper);
26626 		return;
26627 	}
26628 
26629 	/*
26630 	 * IPSEC processing has started.
26631 	 */
26632 	io->ipsec_out_proc_begin = B_TRUE;
26633 	ap = io->ipsec_out_act;
26634 	if (ap == NULL) {
26635 		pp = io->ipsec_out_policy;
26636 		ASSERT(pp != NULL);
26637 		ap = pp->ipsp_act;
26638 		ASSERT(ap != NULL);
26639 	}
26640 
26641 	/*
26642 	 * Save the outbound ill index. When the packet comes back
26643 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26644 	 * before sending it the accelerated packet.
26645 	 */
26646 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26647 		int ifindex;
26648 		ill = ire_to_ill(ire);
26649 		ifindex = ill->ill_phyint->phyint_ifindex;
26650 		io->ipsec_out_capab_ill_index = ifindex;
26651 	}
26652 
26653 	/*
26654 	 * The order of processing is first insert a IP header if needed.
26655 	 * Then insert the ESP header and then the AH header.
26656 	 */
26657 	if ((io->ipsec_out_se_done == B_FALSE) &&
26658 	    (ap->ipa_want_se)) {
26659 		/*
26660 		 * First get the outer IP header before sending
26661 		 * it to ESP.
26662 		 */
26663 		ipha_t *oipha, *iipha;
26664 		mblk_t *outer_mp, *inner_mp;
26665 
26666 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26667 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26668 			    "ipsec_out_process: "
26669 			    "Self-Encapsulation failed: Out of memory\n");
26670 			freemsg(ipsec_mp);
26671 			if (ill != NULL) {
26672 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26673 			} else {
26674 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26675 			}
26676 			return;
26677 		}
26678 		inner_mp = ipsec_mp->b_cont;
26679 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26680 		oipha = (ipha_t *)outer_mp->b_rptr;
26681 		iipha = (ipha_t *)inner_mp->b_rptr;
26682 		*oipha = *iipha;
26683 		outer_mp->b_wptr += sizeof (ipha_t);
26684 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26685 		    sizeof (ipha_t));
26686 		oipha->ipha_protocol = IPPROTO_ENCAP;
26687 		oipha->ipha_version_and_hdr_length =
26688 		    IP_SIMPLE_HDR_VERSION;
26689 		oipha->ipha_hdr_checksum = 0;
26690 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26691 		outer_mp->b_cont = inner_mp;
26692 		ipsec_mp->b_cont = outer_mp;
26693 
26694 		io->ipsec_out_se_done = B_TRUE;
26695 		io->ipsec_out_tunnel = B_TRUE;
26696 	}
26697 
26698 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26699 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26700 	    !ipsec_out_select_sa(ipsec_mp))
26701 		return;
26702 
26703 	/*
26704 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26705 	 * to do the heavy lifting.
26706 	 */
26707 	zoneid = io->ipsec_out_zoneid;
26708 	ASSERT(zoneid != ALL_ZONES);
26709 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26710 		ASSERT(io->ipsec_out_esp_sa != NULL);
26711 		io->ipsec_out_esp_done = B_TRUE;
26712 		/*
26713 		 * Note that since hw accel can only apply one transform,
26714 		 * not two, we skip hw accel for ESP if we also have AH
26715 		 * This is an design limitation of the interface
26716 		 * which should be revisited.
26717 		 */
26718 		ASSERT(ire != NULL);
26719 		if (io->ipsec_out_ah_sa == NULL) {
26720 			ill = (ill_t *)ire->ire_stq->q_ptr;
26721 			ipsec_out_is_accelerated(ipsec_mp,
26722 			    io->ipsec_out_esp_sa, ill, ire);
26723 		}
26724 
26725 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26726 		switch (ipsec_rc) {
26727 		case IPSEC_STATUS_SUCCESS:
26728 			break;
26729 		case IPSEC_STATUS_FAILED:
26730 			if (ill != NULL) {
26731 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26732 			} else {
26733 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26734 			}
26735 			/* FALLTHRU */
26736 		case IPSEC_STATUS_PENDING:
26737 			return;
26738 		}
26739 	}
26740 
26741 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26742 		ASSERT(io->ipsec_out_ah_sa != NULL);
26743 		io->ipsec_out_ah_done = B_TRUE;
26744 		if (ire == NULL) {
26745 			int idx = io->ipsec_out_capab_ill_index;
26746 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26747 			    NULL, NULL, NULL, NULL);
26748 			ill_need_rele = B_TRUE;
26749 		} else {
26750 			ill = (ill_t *)ire->ire_stq->q_ptr;
26751 		}
26752 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26753 		    ire);
26754 
26755 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26756 		switch (ipsec_rc) {
26757 		case IPSEC_STATUS_SUCCESS:
26758 			break;
26759 		case IPSEC_STATUS_FAILED:
26760 			if (ill != NULL) {
26761 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26762 			} else {
26763 				BUMP_MIB(&ip_mib, ipIfStatsOutDiscards);
26764 			}
26765 			/* FALLTHRU */
26766 		case IPSEC_STATUS_PENDING:
26767 			if (ill != NULL && ill_need_rele)
26768 				ill_refrele(ill);
26769 			return;
26770 		}
26771 	}
26772 	/*
26773 	 * We are done with IPSEC processing. Send it over
26774 	 * the wire.
26775 	 */
26776 done:
26777 	mp = ipsec_mp->b_cont;
26778 	ipha = (ipha_t *)mp->b_rptr;
26779 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26780 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26781 	} else {
26782 		ip6h = (ip6_t *)ipha;
26783 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26784 	}
26785 	if (ill != NULL && ill_need_rele)
26786 		ill_refrele(ill);
26787 }
26788 
26789 /* ARGSUSED */
26790 void
26791 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26792 {
26793 	opt_restart_t	*or;
26794 	int	err;
26795 	conn_t	*connp;
26796 
26797 	ASSERT(CONN_Q(q));
26798 	connp = Q_TO_CONN(q);
26799 
26800 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26801 	or = (opt_restart_t *)first_mp->b_rptr;
26802 	/*
26803 	 * We don't need to pass any credentials here since this is just
26804 	 * a restart. The credentials are passed in when svr4_optcom_req
26805 	 * is called the first time (from ip_wput_nondata).
26806 	 */
26807 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26808 		err = svr4_optcom_req(q, first_mp, NULL,
26809 		    &ip_opt_obj);
26810 	} else {
26811 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26812 		err = tpi_optcom_req(q, first_mp, NULL,
26813 		    &ip_opt_obj);
26814 	}
26815 	if (err != EINPROGRESS) {
26816 		/* operation is done */
26817 		CONN_OPER_PENDING_DONE(connp);
26818 	}
26819 }
26820 
26821 /*
26822  * ioctls that go through a down/up sequence may need to wait for the down
26823  * to complete. This involves waiting for the ire and ipif refcnts to go down
26824  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26825  */
26826 /* ARGSUSED */
26827 void
26828 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26829 {
26830 	struct iocblk *iocp;
26831 	mblk_t *mp1;
26832 	ipif_t	*ipif;
26833 	ip_ioctl_cmd_t *ipip;
26834 	int err;
26835 	sin_t	*sin;
26836 	struct lifreq *lifr;
26837 	struct ifreq *ifr;
26838 
26839 	iocp = (struct iocblk *)mp->b_rptr;
26840 	ASSERT(ipsq != NULL);
26841 	/* Existence of mp1 verified in ip_wput_nondata */
26842 	mp1 = mp->b_cont->b_cont;
26843 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26844 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26845 		ill_t *ill;
26846 		/*
26847 		 * Special case where ipsq_current_ipif may not be set.
26848 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26849 		 * ill could also have become part of a ipmp group in the
26850 		 * process, we are here as were not able to complete the
26851 		 * operation in ipif_set_values because we could not become
26852 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26853 		 * will not be set so we need to set it.
26854 		 */
26855 		ill = (ill_t *)q->q_ptr;
26856 		ipsq->ipsq_current_ipif = ill->ill_ipif;
26857 		ipsq->ipsq_last_cmd = ipip->ipi_cmd;
26858 	}
26859 
26860 	ipif = ipsq->ipsq_current_ipif;
26861 	ASSERT(ipif != NULL);
26862 	if (ipip->ipi_cmd_type == IF_CMD) {
26863 		/* This a old style SIOC[GS]IF* command */
26864 		ifr = (struct ifreq *)mp1->b_rptr;
26865 		sin = (sin_t *)&ifr->ifr_addr;
26866 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26867 		/* This a new style SIOC[GS]LIF* command */
26868 		lifr = (struct lifreq *)mp1->b_rptr;
26869 		sin = (sin_t *)&lifr->lifr_addr;
26870 	} else {
26871 		sin = NULL;
26872 	}
26873 
26874 	err = (*ipip->ipi_func_restart)(ipif, sin, q, mp, ipip,
26875 	    (void *)mp1->b_rptr);
26876 
26877 	/* SIOCLIFREMOVEIF could have removed the ipif */
26878 	ip_ioctl_finish(q, mp, err,
26879 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26880 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ipif, ipsq);
26881 }
26882 
26883 /*
26884  * ioctl processing
26885  *
26886  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
26887  * the ioctl command in the ioctl tables and determines the copyin data size
26888  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
26889  * size.
26890  *
26891  * ioctl processing then continues when the M_IOCDATA makes its way down.
26892  * Now the ioctl is looked up again in the ioctl table, and its properties are
26893  * extracted. The associated 'conn' is then refheld till the end of the ioctl
26894  * and the general ioctl processing function ip_process_ioctl is called.
26895  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26896  * so goes thru the serialization primitive ipsq_try_enter. Then the
26897  * appropriate function to handle the ioctl is called based on the entry in
26898  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26899  * which also refreleases the 'conn' that was refheld at the start of the
26900  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26901  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
26902  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
26903  *
26904  * Many exclusive ioctls go thru an internal down up sequence as part of
26905  * the operation. For example an attempt to change the IP address of an
26906  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26907  * does all the cleanup such as deleting all ires that use this address.
26908  * Then we need to wait till all references to the interface go away.
26909  */
26910 void
26911 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26912 {
26913 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26914 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
26915 	cmd_info_t ci;
26916 	int err;
26917 	boolean_t entered_ipsq = B_FALSE;
26918 
26919 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26920 
26921 	if (ipip == NULL)
26922 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26923 
26924 	/*
26925 	 * SIOCLIFADDIF needs to go thru a special path since the
26926 	 * ill may not exist yet. This happens in the case of lo0
26927 	 * which is created using this ioctl.
26928 	 */
26929 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26930 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26931 		ip_ioctl_finish(q, mp, err,
26932 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
26933 		    NULL, NULL);
26934 		return;
26935 	}
26936 
26937 	ci.ci_ipif = NULL;
26938 	switch (ipip->ipi_cmd_type) {
26939 	case IF_CMD:
26940 	case LIF_CMD:
26941 		/*
26942 		 * ioctls that pass in a [l]ifreq appear here.
26943 		 * ip_extract_lifreq_cmn returns a refheld ipif in
26944 		 * ci.ci_ipif
26945 		 */
26946 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
26947 		    ipip->ipi_flags, &ci, ip_process_ioctl);
26948 		if (err != 0) {
26949 			ip_ioctl_finish(q, mp, err,
26950 			    ipip->ipi_flags & IPI_GET_CMD ?
26951 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26952 			return;
26953 		}
26954 		ASSERT(ci.ci_ipif != NULL);
26955 		break;
26956 
26957 	case TUN_CMD:
26958 		/*
26959 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
26960 		 * a refheld ipif in ci.ci_ipif
26961 		 */
26962 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
26963 		if (err != 0) {
26964 			ip_ioctl_finish(q, mp, err,
26965 			    ipip->ipi_flags & IPI_GET_CMD ?
26966 			    COPYOUT : NO_COPYOUT, NULL, NULL);
26967 			return;
26968 		}
26969 		ASSERT(ci.ci_ipif != NULL);
26970 		break;
26971 
26972 	case MISC_CMD:
26973 		/*
26974 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
26975 		 * For eg. SIOCGLIFCONF will appear here.
26976 		 */
26977 		switch (ipip->ipi_cmd) {
26978 		case IF_UNITSEL:
26979 			/* ioctl comes down the ill */
26980 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26981 			ipif_refhold(ci.ci_ipif);
26982 			break;
26983 		case SIOCGMSFILTER:
26984 		case SIOCSMSFILTER:
26985 		case SIOCGIPMSFILTER:
26986 		case SIOCSIPMSFILTER:
26987 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
26988 			    ip_process_ioctl);
26989 			if (err != 0) {
26990 				ip_ioctl_finish(q, mp, err,
26991 				    ipip->ipi_flags & IPI_GET_CMD ?
26992 				    COPYOUT : NO_COPYOUT, NULL, NULL);
26993 				return;
26994 			}
26995 			break;
26996 		}
26997 		err = 0;
26998 		ci.ci_sin = NULL;
26999 		ci.ci_sin6 = NULL;
27000 		ci.ci_lifr = NULL;
27001 		break;
27002 	}
27003 
27004 	/*
27005 	 * If ipsq is non-null, we are already being called exclusively
27006 	 */
27007 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27008 	if (!(ipip->ipi_flags & IPI_WR)) {
27009 		/*
27010 		 * A return value of EINPROGRESS means the ioctl is
27011 		 * either queued and waiting for some reason or has
27012 		 * already completed.
27013 		 */
27014 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27015 		    ci.ci_lifr);
27016 		if (ci.ci_ipif != NULL)
27017 			ipif_refrele(ci.ci_ipif);
27018 		ip_ioctl_finish(q, mp, err,
27019 		    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
27020 		    NULL, NULL);
27021 		return;
27022 	}
27023 
27024 	ASSERT(ci.ci_ipif != NULL);
27025 
27026 	if (ipsq == NULL) {
27027 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27028 		    ip_process_ioctl, NEW_OP, B_TRUE);
27029 		entered_ipsq = B_TRUE;
27030 	}
27031 	/*
27032 	 * Release the ipif so that ipif_down and friends that wait for
27033 	 * references to go away are not misled about the current ipif_refcnt
27034 	 * values. We are writer so we can access the ipif even after releasing
27035 	 * the ipif.
27036 	 */
27037 	ipif_refrele(ci.ci_ipif);
27038 	if (ipsq == NULL)
27039 		return;
27040 
27041 	mutex_enter(&ipsq->ipsq_lock);
27042 	ASSERT(ipsq->ipsq_current_ipif == NULL);
27043 	ipsq->ipsq_current_ipif = ci.ci_ipif;
27044 	ipsq->ipsq_last_cmd = ipip->ipi_cmd;
27045 	mutex_exit(&ipsq->ipsq_lock);
27046 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27047 	/*
27048 	 * For most set ioctls that come here, this serves as a single point
27049 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27050 	 * be any new references to the ipif. This helps functions that go
27051 	 * through this path and end up trying to wait for the refcnts
27052 	 * associated with the ipif to go down to zero. Some exceptions are
27053 	 * Failover, Failback, and Groupname commands that operate on more than
27054 	 * just the ci.ci_ipif. These commands internally determine the
27055 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27056 	 * flags on that set. Another exception is the Removeif command that
27057 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27058 	 * ipif to operate on.
27059 	 */
27060 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27061 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27062 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27063 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27064 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27065 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27066 
27067 	/*
27068 	 * A return value of EINPROGRESS means the ioctl is
27069 	 * either queued and waiting for some reason or has
27070 	 * already completed.
27071 	 */
27072 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27073 	    ci.ci_lifr);
27074 
27075 	/* SIOCLIFREMOVEIF could have removed the ipif */
27076 	ip_ioctl_finish(q, mp, err,
27077 	    ipip->ipi_flags & IPI_GET_CMD ? COPYOUT : NO_COPYOUT,
27078 	    ipip->ipi_cmd == SIOCLIFREMOVEIF ? NULL : ci.ci_ipif, ipsq);
27079 
27080 	if (entered_ipsq)
27081 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27082 }
27083 
27084 /*
27085  * Complete the ioctl. Typically ioctls use the mi package and need to
27086  * do mi_copyout/mi_copy_done.
27087  */
27088 void
27089 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode,
27090     ipif_t *ipif, ipsq_t *ipsq)
27091 {
27092 	conn_t	*connp = NULL;
27093 	hook_nic_event_t *info;
27094 
27095 	if (err == EINPROGRESS)
27096 		return;
27097 
27098 	if (CONN_Q(q)) {
27099 		connp = Q_TO_CONN(q);
27100 		ASSERT(connp->conn_ref >= 2);
27101 	}
27102 
27103 	switch (mode) {
27104 	case COPYOUT:
27105 		if (err == 0)
27106 			mi_copyout(q, mp);
27107 		else
27108 			mi_copy_done(q, mp, err);
27109 		break;
27110 
27111 	case NO_COPYOUT:
27112 		mi_copy_done(q, mp, err);
27113 		break;
27114 
27115 	default:
27116 		/* An ioctl aborted through a conn close would take this path */
27117 		break;
27118 	}
27119 
27120 	/*
27121 	 * The refhold placed at the start of the ioctl is released here.
27122 	 */
27123 	if (connp != NULL)
27124 		CONN_OPER_PENDING_DONE(connp);
27125 
27126 	/*
27127 	 * If the ioctl were an exclusive ioctl it would have set
27128 	 * IPIF_CHANGING at the start of the ioctl which is undone here.
27129 	 */
27130 	if (ipif != NULL) {
27131 		mutex_enter(&(ipif)->ipif_ill->ill_lock);
27132 		ipif->ipif_state_flags &= ~IPIF_CHANGING;
27133 
27134 		/*
27135 		 * Unhook the nic event message from the ill and enqueue it into
27136 		 * the nic event taskq.
27137 		 */
27138 		if ((info = ipif->ipif_ill->ill_nic_event_info) != NULL) {
27139 			if (ddi_taskq_dispatch(eventq_queue_nic,
27140 			    ip_ne_queue_func, (void *)info, DDI_SLEEP)
27141 			    == DDI_FAILURE) {
27142 				ip2dbg(("ip_ioctl_finish: ddi_taskq_dispatch"
27143 				    "failed\n"));
27144 				if (info->hne_data != NULL)
27145 					kmem_free(info->hne_data,
27146 					    info->hne_datalen);
27147 				kmem_free(info, sizeof (hook_nic_event_t));
27148 			}
27149 
27150 			ipif->ipif_ill->ill_nic_event_info = NULL;
27151 		}
27152 
27153 		mutex_exit(&(ipif)->ipif_ill->ill_lock);
27154 	}
27155 
27156 	/*
27157 	 * Clear the current ipif in the ipsq at the completion of the ioctl.
27158 	 * Note that a non-null ipsq_current_ipif prevents new ioctls from
27159 	 * entering the ipsq
27160 	 */
27161 	if (ipsq != NULL) {
27162 		mutex_enter(&ipsq->ipsq_lock);
27163 		ipsq->ipsq_current_ipif = NULL;
27164 		mutex_exit(&ipsq->ipsq_lock);
27165 	}
27166 }
27167 
27168 /*
27169  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27170  */
27171 /* ARGSUSED */
27172 void
27173 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27174 {
27175 	conn_t *connp = arg;
27176 	tcp_t	*tcp;
27177 
27178 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27179 	tcp = connp->conn_tcp;
27180 
27181 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27182 		freemsg(mp);
27183 	else
27184 		tcp_rput_other(tcp, mp);
27185 	CONN_OPER_PENDING_DONE(connp);
27186 }
27187 
27188 /* Called from ip_wput for all non data messages */
27189 /* ARGSUSED */
27190 void
27191 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27192 {
27193 	mblk_t		*mp1;
27194 	ire_t		*ire, *fake_ire;
27195 	ill_t		*ill;
27196 	struct iocblk	*iocp;
27197 	ip_ioctl_cmd_t	*ipip;
27198 	cred_t		*cr;
27199 	conn_t		*connp = NULL;
27200 	int		cmd, err;
27201 	nce_t		*nce;
27202 	ipif_t		*ipif;
27203 
27204 	if (CONN_Q(q))
27205 		connp = Q_TO_CONN(q);
27206 
27207 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27208 
27209 	/* Check if it is a queue to /dev/sctp. */
27210 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27211 	    connp->conn_rq == NULL) {
27212 		sctp_wput(q, mp);
27213 		return;
27214 	}
27215 
27216 	switch (DB_TYPE(mp)) {
27217 	case M_IOCTL:
27218 		/*
27219 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27220 		 * will arrange to copy in associated control structures.
27221 		 */
27222 		ip_sioctl_copyin_setup(q, mp);
27223 		return;
27224 	case M_IOCDATA:
27225 		/*
27226 		 * Ensure that this is associated with one of our trans-
27227 		 * parent ioctls.  If it's not ours, discard it if we're
27228 		 * running as a driver, or pass it on if we're a module.
27229 		 */
27230 		iocp = (struct iocblk *)mp->b_rptr;
27231 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27232 		if (ipip == NULL) {
27233 			if (q->q_next == NULL) {
27234 				goto nak;
27235 			} else {
27236 				putnext(q, mp);
27237 			}
27238 			return;
27239 		} else if ((q->q_next != NULL) &&
27240 		    !(ipip->ipi_flags & IPI_MODOK)) {
27241 			/*
27242 			 * the ioctl is one we recognise, but is not
27243 			 * consumed by IP as a module, pass M_IOCDATA
27244 			 * for processing downstream, but only for
27245 			 * common Streams ioctls.
27246 			 */
27247 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27248 				putnext(q, mp);
27249 				return;
27250 			} else {
27251 				goto nak;
27252 			}
27253 		}
27254 
27255 		/* IOCTL continuation following copyin or copyout. */
27256 		if (mi_copy_state(q, mp, NULL) == -1) {
27257 			/*
27258 			 * The copy operation failed.  mi_copy_state already
27259 			 * cleaned up, so we're out of here.
27260 			 */
27261 			return;
27262 		}
27263 		/*
27264 		 * If we just completed a copy in, we become writer and
27265 		 * continue processing in ip_sioctl_copyin_done.  If it
27266 		 * was a copy out, we call mi_copyout again.  If there is
27267 		 * nothing more to copy out, it will complete the IOCTL.
27268 		 */
27269 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27270 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27271 				mi_copy_done(q, mp, EPROTO);
27272 				return;
27273 			}
27274 			/*
27275 			 * Check for cases that need more copying.  A return
27276 			 * value of 0 means a second copyin has been started,
27277 			 * so we return; a return value of 1 means no more
27278 			 * copying is needed, so we continue.
27279 			 */
27280 			cmd = iocp->ioc_cmd;
27281 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27282 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27283 			    MI_COPY_COUNT(mp) == 1) {
27284 				if (ip_copyin_msfilter(q, mp) == 0)
27285 					return;
27286 			}
27287 			/*
27288 			 * Refhold the conn, till the ioctl completes. This is
27289 			 * needed in case the ioctl ends up in the pending mp
27290 			 * list. Every mp in the ill_pending_mp list and
27291 			 * the ipsq_pending_mp must have a refhold on the conn
27292 			 * to resume processing. The refhold is released when
27293 			 * the ioctl completes. (normally or abnormally)
27294 			 * In all cases ip_ioctl_finish is called to finish
27295 			 * the ioctl.
27296 			 */
27297 			if (connp != NULL) {
27298 				/* This is not a reentry */
27299 				ASSERT(ipsq == NULL);
27300 				CONN_INC_REF(connp);
27301 			} else {
27302 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27303 					mi_copy_done(q, mp, EINVAL);
27304 					return;
27305 				}
27306 			}
27307 
27308 			ip_process_ioctl(ipsq, q, mp, ipip);
27309 
27310 		} else {
27311 			mi_copyout(q, mp);
27312 		}
27313 		return;
27314 nak:
27315 		iocp->ioc_error = EINVAL;
27316 		mp->b_datap->db_type = M_IOCNAK;
27317 		iocp->ioc_count = 0;
27318 		qreply(q, mp);
27319 		return;
27320 
27321 	case M_IOCNAK:
27322 		/*
27323 		 * The only way we could get here is if a resolver didn't like
27324 		 * an IOCTL we sent it.	 This shouldn't happen.
27325 		 */
27326 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27327 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27328 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27329 		freemsg(mp);
27330 		return;
27331 	case M_IOCACK:
27332 		/* Finish socket ioctls passed through to ARP. */
27333 		ip_sioctl_iocack(q, mp);
27334 		return;
27335 	case M_FLUSH:
27336 		if (*mp->b_rptr & FLUSHW)
27337 			flushq(q, FLUSHALL);
27338 		if (q->q_next) {
27339 			/*
27340 			 * M_FLUSH is sent up to IP by some drivers during
27341 			 * unbind. ip_rput has already replied to it. We are
27342 			 * here for the M_FLUSH that we originated in IP
27343 			 * before sending the unbind request to the driver.
27344 			 * Just free it as we don't queue packets in IP
27345 			 * on the write side of the device instance.
27346 			 */
27347 			freemsg(mp);
27348 			return;
27349 		}
27350 		if (*mp->b_rptr & FLUSHR) {
27351 			*mp->b_rptr &= ~FLUSHW;
27352 			qreply(q, mp);
27353 			return;
27354 		}
27355 		freemsg(mp);
27356 		return;
27357 	case IRE_DB_REQ_TYPE:
27358 		/* An Upper Level Protocol wants a copy of an IRE. */
27359 		ip_ire_req(q, mp);
27360 		return;
27361 	case M_CTL:
27362 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27363 			break;
27364 
27365 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27366 		    TUN_HELLO) {
27367 			ASSERT(connp != NULL);
27368 			connp->conn_flags |= IPCL_IPTUN;
27369 			freeb(mp);
27370 			return;
27371 		}
27372 
27373 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27374 		    IP_ULP_OUT_LABELED) {
27375 			out_labeled_t *olp;
27376 
27377 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27378 				break;
27379 			olp = (out_labeled_t *)mp->b_rptr;
27380 			connp->conn_ulp_labeled = olp->out_qnext == q;
27381 			freemsg(mp);
27382 			return;
27383 		}
27384 
27385 		/* M_CTL messages are used by ARP to tell us things. */
27386 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27387 			break;
27388 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27389 		case AR_ENTRY_SQUERY:
27390 			ip_wput_ctl(q, mp);
27391 			return;
27392 		case AR_CLIENT_NOTIFY:
27393 			ip_arp_news(q, mp);
27394 			return;
27395 		case AR_DLPIOP_DONE:
27396 			ASSERT(q->q_next != NULL);
27397 			ill = (ill_t *)q->q_ptr;
27398 			/* qwriter_ip releases the refhold */
27399 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27400 			ill_refhold(ill);
27401 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27402 			    CUR_OP, B_FALSE);
27403 			return;
27404 		case AR_ARP_CLOSING:
27405 			/*
27406 			 * ARP (above us) is closing. If no ARP bringup is
27407 			 * currently pending, ack the message so that ARP
27408 			 * can complete its close. Also mark ill_arp_closing
27409 			 * so that new ARP bringups will fail. If any
27410 			 * ARP bringup is currently in progress, we will
27411 			 * ack this when the current ARP bringup completes.
27412 			 */
27413 			ASSERT(q->q_next != NULL);
27414 			ill = (ill_t *)q->q_ptr;
27415 			mutex_enter(&ill->ill_lock);
27416 			ill->ill_arp_closing = 1;
27417 			if (!ill->ill_arp_bringup_pending) {
27418 				mutex_exit(&ill->ill_lock);
27419 				qreply(q, mp);
27420 			} else {
27421 				mutex_exit(&ill->ill_lock);
27422 				freemsg(mp);
27423 			}
27424 			return;
27425 		case AR_ARP_EXTEND:
27426 			/*
27427 			 * The ARP module above us is capable of duplicate
27428 			 * address detection.  Old ATM drivers will not send
27429 			 * this message.
27430 			 */
27431 			ASSERT(q->q_next != NULL);
27432 			ill = (ill_t *)q->q_ptr;
27433 			ill->ill_arp_extend = B_TRUE;
27434 			freemsg(mp);
27435 			return;
27436 		default:
27437 			break;
27438 		}
27439 		break;
27440 	case M_PROTO:
27441 	case M_PCPROTO:
27442 		/*
27443 		 * The only PROTO messages we expect are ULP binds and
27444 		 * copies of option negotiation acknowledgements.
27445 		 */
27446 		switch (((union T_primitives *)mp->b_rptr)->type) {
27447 		case O_T_BIND_REQ:
27448 		case T_BIND_REQ: {
27449 			/* Request can get queued in bind */
27450 			ASSERT(connp != NULL);
27451 			/*
27452 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27453 			 * instead of going through this path.  We only get
27454 			 * here in the following cases:
27455 			 *
27456 			 * a. Bind retries, where ipsq is non-NULL.
27457 			 * b. T_BIND_REQ is issued from non TCP/UDP
27458 			 *    transport, e.g. icmp for raw socket,
27459 			 *    in which case ipsq will be NULL.
27460 			 */
27461 			ASSERT(ipsq != NULL ||
27462 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27463 
27464 			/* Don't increment refcnt if this is a re-entry */
27465 			if (ipsq == NULL)
27466 				CONN_INC_REF(connp);
27467 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27468 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27469 			if (mp == NULL)
27470 				return;
27471 			if (IPCL_IS_TCP(connp)) {
27472 				/*
27473 				 * In the case of TCP endpoint we
27474 				 * come here only for bind retries
27475 				 */
27476 				ASSERT(ipsq != NULL);
27477 				CONN_INC_REF(connp);
27478 				squeue_fill(connp->conn_sqp, mp,
27479 				    ip_resume_tcp_bind, connp,
27480 				    SQTAG_BIND_RETRY);
27481 				return;
27482 			} else if (IPCL_IS_UDP(connp)) {
27483 				/*
27484 				 * In the case of UDP endpoint we
27485 				 * come here only for bind retries
27486 				 */
27487 				ASSERT(ipsq != NULL);
27488 				udp_resume_bind(connp, mp);
27489 				return;
27490 			}
27491 			qreply(q, mp);
27492 			CONN_OPER_PENDING_DONE(connp);
27493 			return;
27494 		}
27495 		case T_SVR4_OPTMGMT_REQ:
27496 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27497 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27498 
27499 			ASSERT(connp != NULL);
27500 			if (!snmpcom_req(q, mp, ip_snmp_set,
27501 			    ip_snmp_get, cr)) {
27502 				/*
27503 				 * Call svr4_optcom_req so that it can
27504 				 * generate the ack. We don't come here
27505 				 * if this operation is being restarted.
27506 				 * ip_restart_optmgmt will drop the conn ref.
27507 				 * In the case of ipsec option after the ipsec
27508 				 * load is complete conn_restart_ipsec_waiter
27509 				 * drops the conn ref.
27510 				 */
27511 				ASSERT(ipsq == NULL);
27512 				CONN_INC_REF(connp);
27513 				if (ip_check_for_ipsec_opt(q, mp))
27514 					return;
27515 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27516 				if (err != EINPROGRESS) {
27517 					/* Operation is done */
27518 					CONN_OPER_PENDING_DONE(connp);
27519 				}
27520 			}
27521 			return;
27522 		case T_OPTMGMT_REQ:
27523 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27524 			/*
27525 			 * Note: No snmpcom_req support through new
27526 			 * T_OPTMGMT_REQ.
27527 			 * Call tpi_optcom_req so that it can
27528 			 * generate the ack.
27529 			 */
27530 			ASSERT(connp != NULL);
27531 			ASSERT(ipsq == NULL);
27532 			/*
27533 			 * We don't come here for restart. ip_restart_optmgmt
27534 			 * will drop the conn ref. In the case of ipsec option
27535 			 * after the ipsec load is complete
27536 			 * conn_restart_ipsec_waiter drops the conn ref.
27537 			 */
27538 			CONN_INC_REF(connp);
27539 			if (ip_check_for_ipsec_opt(q, mp))
27540 				return;
27541 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27542 			if (err != EINPROGRESS) {
27543 				/* Operation is done */
27544 				CONN_OPER_PENDING_DONE(connp);
27545 			}
27546 			return;
27547 		case T_UNBIND_REQ:
27548 			mp = ip_unbind(q, mp);
27549 			qreply(q, mp);
27550 			return;
27551 		default:
27552 			/*
27553 			 * Have to drop any DLPI messages coming down from
27554 			 * arp (such as an info_req which would cause ip
27555 			 * to receive an extra info_ack if it was passed
27556 			 * through.
27557 			 */
27558 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27559 			    (int)*(uint_t *)mp->b_rptr));
27560 			freemsg(mp);
27561 			return;
27562 		}
27563 		/* NOTREACHED */
27564 	case IRE_DB_TYPE: {
27565 		nce_t		*nce;
27566 		ill_t		*ill;
27567 		in6_addr_t	gw_addr_v6;
27568 
27569 
27570 		/*
27571 		 * This is a response back from a resolver.  It
27572 		 * consists of a message chain containing:
27573 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27574 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27575 		 * The LL_HDR_MBLK is the DLPI header to use to get
27576 		 * the attached packet, and subsequent ones for the
27577 		 * same destination, transmitted.
27578 		 */
27579 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27580 			break;
27581 		/*
27582 		 * First, check to make sure the resolution succeeded.
27583 		 * If it failed, the second mblk will be empty.
27584 		 * If it is, free the chain, dropping the packet.
27585 		 * (We must ire_delete the ire; that frees the ire mblk)
27586 		 * We're doing this now to support PVCs for ATM; it's
27587 		 * a partial xresolv implementation. When we fully implement
27588 		 * xresolv interfaces, instead of freeing everything here
27589 		 * we'll initiate neighbor discovery.
27590 		 *
27591 		 * For v4 (ARP and other external resolvers) the resolver
27592 		 * frees the message, so no check is needed. This check
27593 		 * is required, though, for a full xresolve implementation.
27594 		 * Including this code here now both shows how external
27595 		 * resolvers can NACK a resolution request using an
27596 		 * existing design that has no specific provisions for NACKs,
27597 		 * and also takes into account that the current non-ARP
27598 		 * external resolver has been coded to use this method of
27599 		 * NACKing for all IPv6 (xresolv) cases,
27600 		 * whether our xresolv implementation is complete or not.
27601 		 *
27602 		 */
27603 		ire = (ire_t *)mp->b_rptr;
27604 		ill = ire_to_ill(ire);
27605 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27606 		if (mp1->b_rptr == mp1->b_wptr) {
27607 			if (ire->ire_ipversion == IPV6_VERSION) {
27608 				/*
27609 				 * XRESOLV interface.
27610 				 */
27611 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27612 				mutex_enter(&ire->ire_lock);
27613 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27614 				mutex_exit(&ire->ire_lock);
27615 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27616 					nce = ndp_lookup_v6(ill,
27617 					    &ire->ire_addr_v6, B_FALSE);
27618 				} else {
27619 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27620 					    B_FALSE);
27621 				}
27622 				if (nce != NULL) {
27623 					nce_resolv_failed(nce);
27624 					ndp_delete(nce);
27625 					NCE_REFRELE(nce);
27626 				}
27627 			}
27628 			mp->b_cont = NULL;
27629 			freemsg(mp1);		/* frees the pkt as well */
27630 			ASSERT(ire->ire_nce == NULL);
27631 			ire_delete((ire_t *)mp->b_rptr);
27632 			return;
27633 		}
27634 
27635 		/*
27636 		 * Split them into IRE_MBLK and pkt and feed it into
27637 		 * ire_add_then_send. Then in ire_add_then_send
27638 		 * the IRE will be added, and then the packet will be
27639 		 * run back through ip_wput. This time it will make
27640 		 * it to the wire.
27641 		 */
27642 		mp->b_cont = NULL;
27643 		mp = mp1->b_cont;		/* now, mp points to pkt */
27644 		mp1->b_cont = NULL;
27645 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27646 		if (ire->ire_ipversion == IPV6_VERSION) {
27647 			/*
27648 			 * XRESOLV interface. Find the nce and put a copy
27649 			 * of the dl_unitdata_req in nce_res_mp
27650 			 */
27651 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27652 			mutex_enter(&ire->ire_lock);
27653 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27654 			mutex_exit(&ire->ire_lock);
27655 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27656 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27657 				    B_FALSE);
27658 			} else {
27659 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27660 			}
27661 			if (nce != NULL) {
27662 				/*
27663 				 * We have to protect nce_res_mp here
27664 				 * from being accessed by other threads
27665 				 * while we change the mblk pointer.
27666 				 * Other functions will also lock the nce when
27667 				 * accessing nce_res_mp.
27668 				 *
27669 				 * The reason we change the mblk pointer
27670 				 * here rather than copying the resolved address
27671 				 * into the template is that, unlike with
27672 				 * ethernet, we have no guarantee that the
27673 				 * resolved address length will be
27674 				 * smaller than or equal to the lla length
27675 				 * with which the template was allocated,
27676 				 * (for ethernet, they're equal)
27677 				 * so we have to use the actual resolved
27678 				 * address mblk - which holds the real
27679 				 * dl_unitdata_req with the resolved address.
27680 				 *
27681 				 * Doing this is the same behavior as was
27682 				 * previously used in the v4 ARP case.
27683 				 */
27684 				mutex_enter(&nce->nce_lock);
27685 				if (nce->nce_res_mp != NULL)
27686 					freemsg(nce->nce_res_mp);
27687 				nce->nce_res_mp = mp1;
27688 				mutex_exit(&nce->nce_lock);
27689 				/*
27690 				 * We do a fastpath probe here because
27691 				 * we have resolved the address without
27692 				 * using Neighbor Discovery.
27693 				 * In the non-XRESOLV v6 case, the fastpath
27694 				 * probe is done right after neighbor
27695 				 * discovery completes.
27696 				 */
27697 				if (nce->nce_res_mp != NULL) {
27698 					int res;
27699 					nce_fastpath_list_add(nce);
27700 					res = ill_fastpath_probe(ill,
27701 					    nce->nce_res_mp);
27702 					if (res != 0 && res != EAGAIN)
27703 						nce_fastpath_list_delete(nce);
27704 				}
27705 
27706 				ire_add_then_send(q, ire, mp);
27707 				/*
27708 				 * Now we have to clean out any packets
27709 				 * that may have been queued on the nce
27710 				 * while it was waiting for address resolution
27711 				 * to complete.
27712 				 */
27713 				mutex_enter(&nce->nce_lock);
27714 				mp1 = nce->nce_qd_mp;
27715 				nce->nce_qd_mp = NULL;
27716 				mutex_exit(&nce->nce_lock);
27717 				while (mp1 != NULL) {
27718 					mblk_t *nxt_mp;
27719 					queue_t *fwdq = NULL;
27720 					ill_t   *inbound_ill;
27721 					uint_t ifindex;
27722 
27723 					nxt_mp = mp1->b_next;
27724 					mp1->b_next = NULL;
27725 					/*
27726 					 * Retrieve ifindex stored in
27727 					 * ip_rput_data_v6()
27728 					 */
27729 					ifindex =
27730 					    (uint_t)(uintptr_t)mp1->b_prev;
27731 					inbound_ill =
27732 						ill_lookup_on_ifindex(ifindex,
27733 						    B_TRUE, NULL, NULL, NULL,
27734 						    NULL);
27735 					mp1->b_prev = NULL;
27736 					if (inbound_ill != NULL)
27737 						fwdq = inbound_ill->ill_rq;
27738 
27739 					if (fwdq != NULL) {
27740 						put(fwdq, mp1);
27741 						ill_refrele(inbound_ill);
27742 					} else
27743 						put(WR(ill->ill_rq), mp1);
27744 					mp1 = nxt_mp;
27745 				}
27746 				NCE_REFRELE(nce);
27747 			} else {	/* nce is NULL; clean up */
27748 				ire_delete(ire);
27749 				freemsg(mp);
27750 				freemsg(mp1);
27751 				return;
27752 			}
27753 		} else {
27754 			nce_t *arpce;
27755 			/*
27756 			 * Link layer resolution succeeded. Recompute the
27757 			 * ire_nce.
27758 			 */
27759 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27760 			if ((arpce = ndp_lookup_v4(ill,
27761 			    (ire->ire_gateway_addr != INADDR_ANY ?
27762 			    &ire->ire_gateway_addr : &ire->ire_addr),
27763 			    B_FALSE)) == NULL) {
27764 				freeb(ire->ire_mp);
27765 				freeb(mp1);
27766 				freemsg(mp);
27767 				return;
27768 			}
27769 			mutex_enter(&arpce->nce_lock);
27770 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27771 			if (arpce->nce_state == ND_REACHABLE) {
27772 				/*
27773 				 * Someone resolved this before us;
27774 				 * cleanup the res_mp. Since ire has
27775 				 * not been added yet, the call to ire_add_v4
27776 				 * from ire_add_then_send (when a dup is
27777 				 * detected) will clean up the ire.
27778 				 */
27779 				freeb(mp1);
27780 			} else {
27781 				if (arpce->nce_res_mp != NULL)
27782 					freemsg(arpce->nce_res_mp);
27783 				arpce->nce_res_mp = mp1;
27784 				arpce->nce_state = ND_REACHABLE;
27785 			}
27786 			mutex_exit(&arpce->nce_lock);
27787 			if (ire->ire_marks & IRE_MARK_NOADD) {
27788 				/*
27789 				 * this ire will not be added to the ire
27790 				 * cache table, so we can set the ire_nce
27791 				 * here, as there are no atomicity constraints.
27792 				 */
27793 				ire->ire_nce = arpce;
27794 				/*
27795 				 * We are associating this nce with the ire
27796 				 * so change the nce ref taken in
27797 				 * ndp_lookup_v4() from
27798 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27799 				 */
27800 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27801 			} else {
27802 				NCE_REFRELE(arpce);
27803 			}
27804 			ire_add_then_send(q, ire, mp);
27805 		}
27806 		return;	/* All is well, the packet has been sent. */
27807 	}
27808 	case IRE_ARPRESOLVE_TYPE: {
27809 
27810 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27811 			break;
27812 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27813 		mp->b_cont = NULL;
27814 		/*
27815 		 * First, check to make sure the resolution succeeded.
27816 		 * If it failed, the second mblk will be empty.
27817 		 */
27818 		if (mp1->b_rptr == mp1->b_wptr) {
27819 			/* cleanup  the incomplete ire, free queued packets */
27820 			freemsg(mp); /* fake ire */
27821 			freeb(mp1);  /* dl_unitdata response */
27822 			return;
27823 		}
27824 
27825 		/*
27826 		 * update any incomplete nce_t found. we lookup the ctable
27827 		 * and find the nce from the ire->ire_nce because we need
27828 		 * to pass the ire to ip_xmit_v4 later, and can find both
27829 		 * ire and nce in one lookup from the ctable.
27830 		 */
27831 		fake_ire = (ire_t *)mp->b_rptr;
27832 		/*
27833 		 * By the time we come back here from ARP
27834 		 * the logical outgoing interface  of the incomplete ire
27835 		 * we added in ire_forward could have disappeared,
27836 		 * causing the incomplete ire to also have
27837 		 * dissapeared. So we need to retreive the
27838 		 * proper ipif for the ire  before looking
27839 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27840 		 */
27841 		ill = q->q_ptr;
27842 
27843 		/* Get the outgoing ipif */
27844 		mutex_enter(&ill->ill_lock);
27845 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27846 			mutex_exit(&ill->ill_lock);
27847 			freemsg(mp); /* fake ire */
27848 			freeb(mp1);  /* dl_unitdata response */
27849 			return;
27850 		}
27851 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27852 
27853 		if (ipif == NULL) {
27854 			mutex_exit(&ill->ill_lock);
27855 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27856 			freemsg(mp);
27857 			freeb(mp1);
27858 			return;
27859 		}
27860 		ipif_refhold_locked(ipif);
27861 		mutex_exit(&ill->ill_lock);
27862 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27863 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27864 		    ipif, fake_ire->ire_zoneid, NULL,
27865 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY));
27866 		ipif_refrele(ipif);
27867 		if (ire == NULL) {
27868 			/*
27869 			 * no ire was found; check if there is an nce
27870 			 * for this lookup; if it has no ire's pointing at it
27871 			 * cleanup.
27872 			 */
27873 			if ((nce = ndp_lookup_v4(ill,
27874 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27875 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27876 			    B_FALSE)) != NULL) {
27877 				/*
27878 				 * cleanup: just reset nce.
27879 				 * We check for refcnt 2 (one for the nce
27880 				 * hash list + 1 for the ref taken by
27881 				 * ndp_lookup_v4) to ensure that there are
27882 				 * no ire's pointing at the nce.
27883 				 */
27884 				if (nce->nce_refcnt == 2) {
27885 					nce = nce_reinit(nce);
27886 				}
27887 				if (nce != NULL)
27888 					NCE_REFRELE(nce);
27889 			}
27890 			freeb(mp1);  /* dl_unitdata response */
27891 			freemsg(mp); /* fake ire */
27892 			return;
27893 		}
27894 		nce = ire->ire_nce;
27895 		DTRACE_PROBE2(ire__arpresolve__type,
27896 		    ire_t *, ire, nce_t *, nce);
27897 		ASSERT(nce->nce_state != ND_INITIAL);
27898 		mutex_enter(&nce->nce_lock);
27899 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27900 		if (nce->nce_state == ND_REACHABLE) {
27901 			/*
27902 			 * Someone resolved this before us;
27903 			 * our response is not needed any more.
27904 			 */
27905 			mutex_exit(&nce->nce_lock);
27906 			freeb(mp1);  /* dl_unitdata response */
27907 		} else {
27908 			if (nce->nce_res_mp != NULL) {
27909 				freemsg(nce->nce_res_mp);
27910 				/* existing dl_unitdata template */
27911 			}
27912 			nce->nce_res_mp = mp1;
27913 			nce->nce_state = ND_REACHABLE;
27914 			mutex_exit(&nce->nce_lock);
27915 			ire_fastpath(ire);
27916 		}
27917 		/*
27918 		 * The cached nce_t has been updated to be reachable;
27919 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
27920 		 */
27921 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27922 		freemsg(mp);
27923 		/*
27924 		 * send out queued packets.
27925 		 */
27926 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27927 
27928 		IRE_REFRELE(ire);
27929 		return;
27930 	}
27931 	default:
27932 		break;
27933 	}
27934 	if (q->q_next) {
27935 		putnext(q, mp);
27936 	} else
27937 		freemsg(mp);
27938 }
27939 
27940 /*
27941  * Process IP options in an outbound packet.  Modify the destination if there
27942  * is a source route option.
27943  * Returns non-zero if something fails in which case an ICMP error has been
27944  * sent and mp freed.
27945  */
27946 static int
27947 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27948     boolean_t mctl_present, zoneid_t zoneid)
27949 {
27950 	ipoptp_t	opts;
27951 	uchar_t		*opt;
27952 	uint8_t		optval;
27953 	uint8_t		optlen;
27954 	ipaddr_t	dst;
27955 	intptr_t	code = 0;
27956 	mblk_t		*mp;
27957 	ire_t		*ire = NULL;
27958 
27959 	ip2dbg(("ip_wput_options\n"));
27960 	mp = ipsec_mp;
27961 	if (mctl_present) {
27962 		mp = ipsec_mp->b_cont;
27963 	}
27964 
27965 	dst = ipha->ipha_dst;
27966 	for (optval = ipoptp_first(&opts, ipha);
27967 	    optval != IPOPT_EOL;
27968 	    optval = ipoptp_next(&opts)) {
27969 		opt = opts.ipoptp_cur;
27970 		optlen = opts.ipoptp_len;
27971 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27972 		    optval, optlen));
27973 		switch (optval) {
27974 			uint32_t off;
27975 		case IPOPT_SSRR:
27976 		case IPOPT_LSRR:
27977 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27978 				ip1dbg((
27979 				    "ip_wput_options: bad option offset\n"));
27980 				code = (char *)&opt[IPOPT_OLEN] -
27981 				    (char *)ipha;
27982 				goto param_prob;
27983 			}
27984 			off = opt[IPOPT_OFFSET];
27985 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27986 			    ntohl(dst)));
27987 			/*
27988 			 * For strict: verify that dst is directly
27989 			 * reachable.
27990 			 */
27991 			if (optval == IPOPT_SSRR) {
27992 				ire = ire_ftable_lookup(dst, 0, 0,
27993 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27994 				    MBLK_GETLABEL(mp),
27995 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
27996 				if (ire == NULL) {
27997 					ip1dbg(("ip_wput_options: SSRR not"
27998 					    " directly reachable: 0x%x\n",
27999 					    ntohl(dst)));
28000 					goto bad_src_route;
28001 				}
28002 				ire_refrele(ire);
28003 			}
28004 			break;
28005 		case IPOPT_RR:
28006 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28007 				ip1dbg((
28008 				    "ip_wput_options: bad option offset\n"));
28009 				code = (char *)&opt[IPOPT_OLEN] -
28010 				    (char *)ipha;
28011 				goto param_prob;
28012 			}
28013 			break;
28014 		case IPOPT_TS:
28015 			/*
28016 			 * Verify that length >=5 and that there is either
28017 			 * room for another timestamp or that the overflow
28018 			 * counter is not maxed out.
28019 			 */
28020 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28021 			if (optlen < IPOPT_MINLEN_IT) {
28022 				goto param_prob;
28023 			}
28024 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28025 				ip1dbg((
28026 				    "ip_wput_options: bad option offset\n"));
28027 				code = (char *)&opt[IPOPT_OFFSET] -
28028 				    (char *)ipha;
28029 				goto param_prob;
28030 			}
28031 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28032 			case IPOPT_TS_TSONLY:
28033 				off = IPOPT_TS_TIMELEN;
28034 				break;
28035 			case IPOPT_TS_TSANDADDR:
28036 			case IPOPT_TS_PRESPEC:
28037 			case IPOPT_TS_PRESPEC_RFC791:
28038 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28039 				break;
28040 			default:
28041 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28042 				    (char *)ipha;
28043 				goto param_prob;
28044 			}
28045 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28046 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28047 				/*
28048 				 * No room and the overflow counter is 15
28049 				 * already.
28050 				 */
28051 				goto param_prob;
28052 			}
28053 			break;
28054 		}
28055 	}
28056 
28057 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28058 		return (0);
28059 
28060 	ip1dbg(("ip_wput_options: error processing IP options."));
28061 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28062 
28063 param_prob:
28064 	/*
28065 	 * Since ip_wput() isn't close to finished, we fill
28066 	 * in enough of the header for credible error reporting.
28067 	 */
28068 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
28069 		/* Failed */
28070 		freemsg(ipsec_mp);
28071 		return (-1);
28072 	}
28073 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid);
28074 	return (-1);
28075 
28076 bad_src_route:
28077 	/*
28078 	 * Since ip_wput() isn't close to finished, we fill
28079 	 * in enough of the header for credible error reporting.
28080 	 */
28081 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid)) {
28082 		/* Failed */
28083 		freemsg(ipsec_mp);
28084 		return (-1);
28085 	}
28086 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid);
28087 	return (-1);
28088 }
28089 
28090 /*
28091  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28092  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28093  * thru /etc/system.
28094  */
28095 #define	CONN_MAXDRAINCNT	64
28096 
28097 static void
28098 conn_drain_init(void)
28099 {
28100 	int i;
28101 
28102 	conn_drain_list_cnt = conn_drain_nthreads;
28103 
28104 	if ((conn_drain_list_cnt == 0) ||
28105 	    (conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28106 		/*
28107 		 * Default value of the number of drainers is the
28108 		 * number of cpus, subject to maximum of 8 drainers.
28109 		 */
28110 		if (boot_max_ncpus != -1)
28111 			conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28112 		else
28113 			conn_drain_list_cnt = MIN(max_ncpus, 8);
28114 	}
28115 
28116 	conn_drain_list = kmem_zalloc(conn_drain_list_cnt * sizeof (idl_t),
28117 	    KM_SLEEP);
28118 
28119 	for (i = 0; i < conn_drain_list_cnt; i++) {
28120 		mutex_init(&conn_drain_list[i].idl_lock, NULL,
28121 		    MUTEX_DEFAULT, NULL);
28122 	}
28123 }
28124 
28125 static void
28126 conn_drain_fini(void)
28127 {
28128 	int i;
28129 
28130 	for (i = 0; i < conn_drain_list_cnt; i++)
28131 		mutex_destroy(&conn_drain_list[i].idl_lock);
28132 	kmem_free(conn_drain_list, conn_drain_list_cnt * sizeof (idl_t));
28133 	conn_drain_list = NULL;
28134 }
28135 
28136 /*
28137  * Note: For an overview of how flowcontrol is handled in IP please see the
28138  * IP Flowcontrol notes at the top of this file.
28139  *
28140  * Flow control has blocked us from proceeding. Insert the given conn in one
28141  * of the conn drain lists. These conn wq's will be qenabled later on when
28142  * STREAMS flow control does a backenable. conn_walk_drain will enable
28143  * the first conn in each of these drain lists. Each of these qenabled conns
28144  * in turn enables the next in the list, after it runs, or when it closes,
28145  * thus sustaining the drain process.
28146  *
28147  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28148  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28149  * running at any time, on a given conn, since there can be only 1 service proc
28150  * running on a queue at any time.
28151  */
28152 void
28153 conn_drain_insert(conn_t *connp)
28154 {
28155 	idl_t	*idl;
28156 	uint_t	index;
28157 
28158 	mutex_enter(&connp->conn_lock);
28159 	if (connp->conn_state_flags & CONN_CLOSING) {
28160 		/*
28161 		 * The conn is closing as a result of which CONN_CLOSING
28162 		 * is set. Return.
28163 		 */
28164 		mutex_exit(&connp->conn_lock);
28165 		return;
28166 	} else if (connp->conn_idl == NULL) {
28167 		/*
28168 		 * Assign the next drain list round robin. We dont' use
28169 		 * a lock, and thus it may not be strictly round robin.
28170 		 * Atomicity of load/stores is enough to make sure that
28171 		 * conn_drain_list_index is always within bounds.
28172 		 */
28173 		index = conn_drain_list_index;
28174 		ASSERT(index < conn_drain_list_cnt);
28175 		connp->conn_idl = &conn_drain_list[index];
28176 		index++;
28177 		if (index == conn_drain_list_cnt)
28178 			index = 0;
28179 		conn_drain_list_index = index;
28180 	}
28181 	mutex_exit(&connp->conn_lock);
28182 
28183 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28184 	if ((connp->conn_drain_prev != NULL) ||
28185 	    (connp->conn_state_flags & CONN_CLOSING)) {
28186 		/*
28187 		 * The conn is already in the drain list, OR
28188 		 * the conn is closing. We need to check again for
28189 		 * the closing case again since close can happen
28190 		 * after we drop the conn_lock, and before we
28191 		 * acquire the CONN_DRAIN_LIST_LOCK.
28192 		 */
28193 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28194 		return;
28195 	} else {
28196 		idl = connp->conn_idl;
28197 	}
28198 
28199 	/*
28200 	 * The conn is not in the drain list. Insert it at the
28201 	 * tail of the drain list. The drain list is circular
28202 	 * and doubly linked. idl_conn points to the 1st element
28203 	 * in the list.
28204 	 */
28205 	if (idl->idl_conn == NULL) {
28206 		idl->idl_conn = connp;
28207 		connp->conn_drain_next = connp;
28208 		connp->conn_drain_prev = connp;
28209 	} else {
28210 		conn_t *head = idl->idl_conn;
28211 
28212 		connp->conn_drain_next = head;
28213 		connp->conn_drain_prev = head->conn_drain_prev;
28214 		head->conn_drain_prev->conn_drain_next = connp;
28215 		head->conn_drain_prev = connp;
28216 	}
28217 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28218 }
28219 
28220 /*
28221  * This conn is closing, and we are called from ip_close. OR
28222  * This conn has been serviced by ip_wsrv, and we need to do the tail
28223  * processing.
28224  * If this conn is part of the drain list, we may need to sustain the drain
28225  * process by qenabling the next conn in the drain list. We may also need to
28226  * remove this conn from the list, if it is done.
28227  */
28228 static void
28229 conn_drain_tail(conn_t *connp, boolean_t closing)
28230 {
28231 	idl_t *idl;
28232 
28233 	/*
28234 	 * connp->conn_idl is stable at this point, and no lock is needed
28235 	 * to check it. If we are called from ip_close, close has already
28236 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28237 	 * called us only because conn_idl is non-null. If we are called thru
28238 	 * service, conn_idl could be null, but it cannot change because
28239 	 * service is single-threaded per queue, and there cannot be another
28240 	 * instance of service trying to call conn_drain_insert on this conn
28241 	 * now.
28242 	 */
28243 	ASSERT(!closing || (connp->conn_idl != NULL));
28244 
28245 	/*
28246 	 * If connp->conn_idl is null, the conn has not been inserted into any
28247 	 * drain list even once since creation of the conn. Just return.
28248 	 */
28249 	if (connp->conn_idl == NULL)
28250 		return;
28251 
28252 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28253 
28254 	if (connp->conn_drain_prev == NULL) {
28255 		/* This conn is currently not in the drain list.  */
28256 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28257 		return;
28258 	}
28259 	idl = connp->conn_idl;
28260 	if (idl->idl_conn_draining == connp) {
28261 		/*
28262 		 * This conn is the current drainer. If this is the last conn
28263 		 * in the drain list, we need to do more checks, in the 'if'
28264 		 * below. Otherwwise we need to just qenable the next conn,
28265 		 * to sustain the draining, and is handled in the 'else'
28266 		 * below.
28267 		 */
28268 		if (connp->conn_drain_next == idl->idl_conn) {
28269 			/*
28270 			 * This conn is the last in this list. This round
28271 			 * of draining is complete. If idl_repeat is set,
28272 			 * it means another flow enabling has happened from
28273 			 * the driver/streams and we need to another round
28274 			 * of draining.
28275 			 * If there are more than 2 conns in the drain list,
28276 			 * do a left rotate by 1, so that all conns except the
28277 			 * conn at the head move towards the head by 1, and the
28278 			 * the conn at the head goes to the tail. This attempts
28279 			 * a more even share for all queues that are being
28280 			 * drained.
28281 			 */
28282 			if ((connp->conn_drain_next != connp) &&
28283 			    (idl->idl_conn->conn_drain_next != connp)) {
28284 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28285 			}
28286 			if (idl->idl_repeat) {
28287 				qenable(idl->idl_conn->conn_wq);
28288 				idl->idl_conn_draining = idl->idl_conn;
28289 				idl->idl_repeat = 0;
28290 			} else {
28291 				idl->idl_conn_draining = NULL;
28292 			}
28293 		} else {
28294 			/*
28295 			 * If the next queue that we are now qenable'ing,
28296 			 * is closing, it will remove itself from this list
28297 			 * and qenable the subsequent queue in ip_close().
28298 			 * Serialization is acheived thru idl_lock.
28299 			 */
28300 			qenable(connp->conn_drain_next->conn_wq);
28301 			idl->idl_conn_draining = connp->conn_drain_next;
28302 		}
28303 	}
28304 	if (!connp->conn_did_putbq || closing) {
28305 		/*
28306 		 * Remove ourself from the drain list, if we did not do
28307 		 * a putbq, or if the conn is closing.
28308 		 * Note: It is possible that q->q_first is non-null. It means
28309 		 * that these messages landed after we did a enableok() in
28310 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28311 		 * service them.
28312 		 */
28313 		if (connp->conn_drain_next == connp) {
28314 			/* Singleton in the list */
28315 			ASSERT(connp->conn_drain_prev == connp);
28316 			idl->idl_conn = NULL;
28317 			idl->idl_conn_draining = NULL;
28318 		} else {
28319 			connp->conn_drain_prev->conn_drain_next =
28320 			    connp->conn_drain_next;
28321 			connp->conn_drain_next->conn_drain_prev =
28322 			    connp->conn_drain_prev;
28323 			if (idl->idl_conn == connp)
28324 				idl->idl_conn = connp->conn_drain_next;
28325 			ASSERT(idl->idl_conn_draining != connp);
28326 
28327 		}
28328 		connp->conn_drain_next = NULL;
28329 		connp->conn_drain_prev = NULL;
28330 	}
28331 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28332 }
28333 
28334 /*
28335  * Write service routine. Shared perimeter entry point.
28336  * ip_wsrv can be called in any of the following ways.
28337  * 1. The device queue's messages has fallen below the low water mark
28338  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28339  *    the drain lists and backenable the first conn in each list.
28340  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28341  *    qenabled non-tcp upper layers. We start dequeing messages and call
28342  *    ip_wput for each message.
28343  */
28344 
28345 void
28346 ip_wsrv(queue_t *q)
28347 {
28348 	conn_t	*connp;
28349 	ill_t	*ill;
28350 	mblk_t	*mp;
28351 
28352 	if (q->q_next) {
28353 		ill = (ill_t *)q->q_ptr;
28354 		if (ill->ill_state_flags == 0) {
28355 			/*
28356 			 * The device flow control has opened up.
28357 			 * Walk through conn drain lists and qenable the
28358 			 * first conn in each list. This makes sense only
28359 			 * if the stream is fully plumbed and setup.
28360 			 * Hence the if check above.
28361 			 */
28362 			ip1dbg(("ip_wsrv: walking\n"));
28363 			conn_walk_drain();
28364 		}
28365 		return;
28366 	}
28367 
28368 	connp = Q_TO_CONN(q);
28369 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28370 
28371 	/*
28372 	 * 1. Set conn_draining flag to signal that service is active.
28373 	 *
28374 	 * 2. ip_output determines whether it has been called from service,
28375 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28376 	 *    has been called from service.
28377 	 *
28378 	 * 3. Message ordering is preserved by the following logic.
28379 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28380 	 *    the message at the tail, if conn_draining is set (i.e. service
28381 	 *    is running) or if q->q_first is non-null.
28382 	 *
28383 	 *    ii. If ip_output is called from service, and if ip_output cannot
28384 	 *    putnext due to flow control, it does a putbq.
28385 	 *
28386 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28387 	 *    (causing an infinite loop).
28388 	 */
28389 	ASSERT(!connp->conn_did_putbq);
28390 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28391 		connp->conn_draining = 1;
28392 		noenable(q);
28393 		while ((mp = getq(q)) != NULL) {
28394 			ASSERT(CONN_Q(q));
28395 
28396 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28397 			if (connp->conn_did_putbq) {
28398 				/* ip_wput did a putbq */
28399 				break;
28400 			}
28401 		}
28402 		/*
28403 		 * At this point, a thread coming down from top, calling
28404 		 * ip_wput, may end up queueing the message. We have not yet
28405 		 * enabled the queue, so ip_wsrv won't be called again.
28406 		 * To avoid this race, check q->q_first again (in the loop)
28407 		 * If the other thread queued the message before we call
28408 		 * enableok(), we will catch it in the q->q_first check.
28409 		 * If the other thread queues the message after we call
28410 		 * enableok(), ip_wsrv will be called again by STREAMS.
28411 		 */
28412 		connp->conn_draining = 0;
28413 		enableok(q);
28414 	}
28415 
28416 	/* Enable the next conn for draining */
28417 	conn_drain_tail(connp, B_FALSE);
28418 
28419 	connp->conn_did_putbq = 0;
28420 }
28421 
28422 /*
28423  * Walk the list of all conn's calling the function provided with the
28424  * specified argument for each.	 Note that this only walks conn's that
28425  * have been bound.
28426  * Applies to both IPv4 and IPv6.
28427  */
28428 static void
28429 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid)
28430 {
28431 	conn_walk_fanout_table(ipcl_udp_fanout, ipcl_udp_fanout_size,
28432 	    func, arg, zoneid);
28433 	conn_walk_fanout_table(ipcl_conn_fanout, ipcl_conn_fanout_size,
28434 	    func, arg, zoneid);
28435 	conn_walk_fanout_table(ipcl_bind_fanout, ipcl_bind_fanout_size,
28436 	    func, arg, zoneid);
28437 	conn_walk_fanout_table(ipcl_proto_fanout,
28438 	    A_CNT(ipcl_proto_fanout), func, arg, zoneid);
28439 	conn_walk_fanout_table(ipcl_proto_fanout_v6,
28440 	    A_CNT(ipcl_proto_fanout_v6), func, arg, zoneid);
28441 }
28442 
28443 /*
28444  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28445  * of conns that need to be drained, check if drain is already in progress.
28446  * If so set the idl_repeat bit, indicating that the last conn in the list
28447  * needs to reinitiate the drain once again, for the list. If drain is not
28448  * in progress for the list, initiate the draining, by qenabling the 1st
28449  * conn in the list. The drain is self-sustaining, each qenabled conn will
28450  * in turn qenable the next conn, when it is done/blocked/closing.
28451  */
28452 static void
28453 conn_walk_drain(void)
28454 {
28455 	int i;
28456 	idl_t *idl;
28457 
28458 	IP_STAT(ip_conn_walk_drain);
28459 
28460 	for (i = 0; i < conn_drain_list_cnt; i++) {
28461 		idl = &conn_drain_list[i];
28462 		mutex_enter(&idl->idl_lock);
28463 		if (idl->idl_conn == NULL) {
28464 			mutex_exit(&idl->idl_lock);
28465 			continue;
28466 		}
28467 		/*
28468 		 * If this list is not being drained currently by
28469 		 * an ip_wsrv thread, start the process.
28470 		 */
28471 		if (idl->idl_conn_draining == NULL) {
28472 			ASSERT(idl->idl_repeat == 0);
28473 			qenable(idl->idl_conn->conn_wq);
28474 			idl->idl_conn_draining = idl->idl_conn;
28475 		} else {
28476 			idl->idl_repeat = 1;
28477 		}
28478 		mutex_exit(&idl->idl_lock);
28479 	}
28480 }
28481 
28482 /*
28483  * Walk an conn hash table of `count' buckets, calling func for each entry.
28484  */
28485 static void
28486 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28487     zoneid_t zoneid)
28488 {
28489 	conn_t	*connp;
28490 
28491 	while (count-- > 0) {
28492 		mutex_enter(&connfp->connf_lock);
28493 		for (connp = connfp->connf_head; connp != NULL;
28494 		    connp = connp->conn_next) {
28495 			if (zoneid == GLOBAL_ZONEID ||
28496 			    zoneid == connp->conn_zoneid) {
28497 				CONN_INC_REF(connp);
28498 				mutex_exit(&connfp->connf_lock);
28499 				(*func)(connp, arg);
28500 				mutex_enter(&connfp->connf_lock);
28501 				CONN_DEC_REF(connp);
28502 			}
28503 		}
28504 		mutex_exit(&connfp->connf_lock);
28505 		connfp++;
28506 	}
28507 }
28508 
28509 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28510 static void
28511 conn_report1(conn_t *connp, void *mp)
28512 {
28513 	char	buf1[INET6_ADDRSTRLEN];
28514 	char	buf2[INET6_ADDRSTRLEN];
28515 	uint_t	print_len, buf_len;
28516 
28517 	ASSERT(connp != NULL);
28518 
28519 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28520 	if (buf_len <= 0)
28521 		return;
28522 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28523 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28524 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28525 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28526 	    "%5d %s/%05d %s/%05d\n",
28527 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28528 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28529 	    buf1, connp->conn_lport,
28530 	    buf2, connp->conn_fport);
28531 	if (print_len < buf_len) {
28532 		((mblk_t *)mp)->b_wptr += print_len;
28533 	} else {
28534 		((mblk_t *)mp)->b_wptr += buf_len;
28535 	}
28536 }
28537 
28538 /*
28539  * Named Dispatch routine to produce a formatted report on all conns
28540  * that are listed in one of the fanout tables.
28541  * This report is accessed by using the ndd utility to "get" ND variable
28542  * "ip_conn_status".
28543  */
28544 /* ARGSUSED */
28545 static int
28546 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28547 {
28548 	(void) mi_mpprintf(mp,
28549 	    "CONN      " MI_COL_HDRPAD_STR
28550 	    "rfq      " MI_COL_HDRPAD_STR
28551 	    "stq      " MI_COL_HDRPAD_STR
28552 	    " zone local                 remote");
28553 
28554 	/*
28555 	 * Because of the ndd constraint, at most we can have 64K buffer
28556 	 * to put in all conn info.  So to be more efficient, just
28557 	 * allocate a 64K buffer here, assuming we need that large buffer.
28558 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28559 	 */
28560 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28561 		/* The following may work even if we cannot get a large buf. */
28562 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28563 		return (0);
28564 	}
28565 
28566 	conn_walk_fanout(conn_report1, mp->b_cont, Q_TO_CONN(q)->conn_zoneid);
28567 	return (0);
28568 }
28569 
28570 /*
28571  * Determine if the ill and multicast aspects of that packets
28572  * "matches" the conn.
28573  */
28574 boolean_t
28575 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28576     zoneid_t zoneid)
28577 {
28578 	ill_t *in_ill;
28579 	boolean_t found;
28580 	ipif_t *ipif;
28581 	ire_t *ire;
28582 	ipaddr_t dst, src;
28583 
28584 	dst = ipha->ipha_dst;
28585 	src = ipha->ipha_src;
28586 
28587 	/*
28588 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28589 	 * unicast, broadcast and multicast reception to
28590 	 * conn_incoming_ill. conn_wantpacket itself is called
28591 	 * only for BROADCAST and multicast.
28592 	 *
28593 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28594 	 *    is part of a group. Hence, we should be receiving
28595 	 *    just one copy of broadcast for the whole group.
28596 	 *    Thus, if it is part of the group the packet could
28597 	 *    come on any ill of the group and hence we need a
28598 	 *    match on the group. Otherwise, match on ill should
28599 	 *    be sufficient.
28600 	 *
28601 	 * 2) ip_rput does not suppress duplicate multicast packets.
28602 	 *    If there are two interfaces in a ill group and we have
28603 	 *    2 applications (conns) joined a multicast group G on
28604 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28605 	 *    will give us two packets because we join G on both the
28606 	 *    interfaces rather than nominating just one interface
28607 	 *    for receiving multicast like broadcast above. So,
28608 	 *    we have to call ilg_lookup_ill to filter out duplicate
28609 	 *    copies, if ill is part of a group.
28610 	 */
28611 	in_ill = connp->conn_incoming_ill;
28612 	if (in_ill != NULL) {
28613 		if (in_ill->ill_group == NULL) {
28614 			if (in_ill != ill)
28615 				return (B_FALSE);
28616 		} else if (in_ill->ill_group != ill->ill_group) {
28617 			return (B_FALSE);
28618 		}
28619 	}
28620 
28621 	if (!CLASSD(dst)) {
28622 		if (IPCL_ZONE_MATCH(connp, zoneid))
28623 			return (B_TRUE);
28624 		/*
28625 		 * The conn is in a different zone; we need to check that this
28626 		 * broadcast address is configured in the application's zone and
28627 		 * on one ill in the group.
28628 		 */
28629 		ipif = ipif_get_next_ipif(NULL, ill);
28630 		if (ipif == NULL)
28631 			return (B_FALSE);
28632 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28633 		    connp->conn_zoneid, NULL,
28634 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP));
28635 		ipif_refrele(ipif);
28636 		if (ire != NULL) {
28637 			ire_refrele(ire);
28638 			return (B_TRUE);
28639 		} else {
28640 			return (B_FALSE);
28641 		}
28642 	}
28643 
28644 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28645 	    connp->conn_zoneid == zoneid) {
28646 		/*
28647 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28648 		 * disabled, therefore we don't dispatch the multicast packet to
28649 		 * the sending zone.
28650 		 */
28651 		return (B_FALSE);
28652 	}
28653 
28654 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28655 	    connp->conn_zoneid != zoneid) {
28656 		/*
28657 		 * Multicast packet on the loopback interface: we only match
28658 		 * conns who joined the group in the specified zone.
28659 		 */
28660 		return (B_FALSE);
28661 	}
28662 
28663 	if (connp->conn_multi_router) {
28664 		/* multicast packet and multicast router socket: send up */
28665 		return (B_TRUE);
28666 	}
28667 
28668 	mutex_enter(&connp->conn_lock);
28669 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28670 	mutex_exit(&connp->conn_lock);
28671 	return (found);
28672 }
28673 
28674 /*
28675  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28676  */
28677 /* ARGSUSED */
28678 static void
28679 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28680 {
28681 	ill_t *ill = (ill_t *)q->q_ptr;
28682 	mblk_t	*mp1, *mp2;
28683 	ipif_t  *ipif;
28684 	int err = 0;
28685 	conn_t *connp = NULL;
28686 	ipsq_t	*ipsq;
28687 	arc_t	*arc;
28688 
28689 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28690 
28691 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28692 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28693 
28694 	ASSERT(IAM_WRITER_ILL(ill));
28695 	mp2 = mp->b_cont;
28696 	mp->b_cont = NULL;
28697 
28698 	/*
28699 	 * We have now received the arp bringup completion message
28700 	 * from ARP. Mark the arp bringup as done. Also if the arp
28701 	 * stream has already started closing, send up the AR_ARP_CLOSING
28702 	 * ack now since ARP is waiting in close for this ack.
28703 	 */
28704 	mutex_enter(&ill->ill_lock);
28705 	ill->ill_arp_bringup_pending = 0;
28706 	if (ill->ill_arp_closing) {
28707 		mutex_exit(&ill->ill_lock);
28708 		/* Let's reuse the mp for sending the ack */
28709 		arc = (arc_t *)mp->b_rptr;
28710 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28711 		arc->arc_cmd = AR_ARP_CLOSING;
28712 		qreply(q, mp);
28713 	} else {
28714 		mutex_exit(&ill->ill_lock);
28715 		freeb(mp);
28716 	}
28717 
28718 	/* We should have an IOCTL waiting on this. */
28719 	ipsq = ill->ill_phyint->phyint_ipsq;
28720 	ipif = ipsq->ipsq_pending_ipif;
28721 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28722 	ASSERT(!((mp1 != NULL)  ^ (ipif != NULL)));
28723 	if (mp1 == NULL) {
28724 		/* bringup was aborted by the user */
28725 		freemsg(mp2);
28726 		return;
28727 	}
28728 	ASSERT(connp != NULL);
28729 	q = CONNP_TO_WQ(connp);
28730 	/*
28731 	 * If the DL_BIND_REQ fails, it is noted
28732 	 * in arc_name_offset.
28733 	 */
28734 	err = *((int *)mp2->b_rptr);
28735 	if (err == 0) {
28736 		if (ipif->ipif_isv6) {
28737 			if ((err = ipif_up_done_v6(ipif)) != 0)
28738 				ip0dbg(("ip_arp_done: init failed\n"));
28739 		} else {
28740 			if ((err = ipif_up_done(ipif)) != 0)
28741 				ip0dbg(("ip_arp_done: init failed\n"));
28742 		}
28743 	} else {
28744 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28745 	}
28746 
28747 	freemsg(mp2);
28748 
28749 	if ((err == 0) && (ill->ill_up_ipifs)) {
28750 		err = ill_up_ipifs(ill, q, mp1);
28751 		if (err == EINPROGRESS)
28752 			return;
28753 	}
28754 
28755 	if (ill->ill_up_ipifs) {
28756 		ill_group_cleanup(ill);
28757 	}
28758 
28759 	/*
28760 	 * The ioctl must complete now without EINPROGRESS
28761 	 * since ipsq_pending_mp_get has removed the ioctl mblk
28762 	 * from ipsq_pending_mp. Otherwise the ioctl will be
28763 	 * stuck for ever in the ipsq.
28764 	 */
28765 	ASSERT(err != EINPROGRESS);
28766 	ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipif, ipsq);
28767 }
28768 
28769 /* Allocate the private structure */
28770 static int
28771 ip_priv_alloc(void **bufp)
28772 {
28773 	void	*buf;
28774 
28775 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28776 		return (ENOMEM);
28777 
28778 	*bufp = buf;
28779 	return (0);
28780 }
28781 
28782 /* Function to delete the private structure */
28783 void
28784 ip_priv_free(void *buf)
28785 {
28786 	ASSERT(buf != NULL);
28787 	kmem_free(buf, sizeof (ip_priv_t));
28788 }
28789 
28790 /*
28791  * The entry point for IPPF processing.
28792  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28793  * routine just returns.
28794  *
28795  * When called, ip_process generates an ipp_packet_t structure
28796  * which holds the state information for this packet and invokes the
28797  * the classifier (via ipp_packet_process). The classification, depending on
28798  * configured filters, results in a list of actions for this packet. Invoking
28799  * an action may cause the packet to be dropped, in which case the resulting
28800  * mblk (*mpp) is NULL. proc indicates the callout position for
28801  * this packet and ill_index is the interface this packet on or will leave
28802  * on (inbound and outbound resp.).
28803  */
28804 void
28805 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28806 {
28807 	mblk_t		*mp;
28808 	ip_priv_t	*priv;
28809 	ipp_action_id_t	aid;
28810 	int		rc = 0;
28811 	ipp_packet_t	*pp;
28812 #define	IP_CLASS	"ip"
28813 
28814 	/* If the classifier is not loaded, return  */
28815 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28816 		return;
28817 	}
28818 
28819 	mp = *mpp;
28820 	ASSERT(mp != NULL);
28821 
28822 	/* Allocate the packet structure */
28823 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28824 	if (rc != 0) {
28825 		*mpp = NULL;
28826 		freemsg(mp);
28827 		return;
28828 	}
28829 
28830 	/* Allocate the private structure */
28831 	rc = ip_priv_alloc((void **)&priv);
28832 	if (rc != 0) {
28833 		*mpp = NULL;
28834 		freemsg(mp);
28835 		ipp_packet_free(pp);
28836 		return;
28837 	}
28838 	priv->proc = proc;
28839 	priv->ill_index = ill_index;
28840 	ipp_packet_set_private(pp, priv, ip_priv_free);
28841 	ipp_packet_set_data(pp, mp);
28842 
28843 	/* Invoke the classifier */
28844 	rc = ipp_packet_process(&pp);
28845 	if (pp != NULL) {
28846 		mp = ipp_packet_get_data(pp);
28847 		ipp_packet_free(pp);
28848 		if (rc != 0) {
28849 			freemsg(mp);
28850 			*mpp = NULL;
28851 		}
28852 	} else {
28853 		*mpp = NULL;
28854 	}
28855 #undef	IP_CLASS
28856 }
28857 
28858 /*
28859  * Propagate a multicast group membership operation (add/drop) on
28860  * all the interfaces crossed by the related multirt routes.
28861  * The call is considered successful if the operation succeeds
28862  * on at least one interface.
28863  */
28864 static int
28865 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28866     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28867     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28868     mblk_t *first_mp)
28869 {
28870 	ire_t		*ire_gw;
28871 	irb_t		*irb;
28872 	int		error = 0;
28873 	opt_restart_t	*or;
28874 
28875 	irb = ire->ire_bucket;
28876 	ASSERT(irb != NULL);
28877 
28878 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28879 
28880 	or = (opt_restart_t *)first_mp->b_rptr;
28881 	IRB_REFHOLD(irb);
28882 	for (; ire != NULL; ire = ire->ire_next) {
28883 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28884 			continue;
28885 		if (ire->ire_addr != group)
28886 			continue;
28887 
28888 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28889 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28890 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE);
28891 		/* No resolver exists for the gateway; skip this ire. */
28892 		if (ire_gw == NULL)
28893 			continue;
28894 
28895 		/*
28896 		 * This function can return EINPROGRESS. If so the operation
28897 		 * will be restarted from ip_restart_optmgmt which will
28898 		 * call ip_opt_set and option processing will restart for
28899 		 * this option. So we may end up calling 'fn' more than once.
28900 		 * This requires that 'fn' is idempotent except for the
28901 		 * return value. The operation is considered a success if
28902 		 * it succeeds at least once on any one interface.
28903 		 */
28904 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28905 		    NULL, fmode, src, first_mp);
28906 		if (error == 0)
28907 			or->or_private = CGTP_MCAST_SUCCESS;
28908 
28909 		if (ip_debug > 0) {
28910 			ulong_t	off;
28911 			char	*ksym;
28912 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28913 			ip2dbg(("ip_multirt_apply_membership: "
28914 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28915 			    "error %d [success %u]\n",
28916 			    ksym ? ksym : "?",
28917 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28918 			    error, or->or_private));
28919 		}
28920 
28921 		ire_refrele(ire_gw);
28922 		if (error == EINPROGRESS) {
28923 			IRB_REFRELE(irb);
28924 			return (error);
28925 		}
28926 	}
28927 	IRB_REFRELE(irb);
28928 	/*
28929 	 * Consider the call as successful if we succeeded on at least
28930 	 * one interface. Otherwise, return the last encountered error.
28931 	 */
28932 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28933 }
28934 
28935 
28936 /*
28937  * Issue a warning regarding a route crossing an interface with an
28938  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28939  * amount of time is logged.
28940  */
28941 static void
28942 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28943 {
28944 	hrtime_t	current = gethrtime();
28945 	char		buf[INET_ADDRSTRLEN];
28946 
28947 	/* Convert interval in ms to hrtime in ns */
28948 	if (multirt_bad_mtu_last_time +
28949 	    ((hrtime_t)ip_multirt_log_interval * (hrtime_t)1000000) <=
28950 	    current) {
28951 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28952 		    "to %s, incorrect MTU %u (expected %u)\n",
28953 		    ip_dot_addr(ire->ire_addr, buf),
28954 		    ire->ire_max_frag, max_frag);
28955 
28956 		multirt_bad_mtu_last_time = current;
28957 	}
28958 }
28959 
28960 
28961 /*
28962  * Get the CGTP (multirouting) filtering status.
28963  * If 0, the CGTP hooks are transparent.
28964  */
28965 /* ARGSUSED */
28966 static int
28967 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28968 {
28969 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28970 
28971 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28972 	return (0);
28973 }
28974 
28975 
28976 /*
28977  * Set the CGTP (multirouting) filtering status.
28978  * If the status is changed from active to transparent
28979  * or from transparent to active, forward the new status
28980  * to the filtering module (if loaded).
28981  */
28982 /* ARGSUSED */
28983 static int
28984 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28985     cred_t *ioc_cr)
28986 {
28987 	long		new_value;
28988 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28989 
28990 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28991 	    new_value < 0 || new_value > 1) {
28992 		return (EINVAL);
28993 	}
28994 
28995 	/*
28996 	 * Do not enable CGTP filtering - thus preventing the hooks
28997 	 * from being invoked - if the version number of the
28998 	 * filtering module hooks does not match.
28999 	 */
29000 	if ((ip_cgtp_filter_ops != NULL) &&
29001 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29002 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29003 		    "(module hooks version %d, expecting %d)\n",
29004 		    ip_cgtp_filter_ops->cfo_filter_rev, CGTP_FILTER_REV);
29005 		return (ENOTSUP);
29006 	}
29007 
29008 	if ((!*ip_cgtp_filter_value) && new_value) {
29009 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29010 		    ip_cgtp_filter_ops == NULL ?
29011 		    " (module not loaded)" : "");
29012 	}
29013 	if (*ip_cgtp_filter_value && (!new_value)) {
29014 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29015 		    ip_cgtp_filter_ops == NULL ?
29016 		    " (module not loaded)" : "");
29017 	}
29018 
29019 	if (ip_cgtp_filter_ops != NULL) {
29020 		int	res;
29021 		if ((res = ip_cgtp_filter_ops->cfo_change_state(new_value))) {
29022 			return (res);
29023 		}
29024 	}
29025 
29026 	*ip_cgtp_filter_value = (boolean_t)new_value;
29027 
29028 	return (0);
29029 }
29030 
29031 
29032 /*
29033  * Return the expected CGTP hooks version number.
29034  */
29035 int
29036 ip_cgtp_filter_supported(void)
29037 {
29038 	return (ip_cgtp_filter_rev);
29039 }
29040 
29041 
29042 /*
29043  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29044  * or by invoking this function. In the first case, the version number
29045  * of the registered structure is checked at hooks activation time
29046  * in ip_cgtp_filter_set().
29047  */
29048 int
29049 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29050 {
29051 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29052 		return (ENOTSUP);
29053 
29054 	ip_cgtp_filter_ops = ops;
29055 	return (0);
29056 }
29057 
29058 static squeue_func_t
29059 ip_squeue_switch(int val)
29060 {
29061 	squeue_func_t rval = squeue_fill;
29062 
29063 	switch (val) {
29064 	case IP_SQUEUE_ENTER_NODRAIN:
29065 		rval = squeue_enter_nodrain;
29066 		break;
29067 	case IP_SQUEUE_ENTER:
29068 		rval = squeue_enter;
29069 		break;
29070 	default:
29071 		break;
29072 	}
29073 	return (rval);
29074 }
29075 
29076 /* ARGSUSED */
29077 static int
29078 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29079     caddr_t addr, cred_t *cr)
29080 {
29081 	int *v = (int *)addr;
29082 	long new_value;
29083 
29084 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29085 		return (EINVAL);
29086 
29087 	ip_input_proc = ip_squeue_switch(new_value);
29088 	*v = new_value;
29089 	return (0);
29090 }
29091 
29092 /* ARGSUSED */
29093 static int
29094 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29095     caddr_t addr, cred_t *cr)
29096 {
29097 	int *v = (int *)addr;
29098 	long new_value;
29099 
29100 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29101 		return (EINVAL);
29102 
29103 	*v = new_value;
29104 	return (0);
29105 }
29106 
29107 static void
29108 ip_kstat_init(void)
29109 {
29110 	ip_named_kstat_t template = {
29111 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29112 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29113 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29114 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29115 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29116 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29117 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29118 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29119 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29120 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29121 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29122 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29123 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29124 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29125 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29126 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29127 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29128 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29129 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29130 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29131 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29132 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29133 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29134 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29135 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29136 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29137 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29138 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29139 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29140 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29141 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29142 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29143 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29144 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29145 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29146 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29147 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29148 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29149 	};
29150 
29151 	ip_mibkp = kstat_create("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29152 					NUM_OF_FIELDS(ip_named_kstat_t),
29153 					0);
29154 	if (!ip_mibkp)
29155 		return;
29156 
29157 	template.forwarding.value.ui32 = WE_ARE_FORWARDING ? 1:2;
29158 	template.defaultTTL.value.ui32 = (uint32_t)ip_def_ttl;
29159 	template.reasmTimeout.value.ui32 = ip_g_frag_timeout;
29160 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29161 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29162 
29163 	template.netToMediaEntrySize.value.i32 =
29164 		sizeof (mib2_ipNetToMediaEntry_t);
29165 
29166 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29167 
29168 	bcopy(&template, ip_mibkp->ks_data, sizeof (template));
29169 
29170 	ip_mibkp->ks_update = ip_kstat_update;
29171 
29172 	kstat_install(ip_mibkp);
29173 }
29174 
29175 static void
29176 ip_kstat_fini(void)
29177 {
29178 
29179 	if (ip_mibkp != NULL) {
29180 		kstat_delete(ip_mibkp);
29181 		ip_mibkp = NULL;
29182 	}
29183 }
29184 
29185 static int
29186 ip_kstat_update(kstat_t *kp, int rw)
29187 {
29188 	ip_named_kstat_t *ipkp;
29189 	mib2_ipIfStatsEntry_t ipmib;
29190 	ill_walk_context_t ctx;
29191 	ill_t *ill;
29192 
29193 	if (!kp || !kp->ks_data)
29194 		return (EIO);
29195 
29196 	if (rw == KSTAT_WRITE)
29197 		return (EACCES);
29198 
29199 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29200 
29201 	bcopy(&ip_mib, &ipmib, sizeof (ipmib));
29202 	rw_enter(&ill_g_lock, RW_READER);
29203 	ill = ILL_START_WALK_V4(&ctx);
29204 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29205 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29206 	rw_exit(&ill_g_lock);
29207 
29208 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29209 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29210 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29211 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29212 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29213 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29214 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29215 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29216 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29217 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29218 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29219 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29220 	ipkp->reasmTimeout.value.ui32 =		ip_g_frag_timeout;
29221 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29222 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29223 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29224 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29225 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29226 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29227 
29228 	ipkp->routingDiscards.value.ui32 =	0;
29229 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29230 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29231 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29232 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29233 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29234 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29235 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29236 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29237 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29238 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29239 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29240 
29241 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29242 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29243 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29244 
29245 	return (0);
29246 }
29247 
29248 static void
29249 icmp_kstat_init(void)
29250 {
29251 	icmp_named_kstat_t template = {
29252 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29253 		{ "inErrors",		KSTAT_DATA_UINT32 },
29254 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29255 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29256 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29257 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29258 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29259 		{ "inEchos",		KSTAT_DATA_UINT32 },
29260 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29261 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29262 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29263 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29264 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29265 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29266 		{ "outErrors",		KSTAT_DATA_UINT32 },
29267 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29268 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29269 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29270 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29271 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29272 		{ "outEchos",		KSTAT_DATA_UINT32 },
29273 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29274 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29275 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29276 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29277 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29278 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29279 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29280 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29281 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29282 		{ "outDrops",		KSTAT_DATA_UINT32 },
29283 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29284 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29285 	};
29286 
29287 	icmp_mibkp = kstat_create("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29288 					NUM_OF_FIELDS(icmp_named_kstat_t),
29289 					0);
29290 	if (icmp_mibkp == NULL)
29291 		return;
29292 
29293 	bcopy(&template, icmp_mibkp->ks_data, sizeof (template));
29294 
29295 	icmp_mibkp->ks_update = icmp_kstat_update;
29296 
29297 	kstat_install(icmp_mibkp);
29298 }
29299 
29300 static void
29301 icmp_kstat_fini(void)
29302 {
29303 
29304 	if (icmp_mibkp != NULL) {
29305 		kstat_delete(icmp_mibkp);
29306 		icmp_mibkp = NULL;
29307 	}
29308 }
29309 
29310 static int
29311 icmp_kstat_update(kstat_t *kp, int rw)
29312 {
29313 	icmp_named_kstat_t *icmpkp;
29314 
29315 	if ((kp == NULL) || (kp->ks_data == NULL))
29316 		return (EIO);
29317 
29318 	if (rw == KSTAT_WRITE)
29319 		return (EACCES);
29320 
29321 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29322 
29323 	icmpkp->inMsgs.value.ui32 =		icmp_mib.icmpInMsgs;
29324 	icmpkp->inErrors.value.ui32 =		icmp_mib.icmpInErrors;
29325 	icmpkp->inDestUnreachs.value.ui32 =	icmp_mib.icmpInDestUnreachs;
29326 	icmpkp->inTimeExcds.value.ui32 =	icmp_mib.icmpInTimeExcds;
29327 	icmpkp->inParmProbs.value.ui32 =	icmp_mib.icmpInParmProbs;
29328 	icmpkp->inSrcQuenchs.value.ui32 =	icmp_mib.icmpInSrcQuenchs;
29329 	icmpkp->inRedirects.value.ui32 =	icmp_mib.icmpInRedirects;
29330 	icmpkp->inEchos.value.ui32 =		icmp_mib.icmpInEchos;
29331 	icmpkp->inEchoReps.value.ui32 =		icmp_mib.icmpInEchoReps;
29332 	icmpkp->inTimestamps.value.ui32 =	icmp_mib.icmpInTimestamps;
29333 	icmpkp->inTimestampReps.value.ui32 =	icmp_mib.icmpInTimestampReps;
29334 	icmpkp->inAddrMasks.value.ui32 =	icmp_mib.icmpInAddrMasks;
29335 	icmpkp->inAddrMaskReps.value.ui32 =	icmp_mib.icmpInAddrMaskReps;
29336 	icmpkp->outMsgs.value.ui32 =		icmp_mib.icmpOutMsgs;
29337 	icmpkp->outErrors.value.ui32 =		icmp_mib.icmpOutErrors;
29338 	icmpkp->outDestUnreachs.value.ui32 =	icmp_mib.icmpOutDestUnreachs;
29339 	icmpkp->outTimeExcds.value.ui32 =	icmp_mib.icmpOutTimeExcds;
29340 	icmpkp->outParmProbs.value.ui32 =	icmp_mib.icmpOutParmProbs;
29341 	icmpkp->outSrcQuenchs.value.ui32 =	icmp_mib.icmpOutSrcQuenchs;
29342 	icmpkp->outRedirects.value.ui32 =	icmp_mib.icmpOutRedirects;
29343 	icmpkp->outEchos.value.ui32 =		icmp_mib.icmpOutEchos;
29344 	icmpkp->outEchoReps.value.ui32 =	icmp_mib.icmpOutEchoReps;
29345 	icmpkp->outTimestamps.value.ui32 =	icmp_mib.icmpOutTimestamps;
29346 	icmpkp->outTimestampReps.value.ui32 =	icmp_mib.icmpOutTimestampReps;
29347 	icmpkp->outAddrMasks.value.ui32 =	icmp_mib.icmpOutAddrMasks;
29348 	icmpkp->outAddrMaskReps.value.ui32 =	icmp_mib.icmpOutAddrMaskReps;
29349 	icmpkp->inCksumErrs.value.ui32 =	icmp_mib.icmpInCksumErrs;
29350 	icmpkp->inUnknowns.value.ui32 =		icmp_mib.icmpInUnknowns;
29351 	icmpkp->inFragNeeded.value.ui32 =	icmp_mib.icmpInFragNeeded;
29352 	icmpkp->outFragNeeded.value.ui32 =	icmp_mib.icmpOutFragNeeded;
29353 	icmpkp->outDrops.value.ui32 =		icmp_mib.icmpOutDrops;
29354 	icmpkp->inOverflows.value.ui32 =	icmp_mib.icmpInOverflows;
29355 	icmpkp->inBadRedirects.value.ui32 =	icmp_mib.icmpInBadRedirects;
29356 
29357 	return (0);
29358 }
29359 
29360 /*
29361  * This is the fanout function for raw socket opened for SCTP.  Note
29362  * that it is called after SCTP checks that there is no socket which
29363  * wants a packet.  Then before SCTP handles this out of the blue packet,
29364  * this function is called to see if there is any raw socket for SCTP.
29365  * If there is and it is bound to the correct address, the packet will
29366  * be sent to that socket.  Note that only one raw socket can be bound to
29367  * a port.  This is assured in ipcl_sctp_hash_insert();
29368  */
29369 void
29370 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29371     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29372     uint_t ipif_seqid, zoneid_t zoneid)
29373 {
29374 	conn_t		*connp;
29375 	queue_t		*rq;
29376 	mblk_t		*first_mp;
29377 	boolean_t	secure;
29378 	ip6_t		*ip6h;
29379 
29380 	first_mp = mp;
29381 	if (mctl_present) {
29382 		mp = first_mp->b_cont;
29383 		secure = ipsec_in_is_secure(first_mp);
29384 		ASSERT(mp != NULL);
29385 	} else {
29386 		secure = B_FALSE;
29387 	}
29388 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29389 
29390 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha);
29391 	if (connp == NULL) {
29392 		sctp_ootb_input(first_mp, recv_ill, ipif_seqid, zoneid,
29393 		    mctl_present);
29394 		return;
29395 	}
29396 	rq = connp->conn_rq;
29397 	if (!canputnext(rq)) {
29398 		CONN_DEC_REF(connp);
29399 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29400 		freemsg(first_mp);
29401 		return;
29402 	}
29403 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp) :
29404 	    CONN_INBOUND_POLICY_PRESENT_V6(connp)) || secure) {
29405 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29406 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29407 		if (first_mp == NULL) {
29408 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29409 			CONN_DEC_REF(connp);
29410 			return;
29411 		}
29412 	}
29413 	/*
29414 	 * We probably should not send M_CTL message up to
29415 	 * raw socket.
29416 	 */
29417 	if (mctl_present)
29418 		freeb(first_mp);
29419 
29420 	/* Initiate IPPF processing here if needed. */
29421 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN) && ip_policy) ||
29422 	    (!isv4 && IP6_IN_IPP(flags))) {
29423 		ip_process(IPP_LOCAL_IN, &mp,
29424 		    recv_ill->ill_phyint->phyint_ifindex);
29425 		if (mp == NULL) {
29426 			CONN_DEC_REF(connp);
29427 			return;
29428 		}
29429 	}
29430 
29431 	if (connp->conn_recvif || connp->conn_recvslla ||
29432 	    ((connp->conn_ip_recvpktinfo ||
29433 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29434 	    (flags & IP_FF_IPINFO))) {
29435 		int in_flags = 0;
29436 
29437 		/*
29438 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29439 		 * IPF_RECVIF.
29440 		 */
29441 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29442 			in_flags = IPF_RECVIF;
29443 		}
29444 		if (connp->conn_recvslla) {
29445 			in_flags |= IPF_RECVSLLA;
29446 		}
29447 		if (isv4) {
29448 			mp = ip_add_info(mp, recv_ill, in_flags,
29449 			    IPCL_ZONEID(connp));
29450 		} else {
29451 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29452 			if (mp == NULL) {
29453 				BUMP_MIB(recv_ill->ill_ip_mib,
29454 				    ipIfStatsInDiscards);
29455 				CONN_DEC_REF(connp);
29456 				return;
29457 			}
29458 		}
29459 	}
29460 
29461 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29462 	/*
29463 	 * We are sending the IPSEC_IN message also up. Refer
29464 	 * to comments above this function.
29465 	 */
29466 	putnext(rq, mp);
29467 	CONN_DEC_REF(connp);
29468 }
29469 
29470 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29471 {									\
29472 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29473 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29474 }
29475 /*
29476  * This function should be called only if all packet processing
29477  * including fragmentation is complete. Callers of this function
29478  * must set mp->b_prev to one of these values:
29479  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29480  * prior to handing over the mp as first argument to this function.
29481  *
29482  * If the ire passed by caller is incomplete, this function
29483  * queues the packet and if necessary, sends ARP request and bails.
29484  * If the ire passed is fully resolved, we simply prepend
29485  * the link-layer header to the packet, do ipsec hw acceleration
29486  * work if necessary, and send the packet out on the wire.
29487  *
29488  * NOTE: IPSEC will only call this function with fully resolved
29489  * ires if hw acceleration is involved.
29490  * TODO list :
29491  * 	a Handle M_MULTIDATA so that
29492  *	  tcp_multisend->tcp_multisend_data can
29493  *	  call ip_xmit_v4 directly
29494  *	b Handle post-ARP work for fragments so that
29495  *	  ip_wput_frag can call this function.
29496  */
29497 ipxmit_state_t
29498 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29499 {
29500 	nce_t		*arpce;
29501 	queue_t		*q;
29502 	int		ill_index;
29503 	mblk_t		*nxt_mp, *first_mp;
29504 	boolean_t	xmit_drop = B_FALSE;
29505 	ip_proc_t	proc;
29506 	ill_t		*out_ill;
29507 	int		pkt_len;
29508 
29509 	arpce = ire->ire_nce;
29510 	ASSERT(arpce != NULL);
29511 
29512 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29513 
29514 	mutex_enter(&arpce->nce_lock);
29515 	switch (arpce->nce_state) {
29516 	case ND_REACHABLE:
29517 		/* If there are other queued packets, queue this packet */
29518 		if (arpce->nce_qd_mp != NULL) {
29519 			if (mp != NULL)
29520 				nce_queue_mp_common(arpce, mp, B_FALSE);
29521 			mp = arpce->nce_qd_mp;
29522 		}
29523 		arpce->nce_qd_mp = NULL;
29524 		mutex_exit(&arpce->nce_lock);
29525 
29526 		/*
29527 		 * Flush the queue.  In the common case, where the
29528 		 * ARP is already resolved,  it will go through the
29529 		 * while loop only once.
29530 		 */
29531 		while (mp != NULL) {
29532 
29533 			nxt_mp = mp->b_next;
29534 			mp->b_next = NULL;
29535 			ASSERT(mp->b_datap->db_type != M_CTL);
29536 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29537 			/*
29538 			 * This info is needed for IPQOS to do COS marking
29539 			 * in ip_wput_attach_llhdr->ip_process.
29540 			 */
29541 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29542 			mp->b_prev = NULL;
29543 
29544 			/* set up ill index for outbound qos processing */
29545 			out_ill = ire->ire_ipif->ipif_ill;
29546 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29547 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29548 			    ill_index);
29549 			if (first_mp == NULL) {
29550 				xmit_drop = B_TRUE;
29551 				BUMP_MIB(out_ill->ill_ip_mib,
29552 				    ipIfStatsOutDiscards);
29553 				goto next_mp;
29554 			}
29555 			/* non-ipsec hw accel case */
29556 			if (io == NULL || !io->ipsec_out_accelerated) {
29557 				/* send it */
29558 				q = ire->ire_stq;
29559 				if (proc == IPP_FWD_OUT) {
29560 					UPDATE_IB_PKT_COUNT(ire);
29561 				} else {
29562 					UPDATE_OB_PKT_COUNT(ire);
29563 				}
29564 				ire->ire_last_used_time = lbolt;
29565 
29566 				if (flow_ctl_enabled || canputnext(q))  {
29567 					if (proc == IPP_FWD_OUT) {
29568 						BUMP_MIB(out_ill->ill_ip_mib,
29569 						ipIfStatsHCOutForwDatagrams);
29570 					}
29571 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29572 					    pkt_len);
29573 
29574 					putnext(q, first_mp);
29575 				} else {
29576 					BUMP_MIB(out_ill->ill_ip_mib,
29577 					    ipIfStatsOutDiscards);
29578 					xmit_drop = B_TRUE;
29579 					freemsg(first_mp);
29580 				}
29581 			} else {
29582 				/*
29583 				 * Safety Pup says: make sure this
29584 				 *  is going to the right interface!
29585 				 */
29586 				ill_t *ill1 =
29587 				    (ill_t *)ire->ire_stq->q_ptr;
29588 				int ifindex =
29589 				    ill1->ill_phyint->phyint_ifindex;
29590 				if (ifindex !=
29591 				    io->ipsec_out_capab_ill_index) {
29592 					xmit_drop = B_TRUE;
29593 					freemsg(mp);
29594 				} else {
29595 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29596 					    pkt_len);
29597 					ipsec_hw_putnext(ire->ire_stq, mp);
29598 				}
29599 			}
29600 next_mp:
29601 			mp = nxt_mp;
29602 		} /* while (mp != NULL) */
29603 		if (xmit_drop)
29604 			return (SEND_FAILED);
29605 		else
29606 			return (SEND_PASSED);
29607 
29608 	case ND_INITIAL:
29609 	case ND_INCOMPLETE:
29610 
29611 		/*
29612 		 * While we do send off packets to dests that
29613 		 * use fully-resolved CGTP routes, we do not
29614 		 * handle unresolved CGTP routes.
29615 		 */
29616 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29617 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29618 
29619 		if (mp != NULL) {
29620 			/* queue the packet */
29621 			nce_queue_mp_common(arpce, mp, B_FALSE);
29622 		}
29623 
29624 		if (arpce->nce_state == ND_INCOMPLETE) {
29625 			mutex_exit(&arpce->nce_lock);
29626 			DTRACE_PROBE3(ip__xmit__incomplete,
29627 			    (ire_t *), ire, (mblk_t *), mp,
29628 			    (ipsec_out_t *), io);
29629 			return (LOOKUP_IN_PROGRESS);
29630 		}
29631 
29632 		arpce->nce_state = ND_INCOMPLETE;
29633 		mutex_exit(&arpce->nce_lock);
29634 		/*
29635 		 * Note that ire_add() (called from ire_forward())
29636 		 * holds a ref on the ire until ARP is completed.
29637 		 */
29638 
29639 		ire_arpresolve(ire, ire_to_ill(ire));
29640 		return (LOOKUP_IN_PROGRESS);
29641 	default:
29642 		ASSERT(0);
29643 		mutex_exit(&arpce->nce_lock);
29644 		return (LLHDR_RESLV_FAILED);
29645 	}
29646 }
29647 
29648 #undef	UPDATE_IP_MIB_OB_COUNTERS
29649 
29650 /*
29651  * Return B_TRUE if the buffers differ in length or content.
29652  * This is used for comparing extension header buffers.
29653  * Note that an extension header would be declared different
29654  * even if all that changed was the next header value in that header i.e.
29655  * what really changed is the next extension header.
29656  */
29657 boolean_t
29658 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29659     uint_t blen)
29660 {
29661 	if (!b_valid)
29662 		blen = 0;
29663 
29664 	if (alen != blen)
29665 		return (B_TRUE);
29666 	if (alen == 0)
29667 		return (B_FALSE);	/* Both zero length */
29668 	return (bcmp(abuf, bbuf, alen));
29669 }
29670 
29671 /*
29672  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29673  * Return B_FALSE if memory allocation fails - don't change any state!
29674  */
29675 boolean_t
29676 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29677     const void *src, uint_t srclen)
29678 {
29679 	void *dst;
29680 
29681 	if (!src_valid)
29682 		srclen = 0;
29683 
29684 	ASSERT(*dstlenp == 0);
29685 	if (src != NULL && srclen != 0) {
29686 		dst = mi_alloc(srclen, BPRI_MED);
29687 		if (dst == NULL)
29688 			return (B_FALSE);
29689 	} else {
29690 		dst = NULL;
29691 	}
29692 	if (*dstp != NULL)
29693 		mi_free(*dstp);
29694 	*dstp = dst;
29695 	*dstlenp = dst == NULL ? 0 : srclen;
29696 	return (B_TRUE);
29697 }
29698 
29699 /*
29700  * Replace what is in *dst, *dstlen with the source.
29701  * Assumes ip_allocbuf has already been called.
29702  */
29703 void
29704 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29705     const void *src, uint_t srclen)
29706 {
29707 	if (!src_valid)
29708 		srclen = 0;
29709 
29710 	ASSERT(*dstlenp == srclen);
29711 	if (src != NULL && srclen != 0)
29712 		bcopy(src, *dstp, srclen);
29713 }
29714 
29715 /*
29716  * Free the storage pointed to by the members of an ip6_pkt_t.
29717  */
29718 void
29719 ip6_pkt_free(ip6_pkt_t *ipp)
29720 {
29721 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29722 
29723 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29724 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29725 		ipp->ipp_hopopts = NULL;
29726 		ipp->ipp_hopoptslen = 0;
29727 	}
29728 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29729 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29730 		ipp->ipp_rtdstopts = NULL;
29731 		ipp->ipp_rtdstoptslen = 0;
29732 	}
29733 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29734 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29735 		ipp->ipp_dstopts = NULL;
29736 		ipp->ipp_dstoptslen = 0;
29737 	}
29738 	if (ipp->ipp_fields & IPPF_RTHDR) {
29739 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29740 		ipp->ipp_rthdr = NULL;
29741 		ipp->ipp_rthdrlen = 0;
29742 	}
29743 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29744 	    IPPF_RTHDR);
29745 }
29746